Skip to content
Tech Interview Prep
Technical interview guide

ETL for Reporting

The lighter-weight, reporting-focused data prep that sits between raw warehouse tables and a BI tool.

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

Scope: Current dbt, Google Dataform and BigQuery, Snowflake streams/tasks, Apache Airflow, Apache Iceberg, and OpenLineage guidance reviewed 2026-09-04.

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-25

When would you keep transformation before the load (classic ETL) for a reporting pipeline instead of loading raw and transforming in the warehouse (ELT), and what does that choice change about the pipeline's design, its reprocessing story, and the freshness the report can promise?

Answer

Start by naming the two things that decide it: where the raw data is allowed to land, and whether the source can be replayed. Classic ETL wins when either the raw data must not exist in the warehouse (PII, residency, contractual) or the source volume is so much larger than the useful slice that retaining raw is the dominant cost. ELT wins by default when raw retention is cheap and the warehouse is the cheapest place to transform, because it keeps the raw layer as the replay log.

Assumptions I'd state: batch reporting, source is a transactional DB or event stream, warehouse is BigQuery/Snowflake-class, and the report has a daily or hourly SLA.

Design changes. ETL adds a transform tier between source and warehouse: Spark/Flink job, source-side SQL, or a stream processor. That tier owns state, retries, and schema handling; the warehouse load becomes a dumb, fast writer (COPY/INSERT). Orchestration splits: Airflow now has a pre-load task with its own sensors and retries, and lineage must cover it. OpenLineage events from the transform job, not just the dbt models downstream. ELT collapses that: one load, then dbt incremental models, Snowflake tasks, or BigQuery materialized views transform in place.

Reprocessing. This is the real cost. ETL reprocessing requires the source to be replayable: Kafka retention, a CDC log, or source snapshots. If the source only keeps 7 days and you find a transform bug on day 30, you cannot rebuild the report without a full re-extract, and often you can't. ELT reprocessing is a re-run of the model over retained raw history. So a hybrid, transform before load but also land raw, is just ELT with extra steps and double storage.

Freshness. ETL can promise a lower floor because the loaded table is already report-ready: one publish step, no post-load transform window. But end-to-end freshness is bounded by the slowest stage, and the transform tier is a stage you own and must scale. ELT's freshness is bounded by load + transform; a dbt incremental model over 200 GB might add 10-20 minutes, while a BigQuery materialized view can be near-real-time within its staleness limit. The ETL promise is easier to state and harder to improve.

dimensionETL (transform before load)ELT (load raw, transform in warehouse)
where transform runsSpark/Flink/source SQLdbt, Snowflake tasks, BigQuery MV
warehouse loaddumb writer, already cleanraw append, schema-on-read
reprocessingneeds source replay (Kafka/CDC/snapshot)re-run model over retained raw
freshness floorone publish step, no post-load windowload + transform window
cost shapetransform compute outside warehouse; less storagewarehouse compute + raw storage
lineagemust cover pre-load jobdbt/warehouse-native

Arithmetic, illustrative: 40 TB/day raw clickstream, 0.5% useful = 200 GB/day. 90-day raw retention at ~$20/TB-month = 3,600 TB * $20 = $72k/month storage alone; transformed-only is 18 TB = $360/month. That gap is the whole argument for ETL, until you need to reprocess and the raw is gone.

Failure modes. Transform bug corrupts the loaded table and raw is gone → unrecoverable; detect with source-to-output control totals and keep a raw landing zone. Transform tier backpressure → source lag; alert on queue depth and job lag. Schema drift breaks the transform before load, so the warehouse never sees the new column; contract tests in the transform job. Cost moves outside the warehouse budget; tag jobs and track cost per pipeline.

Decision rule: default ELT; choose ETL when raw cannot land or raw retention cost exceeds the reprocessing risk you're accepting. If you choose ETL, keep a raw landing zone anyway unless regulation forbids it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Implement an idempotent daily reporting load.

Answer

Assumptions. Daily batch. Source ledger is append-mostly with report_date and updated_at; late rows can land up to 3 days after their date. Target report_daily is partitioned by report_date. The scheduler (Airflow, or any at-least-once runner) can execute the same logical date twice. Contract: for a given report_date, the partition must equal the deterministic aggregate of all source rows for that date as of the run's snapshot.

Core answer. Idempotency here is not "don't run twice": it's "running twice produces the same partition." Two things buy that: a deterministic key (the business date, never now() or a run id), and a partition-scoped atomic replace. Then the checkpoint is written in the same transaction as the data, so "data committed" and "checkpoint advanced" are one event.

SQL
-- Postgres 16
BEGIN;
DELETE FROM report_daily WHERE report_date = DATE '2024-06-01';
INSERT INTO report_daily (report_date, account_id, gross_cents, net_cents)
SELECT DATE '2024-06-01', account_id, sum(gross_cents), sum(net_cents)
FROM   ledger
WHERE  report_date = DATE '2024-06-01'
GROUP  BY account_id;

INSERT INTO load_audit (report_date, source_snapshot_ts, row_count, checksum)
VALUES (DATE '2024-06-01', now(), 12431, :checksum)
ON CONFLICT (report_date) DO UPDATE
  SET source_snapshot_ts = EXCLUDED.source_snapshot_ts,
      row_count = EXCLUDED.row_count,
      checksum = EXCLUDED.checksum;
COMMIT;

:checksum is md5(string_agg(account_id || ':' || gross_cents || ':' || net_cents, ',' ORDER BY account_id)) over the inserted rows. load_audit has UNIQUE(report_date). That one constraint does two jobs: it makes the audit row an upsert (rerun-safe), and it makes a concurrent second run for the same date fail on the insert rather than double-write.

Trace. Run 1: DELETE 0 rows, INSERT 12,431 rows, upsert audit, COMMIT. The scheduler loses the ack and retries. Run 2: DELETE 12,431 rows, INSERT 12,431 rows with the same checksum, upsert audit to the same values, COMMIT. Target checksum is unchanged. If instead the checkpoint were a separate UPDATE after COMMIT, a crash in between leaves data present and checkpoint stale: the next run redoes the work, harmless. The reverse ordering, checkpoint first, leaves the date marked done with no data, and nothing ever reprocesses it.

Merge vs replace.

partition replace (DELETE+INSERT in one txn)keyed MERGE/upsert
rerun costrewrites the whole partitiontouches only changed keys
source deleteshandled: deleted rows vanishmissed unless you also delete
reader visibilityold partition or new, never partialcan see a mix of old and new keys
use whendaily partition, source can delete rowslarge partition, insert/update only

Replace is the default for a daily report; MERGE only when the partition is too big to rewrite and the source never deletes.

Failure modes.

  • Checkpoint outside the data transaction, ordered checkpoint-first → silent data loss. Detect: a load_audit row for a date with no matching partition rows; alert on that join.
  • Non-deterministic key → rerun appends. Detect: row count grows across identical snapshots, or checksum differs for the same source_snapshot_ts.
  • Late source rows after publish → stale partition. Detect: max(ledger.updated_at) > load_audit.source_snapshot_ts for an already-loaded date. Cost: dashboards wrong until backfill.
  • Concurrent runs → lock waits on the partition. Detect: pg_locks waits, or the load_audit unique violation failing the second run fast.

Cost. Illustrative: 40M source rows/day aggregating to 12k accounts is ~40 s of scan+aggregate on a 16-vCPU Postgres; the 12k-row partition rewrite is ~15 ms. A 90-day backfill is ~1 hour sequential, or ~10 minutes at 6-way parallelism if each date is independent.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Choose append, merge, delete-insert, or partition replacement.

Answer

Core answer

The choice falls out of two questions: does the source tell you which rows changed and which disappeared, and can you bound the write to whole partitions?

  • Source is immutable events, no updates or deletes → append. Cheapest write, no target read.
  • Source is keyed CDC with updates and deletes → MERGE on the key.
  • You can enumerate the affected key set, but the source emits no tombstones → delete-insert.
  • The change is confined to partitions you can rebuild completely → partition replacement (INSERT OVERWRITE).

Assumptions: target is Iceberg or Delta on object storage, or Snowflake/BigQuery; keys are stable; you have a change timestamp or a CDC stream.

Why each behaves the way it does

Append writes new files and never reads the target. That is why it is cheap, and why it cannot dedupe or update: uniqueness is the writer's problem, not the table's.

MERGE reads the target files that overlap the source keys and rewrites them. Cost is file-granular, not row-granular: Iceberg's default target file size is 512 MB (write.target-file-size-bytes). A MERGE touching 5% of rows scattered across 10,000 files rewrites all 10,000 files. It commits once, but two concurrent MERGEs on overlapping files conflict: Iceberg raises CommitFailedException, Delta raises ConcurrentModificationException.

Delete-insert is two statements. Between the DELETE and the INSERT, readers see the rows missing. It is atomic only if you wrap both in one transaction, which most lakehouse writers do not.

Partition replacement is a metadata swap: the commit drops the old partition's file list and adds the new one. Readers see the old snapshot or the new one, never a gap, and the writer never reads the target to find matching rows. That is the atomicity delete-insert lacks, and the reason it is the default for daily rebuilds.

StrategyReads target?Handles deletesAtomicCost driver
AppendNoNoYes, per commitWrite volume
MERGEYes, matched filesYesYes, but conflictsFiles touched
Delete-insertYes, by keyYesNo, unless transactionalKey set size
Partition replaceNoYes, within partitionYesPartition size

Failure modes and how you catch them

  • Append duplicates. A retried job writes the same event ids twice. Detect with SELECT event_id, count(*) FROM t GROUP BY 1 HAVING count(*) > 1. Downstream sums double-count.
  • MERGE with multiple source rows per key. Spark fails the write: "Cannot perform Merge as multiple source rows matched and attempted to modify the same target row." Dedupe the source first with row_number() over (partition by key order by updated_at desc).
  • Delete-insert gap. A reader between the two statements sees missing rows. Catch it with a concurrent count; fix by folding the delete into a MERGE condition or a single transaction.
  • Partition replacement with late data. One late event for a closed month forces rewriting the whole month. If that partition is 200 GB, one row costs 200 GB of write. Watch write amplification per commit; fix with finer partitions or a separate late-arrivals table.
  • Schema evolution. A new column added to an append-only table leaves old files without it; readers get nulls. Delta needs mergeSchema=true on the write; Iceberg's ALTER TABLE ... ADD COLUMN is metadata-only.

