Skip to content
Tech Interview Prep
Technical interview guide

ETL vs. ELT

Transform-before-load versus load-then-transform, and why modern warehouses shifted the order.

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

Scope: BigQuery documentation current 2026-08-31; Apache Spark 4.2; Apache Airflow stable current 2026-08-31; Apache Iceberg and Parquet current 2026-08-31; PostgreSQL 18.

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

A team has a fixed monthly revenue report and a second team exploring semi-structured clickstream events. Compare schema-on-write ETL and schema-on-read ELT for this use case on data quality and query performance.

Answer

Core. Split the estate by contract strength, not by tool preference. The revenue report has a known schema, a named consumer and a correctness obligation: write the schema at ingest. The clickstream exploration has unknown questions and no consumer contract: land the bytes raw and apply a schema at read time. The mistake is picking one of them for both workloads.

What actually differs. Schema-on-write validates and types at the boundary: the loader rejects or quarantines a record that does not match, and the sink stores typed columns with per-column statistics. Schema-on-read stores what arrived (JSON, or Parquet written by the producer) and applies types inside each query.

schema-on-write (ETL)schema-on-read (ELT)
where types are enforcedingest jobevery query
new field arrivespipeline change, often a backfillvisible immediately
bad recordrejected or quarantined at the boundary, countedquery error, or a silent NULL
pruningcolumn stats and partition pruningonly if the file format carries stats
who owns correctnesspipeline ownerevery consumer

Query performance. Parquet keeps min/max statistics per column chunk, so a filter on event_date skips row groups before their bytes are read. Raw JSON carries no such statistics: every query parses every byte it scans. BigQuery on-demand pricing bills bytes scanned ($6.25 per TB in US multi-region at the time of writing), so this lands directly on the bill.

Illustrative arithmetic: 2 TB/day of raw events, a dashboard over 30 days. Reading raw JSON scans 60 TB → $375 per run. The same events written to Parquet partitioned by date and clustered by user_id, with the dashboard touching 400 GB → $2.50. Same data, same question, roughly 150× the cost. The absolute numbers are hypothetical; the ratio is what pruning alone buys you.

Data quality. Schema-on-write gives one enforcement point and one place to count rejects. Schema-on-read gives none. Consumer A reads user_id as INT64, consumer B as STRING, and both queries succeed. The failure is silent: a type drift upstream turns a join key into NULLs and the dashboard shows a dip rather than an error. Detect it with assertions on the read layer (Dataform assertions run as part of the pipeline and fail the run), null-rate and row-count monitors, and column-level lineage (OpenLineage) to find which consumers a drift touches.

Streaming makes schema-on-read worse. Spark Structured Streaming's JSON inference requires a full pass over the data and is documented as unsuitable for production; you supply an explicit StructType and handle the mismatched rows yourself.

When not to. Do not schema-on-write exploratory data: you will rebuild the pipeline every sprint. Do not schema-on-read anything with a contractual consumer or a regulatory obligation. The usual landing pattern is bronze raw (schema-on-read, immutable, replayable) → silver typed (schema-on-write, validated, partitioned) → gold marts, where the silver step pays the validation cost once instead of on every query.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Choose ETL, ELT, or hybrid for a new analytics platform.

Answer

What I'd say in the first two minutes

Default to ELT, with a thin ETL pre-stage in front of it. Land source-shaped data in the warehouse, transform with SQL/dbt where the compute already is, and put a narrow extraction-side stage in front only for fields that legally or operationally cannot cross the landing boundary. I'd flip to full ETL only when the source system itself is the binding constraint: a production OLTP database that can't absorb the read load, or a residency rule that forbids raw rows from landing at all.

Why ELT wins by default

Separating storage from compute is the whole mechanism. Snowflake, BigQuery and Databricks let you size a warehouse per workload and pay per query, so a transformation that scans 2 TB costs credits, not a permanently running Spark cluster. You also keep raw history, which is what makes replay cheap: source databases retain binlogs or CDC streams for days, not years. If a transform has a bug, ELT re-runs SQL against landed history; ETL has to re-extract from the source, which means a full scan against a production replica you probably can't afford to run.

Where each fits

ETLELTHybrid
Transform runsstaging clusterwarehouseexclusion/validation at source, rest in warehouse
Raw history keptnoyesyes, minus excluded fields
Replay costre-extract from sourcere-run SQLre-run SQL
Choose whenminimization/residency forbids raw landing, or source compute is cheap and target is expensiveelastic target compute, SQL-literate team, several consumersregulated fields plus analytics

Failure modes and how I'd catch them

  • Raw landing of PII. Detect with a column-level lineage and tagging scan in the catalog. The cost shows up later: a GDPR erasure request now has to delete from every downstream model, not just the landing table.
  • Source-side transform saturating OLTP. Detect via CDC replication lag: Debezium exposes MilliSecondsBehindSource; alert above 5 minutes. A heavy extraction job that pushes lag to 30 minutes is a production incident, not a pipeline delay.
  • Deletes never propagated. Append-only ELT leaves phantom rows. Detect with a nightly row-count reconciliation between source and landing; 0.1% drift on a 500M-row table is 500k stale rows feeding dashboards.
  • Over-partitioned landing. Small files inflate bytes-scanned per query. Detect in the warehouse query history and watch cost per dashboard refresh, not just runtime.

Illustrative arithmetic (list prices, order-of-magnitude only)

2 TB/day of CDC, 30-day raw retention = 60 TB stored. At roughly $23/TB/month that's about $1,380/month of storage. A full dbt rebuild scanning 60 TB on BigQuery on-demand at $6.25/TB is about $375; daily incremental at 2 TB is about $12.50. The ETL alternative needs a cluster sized for the peak 2 TB/day transform plus a second copy of the data: the storage and compute you avoid is the argument, and it's checkable against your own numbers.

What I'd lock down either way

Contracts on schema and change semantics, explicit handling of late-arriving and deleted rows, atomic publication so consumers never read a half-built model, and lineage that ties every curated column back to a source field. Then pilot two representative flows and measure end-to-end correctness, latency, recovery time and cost before committing the whole platform.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Decide between batch, micro-batch, and continuous streaming.

Answer

What you say first (60-120 seconds)

Ask one question before anything else: what is the deadline between an event happening and a decision being taken on it? Then take the cheapest mode whose p99 freshness at peak beats that deadline, and check that the sink, the state and the on-call team can hold that mode's semantics. Three bands fall out:

ModeShapeFreshness at peak (illustrative, 40k events/s)Recovery unitSink requirement
Batch: hourly Spark job over Parquet on object storage, 12 min runtimebounded input, one output partition per run60 min window + 12 min run = about 72 minrerun the same partitionidempotent partition overwrite
Micro-batch: Spark Structured Streaming, trigger processingTime = 1 minute, batch takes 20 srepeated bounded execution, 1,440 commits/dayabout 80 sreplay from the last committed batchengine checkpoint plus transactional table (Delta or Iceberg)
Continuous: Flink with a 10 s checkpoint, or Kafka Streams with its 30,000 ms default commit.interval.msper-event processing, state in the operator100-300 msrestore checkpoint, replay inputtwo-phase-commit sink, or idempotent upsert on event key

The numbers are illustrative; the derivations are what you defend. Micro-batch p99 = trigger interval + batch duration, so the moment batch duration exceeds the trigger you stop keeping up and latency grows without bound until parallelism or partition count increases. Continuous latency is per-event, but its duplicate window equals the checkpoint interval. Batch freshness is the partition window plus job runtime and nothing else.

Why micro-batch creates small files

Every commit writes one file per writer task per active table partition. A 1-minute trigger with 8 writer tasks and no compaction writes 1,440 * 8 = 11,520 files per day per table. File listing and planning scale with file count, so a reader pays seconds of planning over 10k files before reading a byte. Watch Delta's DESCRIBE DETAIL numFiles or Iceberg's files metadata table; fix it with scheduled OPTIMIZE or rewrite_data_files, or a longer trigger if the deadline allows.

Why continuous is expensive: recovery, not latency

A job checkpointing every 10 s restores operator state from object storage and replays the input topic from the offset recorded in that checkpoint. With 4 GB of RocksDB state and a 100 MB/s restore budget that is roughly 40 s before the job is back at the head of the topic, and scoring is blind for that whole window. Kafka Streams has the same shape with a larger default window. So the sink must be transactional (Flink two-phase-commit sinks) or every write must be idempotent on event key, because the checkpoint interval is exactly the duplicate window. Batch has no equivalent: a bad partition is simply rerun.

Failure modes and their signals

  • Backpressure: batch duration exceeds the trigger in StreamingQueryProgress, or consumer-group LAG climbs. Freshness drifts with traffic rather than erroring.
  • Late data: a 5 s watermark drops anything older in event time. Watch numLateRecordsDropped in Flink, or numRowsDroppedByWatermark in Spark, and route drops to a side output instead of silently losing them.
  • Poison record: one bad message fails the micro-batch, the retry reads the same offsets, and progress stops flat. Dead-letter it and skip the offset.
  • Checkpoint cost: 10 s checkpoints against object storage are 8,640 small writes a day, and throttling there lengthens the restore window that decides whether continuous can serve the deadline at all.

Putting it together

Fraud scoring with a 2 s deadline at a 40k events/s peak: micro-batch on a 1 s trigger takes 3 s per batch at peak, so p99 lands near 4 s and misses. Continuous is the answer, plus a cheap fallback rule path during the roughly 40 s restore. The daily chargeback report off the same events stays batch, because its deadline is hours. Hybrid is the normal end state: stream into a durable log for the low-latency consumers, build the curated models in periodic batches.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Build an idempotent incremental batch pipeline.

Answer

Core answer (first 90 seconds)

An idempotent incremental batch pipeline has one invariant: re-running any window produces the same target state as running it once. Everything else follows from two decisions, where the source position lives, and how rows are keyed.

Assume a Postgres source, a warehouse target, nightly runs, ~2M rows/day, and an updated_at column the application maintains. Say that assumption out loud: if the source has no reliable monotonic column, you need CDC or a snapshot diff, not a watermark scan.

