Skip to content
Tech Interview Prep
Technical interview guide

Data Warehousing & Modeling

Star and snowflake schemas, and the fact/dimension split that makes analytical queries fast.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: BigQuery, Amazon Redshift, Snowflake, Apache Iceberg 1.11, PostgreSQL 18, dbt MetricFlow, and OpenLineage documentation current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Define and enforce fact-table grain for a new analytical product.

Answer

The 90-second answer

Grain is the sentence that says what one row means, and it gets written before the columns. For a new analytical product I'd say it out loud: "one row per order line, current version only, keyed by (order_id, line_id), event time in UTC." Then I check that sentence against the source. Does the order service actually emit one row per line, or one per line per status change?

Assumptions I'd state up front: the source is append-only, corrections arrive as new versions, and the product needs line-level revenue rather than order-level.

Then I test every measure against that sentence. line_amount is at line grain, fine. shipping_cost is charged once per order, so it either gets allocated or lives in a separate order-grain fact. customer_lifetime_value is coarser still: separate model. Enforcement is where most teams stop; a declared grain with no test is a comment.

Worked example: catching fanout

Staging holds 3 order lines: 100.00, 140.00, 1000.00. 1240.00 total.

SQL
-- fct_order_lines: one row per (order_id, line_id)
select order_id, line_id, count(*) as c
from analytics.fct_order_lines
group by 1, 2
having count(*) > 1;

Trace: the model joins staging to dim_product on product_key. dim_product is SCD2 and holds two rows for that key, the pre- and post-price-change versions. The join isn't filtered to is_current, so each of the 3 lines matches 2 dimension rows and the fact gets 6 rows. The having clause returns all 3 keys. The control total confirms it: sum(line_amount) is 2480.00 against 1240.00 in staging, exactly 2×. Fix by filtering dim_product.is_current or joining on a versioned key, then re-run the count.

Enforcement in dbt

  • unique and not_null on the surrogate key, or dbt_utils.unique_combination_of_columns on [order_id, line_id] when the key is composite.
  • relationships from fct_order_lines.product_key to dim_product.product_key, to catch orphaned keys.
  • A source-to-target count per event_date partition, so a late-arriving line landing in an already-loaded partition shows up instead of vanishing.
  • A daily control total on line_amount.

Failure modes

Fanout from an unfiltered SCD2 join: caught by the duplicate-key test above. Late-arriving rows: caught by per-partition count reconciliation. Grain drift, where someone adds a promotion column that is one row per promotion per line: caught when a uniqueness test that used to pass starts failing. Silent redefinition, where a MERGE changes what a row means without a version bump: caught by comparing row counts and control totals before and after deploy.

Unknown, not-applicable, corrections

Unknown customer becomes a real customer_key = -1 row in the dimension, not NULL, so the relationships test passes and joins don't drop rows. Not-applicable (shipping on a digital line) is 0.00 with a flag, or NULL with a documented meaning: pick one and test it. Corrections are either a new version row with updated_at or an upsert on the natural key; state which, because it decides whether uniqueness is tested on the natural key alone or key plus version.

Allocation

Shipping of 12.00 on that order, allocated by line share: 0.97, 1.35, 9.68. Sums to 12.00. Name the column shipping_cost_allocated so nobody sums it against the order-level figure.

Contract and monitoring

Expose grain, owner and two example rows in the model contract and semantic layer, so a BI user reads "one row per order line" before writing a query. In production, alert on the uniqueness test failing and on daily control-total drift past a threshold. When grain genuinely changes, version the model (fct_order_lines_v2) or migrate with a documented impact list rather than editing the definition in place.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Choose among transaction, periodic snapshot, and accumulating snapshot facts.

Answer

The grain of the question picks the fact table, not the source system. Before choosing, ask what the table must answer: an event, a state at an interval, or a process lifecycle. Those three map to transaction, periodic snapshot, and accumulating snapshot facts.

TransactionPeriodic snapshotAccumulating snapshot
Grainone row per eventone row per entity per intervalone row per process instance
Loadinsert-onlyinsert-only, one row per periodinsert, then update in place
Additivityfully additivesemi-additive: sum across entities, never across timemeasures additive; milestone dates and lags are not
Answersevent detail, audit, replaypoint-in-time state, fixed-interval trendprocess latency, milestone funnel
Breaks whenpoint-in-time queries scan full historymilestones are irregular or sparsethe process has unbounded or variable steps

A transaction fact is one row per atomic event: a line sale, a payment, a click. It is insert-only, so it replays and reconciles cleanly, and every measure is additive. Its cost is that "what was the balance on 2024-03-01" requires scanning every event up to that date, and that scan grows with history.

A periodic snapshot precomputes that state at a fixed interval: one row per account per day, one row per SKU per day. The interval is part of the grain, and balances are semi-additive: you can sum across accounts, not across days. It answers point-in-time questions with one indexed lookup, at the cost of storage and a defined interval.

An accumulating snapshot keeps one row per bounded process instance (an order, a claim) with milestone date columns and derived lags, updated as the process advances. It is the only one that answers "how long from placed to shipped" cheaply, and it overwrites the row each time, so intermediate states vanish unless a transaction fact keeps them.

Worked arithmetic (hypothetical): 5M accounts, 50M transaction rows per day, 730 days. The transaction fact holds 36.5B rows. An account-day snapshot holds 5M × 730 = 3.65B rows, 10× smaller, and turns "balance on 2024-03-01" into one lookup instead of a scan of every prior event. The snapshot earns its storage only if that query is frequent; if it runs monthly, keep the transaction fact and aggregate on read.

Accumulating snapshot trace for order 4471:

Updateorder_statusplaced_tspaid_tsshipped_tsdays_placed_to_shipped
insertplaced03-01nullnullnull
updatepaid03-0103-02nullnull
updateshipped03-0103-0203-054

Each update overwrites the row. The "paid" state is gone unless the transaction fact preserved it. That is the trade: cheap latency queries, no history.

Failure modes and how to catch them:

  • Late event. A return posted for 03-01 arrives on 03-10. The transaction fact absorbs it; the 03-01 periodic snapshot is now wrong. Detect by re-aggregating transactions for the affected days and diffing against the snapshot.
  • Reopened process. A shipped order is returned and re-shipped. The accumulating row's shipped_ts is overwritten and the original latency is lost. Detect by comparing milestone timestamps against the event stream: two ship events there, one here, means you lost one.
  • Duplicate milestone. Two paid events for one order. The accumulating snapshot keeps the last; the transaction fact keeps both. Reconcile counts per milestone.
  • No-activity period. An account with no transactions still needs a snapshot row if "zero balance" must be distinguishable from "no data". Decide and document it.

Two traps: never sum snapshot balances across days (the semi-additive error), and never use an accumulating snapshot for a process with a variable number of steps. A support ticket with N replies will not fit fixed milestone columns.

Most warehouses need two of the three: a transaction fact for audit and replay, an accumulating snapshot for process latency, and a periodic snapshot only where a fixed-interval query is hot enough to pay for the storage.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Implement a trustworthy SCD Type 2 customer dimension.

Answer

Assumptions first. The source is a CDC stream or nightly snapshot from a CRM; customer_id is the stable business key; the warehouse is Postgres 16, so the constraints below are Postgres-specific. Track a named attribute set, say name, email, tier, address, not every column. Everything else is out of scope for versioning.

Core answer. One table, surrogate key, half-open validity interval, hash of the tracked attributes:

SQL
CREATE EXTENSION IF NOT EXISTS btree_gist;  -- needed for the text equality in EXCLUDE
CREATE TABLE dim_customer (
  customer_sk bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id text NOT NULL,
  valid_from  timestamptz NOT NULL,
  valid_to    timestamptz NOT NULL DEFAULT '9999-12-31 00:00:00+00',
  is_current  boolean NOT NULL,
  attr_hash   char(64) NOT NULL,   -- sha256 hex of tracked attrs
  name text, email text, tier text,
  source_seq  bigint NOT NULL,
  loaded_at   timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX one_current ON dim_customer (customer_id) WHERE is_current;
ALTER TABLE dim_customer ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (customer_id WITH =, tstzrange(valid_from, valid_to, '[)') WITH &&);

The half-open interval [valid_from, valid_to) is the load-bearing choice. A fact at exactly valid_to matches the next version and only the next version, so fact.event_time >= d.valid_from AND fact.event_time < d.valid_to returns exactly one row. Closed intervals double-match at the boundary and force a tie-break in every query.

Change detection: hash the normalized tracked attributes, sha256(coalesce(upper(trim(name)),'') || '|' || ...), and compare to the current row's attr_hash. Equal means no-op. Different means, in one transaction, expire first then insert:

SQL
UPDATE dim_customer SET valid_to = :new_from, is_current = false
 WHERE customer_id = :id AND is_current;
INSERT INTO dim_customer (...) VALUES (...);

Order matters: the partial unique index rejects a second current row, and the exclusion constraint rejects an overlap, so inserting before expiring fails at commit. Both constraints are the safety net; a buggy retry rolls back instead of corrupting history.

Late-arriving change: the hard case. C1 has [2024-01-01, 2024-06-01) tier=gold and [2024-06-01, 9999-12-31) tier=platinum (current). A late event arrives effective 2024-03-01 tier=silver. You split the first interval:

  1. UPDATE dim_customer SET valid_to='2024-03-01' WHERE customer_sk=101;
  2. INSERT sk=104, [2024-03-01, 2024-06-01), tier=silver, is_current=false.

Facts that joined to sk=101 between 2024-03-01 and 2024-06-01 are now wrong. Two ways out:

approachwhen it's rightwhen it's wrong
restate facts: UPDATE fact SET customer_sk=104 WHERE customer_sk=101 AND event_time >= '2024-03-01' AND event_time < '2024-06-01'facts are mutable, restatement window is small, BI needs a single equi-joinfacts are append-only, or the window is months and you rewrite millions of rows
dynamic time join: keep facts immutable, join fact.event_time >= d.valid_from AND fact.event_time < d.valid_tolate data is routine, facts are immutablehigh-concurrency BI where a range join on a 500M-row fact table blows the plan

Hypothetical sizing: a 50M-row customer dimension at 2% daily change adds ~1M versions/day; a 3-month late window can touch ~4M fact rows. That number decides restate vs dynamic join.

Correction vs new change. A correction is the same source_seq with a different payload: overwrite the attribute in place if no facts depend on it, otherwise insert a version flagged is_correction and restate. A new change has a new source_seq. Dedupe on (customer_id, source_seq) so retries are idempotent.

Unknown member. Insert customer_sk=0, customer_id='UNKNOWN', valid_from='1900-01-01', valid_to='9999-12-31' so early-arriving facts have a home.

Tie rule. Order same-timestamp changes by (source_seq, sha256(payload)); if all three match, they are the same event: dedupe.

Test and reconcile. First load, no-op, repeated event, out-of-order correction, business-key reuse, delete/reactivate, concurrent writers, boundary instant, rollback. Then three queries: overlaps (self-join on customer_id where ranges overlap), gaps (lead(valid_from) OVER (PARTITION BY customer_id ORDER BY valid_from) <> valid_to), multiple current (GROUP BY customer_id HAVING count(*) FILTER (WHERE is_current) > 1). Alert on any non-zero.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Model a many-to-many relationship with a bridge table.

Answer

Open with the decision, not the DDL. Two dimensions, many-to-many, so I need a bridge between them. Before I write any DDL I ask one question: will any measure ever be summed through this bridge? That single question decides whether the bridge is a plain junction table or carries allocation weights. I'll assume the relationship is order ↔ promotion: an order can carry several promotions, a promotion applies to many orders.

Plain junction table, when the bridge is only a filter or grouping path and every measure is reported at the fact grain:

SQL
CREATE TABLE bridge_order_promotion (
  order_id      BIGINT NOT NULL,
  promotion_key BIGINT NOT NULL,
  PRIMARY KEY (order_id, promotion_key),
  FOREIGN KEY (promotion_key) REFERENCES dim_promotion(promotion_key)
);

The composite primary key is the relationship identity: it makes duplicate relationships impossible and gives the query planner a covering index for the join.

Bridge with weights, when a measure must be attributed across the members. Add a weight that is explicit about its population and sum rule:

SQL
ALTER TABLE bridge_order_promotion
  ADD COLUMN weight NUMERIC(5,4) NOT NULL
    CHECK (weight > 0 AND weight <= 1);

Why the weight exists: the fanout trace. Three orders, total amount 200:

order_idamountpromotions (weight)
1001100P1 (0.6), P2 (0.4)
100260P1 (1.0)
100340P2 (0.5), P3 (0.5)

Naive join and sum:

SQL
SELECT p.name, SUM(f.amount)
FROM fact_order f
JOIN bridge_order_promotion b USING (order_id)
JOIN dim_promotion p USING (promotion_key)
GROUP BY 1;

Order 1001 now appears twice, so its 100 is counted once under P1 and again under P2. Result: P1 = 160, P2 = 140, P3 = 40. A total of 340 against a true 200. The bridge multiplied the fact by its average degree, 1.7.

Weighted:

SQL
SELECT p.name, SUM(f.amount * b.weight) ...

P1 = 60 + 60 = 120, P2 = 40 + 20 = 60, P3 = 20. Total 200. The weights sum to 1 per order, so the allocation is a partition, not a second copy.

Choosing between the three shapes.

ShapeUse whenDon't use when
Junction tableBridge is a filter/grouping path onlyAny measure is summed through it
Weighted bridgeMeasures must be attributed across membersWeights can't be justified per fact row
Effective-dated bridgeMembership changes and you need point-in-time attributionRelationship is immutable

Effective-dating adds valid_from/valid_to to the bridge and forces every fact join to carry the event timestamp into the interval predicate: that's the cost, and it's only worth paying when history genuinely changes the answer.

Failure modes and how I'd catch them.

  • Fanout double-count. Detect by comparing SUM(amount) through the bridge against SUM(amount) at the fact grain; a ratio above 1 is the leak.
  • Weights that don't partition. GROUP BY order_id HAVING SUM(weight) <> 1: this is the check that keeps the weighted total honest.
  • Overlapping validity intervals. Self-join the bridge on a.valid_from < b.valid_to AND b.valid_from < a.valid_to for the same relationship key; any hit is a broken interval.
  • Hierarchy cycle. If the bridge is self-referencing (employee → manager), a recursive CTE loops forever; cap the recursion depth and alert when the cap is hit.

If the interviewer pushes further: publish the allowed join paths and cardinality so the semantic layer generates the weighted join rather than the naive one, and reconcile bridge row counts against the source relationship population on every load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Handle early-arriving facts and late-arriving dimensions.

Answer

Assume a star schema where facts carry a surrogate FK into a Type-2 dimension, and the loader gives no ordering guarantee between fact and dimension. The answer in the first minute: never drop the fact, never bind it to a wrong current version. Land it against a reserved unknown member, keep the natural key on the fact row so it can be re-resolved, and repair when the dimension arrives.

Mechanism. Reserve negative surrogate keys and seed them as real dimension rows: -1 unknown, -2 not applicable, -3 invalid/redacted. Because they are rows, every inner join still returns the fact: the fact stays complete and the descriptive context is honestly labelled. The fact row also carries the natural key (customer_id) as a degenerate dimension; that is what makes repair possible later.

When the dimension arrives, insert the Type-2 version with effective dates backdated to cover the fact's event time, then re-point the fact:

SQL
INSERT INTO dim_customer (customer_sk, customer_id, name, eff_start, eff_end, is_current)
VALUES (-1, 'UNKNOWN', 'Unknown', '1900-01-01', '9999-12-31', TRUE);

INSERT INTO fct_order (order_id, customer_sk, customer_id, order_ts, amount)
VALUES (9001, -1, 'C-4471', '2024-03-01 09:14:00', 120.00);

INSERT INTO dim_customer (customer_sk, customer_id, name, eff_start, eff_end, is_current)
VALUES (55012, 'C-4471', 'Acme Ltd', '2024-03-01', '9999-12-31', TRUE);

UPDATE fct_order f
SET customer_sk = d.customer_sk
FROM dim_customer d
WHERE f.customer_sk = -1
  AND f.customer_id = d.customer_id
  AND f.order_ts >= d.eff_start
  AND f.order_ts <  d.eff_end;

Trace: order 9001 lands with customer_sk = -1. The dimension row arrives on 2024-03-04 with eff_start 2024-03-01, so the join predicate matches and the update sets customer_sk = 55012. One row changed.

Trade-off. In-place update is cheap and keeps a single fact table, but it mutates history and breaks immutability. If the fact must stay immutable (audit, event sourcing), leave the fact alone and resolve through a versioned mapping table or a view that joins fact.customer_id to the dimension as-of the event time. That costs a join on every read and needs the mapping maintained, but the original fact is never rewritten.

Failure modes. Key reuse: a customer_id recycled for a different entity: guard by matching on the natural key plus event time, and alert when one natural key maps to two live versions. Two late versions: pick the version whose [eff_start, eff_end) contains the event time, not the latest. Deletion: a dimension row removed leaves the fact orphaned. Detect with a left-anti join from fact to dim and re-point to -3. Concurrent repair: two repair jobs racing on the same fact. Make the update idempotent (WHERE customer_sk = -1) and take a row lock.

Reconciliation. Report total facts, unresolved count, age in days, and value at risk. Example: 1.2M facts/day, 0.3% arrive before the dimension → 3,600 rows/day; with a 48h dimension SLA, steady-state unresolved ≈ 7,200 rows. Escalate: unresolved older than the SLA pages the on-call owner. Notify consumers when a repair changes historical aggregates, and keep lineage from the original fact row through the repair.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Create conformed dimensions across independently owned data marts.

Answer

What a strong candidate says first. A conformed dimension is one physical table, owned by one team, that several marts join to with the same meaning and the same surrogate keys. Assume two independently owned marts, Sales and Support, that both need customer, and that neither team will accept the other's schema. The move is to publish a narrow contract: identity, keys, a few core attributes, and time semantics. Domains keep their own attributes in extension tables keyed by the conformed surrogate. Centralizing every attribute is what turns a conformed dimension into a bottleneck.

The contract.

ColumnTypeWritten byNotes
customer_skbigintconformed dimsurrogate; never reused; the join key
source_systemtextsourcenamespace, e.g. crm, zendesk
source_idtextsourcebusiness key, unique within source_system
name, email, segmenttextCRMcore attributes, SCD2-tracked
valid_from, valid_todateconformed diminclusive; 9999-12-31 while current
is_currentbooleanconformed dimconvenience flag

The CRM is authoritative for identity. Sales and Support each keep their own customer_id; a crosswalk table maps (source_system, source_id) -> customer_sk so a mart resolves its own IDs without knowing anyone else's. support_tier and sales_region stay in per-domain extension tables keyed by customer_sk.

History. SCD2, with the effective date carried in staging rather than taken from the clock (PostgreSQL 15):

SQL
BEGIN;

-- 1. Close the current row wherever a tracked attribute changed.
UPDATE dim_customer d
SET valid_to = s.effective_date - 1, is_current = false
FROM stg_customer s
WHERE d.source_system = s.source_system
  AND d.source_id     = s.source_id
  AND d.is_current
  AND (d.name, d.email, d.segment)
      IS DISTINCT FROM (s.name, s.email, s.segment);

-- 2. Insert a current row for changed keys and for keys never seen.
INSERT INTO dim_customer
  (customer_sk, source_system, source_id, name, email, segment,
   valid_from, valid_to, is_current)
SELECT nextval('customer_sk_seq'), s.source_system, s.source_id,
       s.name, s.email, s.segment,
       s.effective_date, DATE '9999-12-31', true
FROM stg_customer s
LEFT JOIN dim_customer d
  ON d.source_system = s.source_system
 AND d.source_id     = s.source_id
 AND d.is_current
WHERE d.customer_sk IS NULL;

COMMIT;

Step 1 runs first, so a changed key no longer has a current row and step 2's join misses it. IS DISTINCT FROM matters: plain <> returns NULL when either side is NULL, so a NULL-to-value change would never close the old row.

Trace. Customer (crm, 42) currently holds sk 1001, name Ana Ruiz, email ana@old.example, segment smb, valid_from 2023-01-01, valid_to 9999-12-31, is_current true. Staging delivers effective_date 2024-03-10, name Ana Ruiz-Wong, email ana@new.example, segment smb. Step 1 matches and sets valid_to 2024-03-09, is_current false. Step 2's join finds no current row, so it inserts sk 1002 with valid_from 2024-03-10. Sales facts dated before 2024-03-10 still resolve to 1001; later ones resolve to 1002, and Support sees the identical two rows. If the correction actually took effect 2024-02-01 but arrived on 2024-03-10, staging must pass 2024-02-01: using CURRENT_DATE would make every fact dated 2024-02-15 join the wrong version.

Numbers. Sales holds 8M customer rows, Support 6M, overlap 5M. The conformed dimension and crosswalk hold 8M + 6M - 5M = 9M rows. A naive union of the two marts gives 14M, double-counting the 5M shared customers; conforming removes that without fuzzy matching.

When not to. If two domains genuinely share no entity, don't force a join: a shared dimension with no shared grain just adds a hop. And keep the contract narrow: every attribute you add to it is an attribute two teams must agree on before either can ship.

Failure modes and how to catch them.

  • ID recycling: a source reuses source_id for a different person. Detect with a check that no (source_system, source_id) has two rows with is_current = true, plus a uniqueness check on (source_system, source_id, valid_from).
  • Divergent hierarchies: Sales rolls up to region, Support to org. Detect by counting dimension rows whose parent_sk has no row in the conformed parent.
  • Stale consumers: a mart pinned to contract v1 keeps reading a renamed column. Detect from the warehouse's access history for the old name, and keep v1 readable for a fixed deprecation window (90 days is a common one) before dropping it.
  • Late-arriving facts: a fact dated 2024-02-15 lands after the dimension moved. Detect with a reconciliation query counting facts whose date falls outside every matching row's [valid_from, valid_to].
  • Mergers and splits: two source customers merge into one, or one splits into two. Point both source_ids at one customer_sk in the crosswalk and never rewrite history; a split gets a new customer_sk and old facts keep the old one.

Governance. Publish the dimension as a versioned dataset behind a controlled interface (a dbt model with an enforced contract, or a data share) and require a change proposal with impact analysis before the contract moves. Test mergers, splits, deletes, late corrections and rollback, each with a named owner.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you design an enterprise data warehouse bus architecture and bus matrix across multiple business processes?

Answer

The 90-second answer. The bus architecture is two artefacts: a matrix mapping business processes to conformed dimensions, and a set of dimension tables every fact joins with identical keys and attribute semantics. You build the matrix before any ETL, because it is the contract that lets separate teams ship fact tables independently and still drill across them. Conformance is a governance cost you pay on purpose. It pays off when three or more processes share an entity and more than one team owns a fact table; it does not when you have one domain, one team, and no cross-process question to answer.

1. Building the matrix

  1. Rows are business processes, not departments or reports: Order Placement, Fulfillment, Invoicing, Inventory Snapshot. Each produces one or more fact tables.
  2. Columns are conformed dimensions: dim_date, dim_customer, dim_product, dim_facility.
  3. Mark participation and grain per cell: direct, rolled up, or via an outrigger.
  4. Freeze the dimension contract: surrogate keys, natural business keys, attribute names, and SCD policy. When a process needs a coarser grain (monthly targets vs daily transactions), publish a shrunken rollup dimension with the same attribute definitions rather than a second dimension.
Business Process (Fact Grain)DateCustomerProductFacilityCarrierCore Metric / Type
Order Placement (order line)XXXXOrdered Qty, Gross Amount (Transaction)
Fulfillment (shipment line)XXXXXShipped Qty, Freight Cost (Transaction)
Invoicing (invoice line)XXXInvoiced Amount, Tax (Transaction)
Inventory (SKU × day × facility)XXXQuantity on Hand (Periodic Snapshot)

2. Drill-across, not multi-fact joins

Joining fact_orders to fact_shipments on order_id fans out: one order line can map to several shipment lines, so gross_amount is counted once per shipment. Aggregate each fact to the shared conformed keys, then FULL OUTER JOIN on those keys.

SQL
WITH orders_agg AS (
    SELECT dim_customer_key, dim_product_key,
           SUM(ordered_qty)  AS total_ordered_qty,
           SUM(gross_amount) AS total_gross_amount
    FROM fact_orders
    WHERE order_date_key >= 20240101
    GROUP BY 1, 2
),
shipments_agg AS (
    SELECT dim_customer_key, dim_product_key,
           SUM(shipped_qty) AS total_shipped_qty
    FROM fact_shipments
    WHERE shipment_date_key >= 20240101
    GROUP BY 1, 2
)
SELECT COALESCE(o.dim_customer_key, s.dim_customer_key) AS dim_customer_key,
       COALESCE(o.dim_product_key,  s.dim_product_key)  AS dim_product_key,
       COALESCE(o.total_ordered_qty, 0) AS ordered_qty,
       COALESCE(s.total_shipped_qty, 0) AS shipped_qty,
       COALESCE(o.total_ordered_qty, 0) - COALESCE(s.total_shipped_qty, 0) AS pending_fulfillment_qty
FROM orders_agg o
FULL OUTER JOIN shipments_agg s
  ON o.dim_customer_key = s.dim_customer_key
 AND o.dim_product_key  = s.dim_product_key;

Note the two CTEs filter on different date roles. That makes the last column a period comparison, not a true backlog. For a real backlog, fact_shipments must carry order_date_key as a role-playing dimension and both CTEs filter on it.

3. When conformance is not worth it

ApproachBuysCostsChoose when
Kimball busIndependent team delivery, drill-across, one customer definitionDimension design authority, coordinated SCD releases≥3 processes share an entity, ≥2 teams own facts
One Big TableFastest to first dashboard, no joinsDimension logic re-implemented per table; rebuild cost grows with widthSingle domain, one team, no cross-process question
Data Vault 2.0Auditable hubs/links/satellites, parallel loads, absorbs source churnRaw vault queries need PIT/bridge tables; you still build a star layer on topMany volatile sources, regulatory lineage
Semantic layer (dbt Semantic Layer, Cube, LookML)Metrics defined once, computed at query timeBreaks when teams fork definitions; row-level drill-across gets expensiveLakehouse compute is cheap, dimension count is small

Data Vault is upstream of the bus, not a substitute: it still needs conformed dimensions in the presentation layer.

4. Failure modes

  • Forked dimensions. Marketing builds dim_mkt_customer, Finance builds dim_fin_customer; drill-across silently drops rows. Detect with lineage tooling (OpenLineage) flagging parallel pipelines writing the same entity.
  • Mismatched SCD policy. Customer is Type 2 in orders and Type 1 in shipments, so historical drill-across attributes the shipment to today's customer version. Enforce one SCD policy per dimension in the contract.
  • Grain mismatch. Joining monthly budget facts to daily transactions without rolling to month_end_date_key yields nulls or a Cartesian blowup.
  • Late-arriving members. A shipment references a customer key not yet in dim_customer; the drill-across row survives via COALESCE but the attributes are null. Inferred-member rows in the dimension fix this.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a sales warehouse model for orders, shipments, refunds, and customers.

Answer

Two things decide this model before any table gets drawn: what one row means in each fact, and whether the customer dimension needs history. I'll assume a Kimball star schema on a columnar warehouse (Snowflake, BigQuery, Redshift), batch loads, and refunds that can be partial and land days after the order.

Grains. Separate facts, one grain each:

FactOne row is
order_lineone order line, per order revision
shipment_lineone shipment line event
fulfillmentone order, updated at each milestone (accumulating snapshot)
refund_lineone refunded line, pointing back at the order line it reverses
inventory_dailyone product × location × day

The accumulating snapshot is what lets you answer "orders shipped late" without joining three facts; it carries order_date, ship_date, delivery_date, return_date and the lag columns between them.

Keys and dimensions. Every fact gets a warehouse surrogate key plus the source business key, so reloads are idempotent. Conformed dimensions: date, product, customer, channel, geography. Dates role-play: order_date_key, ship_date_key and refund_date_key all point at the same date dimension. order_number is a degenerate dimension on the order line fact. Promotions are many-to-many, so a bridge table with allocation weights that sum to 1 per order.

History. Decide Type 1 versus Type 2 per attribute, not per dimension. Customer segment and credit tier are Type 2 (valid_from, valid_to, is_current); a corrected spelling is Type 1. Each Type 2 version gets a new surrogate key while the natural key stays stable.

Money. Store additive components (extended_amount, discount_amount, tax_amount) and derive rates. Never put an order-level discount on the line fact without allocating it. Worked example: an order has lines 2 × 30.00 and 1 × 40.00 = 100.00, with a 10.00 order-level discount. Allocate by extended amount: 60/100 × 10 = 6.00 and 40/100 × 10 = 4.00. Now sum(line net) = 90.00 and it ties to the header. Skip the allocation and you either double-count the 10.00 or lose it.

Failure modes and how I'd catch them.

  • Mixed grains: sum(line extended_amount) ≠ order header total. Test: reconcile per order, tolerance 0.01.
  • SCD2 overlap: a customer counted twice in a month. Test: for each customer_id, no two [valid_from, valid_to) intervals overlap.
  • Late-arriving dimension: the fact lands before the customer row. Insert an inferred member (key 0) and backfill later. Detect: count of facts with customer_key = 0.
  • Currency mixing: summing across currencies is meaningless. Store transaction currency plus a converted amount and the rate date; detect: distinct currency_code > 1 inside one aggregate.
  • Restatement: reloads duplicate rows. Merge on business key + load date; detect: duplicate business keys.

Reconciliation. Publish source-to-fact row counts and monetary sums, referential and interval tests, freshness and lineage. I'd validate the cross-process queries, order to ship to refund, against source controls before tuning layout.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design an incremental warehouse load from change data capture.

Answer

Assumptions. Source is Postgres 15 with wal_level=logical, captured by Debezium 2.x into Kafka with 7-day retention; sink is a Postgres warehouse. Volume is ~5,000 row changes/s at ~1 KB each. If your source has no primary key or no monotonic log position, stop: this design does not apply.

The answer. Bootstrap with pg_export_snapshot() plus the current LSN, so the snapshot and the log stream meet at exactly one point. Land every change raw and immutable in an append-only table keyed by (source_table, pk, lsn). Deduplicate exact retries on that key: Debezium redelivers at-least-once after a restart. Then apply one idempotent merge per target table, guarded by a monotonic op_seq (the LSN), and commit the Kafka offset only after the sink transaction commits. That ordering is what makes the pipeline exactly-once at the business outcome: a crash between sink commit and offset commit replays a batch that the op_seq guard turns into a no-op.

The merge, and why it is idempotent.

SQL
INSERT INTO dim_customer (customer_id, name, email, op_seq, is_deleted)
SELECT customer_id, name, email, op_seq, (op = 'd')
FROM (
  SELECT DISTINCT ON (customer_id) customer_id, name, email, op, op_seq
  FROM stg_customer_changes
  ORDER BY customer_id, op_seq DESC
) s
ON CONFLICT (customer_id) DO UPDATE
SET name = EXCLUDED.name, email = EXCLUDED.email,
    op_seq = EXCLUDED.op_seq, is_deleted = EXCLUDED.is_deleted
WHERE EXCLUDED.op_seq > dim_customer.op_seq;

Trace with three staged rows for customer 7: (7,'a',100,'u'), (7,'b',101,'u'), (7,'a',100,'u'). The last is a redelivery. DISTINCT ON keeps the row at op_seq=101. First run: no target row, so INSERT (7,'b',101,false). Replay the same batch: target op_seq=101, EXCLUDED.op_seq=101, and 101 > 101 is false, so no write. A late-arriving op_seq=99 change also fails the guard. Deletes are not physical: is_deleted=true keeps the key so a later re-insert with a higher op_seq resurrects it correctly.

Alternatives.

approachwhen it winswhen it breaks
CDC log-apply (above)source has a reliable log; need seconds-level freshnessno PK / no LSN; retention shorter than your worst outage
periodic full-snapshot diffsmall tables, no log accessa 10M-row table re-read hourly; misses deletes unless you diff
timestamp watermark (updated_at > last_run)trivial to buildclock skew and same-second updates silently drop rows

Sizing. 5,000 changes/s × 1 KB = 5 MB/s ≈ 432 GB/day; 7-day Kafka retention ≈ 3 TB. If your worst sink outage can exceed retention, you must be able to re-snapshot, not just replay.

Failure modes to test. Kafka retention expiry while the sink is down → an unrecoverable gap; record it, do not advance the offset. A transaction split across two Kafka messages → apply per transaction, not per message, or you expose a half-applied order. Primary-key reuse after a delete → the op_seq guard handles it only if the new row's LSN is higher. Sink failure after commit but before offset commit → replay, absorbed by the guard. Schema change → version the staging table and fail the merge loudly on an unknown column rather than dropping it.

When not to use this. If the source cannot give you a monotonic position or a stable key, use snapshot-diff instead and accept the freshness cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design warehouse data-quality checks and reconciliation.

Answer

The 90-second answer. Ask two things before writing a check: what decision does this table feed, and what does a wrong number cost? A finance close off by one row is a restatement; a marketing dashboard off by four rows is noise. That sets the fail/warn line. Then put checks at the boundaries where data changes shape (source extract, staging load, modelled mart) and reconcile each boundary against the one before it, not against a hand-maintained expectation.

Assumptions I'd state up front: batch ELT, a daily business date in a named timezone, one source system of record per entity, and a warehouse that can hold a reject table.

What to check, and where. At extract: file or partition completeness (did all 24 hourly files land?), source high-water mark, row count by status. At staging: schema drift (column added, removed, retyped), duplicate keys, null rate on required columns. At the mart: grain uniqueness, referential coverage, SCD2 one-current-per-key and non-overlapping validity, bridge allocation summing back to the fact.

Reconciliation. Compare populations by a dimension that can't cancel (status, business date, source system) plus additive control totals (count, units, currency-normalized amount). Totals alone are not enough: two errors of opposite sign cancel. Every expected difference gets a reason code and an owner; an unexplained difference is a failure.

Worked trace. Oracle orders, business date 2024-03-11 America/New_York, extract filter order_ts >= 2024-03-11 AND < 2024-03-12 local.

  • Extract: 1,284,301 rows. Staging: 1,284,297. Delta 4.
  • By status: COMPLETE 1,201,884 / PENDING 61,203 / CANCELLED 21,214 on the source, against 1,201,884 / 61,203 / 21,210 in staging. All four missing rows are CANCELLED.
  • Control totals: SUM(units) 3,847,112 on both sides; SUM(amount_usd) 412,889,301.44 on both sides. A totals-only check passes: the four dropped rows were cancellations carrying zero units and zero amount.
  • Cause: the loader deduped with ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC). Four order_ids were reused after cancellation, so the dedup kept one row per id and dropped the rest. Fix: partition by (order_id, updated_at), or key on the source surrogate.
  • Freshness: staging max(order_ts) is 2024-03-11 23:59:58 -04:00; source max is 2024-03-12 03:59:58 UTC. Same instant: a naive string compare of the two would report a false four-hour lag.