What changes the decision

If the source has no tombstones, MERGE cannot delete: you are on delete-insert or partition replacement. If partitions are too coarse, replacement cost explodes and you want MERGE with partition pruning. If the target is small enough that a full rebuild takes minutes, replace everything and skip the incremental logic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Choose keys and deduplication for a report fact.

Answer

Assume the fact is fct_order_line: one row per (tenant_id, order_line_id) for the current version, fed by Debezium CDC from Postgres through Kafka into Snowflake. The grain is the contract: the key must be unique at that grain and identical across replays. My default is a surrogate hash key over the natural key, with dedup at ingest and a deterministic winner. Here is the reasoning.

Key choice. Three candidates, and the deciding question is whether the source guarantees the business key is immutable.

optionstable across retrieswidthbreaks when
identity/sequenceno8 Bany reload renumbers rows
composite natural (tenant_id, order_line_id)yes~44 Bsource rekeys the line
hash surrogate sha2(tenant_id || '|' || order_line_id)yes32 Bsource rekeys; missing delimiter collides

If the source guarantees order_line_id never changes, take the hash surrogate: 32 B joins beat 44 B string joins, and it survives a full reload. If the key can be reassigned, keep a rekey mapping table keyed on the old value, or you will silently double-count. Never use a sequence: a backfill renumbers it and every downstream join breaks.

Where to dedup. Ingest-time MERGE versus query-time QUALIFY. At 180M order-line events/day with ~12% CDC retry duplicates, that is ~21.6M dupes/day. Ingest dedup costs one ~6-minute merge and leaves the table clean. Query-time dedup adds a full sort to every read, roughly 40 s and a full scan on 180M rows, and you pay it on each query. Dedup at ingest unless the raw table is the audit record of truth.

Deterministic winner. Order by source LSN, then ingest sequence, not ingestion timestamp, because a Kafka replay can land an older event later.

SQL
merge into fct_order_line t
using (
  select *
  from raw_order_line
  qualify row_number() over (
    partition by tenant_id, order_line_id
    order by source_lsn desc, _ingest_seq desc
  ) = 1
) s
on t.tenant_id = s.tenant_id and t.order_line_id = s.order_line_id
when matched and s.source_lsn > t.source_lsn then update set ...
when not matched then insert ...;

Trace: tenant A, line 77 arrives twice. LSN 5/16 ingested at 10:00, then LSN 5/12 ingested at 10:05 after a replay. row_number orders by LSN descending, so 5/16 wins despite arriving first. Ordering by _ingest_ts would have picked 5/12 and regressed the row.

Failure modes and detection.

  • Null tenant_id: NULL || '|' || id collapses every null-tenant row to one key. Detect with count(*) where tenant_id is null; expect 0. Cost: unrelated rows merged.
  • Delimiter collision: 'ab'||'c' and 'a'||'bc' hash the same. Detect by grouping on the hash and asserting count(distinct concat) = 1.
  • Rekey: source reassigns order_line_id, producing duplicate facts. Detect by comparing fact row count to source count per day.
  • Cross-tenant sameness: the same order_line_id in two tenants. The composite key handles it; a hash without tenant_id does not.

One source event can legitimately produce several target rows (a split shipment). That is not a duplicate: dedup on the event key, not the fact key, or you will delete real rows.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Build a Type 2 dimension incrementally.

Answer

Assume the source gives you a durable business key (customer_id), a change timestamp (updated_at), and a set of tracked attributes, and that you can run a merge on a schedule or from CDC. The answer: keep one row per version, close the current row and insert the new one in the same transaction, and join facts on the business key plus event time against a half-open interval.

In Postgres 16 (needs CREATE EXTENSION btree_gist; for the equality operator in a GiST index):

SQL
CREATE TABLE dim_customer (
  customer_sk    BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id    TEXT        NOT NULL,
  name           TEXT,
  tier           TEXT,
  row_hash       BYTEA       NOT NULL,
  effective_from TIMESTAMPTZ NOT NULL,
  effective_to   TIMESTAMPTZ NOT NULL DEFAULT '9999-12-31 00:00:00+00',
  is_current     BOOLEAN     NOT NULL,
  EXCLUDE USING gist (
    customer_id WITH =,
    tstzrange(effective_from, effective_to, '[)') WITH &&
  )
);

The EXCLUDE constraint is the point: overlapping intervals become a database error, not a report you find a week later. Half-open [from, to) means a boundary timestamp belongs to exactly one row.

Load, assuming stage is deduped to the latest row per customer_id:

SQL
BEGIN;
UPDATE dim_customer d
SET effective_to = s.updated_at, is_current = FALSE
FROM stage_customer s
WHERE d.customer_id = s.customer_id
  AND d.is_current
  AND d.row_hash IS DISTINCT FROM s.row_hash;

INSERT INTO dim_customer (customer_id, name, tier, row_hash,
                          effective_from, effective_to, is_current)
SELECT s.customer_id, s.name, s.tier, s.row_hash,
       s.updated_at, '9999-12-31 00:00:00+00', TRUE
FROM stage_customer s
WHERE NOT EXISTS (
  SELECT 1 FROM dim_customer d
  WHERE d.customer_id = s.customer_id AND d.is_current
);
COMMIT;

Why hash instead of updated_at? A source updated_at moves on touch updates that change nothing you track, and a backfill can rewrite it. A digest of the tracked columns (sha256(name || '|' || coalesce(tier,''))) changes only when a tracked value changes. Use IS DISTINCT FROM so NULL→'gold' counts as a change; <> silently misses it. SHA-256 collisions are not a practical concern; the cost is reading the tracked columns per row, which is fine at dimension scale.

Trace. Start:

skcustomer_idnametierhashfromtocurrent
1C-100Adasilverh12024-01-019999-12-31true

Stage: C-100, Ada Lovelace, gold, h2, 2024-03-15. After the transaction:

| 1 | C-100 | Ada | silver | h1 | 2024-01-01 | 2024-03-15 | false | | 2 | C-100 | Ada Lovelace | gold | h2 | 2024-03-15 | 9999-12-31 | true |

A fact order at 2024-02-10 joins to silver; at 2024-04-01, gold.

Trade-offs. Type 1 overwrites and loses history. Type 3 keeps only the previous value in a column: cheap, but you cannot answer "as of last March" more than one step back. Type 4 splits history into a separate table, right when the dimension is wide and history is rarely queried. Type 6 adds a current-value column to every row so you can filter without a self-join. Bitemporal adds transaction time on top of valid time; you need it when a correction restates the past ("tier was gold from January, we learned in March"). Plain Type 2 cannot represent that without rewriting intervals. And Type 2 is the wrong tool for fast-changing attributes like account balance: those belong in a fact or periodic snapshot.

Failure modes. Non-atomic close+insert gives two current rows or a gap; detect with SELECT customer_id FROM dim_customer WHERE is_current GROUP BY 1 HAVING count(*) > 1 and a gap check on lag(effective_to). A late correction that inserts a past-dated row trips the EXCLUDE constraint unless you split the existing interval first. Delete/restore: close the row and insert a tombstone with a deleted flag, then a new version on restore. Same-timestamp changes need a tiebreaker (source sequence number) or they collapse into one version.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design an incremental extraction watermark.

Answer

What I'd say first

Assume the source is an OLTP table with an updated_at column and a stable primary key, and the target is a warehouse table we can upsert into. The watermark is a pair, (updated_at, id), not a single timestamp, because timestamps tie and a single-column bound silently drops rows that share the boundary value.

The loop: capture a ceiling, read the half-open range below it, publish, then persist the watermark. Persist only after the target commit succeeds. Advance the watermark before the data lands and a crash loses the batch permanently.

Why a naive timestamp watermark misses rows

The hole is commit order, not insert order. A transaction can write updated_at = 09:59:59 and commit at 10:00:03, after your 10:00:00 read finished. Its row sits below your ceiling, so the next run, which starts at the ceiling, never sees it. Overlap closes this: the next run's lower bound is previous_ceiling - overlap, so it re-reads a trailing window and catches late commits. Dedup by business key makes the re-read harmless.

The read

SQL
-- Postgres 16. Half-open on the tuple; ceiling captured before the read.
SELECT id, business_key, updated_at, version
FROM orders
WHERE (updated_at, id) > (:wm_ts, :wm_id)           -- exclusive lower
  AND (updated_at, id) <= (:ceiling_ts, :ceiling_id) -- inclusive upper
ORDER BY updated_at, id
LIMIT 10000;

Ceiling: SELECT updated_at, id FROM orders ORDER BY updated_at DESC, id DESC LIMIT 1; captured in its own statement before the read. Next run's lower bound is (ceiling_ts - interval '5 minutes', ceiling_id): the overlap.

Trace

  • Run 1, 10:00:00: ceiling = (10:00:00, 500). Reads and publishes rows up to id 500. Watermark saved as (10:00:00, 500).
  • Transaction T began 09:59:58, inserted id 498 with updated_at = 09:59:59, commits 10:00:03. Run 1 missed it.
  • Run 2, 10:05:00: lower bound = 10:00:00 − 5 min = 09:55:00. The scan picks up id 498. Upsert on business_key overwrites the rows run 1 already loaded: no duplicates.

Choosing the column

columnmonotonic in commit order?sees hard deleteslate-commit risk
auto-increment idno: assigned at insert, not commitnohigh
commit LSN / WAL positionyesyes, via CDC tombstonelow
updated_at, DB clockno: ties, skewnomedium
updated_at, app clockno: skew across hostsnohigh

If the source offers a commit LSN (Postgres logical replication, Debezium), watermark on that: it's commit-ordered, so overlap can shrink to seconds. Timestamps are the fallback when you only have read access to a table.

Sizing the overlap

Size it to the max transaction duration, not p99. If p99 is 2s but a nightly batch holds a transaction for 90s, a 5-minute window covers it. Cost: at 200 changed rows/s, a 5-minute overlap re-reads ~60k rows per run, all deduped. Overlap buys correctness; dedup pays for it.

