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 separatecubejs/cubestore:v1.8.35container (cubebi-cubestore) is already running, andcubebi-cubehasCUBEJS_CUBESTORE_HOST,CUBEJS_REFRESH_WORKERandCUBEJS_SCHEDULED_REFRESH_TIMEZONESset. 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.jshasCUBEJS_TESSERACT_SQL_PLANNERdefaulting totrue. 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.jsregisters/cubejs-system/v1/pre-aggregations,/security-contexts,/timezones,/partitions,/preview,/build,/queueand/cancel, but only whenCUBEJS_PLAYGROUND_AUTH_SECRETis 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 neitherCUBEJS_PLAYGROUND_AUTH_SECRETnorCUBEJS_DEFAULT_API_SCOPES, so today both the system endpoints and the Orchestration API (jobsscope) 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_keyisevery: 2 minutefor Athena, BigQuery, Databricks, Firebolt, Presto and Snowflake, andevery: 10 secondfor everything else. Asql:refresh key (e.g.SELECT MAX(updated_at)) is checked every 10 s by default. The lowest recommendedeveryis 1 minute. - The cache can't be switched off: it doubles as the cluster's coordination point, and
/v1/loadcalls 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 andCUBEJS_DEV_MODEare 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/loadresponse carriesusedPreAggregations, andgateway.jscontainsusedPreAggregations, 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
usedPreAggregationsand the external/dataSourcefields from the load response or the SQL APIEXPLAIN. - 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,
rollupbeforeoriginal_sql. The first match wins. - The algorithm:
- If the query is leaf-measure additive, every member exists in the pre-agg, and no measure is multiplied by a
one_to_manyjoin, the pre-agg is used. - 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).
- If the query is leaf-measure additive, every member exists in the pre-agg, and no measure is multiplied by a
- Time dimensions:
- Granularity acts as a dimension, with a GCD common granularity for unaligned ranges.
allow_non_strict_date_range_matchdefaults 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
inDateRangefilter (instead oftimeDimensions.dateRange) matches only if that time dimension is in the pre-agg'sdimensions. - Ungrouped queries need the primary keys of every cube involved, and only members of those cubes.
switchdimensions 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 nograin/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.
- 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,
- 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_aggregationsmodel section,/v1/dry-runand/v1/pre-aggregations/can-use(match testing), andscheduled_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-runandcan-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=trueserves 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, andshared/dist/src/env.jsrollupOnlyMode. - 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_WORKERandCUBEJS_PRE_AGGREGATIONS_BUILDERCUBEJS_PRE_AGGREGATIONS_SCHEMACUBEJS_SCHEDULED_REFRESH_TIMEZONESCUBEJS_DB_QUERY_TIMEOUTCUBEJS_REFRESH_WORKER_CONCURRENCYandCUBEJS_CONCURRENCYCUBEJS_SCHEDULED_REFRESH_QUERIES_PER_APP_IDCUBEJS_DROP_PRE_AGG_WITHOUT_TOUCHCUBEJS_PRE_AGGREGATIONS_BACKOFF_MAX_TIME
- Pre-agg
refresh_keydefaults toevery: 1 hour. Withsqlonly,everydefaults to 10 s. With both, the SQL runs everyeveryand a rebuild happens when its result changes. - Error
Refresh Scheduler Interval Error ... Previous interval #2 was not finished with 60000 intervalmeans the worker is overloaded. The fix is to split tenants across several Cube clusters (Core). Cloud's "Multi-cluster deployment" does that split automatically.
- The refresh worker builds and refreshes pre-aggs. It's configured with these env vars:
- Availability: CORE+CLOUD. Core: the refresh worker, every env var above (all found in
shared/dist/src/env.js), andRefreshScheduler.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_contextssubset, 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) orCUBEJS_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 toCUBEJS_DB_*. _DB_TYPEis 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_factorywins, and aPre-aggregation driver conflictwarning is logged.
- Variables matching
- Availability: CORE. Evidence:
hasPreAggregationsEnvVars()inshared/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_granularitygives one table per period.refresh_key.incremental: trueplusupdate_windowrebuilds 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.sqlis evaluated per partition. Adding{FILTER_PARAMS.cube.time.filter('col')}makes it partition-scoped, so only partitions whoseMAX(updated_at)changed are rebuilt (the "refreshing select partitions" recipe). FILTER_PARAMSin the cubesqlpushes 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_schemaeach, 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, andcontext_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/partitionslists partitions and versions. Cube Storeinformation_schema.tablesandEXPLAIN ANALYZE. - To build on Core: partition and build-history dashboard is M. Collect build events (Core
loggeremits pre-agg build start/finish events) into a store, and show partitions from the system endpoint. - Gotchas: without
FILTER_PARAMS, arefresh_key.sqlchange 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 BYdims, then everything else (multi-value filters last). A matching order gives merge-sort/inplace aggregation; otherwise you get hash aggregation. type: aggregatebuilds 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.jshasjoi.valid('regular', 'aggregate')with the description "aggregate for an aggregating index". Cube Store is bundled. - Core building blocks to use:
indexesin pre-agg definitions. Cube StoreEXPLAINandEXPLAIN ANALYZE. - To build on Core: nothing. An index advisor that suggests indexes from query logs is M (optional).
- Gotchas: aggregating indexes can't serve
avgor exactcount_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_joinwithrollups: [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}), otherwiseFrom 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 ALLof per-source cubes, via SQL API post-processing.JOINof 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.
- A cube-to-cube join across sources (error
- Fail regardless: an ungrouped-subquery join.
- Work:
- Each post-processed sub-query is capped by
CUBESQL_NON_STREAMING_QUERY_MAX_ROW_LIMIT(defaultCUBEJS_DB_QUERY_LIMIT= 50,000). Non-additive measures can't be combined across sources, and no error is raised.
- Availability: CORE (Preview). Evidence:
rollup_joininCubeValidator.js, andCUBESTORE_MAX_JOINED_PARTITIONSplus theCan't find index to join tablestring in the bundledcubestoredbinary. 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 theCUBESTORE_MAX_JOINED_PARTITIONSenv var. - Core building blocks to use:
rollup_join,indexes,CUBEJS_DATASOURCES+data_source, the SQL API (EXPLAINshowsCubeScanvsCubeScanWrappedSql). - 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_lambdawithrollups: [...]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_dimensionandpartition_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_lambdainCubeValidator.js,@cubejs-backend/ksql-driverin the image, andCUBEJS_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 needsCREATE TABLErights, 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_sqlpre-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 membersql.
- 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: falsepre-agg materializes an expensive cubesqlonce in the source DB. Rollups withuse_original_sql_pre_aggregations: truebuild from it, and so do non-pre-aggregated queries. The driver must not bereadOnly. - 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) andCUBESTORE_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 isCUBESTORE_CHUNKS_TOTAL_SIZE_THRESHOLD. File swap is atomic via a metastore transaction.
- Cluster layout:
- Availability: CORE+CLOUD. Core: the open-source Cube Store binary is bundled in the Core image, and the
cubejs/cubestore:v1.8.35container is running in the user's stack. Every documentedCUBESTORE_*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/cubestoreimage (router plus N workers), an S3/GCS/MinIO bucket,CUBEJS_CUBESTORE_HOST,context_to_cube_store_router_idfor 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:keypaths with an optional TTL. - Eviction budgets:
CUBESTORE_CACHE_MAX_SIZE(4 GiB) andCUBESTORE_CACHE_MAX_KEYS(100k). Policies:allkeys-lru(default),-lfu,-ttlandsampled-*. 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.
concurrencyis a cluster-wide cap enforced atomically inQUEUE 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 waitcomes after 10 s, and stalled queries are cancelled in the warehouse.
- Message limits:
CUBESTORE_TRANSPORT_MAX_MESSAGE_SIZEand_FRAME_SIZEare 64 MiB (16–256 MiB), and must be raised together.CUBESTORE_CACHE_MAX_ENTRY_SIZEis 63 MiB. On the Cube side,CUBEJS_CUBESTORE_MAX_MESSAGE_SIZEis 100 MB.
- Cache:
- Availability: CORE. Evidence: the binary and env vars above.
CUBEJS_CUBESTORE_MAX_MESSAGE_SIZEis 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), loginmysql -h <ip> --user=cubestore -pcubestore. Windows clients aren't supported. - Diagnostics:
information_schema.tableslists the pre-agg tables.EXPLAINgives the logical plan.EXPLAIN ANALYZEgives router and worker physical plans (not usable on system tables).EXPLAIN ANALYZE DETAILEDexecutes the query with a timing trace.- Plans showing
PartialHashAggregate+FinalHashAggregate+Mergeare usually suboptimal, while*InplaceAggregate+MergeSortare optimal. DUMP selectwrites a metastore backup plus the Parquet files todumps/, 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 | TRUNCATESYS CACHESTORE HEALTHCHECK | INFO | COMPACTION | PERSIST | EVICTION | TRUNCATE | WIPESYS KILL ALL JOBS,SYS REPARTITION <id>,SYS DROP [QUERY] CACHE,SYS PANIC WORKER
- Cloud doesn't expose the port: only read-only
EXPLAINthrough the Source SQL tab, Explore source SQL or the SQL Runner'scachesource, and other commands are rejected (contact support).
- MySQL protocol on the router at port 3306 (
- 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,WIPEandREPARTITIONstrings in the bundled binary.MERGE_EXTRAandPANIC WORKERdidn'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:
TRUNCATEandWIPEare irreversible, andCLEARandTRUNCATEdo different things. Never expose the port publicly: the default credentials arecubestore/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 ingateway.jsand enabled byCUBEJS_PLAYGROUND_AUTH_SECRETusedPreAggregationsin load responses- Cube Store
information_schema.tables,QUEUE ACTIVE/PENDING,EXPLAIN ANALYZE DETAILED - the Core
loggerhook 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
usedPreAggregationsand 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-useand the old Playground): M.
- Gotchas: the system endpoints are private/undocumented and could change between versions.
CUBEJS_PLAYGROUND_AUTH_SECRETgrants 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/jobstakesaction: postwith aselector:contexts: [{securityContext}],timezones- optional
preAggregationsids,cubes,dataSources,dateRange(partitions only) - also, per the Core code:
force(default true) anddryRun
- It returns job tokens.
action: getreturns their status. - It's enabled by default but needs the
jobsAPI scope, e.g.CUBEJS_DEFAULT_API_SCOPES=meta,data,graphql,jobs. - Integration packages:
- Airflow
airflow-provider-cube:CubeQueryOperator(/v1/load:query,timeout30,wait10) andCubeBuildOperator(selector,completeto block until built,wait). The connection isgeneric, with the host set to the Cube URL, the password set to the API secret, andextra.security_context. - Dagster
dagster_cube.CubeResource.make_request(method, endpoint, data). - Prefect
prefect-cubejs:run_queryandbuild_pre_aggregations(..., wait_for_job_run_completion=True).
- Airflow
- Typical use: dbt finishes, then the orchestrator triggers builds.
- Availability: CORE. Evidence: the
app.post(.../v1/pre-aggregations/jobs)route pluspreAggregationsJobsPOSTinapi-gateway/dist/src/gateway.js, andCUBEJS_DEFAULT_API_SCOPESin the Core env reference. The doc examples use Cloud URLs, but the packages are generic. The user'scubebi-cubedoesn't setCUBEJS_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_contextstenants. ErrorA 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.avgas{sum}/{count}with only the additive parts in the rollup.- Or extra exact-match rollups.
incrementally-building-pre-aggregations-for-a-date-range.md: pushFILTER_PARAMSinto inner CTEs so build ranges prune early.disabling-pre-aggregations.md: Jinja{% if env_var('PRE_AGGREGATIONS_ENABLED','true') | lower != 'false' %}. A bareif 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-scopedrefresh_key.sqlusingFILTER_PARAMS.joining-multiple-data-sources.mdandmixed-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_idgives a per-tenant model, andscheduled_refresh_contextslists the tenants for refresh.- Queues, connections and pre-aggs stay shared unless you also set
context_to_orchestrator_idandpre_aggregations_schema. Without the orchestrator id, all tenants share the first-resolved DB connection. - Ways to customize per tenant:
- Member visibility:
public: {{ tenant == ... }}viaCOMPILE_CONTEXT. Playground ignores it and shows lock icons. - Per-tenant
sql_table,data_sourceorextends. - Jinja conditionals that add members.
repository_factory+file_repository("model/<tenant>"), or a custom repository loading from S3, a DB or an API.
- Member visibility:
- Data source per tenant:
driver_factorykeyed onsecurityContext.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_idleaks 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.environincube.pyandglobals.py(exposed viaTemplateContext.add_variable),env_var('X','default')in YAML Jinja, andprocess.envincube.js.process.envisn't available inside JS model files, so import it from a file outsidemodel/. - SSL:
CUBEJS_DB_SSL=trueplusCUBEJS_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_windowfor late-settling data (e.g. T+2).
- Env vars:
- 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.envrestriction.
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/metalists dimensions for dropdowns. - Numerics: REST returns numbers as strings by design (IEEE-754 safe range ±9007199254740991). The JS SDK
castNumerics: trueconverts them, with possible precision loss. - Sorting:
- NULLs sort last in ascending order. Add a
COALESCEsort-key dimension to control it. - The SQL API doesn't support
NULLS FIRST/LAST(issue #8464).
- NULLs sort last in ascending order. Add a
- Pagination:
limit+offsetwith deterministicorder. Get the total with a count query. - Drilldowns:
drill_memberson a measure, plus the clientResultSet.drillDown(). - Real-time: WebSocket transport (
CUBEJS_WEB_SOCKETS,/v1/subscribe). Updates followrefresh_key.every.
- Unique values: a dimension-only query returns distinct values, and
- Availability: CORE. Evidence:
/v1/meta,/v1/loadand/v1/subscriberoutes ingateway.js, andCUBEJS_WEB_SOCKETSin 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 withCUBEJS_API_SECRET. A direct SQL API (/v1/cubesql) or REST call is then treated like a Cloud UI user, soaccess_policyrules work. - Example policy:
group: marketingwith a row filtervalues: ["{ userAttributes.country }"].
- Puts
- Availability: CORE+CLOUD. This recipe is the main Cloud-dependent one in Core Data APIs.
- Core:
schema-compiler/.../CubePropContextTranspiler.jsrewrites the model shorthandsuserAttributes,user_attributesandgroupstosecurityContext.cubeCloud.<prop>, so{ userAttributes.country }resolves in plain Core.- But group matching for
access_policy(group:/groups:) goes throughcontextToGroups(CompilerApi.getGroupsFromContext). That returns an empty set whencontext_to_groupsisn't configured, and Core has no default that readscubeCloud.groups.
- Cloud: managing groups and user attributes in the Cloud admin UI, and filling the claim automatically for Cloud users.
- Core:
- Core building blocks to use: JWT security context,
context_to_groups,access_policy, the/v1/cubesqlSQL-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.
- Set
- 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 embeddedagentId,Authorization: Api-Key ...) as anask_cubetool. - Request body:
{input, chatId?, sessionSettings:{externalId, email?, userAttributes?}}. - It parses the streamed NDJSON. The final answer is the last
role: assistantmessage withgraphPath[0]=="final"andlen<=2, falling back to the last assistant content.chatIdcomes from theid=="__cutoff__"message'sstate.chatIdfor multi-turn. - Several Cube agents (multi-agent/spaces) are routed through
list_cube_agentsandask_cube_agent(agent_name, question). - RLS is enforced via
sessionSettings.userAttributes.
- Wraps the Cloud Chat API (
- 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/loador/v1/cubesql(execution), the security context orcontext_to_groupsfor RLS, and viewmeta/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_dbtPython package inglobals.py:Dbt.from_file/from_url/Dbt(manifest_dict),.filter(paths=, tags=, names=). - It's exposed to Jinja via
TemplateContextfunctions.model.as_cube()andmodel.as_dimensions(skip=)map dbtdata_typeto dimension types, and a column taggedprimary_keybecomes the PK. Enrich one cube per file with measures, joins and pre-aggs. - Advice: cast temporals to TIMESTAMP, use an
updated_atrefresh key (ordbt_valid_from/dbt_valid_towith snapshots), and trigger builds through the Orchestration API.
- Uses the
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, andcube data-model dev-mode|exit-dev-mode|merge-to-default|delete-branch. - Needs
CUBE_API_URL(*.cubecloud.dev),CUBE_API_KEYandDEPLOYMENT_ID, plus permissionsSchemaUpdate,SchemaRead,SchemaUpdateDevBranches,DeploymentRead.
- Cube CLI commands:
- 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 viarequirements.txtor 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/cloudpackage has onlydeployandlive-previewmodules 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. Thecube_dbtrendering 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 deploydeletes 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: truemeasure on a view or a cube, with shared conformed dims (items,locations,dates) and measurefilterson the line-item cube. - Without
multi_stageit 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.
- Same cube:
- Share of total:
- Helper measure
multi_stagewithgrain: keep_only: [](grand total) orkeep_only: [category](subtotal), plus a ratio measure. Hide the helper with viewexcludes. - Filters on the grouped dimension also shrink the total, so use the
filteroverride. - The Cloud workbook "Calculations → % of total" calculated field is CLOUD-ONLY (Count/Sum measures only).
- Helper measure
- 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/*.jinjagenerates*_week|month|quarter|year_to_datemeasures withrolling_window: {type: to_date, granularity}.safe,indentand 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: truedimension in a second, joined cube, and the outerPERCENTILE_CONTmeasure sits there. Alternative: a multi-stagenumber_aggmeasure withgrain. - 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 GROUPin atype: numbermeasure (BigQuery:APPROX_QUANTILES). - Active users:
count_distinctwithrolling_window: {trailing: 30 day, offset: start}for DAU/WAU/MAU, and a WAU/MAU ratio.
- AOV:
- 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, measurefilters, 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_distinctisn'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: switchdimension (growth_window: [3m, 6m, 9m, 12m]) is the query-time parameter. Jinja generates per-windowrolling_windowandtime_shiftmeasures. casemeasures (with a mandatoryelse) dispatch on the switch. The switch dimension must be in the query.- A view's
default_filterswithunless: [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.
- A
- Dynamic parameters:
FILTER_PARAMS.users.city.filter('city')in the cube SQL is cross-joined to create acity_filtercolumn, so a filter value feeds a calculation without filtering the whole query. Only existing values can be selected.
- Rolling windows:
- Availability: CORE. Evidence: Tesseract default-on, and
switch/case/default_filtersare model features. - Core building blocks to use:
switchdimensions,casemeasures, viewdefault_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, notinDateRange, 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: truecube over a calendar table. Overrideweek/month/quarter/yearwithsql:columns (names must be default names). - Calendar time shifts via
time_shift: [{type: prior, interval, sql: {CUBE}.date_prev_month}]. - Join facts with join
aliasper time dimension (v1.8.7+). Ato_daterolling 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.
- A
- String time dims: parse in
sql(e.g. BigQueryPARSE_TIMESTAMP). Set the timezone, and expect slower RDBMS queries. - Snapshots (SCD2): a
GENERATE_SERIESdate range joined to the latest status per date, withextends+{statuses.sql()}.
- Custom granularities:
- Availability: CORE. Evidence: model features, and the version requirements are met by 1.8.35.
- Core building blocks to use:
granularities, calendar cubes, joinalias,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 fromLAGinactivity over 30 min, and events join sessions by a time-window condition. - Session end and duration via a
sub_querymax timestamp. Users via anidentifiescube. - Also covers bounce rate, new vs repeat sessions, and sessions containing event X (a subquery count of 0 or more).
- Union tracks and pages into
- Cohort retention: cross-join users × activity months,
months_since_signupwithDATEDIFF, apercentage_of_activemeasure, and an explicit timezone onsignup_month. - EAV: a static pivot via per-attribute LEFT JOINs. JS-only variants are a DRY helper and
asyncModule+pgfetching the attribute list at compile time. - Polymorphic cubes: a base
userscube, withteachersandstudentsdefined viaextends+{users.sql()} WHERE type=..., and separate joins fromlessons. - Dynamic union: a Jinja loop generates
UNION ALLover per-client tables. - Generated measures: the JS
asyncModulebuilds per-status count and percent measures from an external list.
- Event analytics (Segment):
- Availability: CORE. Evidence: model features (
sub_query,extends, Jinja,asyncModule). - Core building blocks to use: as listed.
- To build on Core: nothing.
- Gotchas:
asyncModulefetching 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_stagemeasure once on apublic: falsebase view, then child viewsextendsit. Children inheritpublic, so setpublic: trueon them. excludescan'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.
- Define a multi-fact
- Custom order: a
CASEsort-key dimension (data-model approach), or an inlineCASEin 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/cubesandmodel/viewsper business unit. - Cubes are
public: falseand plural, with abase_prefix on clashes. Prefersql_table, and usemany_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.
- YAML, snake_case,
- Reusing view measures:
- 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 orurls.txt, so it's not covered here. - Availability: N/A (navigation).
Summary table
| Feature | Availability | Plan | Effort to build on Core | Depends on |
|---|---|---|---|---|
| In-memory cache and refresh keys | CORE | not stated | none (S for a cache-type badge) | refresh worker, usedPreAggregations |
| Pre-agg matching (aggregate awareness) | CORE | not stated | none (S–M for a "why no match" tool) | Tesseract, /v1/dry-run, can-use |
| Rollup-only mode | CORE | not stated | none | CUBEJS_ROLLUP_ONLY |
| Refresh worker and scheduled refresh | CORE+CLOUD (multi-cluster sharding is Cloud) | not stated | none; M for tenant sharding | scheduled_refresh_contexts, context_to_orchestrator_id |
| Dedicated pre-agg data source connection | CORE | not stated | none | CUBEJS_PRE_AGGREGATIONS_DB_* |
| Partitioning, incremental refresh, build ranges | CORE+CLOUD (tuning UIs are Cloud) | not stated | none; M for a partition/build dashboard | FILTER_PARAMS, system endpoints, logger |
| Indexes and aggregating indexes | CORE | not stated | none | Cube Store |
| rollup_join / cross-data-source queries | CORE (Preview) | not stated | none | Cube Store, CUBESTORE_MAX_JOINED_PARTITIONS, SQL API |
| Lambda and streaming pre-aggs | CORE | not stated | none | Cube Store, ksql driver |
| Build strategies and export bucket | CORE | not stated | none (S for bucket lifecycle) | driver export-bucket env vars |
| original_sql reuse | CORE | not stated | none | source write access |
| Cube Store engine (self-hosted cluster) | CORE+CLOUD (managed/tiers are Cloud) | not stated | M (prod cluster); L (autoscaling) | cubestore image, object storage |
| Cube Store cache and queue store | CORE | not stated | none | Cube Store router |
| Cube Store SQL / admin commands | CORE (full when self-hosted; Cloud restricts to read-only EXPLAIN) | not stated | S–M (admin console) | MySQL protocol on port 3306 |
| Pre-agg monitoring UI (Query History cache types, Pre-Aggs page, Build History, Perf Insights) | CLOUD-ONLY | not stated in slice | M (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/Prefect | CORE | not stated | none (enable jobs scope) | /v1/pre-aggregations/jobs, CUBEJS_DEFAULT_API_SCOPES |
| Recipes: pre-agg patterns (7) | CORE | not stated | none | model features |
| Recipes: multitenancy (model/data source per tenant) | CORE | not stated | none (M for a tenant admin UI) | context_to_app_id, driver_factory, repository_factory |
| Recipes: env vars, SSL, cost guide | CORE (Cloud settings UI) | not stated | none | env vars, Jinja env_var |
| Recipes: Core Data API usage (6) | CORE | not stated | none | REST, WebSockets, JS SDK |
| Recipe: Cloud groups and user attributes via JWT | CORE+CLOUD | not stated | S (context_to_groups) + M (user/group admin and token service) | JWT cubeCloud claim, context_to_groups, access_policy |
| Recipe: agent-to-agent via Chat API | CLOUD-ONLY | Premium / Enterprise | S for the tool; XL for the agent itself | LLM agent service, /v1/meta, /v1/load, /v1/cubesql, RLS |
| Recipe: dbt with cube_dbt | CORE | not stated | S (custom image with cube_dbt) | globals.py, Jinja |
| Recipe: dbt pull with the Cube CLI | CLOUD-ONLY | not stated | M (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 stated | none (S for a client-side % of total) | Tesseract multi-stage, grain, time_shift |
| Recipes: query-time parameters | CORE | not stated | none | switch/case, default_filters, FILTER_PARAMS |
| Recipes: time and calendars | CORE | not stated | none | calendar cubes, join alias, granularities |
| Recipes: analytics patterns (events, cohorts, EAV, polymorphic, dynamic) | CORE | not stated | none | sub_query, extends, Jinja, asyncModule |
| Recipes: view reuse, custom order, style guide | CORE (workbook AI suggestion is Cloud) | not stated | none (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.