That's the shape: the count-by-status check caught it, the totals check didn't, and the freshness check would have lied if it compared timestamps without normalizing timezone.

Thresholds and tooling. Freshness: warn at 15 minutes past data_interval_end, fail at 30. Null rate on a required column: fail above 0.1%. Duplicate rate on the grain key: fail above 0. dbt covers unique, not_null, relationships, accepted_values and dbt_utils.unique_combination_of_columns; Great Expectations or a source-side SQL check covers the extract; Snowflake ACCOUNT_USAGE.COPY_HISTORY proves which files landed. SCD2 overlap: LEAD(valid_from) OVER (PARTITION BY customer_id ORDER BY valid_from) < valid_to must return zero rows.

Failure modes. Checks that always pass (stale thresholds, a filter that excludes the bad rows), checks that fail every run so people ignore them, and quarantine tables nobody drains. Detect by tracking pass rate and reject volume per check over time; a check at 100% pass for 90 days gets reviewed, not trusted.

What changes the decision. If the consumer is a regulatory report, the four-row delta fails the pipeline and blocks publish. If it's an internal dashboard, it warns, publishes with the quality result attached, and opens a ticket. Same check, different gate, which is why the consequence question comes first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Backfill and restate a large historical warehouse partition safely.

Answer

Assumptions I'd state first: a partitioned fact table with daily partitions, roughly three years of history, and a live incremental job writing today's partition. I'll assume Iceberg or Delta on object storage; the shape is the same on Snowflake or BigQuery.