Failure modes and detection

  • Late commit below the ceiling: detected by a nightly reconciliation. COUNT(*) and a checksum of business_key per day compared against source. An overlap sized too small shows up as a nonzero diff.
  • Clock skew on app-written updated_at: rows land in the past. Detect by monitoring max(updated_at) - now(); fix by writing now() from the DB, not the app host.
  • Hard deletes: invisible to any timestamp watermark. Detect by row-count drift; handle with soft delete (deleted_at) or CDC tombstones.
  • Rekeys: a business key change looks like delete+insert. Detect via a key that no longer matches; carry a stable surrogate key or emit both events.
  • Empty run: don't regress the watermark to NULL. Advance to the captured ceiling so you don't rescan; the overlap still covers late commits.
  • Retry: safe only because the target upsert is idempotent. If it isn't, a retry after a partial publish duplicates rows.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Use change data capture for reporting models.

Answer

Assumptions first. Reporting model = a warehouse table (Snowflake/BigQuery/Postgres) that analysts query; source = Postgres OLTP; freshness target = minutes, not seconds; the reporting table is current-state plus an append-only history, not full SCD2 versioning.

The 90-second answer. Run Debezium's Postgres connector against a logical replication slot (wal_level=logical, plugin=pgoutput), land change events in Kafka keyed by primary key, and have the sink merge them into the reporting table on that same key. The merge is idempotent and guarded by the source LSN, so replays are free. Deletes must be handled explicitly: an upsert-only sink silently keeps deleted rows. Commit the consumer offset only after the target transaction commits; that gives at-least-once delivery with idempotent apply, the only combination that survives a crash between the two.

Why keyed by primary key. Kafka orders within a partition, and Debezium's default key is the row's primary key, so every change to order 42 lands in one partition and arrives in commit order. That is the whole ordering story: no global ordering, and you don't need it.

Worked trace. One row, orders.id=42, REPLICA IDENTITY DEFAULT:

eventoppayloadtarget row 42 after merge
1cafter={42, NEW, 100}42 NEW 100
2uafter={42, PAID, 100}42 PAID 100
3uafter={42, SHIPPED, 100}42 SHIPPED 100
4dbefore={42}row deleted
5cafter={42, NEW, 250}42 NEW 250

Two things fall out. Under REPLICA IDENTITY DEFAULT the delete carries only the key, so the sink must delete by key: you cannot filter deletes on status. And the reinsert is a plain insert with a new LSN; a sink that only upserts never removes the row, so the reporting model shows SHIPPED forever while the source says NEW. That is the most common CDC-to-reporting bug.

Alternatives and when to pick them.

approachfreshnesscostpick when
nightly batch extracthoursfull scan on primary, cheap infraanalysts tolerate overnight data
dual writes from the appsecondsno atomicity with the DB txn, drift on partial failurenever for money or inventory
periodic full snapshot rebuildhours200 GB table → 200 GB read + load per runsmall tables, or as the resnapshot path
CDC (Debezium + Kafka)seconds–minutesslot WAL retention, connector opsfreshness matters and full scans are too expensive

Deciding criterion: if the reporting model tolerates hours of staleness, batch is cheaper and has no slot to babysit. CDC buys freshness at the price of a replication slot that can fill your primary's disk.

Failure modes, detection, cost.

  • Slot retention. An inactive slot pins WAL. Alert when pg_current_wal_lsn() - confirmed_flush_lsn exceeds 50 GB; set max_slot_wal_keep_size (Postgres 13+) so a runaway slot invalidates instead of filling the disk. Cost: a full resnapshot, primary stays up.
  • Snapshot WAL. snapshot.mode=initial holds WAL for the whole snapshot. A 200 GB table taking 30 minutes to snapshot is 30 minutes of WAL you must have room for.
  • Lag. Debezium's MilliSecondsBehindSource JMX metric plus consumer-group lag. Page at > 300,000 ms sustained 10 minutes (hypothetical threshold: set yours from the freshness SLA).
  • Long transactions. One open txn holds the slot's LSN; every consumer stalls behind it. Detect via max transaction age in pg_stat_activity; cost is unbounded lag.
  • Schema change. A column add is fine; a type change or rename needs a connector restart and a sink DDL change. Detect by diffing the schema history topic against the target DDL.
  • Consumer outage. Offsets don't advance, the slot grows. Detect via consumer lag; cost is the WAL above.

Resnapshot path. Keep snapshot.mode=schema_only_recovery or a full initial re-run as a documented runbook, and make the sink's merge idempotent so a re-snapshot is safe to replay over live data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Handle deletes in incremental reporting ETL.

Answer

Core answer

Assume the source is an operational database and the target is a warehouse with current-state dimensions, SCD2 history, and fact tables. The thing that decides everything: a delete leaves no row behind, so any pipeline that pulls WHERE updated_at > :watermark will never see it. Row counts drift down silently and nobody notices until a dashboard is wrong. So the first question is not "how do I delete" but "how do I learn a delete happened."

If the source is a database you control, turn on log-based CDC. Postgres with wal_level=logical and a replication slot, MySQL with binlog_format=ROW; Debezium reads the WAL/binlog and emits an event with op: "d" and a before image carrying the old key. That is the only mechanism that gives you hard deletes at low latency without scanning the source. If you can't get log access (a SaaS API, a vendor feed) you fall back to reconciliation: pull the full key set and anti-join against the target. That's O(N) per run. Illustratively, at ~50k rows/s a 200k-row dimension reconciles in ~4s; a 2B-row fact table takes ~11 hours, which is why you don't do it per run.

What the delete event looks like

Debezium emits two records per delete: the delete event, then a tombstone with a null value.

JSON
{"op":"d","before":{"id":42,"updated_at":"2024-05-01T10:00:00Z"},"after":null}
null

The tombstone matters: on a compacted Kafka topic (cleanup.policy=compact), the null value is what lets the broker actually drop the key. If your consumer filters out nulls, the key survives compaction and the row resurrects on the next replay.

Per-target handling

targetactionwhy
current-state dimMERGE ... WHEN MATCHED THEN DELETE, or set is_deleted=truerow must stop appearing
SCD2 historyclose validity: valid_to=delete_ts, is_current=falseyou still need the history
immutable factkeep itthe transaction happened
snapshot factinsert a compensating negative rowkeeps audit trail, no physical delete
aggregatesrecompute affected partitionsstale sums overcount

SCD2 close:

SQL
UPDATE dim_customer
SET valid_to = :delete_ts, is_current = false
WHERE customer_id = :id AND is_current = true;

Failure modes

  • Silent row loss: a watermark pull never sees deletes; detect with per-partition count(source) - count(target) reconciliation, alert on any nonzero.
  • Watermark skip: a delete with updated_at older than the watermark (late-arriving) is dropped; detect by comparing max(updated_at) against max(ingested_at).
  • Resurrection: a late update with an older offset re-creates a deleted row; order by LSN/offset, not timestamp.
  • Downstream drift: aggregates and caches not invalidated; the row is gone but the sum still counts it.
  • Privacy deletion: a GDPR erasure must reach every copy including backups; hard delete or crypto-shredding, not a soft flag.

Test delete-then-restore and late delete explicitly, but the reconciliation count is what catches the ones you didn't think of.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Validate incremental equivalence over time.

Answer

What I'd say first. "Equivalence over time" needs a definition before I can validate it, so I'd pin three things: the comparison key, the window, and the tolerance. Assume a Postgres source, Debezium CDC into Kafka, and a dbt incremental model on Snowflake that merges into analytics.orders_incremental; a nightly job rebuilds the same window from source into analytics.orders_full_rebuild. Equivalence means: for a settled window (I use T-7 to T-2, so late events have landed) the incremental table and the rebuild agree on row count, on the set of primary keys, and on a per-row hash of the business columns. I compare on a lagged window, not today's, because today's partition is still moving.

Why drift accumulates. Each class of divergence has a distinct mechanism, and the mechanism tells you where to look:

causemechanismsymptomdetection
late eventswatermark advanced before event time settledincremental misses rows arriving after cutoffcount delta grows as the window gets more recent
deletessource emits no tombstone, or merge ignores the delete flagrows present only in incrementaltruth_rows < inc_rows, keys in inc not truth
duplicatesat-least-once delivery, dedupe key missing from mergeinflated countsduplicate order_id count > 0
schema evolutionnew column defaults null in incremental, rebuild backfills ithash mismatch isolated to one columnmismatches concentrated in the new column
logic changemerge SQL edited, history never backfilledmismatch starts at a boundaryboundary timestamp aligns with a deploy

The check itself. One query does keys, counts and hashes:

SQL
-- Snowflake; nightly, window [T-7, T-2]
with truth as (
  select order_id,
         md5(concat_ws('|', cast(status as string), cast(amount as string),
                       cast(updated_at as string))) as row_hash
  from analytics.orders_full_rebuild
  where order_date between dateadd(day,-7,current_date) and dateadd(day,-2,current_date)
),
inc as (
  select order_id, row_hash from analytics.orders_incremental
  where order_date between dateadd(day,-7,current_date) and dateadd(day,-2,current_date)
)
select
  (select count(*) from truth) as truth_rows,
  (select count(*) from inc)   as inc_rows,
  (select count(*) from truth t full outer join inc i using (order_id)
     where t.row_hash is distinct from i.row_hash) as mismatched_rows;

Example figures: at 1M orders/day the window is 5M rows; a full outer join on 5M rows on an XS warehouse runs in tens of seconds, cheap enough to run nightly. Tolerance is 0 for exact tables; if a metric is approximate (an HLL distinct count, say), I allow 2% relative error and say so in the alert.

Repair vs rebuild. The deciding question is whether the defect is in the data or in the merge logic. If drift is confined to a few partitions and the merge is correct, delete-and-reinsert those partitions: minutes, bounded blast radius. If the merge itself is wrong (duplicate handling, delete flags), backfilling with the same code reproduces the bug; rebuild from source with corrected logic. Rule of thumb: drift in more than ~10% of partitions, or any mismatch that tracks a deploy boundary, means rebuild.

Testing the check. Seed a known defect into a staging copy, delete exactly 100 rows from the incremental side, and confirm the query reports exactly 100 mismatches. If it doesn't, the comparison is broken, not the pipeline. Common ways it breaks: comparing on a non-unique key, hashing floats, or a timezone mismatch between updated_at in source and warehouse.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Build and validate a daily reporting aggregate.

Answer

I'd start by clarifying the grain and the consumer's tolerance for staleness and error. For a daily reporting aggregate, I assume we're building a table that answers questions like "daily active users per tenant per product" or "daily revenue per region", and that the source is an append-only event stream or a transactional table with an event_time column. I assume daily grain in UTC. The key decision is whether to pre-aggregate or compute on read.

