Skip to content

04-preaggs-recipes ​

Pages read: 59 (list of paths at the bottom)

How I checked Core: I grepped the running cubebi-cube (cubejs/cube:v1.8.35) image under /cube/node_modules/@cubejs-backend/*, read the Core config and env reference (pages/reference/configuration/{config,environment-variables}.md), and listed the env var names of cubebi-cube/cubebi-cubestore (no values). Findings that apply to the whole slice:

  • The Core image ships Cube Store. The binary is at @cubejs-backend/cubestore/downloaded/latest/bin/cubestored (v1.8.35, 160 MB). A separate cubejs/cubestore:v1.8.35 container (cubebi-cubestore) is already running, and cubebi-cube has CUBEJS_CUBESTORE_HOST, CUBEJS_REFRESH_WORKER and CUBEJS_SCHEDULED_REFRESH_TIMEZONES set. Every pre-aggregation engine feature on these pages is available to the user's stack.
  • Tesseract is the default planner in 1.8.35. shared/dist/src/env.js has CUBEJS_TESSERACT_SQL_PLANNER defaulting to true. So multi-stage, switch/case, calendar cubes, multi-fact and time-shift matching all work in Core.
  • Core already has pre-aggregation management endpoints. api-gateway/dist/src/gateway.js registers /cubejs-system/v1/pre-aggregations, /security-contexts, /timezones, /partitions, /preview, /build, /queue and /cancel, but only when CUBEJS_PLAYGROUND_AUTH_SECRET is set. These are the private APIs a Cloud-style "Pre-Aggregations" page sits on. /v1/pre-aggregations/can-use ("Used by Rollup Designer") is also present. The user's stack sets neither CUBEJS_PLAYGROUND_AUTH_SECRET nor CUBEJS_DEFAULT_API_SCOPES, so today both the system endpoints and the Orchestration API (jobs scope) are off.

Pre-aggregations: caching layers, in-memory cache and refresh keys ​

  • Docs: pages/docs/pre-aggregations/index.md, getting-started-pre-aggregations.md
  • What it does:
    • Caching has two levels. Level 1 is an in-memory result cache, on by default, keyed by the generated SQL plus the pre-aggregations the query depends on. Level 2 is pre-aggregations, which must be configured explicitly.
    • On a cache hit Cube re-evaluates the cube's refresh_key, and serves the cached result only if the key's value is unchanged. Otherwise it re-runs the query against Cube Store or the source.
    • Default cube refresh_key is every: 2 minute for Athena, BigQuery, Databricks, Firebolt, Presto and Snowflake, and every: 10 second for everything else. A sql: refresh key (e.g. SELECT MAX(updated_at)) is checked every 10 s by default. The lowest recommended every is 1 minute.
    • The cache can't be switched off: it doubles as the cluster's coordination point, and /v1/load calls are idempotent and can't be tied to a client.
    • Background refresh is on in dev mode. In production it belongs in a separate refresh worker, otherwise refresh happens on the query path.
    • Every query is labelled with one of five cache types: Cube Store pre-agg, Cube Store pre-agg with a suboptimal plan (no matching index), pre-agg in the source DB, in-memory cache, or no cache.
    • The "Getting started" page gives two examples: a dimension-only pre-agg (order_statuses) for dropdowns, and a monthly time-dimension rollup.
  • Availability: CORE. Evidence: refresh_key, the refresh worker and CUBEJS_DEV_MODE are all Core config. The cache-type icons in Query History and Performance Insights are CLOUD-ONLY UI.
  • Core building blocks to use: cube/pre-agg refresh_key, CUBEJS_REFRESH_WORKER, orchestrator_options. The /v1/load response carries usedPreAggregations, and gateway.js contains usedPreAggregations, which lets you derive the cache type.
  • To build on Core: nothing for the engine. A cache-type badge in your own UI is S: read usedPreAggregations and the external/dataSource fields from the load response or the SQL API EXPLAIN.
  • Gotchas: in dev mode the in-memory cache is reset by restarting the server. Since there's no client-initiated refresh, the only freshness guarantee is the refresh key.

Pre-aggregations: matching algorithm (aggregate awareness) ​

  • Docs: pages/docs/pre-aggregations/matching-pre-aggregations.md, using-pre-aggregations.md (Matching), getting-started-pre-aggregations.md
  • What it does:
    • Matching extracts members from the query, replacing view members with the underlying cube members, so pre-aggs never need to be defined on views. It then searches pre-aggs in every cube involved, in definition order, rollup before original_sql. The first match wins.
    • The algorithm:
      1. If the query is leaf-measure additive, every member exists in the pre-agg, and no measure is multiplied by a one_to_many join, the pre-agg is used.
      2. Otherwise the query must have a time-dimension granularity, its filter dimensions must be among its dimensions, and the pre-agg must have exactly the query's dimensions plus every measure (or every leaf measure).
    • Time dimensions:
      • Granularity acts as a dimension, with a GCD common granularity for unaligned ranges.
      • allow_non_strict_date_range_match defaults to true.
      • The query timezone must be one the pre-agg was built for (scheduled_refresh_time_zones).
      • A custom granularity prefers a pre-agg with the same custom granularity.
    • A date range given as an inDateRange filter (instead of timeDimensions.dateRange) matches only if that time dimension is in the pre-agg's dimensions.
    • Ungrouped queries need the primary keys of every cube involved, and only members of those cubes.
    • switch dimensions don't have to be in the pre-agg; the selected value is applied over the scan.
    • Multi-fact and multi-stage queries match one pre-agg per subquery, all-or-nothing. A common miss is keying the pre-agg on its own cube's time dimension when the query groups by another cube's.
    • Time-shift measures can be served from a rollup holding the base measure, or rolled up if: they reference a single measure; are of type number|string|time|boolean|sum|min|max|avg; have no grain/filters/case/rolling_window; and the referenced measure is additive. A time shift on a calendar-cube dimension must be listed in the rollup.
    • Troubleshoot by removing members until the query matches. The usual culprits are non-additive measures and non-UTC timezones.
  • Availability: CORE. Evidence: implemented in schema-compiler/Tesseract (default-on in 1.8.35). The page names no plan.
  • Core building blocks to use: the pre_aggregations model section, /v1/dry-run and /v1/pre-aggregations/can-use (match testing), and scheduled_refresh_time_zones.
  • To build on Core: nothing for the engine. A "why didn't this match" assistant (UI that bisects members using /v1/dry-run and can-use) is S–M.
  • Gotchas: multi-fact matching silently falls back to the source. Results stay correct but you lose acceleration and cost goes up. Non-additive measures are the #1 miss.

Pre-aggregations: rollup-only mode ​

  • Docs: pages/docs/pre-aggregations/using-pre-aggregations.md (Rollup-only mode), recipes/configuration/data-store-cost-saving-guide.md
  • What it does:
    • CUBEJS_ROLLUP_ONLY=true serves queries only from pre-aggs and rejects everything else. Use it to keep the warehouse suspended except during builds.
    • On a single-node deployment (API doubles as refresh worker), unmatched queries error, and scheduled refresh still runs.
    • Streamed SQL API queries can't read Cube Store pre-aggs, so in rollup-only mode they fail unless a source-side pre-agg serves them. See CUBESQL_STREAM_MODE.
  • Availability: CORE. Evidence: env reference CUBEJS_ROLLUP_ONLY, and shared/dist/src/env.js rollupOnlyMode.
  • Core building blocks to use: CUBEJS_ROLLUP_ONLY, CUBESQL_STREAM_MODE.
  • To build on Core: nothing.
  • Gotchas: the streaming SQL API interaction above.

Pre-aggregations: refresh worker and scheduled refresh configuration ​

  • Docs: pages/docs/pre-aggregations/refreshing-pre-aggregations.md, using-pre-aggregations.md (Refresh strategy)
  • What it does:
    • The refresh worker builds and refreshes pre-aggs. It's configured with these env vars:
      • CUBEJS_REFRESH_WORKER and CUBEJS_PRE_AGGREGATIONS_BUILDER
      • CUBEJS_PRE_AGGREGATIONS_SCHEMA
      • CUBEJS_SCHEDULED_REFRESH_TIMEZONES
      • CUBEJS_DB_QUERY_TIMEOUT
      • CUBEJS_REFRESH_WORKER_CONCURRENCY and CUBEJS_CONCURRENCY
      • CUBEJS_SCHEDULED_REFRESH_QUERIES_PER_APP_ID
      • CUBEJS_DROP_PRE_AGG_WITHOUT_TOUCH
      • CUBEJS_PRE_AGGREGATIONS_BACKOFF_MAX_TIME
    • Pre-agg refresh_key defaults to every: 1 hour. With sql only, every defaults to 10 s. With both, the SQL runs every every and a rebuild happens when its result changes.
    • Error Refresh Scheduler Interval Error ... Previous interval #2 was not finished with 60000 interval means the worker is overloaded. The fix is to split tenants across several Cube clusters (Core). Cloud's "Multi-cluster deployment" does that split automatically.
  • Availability: CORE+CLOUD. Core: the refresh worker, every env var above (all found in shared/dist/src/env.js), and RefreshScheduler.js. Cloud: automatic sharding of tenants across clusters (Multi-cluster deployment).
  • Core building blocks to use: scheduled_refresh_contexts, scheduled_refresh_time_zones, scheduled_refresh_timer, context_to_orchestrator_id, context_to_app_id, pre_aggregations_schema.
  • To build on Core: tenant-to-cluster sharding (Cloud multi-cluster) is M. Write a deployer that partitions the tenant list and gives each Cube cluster its own scheduled_refresh_contexts subset, plus routing of API traffic by tenant (reverse proxy keyed on JWT tenant).
  • Gotchas: one refresh worker per cluster iterates every tenant × pre-agg × partition × timezone, so it scales poorly with tenant count.

Pre-aggregations: dedicated pre-aggregation data source connection ​

  • Docs: pages/docs/pre-aggregations/refreshing-pre-aggregations.md (Pre-aggregation data source)
  • What it does:
    • Variables matching CUBEJS_PRE_AGGREGATIONS_DB_* (default DS) or CUBEJS_DS_<NAME>_PRE_AGGREGATIONS_DB_* (named DS) make that source build and read its pre-aggs over a separate connection. Driver families work too (_JDBC_, _AWS_, DATABASE, FIREBOLT_).
    • Activation is by prefix: any matching var switches it on, even a typo like ..._DB_HSOT. Each var falls back to the driver default, not to CUBEJS_DB_*.
    • _DB_TYPE is ignored, since the driver is the same. Four prefixed vars are behavior settings and don't trigger it: SCHEMA, BUILDER, BACKOFF_MAX_TIME, ALLOW_NON_STRICT_DATE_RANGE_MATCH.
    • A custom driver_factory wins, and a Pre-aggregation driver conflict warning is logged.
  • Availability: CORE. Evidence: hasPreAggregationsEnvVars() in shared/dist/src/env.js, with exactly those four keys on the exclusion list.
  • Core building blocks to use: env vars, driver_factory.
  • To build on Core: nothing.
  • Gotchas: partial config silently connects with the driver's default credentials.

Pre-aggregations: time partitioning, incremental refresh and build ranges ​

  • Docs: pages/docs/pre-aggregations/using-pre-aggregations.md (Partitioning, Best practices), recipes/pre-aggregations/incrementally-building-pre-aggregations-for-a-date-range.md, refreshing-select-partitions.md, recipes/configuration/data-store-cost-saving-guide.md
  • What it does:
    • partition_granularity gives one table per period. refresh_key.incremental: true plus update_window rebuilds only the current partitions and those that ended within the window. build_range_start/build_range_end (SQL) bound the range.
    • A partitioned refresh_key.sql is evaluated per partition. Adding {FILTER_PARAMS.cube.time.filter('col')} makes it partition-scoped, so only partitions whose MAX(updated_at) changed are rebuilt (the "refreshing select partitions" recipe).
    • FILTER_PARAMS in the cube sql pushes the build range into inner CTEs (the "incremental build" recipe).
    • Sizing guidance:
      • Aim for each partition to be scannable in under 100 ms per Cube Store worker.
      • A worker handles up to 4 partitions concurrently, and clusters max out around 16 workers, so stay under about 64 partitions. Indexes multiply partition count (2 indexes means 32 or fewer).
    • Cube Store auto-splits logical partitions into physical ones by index sort key.
    • For explicit key partitioning, use multitenancy with multiple orchestrator IDs, a different pre_aggregations_schema each, and a multi-router Cube Store.
    • Docs point to Query History flame graphs, Build History and Performance Insights for tuning.
  • Availability: CORE+CLOUD. Core: all model params, FILTER_PARAMS, context_to_orchestrator_id, and context_to_cube_store_router_id (Core config reference). Cloud: the flame graph, Build History and Performance Insights used for tuning, and the "Pre-aggregations view" to check partition status.
  • Core building blocks to use: the model params above. /cubejs-system/v1/pre-aggregations/partitions lists partitions and versions. Cube Store information_schema.tables and EXPLAIN ANALYZE.
  • To build on Core: partition and build-history dashboard is M. Collect build events (Core logger emits pre-agg build start/finish events) into a store, and show partitions from the system endpoint.
  • Gotchas: without FILTER_PARAMS, a refresh_key.sql change rebuilds all partitions. Many partitions with indexes cause build queueing.

Pre-aggregations: indexes, aggregating indexes and compaction ​

  • Docs: pages/docs/pre-aggregations/using-pre-aggregations.md (Using indexes, Aggregating indexes, Compaction), cube-store-architecture.md (Indexes are sorted copies)
  • What it does:
    • With no explicit index, a default index is created: dimensions first, then time dimensions. Each index is a full sorted copy built at ingestion. It costs nothing extra in the warehouse but adds build time.
    • Index column order: high-selectivity single-value filters, then GROUP BY dims, then everything else (multi-value filters last). A matching order gives merge-sort/inplace aggregation; otherwise you get hash aggregation.
    • type: aggregate builds an aggregating index:
      • It stores only the index columns plus additive measures (SUM, MIN/MAX, MERGE for HLL), rolled up during compaction.
      • A query qualifies only if every measure is additive and every dimension and filter is an index column.
      • It's preferred over regular indexes, and among several qualifying ones the smallest key wins.
      • It beats a second pre-agg because it needs one warehouse read instead of N.
    • Compaction: a freshly built version is suboptimal until compacted, which takes seconds to minutes.
  • Availability: CORE. Evidence: CubeValidator.js has joi.valid('regular', 'aggregate') with the description "aggregate for an aggregating index". Cube Store is bundled.
  • Core building blocks to use: indexes in pre-agg definitions. Cube Store EXPLAIN and EXPLAIN ANALYZE.
  • To build on Core: nothing. An index advisor that suggests indexes from query logs is M (optional).
  • Gotchas: aggregating indexes can't serve avg or exact count_distinct. Unique-key deduplication and aggregating indexes are mutually exclusive.

Pre-aggregations: rollup_join (joins between pre-aggregations, cross-data-source) ​

  • Docs: pages/docs/pre-aggregations/using-pre-aggregations.md (Joins between pre-aggregations), recipes/pre-aggregations/joining-multiple-data-sources.md, recipes/pre-aggregations/mixed-refresh-cadences-rollup-join.md, recipes/data-modeling/cross-data-source-queries.md
  • What it does:
    • type: rollup_join with rollups: [a, b] joins two rollups inside Cube Store at query time. It's ephemeral: no refresh key of its own, and freshness comes from each side.
    • It's a Preview feature, designed for cross-data-source joins, and limited to two rollups.
    • Each side must be scannable in join-key order: the join key must be the leading index columns, otherwise Can't find index to join table. The join SQL must reference members ({CUBE.x} = {other.y}), otherwise From members are not found in join.
    • To get partition pruning on the joined side, put a selective equality-filter dimension before the join key in its index.
    • The right side is included whole in every batch, bounded by CUBESTORE_MAX_JOINED_PARTITIONS (default 5 per batch).
    • Mixed-cadence pattern: a slow fact rollup (daily) joined to a fast lookup rollup (hourly, e.g. FX rates). A derived measure {amount} * {fx_rates.rate} then stays fresh without rebuilding facts.
    • Cross-data-source query shapes:
      • Work:
        • UNION ALL of per-source cubes, via SQL API post-processing.
        • JOIN of grouped subqueries.
        • A view query touching one source.
      • Fail, unless a rollup_join covers the members:
        • A cube-to-cube join across sources (error To join across data sources use rollupJoin with Cube Store).
        • A view spanning sources.
        • A pushed-down expression over both sources.
      • Fail regardless: an ungrouped-subquery join.
    • Each post-processed sub-query is capped by CUBESQL_NON_STREAMING_QUERY_MAX_ROW_LIMIT (default CUBEJS_DB_QUERY_LIMIT = 50,000). Non-additive measures can't be combined across sources, and no error is raised.
  • Availability: CORE (Preview). Evidence: rollup_join in CubeValidator.js, and CUBESTORE_MAX_JOINED_PARTITIONS plus the Can't find index to join table string in the bundled cubestored binary. The mixed-cadence recipe says the right side's partition limit "depends on your Cube Store compute tier", which is Cloud wording. Self-hosted, it's the CUBESTORE_MAX_JOINED_PARTITIONS env var.
  • Core building blocks to use: rollup_join, indexes, CUBEJS_DATASOURCES + data_source, the SQL API (EXPLAIN shows CubeScan vs CubeScanWrappedSql).
  • To build on Core: nothing.
  • Gotchas: Preview API. A cube name starting with pg_ needs a schema qualifier in the SQL API. Silent double counting for non-additive measures across sources.

Pre-aggregations: lambda and streaming pre-aggregations ​

  • Docs: pages/docs/pre-aggregations/lambda-pre-aggregations.md, using-pre-aggregations.md (Streaming pre-aggregations)
  • What it does:
    • type: rollup_lambda with rollups: [...] unions batch rollups with either source data (union_with_source_data: true) or a streaming rollup. It works only with Cube Store.
    • The batch rollup needs time_dimension and partition_granularity. The lambda definition must come first in the cube.
    • The source-data leg is capped by CUBEJS_MAX_SOURCE_ROW_LIMIT (default 200,000) and errors rather than truncating.
    • With several rollups, each date range is served by the first rollup with a fully built partition. The last rollup's partitions are used even if incomplete.
    • Build ranges must overlap by more than the previous rollup's refresh interval plus build time, otherwise days silently go missing. With coarser partitions on the earlier rollup, start the next one at the beginning of the previous rollup's last partition.
    • Streaming pre-aggs are push-based and need no refresh_key. The only streaming source is ksqlDB.
    • Cube Store buffers streamed rows as in-memory chunks, deduplicates last-row by unique key using __seq, and compacts to Parquet roughly every minute.
  • Availability: CORE. Evidence: rollup_lambda in CubeValidator.js, @cubejs-backend/ksql-driver in the image, and CUBEJS_MAX_SOURCE_ROW_LIMIT (maxSourceRowLimit) in env.js.
  • Core building blocks to use: rollup_lambda, union_with_source_data, build_range_*, ksql driver, Cube Store.
  • To build on Core: nothing.
  • Gotchas: non-overlapping build ranges silently drop days. Lambda doesn't work with source-DB pre-agg storage.

Pre-aggregations: build strategies and export buckets ​

  • Docs: pages/docs/pre-aggregations/using-pre-aggregations.md (Pre-Aggregation build strategies, Pre-aggregations storage, Troubleshooting)
  • What it does:
    • Simple: the source DB is a staging area, and results are loaded into memory and then sent to Cube Store.
    • Batching: compressed CSV batches are sent to Cube Store. It's automatic where supported and scales with Cube instance memory.
    • Export bucket: for more than 100k rows. The DB UNLOADs to cloud storage and Cube Store loads in parallel. It needs CREATE TABLE rights, and you must set a bucket retention policy yourself (Cube doesn't clean up; about 1 day is enough). Don't confuse it with Cube Store's own storage bucket.
    • original_sql pre-aggs are stored in the source DB by default, and storing them in Cube Store isn't recommended.
    • Two troubleshooting cases are covered: pre-aggs that reference no member of their own cube, or duplicate a finer-partitioned twin, are ignored; and an unknown upstream type (e.g. Custom type 'fixed') must be cast in the member sql.
  • Availability: CORE. Evidence: CUBEJS_DB_EXPORT_BUCKET* env vars in the Core env reference, implemented per database driver.
  • Core building blocks to use: CUBEJS_DB_EXPORT_BUCKET, _TYPE, credentials vars, CUBEJS_PRE_AGGREGATIONS_SCHEMA.
  • To build on Core: nothing, apart from bucket lifecycle rules (S, infra).
  • Gotchas: the export bucket needs write access to the source.

Pre-aggregations: original_sql reuse ​

  • Docs: pages/recipes/pre-aggregations/using-originalsql-and-rollups-effectively.md
  • What it does: a type: original_sql, external: false pre-agg materializes an expensive cube sql once in the source DB. Rollups with use_original_sql_pre_aggregations: true build from it, and so do non-pre-aggregated queries. The driver must not be readOnly.
  • Availability: CORE. Evidence: a data-model feature validated by the Core schema compiler.
  • Core building blocks to use: original_sql, use_original_sql_pre_aggregations.
  • To build on Core: nothing.
  • Gotchas: needs write access to the source.

Cube Store engine (storage, query execution, self-hosted cluster) ​

  • Docs: pages/docs/pre-aggregations/cube-store-architecture.md (also linked: cube-core/running-in-production.md, outside this slice)
  • What it does:
    • Cluster layout:
      • A router holds the RocksDB metastore (schema → table → index → partition → chunk) and plans queries.
      • Workers own partitions by consistent hashing and share nothing.
      • Data is Parquet on S3, GCS, MinIO or a local dir. Workers are disposable caches.
    • Partition warmup: workers download assigned partitions before a table goes online. This is internal, not Cloud's "warm-up" feature.
    • Partition splits at compaction use CUBESTORE_PARTITION_SPLIT_THRESHOLD (2,097,152 rows, also settable per pre-agg) and CUBESTORE_PARTITION_SIZE_SPLIT_THRESHOLD (100 MiB), with at most 16 children per pass.
    • Planning is DataFusion-based:
      • Index selection: aggregating beats regular, then earliest filter column, then earliest projected column.
      • Three-level min/max pruning: partitions, then chunks, then row groups.
      • Pushdowns: aggregate, top-k and limit, plus sorted aggregation.
      • The router delegates the "router plan" to a randomly chosen worker coordinator.
    • Joins are merge-only. A missing join-key index fails planning with a suggested CREATE INDEX.
    • Streaming in-memory chunks are compacted at about 60 s (CUBESTORE_IN_MEMORY_CHUNKS_MAX_LIFETIME_THRESHOLD). The compaction row budget is CUBESTORE_CHUNKS_TOTAL_SIZE_THRESHOLD. File swap is atomic via a metastore transaction.
  • Availability: CORE+CLOUD. Core: the open-source Cube Store binary is bundled in the Core image, and the cubejs/cubestore:v1.8.35 container is running in the user's stack. Every documented CUBESTORE_* var I grepped exists in the binary: MAX_JOINED_PARTITIONS, CACHE_POLICY, CACHE_EVICTION_SIZE_CLASSES, TRANSPORT_MAX_MESSAGE_SIZE, TRANSPORT_MAX_FRAME_SIZE, CACHE_MAX_ENTRY_SIZE, PARTITION_SIZE_SPLIT_THRESHOLD, IN_MEMORY_CHUNKS_MAX_LIFETIME_THRESHOLD. Cloud: managed or auto-scaled Cube Store, "compute tiers", and no MySQL port exposed (sql-commands.md).
  • Core building blocks to use: the cubejs/cubestore image (router plus N workers), an S3/GCS/MinIO bucket, CUBEJS_CUBESTORE_HOST, context_to_cube_store_router_id for multi-router tenant isolation.
  • To build on Core: a production cluster (router plus workers on k8s, object storage, monitoring) is M. Autoscaling workers by load (Cloud-like tiers) is L.
  • Gotchas: a single router is a shared dependency (metastore plus cache/queue). The partition-count limits above assume about 16 workers. You lose the managed upgrades and the support path for recovery commands.

Cube Store cache and queue store (Redis replacement) ​

  • Docs: pages/docs/pre-aggregations/cube-store-architecture.md (Cache and queue store)
  • What it does:
    • Cache:
      • A Redis-style KV store on the router, backed by its own RocksDB, so it survives restarts.
      • Keys are prefix:key paths with an optional TTL.
      • Eviction budgets: CUBESTORE_CACHE_MAX_SIZE (4 GiB) and CUBESTORE_CACHE_MAX_KEYS (100k). Policies: allkeys-lru (default), -lfu, -ttl and sampled-*. Size classes (CUBESTORE_CACHE_EVICTION_SIZE_CLASSES) evict large entries first.
    • Query queue:
      • One queue per data source plus a pre-agg build queue.
      • Priority runs from -10000 to 10000, FIFO within a priority. Items go Pending → Active → Finished.
      • The item key is a hash of SQL, params and security context, with insert-if-absent. That's why N identical dashboard queries cost 1 DB execution.
      • concurrency is a cluster-wide cap enforced atomically in QUEUE RETRIEVE.
      • Heartbeat every 30 s. Stalled is 4× the heartbeat (2 min). The orphaned deadline is at least 120 s and up to 1.5× the timeout.
      • Continue wait comes after 10 s, and stalled queries are cancelled in the warehouse.
    • Message limits: CUBESTORE_TRANSPORT_MAX_MESSAGE_SIZE and _FRAME_SIZE are 64 MiB (16–256 MiB), and must be raised together. CUBESTORE_CACHE_MAX_ENTRY_SIZE is 63 MiB. On the Cube side, CUBEJS_CUBESTORE_MAX_MESSAGE_SIZE is 100 MB.
  • Availability: CORE. Evidence: the binary and env vars above. CUBEJS_CUBESTORE_MAX_MESSAGE_SIZE is in the Core env reference.
  • Core building blocks to use: Cube Store, orchestrator_options (concurrency), CUBEJS_CONCURRENCY.
  • To build on Core: nothing.
  • Gotchas: large result sets can exceed the transport limit and can't be delivered at all, so reduce the result or raise both limits. Self-hosting means you own the operational recovery of the cachestore.

Cube Store SQL interface: diagnostics, cache/queue and maintenance commands ​

  • Docs: pages/reference/cubestore/sql-commands.md, using-pre-aggregations.md (Inspecting pre-aggregations)
  • What it does:
    • MySQL protocol on the router at port 3306 (CUBESTORE_PORT / CUBESTORE_BIND_ADDR), login mysql -h <ip> --user=cubestore -pcubestore. Windows clients aren't supported.
    • Diagnostics:
      • information_schema.tables lists the pre-agg tables.
      • EXPLAIN gives the logical plan. EXPLAIN ANALYZE gives router and worker physical plans (not usable on system tables). EXPLAIN ANALYZE DETAILED executes the query with a timing trace.
      • Plans showing PartialHashAggregate + FinalHashAggregate + Merge are usually suboptimal, while *InplaceAggregate + MergeSort are optimal.
      • DUMP select writes a metastore backup plus the Parquet files to dumps/, and they're never cleaned up.
    • Cache commands: CACHE SET [NX] [TTL] | GET | KEYS | INCR | REMOVE (prefix:* allowed) | CLEAR.
    • Queue commands: QUEUE ADD, ADD_AND_RETRIEVE, GET, LIST, PENDING, ACTIVE, RESULT, RESULT_BLOCKING, ACK, CANCEL, HEARTBEAT, RETRIEVE, STALLED, ORPHANED, TO_CANCEL, MERGE_EXTRA, CLEAR.
    • Maintenance:
      • SYS METASTORE HEALTHCHECK | COMPACTION | SET_CURRENT | TRUNCATE
      • SYS CACHESTORE HEALTHCHECK | INFO | COMPACTION | PERSIST | EVICTION | TRUNCATE | WIPE
      • SYS KILL ALL JOBS, SYS REPARTITION <id>, SYS DROP [QUERY] CACHE, SYS PANIC WORKER
    • Cloud doesn't expose the port: only read-only EXPLAIN through the Source SQL tab, Explore source SQL or the SQL Runner's cache source, and other commands are rejected (contact support).
  • Availability: CORE (self-hosted gets the full command set). The Cloud path is a restricted subset. Evidence: the doc note, and ADD_AND_RETRIEVE, DETAILED, WIPE and REPARTITION strings in the bundled binary. MERGE_EXTRA and PANIC WORKER didn't show up as literal strings, likely because they're tokenized differently; I didn't verify further.
  • Core building blocks to use: a direct MySQL client against cubebi-cubestore.
  • To build on Core: an admin console wrapping these commands (queue viewer, kill stuck jobs, explain) is S–M. Gate the destructive commands.
  • Gotchas: TRUNCATE and WIPE are irreversible, and CLEAR and TRUNCATE do different things. Never expose the port publicly: the default credentials are cubestore/cubestore.

Pre-aggregation monitoring and inspection UI (Query History cache types, Pre-Aggregations page, Build History, Performance Insights) ​

  • Docs: pages/docs/pre-aggregations/index.md (Inspecting Queries, Cache type), using-pre-aggregations.md (Best practices links), recipes/configuration/data-store-cost-saving-guide.md. The dedicated pages (admin/monitoring/*, admin/deployment/warm-up.md) are in other slices.
  • What it does:
    • Query History filters by cache hit, pre-agg or raw. Query detail shows DB time, queue size at execution, generated SQL, a timeline, a flame graph and the "optimal pre-aggregations" for the query. Colored bolt icons mark the cache type.
    • The Pre-Aggregations page lists every pre-agg with last refresh and build time. Its detail view shows the queries served and all versions/partitions.
    • Build History shows build times. Performance Insights shows API requests by cache type and Cube Store worker load.
    • Core alternative: the dev-mode Playground "cache" button shows the refresh key and pre-agg usage for one query.
  • Availability: CLOUD-ONLY (UI). The data is mostly reachable in Core:
    • /cubejs-system/v1/pre-aggregations (+ partitions, preview, build, queue, cancel), present in gateway.js and enabled by CUBEJS_PLAYGROUND_AUTH_SECRET
    • usedPreAggregations in load responses
    • Cube Store information_schema.tables, QUEUE ACTIVE/PENDING, EXPLAIN ANALYZE DETAILED
    • the Core logger hook for events
  • Core building blocks to use: the endpoints above, logger (query and pre-agg build events), Cube Store SQL, and /v1/dry-run.
  • To build on Core:
    • (a) Pre-aggregations page (list, partitions, preview, manual build, queue/cancel) on the system endpoints: M.
    • (b) Query history with cache-type classification: a logger sink into a DB, a classifier from usedPreAggregations and external flags, and a UI. L, shared with the monitoring slice.
    • (c) Build history and worker load: build events from the logger plus Cube Store metrics. M.
    • (d) "Optimal pre-aggregation" suggestions (Rollup Designer logic from can-use and the old Playground): M.
  • Gotchas: the system endpoints are private/undocumented and could change between versions. CUBEJS_PLAYGROUND_AUTH_SECRET grants powerful build/cancel rights, so keep it server-side.

Orchestration API (push-based pre-aggregation builds) and Airflow, Dagster, Prefect integrations ​

  • Docs: pages/reference/orchestration-api/index.md, airflow.md, dagster.md, prefect.md, recipes/data-modeling/dbt.md (Pre-aggregations)
  • What it does:
    • POST /cubejs-api/v1/pre-aggregations/jobs takes action: post with a selector:
      • contexts: [{securityContext}], timezones
      • optional preAggregations ids, cubes, dataSources, dateRange (partitions only)
      • also, per the Core code: force (default true) and dryRun
    • It returns job tokens. action: get returns their status.
    • It's enabled by default but needs the jobs API scope, e.g. CUBEJS_DEFAULT_API_SCOPES=meta,data,graphql,jobs.
    • Integration packages:
      • Airflow airflow-provider-cube: CubeQueryOperator (/v1/load: query, timeout 30, wait 10) and CubeBuildOperator (selector, complete to block until built, wait). The connection is generic, with the host set to the Cube URL, the password set to the API secret, and extra.security_context.
      • Dagster dagster_cube.CubeResource.make_request(method, endpoint, data).
      • Prefect prefect-cubejs: run_query and build_pre_aggregations(..., wait_for_job_run_completion=True).
    • Typical use: dbt finishes, then the orchestrator triggers builds.
  • Availability: CORE. Evidence: the app.post(.../v1/pre-aggregations/jobs) route plus preAggregationsJobsPOST in api-gateway/dist/src/gateway.js, and CUBEJS_DEFAULT_API_SCOPES in the Core env reference. The doc examples use Cloud URLs, but the packages are generic. The user's cubebi-cube doesn't set CUBEJS_DEFAULT_API_SCOPES, so the endpoint is currently forbidden.
  • Core building blocks to use: the jobs endpoint, JWT signed with CUBEJS_API_SECRET, context_to_api_scopes.
  • To build on Core: nothing beyond enabling the scope. An optional webhook "rebuild on dbt run" service is S.
  • Gotchas: jobs run with the security contexts you pass, which must match scheduled_refresh_contexts tenants. Error A user's selector doesn't match any of the ... means the selector matched nothing.

Recipes: pre-aggregation patterns (7 pages, in addition to the sections above) ​

  • Docs: pages/recipes/pre-aggregations/*.md
  • What it does (one line each):
    • non-additivity.md: accelerate non-additive measures three ways:
      • count_distinct → count_distinct_approx, additive via HLL, supported on Athena/BigQuery/Snowflake per the docs.
      • avg as {sum}/{count} with only the additive parts in the rollup.
      • Or extra exact-match rollups.
    • incrementally-building-pre-aggregations-for-a-date-range.md: push FILTER_PARAMS into inner CTEs so build ranges prune early.
    • disabling-pre-aggregations.md: Jinja {% if env_var('PRE_AGGREGATIONS_ENABLED','true') | lower != 'false' %}. A bare if env_var(...) is always truthy. Jinja runs inside YAML comments too.
    • using-originalsql-and-rollups-effectively.md: see the original_sql section.
    • refreshing-select-partitions.md: partition-scoped refresh_key.sql using FILTER_PARAMS.
    • joining-multiple-data-sources.md and mixed-refresh-cadences-rollup-join.md: see the rollup_join section.
  • Availability: CORE, all of them. The only Cloud reference is "Cube Store compute tier" in the mixed-cadence warning.
  • Core building blocks to use: model params, Jinja env_var, FILTER_PARAMS.
  • To build on Core: nothing.
  • Gotchas: see the individual items.

Recipes: multitenancy (custom data model or data source per tenant) ​

  • Docs: pages/recipes/configuration/custom-data-model-per-tenant.md, multiple-sources-same-schema.md
  • What it does:
    • context_to_app_id gives a per-tenant model, and scheduled_refresh_contexts lists the tenants for refresh.
    • Queues, connections and pre-aggs stay shared unless you also set context_to_orchestrator_id and pre_aggregations_schema. Without the orchestrator id, all tenants share the first-resolved DB connection.
    • Ways to customize per tenant:
      • Member visibility: public: {{ tenant == ... }} via COMPILE_CONTEXT. Playground ignores it and shows lock icons.
      • Per-tenant sql_table, data_source or extends.
      • Jinja conditionals that add members.
      • repository_factory + file_repository("model/<tenant>"), or a custom repository loading from S3, a DB or an API.
    • Data source per tenant: driver_factory keyed on securityContext.tenant. Unknown tenants are rejected.
  • Availability: CORE. Evidence: all of these are Core config options (config.md lines 53, 95, 324, 497, 686, 852).
  • Core building blocks to use: context_to_app_id, context_to_orchestrator_id, driver_factory, repository_factory, scheduled_refresh_contexts, COMPILE_CONTEXT.
  • To build on Core: nothing. A tenant admin UI that edits per-tenant model files is M if wanted.
  • Gotchas: forgetting context_to_orchestrator_id leaks one tenant's connection to everyone (correctness and security).

Recipes: other configuration (env vars, SSL, cost optimization) ​

  • Docs: pages/recipes/configuration/environment-variables.md, using-ssl-connections-to-data-source.md, data-store-cost-saving-guide.md
  • What it does:
    • Env vars: os.getenv/os.environ in cube.py and globals.py (exposed via TemplateContext.add_variable), env_var('X','default') in YAML Jinja, and process.env in cube.js. process.env isn't available inside JS model files, so import it from a file outside model/.
    • SSL: CUBEJS_DB_SSL=true plus CUBEJS_DB_SSL_CA/_CERT/_KEY, as a path or inline PEM.
    • Cost guide:
      • Use pre-aggs, rollup-only mode, refresh cadence aligned with ETL, and lambda for real-time.
      • Use partitions with incremental refresh, and a wider update_window for late-settling data (e.g. T+2).
  • Availability: CORE. The Cloud parts are the Settings → Environment variables page, the SSL checkbox in the deployment wizard, and Query History or the Pre-aggregations view for monitoring.
  • Core building blocks to use: env vars, globals.py, Jinja.
  • To build on Core: a settings UI for env vars and secrets would be part of a deployment-management product (other slice).
  • Gotchas: none beyond the JS process.env restriction.

Recipes: Core Data API usage (unique values, numerics, sorting, pagination, drilldowns, real-time) ​

  • Docs: pages/recipes/core-data-api/getting-unique-values-for-a-field.md, cast-numerics.md, sorting.md, pagination.md, drilldowns.md, real-time-data-fetch.md
  • What it does:
    • Unique values: a dimension-only query returns distinct values, and /v1/meta lists dimensions for dropdowns.
    • Numerics: REST returns numbers as strings by design (IEEE-754 safe range ±9007199254740991). The JS SDK castNumerics: true converts them, with possible precision loss.
    • Sorting:
      • NULLs sort last in ascending order. Add a COALESCE sort-key dimension to control it.
      • The SQL API doesn't support NULLS FIRST/LAST (issue #8464).
    • Pagination: limit + offset with deterministic order. Get the total with a count query.
    • Drilldowns: drill_members on a measure, plus the client ResultSet.drillDown().
    • Real-time: WebSocket transport (CUBEJS_WEB_SOCKETS, /v1/subscribe). Updates follow refresh_key.every.
  • Availability: CORE. Evidence: /v1/meta, /v1/load and /v1/subscribe routes in gateway.js, and CUBEJS_WEB_SOCKETS in env.js and the env reference.
  • Core building blocks to use: REST, the WebSocket transport, @cubejs-client/core, drill_members.
  • To build on Core: nothing.
  • Gotchas: real-time is polling-by-refresh-key, not CDC push. The query must be much faster than the refresh rate.

Recipe: Cloud groups and user attributes with Core Data APIs (JWT cubeCloud claim) ​

  • Docs: pages/recipes/core-data-api/cloud-groups-and-user-attributes.md
  • What it does:
    • Puts { "cubeCloud": { "groups": [...], "userAttributes": {...} } } in the JWT, signed with CUBEJS_API_SECRET. A direct SQL API (/v1/cubesql) or REST call is then treated like a Cloud UI user, so access_policy rules work.
    • Example policy: group: marketing with a row filter values: ["{ userAttributes.country }"].
  • Availability: CORE+CLOUD. This recipe is the main Cloud-dependent one in Core Data APIs.
    • Core:
      • schema-compiler/.../CubePropContextTranspiler.js rewrites the model shorthands userAttributes, user_attributes and groups to securityContext.cubeCloud.<prop>, so { userAttributes.country } resolves in plain Core.
      • But group matching for access_policy (group:/groups:) goes through contextToGroups (CompilerApi.getGroupsFromContext). That returns an empty set when context_to_groups isn't configured, and Core has no default that reads cubeCloud.groups.
    • Cloud: managing groups and user attributes in the Cloud admin UI, and filling the claim automatically for Cloud users.
  • Core building blocks to use: JWT security context, context_to_groups, access_policy, the /v1/cubesql SQL-over-HTTP endpoint.
  • To build on Core:
    • Set contextToGroups: ({securityContext}) => securityContext.cubeCloud?.groups ?? []. This is S.
    • User and group admin plus attribute storage, and a token-minting service that embeds cubeCloud.{groups,userAttributes}: M.
  • Gotchas: without context_to_groups, group-scoped policies never match. Depending on the policy set that can mean no access at all or only the catch-all policy, with no error. Don't let clients mint their own JWTs with arbitrary groups.

Recipe: agent-to-agent (Chat API as a tool for LangChain and others) ​

  • Docs: pages/recipes/ai/agent-to-agent.md
  • What it does:
    • Wraps the Cloud Chat API (POST .../chat/stream-chat-state, Agent Chat API URL with an embedded agentId, Authorization: Api-Key ...) as an ask_cube tool.
    • Request body: {input, chatId?, sessionSettings:{externalId, email?, userAttributes?}}.
    • It parses the streamed NDJSON. The final answer is the last role: assistant message with graphPath[0]=="final" and len<=2, falling back to the last assistant content. chatId comes from the id=="__cutoff__" message's state.chatId for multi-turn.
    • Several Cube agents (multi-agent/spaces) are routed through list_cube_agents and ask_cube_agent(agent_name, question).
    • RLS is enforced via sessionSettings.userAttributes.
  • Availability: CLOUD-ONLY. Plan: Premium or Enterprise (stated). Evidence: prerequisites say "Cube Cloud deployment", "Admin → Agents" and "API key". There's no chat endpoint in Core gateway.js (routes listed above).
  • Core building blocks to use: to replicate the Cube side, /v1/meta (model context for the LLM), /v1/load or /v1/cubesql (execution), the security context or context_to_groups for RLS, and view meta/descriptions.
  • To build on Core: the recipe itself is S once a chat agent exists. The agent behind it is XL: an LLM text-to-semantic-query agent, NDJSON streaming API, chat/session store, API keys, per-agent config, spaces and certified queries (AI slice).
  • Gotchas: the response-stream format (graphPath, __cutoff__) is Cloud-specific. If you build your own agent, keep a compatible shape only if you want to reuse such clients.

Recipes: dbt integration (cube_dbt dynamic models vs Cloud dbt pull) ​

  • Docs: pages/recipes/data-modeling/dbt.md, dbt-cli.md
  • What it does:
    • dbt.md:
      • Uses the cube_dbt Python package in globals.py: Dbt.from_file/from_url/Dbt(manifest_dict), .filter(paths=, tags=, names=).
      • It's exposed to Jinja via TemplateContext functions. model.as_cube() and model.as_dimensions(skip=) map dbt data_type to dimension types, and a column tagged primary_key becomes the PK. Enrich one cube per file with measures, joins and pre-aggs.
      • Advice: cast temporals to TIMESTAMP, use an updated_at refresh key (or dbt_valid_from/dbt_valid_to with snapshots), and trigger builds through the Orchestration API.
    • dbt-cli.md:
      • Cube CLI commands: cube dbt sync <deployment> --manifest --output-path --name-prefix --wait (creates a Cloud review branch and emails), cube dbt generate (writes files locally, --check), cube deploy (CLI deploy mode), cube deployments build-status, cube validate, and cube data-model dev-mode|exit-dev-mode|merge-to-default|delete-branch.
      • Needs CUBE_API_URL (*.cubecloud.dev), CUBE_API_KEY and DEPLOYMENT_ID, plus permissions SchemaUpdate, SchemaRead, SchemaUpdateDevBranches, DeploymentRead.
  • Availability: split.
    • dbt.md (cube_dbt): CORE. A pure Python/Jinja dynamic model. The package isn't preinstalled in the 1.8.35 image (import cube_dbt → ModuleNotFoundError), so install it via requirements.txt or a custom image.
    • dbt-cli.md (dbt pull/sync): CLOUD-ONLY. Every command targets the Cloud deployment API, branches and dev mode. The Core @cubejs-backend/cloud package has only deploy and live-preview modules and nothing dbt-related.
  • Core building blocks to use: globals.py, TemplateContext, Jinja, repository_factory.
  • To build on Core: cube_dbt route is S (custom image with cube_dbt). A "dbt pull" equivalent (manifest → static YAML generator, git PR bot, CI check) is M. The cube_dbt rendering can be reused offline to write files instead of rendering at compile time.
  • Gotchas: dynamic dbt models re-render on every compile, and large manifests slow schema compilation. cube deploy deletes remote files not in the directory (Cloud).

Recipes: data modeling calculations and metrics ​

  • Docs: pages/recipes/data-modeling/average-order-value.md, share-of-total.md, period-over-period.md, reusable-period-to-date.md, nested-aggregates.md, filtered-aggregates.md, percentiles.md, active-users.md
  • What it does (each item):
    • AOV:
      • Same cube: {revenue}/NULLIF({count},0).
      • Across two facts, use a multi_stage: true measure on a view or a cube, with shared conformed dims (items, locations, dates) and measure filters on the line-item cube.
      • Without multi_stage it fails with "Can't find join path".
      • Placement trade-off: a cube measure is reusable but couples the cubes, a view measure keeps them decoupled.
    • Share of total:
      • Helper measure multi_stage with grain: keep_only: [] (grand total) or keep_only: [category] (subtotal), plus a ratio measure. Hide the helper with view excludes.
      • Filters on the grouped dimension also shrink the total, so use the filter override.
      • The Cloud workbook "Calculations → % of total" calculated field is CLOUD-ONLY (Count/Sum measures only).
    • Period-over-period: a time_shift: [{interval: 1 month, type: prior}] multi-stage measure plus a ratio measure. Query with a matching granularity.
    • Period-to-date macro: a Jinja macro in model/macros/*.jinja generates *_week|month|quarter|year_to_date measures with rolling_window: {type: to_date, granularity}.
      • safe, indent and the |- block scalar are load-bearing.
      • Calendar cubes change what the periods mean. Pass only overridden periods, otherwise you silently get Gregorian.
      • Custom-interval names need Tesseract and must be declared on the grouped dimension.
    • Nested aggregates: an inner measure becomes a sub_query: true dimension in a second, joined cube, and the outer PERCENTILE_CONT measure sits there. Alternative: a multi-stage number_agg measure with grain.
    • Filtered aggregates: pass aggregates up the join path via subquery dimensions and dimensions down (goal_start), then use a filtered measure {order_date} >= {goal_start}.
    • Percentiles: PERCENTILE_CONT(...) WITHIN GROUP in a type: number measure (BigQuery: APPROX_QUANTILES).
    • Active users: count_distinct with rolling_window: {trailing: 30 day, offset: start} for DAU/WAU/MAU, and a WAU/MAU ratio.
  • Availability: CORE (all modeling). Tesseract-dependent items are noted, and Tesseract is on by default in 1.8.35. The workbook calculated field is CLOUD-ONLY.
  • Core building blocks to use: multi_stage, grain, time_shift, rolling_window, sub_query, measure filters, Jinja macros, views.
  • To build on Core: nothing for the model. A client-side "% of total" calculated column in your own UI is S (compute over the result set).
  • Gotchas: several of these fail silently (Gregorian fallback, share-of-total under filters). Rolling count_distinct isn't additive, so pre-aggs must match exactly.

Recipes: query-time parameters (configurable rolling windows, dynamic parameters) ​

  • Docs: pages/recipes/data-modeling/dynamic-rolling-windows.md, passing-dynamic-parameters-in-a-query.md
  • What it does:
    • Rolling windows:
      • A type: switch dimension (growth_window: [3m, 6m, 9m, 12m]) is the query-time parameter. Jinja generates per-window rolling_window and time_shift measures.
      • case measures (with a mandatory else) dispatch on the switch. The switch dimension must be in the query.
      • A view's default_filters with unless: [growth_window] provides the default.
      • The rollup lists the per-window measures, not the case measures, and the switch dimension can be left out. In JS, reference members via CUBE[...], not strings, or the rollup compiles empty.
    • Dynamic parameters: FILTER_PARAMS.users.city.filter('city') in the cube SQL is cross-joined to create a city_filter column, so a filter value feeds a calculation without filtering the whole query. Only existing values can be selected.
  • Availability: CORE. Evidence: Tesseract default-on, and switch/case/default_filters are model features.
  • Core building blocks to use: switch dimensions, case measures, view default_filters, FILTER_PARAMS.
  • To build on Core: nothing. A UI dropdown bound to a switch dimension is S.
  • Gotchas: pass the date range via timeDimensions, not inDateRange, or the rollup won't match.

Recipes: time and calendars (custom granularity, custom calendar, string time dims, snapshots) ​

  • Docs: pages/recipes/data-modeling/custom-granularity.md, custom-calendar.md, string-time-dimensions.md, snapshots.md
  • What it does:
    • Custom granularities:
      • granularities: [{name, interval, offset}] for Sunday weeks, fiscal year and fiscal quarter.
      • REST can query them by name, but the SQL and GraphQL APIs can't, so expose proxy dimensions sql: "{timestamp.fiscal_year}".
    • Custom (4-5-4) calendar:
      • A calendar: true cube over a calendar table. Override week/month/quarter/year with sql: columns (names must be default names).
      • Calendar time shifts via time_shift: [{type: prior, interval, sql: {CUBE}.date_prev_month}].
      • Join facts with join alias per time dimension (v1.8.7+). A to_date rolling window over an overridden granularity needs v1.7.32+.
      • Declare a rollup per overridden granularity, because a finer rollup can't be assembled into retail months.
    • String time dims: parse in sql (e.g. BigQuery PARSE_TIMESTAMP). Set the timezone, and expect slower RDBMS queries.
    • Snapshots (SCD2): a GENERATE_SERIES date range joined to the latest status per date, with extends + {statuses.sql()}.
  • Availability: CORE. Evidence: model features, and the version requirements are met by 1.8.35.
  • Core building blocks to use: granularities, calendar cubes, join alias, time_shift, extends.
  • To build on Core: nothing.
  • Gotchas: grouping by a dimension without the override silently returns Gregorian periods.

Recipes: analytics patterns (event analytics, cohorts, EAV, polymorphic cubes, dynamic union and generated models) ​

  • Docs: pages/recipes/data-modeling/event-analytics.md, cohort-retention.md, entity-attribute-value.md, polymorphic-cubes.md, dynamic-union-tables.md, using-dynamic-measures.md
  • What it does:
    • Event analytics (Segment):
      • Union tracks and pages into events. Sessions come from LAG inactivity over 30 min, and events join sessions by a time-window condition.
      • Session end and duration via a sub_query max timestamp. Users via an identifies cube.
      • Also covers bounce rate, new vs repeat sessions, and sessions containing event X (a subquery count of 0 or more).
    • Cohort retention: cross-join users × activity months, months_since_signup with DATEDIFF, a percentage_of_active measure, and an explicit timezone on signup_month.
    • EAV: a static pivot via per-attribute LEFT JOINs. JS-only variants are a DRY helper and asyncModule + pg fetching the attribute list at compile time.
    • Polymorphic cubes: a base users cube, with teachers and students defined via extends + {users.sql()} WHERE type=..., and separate joins from lessons.
    • Dynamic union: a Jinja loop generates UNION ALL over per-client tables.
    • Generated measures: the JS asyncModule builds per-status count and percent measures from an external list.
  • Availability: CORE. Evidence: model features (sub_query, extends, Jinja, asyncModule).
  • Core building blocks to use: as listed.
  • To build on Core: nothing.
  • Gotchas: asyncModule fetching at compile time adds latency and needs DB credentials in model code. The event recipe's SQL is Redshift-specific.

Recipes: view design and conventions (reusing view measures, custom ordering, style guide) ​

  • Docs: pages/recipes/data-modeling/reusing-view-measures.md, custom-order.md, style-guide.md
  • What it does:
    • Reusing view measures:
      • Define a multi-fact multi_stage measure once on a public: false base view, then child views extends it. Children inherit public, so set public: true on them.
      • excludes can't remove inherited members, and there's no error.
      • A child can't redefine an inherited included member (Included member ... conflicts), and folder names must be unique.
    • Custom order: a CASE sort-key dimension (data-model approach), or an inline CASE in a semantic SQL query. The page suggests asking the workbook AI to write that query, which is a Cloud UI convenience. The SQL itself works via the Core SQL API.
    • Style guide:
      • YAML, snake_case, model/cubes and model/views per business unit.
      • Cubes are public: false and plural, with a base_ prefix on clashes. Prefer sql_table, and use many_to_one/one_to_many/one_to_one.
      • Fixed parameter ordering for cubes, members and views. SQL style (uppercase keywords, CTEs, !=, AS), YAML style (.yml, 2-space indent, 80 columns, |), and JS style.
  • Availability: CORE. The only Cloud part is the workbook AI suggestion in custom-order.
  • Core building blocks to use: views, extends, folders, public.
  • To build on Core: a style-guide linter is S (optional).
  • Gotchas: see the inheritance pitfalls above.

Recipes index ​

  • Docs: pages/recipes/index.md
  • What it does: card index of 41 recipes across Data Modeling, Calculations, Query-time parameters, Time series, User & Event analytics, Pre-aggregations, Configuration, APIs & Frontend, and AI. It lists a "Designing metrics" recipe (recipes/data-modeling/designing-metrics.md) that isn't in the downloaded pages or urls.txt, so it's not covered here.
  • Availability: N/A (navigation).

Summary table ​

FeatureAvailabilityPlanEffort to build on CoreDepends on
In-memory cache and refresh keysCOREnot statednone (S for a cache-type badge)refresh worker, usedPreAggregations
Pre-agg matching (aggregate awareness)COREnot statednone (S–M for a "why no match" tool)Tesseract, /v1/dry-run, can-use
Rollup-only modeCOREnot statednoneCUBEJS_ROLLUP_ONLY
Refresh worker and scheduled refreshCORE+CLOUD (multi-cluster sharding is Cloud)not statednone; M for tenant shardingscheduled_refresh_contexts, context_to_orchestrator_id
Dedicated pre-agg data source connectionCOREnot statednoneCUBEJS_PRE_AGGREGATIONS_DB_*
Partitioning, incremental refresh, build rangesCORE+CLOUD (tuning UIs are Cloud)not statednone; M for a partition/build dashboardFILTER_PARAMS, system endpoints, logger
Indexes and aggregating indexesCOREnot statednoneCube Store
rollup_join / cross-data-source queriesCORE (Preview)not statednoneCube Store, CUBESTORE_MAX_JOINED_PARTITIONS, SQL API
Lambda and streaming pre-aggsCOREnot statednoneCube Store, ksql driver
Build strategies and export bucketCOREnot statednone (S for bucket lifecycle)driver export-bucket env vars
original_sql reuseCOREnot statednonesource write access
Cube Store engine (self-hosted cluster)CORE+CLOUD (managed/tiers are Cloud)not statedM (prod cluster); L (autoscaling)cubestore image, object storage
Cube Store cache and queue storeCOREnot statednoneCube Store router
Cube Store SQL / admin commandsCORE (full when self-hosted; Cloud restricts to read-only EXPLAIN)not statedS–M (admin console)MySQL protocol on port 3306
Pre-agg monitoring UI (Query History cache types, Pre-Aggs page, Build History, Perf Insights)CLOUD-ONLYnot stated in sliceM (pre-aggs page) + L (query history) + M (build history)/cubejs-system/v1/pre-aggregations/* (needs CUBEJS_PLAYGROUND_AUTH_SECRET), logger, Cube Store SQL
Orchestration API and Airflow/Dagster/PrefectCOREnot statednone (enable jobs scope)/v1/pre-aggregations/jobs, CUBEJS_DEFAULT_API_SCOPES
Recipes: pre-agg patterns (7)COREnot statednonemodel features
Recipes: multitenancy (model/data source per tenant)COREnot statednone (M for a tenant admin UI)context_to_app_id, driver_factory, repository_factory
Recipes: env vars, SSL, cost guideCORE (Cloud settings UI)not statednoneenv vars, Jinja env_var
Recipes: Core Data API usage (6)COREnot statednoneREST, WebSockets, JS SDK
Recipe: Cloud groups and user attributes via JWTCORE+CLOUDnot statedS (context_to_groups) + M (user/group admin and token service)JWT cubeCloud claim, context_to_groups, access_policy
Recipe: agent-to-agent via Chat APICLOUD-ONLYPremium / EnterpriseS for the tool; XL for the agent itselfLLM agent service, /v1/meta, /v1/load, /v1/cubesql, RLS
Recipe: dbt with cube_dbtCOREnot statedS (custom image with cube_dbt)globals.py, Jinja
Recipe: dbt pull with the Cube CLICLOUD-ONLYnot statedM (manifest → YAML generator + git PR bot)dbt manifest, git
Recipes: calculations (AOV, share of total, PoP, PTD, nested/filtered aggs, percentiles, DAU)CORE (workbook "% of total" is Cloud)not statednone (S for a client-side % of total)Tesseract multi-stage, grain, time_shift
Recipes: query-time parametersCOREnot statednoneswitch/case, default_filters, FILTER_PARAMS
Recipes: time and calendarsCOREnot statednonecalendar cubes, join alias, granularities
Recipes: analytics patterns (events, cohorts, EAV, polymorphic, dynamic)COREnot statednonesub_query, extends, Jinja, asyncModule
Recipes: view reuse, custom order, style guideCORE (workbook AI suggestion is Cloud)not statednone (S for a linter)views extends, folders

Pages read ​

docs/pre-aggregations/cube-store-architecture.md docs/pre-aggregations/getting-started-pre-aggregations.md docs/pre-aggregations/index.md docs/pre-aggregations/lambda-pre-aggregations.md docs/pre-aggregations/matching-pre-aggregations.md docs/pre-aggregations/refreshing-pre-aggregations.md docs/pre-aggregations/using-pre-aggregations.md reference/cubestore/sql-commands.md reference/orchestration-api/index.md reference/orchestration-api/airflow.md reference/orchestration-api/dagster.md reference/orchestration-api/prefect.md recipes/index.md recipes/ai/agent-to-agent.md recipes/configuration/custom-data-model-per-tenant.md recipes/configuration/data-store-cost-saving-guide.md recipes/configuration/environment-variables.md recipes/configuration/multiple-sources-same-schema.md recipes/configuration/using-ssl-connections-to-data-source.md recipes/core-data-api/cast-numerics.md recipes/core-data-api/cloud-groups-and-user-attributes.md recipes/core-data-api/drilldowns.md recipes/core-data-api/getting-unique-values-for-a-field.md recipes/core-data-api/pagination.md recipes/core-data-api/real-time-data-fetch.md recipes/core-data-api/sorting.md recipes/data-modeling/active-users.md recipes/data-modeling/average-order-value.md recipes/data-modeling/cohort-retention.md recipes/data-modeling/cross-data-source-queries.md recipes/data-modeling/custom-calendar.md recipes/data-modeling/custom-granularity.md recipes/data-modeling/custom-order.md recipes/data-modeling/dbt-cli.md recipes/data-modeling/dbt.md recipes/data-modeling/dynamic-rolling-windows.md recipes/data-modeling/dynamic-union-tables.md recipes/data-modeling/entity-attribute-value.md recipes/data-modeling/event-analytics.md recipes/data-modeling/filtered-aggregates.md recipes/data-modeling/nested-aggregates.md recipes/data-modeling/passing-dynamic-parameters-in-a-query.md recipes/data-modeling/percentiles.md recipes/data-modeling/period-over-period.md recipes/data-modeling/polymorphic-cubes.md recipes/data-modeling/reusable-period-to-date.md recipes/data-modeling/reusing-view-measures.md recipes/data-modeling/share-of-total.md recipes/data-modeling/snapshots.md recipes/data-modeling/string-time-dimensions.md recipes/data-modeling/style-guide.md recipes/data-modeling/using-dynamic-measures.md recipes/pre-aggregations/disabling-pre-aggregations.md recipes/pre-aggregations/incrementally-building-pre-aggregations-for-a-date-range.md recipes/pre-aggregations/joining-multiple-data-sources.md recipes/pre-aggregations/mixed-refresh-cadences-rollup-join.md recipes/pre-aggregations/non-additivity.md recipes/pre-aggregations/refreshing-select-partitions.md recipes/pre-aggregations/using-originalsql-and-rollups-effectively.md

Note: JavaScript code blocks that duplicate a YAML example were skimmed. JS-only examples (EAV DRY/dynamic, using-dynamic-measures, the env.js helpers) are described from their surrounding text.