The answer: never correct history in place. Build the corrected partitions in an isolated location, prove them against the version you're replacing, then swap them in with one atomic commit. Fencing the writer, throttling, and consumer notification all hang off that.

Why staging beats in-place: an UPDATE across 1,095 daily partitions is not atomic. Readers see a half-corrected table, and if the job dies at 60% there's no clean rollback: you reconcile by hand. A staged build has one commit point, and rollback is "don't swap".

The swap, per engine:

engineatomic swapcost
SnowflakeALTER TABLE fact SWAP WITH fact_stagemetadata-only, milliseconds
BigQueryCREATE OR REPLACE TABLE, or WRITE_TRUNCATE on fact$20240101per-partition
IcebergALTER TABLE fact REPLACE WITH fact_v2one new snapshot
DeltaREPLACE TABLE fact USING DELTA AS SELECT ... (Delta 2.0+)one commit

Fence the writer for the affected range only. On Snowflake, ALTER TASK ... SUSPEND then resume; on Airflow, pause the DAG; on Kafka, pause the partitions and commit offsets. Cheaper than a full freeze: a watermark table the incremental job reads, so it refuses to write any partition at or below the backfill's high-water mark.

Now the numbers that decide whether this is safe. Your "reproducible snapshot" has an expiry. Snowflake Time Travel defaults to 1 day on Standard (up to 90 on Enterprise); BigQuery's time-travel window is 7 days; Iceberg expires snapshots at history.expire.max-snapshot-age-ms = 5 days by default; Delta keeps logs 30 days but deletes files after 7. If the backfill outruns that window, the snapshot you validated against is gone. Set retention explicitly before you start.

Sizing: three years of daily partitions is ~1,095. At 10 GB each that's ~11 TB. Spark's spark.sql.shuffle.partitions defaults to 200, so each task handles ~55 GB and spills to disk. Set it to a few thousand, or turn on AQE.

Validation before the swap: per-partition row count, sum(amount), count(distinct entity_id), min/max event time. Then a FULL OUTER JOIN on the natural key between old and new, classifying every diff as expected (the correction) or not. For SCD2, assert no overlapping intervals: LEAD(valid_from) OVER (PARTITION BY entity_id ORDER BY valid_from) = valid_to.

Failure modes, with the signal that catches each:

  • Snapshot expired mid-run. Signal: "snapshot not found", or the load checksum differs from the validation checksum. Blast radius: silent wrong data if you fall back to "latest". Cost: full re-run.
  • Double-apply. The backfill writes rows the incremental job also writes. Signal: count(*) != count(distinct pk). Blast radius: doubled revenue.
  • Mixed schema. Reader sees old and new columns. Signal: nulls in the new column, or a schema-mismatch error. Blast radius: dashboards break.
  • Compaction storm. 11 TB of new small files. Signal: file count per partition, query latency. Cost: storage and compute.

After the swap, version the aggregates and caches, tell consumers the numbers changed, and watch late deltas for a few days.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Evolve a warehouse schema and metric contract without corrupting history.

Answer

"Corrupting history" means one of two things: old rows become unreadable, or old rows stay readable but get reinterpreted under the new contract. A 2023 order that was gross revenue silently starts counting as net. The second is worse, because nothing errors.

Assume Iceberg or Delta on object storage (or Snowflake), dbt for transforms, a semantic layer (MetricFlow, Cube, LookML) over the marts, and consumers split between BI dashboards and an ML feature pipeline. If your warehouse is one Postgres and every consumer is a dbt model you own, most of this collapses to a coordinated rename in a single PR.

Classify the change before touching anything. The class picks the mechanism, and storage-format support is not semantic safety: Iceberg will happily let you drop and re-add a column with the same name.

changemechanismwhat breaks if you skip it
additive nullable columnALTER TABLE ... ADD COLUMN (metadata-only in Iceberg and Snowflake)nothing; old files return NULL
type widening (int to bigint)in place in Iceberg/Delta; full rewrite in Parquet-onlyoverflow on old readers
renameadd new, dual-write, compat view, then dropname-resolving readers see NULL
grain change (order-line to order)new table plus a versioned modeldouble-counted sums
unit or timezone shiftnew column, never in placesilent 5-8 hour skew
metric redefinitionnew metric versiondashboards change meaning overnight

Then expand-and-contract. In dbt:

YAML
models:
  - name: fct_orders
    latest_version: 2
    versions:
      - v: 1
        defined_in: fct_orders_v1
      - v: 2
        defined_in: fct_orders_v2

with a compatibility view so v1 readers keep working while you migrate:

SQL
CREATE OR REPLACE VIEW analytics.fct_orders AS
SELECT order_id, order_total_usd AS order_total, ordered_at
FROM marts.fct_orders_v2;

Backfill sizing, hypothetical: 2.4B rows, 1.1 TB Parquet, partitioned by day. Adding a nullable column is metadata-only: seconds. Recomputing a derived column reads 1.1 TB; at 500 MB/s that is roughly 37 minutes I/O-bound, so run it partition by partition and reconcile each day's row count and SUM(amount) against the pre-change snapshot before moving on.

Deploy order: tolerant readers and the compat view first, then writers, then backfill, then migrate consumers using query-log evidence of who actually reads the old name. Keep the old column until the longest retention or legal window closes, seven years for financial facts is common, and never reuse a dropped name with a new domain.

Failure modes and how you catch them:

  • Column reuse: old Parquet files resolve the reused name to the new domain. Detect with a schema-drift check comparing Iceberg column IDs to names.
  • Timezone shift: histogram ordered_at by hour-of-day across the cutover; a step change is the tell.
  • Grain change: row-count ratio plus control-total reconciliation against the source system.
  • Mixed-version join: a v1 fact joined to a v2 dim on a renamed key returns NULLs, not errors. Assert non-null on join keys in the mart tests.

What would change my decision: if every consumer is a dbt model in the same repo, skip the compat view and rename in one PR. If a metric's meaning changes, never redefine in place: publish revenue_v2 alongside revenue_v1 and let the semantic layer deprecate v1 on a dated schedule.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Recover a warehouse model after a partial or corrupt publication.

Answer

I'd treat this as a distributed commit failure, not a data bug. First I clarify: is publication one atomic commit across facts, dimensions, aggregates and semantic metadata, or a sequence of independent table writes? If it's a sequence, there is no cross-table rollback; I need a manifest of the intended version. Then I fence writers, find the last coherent snapshot, roll back or route consumers, rebuild only if no snapshot exists, validate, reconcile exports, and resume from the exact boundary.

Fencing beats stopping writers because stopping leaves in-flight jobs that can commit after I've inspected state. Fencing revokes the writer role or sets a table property that rejects new commits, so in-flight jobs fail at commit time. Iceberg and Delta commit by swapping a metadata pointer; old files stay in place. That's why rollback is O(1) metadata, not a rewrite. Iceberg: CALL catalog.system.rollback_to_snapshot('db.fact_sales', 1234567890);. Delta: RESTORE TABLE db.fact_sales TO VERSION AS OF 12;. Snowflake Time Travel uses AT (TIMESTAMP => ...); BigQuery uses FOR SYSTEM_TIME AS OF. Retention bounds the option: Iceberg history.expire.max-snapshot-age-ms defaults to 5 days, Delta VACUUM defaults to 7 days, Snowflake Time Travel defaults to 1 day on Standard and up to 90 on Enterprise, BigQuery time travel is 7 days.