The two decisions that decide correctness:

  1. The watermark lives in the target and commits in the same transaction as the data. Not in a separate state store, not written before the load.
  2. Rows are keyed by business key plus source version: never by run id or ingest time.

Why the watermark must share the commit

Write the watermark first and the load then fails: the next run starts past data you never loaded. Silent loss. Write it after and a crash in between reprocesses a window, which is safe only if the load is idempotent. One transaction removes the choice.

Commit ambiguity is the case that makes this concrete. The client sends COMMIT, the server commits, the TCP connection drops before the ack returns. The client cannot tell success from failure. With watermark and data in one transaction, the retry re-reads the same window and upserts the same rows: a no-op. With a separate state store, the retry either double-loads or skips.

SQL
BEGIN;
INSERT INTO dim_orders (order_id, version, amount, updated_at)
SELECT order_id, version, amount, updated_at FROM staging_orders
ON CONFLICT (order_id) DO UPDATE
  SET amount     = EXCLUDED.amount,
      version    = EXCLUDED.version,
      updated_at = EXCLUDED.updated_at
  WHERE dim_orders.version < EXCLUDED.version;
UPDATE pipeline_state
   SET watermark = (SELECT max(updated_at) FROM staging_orders)
 WHERE pipeline = 'orders';
COMMIT;

The WHERE dim_orders.version < EXCLUDED.version is what makes a replay a no-op: an older version arriving late cannot overwrite a newer one.

Why processing-time identity breaks

If the target key is (run_id, order_id), or you stamp ingest_time, a retry inserts a second row for the same logical order. Dedup then has to happen downstream, forever. Keying on order_id with a source version makes the second write collide and update in place.

Late updates and the lookback window

updated_at is set by the application clock. A transaction that commits at 10:00:05 can carry updated_at = 09:59:58 if the app clock lags or the transaction ran long. A watermark of 10:00:00 skips it. So each run re-reads [watermark - 15 min, now]. At 2M rows/day that is roughly 20k extra rows per run: cheap. If source clock skew exceeds 15 minutes, widen the window or move to log-based CDC.

Deletes

A hard DELETE leaves no row to scan, so an updated_at watermark never sees it. Three options, in order of preference: a soft-delete flag in the source (cheap, exact); periodic anti-join reconciliation of full key sets (correct, costs a full scan); CDC (exact, but you now own a log consumer). Pick soft-delete unless the source team refuses.

Choosing the position

PositionCatches deletesLate updatesCost
updated_at watermarkNoLookback windowCheap
Monotonic idNoNo (ids are ordered)Cheap, misses updates
Snapshot idYes (diff)YesFull scan per run
Log position (CDC)YesYesLog consumer to operate

Use a watermark when the source maintains updated_at and deletes are soft. Move to CDC when you need deletes, sub-minute latency, or the source cannot guarantee clock ordering.

Failure modes to test

Crash before extract; crash after extract before commit; commit ambiguity; duplicate input; late update; hard delete; two concurrent runs. The concurrent-run case is why the watermark update should take a row lock (SELECT ... FOR UPDATE on pipeline_state) or the job should hold an advisory lock: otherwise two runs read the same watermark and both load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design orchestration for reliable batch transformations.

Answer

First 90 seconds. Assumptions: hourly or daily partitioned batch, a warehouse like Snowflake or BigQuery, Airflow 2.x as the scheduler, and tables large enough that a full rewrite costs real money. The answer I'd give: model datasets and their contracts, not a chain of scripts. Each task declares bounded inputs and outputs, a code version, an owner, a timeout, a retry policy, an idempotency key, quality checks and cleanup. Dependencies follow data availability, not clock delays. Publication is atomic so a half-finished run stays invisible. Retryable failures retry; deterministic bad data quarantines. Backfills run isolated from live traffic. A green DAG is execution evidence only: reconciliation decides success.

That contract, in Airflow 2.x:

Python
@task(
    retries=3,
    retry_delay=timedelta(minutes=2),
    retry_exponential_backoff=True,
    max_retry_delay=timedelta(minutes=20),
    execution_timeout=timedelta(minutes=45),
    pool="warehouse_etl",   # caps concurrent warehouse sessions
)
def transform(ds=None): ...

Now the three decisions I'd actually argue about.

1. How you wait for upstream. A poke-mode sensor holds a worker slot for the entire wait. Airflow's defaults are poke_interval=60 seconds and timeout=604800 (7 days), so one stuck sensor can pin a slot for a week. mode="reschedule" releases the slot between pokes. Arithmetic: 40 poke-mode sensors against the default pool of 128 slots is survivable; two such DAGs plus a backfill and you are queueing behind sensors, not doing work. If the producer can emit an event: an S3 notification, a Kafka topic, an Airflow dataset (2.4+): schedule off that instead. You lose the polling latency floor and the slot cost, and pay by coupling the producer to the orchestrator.

2. How you publish.

publicationreader-atomiccostgotcha
CREATE OR REPLACE TABLE (BigQuery, Snowflake)yesfull rewritedrops the table's ACLs and column policies; views bound to it break
partition overwrite (INSERT OVERWRITE PARTITION, Spark/Hive)per partitionrewrite one partitionwhole-table readers see mixed partition versions
MERGE on a keystatement-atomicproportional to changed rowsneeds a trustworthy key; rollback needs time travel or a clone

Staging plus swap is the default when the table is large and readers must never see a partial state. If the table is a few GB, CREATE OR REPLACE is cheaper to operate and the ACL breakage is a one-time fix: that is the case where I'd skip the staging dance.

3. Retry versus quarantine. Retry timeouts, 5xx and throttling, with exponential backoff and a cap. Do not retry schema drift, a null in a NOT NULL column, or a 401/403: those are deterministic, and three retries only delays the alert by the backoff window. Quarantine the bad partition with the offending rows and the run id, and leave the checkpoint where it is.

Failure modes and how I'd catch them: kill a task mid-write (staging table is orphaned, published table unchanged); restart the scheduler (idempotent partition overwrite makes the rerun a no-op); fire the trigger twice (same); deliver upstream late (sensor timeout fires, alert on it); expire a credential (auth error, no retry); run a backfill concurrently with live (separate pool, max_active_runs=1). The silent one is an empty output passing a row_count >= 0 check: assert a floor, and alert on failed, late, skipped, stale and unexpectedly empty outputs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Choose partitioning, clustering, and file layout for analytics data.

Answer

What I'd say in the first two minutes

Assume a 40 TB append-mostly event table in Iceberg on S3, read by Trino and Spark, 3 years retained, ~90% of queries filter a date range plus a tenant, ~5% are point lookups by user_id. Under those assumptions: partition by day, sort within each partition by (tenant_id, event_time), and write 128–512 MB zstd Parquet files.

Partitioning is the coarsest pruning you get and the most expensive thing to change, so it should match the predicate that appears in almost every query. 40 TB / 1095 days ≈ 36 GB per day: well above the ~1 GB floor where a partition earns its keep. Hourly gives 1.5 GB partitions and 24× the metadata; partitioning by user_id gives millions of directories and turns every query into a listing problem.

Clustering is the finer lever and it's cheap to rewrite. Sorting each day's files by tenant_id makes the Parquet min/max stats on that column useful, so a single-tenant query skips files instead of scanning the partition. File size is a parallelism knob: Spark's spark.sql.files.maxPartitionBytes defaults to 128 MB, and Iceberg's write.target-file-size-bytes defaults to 512 MB. Pick a target in that band so each file is one or a few tasks, not one giant task and not a thousand tiny opens.

Worked case

Query: WHERE event_date BETWEEN '2024-03-01' AND '2024-03-07' AND tenant_id = 'acme'.

  • Day partitioning prunes to 7 partitions out of 1095: 7 × 36 GB = 252 GB of candidate data.
  • At 512 MB files that's ~73 files per day, ~510 files in range.
  • acme is ~4% of daily rows and the sort makes its rows contiguous: 4% × 36 GB ≈ 1.5 GB, roughly 3 files per day, ~21 files total.
  • So the scan is ~10 GB instead of 252 GB: a ~25× reduction from clustering on top of the ~150× from partitioning.

Trade-offs

LayoutWins whenLoses when
Partition by day, sort by tenantMany tenants, date-ranged scans, late dataSingle-tenant full-history scans
Partition by tenant, then dayFew large tenants, tenant-scoped queries50k tenants → 50k × 365 dirs; cross-tenant analytics
No partitioning, sort onlySmall tables, unpredictable predicatesAny table where a date filter is near-universal

I'd switch to tenant-first partitioning only if tenant count is in the hundreds and nearly every query is single-tenant. If event time and arrival time diverge, partition on event date and let late data land in its correct partition; processing-time partitioning forces retention and event-time queries to scan everything.

Failure modes and how I'd catch them

  • Small files from streaming micro-batches: track median file size per partition; alert below 64 MB or above ~1000 files/partition, then run Iceberg rewrite_data_files compaction.
  • Skew: one tenant at 40% of rows makes one Spark task run 10× the median. Watch the p99/p50 task-duration ratio per stage; if it exceeds ~5, add a salt or split that tenant's sort key.
  • Hot partitions: a single day taking disproportionate scan bytes after a backfill. Monitor bytes scanned per partition and rebalance.
  • Drifting predicates: a new dashboard filtering on a column nobody sorts by. Re-check the top queries quarterly; clustering is cheap to change, partitioning is not.

Migrate layout by writing a new table and atomically swapping the pointer, not by rewriting in place. Physical design changes how fast the answer comes back, never what the answer is.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design a CI/CD and testing strategy for transformation logic in an ELT pipeline, including version control, unit tests, and deployment of SQL models.

Answer

Assumptions first. SQL-first ELT on a warehouse (BigQuery + Dataform is the concrete case), transformations expressed as versioned SQL models with a declared dependency graph, orchestrated by Airflow. If transformations are PySpark, the same shape holds but unit tests run on local Spark with fixture DataFrames.

The core answer: treat transformation logic as application code. One Git repo holds models, tests, and config. Every change goes through a PR. CI compiles the full project and runs tests against a small fixture dataset; merge to main triggers a deploy that publishes the compiled DAG to prod.

