Data engineering · Design

Materialise When It Hurts, Not Before

If you've skipped the enterprise data model and let AI answer questions from raw data on demand, some answers will get popular, slow and expensive. This is a design for spotting those shared components from telemetry, materialising them only when the numbers say so, and proving in CI that the optimisation is worth it and correct.

Why just in time

Donald Knuth's line that "premature optimisation is the root of all evil" (1974) was about programs, but it applies directly to data platforms. The medallion and enterprise-model approach optimises up front for every possible question: it builds and refreshes tables before anyone has asked anything (see "AI Is the Knowledge Layer Now" and "Stop Building the Enterprise Data Model").

The opposite failure is real too. Once three teams, a dashboard and an agent all ask the same question, answering it from raw data every time wastes compute, adds latency, and lets AI-written SQL drift a little between runs. The answer isn't a model built up front. It's a feedback loop: measure, promote what earns it, retire what stops earning it. Choosing which views to materialise is an old database problem (Harinarayan, Rajaraman & Ullman, SIGMOD 1996; Agrawal, Chaudhuri & Narasayya, VLDB 2000). What's new is letting real query telemetry make the decision, continuously.

The lifecycle

Four levels, promoted on evidence and demoted on silence

Each step adds cost and ownership, so each needs a measured reason

L0 · ON DEMAND

Raw + contextThe AI or semantic layer answers from raw data and written definitions. The default for everything.

L1 · RESULT CACHE

TTL cacheCache the result by definition ID and parameters. No owner needed, and it expires on its own.

L2 · MATERIALISED VIEW

Incremental refreshA maintained view with a freshness target. Queries are rewritten to use it.

L3 · SHARED TABLE

Governed contractAn owner, a schema, a freshness target and tests. For reused, external and regulated numbers.

RETIRE

Drop itNo reads for 30 days (L1/L2) or 90 days (L3), and nothing downstream depends on it.
→ promote when a trigger fires← demote when reads stop
Skipping levels is allowed only for regulated or external numbers, which go straight to L3.

Noticing: telemetry that sees meaning

You can't promote what you can't see. The catch is that AI-written SQL varies: two agents asking "revenue by region last quarter" can produce different SQL text with the same meaning. So fingerprint at two levels:

  • Structural fingerprint. The warehouse's own normalised query hash. BigQuery records query_info.query_hashes.normalized_literals in INFORMATION_SCHEMA.JOBS (it ignores literals and comments). Snowflake records QUERY_PARAMETERIZED_HASH (literals replaced with parameters).
  • Semantic fingerprint. Tag every AI or semantic-layer query with the definition IDs it used: metric, grain and filters. In BigQuery use job labels; in Snowflake set QUERY_TAG. Reuse is then counted per meaning, however the SQL was written.
-- BigQuery: candidates for promotion over the last 14 days
SELECT
  COALESCE((SELECT value FROM UNNEST(labels) WHERE key = 'definition_id'),
           query_info.query_hashes.normalized_literals)            AS fingerprint,
  COUNT(*)                                                         AS runs,
  COUNT(DISTINCT user_email)                                       AS consumers,
  SUM(total_bytes_processed) / POW(1024, 4)                        AS tib_scanned,
  APPROX_QUANTILES(TIMESTAMP_DIFF(end_time, start_time, MILLISECOND), 100)[OFFSET(95)] AS p95_ms
FROM `region-us`.INFORMATION_SCHEMA.JOBS
WHERE creation_time > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 14 DAY)
  AND job_type = 'QUERY' AND statement_type != 'SCRIPT'   -- avoid double-counting scripts
GROUP BY fingerprint
HAVING consumers >= 2
ORDER BY tib_scanned DESC
LIMIT 50;

Also record a result digest (a hash of the result for a fixed time window) per semantic fingerprint. If the same definition and window give different digests on different runs, that's an inconsistency signal, not a performance one, and it's the strongest reason to promote.

When to promote