Newest table timestamp is not proof. Here's a hypothetical trace. SELECT snapshot_id, committed_at, summary FROM db.fact_sales.snapshots ORDER BY committed_at DESC LIMIT 5; returns s3 at 10:07 with added-records=1200, s2 at 10:05 with added-records=0, deleted-records=400, s1 at 10:00 with added-records=800. DESCRIBE HISTORY db.dim_customer; shows the 10:06 load deleted 400 customer rows. s3 is newest, but s2's dimension delete breaks referential intervals, so the last coherent version is s1. I roll back fact_sales to s1 and dim_customer to its 10:00 version, then check that aggregates and semantic metadata also point at s1.

If no snapshot exists, rebuild from a reproducible source snapshot or log position using idempotent transformations, isolated staging and a single writer. Validate before atomic republish: grain (SELECT COUNT(*) FROM fact_sales WHERE ds='2025-01-01'; against source), populations, control totals (SELECT SUM(amount) ...), referential integrity (SELECT COUNT(*) FROM fact_sales f LEFT JOIN dim_customer d ON f.customer_key=d.customer_key WHERE d.customer_key IS NULL;), SCD intervals (SELECT customer_key FROM (SELECT customer_key, effective_from, LAG(effective_to) OVER (PARTITION BY customer_key ORDER BY effective_from) AS prev_to FROM dim_customer) WHERE prev_to > effective_from;), deletes, and representative metrics.

optionmechanismwhen not to use
Rollback to snapshotMetadata pointer swap; O(1)Snapshot expired, or consumers already exported mixed results
Route to prior viewPoint consumers at verified viewView lacks new schema or required partitions
RebuildReplay from source snapshot/logSource retention expired or transformations nondeterministic

Failure modes: two writers interleave commits (detect via overlapping committed_at and duplicate snapshot IDs); HDFS rename is not atomic across directories, and object stores can leave orphan multipart uploads; schema drift makes old snapshots unreadable; nondeterministic transforms produce different row counts on replay; permission changes block rollback; orchestration retries publish twice. Root-cause those, then harden gates. Drill loss of snapshot, expired source retention and rollback incompatibility. If evidence cannot establish the interval, say so rather than synthesizing certainty.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you reconcile and validate historical metrics between an existing reporting system and a newly migrated dimensional warehouse?

Answer

I'd start by pinning down what "reconcile" means here: for a frozen historical window, the same metric at the same grain should produce the same number in both systems, and every difference should be attributable to a named cause. I'd assume the legacy system is the reference for the historical period, it's what finance already signed off on, and that both sides can be read at a fixed point in time. If the warehouse is meant to be the new truth rather than a re-implementation, you're not reconciling, you're restating, and that needs a business owner, not a query.

First move is to freeze the window. Comparing against live tables gives you phantom diffs from late-arriving rows and in-flight updates. Pick closed periods (full calendar quarters, or explicit t_start/t_end) and read both sides at a snapshot. On Iceberg that's AS OF a snapshot ID or timestamp; on anything else, materialize the legacy extract into a read-only schema and hash it so nobody can mutate it mid-audit.

Then compare coarse to fine, never the reverse. Global totals first (SUM(revenue), COUNT(DISTINCT account_id)) because one matching number tells you the pipelines agree and the problem is slicing. Then month × country, then down to order IDs with a set difference. Row-level diffing first burns compute and hides the cause.

Postgres-flavoured SQL for the middle step:

SQL
SELECT COALESCE(l.month, w.month) AS month,
       COALESCE(l.country, w.country) AS country,
       l.rev AS legacy_rev, w.rev AS wh_rev
FROM (SELECT date_trunc('month', order_ts)::date AS month,
             country_code AS country, SUM(amount_usd) AS rev
      FROM legacy.orders
      WHERE order_ts >= '2023-01-01' AND order_ts < '2024-01-01'
      GROUP BY 1, 2) l
FULL OUTER JOIN
     (SELECT d.month_start_date AS month, g.country_code AS country,
             SUM(f.amount_usd) AS rev
      FROM wh.fact_orders f
      JOIN wh.dim_date d ON f.date_key = d.date_key
      JOIN wh.dim_geo  g ON f.geo_key  = g.geo_key
      WHERE d.full_date >= '2023-01-01' AND d.full_date < '2024-01-01'
      GROUP BY 1, 2) w
  ON l.month = w.month AND l.country = w.country
WHERE l.rev IS DISTINCT FROM w.rev;

Every surviving row falls into one of four buckets, and the signature tells you which:

ClassSignatureFix
Time-zone / boundarydiffs cluster on the 1st and last day of the month, magnitude ≈ one day's volumealign both sides to UTC, or to the dim_date convention, and re-run
SCD2 reattributionglobal totals match, but value moves between region or segment slicesresolve FKs to point-in-time dimension versions; confirm the business wants as-of attribution
Fanoutwarehouse > legacy by roughly an integer factor (2×, 3×)apply allocation factors on bridge joins
Filter drifta fixed row set present on one side only, matching a status predicatecodify the metric once, dbt MetricFlow or equivalent, so the filter lives in one place

Tolerances are per metric class, not global. Money gets exact equality after currency rules; a cent of drift on revenue is a bug, not noise. Non-financial counts like sessions or events can carry ≤ 0.01%: on 50 million events that's 5,000 rows, so a 40,000-row diff isn't rounding, it's a missing filter.

What changes my recommendation: if the residual is explained and inside tolerance, I sign off and retire the legacy extract. If it's explained but the business prefers the legacy semantics, current-state attribution instead of point-in-time, I don't loosen the tolerance, I change the warehouse model or document a restatement. If it's unexplained and above tolerance, no cutover, and the legacy table stays read-only as the fallback until it is.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design a semantic metric layer over warehouse models.

Answer

Core answer. Treat the semantic layer as a compiler from metric definitions to SQL, not as documentation. It fixes meaning; it cannot fix data. So the order is: prove grain on the models, declare entities and join paths, then define metrics on top. If a fact table's grain is ambiguous, stop and fix the model: a metric defined over it will be wrong in a way no amount of governance catches.

Assumptions: the warehouse is the system of record; consumers are BI, notebooks and reverse-ETL; joins happen in the warehouse, not in the BI tool.

Entities and join paths. For each model, declare grain in one sentence ("one row per order", "one row per order line per status change"). Then keys: a surrogate primary key, foreign keys to conformed dimensions, and a natural/business key that survives reloads. Declare every allowed join with its cardinality (one-to-many, many-to-many) because that declaration is what lets the compiler avoid fanout. Disallow joins that aren't declared; an undeclared join is where double counting enters.

Metric spec. A metric carries: aggregation or numerator/denominator, filters, the time dimension, calendar and timezone, null and late-data rules, currency/unit, valid dimensions, owner, version, freshness SLA. Ratios derive from additive components and are computed after aggregation, never as a row-level division.

YAML
metric: net_revenue
type: derived
expression: revenue - refunds
time_dimension: order_completed_at   # event time, not loaded_at
timezone: UTC
grain: day
late_data_window: 3 days
valid_dimensions: [region, channel, product_family]
owner: finance-analytics
version: 4

Worked trace: fanout. orders is one row per order; order_items is one row per line.

order_idamount
1100
250
320

SUM(amount) = 170. Order 1 has 2 items, order 2 has 1, order 3 has 3. orders JOIN order_items USING (order_id) produces 6 rows, and SUM(orders.amount) = 100+100+50+20+20+20 = 310: an 82% overstatement. The fix is to aggregate orders to the order grain before the join, or declare the relationship one-to-many and let the compiler do it. Looker's symmetric aggregates do exactly this, keyed on the declared primary key; MetricFlow needs the cardinality in the semantic model; Cube's pre-aggregations must be built at the same grain or they reintroduce it.

Failure modes, detection, cost.

failuredetectioncost
fanout double countfixture test comparing metric to a hand-computed total; runs in CI in seconds82% overstatement above; every downstream dashboard and the finance close are wrong
SCD-2 grain driftcount(*) per natural key > 1 on the dimensioncounts inflate as history accumulates, silently
late data restating closed dayscompare the as-of snapshot for a closed period against currentnumbers already sent to finance change after sign-off
timezone mismatchdaily totals differ between UTC and local rolluporders near midnight land in the wrong day
policy only in the semantic layerrun the generated SQL as a low-privilege rolerow-level policy bypassed by direct table access

Trade-offs. dbt Semantic Layer/MetricFlow keeps definitions next to the models and versioned in git; Cube adds pre-aggregations and a query API but you now own cache invalidation; LookML is the strongest at fanout-safe aggregation but ties you to Looker's runtime. Pick by where your consumers already are.

What it can't do. Ambiguous fact grain, missing history, and bad source identity are upstream problems. The semantic layer makes them visible, a metric that fails its fixture test is telling you the model is wrong, but it won't repair them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design aggregate tables or materialized views for dashboard performance.

Answer

What I'd say first

Before designing anything I'd ask which dashboard queries are slow and how often they run: a rollup only pays off if the same shape is queried many times a day. Then I'd fix the grain and the freshness SLA, because that decides the refresh mechanism.

Assumptions: Postgres 16 warehouse, ~400M order rows over two years, dashboard p95 of 8 s scanning ~12 GB, refreshed every 5 minutes.

The design

Keep the atomic orders table as the source of truth. Build a daily rollup at (day, country, plan). 400M rows over 730 days is ~548k rows/day; at 200 countries × 5 plans the rollup is ~1,000 rows/day, ~730k rows and roughly 40 MB total. The dashboard scans 40 MB instead of 12 GB: that is the whole win.

Store additive components, not derived ratios: revenue_cents, order_count. Compute averages at read time as sum(revenue)/sum(count). Never store an average.

Why: averaging averages is wrong. Day 1 has 100 orders at avg 200 ms; day 2 has 10 orders at avg 500 ms. True mean = (100×200 + 10×500)/110 = 227 ms. Mean of the two averages = 350 ms: a 54% overstatement. Same trap with semi-additive balances: summing an account balance across days is meaningless; take the last value per account per day.

Refresh mechanism

Postgres materialized views only support full REFRESH MATERIALIZED VIEW, which re-runs the whole query: at 12 GB that is minutes, not seconds. For incremental refresh I'd use a plain table with an idempotent upsert:

SQL
INSERT INTO daily_revenue (day, country, plan, revenue_cents, order_count)
SELECT date_trunc('day', paid_at)::date, country, plan,
       sum(amount_cents), count(*)
FROM orders
WHERE paid_at >= DATE '2024-05-01' AND paid_at < DATE '2024-05-02'
GROUP BY 1, 2, 3
ON CONFLICT (day, country, plan) DO UPDATE
  SET revenue_cents = EXCLUDED.revenue_cents,
      order_count    = EXCLUDED.order_count;