1. Version control and environments

  • One repo, one directory per layer (staging/, marts/), CODEOWNERS on marts so a finance model can't be changed by anyone.
  • Environments are separate datasets/projects (analytics_dev, analytics_staging, analytics_prod) with the same code and different dataform.json targets. Never branch-per-environment: that is how prod drifts from main.
  • Pin the tool version (Dataform CLI, dbt version) in the repo. A compiler upgrade changes generated SQL; it should be a reviewed PR, not a silent CI bump.

2. Testing pyramid

LayerWhat it catchesCostWhere it runs
Unit test on fixture rowsLogic errors: wrong join key, off-by-one on a window frame, NULL handling in a CASEmsEvery PR, local
Schema/contract testColumn type or name drift, missing columnmsEvery PR
Data test (not-null, unique, accepted values, referential integrity)Bad data in prod, broken upstreamseconds–minutesEvery PR on sample, every run on prod
ReconciliationRow count and sum deltas vs sourceminutesPost-deploy, scheduled
FreshnessStale upstreamsecondsScheduled

Unit tests are the ones teams skip and the ones that pay. A Dataform assertion:

sql -- definitions/marts/orders_daily.sqlx config { type: "table", assertions: { uniqueKey: ["order_date", "region"], nonNull: ["order_date", "region", "gross_revenue"] }} SELECT order_date, region, SUM(amount) AS gross_revenue FROM ${ref("stg_orders")} WHERE status != 'cancelled' GROUP BY 1, 2

For logic a data test cannot reach (a refund window, a proration rule) write a unit test with literal input rows and expected output rows. Dataform and dbt both support this; if your tool does not, a small SQL fixture table in CI does the same job.

3. Deployment

CI on PR: compile the whole project (catches broken refs and SQL syntax), run unit + schema tests, run data tests against a sampled prod snapshot. Merge to main: compile, then execute the DAG in dependency order. Dataform executes models in topological order from the compiled graph; Airflow schedules the run and handles retries.

Two rules that prevent most incidents:

  • Deterministic SQL only. No CURRENT_TIMESTAMP() inside a model body: pass the run timestamp as a variable. Otherwise a re-run produces different output and your reconciliation test fails for no reason.
  • Deploy is all-or-nothing per run. If model 12 of 40 fails, downstream models must not run against a half-updated table. Dataform/Airflow dependency ordering gives you this; ad-hoc CREATE OR REPLACE scripts do not.

4. Failure modes

  • Schema drift from upstream: a source column is renamed; staging models break at compile time, not runtime, if you declare source schemas. Detect via contract tests.
  • Test flakiness on sampled data: a uniqueness test passes on a 1% sample, fails in prod. Run uniqueness and referential tests on full prod data post-deploy.
  • Silent logic change: a PR changes a filter and revenue drops 3%. Reconciliation against source totals catches it; code review alone will not.
  • Partial deploy: half the DAG updated, consumers read inconsistent state. Fix: version-scoped writes and atomic publish, or a blue/green dataset swap.

Lineage (OpenLineage) should be emitted on every run so a failed test points at the upstream model that caused it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design data quality controls for an ELT platform.

Answer

I'd assume a warehouse ELT stack: dbt on Snowflake or BigQuery, sources being Postgres CDC, Kafka topics, and a couple of vendor file drops: publishing marts hourly or daily. The first question I'd ask is which datasets have a consumer who'd notice a wrong number within a day. That answer decides where a check blocks a publish and where it only logs.

Then I'd put checks at three boundaries, each where it's cheapest to catch the failure it prevents.

Ingest, before the batch commits. Freshness on the source's own watermark, not on arrival time: max(_ingested_at) within 60 minutes of wall clock, warn at 60, error at 120. Schema drift, a new or retyped column, fails the load rather than silently nulling. A row-count band from the trailing 14 days. Dedupe on the natural key, because Kafka is at-least-once and CDC replays after a connector restart.

YAML
# models/staging/_sources.yml — dbt 1.7
sources:
  - name: raw_orders
    loaded_at_field: _ingested_at
    freshness:
      warn_after:  {count: 60,  period: minute}
      error_after: {count: 120, period: minute}
    tables:
      - name: orders
        columns:
          - name: order_id
            tests: [unique, not_null]
          - name: customer_id
            tests:
              - not_null
              - relationships:
                  to: ref('stg_customers')
                  field: customer_id

Transform, before publish. dbt tests run in the same job as the model, so a failed relationships test stops the mart from being swapped in. Business invariants go here: debits equal credits per journal batch, shipped_at >= ordered_at, no order state going backwards across snapshots.

After publish. Volume and distribution monitors on the published table: Great Expectations or Elementary, or a scheduled query if you don't want another dependency. These catch what the first two can't: a source that's fresh and well-formed but semantically shifted.

Why two volume checks and not one. Trailing 14 days of daily order counts: mean 4.2M, σ 180k, so a ±3σ band is 3.66M–4.74M. A CDC connector that drops a WAL segment and loses the last 6 hours lands at ~3.15M: outside the band, it fires. Lose 2 hours and you land at ~3.85M, inside the band, and volume says nothing. The freshness check on max(_ingested_at) catches that one. Neither check alone covers both.

Trade-offs. Blocking a publish costs a downstream SLA; publishing bad data costs a wrong decision and a backfill. I'd tier: revenue, billing and anything feeding an external report hard-fail and page; internal analytics warn and quarantine the partition, keeping the last coherent version live; exploratory tables log only. A hard fail on a 0.2% null rate in a marketing attribution table is not worth waking anyone. And I'd skip the expensive checks (full-table reconciliation, cross-source joins) on intraday runs, running them on the daily load instead.

Failure modes I'd expect, with the signal that catches each:

failuresignal
source feed truncatedfreshness on max(_ingested_at) lags wall clock
partition never arrivedexpected-partitions check against a calendar table
duplicate CDC replayunique test on the natural key after dedupe
schema driftload fails on unexpected column type
silent semantic shiftdistribution monitor on a key measure

Metrics: rule coverage per tier-1 dataset, time to detect, time to correct, recurrence of the same rule, and consumer-reported incidents. A green suite over a source that stopped loading is worse than a red one, so I'd alert on checks that haven't run as loudly as on checks that failed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Handle schema evolution without silently corrupting analytics.

Answer

Assumptions: Kafka + Avro with Confluent Schema Registry, consumers landing into Snowflake or Iceberg, producers and consumers deployed independently.

The answer: the schema is a versioned contract, and the registry enforces only its structural half. Every change is either provably compatible under a declared compatibility mode, or it is a new field with a dual-write and a backfill. Anything that changes what an existing field means (units, nullability semantics, delete semantics) gets a new field, never an in-place edit, because no registry check can see it.

How resolution works. Avro prefixes each record with a magic byte 0x00 and a 4-byte schema ID; the consumer fetches the writer schema by ID and resolves it against its reader schema. Resolution is by field name (aliases cover renames), with reader defaults filling fields the writer omitted. Promotions are one-directional: int→long→float→double, string↔bytes. Protobuf resolves by field number, so renames are free and renumbering is fatal: reserve removed numbers. The registry's check is a schema-pair comparison; it has no idea what the numbers mean.

ChangeRegistry verdict (BACKWARD default)Silent-corruption risk
Add optional field with defaultAcceptedNone
Add required fieldRejected—
Remove fieldAcceptedOld consumers read the default or fail; check FORWARD
Rename fieldRejected unless alias addedAvro: alias fixes it. Protobuf: free
int → longAccepted (promotion)Silent if the unit changed
long → intRejectedTruncation if forced
Add enum symbolAcceptedProtobuf preserves the raw number; consumers with no default branch misclassify it
Remove enum symbolRejectedOld data containing the symbol no longer resolves
seconds → milliseconds, same typeAccepted: schema is unchanged1000x, nothing throws

Compatibility modes. BACKWARD (the default) means the new schema reads old data, so consumers upgrade first. FORWARD means old consumers keep reading new data, so producers upgrade first. FULL allows either order. The _TRANSITIVE variants check against every previous version, not just the last: use them when consumers may be several versions behind. FULL_TRANSITIVE is the right default for a topic with many independent consumers; the cost is that you can no longer remove fields.

Worked trace: unit drift. v1 declares {"name":"event_time","type":"int"} in seconds. v2 declares the same field as long in milliseconds. int→long is a legal promotion, so the registry accepts it under BACKWARD and nothing errors.

10M old rows carry event_time = 1_700_000_000; 1M new rows carry 1_700_000_000_000. A consumer upgraded to v2 assumes milliseconds and divides by 1000:

  • old row: 1_700_000_000 / 1000 = 1_700_000 s → 1970-01-20T16:13:20Z
  • new row: 1_700_000_000_000 / 1000 = 1_700_000_000 s → 2023-11-14T22:13:20Z

The 2023-11-14 count drops from 10M to 1M and a 1970-01-20 bucket appears holding 10M rows. A consumer still on v1 reading new data throws (long→int is not a legal demotion), so the old consumers fail loudly while the upgraded ones corrupt silently: the reverse of the usual intuition.

Fix: add event_time_ms (long, logical type timestamp-millis), dual-write both fields for one release, backfill the warehouse, migrate consumers, then drop event_time under FULL_TRANSITIVE.

Detection. The registry catches structure, not meaning, so add a plausibility assertion on the field: event_time within [now - 7d, now + 5m] trips on the first shifted record. Track record counts and consumer lag per schema ID: a consumer still on ID 41 while producers are on 47 is an unfinished migration. Run the new and old consumers over the same window and diff the aggregates before promoting. Watch for date buckets outside the data's range, null-rate shifts, and DLQ volume.

Failure modes. TopicNameStrategy puts every event type on a topic into one subject, so compatibility checks compare unrelated schemas: false rejections, or a pass that means nothing; use RecordNameStrategy when a topic carries multiple types. A producer that bypasses the registry (auto.register.schemas=false with an unregistered ID, or a second registry) hands consumers an ID they cannot resolve. And the registry sits on the read path: clients cache writer schemas, but a cold consumer with the registry down fails to deserialize.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Build a data contract between an operational producer and analytics consumers.

Answer