SignalTrigger (starting defaults; tune per platform)Promote to
Reuse2 or more distinct consumers of one semantic fingerprint in 14 daysL1 cache
CostWeekly on-demand cost of the fingerprint > 3× the cost of refreshing and storing a viewL2 view
Latencyp95 above the interactive target (for example 2 s) on more than 5% of runsL2 view
ConsistencyMore than one result digest for the same definition and windowL3 table
ObligationFeeds an external, regulated or board-level numberL3 table, immediately
SilenceNo reads for 30 days (L1/L2) or 90 days (L3), no downstream dependantsRetire

The break-even test. Materialise when the on-demand cost you avoid exceeds what the view costs to keep fresh:

reads × cost_per_query × (1 − cache_hit_rate)  >  refreshes × cost_per_refresh  +  storage

A worked example on BigQuery's on-demand price (US$6.25 per TiB scanned): a fingerprint run 400 times a day, scanning 2.5 GB each time, costs about US$6.10 a day. An incrementally refreshed view, updated every 30 minutes and scanning 0.2 GB per refresh, costs about US$0.06 a day, plus negligible storage. Promote it. A question asked twice a week doesn't pass, however slow it is; give it an L1 cache at most. The numbers are illustrative; plug in your platform's pricing.

Designing the materialised layer

  • Refresh incrementally by event time. Full rebuilds defeat the purpose. Process new and late-arriving partitions only, with a lookback window sized to your late-data reality.
  • Set freshness as a target, not a schedule. Snowflake dynamic tables take a TARGET_LAG (minimum 60 seconds, best effort); Databricks materialised views and Postgres's REFRESH MATERIALIZED VIEW CONCURRENTLY fit the same pattern. Publish the target in the contract.
  • Let consumers stay unaware. Route through query rewrite so nothing calling the data has to change. BigQuery's smart tuning rewrites queries against base tables to use a matching materialised view automatically. Or let the semantic layer route a definition to its view when it's fresh, and to on-demand when it isn't. dbt's saved queries with exports, and Cube's pre-aggregations, are two ways to do the second.
  • Key the view on the definition, not the team. One view per definition and grain, used by everyone. Materialising per team recreates the old data-mart sprawl.
  • Give L3 a contract. Owner, schema, grain, freshness target, the definition version it implements, and the tests below. Version it like an API: a definition change ships as v2 alongside v1, then v1 retires.

Testing it during delivery

Put these in CI and in the release pipeline. The first test is how you notice before production does; the rest prove a promotion is safe.

  • 1. Performance budgets per key question. Keep a set of test questions (the questions with known answers you already use to test AI accuracy). For each, run a dry run and assert bytes scanned and estimated cost are under budget. A budget failure in CI is the earliest promotion signal you'll get.
  • 2. Equivalence. Before switching readers to a view, prove it returns the same answer as on-demand for a fixed snapshot: row counts, sums and a two-way EXCEPT DISTINCT, including a window with late-arriving data.
  • 3. Freshness. Assert the view's lag is within its target after a refresh, and alert when it isn't. If it's stale, fall back to on-demand rather than serve wrong numbers.
  • 4. Replay load. Replay the top fingerprints from the production query log at peak concurrency against staging. Compare p95 and cost before and after promotion.
  • 5. Shadow reads. In production, send a slice of traffic to both paths, compare result digests and latency, and switch only when they match.
  • 6. Retirement check. A scheduled job lists views and tables with no reads in their window and opens a pull request to drop them, so demotion is as routine as promotion.
# pytest sketch: budget and equivalence checks for one test question (BigQuery client)
from google.cloud import bigquery
bq = bigquery.Client()

def scanned_bytes(sql):
    cfg = bigquery.QueryJobConfig(dry_run=True, use_query_cache=False)
    return bq.query(sql, job_config=cfg).total_bytes_processed

def test_revenue_by_region_budget(golden):
    assert scanned_bytes(golden.on_demand_sql) <= golden.max_bytes, "over budget: promote or optimise"

def test_view_matches_on_demand(golden):
    diff = f"""
      (SELECT * FROM ({golden.view_sql})      EXCEPT DISTINCT SELECT * FROM ({golden.on_demand_sql}))
      UNION ALL
      (SELECT * FROM ({golden.on_demand_sql}) EXCEPT DISTINCT SELECT * FROM ({golden.view_sql}))"""
    assert list(bq.query(diff).result()) == [], "view and on-demand disagree"