I'd build an incremental aggregate table partitioned by date, with a watermark column tracking the max event_time processed. For each day, I'd compute additive measures (sum of amount, count of events) and non-additive measures (distinct users, ratios) from components. For distinct counts, I'd use a sketch like HyperLogLog with a 2% error bound if cardinality is high, or exact distinct if it's under a few million. For ratios, I'd store numerator and denominator separately and compute the ratio at query time. I'd validate by reconciling against base facts for a sample of days, checking that sums match and distinct counts are within tolerance.

The alternative is a full refresh each day, which is simpler but costs more and can't handle late data without reprocessing everything. Incremental with a watermark is more complex but cheaper and allows bounded restatement. Another alternative is a materialized view, but that doesn't give control over restatement policy. I'd choose incremental if the source is large and late data is common; full refresh if the table is small and correctness is paramount.

ApproachCostLate dataComplexity
Full refreshHigh: scans all historyRequires full reprocessLow
Incremental + watermarkLow: scans new eventsLookback windowMedium
Materialized viewMedium: depends on engineLimited controlLow

Failure modes: Late events arriving after the watermark are missed. Detection: compare daily row counts to source for the last N days; alert if a day's count changes after the watermark. Missing partitions cause queries to fail. Detection: check partition existence in the orchestration tool. Non-additive measure drift: distinct counts can't be summed across days; summing daily distinct users to get weekly overcounts. Detection: add a test that weekly distinct != sum of daily distinct. Currency: summing amounts in multiple currencies without conversion is wrong. Detection: check for multiple currencies per day and fail if no conversion rate is applied.

Worked example: Suppose we have 1M events/day, 10k tenants, 100 products. Daily aggregate table has 10k * 100 = 1M rows/day. Incremental refresh processes only new events since last watermark, say 50k events. Full refresh would scan 30 days * 1M = 30M events. At $5/TB scanned in BigQuery, if each event is 1KB, 30M events = 30GB = $0.15 per full refresh vs. incremental scanning 50MB = $0.00025. That's a 600x cost difference. But incremental requires handling late data: if 1% of events arrive late, we need to reprocess the affected days. We can use a lookback window of 3 days to catch most late data.

Validation: I'd write a reconciliation query that compares the aggregate to a direct query on the base table for a sample of days. For example:

SQL
SELECT
  a.date,
  a.tenant_id,
  a.product_id,
  a.sum_amount,
  b.sum_amount AS base_sum_amount
FROM daily_aggregate a
JOIN (
  SELECT
    DATE(event_time) AS date,
    tenant_id,
    product_id,
    SUM(amount) AS sum_amount
  FROM base_events
  WHERE event_time >= '2024-01-01' AND event_time < '2024-01-08'
  GROUP BY 1,2,3
) b
ON a.date = b.date AND a.tenant_id = b.tenant_id AND a.product_id = b.product_id
WHERE a.sum_amount != b.sum_amount;

If this returns rows, the aggregate is wrong. I'd also test late updates: insert an event for a past day, run the incremental job, and verify the aggregate updates. And test missing partitions: delete a partition, run the job, verify it recreates it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Evaluate a wide reporting table versus a star schema.

Answer

Core answer (first 90 seconds)

Two things decide this: how varied the read patterns are, and how volatile the dimension attributes are.

If roughly 90% of reads are the same ten dashboards at a single grain, and the attributes you denormalise change rarely, a wide table is correct. You pay the join once in the ETL, every read is one columnar scan, and there is no join left to get wrong. If analysts slice by arbitrary dimension combinations, or attributes change after the fact, a star schema wins: the fact table holds only keys and measures, and a corrected attribute is one row update in a dimension instead of a rewrite of the fact.

Why fanout happens

Fanout is a join-cardinality bug, not a modelling style. If a dimension has more than one row per key (SCD2 history, multiple addresses, a bridge table) joining the fact on the natural key multiplies fact rows and every SUM() overcounts.

SQL
-- dim_customer: customer_sk unique per version, customer_id repeats across versions
SELECT COUNT(*) FROM fact_orders f
JOIN dim_customer c ON c.customer_id = f.customer_id;   -- 3x if 3 versions

The fact stores customer_sk, so ON c.customer_sk = f.customer_sk returns one row per order. Detection is a row-count ratio: if COUNT(*) after the join exceeds COUNT(*) on the fact, you have fanout. A wide table built by that same join bakes the tripled rows into storage, and the error stays invisible until someone reconciles a total.

Optimizer behaviour

Star-schema joins are hash joins on integer surrogate keys, and a filter on a dimension can prune fact partitions before the join runs. A wide table removes the join but widens the scan; columnar engines read only referenced columns, so a 200-column wide table queried on 8 columns is fine: the cost is the duplicated attribute bytes, not the column count.

Arithmetic

1e9 order rows. A wide table carrying 60 bytes of customer attributes duplicates ~60 GB. The star stores 1e9 × 8-byte FK = 8 GB, plus a 10M-row dimension at ~200 bytes = 2 GB. Dictionary encoding on low-cardinality attributes closes much of that gap, but the rewrite cost does not close: a segment change for 2M customers means rewriting the affected fact rows in the wide table versus updating 2M dimension rows in the star.

When not to use each

Don't use a wide table when attributes are volatile, when you need several grains, or when the same dimension must be conformed across facts: one definition of "active customer" is a dimension, not a column copied into five tables. Don't use a star when the workload is one fixed dashboard and the join is measurable in the latency budget; a serving-layer join that pushes p99 from 40 ms to 180 ms is a real reason to pre-join.

Failure modes

Fanout: totals inflate, detected by the row-count ratio and by reconciling SUM against the source. Key drift: a wide table rebuilt from a changed dimension silently rewrites historical values; detect by hashing dimension attributes per partition and alerting on change. Late-arriving dimension rows: in a star they land as a new version; in a wide table they force a backfill, so track which fact partitions were built before the dimension row arrived.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a report-serving model from dashboard requirements.

Answer

First 90 seconds. The dashboard is the requirements document, so read it as one. For each tile, write down the decision it drives, the finest grain anyone will slice to, the measures and their aggregation rule, the dimensions and whether any of them need history, the freshness the viewer actually needs, and the retention window. Two tiles that look alike often disagree on grain, and that disagreement is the design. Then say your assumptions out loud: "finest drill is order line, freshness SLA is hourly, region is a slowly changing dimension where history matters." If the interviewer corrects one, the design changes and you say how.

Core answer. Derive grain from the finest question, not the widest table. Build a fact table at that grain with conformed dimensions shared across dashboards, and add pre-aggregated rollups only for slice combinations that are fixed and hot. A wide denormalized table is right when the tile set is frozen and one team owns it; it is wrong the moment a second dashboard needs a different grain or a dimension needs history. Star first, because conformed dimensions are what make two dashboards agree on "active customer" or "region". The cost is query-time joins and the discipline of declaring every fact's grain.

Fan-out, the failure that bites. Fact at order-line grain:

order_idlinerevenue
11100
2150

dim_promotion says order 1 had promo A and promo B. So

SQL
SELECT SUM(f.revenue)
FROM fct_order_line f
JOIN dim_promotion p ON f.order_id = p.order_id;

returns 100 + 100 + 50 = 250. Truth is 150. The join multiplied order 1's line by its promotion count. Detection: reconcile SUM(revenue) from the fact alone against the joined query; they must match when the join is 1:1 at the fact grain. Fix: aggregate promotions to one row per order before joining, or keep promotion as a bridge table and never sum revenue across it.

Choosing the shape.

shapepick it whencostdon't pick it when
star: fact + conformed dimsseveral dashboards share dimensions; ad-hoc slicingquery-time joins; needs a columnar engine to stay fastone frozen tile set, no reuse
wide denormalizedtile set frozen, one owner, dimensions rarely changerebuild on every dimension change; storage multipliesany dimension needs history or a second consumer
pre-aggregated rollupfixed slice combos, high volume, tight latencyone table per combo, refresh lagad-hoc drill-down below the rollup grain

Hypothetical sizing to make that concrete: a 2B-row order-line fact at ~200 bytes/row is ~400 GB. A daily × region × product rollup over 3 years, 20 regions, 5k products, is at most ~110M rows and realistically far sparser: the difference between a multi-second scan and a sub-second one.

Point-in-time joins. With SCD2, the predicate is half-open, not equality:

SQL
SELECT f.order_date, d.region, SUM(f.revenue)
FROM fct_orders f
JOIN dim_customer d
  ON f.customer_key = d.customer_key
 AND f.order_date >= d.valid_from
 AND f.order_date <  d.valid_to
GROUP BY 1, 2;

Drop the two range predicates and a customer who moved region in March gets their current region applied to January revenue. Detect it by comparing a restated month against the previously published number: if history is stable and the total moved, the join is wrong.

Other failure modes, with detection. Late-arriving facts restating a closed period: watch the gap between max(event_time) and max(load_time), and diff yesterday's total across two refreshes. Rollup staleness against the SLA: alert on now() - max(refresh_ts) for the rollup table. Each of these is a wrong number on a dashboard, which is worse than a slow one.

Finally, prototype the three or four representative queries, reconcile their output to source truth, and write down which analyses the model deliberately does not support.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design atomic publication for reporting datasets.

Answer

Clarify first. Two questions decide the design: do readers join more than one table in a single query, and how much reader-visible downtime is acceptable? I'll assume a warehouse or lakehouse table read by a BI tool and a nightly downstream job, readers are plain SQL, and the contract is: a reader sees the previous complete version or the new complete version, never a partial one. Freshness SLA is a nightly window.

Answer. Never mutate the live table in place. Build the new version under a different name, partition, or branch; validate it; then flip a single catalog pointer in one commit. Readers resolve the dataset through that pointer, so the swap is the only moment that matters and it is atomic by construction.

Why it works. Each platform already has one atomic commit point, and the trick is to make publication be that commit and nothing else.

platformpublish primitivegranularitywhat readers see
Iceberg 1.x (Spark 3.5)CREATE OR REPLACE TABLE ... AS SELECT, or write a branch then CALL cat.system.fast_forward('db.t','main','staging')whole tablenew snapshot after the catalog commit
Delta Lake 3.xCREATE OR REPLACE TABLE; REPLACE WHERE for one partitionwhole table / partitionnew version after commit
SnowflakeALTER TABLE live SWAP WITH staging (same database and schema)whole tableatomic swap of data and metadata
BigQueryCREATE OR REPLACE TABLEwhole tableatomic
Postgres 15BEGIN; ALTER TABLE ... RENAME ...; COMMIT;whole tableblocks on ACCESS EXCLUSIVE, then new table