Clarify first: is the producer an operational service emitting order events to Kafka, and are consumers dbt models and dashboards? I'll assume yes. A data contract is a versioned artifact in the producer's repo, enforced in CI and the schema registry. Build it backwards from consumer decisions, not forwards from producer tables.

Start with the three decisions the contract must support: daily revenue by region, fulfillment SLA, and fraud review. For each, write the grain, identity, and dedupe key. For orders, grain is one row per order_id per event_type per version. Dedupe key is (order_id, event_type, version). Then negotiate service levels: freshness p99 under 15 minutes, completeness 99.9% of events with event_time in day D arriving by 06:00 UTC D+1, volume around 2M events/day. These are hypothetical but realistic; the producer signs off on them.

Encode machine-testable schema and selected invariants near production. A Confluent Schema Registry with Avro or Protobuf enforces structure and compatibility mode. Use BACKWARD compatibility for additive changes. Semantic documentation and examples live next to the schema. Here is a contract snippet:

YAML
contract: orders.v2
owner: payments-platform
consumers: [revenue_daily, fulfillment_sla]
grain: one row per order_id per event_type per version
freshness_p99: 15m
completeness: 99.9% by 06:00 UTC
fields:
  order_id: {type: string, nullable: false}
  event_time: {type: timestamp, timezone: UTC, nullable: false}
  event_type: {type: enum, values: [created, paid, shipped, cancelled], nullable: false}
  amount_cents: {type: int64, nullable: true, unit: cents, currency: USD}

The contract also states producer guarantees and consumer responsibilities. Producer guarantees: at-least-once delivery, replay for 7 days, late data up to 24 hours. Consumer responsibilities: dedupe on the key, take the latest event_time for a given key, tolerate null amount_cents, and handle corrected events. Trace a late event: producer emits order_id=123, event_type=paid, event_time=2025-01-01T10:00Z, amount_cents=4500. Consumer's dbt incremental model runs at 10:05 and sees it. At 10:30, producer replays a corrected event with the same dedupe key but amount_cents=5000. If the consumer dedupes and takes latest event_time, final amount is 5000. If it appends, revenue sums to 9500. Detection: dbt test unique_combination_of_columns on the dedupe key fails, or row count anomaly. Cost: two hours to backfill, three dashboards wrong for a day.

Concrete failure modes. First, semantic drift without schema change: producer changes event_type=paid to mean payment initiated, not settled. Schema registry passes because the enum is unchanged. Detection: dbt accepted_values test plus a business metric anomaly, e.g. revenue drops 12% against forecast. Second, freshness breach: Kafka consumer lag exceeds 15 minutes. Detection: Burrow or a Kafka lag exporter alert. Cost: SLA dashboard stale, on-call paged. Third, nullability change: producer makes amount_cents nullable. Registry BACKWARD allows it. Consumers break on null. Detection: dbt not_null test fails. Fourth, ownership gap: a central platform owns the schema but has no business authority. Detection: change review has no business approver.

Change proposals include impact and lineage, compatibility classification, migration window, dual version or adapter, backfill, acceptance evidence, and rollback. Validate before publication with dbt tests and Great Expectations. Monitor service objectives and breaking drift. Link failures to incident handling. Trade-offs: strict contracts slow producer velocity, so start with critical datasets and use deprecation windows. A schema registry enforces structure but cannot infer whether a field's business meaning changed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Implement lineage that remains useful during incidents and change.

Answer

Assumptions and core answer

Assume batch plus streaming, at least two engines (a warehouse and Spark), some pipelines in custom Python, and a catalog that is already partly populated. Lineage has two jobs during an incident: forward ("what reads this column, and what breaks if I change it") and backward. "what produced this number, and what changed since yesterday". Both must be answerable in minutes from a graph that admits where it is incomplete.

The core answer: emit lineage as events from the systems that already know the truth (orchestrator, engine, transformation framework), key it on stable dataset identifiers, and reconcile the emitted graph against query logs and storage inventory so gaps are visible. Do not hand-maintain a diagram.

Mechanism

Identity first. Every dataset gets a URN of namespace plus name that survives renames: a rename is an event on the same node, not a new node. OpenLineage's RunEvent carries eventType (START/RUNNING/COMPLETE/FAIL/ABORT), eventTime, producer, and job/run/dataset facets; the dataset facets carry schema, dataSource, ownership, lifecycleStateChange (CREATE/ALTER/DROP/OVERWRITE/TRUNCATE) and columnLineage, which maps each output field to the input fields it derives from. The event shape is roughly {eventType, eventTime, producer, job{namespace,name}, run{runId}, inputs[], outputs[]}. Marquez is the reference implementation that stores these events; DataHub ingests the same events through its OpenLineage endpoint. Airflow's OpenLineage provider emits one RunEvent per task, Spark through a query listener, dbt from the manifest, so most of the graph arrives without anyone writing lineage code.

Custom code, file movement, notebooks, exports and reverse ETL emit the same RunEvent shape rather than a bespoke format, so one graph holds everything.

Column-level is where the cost lives. Parse SQL when it is static; when the query is templated or built dynamically, fall back to dataset-level and mark the edge as coarse. That mark is the decision trigger:

situationaction
change is column-scoped and every downstream edge is column-leveltrust the graph, notify from it
change is column-scoped but any critical consumer edge is dataset-levelscan query logs for the column name before notifying
dataset has zero downstream edges but nonzero read counts in the query logtreat as uninstrumented, not unused

Worked trace (hypothetical)

orders.total_amount is renamed to order_total. The graph returns 3 column-level consumers (a dbt model, a Spark job, a reverse-ETL sync) and 9 dataset-level consumers. Because the change is column-scoped and 9 edges are coarse, the trigger fires: a 7-day query-log scan for total_amount finds 2 more readers, a notebook and a BI extract, that never emitted events. Freeze the rename, notify 14 consumers, backfill the 2 unregistered ones, then add instrumentation before re-running.

Failure modes

Silent gaps: dynamic SQL produces no parseable lineage. Detect by comparing emitted edges to query logs and alerting on datasets with reads but no downstream edges. Stale edges after a rename or table swap: detect via lifecycleStateChange events and URN resolution failures, and version the graph so an incident can be replayed against the graph as it was. False completeness: a dataset-level edge rendered as if it were column-level. Never let the UI flatten the two. Metadata is sensitive: SQL text, column names and samples leak business logic, so restrict who can mutate the graph and keep event provenance (producer, eventTime) so a bad edge can be traced to its emitter.

Lineage accelerates reasoning; it does not prove data correctness or enumerate every use. Say that out loud during an incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design a change-data-capture pipeline from a transactional database.

Answer

The 90-second answer. Assume a Postgres 14+ source, we can't add latency to the write path, and the target is a Kafka topic feeding both a warehouse and an operational read model. I'd run Debezium over pgoutput logical replication: create the replication slot, take the initial snapshot inside a single REPEATABLE READ transaction, record the WAL position that transaction is consistent with, then stream from exactly there. Land everything append-only in Kafka keyed by primary key, and merge into current-state tables downstream with an idempotent upsert on (pk, lsn). History lives in the raw topic; the read model is derived from it.

Why log-based, and when not to.

approachlatencysource costcatches deletespick it when
logical replication (Debezium)~100 ms–1 sWAL retention + one slotyesdefault for an OLTP source you control
trigger-based audit tablesame transactionroughly doubles write path, row-lock contentionyesno logical replication available (older MySQL, some managed services)
dual-write from the appimmediatenone on the DB, but no atomicityonly if the app emits itnever as the primary path
batch reconcile on updated_atminutes–hoursfull scansno, unless soft-deletebackfill, or a nightly correctness check

Dual-write is the one people reach for and the one that breaks: the DB commit and the Kafka produce aren't atomic, so a crash between them loses or duplicates a change with no way to tell which happened.

How snapshot and position actually line up. The gap/overlap problem is real. Snapshot at T0 and start streaming at T1 > T0 and changes in (T0, T1] are gone; start at T1 < T0 and you replay. Debezium avoids it by creating the slot first, so WAL from before the snapshot is pinned, then taking the snapshot in a repeatable-read transaction and recording the position that transaction's view is consistent with. The invariant:

t0  create slot 'debezium' (pgoutput)   -> WAL pinned from L0
t1  BEGIN ISOLATION LEVEL REPEATABLE READ; read tables  -> view consistent at L1 >= L0
t2  COMMIT; connector records L1 as stream start
t3  stream from L1  -> nothing in [L0,L1] is skipped (slot held it), nothing before L1 is replayed

Numbers. A source doing 2,000 tx/s at ~400 bytes of WAL each generates ~0.8 MB/s, ~69 GB/day. If the connector dies and nobody notices, the slot holds all of it. max_slot_wal_keep_size defaults to -1 (unlimited) on PG13+: set it to something like 50 GB so the slot is invalidated rather than filling the disk. max_replication_slots defaults to 10. Debezium's heartbeat.interval.ms defaults to 0 (off); set it to 10 s so an idle table still advances the slot LSN and lag monitoring stays meaningful.

Failure modes and how I'd see them.

  • Slot invalidated (WAL exceeded max_slot_wal_keep_size): the connector errors with "slot ... is no longer active"; recovery is a full resnapshot. Alert on pg_replication_slots.confirmed_flush_lsn lag, not just connector heartbeat.
  • TOAST / unchanged large columns: Postgres doesn't write unchanged out-of-line values to WAL, so an update event can carry a null for a column that is actually populated. Set REPLICA IDENTITY FULL on tables where you need before-images, and accept the extra WAL.
  • DDL: pgoutput doesn't emit it. Schema changes need Debezium's schema-history topic and a coordinated deploy; a column rename without it produces a stream the sink can't parse.
  • Long-running source transaction: holds the snapshot open and bloats the source. Cap with snapshot.fetch.size and watch pg_stat_activity.

What would change my decision: a managed source without logical replication pushes me to trigger-based and I eat the write-path cost; a target that only needs daily freshness makes batch reconcile cheaper and simpler than running a slot at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Plan and execute a large historical backfill safely.

Answer

What I'd say first