Decision matrix: just in time, predictive, or full conformance

Just in time isn't the only option. Some answers must be ready before the first person asks: the 9 a.m. board dashboard, month-end close, a product launch. Waiting for telemetry there means the first users get a slow answer. That's what predictive reuse is for: keeping specific views in place ahead of demand you can see coming. Full conformance is the enterprise-model approach: model and build everything up front.

CriterionJust in time (reactive)Predictive reuse (pre-warmed)Full conformance (model first)
What gets builtOnly what telemetry proves is reusedJIT, plus a short list of views kept ready for known, scheduled or seasonal demandEverything, conformed to one model, before use
Up-front costLowestLow: one view per known hot pathHighest: a multi-year programme
Running costLowest; pays only for proven reuseLow to medium; some views warmed and not usedHighest; refreshes everything, read or not
Time to first answer for a new questionMinutesMinutesWeeks: waits for a model change
First-query latency on a hot pathSlow until promoted (cold start)Fast from the first requestFast
Consistency across consumersGood once promoted; drift beforeGood on warmed paths; JIT elsewhereHighest, by construction
AuditabilityNeeds definition versions and digestsSame as JIT, plus contracts on warmed viewsStrongest, but slowest to change
Adapting to change (new sources, acquisitions)BestGoodWorst: every change is a model change
Main riskCold-start pain and early drift on popular questionsGuessing wrong: views warmed for demand that never comesWaste, delay and a model that's out of date when finished
Signals it relies onQuery log: reuse, cost, latency, result digestsCalendar, schedules, seasonality in the query log, known consumers with targetsRequirements gathered in advance
Test that proves itCost and latency budgets, equivalence, retirementAll JIT tests, plus a prediction hit rate: share of warmed views actually read in their windowReconciliation against source systems

Which to use, component by component

If the component is…Use
Ad hoc, exploratory or one team's questionJust in time (L0, maybe an L1 cache)
Reused, with no deadline or scheduled peakJust in time: promote when the triggers fire
Read at a known time with a latency target (board pack, morning dashboard, month-end, launch day)Predictive: warm an L2 view before the window
Seasonal: the query log shows the same spike every month or quarterPredictive: warm before the spike, demote after it
External, regulated or legally consolidated (financial statements, prudential returns)Full conformance, but only for that component (L3)
Cross-company keys and identity (customers, products, accounts)Conformed once: it's a fact, not a performance choice

How to run predictive reuse without rebuilding the medallion: keep a short, reviewed list of "always-warm" definitions, each with a named consumer, a time window and a latency target. Warm it from schedules and from seasonality in the query log, and track its prediction hit rate. A warmed view that isn't read in two consecutive windows drops back to just in time. If the always-warm list grows past a few dozen entries, you're drifting back towards full conformance, so review it.

A view should exist because the query log asked for it, and disappear when the query log stops asking.

Anti-patterns

  • Materialising by org chart. A view per team is a data mart. Materialise per definition.
  • Caching AI SQL text. The text varies from run to run. Cache and fingerprint on definition IDs.
  • Views without owners. L2 can be automated; L3 can't. No owner, no contract, no L3.
  • Promotion without demotion. Without the retirement check, a just-in-time platform quietly becomes the medallion again.
  • Optimising before telemetry. If you can't show the query log row that justifies a view, you don't need it yet.

Skipping the enterprise model doesn't mean skipping performance engineering. It means doing it last, on evidence, one definition at a time.

Sources: Knuth (1974), "Structured Programming with go to Statements", Computing Surveys; Harinarayan, Rajaraman & Ullman (1996), "Implementing Data Cubes Efficiently", SIGMOD; Agrawal, Chaudhuri & Narasayya (2000), "Automated Selection of Materialized Views and Indexes in SQL Databases", VLDB; Google Cloud, INFORMATION_SCHEMA.JOBS and using materialized views (smart tuning); Snowflake, query hash and dynamic table target lag; dbt Labs, saved queries and exports; PostgreSQL documentation, REFRESH MATERIALIZED VIEW. Thresholds are starting defaults, and the cost example is illustrative arithmetic on published on-demand pricing.