Worked trace (Postgres). Build and validate with no lock on the live table, then publish in one transaction:

SQL
CREATE TABLE fact_20240601 (LIKE fact INCLUDING ALL);
INSERT INTO fact_20240601 SELECT ...;   -- build, no lock on fact
-- validate: row count, null checks, reconciliation vs source
BEGIN;
ALTER TABLE fact RENAME TO fact_20240531;
ALTER TABLE fact_20240601 RENAME TO fact;
COMMIT;

Both renames are catalog-only, so the transaction commits in single-digit milliseconds. A reader that starts while the transaction is open blocks on the ACCESS EXCLUSIVE lock and then reads the new table; a reader that started earlier holds an MVCC snapshot and finishes on the old table. No reader sees a mix. The cost is the lock: a 10-minute dashboard query on fact delays the swap by 10 minutes and every query behind it queues. That is the failure mode to watch, not corruption.

Cross-table consistency. Two tables are two commits, and a reader can land between them: fact at N+1, dim at N, wrong numbers. Three fixes: publish both in one catalog commit if the catalog supports it (Nessie commits across tables in one hash); version the dataset and have readers pin (SELECT ... FROM fact VERSION AS OF 12345 in Iceberg, VERSION AS OF in Delta); or a publication pointer table read once per query.

Failure modes, detection, cost.

  • Half-built read: prevented by the pointer. Detect with a canary asserting row count and max(updated_at) on the live table each minute. Cost if it slips: a stale dashboard, not wrong numbers.
  • Validation passes but data is wrong: reconcile row counts and a checksum against source before commit. On failure, don't commit: the live table is untouched, blast radius zero. Cost: one missed SLA window.
  • Commit conflict: two publishers race; the catalog compare-and-swap fails (CommitFailedException in Iceberg). Detect in the orchestrator, retry or fail the job. Cost: a delayed publish, never a corrupt table.
  • Rollback: keep the previous version addressable. Iceberg snapshots until expire_snapshots, SWAP WITH back in Snowflake, rename back in Postgres. Bound retention to N versions or 7 days; cost is storage.

Trade-offs. Whole-table replace is simplest and strongest but rewrites everything and doubles storage during the build. Partition-level replace (REPLACE WHERE, Iceberg REPLACE PARTITION) is cheaper for incremental loads but atomic only per partition, so a reader can see a mix of old and new partitions unless the query filters to one. Branch-then-fast-forward lets you validate the exact bytes readers will see before flipping, at the cost of an extra catalog step. If the dataset is append-only and readers tolerate eventual consistency, a plain INSERT with a watermark column is cheaper and you don't need any of this.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design lateness and period-close handling.

Answer

Core answer

Assume facts carry an event time from the source system, the business date is derived from event time rather than arrival time, and the period close is a policy date, not a technical boundary. A strong answer separates three things: event-time ingestion, the period state machine, and the correction path.

Ingestion: assign watermarks from event time with a bounded out-of-orderness, and give windows an allowed lateness. In Flink, allowedLateness defaults to 0: every late event is dropped unless you set it. Set it from measured lateness, not a guess.

Period state machine: a period moves open → provisional (all facts in, aggregates published, still mutable) → closed (immutable, published version pinned). Close happens at a wall-clock cutoff, e.g. 02:00 UTC on the third business day.

Correction path: inside the restatement window (say three business days after close) a late fact restates the closed period. Reprocess the affected partitions, bump the period version, notify consumers. After the window it becomes an adjustment entry dated in the current open period, and the closed period's published numbers never change.

Mechanism

Watermark = max event time seen − out-of-orderness bound. A window fires when the watermark passes its end. allowedLateness keeps window state alive past firing so late elements update the result and re-emit. Anything later goes to a side output.

Idempotency: every fact gets a deterministic key. (source_system, entity_id, event_time, source_seq). Loads are MERGE/upsert on that key, and partition overwrites are keyed by business date, so replaying a partition is a no-op.

Trade-off: restate vs adjust

RestatementAdjustment entry
What changesClosed period's published numbersOnly the current open period
Consumer impactRe-pull, version bump, downstream recomputeNone; nets out over time
Use whenMaterial error, inside window, audit needs corrected historySmall, immaterial, or window expired
CostFull reprocess plus notification fan-outReconciliation drift until it nets

Rule: restate when the error changes a reported figure a consumer acted on; adjust otherwise.

Failure modes

  • Watermark stalls on an idle partition → windows never fire, dashboards freeze. Detect: watermark lag vs processing time alert. Fix: idle-source timeout (withIdleness).
  • Late event after close silently dropped. Detect: side-output counter > 0 for a closed period. Route to an exception queue, never discard.
  • Backfill collision: a backfill and live traffic write the same business date. Detect: reconciliation sum per (date, entity) against source. Fix: backfills write to a shadow partition, then swap.
  • Reversal arriving after the original was aggregated → net sum drifts. Detect: running net per entity against the source ledger.

Artefact

Java
WatermarkStrategy<Event> wm = WatermarkStrategy
    .<Event>forBoundedOutOfOrderness(Duration.ofMinutes(30))
    .withTimestampAssigner((e, ts) -> e.eventTimeMillis())
    .withIdleness(Duration.ofMinutes(5));

stream.assignTimestampsAndWatermarks(wm)
      .keyBy(Event::accountId)
      .window(TumblingEventTimeWindows.of(Time.days(1)))
      .allowedLateness(Time.hours(2))
      .sideOutputLateData(lateTag)
      .aggregate(new SumAgg(), new DayWindowFn());

Trace: an event with event time 23:50 on day D arrives at 03:10 on D+1. The watermark at 03:10 is ~02:40, past D's window end (00:00 D+1) plus the 2 h allowed lateness (02:00). The window already fired and closed, so the element goes to lateTag → correction topic → applied as an adjustment entry in the open period D+1.

Sizing: if p99 lateness is 40 min and p99.9 is 3 h, allowedLateness = 2h sends roughly 0.1% of events to the side output. At 5M events/day that is ~5k corrections/day: cheap to auto-apply, but it means 2 h of window state per key is retained, so check state size against key cardinality before widening the bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Handle partial input and quarantine decisions.

Answer

If this came in as a one-line ticket, I'd ask three things before touching the pipeline: what's the reporting contract. Hard publish deadline or eventual consistency? What's the tolerance for bad rows per partition? And who consumes the output: an automated settlement that must be exact, or a dashboard where a marked partial is acceptable? The answers decide the policy. Assume a daily batch report over 24 hourly partitions, publish deadline 06:00 UTC, and a 0.5% bad-row tolerance per partition. Then the decision splits into two independent gates: completeness (did every partition arrive?) and validity (are the rows in the arrived partitions usable?).

Completeness. Track a watermark per source: the maximum event time seen, plus a partition manifest of expected partitions. At 05:30, compare manifest to arrived partitions. If partition 17 (16:00–17:00) is missing, you have two choices: wait until the deadline, or publish partial. Waiting is bounded by the deadline; after 06:00 you publish. Never fill the missing hour with zeros: that turns a visible gap into a silent lie. Instead, mark hour 16 as pending, set the report's last_good timestamp to the previous complete period, and include a coverage field: 23/24 partitions, 95.8% of expected rows. If the partition arrives at 05:55, republish atomically before 06:00 with a version bump. If it arrives at 06:10, the 06:00 partial report stands; publish a corrected version at 06:15 and let consumers key on version.

Quarantine. Invalid rows don't get dropped silently. Route them to a quarantine table with the raw payload, a reason code, and the source offset. In a worked example: partition 9 has 1,000,000 rows; 3,000 fail schema validation (missing currency code). Quarantine those 3,000 with reason='missing_currency', source='kafka:topic:9:offset', and the original JSON. Publish partition 9 with a coverage note: 99.7% of rows included, 0.3% quarantined. If the quarantine rate for a partition exceeds 0.5%, mark that partition partial instead of publishing a total that's missing 0.5% of rows. If total coverage across the report drops below 95%, fail the publish and page on-call: at that point the report is not a report, it's a guess.

Hypothetical thresholds for a daily batch report; tune to your SLA.

ConditionThresholdAction
Missing partitionanyPublish partial with explicit missing periods; no zero-fill
Late partition, before deadlinearrival < 06:00Wait up to deadline, then publish partial
Late partition, after deadlinearrival ≥ 06:00Publish partial at 06:00; republish atomically when it arrives
Quarantine rate per partition≤ 0.5%Publish partition with coverage note and quarantine count
Quarantine rate per partition> 0.5% and ≤ 5%Mark partition partial; publish other partitions
Quarantine rate per partition> 5%Fail the whole report; page on-call
Total coverage< 95%Fail the report; do not publish

Failure modes. A late partition that never arrives: the partial marker stays forever unless you have a backfill job that closes the gap and republishes. A quarantine table that grows unbounded: without a retention policy and a remediation SLA, you're just moving the data loss. A republish race: downstream consumers that read the 06:00 partial and the 06:15 corrected version without keying on version will double-count. Detect these with three metrics: watermark lag per source, quarantine rate per partition, and publish version counter per report. Alert on watermark lag > 2 hours, quarantine rate > 0.5%, and any report that publishes without a coverage field.

Trade-offs. Fail-closed (no report) is right when the report drives automated settlement; a partial report there is worse than a late complete one. Fail-open with explicit markers is right for dashboards and exploratory consumers. The alternative to quarantine is to reject the whole partition on any bad row: simpler, but it throws away 99.7% good data. Don't do that unless the contract requires exactness.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design schema-evolution handling for reporting ETL.

Answer

Core answer (first 90 seconds)

Assume: nightly batch ETL, Postgres CDC plus Kafka Avro topics landing in Snowflake, BI dashboards and two downstream marts as consumers. "Schema evolution" here means four change classes: additive columns, type changes, renames, and enum/key changes.

The answer: treat the schema as a versioned contract stored as data, gate every change at publish time against an explicit compatibility rule set, and only then let it reach the warehouse.