Recomputing the whole day makes the write idempotent: a retry after a crash produces the same rows. Postgres 9.5+ supports ON CONFLICT; the unique index on (day, country, plan) is what makes it work.

Failure modes

  • Refresh falls behind: if a day's recompute takes 6 minutes and the scheduler fires every 5, the queue grows without bound. Detect by comparing max(day) in the rollup to now() - interval '15 minutes'; alert on lag, not on job exit code.
  • Late facts: if 3% of orders arrive more than 24 h after paid_at, a rollup that only refreshes yesterday silently undercounts. Fix by re-running a trailing 7-day window each cycle and tracking the max paid_at seen per day.
  • Dimension change: a country re-mapping (Type 2) invalidates every historical row for that key. Version the dimension and restate affected days.
  • Partial refresh: a failed batch leaves some days new and some old. Publish by swapping a version pointer, or wrap the batch in one transaction.

What would change the decision

If the dashboard needs sub-second freshness, a rollup is the wrong tool: query the atomic table with a covering index. If the engine is BigQuery or Snowflake, use their native materialized views with automatic incremental refresh instead of hand-rolled tables.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Choose partitioning, clustering, and sort design for a large fact table.

Answer

Core answer (first 90 seconds)

Assume a 1 TB/day append-mostly event fact table, queries filter on event_date and tenant_id, and join to a 200M-row user dimension. Default: partition by day on event_date, cluster/sort by tenant_id then user_id. Deviate only when measurements say so.

Partitioning is the coarse lever: it removes whole directories or manifests from the plan. Clustering is the fine lever: it narrows per-file min/max stats so the scan skips files inside a surviving partition. Distribution is a third, separate decision: it colocates join keys and controls skew. Conflating the three is the usual mistake.

Sizing arithmetic: 1 TB/day at 128 MB Parquet files is ~8,000 files/day. Partition by day and you have one partition holding 8,000 files; a "last 7 days for tenant 42" query scans 56,000 files. Z-order by tenant_id and each file's min/max covers roughly one tenant, so tenant 42 lands in ~2–5 files/day: call it ~20 files for the week instead of 56,000. Same query, three orders of magnitude fewer bytes. (Approximate: Z-order ranges overlap, so skipping is probabilistic, not exact.)

Why tiny partitions hurt

Pruning eliminates partitions, but every surviving partition costs at least one file and one task. At 8 MB/partition you get 120,000 partitions/day. The query touching one is cheap; the metadata is not. Hive metastore listing, Iceberg manifest entries and BigQuery partition metadata all scale with partition count, and BigQuery hard-caps at 10,000 partitions per table: past that, inserts fail outright. Task scheduling runs ~30–50 ms each, so 10,000 tasks is 5–8 minutes of overhead before a byte is read.

Engine specifics

EnginePartitionCluster / sortDefault file size
Hive/Spark + Parquetdirectory per valueDISTRIBUTE BY … SORT BY, or Delta OPTIMIZE … ZORDER BY128 MB (parquet.block.size)
Iceberghidden days(ts), bucket(N, id)sort order in table metadata512 MB (write.target-file-size-bytes)
BigQueryDATE/TIMESTAMP/INTEGER range, 10,000 partitions maxup to 4 clustering columns—
Snowflakeautomatic micro-partitions, 50–500 MB uncompressedCLUSTER BY—
Postgresdeclarative RANGE/LIST/HASHno clustering; use an index—

Failure modes, with the signal that detects them

  • Small-file explosion. Signal: file count > 10× core count and median file < 32 MB. Symptom: Spark reports 50,000 tasks for a 20 GB scan and p99 is scheduling-bound. Fix: compact to the engine's target size.
  • Skew. Signal: one partition holds >30% of rows; one task runs 10× the median duration. Fix: bucket the hot key or salt it.
  • Clustering decay. Signal: Snowflake SYSTEM$CLUSTERING_INFORMATION average_depth climbs from 1 to 5+ after bulk loads. Reclustering burns credits, so it is a cost decision, not a free fix.
  • Wrong column order. Cluster by (country, user_id) and a query filtering user_id alone gets no skipping: the leading column dominates the sort.
  • Over-partitioning. Signal: partition count grows monotonically with time; Postgres planning time grows with partition count, so keep it in the hundreds, not thousands.

Stage changes behind a rollback, and keep logical consumers reading event_date, not the physical partition column, so you can re-layout without breaking queries.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Choose a distribution strategy for a distributed warehouse star schema.

Answer

Assumptions. Redshift, 8 nodes. fact_sales 1B rows, dim_product 1M, dim_store 1k, dim_date 10k. The hottest join is fact_sales ⋈ dim_product on product_id, and product_id is near-uniform: no single value exceeds 0.1% of fact rows.

Answer. fact_sales gets DISTSTYLE KEY DISTKEY(product_id); dim_product gets DISTSTYLE KEY DISTKEY(product_id); dim_date and dim_store get DISTSTYLE ALL. The fact–product join is collocated: each node joins its local fact slice against its local product slice, and no rows cross the network. The two tiny dimensions are copied to all 8 nodes, so those joins are local too. Storage cost is 8 × (10k + 1k) rows: nothing. dim_product stays distributed, roughly 125k rows per node.

Why not AUTO. AUTO starts a table as EVEN (ALL if it is small) and may convert to KEY after it observes join patterns. For a fact table whose workload you already know, that is a guess you do not need to take; set DISTSTYLE explicitly.

How the join actually executes. Redshift has three options: collocated (both sides distributed on the join key. No movement), broadcast (the smaller side is copied to every node), and redistribute (both sides rehashed on the join key). The KEY/KEY pair buys you the collocated plan.

Skew is the failure mode. If one product_id were 10% of the fact, KEY sends all 100M of those rows to one node: that node holds 100M + 900M/8 = 212.5M rows, the other seven hold 112.5M. That is ~1.9× skew; the hot node becomes the join's critical path and can spill to disk. Detect it with SELECT skew_rows FROM SVV_TABLE_INFO WHERE tablename = 'fact_sales', or by watching per-node CPU and disk in the console.

The fix for skew is not "shuffle the fact." If you flip fact_sales to EVEN, the join can no longer be collocated, but Redshift will broadcast dim_product (1M rows to 8 nodes, about 8M row-copies moved) rather than redistribute the 1B-row fact. That is the cheap escape. The alternative is DISTSTYLE ALL on dim_product: every node then holds all products, so the join is local no matter how the fact is distributed. At 1M rows that is viable; at 5M+ the 8× storage and load-time cost makes it a liability, and you are back to KEY plus accepting the skew.

Two large dimensions. With dim_product (1M) and dim_customer (5M) both joined often, you cannot collocate the fact with both. Pick the join that moves the most data: if fact-to-customer is the more frequent or more selective, use DISTKEY(customer_id); the product join then broadcasts or redistributes. No configuration makes both free.

DDL.

SQL
CREATE TABLE fact_sales (
  sale_id BIGINT, product_id INT, date_id INT, store_id INT, amount DECIMAL(10,2)
) DISTSTYLE KEY DISTKEY (product_id) SORTKEY (date_id);

CREATE TABLE dim_product (
  product_id INT, name VARCHAR(100), category VARCHAR(50)
) DISTSTYLE KEY DISTKEY (product_id);

CREATE TABLE dim_date (date_id INT, date DATE, year INT) DISTSTYLE ALL;
CREATE TABLE dim_store (store_id INT, city VARCHAR(50)) DISTSTYLE ALL;

SORTKEY(date_id) on the fact is separate from distribution: it lets date-range predicates skip blocks.

Other engines. BigQuery has no distribution key: you partition and cluster. Snowflake uses clustering keys over micro-partitions. Same principle (make the expensive join local), different mechanism.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Diagnose and improve a slow warehouse query without changing its answer.

Answer

The 90-second answer

Assume a columnar warehouse (Snowflake, BigQuery, Redshift, or Spark/Databricks SQL) and that "same answer" means an identical result set, not a similar one. Before touching anything, make the query reproducible: pin the parameter set, disable result caching (ALTER SESSION SET USE_CACHED_RESULT = FALSE on Snowflake), and pull a plan with actuals. EXPLAIN (ANALYZE, BUFFERS) on Postgres, Query Profile on Snowflake, INFORMATION_SCHEMA.JOBS_BY_PROJECT (total_bytes_billed, total_slot_ms) on BigQuery, SVL_QUERY_REPORT on Redshift, the SQL tab in the Spark UI on Databricks.

Then split two problems that look alike. A semantic problem (fanout, a join that multiplies rows, a filter applied after aggregation) makes the query wrong, and tuning never fixes wrong. Check grain first: does the join key match the dimension's grain, and does the fact stay at one row per event? Only then tune the physical plan.

Mechanism

The optimizer plans from statistics, and statistics lie in predictable ways. Estimates drift when stats are stale, when predicates are correlated (city = 'Paris' AND country = 'France' is not the product of two selectivities), and when the engine assumes uniform distribution. A 10x estimate error on a join input flips a broadcast join into a shuffle join, or a hash join into a nested loop.

Redistribution causes spill because a shuffle writes every row to a partition chosen by the key hash, and one task processes each partition with a fixed memory budget. If a single key value holds 12% of rows, that partition is ~20x the median, exceeds the budget, and spills: the sort and the join both go through disk instead of RAM. Wall time is then set by that one task, not by total data volume.

Worked trace (illustrative figures)

SELECT u.country, sum(e.revenue) FROM events e JOIN users u ON e.user_id=u.user_id WHERE e.event_date >= '2024-01-01' GROUP BY 1

stagebeforeafter
scan events2.1 TB, no pruning180 GB (partition pruning on event_date)
shuffle200 partitions, max 21 GB, median 0.9 GBAQE coalesces to 64, skew split
spill18 GB to disk, one task 14 min0
wall time14 min 20 s1 min 05 s

The 21 GB partition is one synthetic account holding 12% of events. spark.sql.adaptive.skewJoin.enabled (default true since Spark 3.2) splits any partition above skewedPartitionThresholdInBytes (default 256 MB) and skewedPartitionFactor (default 5x median) into sub-partitions. When AQE can't help, skew in a non-join aggregation, salt the key or pre-aggregate to the join grain first.

Engine levers

enginepruninglayoutstats
Snowflakeclustering-key pruningALTER TABLE ... CLUSTER BY; micro-partitions 50–500 MB uncompressedSYSTEM$CLUSTERING_INFORMATION
BigQuerypartition + clusterCLUSTER BY; min 10 MB billed per tableINFORMATION_SCHEMA.JOBS_BY_PROJECT
Redshiftsort-key zone mapsDISTKEY/SORTKEY; VACUUM, ANALYZESVV_TABLE_INFO.skew_rows, STL_ALERT_EVENT_LOG
Spark/Deltapartition pruningOPTIMIZE ... ZORDER BY; target ~1 GB filesSpark UI, DESCRIBE DETAIL