Assume a daily-partitioned Iceberg table on Spark, 547 partitions (2023-01-01 to 2024-06-30), ~40M rows/day, source is an append-only log in S3 with 400-day retention, and three dashboards plus one feature-store job read it. The bug: a currency conversion applied the wrong FX rate, so amount_usd is off by a fixed factor per currency.

The answer is: don't rewrite in place. Write each corrected partition to a run-scoped path, reconcile it against the source, then swap partitions in one atomic metadata commit. Throttling, cutover and rollback all hang off that.

Mechanism

Idempotency comes from the unit of work being a whole partition keyed by (run_id, date), not a row. A retried task rewrites the same deterministic path from the same input, so it produces the same bytes; the commit is a single Iceberg overwritePartitions() metadata operation, so a reader sees either the old snapshot or the new one. That is why a retry is safe, and why atomic publish prevents partial visibility: there is no window where half a partition is queryable.

Python
# Spark 3.5 / Iceberg 1.5
df = spark.read.parquet(f"s3://src/events/date={d}/") \
    .withColumn("amount_usd", fx_correct(col("amount"), col("ccy"), col("ts")))
(df.writeTo("prod.fct_orders")
   .option("overwrite-mode", "dynamic")
   .overwritePartitions())   # atomic; a retry rewrites the same partition

Reconcile per partition before the swap: row count, sum(amount_usd), and the count of rows that failed FX lookup and went to quarantine. Investigate any difference that is not explained by the known FX factor.

Trade-offs

Dual-run versus cutover. Dual-run writes a parallel table, diffs it for a day, then swaps: 2× storage and a reconciliation window, but you get a side-by-side diff. Cutover rewrites in place behind the atomic commit: cheaper, no diff. Decide on blast radius: money columns get dual-run; a null-handling fix in a non-financial column gets cutover with a 1% sampled diff. Don't backfill at all when source retention has expired (you cannot reconstruct) or when the only consumer is being deprecated: recompute forward instead.

Failure modes and detection

  • Source mutation: a source partition is rewritten after you read it. Record the S3 ETag per partition at read time and re-check at commit; the symptom is a reconciliation mismatch that moves between runs.
  • Partial commit: only possible if you write to a plain Hive directory and rename. Detect by per-partition row count against expected.
  • Schema mismatch: the source adds a column mid-run. Hash the schema per partition and fail fast on the first mismatch.
  • Cost: 21.9B rows scanned. Set a budget alarm before you start.
  • Rollback: keep the pre-run snapshot ID; CALL iceberg.system.rollback_to_snapshot('prod.fct_orders', <id>).

Arithmetic (hypothetical)

547 partitions × 40M rows = 21.9B rows; ~200 MB compressed each → ~110 GB. At 20 concurrent partitions × 3 min each, 547/20 × 3 ≈ 82 min of compute, plus reconciliation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Recover a pipeline after checkpoint or state corruption.

Answer

Assumptions to state before anything else. Kafka → Flink → warehouse sink; the sink supports upsert or transactional commit; raw events still sit in an immutable landing zone; Kafka is at its defaults log.retention.hours=168 (7 days) and offsets.retention.minutes=10080. If the sink is append-only, or the landing zone is gone, the recovery path changes: say which one applies before you answer.

First 90 seconds. Stop the job; do not restart it. Preserve the corrupted checkpoint directory (state.checkpoints.dir), the last good savepoint, Kafka consumer offsets, the sink's commit/transaction log, and the job code and config at the failing version. Then answer one question: what is the last source offset whose target output is both committed and reconciled? A green scheduler run or a checkpoint file on disk is not that answer. Replay from the earliest offset that is safe given the sink's idempotency, reconcile, then resume publication.

Bounding the boundary. Read three artefacts and compare them:

artefactvaluewhat it means
last completed checkpoint N-1partition 3, offset 1,204,553,210where Flink state stopped
sink commit logcommitted through offset 1,204,600,000where the target actually is
gap46,790 records ≈ 9.4 s at 5k events/sreplaying from N-1 duplicates these

The direction of the gap decides everything. Sink ahead of checkpoint → replay duplicates. Sink behind checkpoint → replay loses data. Never trust one side alone.

Reconcile with control totals per partition per hour:

SQL
SELECT s.partition_id,
       date_trunc('hour', s.event_ts) AS hr,
       count(*) FILTER (WHERE t.event_id IS NULL) AS missing
FROM landing.events s
LEFT JOIN warehouse.facts t ON t.event_id = s.event_id
WHERE s.event_ts >= '2024-03-01' AND s.event_ts < '2024-03-02'
GROUP BY 1, 2
HAVING count(*) FILTER (WHERE t.event_id IS NULL) > 0;

Decision triggers.

  • Sink is upsert-keyed (MERGE on event_id, or INSERT ... ON CONFLICT DO NOTHING) → replay from N-1 with a deliberate overlap; duplicates collapse. Cheapest path.
  • Sink is append-only and consumers cannot tolerate duplicates → rebuild the affected partitions into a version-scoped table (warehouse.facts_rebuild_20240301) and swap atomically once counts match.
  • Source offsets no longer exist (retention expired) → resnapshot from the source (Debezium snapshot.mode=initial on a fresh connector, or a full table copy), then resume CDC from the snapshot's LSN.

Failure modes to check before resuming. Late events arriving after the boundary; deletes that replay cannot reconstruct; schema version drift between the checkpoint and now; concurrent live ingestion writing to the same partitions. External side effects (emails, payments, webhooks) are not replayed by the pipeline: reconcile them separately against their own idempotency keys and issue compensating records.

Restore and close out. Restore state transactionally: flink run -s <savepoint> from the last good savepoint, or roll the sink back with RESTORE TABLE ... TO VERSION AS OF n (Delta) / rollback_to_snapshot (Iceberg) before replaying. Watch consumer lag and downstream freshness for one full business cycle. Then fix the cause: checkpoint durability, commit ordering, observability, and add a crash-at-every-boundary test so the next corruption is caught by a test, not by a customer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Review an ETL or ELT design for failure and recovery.

Answer

Clarify first. Batch or streaming? What's the sink: Snowflake, BigQuery, Iceberg? What freshness SLA, and what's the tolerance for a duplicate or a missing row? I'll assume a CDC-fed warehouse pipeline (Debezium → Kafka → Snowflake), at-least-once delivery, and a sink that supports MERGE.

The core answer. A failure-and-recovery review is one question asked at every boundary: what is the unit of work, and is replaying it safe? If each stage is idempotent on a stable natural key and each checkpoint is committed only after the sink commits, every failure is recoverable by replay. If not, recovery depends on a human remembering what they edited: that's the finding.

So the review has three moves:

  1. Find the commit boundary, where does "done" become durable?
  2. Prove replay is idempotent at that boundary.
  3. Prove the last coherent dataset is still queryable while you replay.

Idempotency, concretely. Kafka Connect commits consumer offsets on a timer: offset.flush.interval.ms defaults to 60000 ms. If the sink writes every 60 s and the connector dies, up to 60 s of records replay. At 5,000 records/s that's 300,000 re-delivered records (hypothetical rate). The sink has to absorb them:

SQL
MERGE INTO fact_orders t
USING (SELECT * FROM staging_orders WHERE batch_id = :batch) s
  ON t.order_id = s.order_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN UPDATE SET ...
WHEN NOT MATCHED THEN INSERT ...;

Keyed on order_id and guarded by updated_at, a replayed batch updates zero rows. Keyed on batch_id alone, it doubles the table.

Failure table. Detection and recovery, not just a list of injections:

FailureDetected byRecoveryCost
Partial extractsource count ≠ staged count for the watermark windowre-run from last committed offsetreplay window × rate
Duplicate trigger (two runs, same logical date)GROUP BY order_id HAVING COUNT(*) > 1 returns rowsMERGE dedupes; add a unique constraintnone if idempotent
Target commit ambiguity (client timeout after commit)query target for batch_idre-run; MERGE is a no-opone extra scan
Schema break (new NOT NULL column)schema-registry compatibility check fails at produceroll back schema, backfillpipeline paused
Expired binlogconnector error: position no longer availablefull re-snapshothours, source load
Stalled replication slotWAL/disk growth on the sourcedrop slot, re-snapshotsource disk

Trade-offs. At-least-once plus an idempotent MERGE is the default: cheap, one extra scan per replay. Exactly-once (Kafka transactions with isolation.level=read_committed, or a Flink two-phase-commit sink) removes the dedupe work but adds latency and couples you to the sink's transaction support: worth it only when the sink can't dedupe. Full re-snapshot is the fallback when the log is gone; correct, but it costs source load and hours.

The check that matters. After injecting each failure, confirm the last coherent dataset is still queryable and that replay needs no manual edits. If recovery requires someone to remember a fix, that's the gap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Reconcile financial data through an ETL pipeline.

Answer

What I'd say first

Before touching the pipeline I'd fix four things: which ledger is authoritative for each field, the business date and timezone (a payment posted 23:50 UTC on the 30th may belong to the 1st in the entity's local calendar), the grain (source, entity, account, currency, business_date), and what "reconciled" actually means. Count, sum, and a content hash all matching, not just row count.

Assumptions: two sources, a core banking ledger and a payments processor, roughly 50M rows/day, USD reporting with multi-currency postings, daily close.