Mechanism: one contract row per column. Name, type, nullability, semantic meaning, key role, sensitivity, owner, and the version it was introduced. Each run, the loader reads the incoming schema (Avro schema from the registry, or the CSV header) and diffs it against the registered contract. The diff is classified by rules, not by a human:

changeclassificationwhy
add nullable col with defaultcompatibleold readers ignore it
add NOT NULL col, no defaultbreakingbackfill has no value
int32 → int64compatibleAvro promotion
int64 → int32breakingtruncation
renamebreaking unless alias existsname-based readers break
add enum valuecompatible if consumers have a default branchelse breaking
remove enum valuebreakinghistorical rows unreadable

Confluent Schema Registry's default compatibility level is BACKWARD: a new schema must be able to read data written with the previous one. That is the right default for reporting: you can replay history. FULL is stricter and blocks producers more; use it only on topics whose consumers cannot be patched quickly.

Trade-off: gate at publish versus detect at run. A registry gate fails the producer's CI in seconds and costs them a schema bump; a dbt test on the warehouse catches the same drift after data has landed, so you have already written bad rows and must backfill. Gate where a registry exists (Kafka/Avro). For CSV drops with no registry you can only test at load, so make the header check a hard fail, not a warning.

Failure modes and detection:

  • Positional mis-mapping. A CSV reorder puts gross_revenue into net_revenue. Detect: match on header names, fail on unknown or missing names, never index by position. Cost: a wrong number on an exec dashboard, found by finance a week later.
  • Enum drift. Source adds REFUNDED; the CASE falls to ELSE 'UNKNOWN' and refunds vanish from the total. Detect: assert zero unmapped enum values per run; alert on any UNKNOWN count above zero.
  • Nullability flip. Source makes a column NOT NULL; the backfill for old rows has no value. Detect: pre-flight null count on the new column before enabling the constraint.
  • Timestamp precision change (seconds → milliseconds) silently multiplies partition keys. Detect: contract pins unit and precision.

Rename trace: contract v3 renames cust_id → customer_id. The loader sees unknown column customer_id and missing cust_id. An alias table maps customer_id → cust_id for v3. The loader writes both into the canonical customer_id column, emits a deprecation warning, and after an overlap window of two full runs drops the alias. Rollback: keep the previous contract version pinned; if the new run fails validation, re-point to v2 and re-run. The warehouse table is unchanged because the load is transactional per partition.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Capture useful run metadata and lineage.

Answer

Core answer (first 90 seconds)

Two artifacts, not one list. Run metadata is a row per run: identity, versions, interval, counts, outcome. Lineage is a directed graph of dataset → job → dataset edges, each tagged with the run that produced it. Emit both from the job as structured events, store them in a lineage service, and query the graph for impact. If you only log metadata to the orchestrator's DB you get run history but no cross-engine graph; if you only build a graph you can't answer "which run wrote this partition."

Assumptions: batch warehouse pipelines on Airflow driving Spark and dbt, Snowflake or BigQuery targets, one team owning the catalog.

Mechanism

Emit OpenLineage events (START, COMPLETE, FAIL) from both the orchestrator and the compute engine. Airflow's OpenLineage provider emits task-level events; the Spark integration emits through a SparkListener; dbt emits per model. Each event carries run.runId (a UUID), job.namespace and job.name, inputs[] and outputs[] with dataset namespace and name, and facets: schema, dataSource, version, columnLineage, ownership, nominalTime.

JSON
{
  "eventType": "COMPLETE",
  "eventTime": "2024-06-01T02:14:07.512Z",
  "producer": "https://github.com/apache/airflow",
  "run": { "runId": "b1e4c0a2-7d3f-4a91-9c2e-5f0a8d6b3c11" },
  "job": { "namespace": "warehouse", "name": "build_orders_daily" },
  "inputs": [
    { "namespace": "snowflake://acct", "name": "raw.orders",
      "facets": { "version": { "datasetVersion": "2024-06-01T02:00:00Z" } } }
  ],
  "outputs": [
    { "namespace": "snowflake://acct", "name": "analytics.orders_daily" }
  ]
}

The runId is the join key: it links the orchestrator's task attempt to the Spark job to the written partition. Store events in Marquez (the OpenLineage reference server) or DataHub; both expose a graph API you query by dataset to get upstream and downstream.

Trade-offs

Push vs pull. Push (the job emits) gives precise run boundaries and column lineage, but every engine must be instrumented and you must decide fail-open vs fail-closed on emission errors. Pull (scrape query logs or information_schema) covers uninstrumented engines but lags and misses in-memory transforms.

Column lineage: parsing SQL with sqlglot is cheap and engine-agnostic but breaks on dynamic SQL; engine-native plans are accurate but engine-specific. Choose parsing when most transforms are static SQL; choose plans when you have heavy dynamic SQL and one engine.

Store: the orchestrator DB is free but couples lineage to one scheduler and can't span engines; a dedicated service (Marquez, DataHub) costs an extra deployment but survives an orchestrator migration.

Failure modes

failuredetectioncost
Emission drops silentlyreconcile COMPLETE events per job per day against DAG runsgraph goes stale; impact analysis misses downstream
runId reused across retries/backfillsduplicate runId with differing nominalTimereplay and incident scope wrong
No schema facet on dynamic SQL outputsoutputs with an empty schema facetcolumn-level impact unavailable
Synchronous emission blocks the tasktask duration correlates with lineage endpoint latencypipeline SLA slips

Deciding criteria: number of engines, whether you need column-level lineage, and whether lineage must outlive the scheduler.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Build layered tests for a reporting pipeline.

Answer

What I'd say first

Assume a daily batch warehouse pipeline (dbt on Snowflake, say) feeding a revenue report that must publish by 07:00. The goal is that a wrong number never reaches a consumer, so I'd put tests at three layers, each catching a different class of bug, and give each check a severity that decides whether the run blocks publication. Source tests catch upstream breakage before it propagates; transform tests catch logic errors; output tests catch whether the number a consumer actually sees is right.

Source layer: did the data arrive, complete and on time?

Three checks. Contract: the columns and types the loader promised still exist, so a renamed upstream field fails loudly instead of silently nulling a metric. Freshness: dbt source freshness with warn_after: {count: 12, period: hour} and error_after: {count: 24, period: hour} on _loaded_at. Control counts: today's row count within 20% of the trailing 7-day median. A partial load usually shows as a volume cliff, not a schema error.

Transform layer: is the logic correct?

This is where dbt's generic tests earn their place, because they run per-model and fail the build:

YAML
models:
  - name: fct_orders
    columns:
      - name: order_id
        tests: [unique, not_null]
      - name: status
        tests:
          - accepted_values:
              values: ['placed','shipped','cancelled']
      - name: customer_id
        tests:
          - relationships:
              to: ref('dim_customers')
              field: customer_id

Beyond those, singular SQL tests for the things generic tests can't express: deduplication on the natural key, temporal overlap (no two active subscription rows for one customer), and business invariants like shipped_at >= placed_at.

Output layer: is the published number right?

Reconcile the headline metric against an independent source. Yesterday's fct_orders revenue came to 1,284,300.00 (hypothetical); the finance ledger sums to the same figure; tolerance 0.1% = 1,284.30, and anything larger blocks the report. Then partition completeness (every expected date present), row-change deltas versus yesterday, and a fixture query that runs the consumer's actual dashboard SQL and asserts a known result.

LayerQuestionExample checkSeverity
SourceDid data arrive complete and on time?count within 20% of 7-day median; max(event_time) < 12herror
TransformIs the logic correct?order_id unique; status in set; FK to dimerror
OutputIs the published number right?revenue reconciles to ledger within 0.1%error

Trade-offs and failure modes

Incremental vs full rebuild: a rebuild is ground truth but rescans everything, so I run it weekly and on any schema change, and compare its output to the incremental run. A divergence means the incremental merge logic is wrong. Severity matters: structural checks (uniqueness, FKs) are error and block; soft checks (a 5% volume wobble) are warn and page nobody at 03:00.

Concrete failures I've seen: a freshness test that passes because it reads _loaded_at while the payload's event_time is three days stale. Fix by testing max(event_time). A dedup test that fails every day because the source key genuinely isn't unique: the test is wrong, not the data. And a reconciliation tolerance set at 5% that quietly hid a 2% revenue drop for a month. Each of these is caught by the layer above it, which is the point of layering.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Plan a large historical backfill.

Answer

Core answer (first 90 seconds)

First I pin down three things: the interval (say 2022-01-01 to 2024-12-31), which consumers read the affected table, and whether the new definition must apply retroactively or only going forward. Then I answer: partition the interval into bounded, non-overlapping units, write each unit idempotently into a shadow copy, reconcile it against the source, and publish by swapping a version pointer. Never by mutating the live table in place.

Assumptions: ~1.1B source rows (about 1M/day over 3 years), a batch warehouse (Postgres, Snowflake or BigQuery), and a live daily job already writing the same table.

Partitioning and budget

Partition by day: 1,095 partitions, each ~1M rows. A worker writing 50k-row batches at ~2k rows/s takes ~500s per partition. One worker: 1,095 × 500s ≈ 6.3 days. Twenty workers: ~7.6 hours. That is the budget (20 workers, 50k batch size, ~8 hours wall clock) and it tells you whether you must throttle against the live job's shared slots.

Idempotency mechanism

Each partition writes to metrics_v2 keyed by (metric_date, entity_id). Use INSERT ... ON CONFLICT (metric_date, entity_id) DO UPDATE (Postgres) or MERGE (Snowflake/BigQuery). Re-running a partition overwrites the same keys instead of appending, so a retry after a crash is safe. The alternative, append-only with a run_id, forces every reader to dedupe, which is worse.

Atomic publish

Readers never see a half-filled table. Build into metrics_v2, then swap: rename tables, or point a view metrics at metrics_v2 in one transaction. The swap is the only moment of visibility change.

Reconciliation

Per partition, compare row count and a checksum (e.g., SUM(amount)) against the source. Fail the partition if counts differ or the sum drifts more than 0.01%. This catches silent drops and double writes before publish.

Failure modes

failuredetectioncost
Backfill overlaps live job → double countday row count > source countre-run partition after pausing job
Worker crash mid-partitionpartition has no completion markerresume from last committed batch offset
Source is mutable (late events)reconcile counts diverge from livepin to snapshot ts or accept re-run

Trade-off: coordinate vs isolate

