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.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_literalsinINFORMATION_SCHEMA.JOBS(it ignores literals and comments). Snowflake recordsQUERY_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
| Signal | Trigger (starting defaults; tune per platform) | Promote to |
|---|---|---|
| Reuse | 2 or more distinct consumers of one semantic fingerprint in 14 days | L1 cache |
| Cost | Weekly on-demand cost of the fingerprint > 3× the cost of refreshing and storing a view | L2 view |
| Latency | p95 above the interactive target (for example 2 s) on more than 5% of runs | L2 view |
| Consistency | More than one result digest for the same definition and window | L3 table |
| Obligation | Feeds an external, regulated or board-level number | L3 table, immediately |
| Silence | No reads for 30 days (L1/L2) or 90 days (L3), no downstream dependants | Retire |
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'sREFRESH MATERIALIZED VIEW CONCURRENTLYfit 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.
| Criterion | Just in time (reactive) | Predictive reuse (pre-warmed) | Full conformance (model first) |
|---|---|---|---|
| What gets built | Only what telemetry proves is reused | JIT, plus a short list of views kept ready for known, scheduled or seasonal demand | Everything, conformed to one model, before use |
| Up-front cost | Lowest | Low: one view per known hot path | Highest: a multi-year programme |
| Running cost | Lowest; pays only for proven reuse | Low to medium; some views warmed and not used | Highest; refreshes everything, read or not |
| Time to first answer for a new question | Minutes | Minutes | Weeks: waits for a model change |
| First-query latency on a hot path | Slow until promoted (cold start) | Fast from the first request | Fast |
| Consistency across consumers | Good once promoted; drift before | Good on warmed paths; JIT elsewhere | Highest, by construction |
| Auditability | Needs definition versions and digests | Same as JIT, plus contracts on warmed views | Strongest, but slowest to change |
| Adapting to change (new sources, acquisitions) | Best | Good | Worst: every change is a model change |
| Main risk | Cold-start pain and early drift on popular questions | Guessing wrong: views warmed for demand that never comes | Waste, delay and a model that's out of date when finished |
| Signals it relies on | Query log: reuse, cost, latency, result digests | Calendar, schedules, seasonality in the query log, known consumers with targets | Requirements gathered in advance |
| Test that proves it | Cost and latency budgets, equivalence, retirement | All JIT tests, plus a prediction hit rate: share of warmed views actually read in their window | Reconciliation against source systems |
Which to use, component by component
| If the component is… | Use |
|---|---|
| Ad hoc, exploratory or one team's question | Just in time (L0, maybe an L1 cache) |
| Reused, with no deadline or scheduled peak | Just 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 quarter | Predictive: 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.
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.