Extract. Two options. A transaction-consistent snapshot (Postgres REPEATABLE READ with an exported snapshot, or the source's own consistent-read API) is simpler and fine when the table fits the close window. Ordered CDC (Debezium on the WAL/binlog, ordered by LSN) is what you need for near-real-time or tables too large to snapshot. The deciding criterion is whether you can get a point-in-time consistent read inside the window; if you can't, use CDC, and then you must consume transaction boundaries, because a half-committed transaction read without its commit marker looks exactly like a missing leg.

Land. Append-only Parquet partitioned by business_date, immutable, IAM-scoped. Every row carries source_id, commit LSN, ingest timestamp, and a SHA-256 of the canonical row so you can re-verify later.

Transform. Amounts as decimal(19,4), rates as decimal(38,10): never float. Rates carry their source and effective timestamp. Enforce the journal invariant sum(debit) - sum(credit) = 0 per entry.

Reconcile at three points, keyed by (source, entity, currency, business_date):

checkwhat it catchesexample
countdropped or duplicated rows82,441 vs 82,442
sumrounding, truncation, wrong rate1,234,567.89 vs 1,234,567.79
SHA-256 of sorted rowssilent value editshash mismatch

Worked break. Source control total for 2024-06-14 USD: 82,441 rows, 1,234,567.89. The pipeline lands 82,442 rows summing 1,234,612.89: off by exactly 45.00. Count fires first. Trace: Kafka is at-least-once, so one transaction was redelivered. Dedupe on (source_id, commit_lsn) makes the rerun idempotent and the second pass matches. If instead the sum were off by 0.10 with counts equal, that's a rounding or rate-timing bug, not a delivery bug: a different fix.

Corrections. Never rewrite landed evidence. Late postings after close go through an approved adjustment that appends a new version; the period is restated under sign-off.

Failure modes and detection. Duplicate delivery → count check. Missing leg → journal invariant fails. Timezone edge → business_date mismatch between source and pipeline. Rate correction → sum break on FX rows only. Partial source → control total absent, so treat the batch as incomplete and don't publish. Commit ambiguity → CDC consumed without transaction boundaries.

Trade-off. Snapshot is simpler and cheaper to reason about but stale by the snapshot lag; CDC is current but needs ordering, dedup, and commit markers. Pick snapshot unless you need sub-hour freshness or the table won't snapshot inside the window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design deletion and retention across raw and transformed data.

Answer

Say this first. Deletion is easy at the source and hard everywhere downstream. Before designing I'd pin three assumptions: (1) we carry subject-level erasure obligations (GDPR Art. 17, CCPA) and per-dataset retention clocks; (2) the estate is batch warehouse + streaming + operational stores, not one system; (3) replay and backfill exist, so deletion has to survive them. The goal is one request, one identity, every copy either deleted or provably not holding the subject.

Identity and lineage. Resolve the subject to a surrogate key once, in an identity map, and carry that key through landing, standardized, curated, features, extracts and reverse ETL. Lineage tells you which tables and partitions can contain the key. Without this, deletion is a grep across a data lake.

Mechanism, per layer.

  • Source (Postgres): DELETE FROM orders WHERE cust_id=88213 marks tuples dead; VACUUM reclaims later, VACUUM FULL returns space to the OS. WAL keeps the row until the next checkpoint.
  • Streaming (Kafka): publish a tombstone (null value) keyed by cust_id. Compaction removes it once min.cleanable.dirty.ratio (default 0.5) triggers cleaning, and the tombstone itself is retained for delete.retention.ms (default 24h). Until then, readers must filter.
  • Landing (Iceberg/Delta on S3): DELETE FROM rewrites affected files; expire_snapshots (Iceberg default cutoff 5 days) drops the snapshots that still hold the row. Delta's VACUUM defaults to a 7-day retention: set it explicitly if the obligation is shorter.
  • Curated (Snowflake/BigQuery): DELETE plus Time Travel. Snowflake standard retains 1 day; BigQuery time travel is 7 days. If the obligation forbids that window, set DATA_RETENTION_TIME_IN_DAY=0 on the table.
  • Features: delete if keyed by subject; recompute from post-deletion inputs if aggregated.
  • Reverse ETL: call the destination's delete API (Braze, Marketo) and record the external id.
  • Backups: do not mutate. Restore reapplies a suppression ledger, a small table of (subject_key, deleted_at), after the restore completes.

Trade-offs.

approachuse whencost
Hard deletesmall keyed rows, strong obligationbreaks immutability; expensive on columnar
Tombstoneappend-only streamsdata present until compaction; readers must filter
Crypto-shredper-subject key over wide datakey management; useless if the key is shared
Partition droppartition scope == subject scoperarely true for subject data

Worked trace: subject S-4471.

  1. DSAR validated; S-4471 → cust_id=88213 in the identity map.
  2. Postgres delete; row dead, WAL holds it until checkpoint.
  3. Kafka tombstone on user-events; visible until compaction.
  4. Landing partitions rewritten; expire_snapshots drops old snapshots.
  5. Snowflake delete; Time Travel holds 1 day unless retention set to 0.
  6. Feature rows recomputed from post-deletion inputs.
  7. Reverse ETL delete pushed; external id logged.
  8. Suppression ledger written; backups untouched.
  9. Completion record: counts per system, no PII.

Failure modes and detection.

  • Replay resurrects. A backfill re-reads a partition that still has the row. Detect: nightly reconciliation joining the suppression ledger against each table's subject set; alert on any post-deletion hit.
  • Late event. A stream event for a deleted subject arrives after the tombstone. Detect: consumer-side ledger check; metric late_events_after_deletion.
  • Restore reintroduces. Detect: post-restore job applies the ledger and reports the reapplied count; fail the restore if the ledger is missing.
  • Identity merge. Two subjects merged after one was deleted. Detect: block the merge if either side is suppressed.
  • Hold conflict. Legal hold on a subset. Detect: join hold table against the request; queue the request rather than dropping it silently.

Legal and privacy owners decide the obligation; engineers establish the technical truth of what was actually removed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Secure an ELT platform containing sensitive customer data.

Answer

Assumptions I'd state before designing anything: multi-tenant SaaS; ELT lands PII (email, phone, address) plus a regulated subset (card PANs or health data); sources are SaaS APIs and Postgres CDC; warehouse is Snowflake or BigQuery; consumers are analysts, BI, and reverse-ETL into Salesforce. Regimes: GDPR/CCPA, plus PCI if PANs are in scope. If any of that is wrong, the design changes: say so out loud before proposing controls.

Core answer (first 90 seconds). The durable control is not landing the sensitive value. Masking, row-level security and audit all protect a copy that already exists, and copies multiply: every extract, BI dataset, reverse-ETL sync and backup is a new exposure. So I push in this order: (1) drop prohibited fields at the extract, (2) tokenize or pseudonymize what must stay joinable, (3) encrypt and isolate what lands, (4) gate reads by purpose, (5) prove it with audit and detection. If I can only do one, it's (1).

Transformation choices, and what each costs.

NeedTechniqueWhat it costs
Join across sources on a customerDeterministic token: HMAC-SHA-256 with a key held in KMSThe key becomes the crown jewel, and the token is a stable join key that re-identifies if the key leaks
Analytics on a field, no per-row needAggregation, suppress cells below a small threshold (5 is common)Loses row-level utility
Display in BI, no exportDynamic masking / column policy (Snowflake masking policies, BigQuery policy tags)Protects only that engine's query path
Dev/testSynthetic data, or format-preserving encryption FF1 (NIST SP 800-38G)FPE keeps format but is reversible with the key

A plain SHA-256 over an email is not pseudonymization: an attacker with a dictionary of a billion known addresses precomputes the mapping. The HMAC key is what makes it infeasible, so it lives in a KMS in a separate account from the data plane: the warehouse admin must not be able to decrypt.

Access and isolation. Separate accounts/projects per environment and tenant; pipelines run as a dedicated role scoped to the schemas they load, never ACCOUNTADMIN. Purpose-based grants on raw, curated and operational metadata separately. Transport TLS 1.2+, storage AES-256 with envelope encryption and annual KMS key rotation.

Failure modes, with detection.

  • Compromised connector credential. Blast radius is every table its role can read. Detect via CloudTrail and warehouse ACCESS_HISTORY: new source IPs, off-hours queries, a spike in rows read.
  • Malicious SQL / exfiltration. A SELECT pulling raw PII to a new destination. Detect via egress-byte and rows-returned anomalies, and by scanning export buckets for PII patterns.
  • Cross-tenant join. A curated table missing a tenant predicate. Detect by comparing returned row count to the tenant's expected cardinality.
  • Masking bypass via downstream copy. A BI extract or CSV re-materializes raw values. Detect by periodic PII scanning of every export destination, not just the warehouse.
  • Deletion that doesn't delete. Time Travel (1 day by default in Snowflake), backups and reverse-ETL targets still hold the row. Detect by running the erasure request against every copy and asserting zero rows.

Trade-off to name. Warehouse-native RLS and masking apply to ad-hoc queries too, but only inside that engine; per-consumer secure views are portable but drift. Default to native policy; use views only where the engine can't express it. Secrets belong in Secrets Manager or Vault, never in orchestrator connection params or DAG code: Airflow encrypts Variables and Connections with a Fernet key, and that key is itself a secret.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design multi-tenant ELT with strong isolation.

Answer

Clarify and assume. I'll assume B2B SaaS, ~200 tenants, one tenant is roughly 40% of the rows and the rest are small, warehouse is Snowflake or BigQuery, and two tenants have contractual residency clauses. If you have 5,000 tenants, the tiering below shifts toward the pooled end.

The answer: pick isolation per tenant, not per platform. Three tiers, and a tenant moves between them as its contract or volume changes.

TierIsolationComputeBlast radius of one bugCost driver
Aaccount/project per tenantdedicated warehouse or slot reservationone tenantper-account overhead, idle compute
Bschema/dataset per tenantshared warehouse, per-tenant resource monitorone tenant's schemastorage + shared compute
Cshared table, row policy on tenant_idsharedevery tenantcheapest, highest risk

Deciding criteria, in order: a contractual or regulatory isolation clause → A. A tenant whose load would starve others (the 40% one) → A for compute even if its data stays in B. Everything else → B. C only when per-tenant objects become unmanageable, which in practice is thousands of tenants.

How the row policy is actually enforced. In Postgres:

SQL
ALTER TABLE events ENABLE ROW LEVEL SECURITY;
ALTER TABLE events FORCE ROW LEVEL SECURITY;  -- without FORCE, the table owner bypasses it
CREATE POLICY tenant_isolation ON events
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

The ETL service account usually owns the tables, so without FORCE your own loader reads every tenant. Superusers and any role with BYPASSRLS bypass regardless: check pg_roles.rolbypassrls before you trust the policy. BigQuery and Snowflake row access policies work the same way: the engine filters rows, the query author can't opt out, and a principal with no grant sees zero rows.

Set the tenant per transaction with SET LOCAL app.tenant_id = '...'. SET without LOCAL is the classic leak: under PgBouncer transaction pooling the setting survives the commit on that server connection, so the next tenant's query on the same connection reads the previous tenant's rows. SET LOCAL reverts at commit. If the GUC is unset, current_setting raises rather than returning everything, which is the fail-closed behaviour you want.

Identity. tenant_id is written by the extractor from the authenticated source credential, never inferred from the payload. Keys are composite, (tenant_id, id), so a collision across tenants can't merge rows. Every join carries tenant_id on both sides.

Failure modes and detection.

  • Policy bypass by owner or BYPASSRLS: run a canary query as the app role against a tenant with zero rows; expect zero rows, and treat any row as a page.
  • Pool leak: assert current_setting('app.tenant_id') at the top of every transaction.
  • Cross-tenant join: a CI check that every model referencing a tenant table has a tenant predicate, plus a weekly scan of the query log for joins missing it.
  • Backfill under the wrong tenant: compare per-tenant row counts before and after. This is the one that passes every schema test and every uniqueness test.

When not to. If the "tenants" are internal teams and the data isn't sensitive, schema-per-tenant is over-engineering: one tenant_id column plus the CI check is enough. Strong isolation also costs you cross-tenant analytics: benchmarks and aggregate billing need a separate, deliberately de-identified path, because you can no longer just GROUP BY tenant_id across the silo.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design a governed raw and curated data architecture.

Answer

Core answer (first 90 seconds). I'd assume a cloud object store (S3 or GCS), a mix of batch extracts and CDC streams, roughly 200 source tables, and PII under GDPR. I'd build three zones with a contract at each boundary: landing (raw, append-only, immutable), standardized (typed, deduplicated, conformed), and curated (modeled, certified, owned). The point of the split is that raw preserves source truth so you can replay, and curated exposes stable meaning so consumers don't break when a source changes.

Why immutable landing enables replay. Each batch lands as a new partition keyed by ingestion timestamp and source offset, written as Iceberg or Delta files. The table format gives me a snapshot ID that pins the exact file set. Replay means: read snapshot N, re-run the transform, write snapshot N+1. Because raw is never mutated, a bug in the transform is fixed by re-running, not by re-extracting from a source that has already moved on or will rate-limit you. Landing carries source system, object identity, extraction window, event time, arrival time, schema version, batch ID, checksum, and delete flag.

Identity resolution, concretely. Match on deterministic keys first (account ID, hashed email), then probabilistic (name + DOB + postal code) with a survivorship rule: source precedence, then most recent. Store the match graph so a bad merge is reversible rather than a one-way overwrite.

Trade-offs, and when to go lighter. Immutable landing costs storage. At 10 TB/day raw, 90 days hot on S3 Standard is ~900 TB, about $20.7k/month at $0.023/GB-month; archiving to Glacier Instant Retrieval at $0.004/GB-month drops that to ~$3.6k. If you have one source, no regulatory replay requirement, and a small team, a mutable staging table plus dbt is the right call: full immutability is overhead you won't use. Same with lineage: column-level lineage is expensive to maintain, and table-level lineage plus query logs covers most investigations.

Failure modes and how I'd catch them.

FailureDetection signal
Schema drift: source adds a column, loader drops it silentlySchema-registry diff alert per batch; column-count check
Bad dedup key merges two customersMerge-rate monitor; alert if it jumps >2x the 30-day baseline
GDPR delete in landing not propagated to curated/backupsWeekly reconciliation scan of derived tables for deleted keys
Freshness SLA breachPer-table watermark; alert if raw-to-curated lag >2x p95

Boundaries and consumers. Quarantine invalid records to a visible dead-letter table with the rejection reason, not a silent drop. Consumers read certified interfaces, not landing tables, but I'd publish landing with a clear "unstable" label so analysts who need it aren't blocked. Deletion and legal hold run as workflows across derived copies and backups, with the reconciliation job above proving they landed.

What I'd measure: raw-to-curated freshness, rejected population, boundary reconciliation pass rate, and ungoverned consumption (queries hitting landing directly).

The one-line version: raw is the audit log, curated is the product, and the contract at each boundary is what keeps them from becoming the same thing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Migrate a legacy ETL estate to cloud ELT.

Answer

What I'd say in the first two minutes

Before touching anything I'd pin three things: the target platform (I'll assume Snowflake plus dbt and Airflow, the common landing spot), which consumers have contractual SLAs, and whether there's a hard cutover date or per-domain migration is acceptable. Then I'd refuse the obvious plan, translating every job one-for-one, because that copies the legacy failure modes into a more expensive runtime. The answer is: inventory semantics, not jobs; pick two or three representative pipelines; build the target pattern once; dual-run against a frozen snapshot; cut over per domain behind versioned views.