Coordinate = pause the live daily job for the interval, run the backfill, resume. Simple, but creates a freshness gap and blocks the job. Isolate = write to a separate versioned table and swap. No downtime, but doubles storage for the interval and needs the swap step. Choose coordinate for short intervals where consumers tolerate a gap; isolate when the table is large or consumers cannot pause.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Orchestrate dependent reporting models.

Answer

What I'd say first

Assume daily batch reporting on a warehouse (Snowflake or BigQuery), Airflow 2.x scheduling, and dbt 1.x owning the model DAG. The core answer: a reporting model should depend on the data being ready, the required source partition present and fresh, not on the upstream task turning green or the clock reaching 02:00. Task success means the job ran; it does not mean the partition it was supposed to write is complete. So I gate on a readiness check against the source, key every model to a logical interval ({{ ds }}), and make each model idempotent so re-running the same interval overwrites rather than duplicates.

Mechanism

A SqlSensor waits for the partition to exist, then dbt resolves the model DAG and runs it. The sensor is the dependency; the dbt DAG is the ordering.

Python
wait_for_orders = SqlSensor(
    task_id="wait_for_orders_partition",
    conn_id="warehouse",
    sql="SELECT COUNT(*) > 0 FROM raw.orders WHERE dt = '{{ ds }}'",
    mode="reschedule", poke_interval=300, timeout=6 * 3600,
)
YAML
# sources.yml — freshness is a second gate, not a substitute for the partition check
sources:
  - name: raw
    freshness:
      warn_after: {count: 2, period: hour}
      error_after: {count: 6, period: hour}
    loaded_at_field: _loaded_at

Trace: interval 2024-06-01, source lands at 03:40 instead of 02:00.

  • Clock-based (sleep 1800): model runs 02:30 on ~60% of rows, publishes revenue ~40% low. Nobody notices until finance reconciles.
  • Sensor-based: pokes every 300 s, first success 03:45, model runs on the full partition. Downstream is late but correct.

Dependency strategies

StrategyWaits onFails when
Clock delaywall timesource late → partial data published
Task-completion sensorupstream DAG run successupstream succeeded but wrote nothing
Data-readiness sensorrow present for intervalsource never lands → timeout, chain blocked
Event-driven (Airflow Dataset)upstream asset materializedproducer never emits the event

Trade-offs

Sensors are simple and correct but couple the DAG to the source's schedule and stall the whole chain on one late input. Event-driven decouples but adds a failure mode when the producer doesn't emit. Cost is real: a sensor in poke mode holds a worker slot for up to 6 h; reschedule releases it between pokes. Backfill arithmetic: 90 days × 12 models × 4 min = 4,320 min ≈ 72 h serial; max_active_runs=4 across intervals brings it to ~18 h. Don't add a sensor that never fires, if the source is reliably on time, a plain task dependency is cheaper.

Failure modes and detection

  • Late source → AirflowSensorTimeout after 6 h, downstream upstream_failed, alert fires.
  • Partial partition (freshness passes, volume low) → row-count test asserting within ±30% of the trailing 7-day median.
  • Backfill collision → two runs write the same partition; idempotent merge on grain, detected by a unique test on the partition key.
  • Circular dependency → dbt parse fails with "Cycle detected"; Airflow raises a DAG import error.
  • Scheduler restart → catchup=True replays missed intervals; depends_on_past=True blocks a run if the prior interval failed.

What I'd test

Upstream correction (re-run one interval, confirm downstream overwrites), scheduler restart mid-chain, a cycle, and a consumer query when one input is missing: it should fail loudly, not silently return stale rows.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design scheduling and concurrency for reporting pipelines.

Answer

Core answer (first 90 seconds)

The invariant is: each logical interval (a day, an hour, a tenant-day) is materialized exactly once, and readers never see a partial interval. Everything else is machinery for that.

Assumptions I'd state up front: the interval is the unit of work; the warehouse is the sink; the orchestrator is Airflow 2.7+ or 3.x; late data is handled by re-running the interval, not by patching rows in place.

Three mechanisms carry it:

  1. Serialize per interval. The scheduler must not run two runs that write the same partition.
  2. Make the write idempotent and atomic. Write to a run-scoped staging location, then swap it in one transaction.
  3. Bound the run. Timeout, retries with backoff, and an explicit policy for what happens when a run collides with an active one.

Serialization

max_active_runs is a per-DAG limit on concurrent DAG runs, not a global semaphore. Default is 16. For a daily report where intervals must be ordered, set it to 1. If partitions are independent (different days, different tenants), keep it higher and lock at the partition level instead: a row in a pipeline_locks table keyed by interval, taken with SELECT ... FOR UPDATE, or a Postgres advisory lock.

catchup=False stops the scheduler from creating a run for every interval between start_date and now on first deploy. A daily DAG with start_date=2023-01-01 deployed today would otherwise queue roughly a thousand runs. Backfills then become explicit operator actions.

Add depends_on_past=True if interval N must follow N-1, dagrun_timeout to kill a wedged run, and a pool with N slots to cap concurrent warehouse load across DAGs.

Idempotency and atomic commit

Write to staging/<interval>/<run_id>/, then swap it into final/<interval>/ in a single transaction. On Postgres that's a table rename or a view swap; on Iceberg/Delta it's INSERT OVERWRITE on the partition. S3 has no atomic rename, so use a manifest pointer or a table format that does.

The swap is what makes readers safe: they see the old partition until the commit, then the new one. A failed run leaves staging orphaned and the final partition untouched.

Collision policy

PolicyBehaviorUse when
SkipDrop the new run if one is activeNon-critical reports
QueueWait for the active runOrdered, SLA-bearing reports
ReplaceKill active, start newReal-time dashboards
ParallelRun if partitions are disjointIndependent partitions

Failure modes and detection

  • Run exceeds execution_timeout (2h): task killed, marked failed, retried per retries=3 with retry_exponential_backoff=True. Detect by alerting when task duration exceeds 0.8 × timeout.
  • Scheduler restart: Airflow keeps run and task state in the metadata DB, so a restart resumes; with HA, schedulers coordinate through row locks on dag_run/task_instance. A custom scheduler must persist the same state or it re-triggers.
  • Duplicate trigger (manual plus scheduled): the partition lock rejects the second writer. Without it you get two swaps and last-writer-wins: idempotency alone does not give exactly-once.
  • Warehouse error mid-write: the staging write is incomplete, the swap never runs, the final partition is unchanged; the retry re-runs the whole interval.
  • Zombie task: process killed but still writing. execution_timeout plus a lease/TTL on the lock row.

Detect all of these from task_instance state and duration in the metadata DB, plus row counts per partition compared against the previous interval.

Python
# Airflow 2.7+ / 3.x
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator

def process_interval(ds, run_id, **context):
    stage = f"staging/{ds}/{run_id}"
    write_partition(stage)              # idempotent: overwrite stage
    with warehouse.transaction():
        acquire_lock(ds)                # SELECT ... FOR UPDATE on pipeline_locks
        swap(stage, f"final/{ds}")      # rename / INSERT OVERWRITE

with DAG(
    dag_id="reporting_pipeline",
    start_date=datetime(2023, 1, 1),
    schedule="@daily",                  # schedule_interval removed in Airflow 3
    catchup=False,
    max_active_runs=1,
    dagrun_timeout=timedelta(hours=3),
    default_args={
        "retries": 3,
        "retry_delay": timedelta(minutes=5),
        "retry_exponential_backoff": True,
        "max_retry_delay": timedelta(hours=1),
        "execution_timeout": timedelta(hours=2),
    },
) as dag:
    PythonOperator(
        task_id="process",
        python_callable=process_interval,
        op_kwargs={"ds": "{{ ds }}", "run_id": "{{ run_id }}"},
    )

Trace: daily DAG, max_active_runs=1, catchup=False:

  • 00:00. Scheduler creates the run for interval 2023-10-01, state running. process starts writing staging/2023-10-01/run_abc/.
  • 00:30. Operator triggers a backfill for 2023-09-30. The DAG run is created in state queued; the single max_active_runs slot is taken, so it waits.
  • 01:00. process commits the swap; the run goes success; the queued backfill is promoted to running.
  • 01:40. Backfill commits final/2023-09-30.

No overlap. With max_active_runs=2 both run concurrently; different partitions make the swaps safe, but if a backfill and a scheduled run target the same interval, the partition lock is what prevents the double write.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design failure and rollback behavior for reporting ETL.

Answer

Core answer (first ~90 seconds)

I'd pin down two things before designing anything: what the reporting contract promises consumers, and whether a partial result is ever acceptable. For a nightly revenue aggregate feeding finance, the contract is "the table is either yesterday's complete data or the last good version with a visible stale marker": never a half-loaded table. That decides the rest: fail closed, publish atomically, and make the checkpoint advance part of the publish rather than a separate step.

Concretely, each run loads into a staging table, runs validation gates, and only then swaps it into place in one transaction. The checkpoint, the high-water mark of source data consumed, moves in that same transaction. If anything fails before the swap, the live table is untouched, the checkpoint doesn't move, and the next run reprocesses the same window. Because the write is a partition overwrite keyed by business date, reprocessing is idempotent: rerunning 2024-06-01 replaces that partition instead of appending to it.

Gates that decide block vs. warn

gatecheckwarnblock
row counttoday vs. 7-day median±10%±30%
null ratekey column (customer_id)>0.1%>1%
reconciliationsum(amount) vs. source±0.5%±2%
freshnessmax(event_ts)>2h behind>6h behind

Example thresholds: the point is that each gate has a warn band and a block band, and only block stops the publish. If yesterday was 4.2M rows and staging has 2.9M, that's −31%, so it blocks and the prior version stays live.

Atomic publish

Blue/green via a view swap, so readers never block and never see a half-state:

SQL
BEGIN;
CREATE OR REPLACE VIEW reporting.daily_agg AS
  SELECT * FROM reporting.daily_agg_v2;   -- v2 loaded and validated
UPDATE etl.control
   SET checkpoint = DATE '2024-06-01', published_at = now()
 WHERE pipeline = 'daily_agg';
COMMIT;

CREATE OR REPLACE VIEW is atomic in Postgres and takes only a lock on the view; a reader mid-transaction keeps its old snapshot. The checkpoint update is in the same transaction, so a crash between swap and checkpoint is impossible. Next run alternates to v1.

Trade-offs