Failure modes and verification

  • Skew: one task's duration far above the median in the Spark UI or Query Profile; detected by max/median partition bytes.
  • Spill: Snowflake "Bytes spilled to local storage" or Spark AQE metrics; detected by spill > 0.
  • Stale stats: estimated vs actual rows differ >10x at an operator.
  • Wrong answer: row count and a result checksum must match the baseline exactly, or within a stated tolerance for float sums.

Benchmark across typical and tail parameters plus concurrent load, not one warm-cache run. Stage behind a flag, keep rollback, and monitor p95/p99, bytes scanned, and spill after.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Manage small files and compaction in a lakehouse warehouse table.

Answer

Assume an Apache Iceberg 1.4.0 table on S3, written by Spark, with streaming and batch ingestion. The small-file problem is per-file overhead in planning and reading. Each data file is tracked in a manifest. A query plans by reading manifests, then opens data files. With 100,000 files of 1 MB, the manifest list and manifests can be hundreds of MB, and planning takes seconds to minutes. Reading 1 GB means 1,000 GET requests to S3, each with 10–50 ms latency, so 10–50 seconds just in open/close overhead. Compaction rewrites small files into larger ones, targeting 512 MB (Iceberg's write.target-file-size-bytes default). Delta Lake's delta.targetFileSize defaults to 100 MB, and Databricks' OPTIMIZE targets 1 GB.

Core answer: measure file size distribution per partition, manifest count, planning time, and query latency. Then run compaction on bounded partitions, not the whole table, using Iceberg's rewrite_data_files (default min-input-files is 5) or Delta's OPTIMIZE. Set target-file-size-bytes to 512 MB for Iceberg, or spark.databricks.delta.optimize.maxFileSize to 1 GB for Delta. Throttle compaction to avoid saturating the cluster or competing with live writes. Use optimistic concurrency: the compactor reads a snapshot, rewrites selected files, and commits only if the table's current snapshot is still the one it read. If a concurrent writer commits, the compactor's commit fails and it retries. This prevents it from deleting or replacing files that a writer just added.

Why does this work? Iceberg's commit protocol uses a compare-and-swap on table metadata. The compactor's commit includes the snapshot ID it started from. If metadata has advanced, the commit is rejected. The compactor re-reads the latest snapshot and retries. Delta Lake uses a similar optimistic concurrency model on the transaction log. The cost of a conflict is wasted rewrite work: you may have rewritten 10 GB only to throw it away. So compact partitions that are not actively being written, or coordinate with writers.

Trade-offs: Compaction reads and rewrites data, consuming I/O and CPU. If a partition is cold and rarely queried, compacting it may not be worth the cost. If files are already near target size, compaction yields little. Alternatives: write-time batching (e.g., spark.sql.files.maxRecordsPerFile or Delta's optimizeWrite) reduces small files at ingestion. Z-Order clustering improves data skipping without full compaction. When not to compact: under heavy write load where conflicts would be frequent, or when storage cost of small files is lower than compute cost of compaction.

Failure modes:

  • Concurrent writer commits during compaction: commit fails with CommitFailedException in Iceberg or ConcurrentModificationException in Delta. Detection: retry metrics, commit conflict rate. Cost: wasted rewrite I/O.
  • Two compactors on the same partition: both rewrite the same files. One commit succeeds, the other fails. If not handled, duplicate files or orphans. Detection: duplicate file paths in metadata, orphan file count. Cost: extra storage and I/O.
  • Compaction deletes files still referenced by old snapshots: if you expire snapshots before compaction commits, time travel breaks. Detection: query on old snapshot fails with "snapshot not found". Cost: loss of rollback.
  • Schema evolution during compaction: if compactor uses an old schema, it may write files with missing columns. Detection: read errors on new columns. Cost: data corruption.
  • Failure before commit: orphan files left in storage. Detection: orphan file cleanup job (e.g., Iceberg's remove_orphan_files). Cost: storage waste.

Artefacts:

SystemTarget file size defaultCompaction command
Iceberg 1.4.0512 MB (write.target-file-size-bytes)CALL catalog.system.rewrite_data_files(table => 'db.table', options => map('target-file-size-bytes','536870912'))
Delta Lake 2.4.0100 MB (delta.targetFileSize)OPTIMIZE db.table (Databricks: spark.databricks.delta.optimize.maxFileSize default 1 GB)
Hudi 0.14.0120 MB (hoodie.parquet.max.file.size)async compaction

Arithmetic: 1 TB in 1 MB files = 1,048,576 files. Assume each manifest entry is 100 bytes: ~100 MB of manifest data. Reading at 50 MB/s takes 2 seconds. Querying 1 GB scans 1,024 files. Assume 20 ms per file open: 20.5 seconds overhead. After compaction to 512 MB files, 1 GB is 2 files, overhead ~40 ms. That's a 500x reduction.

Trace of optimistic concurrency:

  • Compactor reads snapshot S1 with files A, B, C.
  • Compactor rewrites A, B, C into D.
  • Writer commits S2, adding E and deleting B.
  • Compactor tries to commit "replace A, B, C with D" based on S1.
  • Iceberg checks current snapshot is S2, not S1. Commit fails.
  • Compactor retries: reads S2, sees A, C, E (B gone). Rewrites A, C, E into D'. Commits.
  • Result: no data loss, extra work.

Monitor rewritten bytes, conflict/retry rate, file count per partition, planning time, total cost. Validate row counts and checksums before expiring old snapshots. Retain rollback for the approved period (e.g., 7 days). Test concurrent insert/delete, schema evolution, failure before commit, orphan cleanup, recovery.

Compaction changes physical layout, not logical grain or source truth.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Control cost in a cloud data warehouse without weakening correctness.

Answer

The 90-second version

Cost in a cloud warehouse is bytes scanned × compute time × concurrency, plus storage, plus the engineering time to keep the pipeline honest. Correctness is the constraint, not a variable you trade against. So the order is: attribute spend to a query or workload, find the dominant term, fix the query or the physical layout, and only then buy capacity. If a change would skip reconciliation, advance an offset past unprocessed data, cut recoverable history below your RPO, or silently drop late arrivals, it is not a cost optimisation: it is an outage you have not detected yet.

Where the money actually goes

Scan volume. In BigQuery on-demand you are billed per byte scanned, so a partition filter is literally the invoice. require_partition_filter = true on a partitioned table makes an unfiltered query fail instead of scanning 4 TB. In Snowflake you are billed for warehouse time, and pruning micro-partitions with a clustering key reduces the time a query holds the warehouse. Same lever, different meter.

Compute time. Snowflake warehouse sizes double in credits per hour: XS is 1 credit/hr, S is 2, M is 4, L is 8, XL is 16. Wall-clock does not halve when you double the size: it improves until the query stops being parallelisable, then you pay double for the same runtime. Right-size by measuring, not by habit.

Idle time. Auto-suspend defaults to 600 seconds. An XS warehouse that wakes for six ad-hoc queries a day, each leaving it idle for the full 10 minutes, burns an hour of credits doing nothing.

A worked example (hypothetical figures)

A nightly aggregate runs on a Medium warehouse (4 credits/hr) for 90 minutes: 6 credits. The query filters event_date >= current_date - 7, but the table is not clustered, so it scans the full history.

Change: cluster on (tenant_id, event_date) and add require_partition_filter. Runtime drops to 20 minutes: 1.33 credits. Saving ≈ 4.7 credits/night ≈ 140 credits/month. At a hypothetical $3/credit that is ~$420/month, and the query returns the same rows: verified by comparing row counts and a checksum against the pre-change output.

Second change: lower auto-suspend to 60 seconds. The six daily wake-ups now cost 6 × 1 min × 1 credit/hr = 0.1 credits instead of ~1 credit.

What breaks

  • Fanout. A join on a non-unique key multiplies rows and every downstream aggregate pays for it. Detect by comparing pre- and post-join row counts in INFORMATION_SCHEMA.QUERY_HISTORY (7-day retention) or ACCOUNT_USAGE (365 days).
  • Skew. One hot partition key sends most rows to one node. Detect in Redshift via STL_SCAN per-slice rows, or in Snowflake via micro-partition pruning statistics in the query profile.
  • Over-clustering. Too many clustering keys, or keys on small tables, cost reclustering credits and buy nothing. Clustering pays on large tables with selective filters.
  • Cache invalidation. Snowflake's result cache (24h) and warehouse cache are free, but any write to the underlying table invalidates them. A pipeline that writes every 5 minutes never gets a cache hit.

Guardrails, not heroics

Cap spend structurally: Snowflake resource monitors, BigQuery maximum_bytes_billed per query and custom quotas, Redshift WLM queues with concurrency-scaling limits. Separate interactive, transformation and backfill onto different warehouses so a backfill cannot starve the dashboard. Alert on anomalies with a named owner.

What you report

Cost per active decision, or per trustworthy row, or per SLA met, not the lowest bill. Re-benchmark p95/p99 query latency and a full load-and-recovery after every change, and include the write and maintenance cost of the change itself. A clustering key that saves 4 credits of query time and costs 6 credits of reclustering is a loss.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Implement useful warehouse lineage and impact analysis.

Answer

What I'd say in the first two minutes

Scope: "warehouse lineage" here means dataset- and column-level dependency edges between warehouse objects, plus the jobs and runs that produced them, across dev/staging/prod. Assumption: Airflow + dbt on Snowflake. If it's Dagster or Spark the emitter changes; the graph model doesn't.

Mechanism: events folded into a graph

Lineage is an append-only event log folded into a graph. Each job run emits an OpenLineage event naming its inputs and outputs; nodes are (namespace, name) pairs, edges are one per input→output pair, keyed by runId. A trimmed event from a dbt model task:

JSON
{
  "eventType": "COMPLETE",
  "eventTime": "2024-06-11T02:14:07.412Z",
  "run":  {"runId": "9f2c-..."},
  "job":  {"namespace": "dbt://prod", "name": "model.analytics.fct_orders"},
  "inputs":  [{"namespace": "snowflake://acct", "name": "ANALYTICS.PUBLIC.STG_ORDERS"}],
  "outputs": [{"namespace": "snowflake://acct", "name": "ANALYTICS.PUBLIC.FCT_ORDERS",
    "facets": {"columnLineage": {"fields": {
      "ORDER_ID": {"inputFields": [{"namespace": "snowflake://acct",
        "name": "ANALYTICS.PUBLIC.STG_ORDERS", "field": "ORDER_ID"}]}}}}}]
}

Folding it yields two nodes and one edge STG_ORDERS → FCT_ORDERS, attributed to runId 9f2c-…, job model.analytics.fct_orders, at 02:14:07Z. The columnLineage facet adds FCT_ORDERS.ORDER_ID ← STG_ORDERS.ORDER_ID.

Freshness propagates the same way: a table's data time is min(input data times) + job duration. Walk forward and a downstream table's freshness is bounded by its slowest path, which is why one stale upstream surfaces as a whole-subtree SLA miss, not one alert. Impact analysis is reverse BFS from the changed node; blast radius is the count of reachable downstream nodes, weighted by whether they're published marts or scratch tables.

Identity is the whole game

Namespace must encode environment. snowflake://acct for both dev and prod merges them into one node, and every dev change then looks like it breaks prod. Use snowflake://acct?env=prod or separate accounts. The Airflow OpenLineage provider's default namespace is default; set OPENLINEAGE_NAMESPACE per environment or you get exactly this collision.

Capture: three options

approachcoversmissescost
Event-based (OpenLineage from Airflow/dbt/Spark)orchestrated jobs, run state, dbt column lineagead-hoc SQL, manual COPY, BI extractsinstrument each engine
Parser-based (sqlglot over compiled SQL / manifest.json)anything with SQL text, incl. ad-hocdynamic SQL, EXECUTE IMMEDIATE, stored procs, uncompiled Jinjabuild and maintain a parser
Query-log (Snowflake ACCESS_HISTORY, DIRECT_OBJECTS_ACCESSED / BASE_OBJECTS_ACCESSED)ad-hoc and BI readsintent, job identity, column mappingvendor-specific, bounded retention

Deciding criterion: need cross-engine lineage → emit OpenLineage and land it in Marquez (OSS, Postgres-backed) or DataHub. dbt-only shop → dbt Cloud's column-level lineage is cheaper than building. Most shops run event-based as primary and query-log as a coverage backstop.

Failure modes and how you see them

  • Missing events: a task fails before emitting COMPLETE. Compare expected task instances from the orchestrator against received events. 1,200 dbt models × 1 daily run = 1,200 expected; 940 received = 78% coverage, and the 260 missing are your blind spot.
  • Rename: a renamed dbt model becomes a new node, old edges orphan, downstream impact is missed. Keep an alias map or key on dbt unique_id.
  • Retries: a new runId per attempt duplicates edges. Dedupe on (job, runId, eventTime).
  • Dynamic SQL: the parser returns zero edges silently. Alert on models that have inputs but no parsed column lineage.

What lineage does not prove

It shows how data is connected, not that values are correct, policies are enforced, or generated SQL does what you think. Pair it with data tests and access classification; a green lineage graph is not a green test suite.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Propagate privacy deletion through a dimensional warehouse.

Answer

Assumptions: The warehouse is Snowflake (or similar) with SCD2 dimensions, fact tables, bridge tables, materialized views, and downstream extracts. The request is a GDPR/CCPA erasure for a single data subject. You have 30 days to complete.

Core answer: The goal is to remove or irreversibly anonymize all data linked to the subject across history, derivatives, and backups, while keeping referential integrity and metric meaning intact. The key decision is hard delete vs. anonymize in place. For dimensions, you cannot simply delete the row if facts reference it: you either cascade delete facts (losing revenue history) or replace the dimension row with a "deleted" member that keeps the surrogate key but redacts PII. For facts, redact any direct identifiers. For aggregates, either recompute without the subject or document that the aggregate is not personally identifiable. For backups and time travel, you cannot delete from immutable storage; you rely on retention expiry and a deletion ledger that prevents restore from republishing the data. You must also propagate to caches, extracts, and downstream processors.

Worked example: Customer 12345 has 3 versions in dim_customer (SCD2), 500 rows in fact_orders, 2 rows in bridge_customer_segment, and 12 rows in agg_monthly_revenue. The deletion process:

  1. Capture surrogate keys: CREATE TEMP TABLE subject_keys AS SELECT sk FROM dim_customer WHERE cust_id = '12345'; (returns 3 rows: sk=100,101,102).
  2. Redact dimension: UPDATE dim_customer SET name='REDACTED', email='REDACTED', phone='REDACTED', cust_id='TOKEN_12345' WHERE sk IN (SELECT sk FROM subject_keys); This updates 3 rows. The surrogate keys remain, so fact joins still work.
  3. Redact facts: UPDATE fact_orders SET shipping_address='REDACTED' WHERE cust_sk IN (SELECT sk FROM subject_keys); This updates 500 rows.
  4. Redact bridge: UPDATE bridge_customer_segment SET segment_name='REDACTED' WHERE cust_sk IN (SELECT sk FROM subject_keys); This updates 2 rows.
  5. Recompute aggregates: DELETE FROM agg_monthly_revenue WHERE cust_sk IN (SELECT sk FROM subject_keys); then INSERT INTO agg_monthly_revenue SELECT ... FROM fact_orders ... This removes the subject's contribution. If you cannot recompute, you must document that the aggregate is not personally identifiable (e.g., it only contains total revenue per month, no customer-level data).
  6. Time travel: Snowflake's default Time Travel is 1 day (Standard) or up to 90 days (Enterprise). The old data is still queryable via AT (TIMESTAMP => ...). You must either wait 1 day or set DATA_RETENTION_TIME_IN_DAYS = 0 (which only affects future changes) and then wait for the existing retention to expire. BigQuery's time travel window is 7 days. So you record the deletion timestamp in a ledger.
  7. Backups: Snowflake failsafe is 7 days (non-configurable). You cannot delete from failsafe. You rely on the ledger: if a restore occurs, you re-apply the deletion before the restored data is made available.
  8. Downstream: Send deletion requests to extracts, caches, and processors. Collect acknowledgements.

Failure modes: Forgetting to refresh a materialized view that joins fact and dimension. The view still returns the old PII. Detection: query the view for the subject's email. Forgetting to update a cache (e.g., Redis) that holds the customer profile. Detection: check cache keys. Restoring from a backup without re-applying the ledger: the subject reappears. Detection: run a post-restore validation query. Merged identities: if customer 12345 was merged into 67890, you must delete both. Detection: check the merge history table.

Why a deleted dimension member preserves metric comparability: because the surrogate key remains, the fact rows still join, so total revenue for a month doesn't change. If you hard-deleted the dimension row, you'd have to either delete the facts (revenue drops) or leave them orphaned (joins fail). So the trade-off is privacy vs. metric integrity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Secure a multi-tenant analytical warehouse and semantic layer.

Answer

I’d clarify two assumptions first: tenants share a warehouse (Snowflake or BigQuery) and a semantic layer (Looker or dbt) generates SQL; some tenants are regulated. The core answer is that tenant identity is a data attribute bound at ingestion, not a dashboard filter. Every fact row carries an immutable tenant_id; every dimension key is tenant-scoped or composite (tenant_id, natural_key); every partition or cluster key leads with tenant_id. Then choose isolation by blast radius and regulation.

IsolationUse whenCost/opsDon’t use when
Separate account/database per tenantFew large or regulated tenants; noisy-neighbor containmentHighest isolation, highest opsThousands of small tenants
Schema/table per tenantMedium tenants; per-tenant retentionModerateCross-tenant joins are required
Row-level policyMany small tenants; shared schemaLowest cost, highest misconfiguration riskTenant can run arbitrary SQL against raw tables

Row-level isolation works because Snowflake row access policies and BigQuery row-level security attach a predicate to the table. BigQuery example:

SQL
CREATE ROW ACCESS POLICY tenant_filter
ON analytics.orders
GRANT TO ("group:tenant_a@example.com")
FILTER USING (tenant_id = "tenant_a");

If tenant_id is the partition or cluster key, BigQuery and Snowflake prune before scanning. On a 10B-row fact table, a 0.5% tenant scans roughly 50M rows; without that key, the filter is applied after scanning all 10B. That is the performance and safety difference.

The semantic layer is where leaks usually happen. Looker access_filters inject WHERE tenant_id = '{{ _user_attributes['tenant_id'] }}' into generated SQL. dbt macros can add predicates in models, but dbt is batch; it does not protect direct queries. Caches leak because the cache key often omits the tenant or user attribute: tenant A runs a dashboard, tenant B gets A’s cached result. Fix by including tenant_id and purpose in the cache key, or disable shared cache for tenant-scoped explores. Tableau extracts are worse: an extract can contain all tenants, so use user filters and per-tenant extracts.

For sensitive attributes, use Snowflake dynamic data masking, BigQuery policy tags, or Databricks column masks. Tokenize PII at ingestion; keep raw data in a separate account with break-glass. Restrict time travel, unload/export, and clone. Use customer-managed keys where the platform supports per-tenant keys.

Failure modes and how to detect them: missing tenant predicate, query audit flags any fact-table query without tenant_id; wrong tenant, canary row per tenant; crafted join, test joining a shared dimension on a surrogate key; shared cache, run the same dashboard as two tenants and compare row counts; inference through aggregates. Suppress counts below 5 and alert on repeated near-identical filters; support access, break-glass with ticket and session recording; copied table, scan for tables lacking tenant_id; restore, restore into an isolated schema and reapply policies; unload, block or watermark; ownership transfer. Re-run entitlement review.

Audit grants, reads, exports, policy changes, and break-glass. Test all of the above. Provide tenant-scoped deletion evidence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Migrate operational reporting tables into a governed warehouse model.

Answer

The 90-second answer

I'd run this as a data-contract migration, not a table copy. First question: how many reports, who consumes them, and what's the cutover tolerance. Can a report be stale for an hour, or does finance need it bit-identical? Assumption I'd state out loud: the operational database stays the system of record for transactions, the warehouse becomes the system of record for reporting, and after cutover no report reads both.

Then the shape: inventory the existing SQL as evidence rather than truth, build the target model in parallel, replay history, reconcile report-by-report, shadow consumers, and only then decommission direct operational queries.

Inventory

Pull every query hitting the operational tables from pg_stat_statements (or the warehouse's query history if reports already run there). For each, record the grain it returns, its joins, the implicit filters (a WHERE status != 'deleted' buried in a view), the timezone it assumes, and its owner. In my experience 30–50% of these are duplicates or dead: a report nobody has opened in 90 days is a decommission candidate, not a migration candidate.

Target model

Decide grain first. A worked example:

source reporttarget fact graindimension policy
daily order totalsone row per order line per daycustomer SCD2, product SCD1
open ticketsone row per ticket per status changeagent SCD2

SCD2 on customer because "revenue by region" must reflect the region at order time; SCD1 on product because nobody asks historical product names. Write that decision down rather than discover it later.

Timezone: store UTC (TIMESTAMP_TZ in Snowflake, TIMESTAMP in BigQuery) and convert at the semantic layer, not in each report. Most "the numbers don't match" tickets come from here.

Extraction

CDC via Debezium reading Postgres WAL (wal_level=logical), landing raw and immutable, then dbt models on top. Snapshots for tables without a reliable updated_at. Every load writes a row count and a checksum into a reconciliation table.

Reconciliation

For each report, compare old vs new by population and by metric:

SQL
select coalesce(o.order_date, n.order_date) as d,
       o.revenue as old_rev, n.revenue as new_rev
from legacy_daily o
full outer join warehouse_daily n using (order_date)
where o.revenue is distinct from n.revenue;

Every row this returns needs an explanation: usually a corrected filter or a timezone fix. Unexplained diffs block cutover.

Cutover

Shadow both paths for two weeks, comparing freshness and p99. Then canary consumers, keep compatibility views with a deprecation date, and never let two definitions be authoritative at once. Decommission direct operational queries only after equivalence is stable, access is migrated, and the owner signs off.

Curated: · Written: · Reviewed:

Difficulty: Hard