Inventory semantics, not jobs. A job list tells you nothing. What matters is the transformation set: dedup rules, late-arriving-dimension handling, timezone conversions, soft-delete filters, currency joins. Pull them from the stored procedures and from the data. The cheap way to find the ones nobody documented is a row-level hash comparison on a frozen input snapshot: every unexplained difference is a rule you didn't port.

Pick pilots by shape, not size. Group jobs into: full-refresh dimension, incremental fact, CDC-fed, file-drop. One pilot per shape, two or three total. A 200-job estate usually collapses to four patterns.

Legacy constructTargetReconciliation check
Stored-proc MERGEdbt incremental model, unique_key, merge strategyfull outer join on key, compare column hash
SQL Agent job chainAirflow DAG, catchup=False in steady statemax(loaded_at) per partition
Full nightly extractlog-based CDCrow count + checksum per source table

Dual-run. Freeze a source snapshot or use CDC with a fixed cutoff, run both paths, compare. Row counts catch almost nothing; a full outer join on the business key with a hash of all columns catches the real bugs:

SQL
select coalesce(l.id, n.id) as id,
       case when l.id is null then 'missing_in_new'
            when n.id is null then 'missing_in_legacy'
            else 'differs' end as kind
from legacy.fact_order l
full outer join new.fact_order n on l.id = n.id
where l.row_hash is distinct from n.row_hash;

is distinct from handles the null side, so a key present in only one table still surfaces. A nonzero differs count on a frozen snapshot is a porting bug, not noise.

Failure modes and how I'd detect them.

  1. Hidden semantics. Detection: the hash diff above. Cost: each one is a manual reconciliation. Budget days, not hours.
  2. Source overload from dual-run. Two extractors on the OLTP primary doubles read load. Detection: replica lag, primary CPU, buffer-pool hit ratio. Mitigation: read from a replica, use log-based CDC, throttle to off-peak.
  3. Non-idempotent backfill. Detection: run the same partition twice and compare checksums; if they differ, the model isn't idempotent and every retry corrupts data.
  4. Consumer breakage. Detection: BI query logs and dashboard error rates, not user complaints.

Cutover. Publish fact_order_v2 alongside fact_order and point consumers at a view you can flip; rollback is flipping it back. Decommission the legacy job, its credentials and intermediate stores only after a full billing cycle with zero reads on the legacy path: check query history, not the job's own logs.

Cost arithmetic. A Snowflake XS warehouse is 1 credit/hour and each size doubles. A 4-hour nightly backfill on XS is 4 credits; at an illustrative $2/credit that's $8/night, roughly $240/month. Leave a Medium warehouse running 24/7 instead of suspending and it's 4 credits/hour × 720 hours = 2,880 credits/month. The auto-suspend default of 600 seconds is what prevents that, so set it explicitly on every warehouse you create.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How do you evaluate and control compute costs when deciding between dedicated Spark ETL clusters and pushing heavy transformations down into a cloud data warehouse ELT engine?

Answer

Evaluate workload unit economics, resource elasticity, data egress/scans, and developer operational burden rather than raw hourly instance rates.

1. Cost Drivers: Spark ETL vs. DW Pushdown ELT

  • Dedicated / Serverless Spark (AWS Glue, EMR, Databricks): Billed by CPU/memory allocated per second (DPU or vCPU-hour) plus raw object storage (S3) and intermediate shuffle storage. Incur lower compute rates for long-running, iterative batch processing, graph transformations, procedural business logic, or large-scale file compaction/un-nesting into Parquet. Minimal read charges against object storage, but operational cost includes tuning partitions, JVM garbage collection, and cluster warm-up latency.
  • Warehouse Pushdown (BigQuery, Snowflake): Billed on demand by scan volume (e.g., $6.25 per TB scanned in BigQuery) or dedicated reservation slots/virtual warehouses per second. Highly cost-effective for pure SQL operations, set-based merges, dimensional aggregation, and declarative modeling (e.g., via Dataform). Highly prone to runaway costs if engineers query unclustered or unpartitioned tables, run frequent full-table rescans, or execute multi-stage self-joins and regex row processing across billions of rows.

2. Economic Threshold & Decision Matrix

Workload TypeOptimal ArchitectureCost MechanismControl Lever
Heavy filtering, unnesting, PII scrubbingSpark ETLPre-filters raw volume before loading; avoids paying DW scan/ingestion tax on dead rows.Glue Job Bookmark / Spark dynamic allocation limits.
Dimensional Modeling & SQL aggregationCloud DW ELT (Dataform)Columnar vectorization, query optimization, and localized data caching beat custom Spark shuffles.Table partitioning, clustering, incremental materialization.
Ad-hoc Backfills (100TB+ scans)Dedicated Spark / EMR SpotControlled cluster runtime caps financial blast radius vs. on-demand scan cost blowouts.Spot instances, explicit DPU ceilings, pre-merge compaction.

3. Worked Economics Trace

Consider daily processing of 10 TB of raw log data compressed in Parquet:

  • Pushdown ELT on Unpartitioned Tables (3 daily pipeline runs):
    • Scan volume: 10 TB × 3 runs = 30 TB/day.
    • At $6.25/TB = $187.50/day ($5,625/month).
    • If downstream analysts scan this raw unpartitioned table 20 times/day, monthly cost jumps to $37,500.
  • Spark Pre-filtering + DW Partitioned Load:
    • AWS Glue job parses, extracts 1 TB of curated data, writes to partitioned Parquet using 10 DPUs for 45 minutes.
    • Glue cost: 10 DPUs × 0.75 hours × $0.44/DPU-hour = $3.30/run × 3 = $9.90/day ($297/month).
    • Downstream DW queries scan only the 1 TB partitioned curated table: 1 TB × 20 scans = 20 TB/day = $125/day ($3,750/month).
    • Net monthly savings: Over $33,000/month by enforcing pre-load ETL filtering.