Fail-closed versus fail-open is the real decision. Fail-open, publish with a partial=true flag, is right when the consumer is a low-stakes dashboard and staleness hurts more than incompleteness. Fail-closed is right when the number drives a money or regulatory decision. Blue/green costs double storage for the window; in-place partition overwrite avoids that but a run spanning 30 partitions is only atomic per partition, so you either accept per-partition freshness or do the whole range as one swap.

Failure modes and detection

  • Checkpoint advanced before publish → silent data gap. Detect by reconciling row counts per business date against source and alerting on missing partitions.
  • Crash leaves a staging table → next run reuses stale staging. Detect staging tables older than 24h and drop them on a TTL.
  • Rollback itself fails mid-swap → re-read the live table after commit and compare to staging; mismatch pages the owner.
  • Expired staging: if TTL is 24h and the rerun happens three days later, staging is gone. The rerun must rebuild from source, not from staging. Test that path, plus a deliberately failed swap and a repeat failure.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Secure a reporting ETL and serving layer.

Answer

What I'd say first

Clarify two things before designing: is isolation between tenants, or between roles inside one tenant (analyst vs. finance), and does "reporting" mean the BI tool queries the warehouse live or reads a materialized extract? Those decide everything. I'll assume multi-tenant SaaS, one warehouse, live queries plus nightly extracts, and a hard requirement that no tenant sees another's rows and no aggregate reveals a single customer.

The core rule: enforce at the boundary that owns the data, the warehouse or query engine, never in the BI tool's filter, because the BI tool is a client and clients can be bypassed. Carry a tenant_id on every table, including derived ones, and attach a row access policy to each. In PostgreSQL 16 that's:

SQL
ALTER TABLE fact_events ENABLE ROW LEVEL SECURITY;
ALTER TABLE fact_events FORCE ROW LEVEL SECURITY;   -- owner is not exempt
CREATE POLICY tenant_isolation ON fact_events
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

Trace: the app runs SET app.tenant_id = '<uuid>' on the connection, then SELECT count(*) FROM fact_events. The planner appends tenant_id = '<uuid>' to the scan, so only that tenant's rows are counted. If the setting is unset, current_setting raises rather than returning everything: fail-closed. FORCE matters because without it the table owner and superusers skip the policy, which is the most common way this leaks.

Trade-offs

Query-time RLS vs. physical per-tenant copies. RLS keeps one copy and one schema, but every query pays the predicate and a policy bug is a total breach. Physical isolation (a schema or database per tenant) is blast-radius-safe but multiplies storage and makes schema migrations N-way. The deciding criterion is tenant count and query shape: RLS is cheap only when tenant_id is the leading cluster/partition key. On a 2B-row fact table clustered by tenant, the predicate prunes to ~4M rows and p99 stays around 200 ms; unclustered, it's a 2B-row scan and p99 goes to tens of seconds. Below roughly 50 tenants with strict contracts, physical isolation is worth the cost.

Aggregates and small-group inference

A pre-aggregated table is not automatically safe. If a report shows revenue by (region, product) and one cell has a single customer, differencing two reports recovers that customer's spend. Suppress cells where COUNT(DISTINCT user_id) < 5, and apply complementary suppression: suppressing one cell while leaving the row total lets you subtract back to it. Snowflake aggregation policies and BigQuery's k_threshold argument on APPROX_COUNT_DISTINCT do this in-engine. Noise (differential privacy) is more robust but changes numbers, so finance reports that must reconcile to the ledger can't use it.

Failure modes and detection

  • Owner/service-account bypass: a shared ETL role owns the table and skips RLS. Detect with a CI canary that queries as a second tenant and asserts zero rows; also assert relforcerowsecurity is true.
  • Stale subscriptions: a scheduled export runs as its owner after that user is offboarded. Reconcile subscription owners against current entitlements nightly and alert on orphans.
  • Extract loses policy: a Tableau extract or Looker PDT published without a user filter. Scan published datasources for extract + no user filter.
  • Backfill with NULL tenant_id: rows become invisible (fail-closed) or, if the policy has an OR, visible to all. Add NOT NULL and alert on NULL counts.

That's the shape: policy at the boundary, forced on owners, re-applied to every materialization, and a canary that proves it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Define freshness and completeness SLOs for reporting.

Answer

Assumptions I'd state first: the report is a daily batch fact table read by a BI tool and a downstream model; the source is an append-only event stream with an event-time column; "correct" means every event whose event_time falls inside the closed period is present. If the source is a mutable OLTP table with no event time, the framing changes: you'd anchor on a binlog position instead of a watermark.

The answer. Freshness and completeness are two different promises, and you need both, because a job that runs green and publishes nothing new satisfies neither.

Freshness is how old the newest fact a reader can see is. Measure it as now − max(event_time) in the published table, sampled every minute. Completeness is what fraction of the events belonging to a closed period actually landed. Measure it per partition, after the partition closes, as published_rows / expected_rows, where expected comes from the source's own count for that period, not from yesterday's row count.

The reason to split them: a scheduler heartbeat tells you a process started. It says nothing about whether the source delivered data or whether the write committed. A pipeline can publish an empty partition on time and look perfectly healthy.

Concrete SLOs, hypothetical numbers for a daily revenue report:

SLODefinitionTargetMeasured
Freshness (live)now − max(event_time) in published table≤ 30 min for 99% of 1-min samplesgauge, per minute
Publish lagpublish_time − period_close≤ 15 min for 99% of daily partitionsper partition
Completenesspublished rows / source rows for closed period≥ 99.5%per partition, after close
Final lagpublish_time of last complete version − period_close≤ 4 h for 99% of partitionsper partition

Error-budget arithmetic: 30 days is 43,200 one-minute freshness samples; 1% is 432 samples, about 7.2 hours of allowed staleness per month. For completeness, a 20M-row daily partition at 99.5% allows 100k missing rows: too loose for revenue, so tighten to 99.9% (20k rows) and accept more pages.

Worked trace of a late source:

  • Day D closes at 00:00 UTC.
  • Source watermark at 00:00 is 23:40. 20 minutes of events still in flight.
  • Run at 00:05 publishes at 00:12 with watermark 23:40. Publish lag 12 min → passes. Live freshness 32 min → breaches the 30-min SLO.
  • Run at 01:05 picks up the rest, publishes 01:12 with watermark 00:00. Final lag 72 min → passes the 4 h target.
  • The partition ends complete; the 32-minute breach is real and should burn budget, but it should not page: it is a known late-source pattern.

Trade-offs. Event-coverage completeness (count every event) is exact but needs the source to expose both a count and a watermark. Watermark-only completeness ("we read up to X") is cheap and works when the source can't count, but it passes silently when the source itself dropped events. Choose coverage when the report drives money or a model; choose watermark when the source is a firehose and a 0.5% miss is tolerable. The wrong choice is watermark-only on a financial close: you will never see the missing rows.

Failure modes and detection:

  • Empty valid period (holiday, no events): the completeness denominator is 0. Guard the divide and mark the partition "no data expected" rather than failing it.
  • Stale consumer cache: the BI tool serves yesterday's extract while the freshness gauge is green because the warehouse table is fresh. Detect by probing the consumer's own API, not the warehouse.
  • Backfill rewrites a closed partition: completeness recomputes and can drop below target retroactively. Version partitions and alert on retroactive breaches separately from live ones.
  • Timezone: period close in UTC versus report in local time shifts the boundary by hours. Pin both and assert the boundary in tests.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Define reporting ETL reliability and cost metrics.

Answer

What I'd actually measure

Assume a daily reporting pipeline: source tables land in a warehouse (Snowflake/BigQuery), dbt models transform them, a BI layer reads the output. Reliability is measured where the consumer reads, not at the job. A green Airflow task that published half a partition is a failure. So I split into three reliability axes and two cost axes, and I alert on the output metric, never on job success rate.

Reliability

MetricHow it's computedExample alert
Freshness lagnow() - max(partition_ts) in the output tableSLA 06:00 UTC; page at 06:30
Completenessrows landed / rows in source control count< 99.9%
Reconciliation deltasum(measure) source vs output> 0.1% or > $1,000
Duplicate ratecount(distinct pk) / count(*)> 1.0
Late-arriving raterows with event_time < watermark> 0.5%
Backlog / oldest intervalmax unprocessed partition age> 3 intervals

Cost

MetricHow it's computedExample alert
Cost per output rowwarehouse credits / rows published+20% week-over-week
Storage growthbytes per table per dayunbudgeted table > 2x
Scan efficiencybytes scanned / bytes returned> 10x

Why these and not job counts

Job success rate is a vanity metric: it tells you the scheduler ran, not that the number is right. The two that decide most incidents are freshness lag and reconciliation delta, because they map directly to what a consumer notices: a stale dashboard or a wrong total.

Worked example (hypothetical figures): daily revenue report, 40M source rows, $8.2M total. Overnight the output lands 40M rows but sums to $8,212,400 against a source control total of $8,200,000. Delta = $12,400 = 0.15%, above the 0.1% threshold → page. Row count matched, so a count-only check would have passed. That gap is the whole argument for control-total reconciliation over row counts.

Trade-offs

Incremental vs full rebuild. Incremental is cheap but drifts silently; a full rebuild reconciles but costs. Deciding criterion: if reconciliation delta breaches threshold twice in a week, schedule a weekly full rebuild and compare its cost against the cost of shipping wrong numbers. At, say, $3/credit and a 6-credit rebuild, that's ~$18/week: usually cheaper than one bad decision.

Freshness vs cost. Running every 15 minutes instead of hourly multiplies warehouse credits roughly 4x for a report nobody reads before 09:00. Match cadence to the consumer's actual read time, not to the source's arrival rate.

Failure modes and detection

  • Silent partial load: job succeeds, half the partitions missing. Detected by completeness vs source control count, not job status.
  • Join fan-out: a duplicate key inflates rows 3x and double-counts revenue. Detected by duplicate rate > 1.0.
  • Late data after publish: numbers restate after the dashboard was read. Detected by late-arriving rate plus a restatement log.
  • Cost creep: an unpartitioned scan fans out. Detected by cost-per-output-row trend, not by the monthly bill.

Closing judgement

If I could keep only two, it's freshness lag and reconciliation delta, segmented by output table and owning team. Everything else is diagnostic depth for when those two fire.

Curated: · Written: · Reviewed:

Difficulty: Medium