4. Technical Guardrails & Budget Controls

  1. Hard Query / Job Quotas: Enforce maximum_bytes_billed per query in BigQuery or strict warehouse auto-suspend (60 seconds) and daily resource monitors in cloud warehouses. Enforce max_capacity / DPU limits and execution timeouts on Spark/Glue jobs.
  2. Partition & Cluster Enforcement: In ELT frameworks like Dataform, enforce table definitions with requirePartitionFilter = true on raw and curated tables to reject runaway full-table scans at compile-time.
  3. Decouple Ingestion from Analytical Warehouses: Load curated Parquet or Apache Iceberg tables to object storage, querying directly via object storage connectors or external tables, only materializing high-frequency BI marts in the warehouse compute layer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Your ELT transformations run inside the warehouse and now compete with BI queries for the same compute. How do you diagnose the contention and redesign the workload so both stay within their latency targets?

Answer

First pin down the engine and the numbers: which warehouse, the BI p95 target, how many concurrent dashboards, and what the transformation jobs actually do. The contention is structural: in an ELT platform the transformation runs on the same compute as the queries, so a nightly rebuild and a dashboard compete for the same slots, warehouses or WLM queues. Tuning the ETL query alone rarely fixes it. You isolate the workloads, then shrink the work.

Mechanism. In BigQuery, every query in the projects attached to a reservation draws from that reservation's slots, and the scheduler spreads them across running queries rather than handing each a fixed slice. So one 400-slot MERGE doesn't just slow itself down, it starves the dashboard queries that each want a handful of slots; they queue and p95 climbs. Snowflake is the same story unless the transformation runs on its own virtual warehouse: a separate warehouse is hard compute isolation, and multi-cluster warehouses add clusters for read concurrency. Redshift gives you WLM queues and concurrency scaling. Postgres has no isolation inside one instance: a long transformation transaction holds a snapshot, blocks vacuum, and bloats the table the BI query is reading; the usual fix is logical decoding to a replica and transforming there.

Mitigations, in the order I'd apply them:

MitigationMechanismCost
Separate reservation / warehouse / WLM queue for ETLBI queries never see ETL slotsIdle capacity when ETL isn't running
Batch or low priority for ETL jobsQueued, doesn't count against interactive concurrencyLonger, less predictable ETL
Incremental models instead of full rebuildScans only changed partitionsNeeds a reliable watermark and late-data handling
Pre-aggregate the join-heavy layerBI reads a small tableExtra storage, a staleness window
Statement timeout plus query labelsKills runaway jobs, attributes slot-ms to a teamTimeouts need retry and alerting
BI Engine or result cache for dashboardsSub-second reads off the hot pathCache invalidation, memory cost

Arithmetic, illustrative. A 500-slot reservation. Twelve nightly models averaging 40 slot-minutes each is 480 slot-minutes: nothing spread over two hours. The problem is the peak: the largest MERGE fans out to 400 slots for 6 minutes. In that window 40 concurrent dashboard queries each want ~10 slots; only 100 are free, so most queue and p95 goes from 1.2 s to 9 s. Giving ETL its own reservation sized to that 400-slot peak costs real money: 400 slots idle most of the day. The cheaper version is to cap the ETL reservation at 150 slots and let the job run roughly 3× longer, which is fine at 2 a.m.

Failure modes and detection. A single unpartitioned join can take the whole reservation: detect it with per-job slot-ms from INFORMATION_SCHEMA.JOBS_BY_PROJECT or the warehouse's query history, and alert on max slot-ms per job, not just the total. Incremental writes create small partitions and metadata churn; watch partition and file counts and schedule compaction. On Postgres, watch table bloat and replication lag on the decoding replica. And re-check the ETL's own latency target after you cap it: isolation moves the queue, it doesn't remove it.

When not to isolate. A small warehouse with five concurrent users doesn't need a second reservation. Scheduling the ETL outside business hours and adding a statement timeout is enough; isolation just fragments capacity you're already paying for.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Optimize ELT warehouse cost without weakening correctness.

Answer

Core answer (first 90 seconds)

Assume a columnar cloud warehouse (Snowflake, BigQuery, Databricks SQL), ELT where transformation runs in-warehouse, and a stated SLO per data product: freshness plus a correctness check. Cost is bytes scanned + compute-seconds + idle time. Correctness is what you publish and when. The optimization is to attack them in that order, and never let a cost control change what a consumer reads.

By leverage:

  1. Stop scanning data you don't need: partition pruning, column projection, clustering on the filter columns. Biggest win, zero correctness risk.
  2. Stop recomputing what you already have: incremental models instead of full rebuilds.
  3. Stop paying for idle: right-size and autosuspend.
  4. Only then tune concurrency and slot allocation.

Mechanism

Incremental vs full rebuild. A full rebuild of a 2 TB table scans 2 TB every run. An incremental model keyed on event_date scans only the new partitions, so cost scales with new data, not total data. The price is merge correctness: late-arriving events and schema drift need explicit handling, and the merge key must be unique or you silently duplicate rows. Don't use it for small tables: a 5 GB dimension rebuilds in seconds and the merge logic is more risk than it saves, or where more than roughly a third of partitions change per run.

Skew. A shuffle keyed on a column with one dominant value sends every row to one task. With 200 slots, 199 sit idle while one runs; wall clock is set by the hot task and you pay for the whole cluster for that duration. Detection: compare task duration p99 to p50 in the job's stage metrics. A ratio above ~10 is skew, not volume.

Autosuspend. Snowflake's default AUTO_SUSPEND is 600 s. Too long and you burn credits between queries; too short and every query pays a cold start. Set it from the measured distribution of inter-query gaps, not a guess.

Worked check (figures hypothetical)

1.2 TB table, 30 full scans/day, at $6.25/TB scanned (verify current list price): 36 TB/day ≈ $225/day ≈ $6,750/month. Partition by day and filter to the last 7 days: ~280 GB/day ≈ $52/day. Same output, ~92% less.

datasetbytes scanned/mocompute creditsfreshness SLOowner
events840 TB31015 mingrowth
orders90 TB401 hfinance
dim_customer4 TB624 hgrowth

events is 90% of scan cost and 15 minutes of freshness. That is the argument to make, not "total spend fell 12%".

Failure modes and how you catch them

  • A cost guardrail cancels a job mid-write and a partial partition is published. Detect: per-partition row count compared to source in the orchestrator before the swap. Fix: write to a staging partition, swap atomically.
  • An incremental merge silently drops late-arriving rows. Detect: daily reconciliation of source vs target counts by day; alert on any nonzero delta, not a percentage threshold.
  • Skew, as above. Detect: p99/p50 task duration per stage.
  • Autosuspend set too aggressively. Detect: queue time rising relative to execution time in the warehouse's query history.

Reporting

Cost per data product with its freshness and quality attached. A dataset that got 40% cheaper and now misses its freshness SLO is a regression, not a win.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design reverse ETL into customer-facing operational systems.

Answer

What I'd say first

Reverse ETL here means pushing computed warehouse attributes (churn score, LTV tier, next-best-action) into systems a human or a customer actually touches: Salesforce, Zendesk, Braze, a billing portal. The design question isn't "how do I sync"; it's "who owns each field, and what happens when the two sides disagree."

Assumptions I'd state up front: the warehouse is authoritative for derived attributes; the operational system is authoritative for anything a human edits there (case owner, deal stage, subscription status). Sync runs every 15 minutes incrementally. Volume is ~2M customer records, ~5% changing per day.

The ownership matrix decides everything

Write field-level ownership down before writing any connector. Without it you get a feedback loop: the warehouse writes churn_score, a rep edits the Salesforce record, CDC ships that edit back to the warehouse, the next sync overwrites it, and the rep's edit silently disappears.

FieldOwnerSync direction
churn_score, ltv_tierwarehousewarehouse → CRM, overwrite
case_owner, deal_stageCRMCRM → warehouse only
email_opt_inconsent serviceboth, consent wins

The sync record

Each row is a deterministic, idempotent upsert keyed on the destination's external id, never on email.

Python
# pseudocode, Python 3.11 syntax
record = {
    "external_id": f"wh_{customer_id}",        # stable, never email
    "churn_score": score,
    "ltv_tier": tier,
    "sync_key": sha256(f"{sync_name}:{customer_id}:{field_set_version}"),
    "source_updated_at": updated_at.isoformat(),
}
# upsert on external_id; skip if destination.source_updated_at >= source_updated_at

The sync_key makes a replayed batch a no-op. The source_updated_at guard is what stops a stale full-reconcile from clobbering a fresher incremental write.

Rate limits and batching

Salesforce Enterprise Edition allows 100,000 API requests per 24 hours; Bulk API 2.0 takes 10,000 records per batch. 100k daily changes = 10 batches, trivial. A naive nightly full sync of 2M records = 200 batches and burns the whole request budget on unchanged rows: that's the argument for watermark-based incremental sync plus a weekly reconcile.

Failure modes and how you see them

  • Wrong identity: two customers share an email. Detect by asserting external_id uniqueness in the mapping table before the sync; alert on any batch where the mapping join returns more than one row.
  • Stale model: the warehouse table didn't refresh. Detect via a freshness check on max(source_updated_at); block the sync if it's older than 2× the model's SLA.
  • Duplicate run: two schedulers fire. The idempotent upsert makes it harmless; alert on overlapping run IDs.
  • Destination outage or permission loss: bounded retries with exponential backoff, then park the batch and page. Never retry a 403: that's a credential problem, not a transient one.
  • Delete request: GDPR erasure must propagate as a delete, not a null-out, and be recorded in the audit log with the request id.

When not to use reverse ETL

If the operational system is the only writer and the warehouse just reads it, you don't need reverse ETL: you need CDC. If the destination has no stable external id, fix identity resolution first; reverse ETL will happily write the wrong person's data at scale.

Curated: · Written: · Reviewed:

Difficulty: Hard