Skip to content
Tech Interview Prep
Technical interview guide

Data Quality & Validation

Catching bad data before it reaches downstream consumers: schema checks, freshness, and anomaly detection.

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

Scope: Great Expectations, dbt, Deequ, OpenLineage 1.53, JSON Schema 2020-12, and OpenAPI current 2026-08-31.

Interview Q&A

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

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Define a producer data contract and validate it at ingestion.

Answer

The 90-second answer. A producer data contract is a versioned, machine-readable agreement about what a producer puts on the wire and what it promises about it. Validation at ingestion is where those promises get enforced before the data becomes trusted. I'd assume Kafka as transport, a schema registry, and a consumer that owns the landing table: say Iceberg or Delta. The contract covers three things: identity and schema, time and completeness, and semantics. Validation runs in three stages (envelope, schema, business invariants) and anything that fails goes to quarantine with its raw bytes intact. Never coerce a value to make it pass.

A contract that's actually enforceable looks like this:

YAML
contract: orders.events
version: 3
owner: payments-platform
producer: checkout-service
schema: registry subject orders.events-value, Avro, compat BACKWARD
key: order_id
required: [order_id, amount, currency, occurred_at]
event_time: occurred_at, UTC, max_lag 15m
completeness: kafka offset per partition, EOF marker per partition
volume: 8k-12k records/min
pii: email -> tokenized at source

compat: BACKWARD is the Confluent Schema Registry mode that lets consumers upgrade before producers. Adding an Avro field with a default is backward compatible; removing one without a default is not. In Protobuf, deleting a field number and reusing it breaks the wire format: reserve it instead. In JSON Schema, additionalProperties: false makes every new producer field a breaking change, which is usually the wrong default for a contract you want to evolve.

Worked trace (hypothetical, one 1-minute micro-batch):

stagecheckinrejectedexample error
1envelope: schema_id present, producer identity matches topic ACL10,0003missing schema_id
2decode against orders.events v39,99712currency not in ISO-4217 enum
3invariants: amount > 0, occurred_at <= ingest_at, order_id non-null9,98522amount = -1
land9,963

37 rejected out of 10,000 is a 0.37% rejection rate. I'd alert at 0.5% sustained over five minutes, and separately alert if the rate drops to exactly zero after a parser deploy: that usually means the validator stopped running, not that the producer got perfect.

Trade-offs, and when the choice flips. Validate at write (producer-side, in CI plus at produce time) versus validate at read. Write-side catches drift before it lands and costs the producer latency; read-side keeps the producer decoupled but lets bad data sit in the lake. Flip to read-side when the producer is a third party you can't put a validator in front of. Quarantine versus reject-the-batch: quarantine keeps the pipeline moving but silently loses data if nobody watches the quarantine topic; reject-batch preserves atomicity but stalls. Flip to reject-batch for a financial ledger, quarantine for clickstream. Compatibility mode flips the same way: BACKWARD when consumers deploy first, FORWARD when producers do, FULL when you control neither, NONE only for a topic with one tightly-coupled producer and consumer.

Failure modes and how you see them. Silent coercion ("12" parsed to 12, or a timestamp read in local time) shows up as a rejection rate that collapses after a parser change. An early EOF marker makes downstream aggregates undercount; detect it by comparing marker count to partition count. Duplicate order_id after a producer restart slips past idempotent-producer dedup, which only covers a single producer session; detect with a key-dedupe window at landing. A producer bypassing the registry and writing raw bytes shows up as a schema_id histogram that doesn't match the subject's current version.

Finally, authenticate producers, mTLS or SASL/SCRAM plus per-topic ACLs, and carry tenant identity inside the signed envelope so one tenant can't declare another's schema or identity. Record contract version, validator version, and accepted/rejected counts per batch, and give the producer a feedback channel plus a replay path from quarantine.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Choose between database constraints and pipeline data tests.

Answer

I'd choose both, but with a clear split: database constraints for local, cheap-to-enforce invariants that must never be violated; pipeline tests for cross-system, statistical, and business rules that are too expensive or impossible to enforce at write time.

The decision rule is simple. If a rule must hold on every single write and the check is O(1) per row: like NOT NULL, CHECK (quantity > 0), UNIQUE (email), or FOREIGN KEY (customer_id) REFERENCES customers(id): put it in the database. PostgreSQL 16 and MySQL 8.0 enforce these by default. But if the rule involves aggregates, time windows, external sources, or late-arriving data: like 'daily order totals must match the payment gateway' or 'no more than 5% of rows can have a null shipping address': put it in the pipeline. dbt tests (unique, not_null, relationships, accepted_values) and Great Expectations are built for this.

Why not just one? Constraints prevent invalid states at the source, but they can't see across systems. Tests catch what constraints can't, but they run after the fact and can be flaky. For example, a CHECK constraint on an orders table can stop a negative quantity from ever being committed. But it can't tell you that the sum of line items doesn't match the order total, because that requires reading multiple rows. A pipeline test can catch that mismatch, but only after the data lands.

Here's a concrete example. In PostgreSQL:

SQL
CREATE TABLE orders (
  id bigint PRIMARY KEY,
  quantity int NOT NULL CHECK (quantity > 0),
  customer_id bigint NOT NULL REFERENCES customers(id)
);

That's prevention. Now a dbt test for reconciliation:

SQL
SELECT order_id
FROM {{ ref('orders') }}
JOIN {{ ref('payments') }} USING (order_id)
GROUP BY order_id
HAVING SUM(orders.total) != SUM(payments.amount);

That's monitoring. You need both because the constraint can't see payments, and the test can't stop a bad write.

Failure modes matter. Constraints can cause write failures under concurrency: a unique index on a hot column can cause deadlocks or serialization errors. In a hypothetical 10M-row orders table, adding a CHECK constraint on quantity adds negligible write overhead (sub-millisecond per row), but a unique index on a hot customer_id column can add 5-10 ms per insert under contention, pushing p99 write latency from 20 ms to 30 ms. In MySQL, you can disable foreign_key_checks for bulk loads, which means the constraint is bypassed. In Snowflake and BigQuery (as of 2024), primary and foreign keys are not enforced: they're metadata for the optimizer. So if you're on those engines, you can't rely on constraints at all; you must test. On the test side, false positives are common: a seasonal spike can trigger an anomaly alert. Late-arriving data can cause a reconciliation test to fail even though nothing is wrong. You need to define quarantine and backfill policies.

A useful comparison:

AspectDatabase constraintsPipeline tests
EnforcementAt write time, per rowAfter load, per batch
ScopeSingle table or immediate FKCross-table, cross-system
CostLow per row, but can block writesHigher, but off critical path
Failure modeWrite rejected, possible availability hitAlert, possible false positive
EnginesPostgreSQL, MySQL enforce; Snowflake, BigQuery don'tdbt, Great Expectations, custom SQL

My rule of thumb: put the invariant where the cost of violation is highest and the check is cheapest. If rejecting a transaction harms availability more than accepting a corrupt row, use a test and quarantine. If accepting a corrupt financial identity is worse, use a constraint. Document residuals where neither layer can prove an external source fact.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How do you validate uniqueness and detect duplicate records against a declared business key, and how do you handle legitimate duplicates that the key does not capture?

Answer

First 90 seconds. Pin the grain before naming the key: "one row per order per tenant", "one row per customer per source system". Then declare the key columns, normalize them, and assert two things together, not-null on every key column and uniqueness of the tuple. A uniqueness check that ignores nulls passes on a table whose key is null, because SQL treats NULLs as distinct in a UNIQUE constraint (Postgres allows many; a SQL Server unique index allows one). The pair is the assertion, not uniqueness alone.

Normalize before comparing: trim, case-fold, Unicode NFKC. 'ABC', 'abc ' and 'A\u00C7B' versus 'A\u0043\u0327B' are three different strings to the engine and one customer to the business.

How to check it. In dbt, unique covers a single column; a composite key needs dbt_utils.unique_combination_of_columns or a singular test:

sql select tenant_id, order_id, count() as n from {{ ref('fct_orders') }} group by 1, 2 having count() > 1

Great Expectations gives expect_column_values_to_be_unique and expect_compound_columns_to_be_unique; Deequ gives isUnique("order_id") and hasUniqueness(Seq("tenant_id","order_id"), Check.IsOne), where uniqueness is distinct/total, so 1.0 is the pass condition. JSON Schema's uniqueItems and OpenAPI's equivalent only constrain elements within one array: they cannot express a key across records, so schema validation is not a substitute.

At 10M rows the group by is a full hash aggregate or sort over the key. Deequ's distinct-count path uses HyperLogLog, standard error about 1.04/√m: roughly 0.8% at m = 2^14 registers. That is fine for "is the duplicate rate near zero" and useless for "which 37 rows are duplicated". Run the approximate check every load, the exact having count(*) > 1 on a schedule or against the failing partition.

Legitimate duplicates. Three cases, three answers:

caseexamplehandling
key too narrowSCD-2 history, split shipment lineswiden the key: add valid_from, line_no
exact duplicateidempotent replay of the same eventdedupe on the full row hash, keep one, count it
key duplicate, different payloadtwo addresses for one customernot a duplicate: a conflict; needs a survivorship rule

For the third, don't silently pick a row. Rank with row_number() over (partition by tenant_id, order_id order by updated_at desc, ingest_seq desc) and record which row won and why, so the choice is auditable and replayable. Where the business genuinely allows repeats, a customer with two emails, declare a bounded tolerance ("≤0.5% of rows may share the key, alert above") rather than weakening the test to a warning nobody reads.

Failure modes. Key drift when a source starts emitting a new id space; soft deletes leaving tombstones that collide; a composite key with one nullable component; a uniqueness check that runs on a partial partition and passes before the load finishes; late-arriving updates that insert a second row instead of merging. Detect them by publishing the duplicate rate as a metric, not just pass/fail, OpenLineage's data quality metrics and assertions facets carry exactly that, and by alerting on conflicts separately from exact duplicates, because the two need different owners.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How do you validate referential integrity across related tables in a warehouse model, and what do you do when a foreign key has no matching parent row?

Answer

Pin down three things before writing a check: which column is the foreign key and which is the parent key, whether the relationship is enforced at load or only asserted after it, and whether a NULL foreign key is legal in this model. Then the orphan check is an anti-join, not a join with a count comparison.

sql -- orphans: child rows whose FK has no parent select f.order_id, f.customer_sk from fact_orders f left join dim_customer d on f.customer_sk = d.customer_sk where d.customer_sk is null and f.order_date >= date '2024-06-01'; -- incremental window

Two traps. NOT IN (select customer_sk from dim_customer) returns zero rows if any parent key is NULL, so it silently passes: use NOT EXISTS or the left join. And a NULL foreign key is not an orphan; it is a separate nullability assertion. One check should not cover both.

The check people skip: the parent key must be unique. If dim_customer holds two rows for customer_sk = 42, the join fans out and the fact table silently doubles: 1M orders × 2 matching parents = 2M rows and revenue up 100%, with zero orphans reported. Run uniqueness on the parent key in the same suite. dbt ships this as the built-in relationships test; Deequ lists referential integrity among its quality dimensions and provides a foreign-key constraint.

failure modechecktypical action
orphan FK, no parentanti-join on the FKblock if the FK carries money or authorization; quarantine the rows if isolatable
duplicate parent keyuniqueness on the parent keyblock: fan-out corrupts every downstream aggregate
NULL FKnullability assertion, separate from RIper contract: sentinel member or reject
late-arriving dimensionanti-join over the incremental window onlyhold the fact, or insert an inferred member and reconcile
SCD2 version mismatchFK must fall inside the parent's valid_from/valid_toblock; the row points at the wrong version
type or format mismatchnormalize (trim, case, cast) before comparingfix the join key, not the data

Late-arriving dimensions are the usual real cause. Three options, each with a cost: hold the fact until the parent lands (adds latency, needs a replay path); insert an inferred dimension row and update it when the real one arrives (needs reconciliation and a way to find inferred rows); or point at a sentinel -1 / Unknown member (publishes immediately, but every aggregate now carries an "Unknown" bucket someone will forget to exclude). Choose by whether consumers can tolerate that bucket.

Cross-system keys produce false orphans more often than real ones: trailing whitespace, case, leading zeros, int-versus-string. Normalize before paging anyone.

Finally, track the orphan rate, not just the count, and alert on change. Twelve orphans in a 400M-row fact table that have sat there for a year is a different decision from twelve new ones today. Emit the assertion result with expected/actual counts and a sample of failing keys so the owner can act.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Measure and enforce data freshness and completeness correctly.

Answer

Assumptions I'd state first: Postgres CDC (Debezium) → Kafka → Flink → Iceberg → dbt → dashboard, event-time semantics, a 5-minute p99 event-to-dashboard SLO, and 12 Kafka partitions on the orders topic. If your SLO is per-tenant or per-region, everything below segments the same way.

The answer. Freshness is the age of the newest validated record available to a consumer, measured in event time and anchored to a source position. Completeness is whether the population you claim through a boundary is fully accounted for: accepted + quarantined + explicitly excluded + never-arrived, with that last term named rather than assumed zero. A recent updated_at, a green Airflow task, or a non-zero row count proves neither.

Track four signals separately, because they fail independently:

SignalWhat it isHow it lies
source positionKafka end offset per partition, or Postgres LSNsource
ingestion time_ingested_at stamped by the sinkskewed producer clocks
processing watermarkFlink watermark = max event time − out-of-ordernessstalls on idle partitions
publicationIceberg snapshot id + added-recordsadvances only on checkpoint

Now the freshness budget, per hop, worst case:

  • Debezium → Kafka p99: 120 ms
  • Kafka consumer lag p99: 400 ms
  • Flink checkpoint interval 30 s → up to 30 s before the Iceberg commit is visible
  • dbt run every 5 min → up to 300 s

Total ≈ 330 s against a 300 s SLO. The batch scheduler alone blows the budget; no amount of tuning the CDC hop fixes it. That arithmetic is why you measure per hop instead of end to end.

Completeness, worked. For the 14:00–15:00 UTC hour:

  • Postgres control total: 1,000,000 rows
  • Kafka delivered: 998,412 records
  • quarantined (schema drift on a new column): 1,540
  • duplicate replays after a Debezium restart: 48
  • accepted: 996,824
  • never arrived: 1,588

The 1,588 is the finding. It localizes the loss to the source→Kafka hop, and it is exactly what a "job succeeded" check hides. Reconcile with control totals and sequence gaps, not row counts.

SQL
-- run per interval; expected comes from the source, landed from the lake
SELECT e.n AS expected,
       l.n AS landed,
       l.quarantined,
       l.duplicates,
       e.n - l.n AS never_arrived
FROM (SELECT count(*) AS n FROM postgres_orders
      WHERE updated_at >= '2024-06-03 14:00'
        AND updated_at <  '2024-06-03 15:00') e,
     (SELECT count(*) AS n,
             count(*) FILTER (WHERE quarantine_reason IS NOT NULL) AS quarantined,
             count(*) FILTER (WHERE is_duplicate) AS duplicates
      FROM iceberg.orders_raw
      WHERE event_hour = '2024-06-03 14:00') l;

Failure modes worth naming, each with its detector:

  • Idle partition stalls the watermark. Flink propagates the minimum watermark across inputs, so one silent partition freezes every downstream window. Fix with withIdleness(Duration.ofMinutes(1)); alert on per-partition watermark lag, not job uptime.
  • auto.offset.reset=latest (the default). A consumer group created after a backlog starts at the log end and looks perfectly fresh while skipping history. Detect by comparing the committed offset to the earliest offset at group creation.
  • Offset expiry. offsets.retention.minutes defaults to 10080 (7 days). A group idle longer resets to latest: a silent gap no freshness metric catches.
  • Clock skew and DST. _ingested_at from a producer with a skewed clock makes freshness negative; event time stored in local time without an offset drops an hour into the wrong interval during a fall-back.

Enforcement is a consumer policy, not a global switch: on a missed deadline, block the publish, mark the partition stale, or serve the prior Iceberg snapshot. Decided per consumer, and never advance the freshness marker past unvalidated data. Publish interval, max source position, accepted/quarantined/dropped counts and validation status in one atomic commit, so a reader can't see a fresh marker over incomplete data.

Test the zero-activity hour, a late file, an early marker, a source retry, a sequence gap, a duplicate, clock skew, DST, a quarantine surge, and catchup after an outage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Reconcile data across a source and transformed warehouse model.

Answer

Reconciling a source against a transformed warehouse model means proving every difference is explained by a named rule, at a boundary you can reproduce. I pin the boundary first: source snapshot (Postgres LSN 0/16B3740), target model version (dbt model FCT_ORDERS v4.2.1), interval (2024-06-01 00:00:00 to 2024-06-02 00:00:00 UTC), currency (USD), units (cents), and the inclusion/exclusion rules. Then I reconcile at three levels (record identity, segmented counts, additive control totals) and keep a reason-code bridge that balances exactly.

Row-count bridge. Source 1,204,332 rows, target 1,198,441, difference 5,891.

Reason codeRows
accepted (present in target)1,198,441
QUARANTINE_NULL_CUSTOMER4,120
LATE_AFTER_CUTOFF1,200
FILTERED_TEST_ACCOUNT571
source total1,204,332

1,198,441 + 4,120 + 1,200 + 571 = 1,204,332. Balances. A grand total alone would hide offsetting missing and duplicate rows, so I segment by source, status, date and tenant before trusting it.

Sum bridge. I run this on the matched key set (inner join on order_id) so the 5,891 rows above don't double-count. Source sum 8,432,109,233 cents, target sum 8,431,266,433 cents, delta 842,800 cents: just under 0.01% of source, above my 0.005% rounding tolerance, so I drill.

SQL
-- Snowflake. STG_ORDERS_PG is the source snapshot staged 1:1, amounts in cents.
SELECT s.order_id,
       s.order_amount_cents AS src_cents,
       t.order_amount_cents AS tgt_cents,
       s.order_amount_cents - t.order_amount_cents AS delta_cents,
       s.promo_code
FROM stg_orders_pg s
JOIN fct_orders t ON t.order_id = s.order_id
WHERE s.order_amount_cents <> t.order_amount_cents
ORDER BY delta_cents DESC
LIMIT 3;
order_idsrc_centstgt_centsdelta_centspromo_code
9876541299912299700SAVE7
98765545993899700SAVE7
98765688008100700SAVE7

Every row is exactly 700 cents low and every one carries promo_code 'SAVE7'. SELECT COUNT(*), SUM(delta_cents) FROM ... returns 1,204 rows and 842,800 cents. The transform applies a flat $7.00 discount for SAVE7 that isn't in the contract. I add reason code PROMO_DISCOUNT_SAVE7 and the bridge balances: 8,431,266,433 + 842,800 = 8,432,109,233.

Record identity is the join on the natural key (order_id) checking for missing keys, duplicates and mismatched attributes: a row count match can hide a swapped row, so I compare keys and attributes, not just counts.

Validation. Grain uniqueness on order_id as a dbt test, referential integrity to dim_customer as a foreign key test, SCD intervals checked with valid_from < valid_to. Great Expectations asserts row-count and sum ranges. I publish expected, actual, difference, rule version and lineage with the output, investigate mismatches by sampling keys under protected access, and repair idempotently.

Failure modes. If the bridge doesn't balance, the usual causes are a missing reason code, a fanout in the join (a dim table with duplicate keys inflating the sum), or a timezone boundary error putting rows on the wrong side of the cutoff. I test duplicate, missing partition, delete, late correction, currency rounding, timezone edge, fanout, partial publish and backfill, and I monitor unexplained difference age and value. For large tables I reconcile partition by partition to keep queries under a few minutes, but I still sum the whole interval.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you validate incremental and change-data-capture loads so that missed, duplicated or out-of-order changes are caught before they corrupt the target table?

Answer

Pin down the delivery contract first, because it decides what you can assert. Log-based CDC (Debezium on Postgres WAL or MySQL binlog) is at-least-once and ordered per source partition/key, not globally; a high-watermark batch job on updated_at is neither. Then validate three invariants against the source's change log rather than against target row counts: completeness (every committed change in the applied offset range landed), uniqueness (each key applied once), and per-key order (the target holds the highest-version change).

Completeness. Record the source log position (LSN, binlog file+pos, or Kafka offset) at the start and end of each batch, and assert the applied range is contiguous: no gaps in the offset sequence. Compare the count of change events in that range against rows affected in the target. A gap means the connector skipped events or a batch filter dropped them.

Duplicates. Assert primary-key uniqueness on the target (count(*) = count(distinct key)), then run an idempotency replay: re-apply the last batch and assert a checksum over the affected key range is unchanged. A MERGE that is not idempotent fails this; an INSERT-only sink duplicates outright.

Order. Carry a monotonic version per key (the source LSN, or (commit_ts, seq)) into the target. Assert target.version = max(source.version) for every key in scope. A stale write shows up as target.version < source.version.

FailureDetection assertion
Missed changeoffset range contiguous; event count == affected rows
DuplicatePK uniqueness; replay checksum unchanged
Out-of-order / staletarget.version == max(source.version) per key
Late-arriving updateno event with commit_ts < watermark − lateness bound
Silent filter dropper-table event counts vs source log counts

Worked trace. Keys A and B. Source log: LSN 100 A=v1, 101 B=v1, 102 A=v2. Batch 1 applies 100–101, batch 2 applies 102. If batch 2 is retried after a partial failure, A receives v2 twice: PK uniqueness still passes because it is the same key, so only the replay checksum catches a non-idempotent write such as a counter increment. If batch 2 lands before batch 1 (parallel consumers), A ends at v1: target.version(1) < source.version(2), caught by the order assertion. If the connector restarts from an earlier offset, batch 1 replays; an idempotent MERGE absorbs it, an INSERT-only sink duplicates.

Failure modes of the validation itself. Running assertions against a replica that lags the writer makes "target == source" flaky, so assert against the source log position, not wall clock. A watermark on updated_at misses rows committed with an earlier timestamp after a long transaction: bound it with a lateness window and reprocess rather than advancing past them. And a validation that only counts rows passes when one duplicate and one miss cancel out; that is exactly why the per-key version comparison has to be there.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Validate data through a breaking or compatible schema evolution.

Answer

Core answer (first 60–120 seconds)

Assume Avro on Kafka with Confluent Schema Registry, whose default compatibility level is BACKWARD. The trap in this question is that "compatible" is two claims, not one. Wire compatibility means the bytes still deserialize. Semantic compatibility means the values still mean the same thing. A change can pass the registry and still corrupt every downstream metric, so validate in three layers in this order: registry compatibility mode, a producer/consumer version matrix, and data assertions bound to the schema version.

The break the registry cannot see

v1:

JSON
{"type":"record","name":"OrderPlaced","fields":[
  {"name":"order_id","type":"string"},
  {"name":"amount_cents","type":"long"}]}

v2 renames the field and switches units:

JSON
{"type":"record","name":"OrderPlaced","fields":[
  {"name":"order_id","type":"string"},
  {"name":"amount","type":"double","default":0.0}]}

Trace it the way Avro resolves schemas. Writer v1 emits {order_id:"A1", amount_cents:1999}. Reader v2 looks for a field named amount in the writer's schema, finds none, and substitutes the default. Output: {order_id:"A1", amount:0.0}. A $19.99 order reads as $0.00, and BACKWARD reports PASS because the reader never failed. That is the whole failure mode: default substitution is silent.

What to do instead

Add amount as a new field, keep amount_cents populated during the transition, and have consumers prefer amount when present, falling back to amount_cents / 100. Deploy readers first (expand), then producers, then backfill history, then retire amount_cents (contract) only after retention evidence shows no reader touches it.

Compatibility levels, and when each is right

LevelGuaranteeUse when
BACKWARD (registry default)New schema reads old dataConsumers upgrade before producers
FORWARDOld schema reads new dataProducers upgrade first
FULLBoth directionsYou cannot control deploy order
*_TRANSITIVEHolds across all prior versionsLong-lived topics with many retained versions

Adding a field with a default is backward compatible. Removing a field without a default is not. Widening int to long is promotable in Avro; changing a field's unit is not a schema change at all, which is why the registry is blind to it.

In Protobuf the equivalent guard is reserved 3; and reserved "amount_cents"; so a retired field number is never reused. Reusing field 3 as double after it was int32 is not wire compatible: int32 is varint, double is fixed64, so the parser reads a different wire type and errors or produces garbage.

Failure modes and how you detect them

  • Silent default substitution: count records where the field equals its default; alert when that count exceeds the pre-change baseline.
  • Field-number reuse: parse errors and dead-letter-queue spikes after a producer deploy.
  • Unit or meaning change: distribution shift, e.g. p50 amount drops 100x overnight.
  • Mixed-version batch: tag each record with its schema version and reconcile source-to-output counts through cutover.

Trade-offs

Expand-and-contract costs you a dual-write window and a backfill. Skip it when the change is a pure widening with no semantic shift, or when a low-volume internal table can take a coordinated deploy in a maintenance window. Do not skip it when a field's meaning, unit, timezone, grain or privacy class changes, because no compatibility level protects you there.

Testing

Run the old/new producer × validator × consumer matrix, plus missing, default and unknown fields, a reused name, replay, rollback, and a mixed-version batch. Bind assertions to the schema version so a rule written for v1 never silently applies to v2 data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do you profile an unfamiliar dataset to derive an initial set of validation expectations, and how do you decide which profiled patterns become enforced rules rather than advisory ones?

Answer

Profile first, but treat profiler output as evidence about what the data looked like, not as a specification of what it must look like.

I'd profile a representative window, at least 30 daily partitions or one full business cycle, and capture per column: row count, null fraction, distinct count, min/max, p01/p50/p99, top-k values, inferred type and format samples; and per table: candidate-key uniqueness, max event timestamp for freshness, and referential overlap with upstream keys. In Great Expectations that's the Onboarding Data Assistant, which emits a candidate suite with mostly= parameters derived from the observed data; in Deequ it's ColumnProfilerRunner with Completeness, Distinctness, Minimum, Maximum analyzers. Both answer "what is here", not "what is required".

The promotion rule I use: a profiled pattern becomes an enforced rule only when it is (1) semantically required. Someone can state the invariant without looking at the data, (2) stable across the whole profiling window, and (3) owned by a producer who can fix a violation. Otherwise it stays advisory.

profiled signalcandidate expectationdefaultpromoted to enforced when
order_id null fraction 0.0not nullenforcedimmediately: key column
coupon_code null fraction 0.02mostly=0.98advisorynever; 2% null is the business
order_id distinct = row countuniqueenforcedimmediately
email distinct = row countuniqueadvisoryafter a dedup contract is agreed
status top-k ⊂ {NEW, PAID, SHIPPED}in setenforcedenum exists in the source schema
p99 latency 180 ms, max 900 msbetween 0 and 1000advisory30 clean partitions plus a stated SLA
max(created_at) lag ≤ 2hfreshnessadvisoryafter measuring producer cadence

The trap is the profiler's mostly parameter. A profiler that sees 0.2% nulls writes mostly=0.998, which silently encodes today's dirt as tomorrow's contract. For anything you've decided is an invariant, set mostly=1.0 and let it fail.

python

Great Expectations 0.18.x

result = context.assistants.onboarding.run( batch_request=batch_request, exclude_column_names=["ssn", "email"], # never profile PII ) suite = context.suites.add(result.suite)

hand-edit: the profiler wrote mostly=0.998 on order_id; make it an invariant

suite.expect_column_values_to_not_be_null("order_id", mostly=1.0)

yaml

models/marts/orders.yml: dbt 1.7+

models:

  • name: orders columns:
    • name: order_id data_tests: [unique, not_null] # enforced: severity error is the default
    • name: coupon_code data_tests:
      • not_null: config: {severity: warn} # advisory

Arithmetic on why tolerances matter: at 1M rows/day, mostly=0.999 on a uniqueness rule admits 1,000 duplicate keys a day, 365k a year, with the dashboard green. If the column is a key, tolerance is zero.

Failure modes. Profiling one partition hides seasonality: month-end spikes and holiday drops look like anomalies and get encoded as bounds. Profiling a partition that was backfilled or repaired hides the exact defect you are trying to catch. A sample that misses the tail makes p99 meaningless. Advisory rules that nobody reads become alert fatigue: track fire rate per rule and retire any advisory rule that has never once been acted on. Before promoting, backtest the candidate against the historical partitions you profiled: a rule that would have fired 40 times last month is either a real defect stream or a badly chosen threshold, and you need to know which before it pages someone.

Promotion is a reviewed change with an owner and a date, not a config edit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design pass, warn, quarantine, and block policies for quality failures.

Answer

Clarify first. I'd ask three things: batch or streaming, who consumes the table, and what's the worst thing that happens if a bad partition ships. My answer assumes a daily batch table in Snowflake, orchestrated by Airflow, checks written as dbt tests plus a few Great Expectations suites, with three consumer classes: finance reporting, an ML feature store, and customer dashboards. If it's streaming, the same four policies apply but the window shrinks to minutes and quarantine becomes a dead-letter topic.

The core idea. Keep three things separate: the assertion result (did the check run, what did it observe), the configured severity, and the publication decision. A check failing is not a decision. The decision is a function of blast radius, reversibility, and whether consumers can detect the problem themselves.

The four policies.

  • Block: publish nothing, fail the task, page. Reserve it for failures a consumer cannot detect or work around: broken referential integrity to a dimension, cross-tenant leakage, a financial control total that doesn't tie, PII in the wrong column, a schema break. These are unrecoverable once read.
  • Quarantine: the failure is row-scoped, the bad rows can be isolated, and the survivors reconcile to a known total. Publish the clean partition, write the bad rows to a quarantine table with rule id, run id, and observed value, and expose coverage so consumers know what's missing.
  • Warn: bounded, low-blast-radius drift the consumer can absorb. Publish, but stamp the partition with a failed status, an owner, and an expiry date. A warning without an expiry is a block you forgot to enforce.
  • Pass: the assertion actually executed against the intended dataset version. Skipped, stale, or "partition didn't exist" is its own state and never counts as pass.

Thresholds (example values, tune per table):

SignalWarnQuarantineBlock
null rate on customer_id0.05–0.5%—> 0.5%
row count vs 28-day median±2–10%±10–25%, if rows isolatable> 25%
control total mismatch——any
cross-tenant key present——any

Quarantine arithmetic. Source partition is 10,000,000 rows. amount > 0 fails on 4,120 of them. Publish 9,995,880, quarantine 4,120. The gate that lets this ship is reconciliation: sum(amount) over published plus sum(amount) over quarantined must equal sum(amount) over source, and 9,995,880 + 4,120 = 10,000,000. If either identity breaks, escalate to block: that's how you catch a partial quarantine.

Failure modes, with detection and cost.

  • Validator outage. Detection: assertion count per run drops below the expected number, or the check's own last-run timestamp goes stale. Blast radius: everything downstream of that table. Cost: a silent bad publish. Treat a missing assertion as block.
  • Cumulative warnings. Twelve warnings each under threshold can together cover 40% of rows. Detection: aggregate warning coverage per table per run. Cap it: more than 5% of rows or three concurrent warnings escalates to block.
  • Warning expiry. Detection: a scheduled job that flips expired warnings to block. Without it, "warn" becomes permanent.
  • Partial quarantine. Quarantine write succeeds, clean-partition publish fails. Detection: the reconciliation identity above. Cost: double-counted or missing rows downstream.
  • Rollback after publish. Detection: consumer-side version/freshness check. Cost: consumers already read the bad partition; rollback doesn't un-read it.

Governance. Every non-pass records expected, actual, scope, rule/data/code versions, owner, action, and consumer notification. Waivers are authenticated, reasoned, time-bounded, and version-specific. Review false positives and escaped defects monthly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design anomaly detection for data-quality metrics.

Answer

Assume daily batch tables, 10k datasets, freshness SLA 6h, and the consumer is an on-call data engineer. The design is two tiers: deterministic invariants that block, and statistical baselines that alert. Invariants: null count in primary key = 0, row count >= 0, foreign key coverage >= 99.9%. Baselines: per metric per segment (dataset, partition, tenant), with weekday and holiday regressors.

Robust baselines matter because a single bad day inflates mean and standard deviation. For a table with daily row counts, median 1.2M, MAD 80k. A day at 400k gives robust z = 0.6745*(400k-1.2M)/80k = -6.7, flagged. Mean/std would give std inflated by the same 400k, z maybe -1.5, missed. Use STL or Prophet for weekly seasonality; Prophet's default 80% interval is too loose for alerting: set interval_width=0.99 and still require 3 consecutive breaches to page.

Python
import numpy as np
def robust_z(x, hist):
    med = np.median(hist)
    mad = np.median(np.abs(hist - med))
    return 0.6745 * (x - med) / mad if mad > 0 else 0.0
# hist = last 28 days same weekday, excluding known incidents
metricmethodthresholdaction
volumerobust z on 28d same weekdayabs(z)>3.5 for 2 daysalert
null proportionbinomial tail vs 30d baselinep<0.001alert
freshnessmax lag vs SLA>6hblock
category distributionPSI vs 30dPSI>0.2alert

Baseline poisoning: a producer bug slowly drops 1% of rows per day. Robust z never fires because the baseline follows. Detect by monitoring baseline drift: median moves >5% over 7 days without a known event label. Freeze baselines on schema or code version change; require a human to accept a new baseline. Detection signal: baseline_drift_7d > 0.05 and no event label. Cost: one false alert per table per quarter if threshold too tight.

Concept drift: a new source version changes category values. PSI jumps to 0.4. Alert, but do not block; compare to peer tables with same schema version.

Alert vs block: block only when impact > $10k or regulatory, and confidence > 99.9% from an invariant. Otherwise alert. Shadow mode for 2 weeks: run detection, log alerts, measure precision/recall against historical incidents. If precision < 80% at the chosen threshold, raise threshold or add segment. When the approach is wrong: tables with <100 rows/day. Statistical baselines are noise; use deterministic checks only. High-cardinality categoricals: per-category z is multiple-testing hell; use PSI or KL on the whole distribution.

Backtest on last 6 months of incidents and normal launches. Inject synthetic shifts: +20% volume, +5% nulls, 12h freshness lag. Measure detection delay: median 1 day for volume, 2 days for nulls. If delay > SLA, add a real-time stream check.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Define data-quality observability and service objectives.

Answer

Two things get conflated here, so I'd separate them before answering.

Data-quality observability is the telemetry that lets you answer, without asking a human, whether a dataset is fit for the decision it feeds, and if not, which rows, since when, and who owns it. Service objectives are the SLOs you put on that telemetry: a target, a window, and an error budget.

The assumption I'd state up front: objectives attach to a critical decision (revenue recognition, fraud scoring, the exec dashboard) not to a table. One table can feed a decision that tolerates a two-hour lag and another that doesn't, so the same dataset gets different objectives per consumer.

I'd define four families. Coverage: what fraction of critical fields and populations have a current control. Execution health: did the validators actually run, on the right data version, before publication. Detection and protection: how fast you notice and how fast consumers stop trusting bad data. Resolution: how fast you replay corrected data.

SLISLO (hypothetical)Window
Freshness: age of latest partition at 07:00≤ 30 min on 99% of days30d
Completeness: rows loaded / rows in source manifest≥ 99.9% per runper run
Validity: critical-field assertions passed100% before publishper run
Detection: bad row lands → alertp95 ≤ 15 min7d
Protection: alert → consumers blocked or marked stalep95 ≤ 5 min7d
Resolution: corrected data replayedp95 ≤ 4h30d
Escaped defects reaching a consumer decision≤ 1/quarter, severity ≤ 290d

That freshness SLO gives a budget of 0.01 × 30 × 1440 = 432 minutes of allowed staleness per month. Two four-hour incidents burn it, which is the point: the budget tells you whether to spend the next sprint on the pipeline or on the feature.

The mechanism worth explaining is why assertion pass/fail/skip/error has to be tracked separately from severity and from the publication action. A rule can pass and still be wrong: an always-green rule that tests a column nobody writes anymore. A validator can error because its queue backed up, and an error is not a pass. A rule can skip because no data arrived, and a skip is not a pass either. So the check's own health is a separate SLI from the data's health, and a missing or stale result counts as failure, not silence.

On trade-offs, the deciding criteria are blast radius and reversibility. Block publication when the consumer is an automated decision that can't tolerate stale input and the pipeline can re-run cheaply. Mark stale when a human reads it: a late number with a visible warning beats no number. Quarantine when you can isolate bad rows and publish the rest, which is usually the cheapest option and the one most teams under-use.

Three failure modes I'd name. Silent failure: the validator runs and passes, but against the wrong data version. Detect it with independent reconciliation, a count or checksum recomputed from source outside the rule engine, not with the same engine that just said pass. Broken alert path: inject a synthetic bad-data canary on a schedule and require the alert to fire and the runbook action to execute; if the canary doesn't fire, your observability is down, not your data. Always-green rules: track per-rule pass rate over 90 days and treat zero variance as a bug in the rule.

Finally, publish a data-version quality status consumers can read (which version, which checks ran, what's stale) so they can decide for themselves instead of paging you.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Test and monitor the data-quality rules themselves.

Answer

What I'd say first

The rules are code, so test them like code, but the failure that hurts is not a rule that crashes, it's a rule that passes while the data is wrong. So I'd split the work: unit fixtures for the rule logic, replay against real history for the rule's scope, and production monitoring of the rule's own behaviour. Assumption: rules are declarative checks (dbt tests, Great Expectations, Soda) run on a schedule against a warehouse, and each has an owner and a severity.

Unit fixtures: three cases per rule, not one

Every rule gets a known-good fixture, a one-defect fixture, and a boundary fixture. The boundary is where rules actually break: amount >= 0 vs amount > 0, a timestamp exactly at the partition edge, a null in a column the rule treats as non-null.

Python
# rules.py — Python 3.12
from decimal import Decimal

def check_amount_non_negative(rows):
    bad = [r["order_id"] for r in rows if r["amount"] < 0]
    return {"passed": not bad, "failed_ids": bad}
Python
def test_zero_passes():
    assert check_amount_non_negative([{"order_id": 1, "amount": Decimal("0")}])["passed"]

def test_one_defect_fails():
    res = check_amount_non_negative([
        {"order_id": 1, "amount": Decimal("10.00")},
        {"order_id": 2, "amount": Decimal("-0.01")},
    ])
    assert res == {"passed": False, "failed_ids": [2]}

Trace: in the first, Decimal("0") < 0 is False, so bad is empty and passed is True. In the second, 10.00 < 0 is False and -0.01 < 0 is True, so bad == [2] and passed is False. Now mutate the rule, change < to <=, and test_zero_passes must fail. If it still passes, the boundary test has no teeth. That mutation step is what separates a fixture that documents intent from one that proves it.

Replay and scope

Fixtures only cover shapes you imagined. Replay the last 20 incidents: for each, ask which rule would have fired. If 12 of 20 had no rule at all, that's your backlog, and it's the only honest measure of coverage. A green suite says nothing about rules that were never written.

Monitoring the rule, not just the data

Record run status separately from pass/fail: "did not run" and "passed" are different facts, and a validator outage that reports green is the worst outcome. Then watch per-rule history:

signalwhat it meansaction
passes 100% for 90 days on a daily tablerule is trivially true or reading the wrong columninspect the query, check rows seen
fails 100%real incident or broken ruletriage before muting
fires on >5% of rowsthreshold wrong, not data wrongshadow-tune
no owner, no consumernobody acts on itdelete via impact analysis

The arithmetic that kills a rule set: 300 rules, each with a 0.5% false-positive rate per daily run, gives ~1.5 false alerts a day. Within a week the channel is muted and the real alert is missed. That's why false-positive rate is a first-class metric, not a nice-to-have.

Trade-offs

Fixtures are fast and precise but blind to real data shapes; replay is realistic but needs history retained and is slow. Blocking rules stop bad data, but a broken blocking rule stops the pipeline, so anything that gates needs a kill switch and a canary. New or retuned rules run in warn-only for a week and I compare fire rate before enforcing. Not every rule deserves the same depth: a rule guarding a regulatory number gets fixtures, replay and mutation; a freshness smoke check gets one test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Use sampling for large-scale data validation responsibly.

Answer

Sampling is a detection instrument with a power curve, so the first move is to name the defect prevalence you must catch and check whether sampling can reach it. For a defect that appears independently at rate p, the chance a sample of n rows contains at least one is 1 − (1 − p)^n, so the n for confidence C is ln(1 − C) / ln(1 − p). At 95% confidence:

prevalencen for 95% chance of ≥1 hit
1 in 100298
1 in 1,0002,994
1 in 10,00029,956
1 in 100,000299,573

That table is the whole argument. A 1-in-100k defect (a cross-tenant leak, a mis-signed financial total) needs ~300k rows sampled to be seen at all, and if the population is 4B rows that is a 0.0075% sample that still costs real money and still misses 5% of the time. So for rare critical defects you do not sample; you run exact controls: row counts per partition, checksums over the key columns, min/max of timestamps and amounts, and source-position reconciliation. Sampling is for the broad, higher-prevalence classes where the arithmetic above is affordable.

Assumptions that decide it

The formula assumes defects are independent and uniformly distributed. That assumption is what usually fails, and it fails in a specific direction: defects cluster. A deploy at 14:02 writes bad rows until 14:09; a single tenant's ETL mis-maps a column. Uniform sampling under-covers clusters, so you stratify by the dimensions along which defects cluster (tenant, region, category, write time) and oversample small or high-risk strata, then reweight when you report a rate. Concretely: if tenant X is 0.5% of traffic, a uniform 3,000-row sample yields ~15 rows from X, which cannot distinguish a 1% defect rate from a 10% one. Oversampling X to 500 rows and weighting by 0.005/0.167 recovers the estimate.

Failure modes

  • Ordering bias: WHERE id % 1000 = 0 on an auto-increment id samples by insertion time, so a time-localized defect is all-in or all-out. Hash a stable business key with a recorded seed instead.
  • Partition omission: a sample drawn from the main table misses rows that only exist in a late-arriving partition or a quarantine table.
  • Source evolution: a schema change or backfill invalidates the manifest's population definition, and the sample silently stops representing the current version.

Artefacts

Deterministic, seed-recorded selection so the check is reproducible:

Python
import hashlib

def in_sample(key: str, seed: str, rate: float) -> bool:
    h = hashlib.blake2b(f"{seed}:{key}".encode(), digest_size=8).digest()
    return int.from_bytes(h, "big") / 2**64 < rate

Same key and seed always give the same verdict; changing the seed rotates the sample across runs while sentinel rows (known-good and planted-defect cases) stay pinned. Store seed, rate, strata weights, population version and row count in a manifest next to the results.

Reporting

A passing sample is evidence of absence at a stated power, not proof. Publish the residual risk: "at n=3,000 we detect a 0.1% defect with 95% confidence; we would miss a 0.01% defect 74% of the time." Escalate coverage after an anomaly rather than re-tuning the sample to fit the cost budget.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Control the cost of data-quality validation without losing critical assurance.

Answer

Clarify first: which datasets are critical, what is the monthly budget, and what does a missed defect cost? Assume a warehouse stack (BigQuery or Snowflake, dbt tests plus Great Expectations, Airflow orchestration) and that "cost" means warehouse credits, results and quarantine storage, and on-call time.

The answer: price each rule, then move each check to the cheapest layer that still catches its defect, and keep exact checks only where a miss is expensive. Four moves: attribute cost per rule, tier by placement, schedule expensive scans by risk, and delete waste.

1. Attribute cost per rule

For every rule, log bytes or credits scanned, rows written to the results table, quarantine bytes, and alert fan-out. Join that to the dataset's criticality and query frequency to get a cost per protected decision. On BigQuery on-demand, a full-table uniqueness test on a 10 TB table costs $50 at $5/TB scanned (2024 list price); the same test scoped to today's partition costs cents. Metadata checks against INFORMATION_SCHEMA are not billed at all. On a flat-rate slot reservation the marginal cost is slot-seconds rather than bytes, but the same consolidation logic applies.

2. Tier by placement

PlacementExampleCost per runAssurance
IngressSchema Registry, NOT NULL~$0Structural, pre-landing
MetadataINFORMATION_SCHEMA schema drift$0 (not billed)Schema, partitions
Warehouse, scopeddbt test on one partitioncentsDomain, per-partition
Warehouse, fullCross-system reconciliation$5/TB scannedExact, cross-system
Sampled1% sample, noncritical$0.05/TBStatistical, misses rare defects

Share scans: one pass over a partition can compute null count, distinct count, min/max together instead of four queries. Store results per partition with a version and re-validate only changed partitions. Compute incremental metrics only when the merge semantics match the update semantics: sum and count update incrementally, distinct count needs a sketch such as HyperLogLog or a full scan.

3. Schedule expensive scans by risk

A full source-to-target reconciliation can run weekly on stable data and daily on high-churn data. For noncritical data, sample with a stated confidence: to detect a defect affecting 1% of rows with 95% confidence you need n where 0.99^n ≤ 0.05, so n ≈ 298 rows. Keep exact checks on critical controls.

4. Remove waste

Delete duplicate, obsolete, and ownerless rules after an impact review. Fix always-fail and always-green rules: they train people to ignore alerts. Partition and cluster validation reads so they touch only relevant data. Cap backfill workloads.

Guardrails

Skipped or stale validation is never a pass. Quarantine is never hidden. Source retention stays long enough to repair. Critical financial and tenant controls are never weakened or sampled. Alert when validation does not run, and on p95 validation latency and publication freshness. Report cost per protected decision and residual coverage.

Worked example

1,000 dbt tests run daily, each scanning 1 TB, at $5/TB → $5,000/day. Breakdown: 800 single-metric tests across 200 tables, 180 partitioned tests, 20 cross-system reconciliations.

  • Consolidate the 800 into 200 multi-metric passes (4 metrics each): 200 TB.
  • Run the 180 partitioned tests incrementally, 10% of partitions changed: 18 TB.
  • Keep the 20 reconciliations full: 20 TB.

Total 238 TB → $1,190/day, saving $3,810/day (76%). Assurance holds because the 20 critical reconciliations still run full and sampling is confined to noncritical dashboards.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design data-quality validation for an event stream.

Answer

The answer, roughly the first 90 seconds

Assume Kafka 3.x as transport, about 20k events/s across 60 partitions, and a consumer that builds a per-tenant hourly rollup plus a daily billing total. A missing event costs money; a late one costs a correction. So the job is not to stop disorder, it is to make loss and duplication visible and replayable.

Pin an envelope first: event_id generated by the producer (never regenerated downstream), schema_id from a registry (Avro or Protobuf), producer_id, tenant_id, event_time, ingest_time, partition key, and a per-(producer, key) sequence number. Then three layers. Stateless checks at ingress, with rejects written to a dead-letter topic carrying topic:partition:offset so the exact record can be replayed. Stateful checks per key with every window bounded by a TTL, because unbounded validator state is how these jobs die at 3am. And a metrics layer reported by event-time window and by (producer, partition), next to the broker's end offset, so you can tell 'the source went quiet' from 'the consumer is stuck'.

Check table (starting values, tune with production traffic)

checkwherestarting thresholdon failure
schema_id resolvable, event_id non-nullingress, statelesseither missingdead-letter with source position
value rangesingressamount >= 0, latency_ms <= 86400000dead-letter
producer clock skewingressingest_time - event_time > 2 h flags, > 24 h dead-lettersflag or isolate
duplicate event_idkeyed state, 15 min TTLsecond occurrence inside TTLdrop, increment dup counter
sequence gap per (producer, key)keyed state, 30 min TTLany gapalert, hold the window back from 'final'
watermark lagoperator metricp99 lag > 5 min sustained 10 minpage
partition offset gapbroker monitoronly on cleanup.policy=delete topicsalert

Sizing the duplicate window

20,000 events/s times a 1-hour dedup TTL is 72M live keys. At roughly 120 bytes per RocksDB entry (36-byte UUID, timestamp, value, overhead) that is about 8.6 GB of state per task before compaction overhead, which does not fit a modest heap. A 15-minute TTL is 18M keys, roughly 2 GB, and still comfortably exceeds the producer's retry horizon. That is the whole argument for a TTL rather than an unbounded set.

One event traced through it

An event with event_time T, event_id present, amount positive, arrives at ingest time T+7m. The watermark for that partition is at T+3m, so it is late but inside a 5-minute allowed lateness. It is emitted as an update that retracts the earlier window result. If the same event arrives at T+9m instead, it falls outside allowed lateness and is routed to a late topic, counted under 'late', and the window that already went final is flagged for reconciliation. Nothing is dropped silently in either branch.

Flink's allowedLateness defaults to 0, which quietly discards late events from window results; set it and wire the side output. Watermarks also lag the slowest partition, so one idle partition stalls every downstream window, which is what WatermarkStrategy.withIdleness(Duration.ofMinutes(1)) is for.

Failure modes worth naming

Offset gaps are normal on compacted topics, so alerting on them there fires constantly; check cleanup.policy before trusting that signal. Broker-side idempotence (default true since Kafka 3.0, KIP-679) only covers retries inside delivery.timeout.ms, default 120 s; a producer that restarts and re-sends under a new event_id defeats it, which is why the business-level dedup window is the real defence. A watermark means 'probably complete', never 'complete', so publish provisional and final status and only mark final after reconciliation against a source of truth. And cap dead-letter writes per producer, or one poisoned producer fills the topic and takes the pipeline down with it.

Test producer clock skew, broker failover mid-produce, partition reassignment, a schema mix during a rolling deploy, replay from offset 0, checkpoint loss, a late delete, and a poison burst. Hash or truncate payload samples in logs and keep tenant state and dead-letter access scoped per tenant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design data-quality checks for machine-learning features and labels.

Answer

Core answer

Assume a feature store with batch training and online serving, labels that arrive late, and a model whose decisions carry real cost. I'd build three layers of checks and wire each to a specific action.

Layer 1: contract. Every feature and label declares entity key, event timestamp, availability timestamp, source, version, dtype, unit, and null policy. Enforce it with a schema tool: TFDV or Pandera on the dataframe, Great Expectations or dbt tests in the pipeline. A null rate above the declared budget: say 0.5% for a required feature: fails the batch.

Layer 2: point-in-time correctness. This is where most silent damage happens. Every training row must join only feature values whose availability timestamp is at or before the event timestamp. Do it with an as-of join, not a plain merge:

Python
pd.merge_asof(
    events.sort_values("event_ts"),
    features.sort_values("feature_ts"),
    left_on="event_ts", right_on="feature_ts",
    by="entity_id",
    direction="backward",
    tolerance=pd.Timedelta("7d"),
)

direction="backward" takes the last value at or before the event; tolerance caps staleness so you don't silently use a 90-day-old value. Then assert max(feature_ts) <= event_ts on the joined frame: one violation means the join is wrong.

Layer 3: parity and distribution. Sample matched entity/time pairs, pull the online value and the offline value, and alert if more than 1% differ beyond tolerance. Track quantiles, null rate, and categorical cardinality per cohort.

Labels

Labels need their own checks: provenance, arrival lag, censoring, corrections. Example: if 30% of labels land within 24h, 90% within 7 days, 99% within 30 days, training on data younger than 7 days drops roughly 10% of labels and biases toward fast-resolving cases. So gate training on a label-maturity window and record it.

Failure modes and detection

failuredetectioncost if missed
future-value leakagemax(feature_ts) > event_ts in joined setoffline AUC 0.95, online 0.62
training-serving skew>1% of matched samples differsilent accuracy loss
stale online cachep99 feature age > TTL at serve timefallback defaults served
unseen categoryserved cardinality > training vocabularydefault bucket, wrong score
duplicate entitydistinct entity_id < row count per windowinflated weight in training
delayed/censored labelarrival-lag distribution shiftsbiased labels

Trade-offs

Block vs degrade: block when the failure breaks the join or the label semantics (negative age, label before event, wrong unit) because that corrupts training irreversibly and you can't detect it later. Degrade (serve the fallback default, log, alert) when only feature quality drops; blocking there costs availability for a model that could still answer. Hard rules vs drift: invariants (age >= 0, unit in a fixed set) are gates; drift is evidence, not a gate. PSI above 0.2 opens a review, it doesn't stop serving, because seasonality and a new market look identical to breakage. Bind every validation result to the feature-dataset and model version so a rollback goes to a verified pair.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Validate a historical backfill or restatement.

Answer

What I'd say first

Before touching anything: is this a correction (the data was wrong) or a redefinition (the data was right under the old meaning)? That one question decides almost everything downstream, and I'd get it answered before writing a line of backfill code.

Assumptions I'd state out loud: the source still retains the history I need; downstream consumers can tolerate a bounded window where old and new partitions disagree; and I have a way to pin the source to a point in time.

Then the answer: pin the source, run the new logic into staging, diff old against new by key and period, classify every difference, and publish atomically, or don't publish at all.

Pinning the source

Pin by snapshot ID, not by timestamp. Iceberg and Delta both give you a snapshot/version handle; a timestamp can land you on a different snapshot than the one you validated against. If the source is Snowflake, Time Travel defaults to 1 day of retention (90 days on Enterprise), and BigQuery's time-travel window is 7 days, so if the correction window is older than that, you cannot re-read the source and you're validating against the landed raw copy instead. Say that out loud; it changes what "validated" means.

Rule versioning: the trade-off

Two options, and the deciding criterion is one question: does a historical row mean the same thing today as it did then?

  • If yes, the change is a bug fix in code, apply the current rule to all history. One rule, one code path.
  • If no: a status code was repurposed, a currency redenominated, a fiscal calendar shifted: version the rule and run the historical one over the historical interval. Applying today's thresholds to old data is how you silently rewrite history.

Full rebuild vs. patch-forward

Rebuild when the rule change is semantic and touches every partition. Patch forward when the defect is bounded to a known interval and the old logic was correct elsewhere. And sometimes the right answer is neither: if the error affects 0.1% of rows and no decision or downstream model depends on them, the cost of a rebuild (reprocessing, downstream invalidation, consumer churn) usually exceeds the benefit. Documenting the defect and moving on is a legitimate outcome.

The differential test

Stage the output, then diff old vs. new on (key, period). Every row must land in a class. Unclassified rows block publication.

Hypothetical example, one account-month grain:

keyperiodoldnewdeltaclass
acct 44712024-031,204.001,204.000unchanged
acct 44712024-040.00318.50+318.50late-arriving correction
acct 88122024-04902.101,041.30+139.20FX rate restated
acct 90032024-0455.000.00−55.00duplicate removed

Totals: 2,161.10 → 2,563.80, delta +402.70, which must equal the sum of the classified deltas. If it doesn't, something is unclassified.

For volume checks, compare against the same weekday or same season last year, not today's volume. A 3% drop in daily rows is noise if the same weekday last year also dropped 3%.

Publishing and failure modes

Publish by partition swap (write to the partition decorator with WRITE_TRUNCATE, or Snowflake's ALTER TABLE ... SWAP WITH) so consumers never see a half-repaired interval. Keep the pre-swap table for rollback. Then rebuild downstream aggregates, features and exports, and tell consumers the restatement happened.

Failure modes I'd test explicitly: duplicate backfill (idempotency key on the run), partial failure mid-partition, a rule that references a column that didn't exist in the historical schema, late corrections arriving after publication, and rollback itself. Run the backfill with max_active_runs=1 so partitions don't overlap.

If the evidence for an interval has expired (source purged, logs rotated) document the assurance gap. Don't mark it passed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Use lineage for quality impact analysis without overstating certainty.

Answer

What I'd say first

Before I trust lineage for impact analysis I want to know two things: what grain the graph is at, table or column, and whether quality results are keyed to a specific dataset version or partition. If results are only keyed to "the table", I can tell you which downstream nodes exist, but not which of them saw the bad data.

Assumption I'd state out loud: we have a lineage graph with column-level edges where the SQL is parseable, and a test/assertion store that records, per run, the assertion ID, the rule version, the result, and the exact input and output snapshot it ran against.

Then the answer: impact analysis is a graph traversal from the failing node, and the honest output is a set of observed reachable consumers, not a proof of everything affected.

Mechanism

Attach each quality result to the edge, not the node. In dbt terms, run_results.json gives you unique_id and invocation_id per test; manifest.json gives you parent_map and child_map. Join the failing test's unique_id to the node, then walk child_map. In OpenLineage terms, the run event carries runId, job, inputs, outputs, and a columnLineage facet when the producer can resolve columns.

Worked trace (hypothetical project)

Graph: stg_orders → fct_orders → dim_customer_ltv → ml_churn_features.

Test not_null on stg_orders.customer_id fails at invocation 2024-06-01T02:14Z.

  • Table-level walk of child_map: {fct_orders, dim_customer_ltv, ml_churn_features}. 3 downstream nodes.
  • Column-level walk of the columnLineage facet for customer_id: fct_orders.customer_id, dim_customer_ltv.customer_id. ml_churn_features reads order_total and order_count only, so it is not reachable through that column.

So the blast radius I report is: 2 nodes affected by the column, 3 nodes affected if the row count also changed. That distinction is the whole point: it's what stops you paging the ML team for a null in a column their features never read.

What lineage does and doesn't support

ClaimSupported byOverstated if
These consumers read the failing columncolumn-level edges + version-keyed resultyou claim they received bad values
This consumer is unaffectedabsence of a path in the graphthe graph has a coverage gap
The rule was correctnothing in lineageyou treat a passing test as semantic correctness

Failure modes and how I'd detect them

  • Dynamic SQL / templated queries: the parser can't resolve the edge. Detect by diffing lineage edges against query history for the same window: a table read in ACCESS_HISTORY with no lineage edge is a gap, not a non-reader.
  • Rename or retry: the old node lingers as an orphan. Detect by counting nodes with no upstream and no downstream and reconciling against catalog inventory.
  • Event lag: the quality result lands after the incident is over. Detect by comparing the event timestamp to the run completion timestamp and alerting on skew.
  • Environment collisions: orders in dev and prod collapse into one node. Detect by requiring namespace in the node key.

Trade-offs

Column-level lineage costs you a SQL parser and breaks on dynamic SQL; table-level is cheap and always available. I'd pay for column-level only on tables feeding sensitive fields or published metrics, and fall back to table-level elsewhere. And there are cases where lineage is the wrong tool: if the failure is a value-level semantic problem with no downstream consumer, or if graph coverage is low, a consumer survey or query-history diff answers the question faster.

Coverage arithmetic (hypothetical): 1,200 tables in the catalog, 1,050 with at least one lineage edge → 87.5% node coverage. Report that number next to every blast radius, because "3 downstream nodes" means "3 of the nodes we can see".

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Protect sensitive data in quality validation and profiling.

Answer

First 90 seconds. Assume the quality platform is a separate plane from the warehouse, and the data is multi-tenant with direct identifiers (email, SSN, account number) plus quasi-identifiers (DOB, ZIP, country). My default: don't copy raw rows into the quality plane at all. Push the checks down as SQL that runs inside the data boundary and returns aggregates and counts. When a sample is genuinely needed for triage, tokenize direct identifiers with a keyed hash so equality and join checks still work.

Why keyed hashing, not plain hashing. A deterministic HMAC-SHA256 with a per-tenant key held in KMS preserves equality, COUNT(DISTINCT email_hmac) and joins to a reference table still work, while defeating re-identification. Plain SHA-256 does not: the SSN space is 10^9, and a single GPU computes on the order of 10^10 SHA-256/s, so an unsalted hash of an SSN is recovered in under a second. A random salt fixes that but destroys joinability, which is the whole point of the check. The keyed hash is the middle: same input gives the same token within a tenant, different tokens across tenants.

Why a minimum group size. Uniqueness checks are the leak. A "distinct country" profile that reports one row for a rare value, in a tenant with 40 rows, has just identified a person. I set a floor of k=5 on any group emitted to a shared profile or dashboard; groups below it are suppressed, not rounded. HIPAA Safe Harbor is the stricter cousin: it removes 18 identifier types outright rather than generalizing.

Field classTechniqueWhat it breaks
direct identifier (email, SSN)HMAC-SHA256, per-tenant KMS keydistribution and histogram checks
quasi-identifier (DOB, ZIP)generalize to a band (age 30-39, ZIP3)exact-match joins
measure (amount, latency)keep raw inside the boundary, emit aggregatesper-row outlier inspection

Worked trace of the suppression rule, tenant acme, 40 rows:

SQL
SELECT country, COUNT(*) AS n
FROM dq.orders_masked
WHERE tenant_id = :tenant
GROUP BY country
HAVING COUNT(*) >= 5;
country groups: US 34, DE 5, LI 1
HAVING n >= 5  ->  US and DE emitted; LI suppressed

Failure modes and how I'd catch them.

  • Assertion echoes the secret. A format check on email puts the offending value into the error, which lands in the Airflow task log and the alert email. Detection: seed a canary row with a sentinel value, run the suite, assert the sentinel never appears in the result store or logs.
  • Rare-category inference. Detection: alert whenever any emitted group has count < k.
  • Validator pointed at an unmasked source. Detection: a policy test that fails the job if its source isn't on the approved masked-view list.

Trade-offs. Tokenization is wrong when the check is distributional: you cannot compute mean(age) or a histogram on an HMAC. Keep numeric and date fields raw inside the boundary and tokenize only direct identifiers; if you need the shape preserved, format-preserving encryption (FF1) keeps the format but is slower and needs key-rotation discipline. Aggregate-only profiling loses the single bad row, so run row-level checks in-boundary and emit only counts.

Close. What would change my decision: if the data is single-tenant and already de-identified at rest, the tokenization layer is cost without benefit and I'd profile raw. If a regulator requires per-row evidence, I'd keep raw rows in a 7-day quarantine behind 15-minute STS credentials with every read audited, rather than weaken the aggregate path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design quality controls for a multi-tenant dataset.

Answer

Assumptions first. I'll take "multi-tenant dataset" to mean one logical table where every row carries a tenant_id, fed by both batch files and a Kafka topic, with a few thousand tenants and one tenant at roughly 30% of volume. If tenants are physically separated instead, most of this collapses into per-tenant pipelines and only the shared control plane is interesting. I'll assume shared.

The core answer. Four layers, in order: bind identity, scope the controls, isolate compute and results, then reconcile and alert.

1. Bind identity at ingestion. Tenant identity comes from the authenticated principal, never the payload. In Postgres 16 that's a row-level security policy:

SQL
ALTER TABLE events ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON events
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

The writer sets app.tenant_id from the verified token. If it's unset, current_setting raises unrecognized configuration parameter and the query fails closed. Snowflake row access policies and BigQuery row-level security do the same job with CURRENT_ROLE() and SESSION_USER(). A client-supplied WHERE tenant_id = ... is a filter, not isolation: it's the thing you're defending against.

2. Scope every control. Each control is either global (schema, cross-tenant referential integrity) or tenant-scoped. Example thresholds, tuned per contract:

controlscopeexample thresholdaction
uniquenesstenant + business keyany duplicate in windowquarantine row
completenesstenant + columnnull rate > 0.5% over 3 batcheswarn; > 2% block publish
freshnesstenant + sourcep99 lag > 15 minpage owner
volumetenant + day|z| > 4 vs trailing 28 same-weekday dayswarn
referentialtenantorphan FK > 0quarantine

For distinct-count controls across thousands of tenants, HyperLogLog at p=14 (16,384 registers, ~0.81% relative error) is cheap enough to run per tenant per batch; exact COUNT(DISTINCT) is not.

3. Worked trace: why tenant-scoped uniqueness matters. Batch from t_42, source position events/7:1042, five rows:

#tenantorder_idoutcome
1t_429001accepted
2t_429002accepted
3t_179002routed to t_17
4t_429001quarantined (dup within tenant)
5t_429003accepted

Reconciliation: 5 in = 3 accepted + 1 quarantined + 1 routed. A global uniqueness check on order_id alone would have quarantined row 3, a valid t_17 row, which is the classic cross-tenant false positive. The same reasoning applies to surrogate keys: hash (tenant_id, business_key), never business_key alone, or two tenants collide on the same generated id.

4. Isolate compute and results. Per-tenant result caches must be keyed by tenant, not by query text. Tiny tenants are the mirror problem: a per-tenant metric computed over 3 rows discloses behavior, so suppress or roll up below a minimum group size (k=5 is a common floor) and expose aggregates only above it. On compute, cap any tenant at a share of cluster slots: a token bucket with weighted fair queuing, or a dedicated Snowflake warehouse for the 30% tenant, so one backfill can't starve everyone else.

5. Failure modes and how you catch them. Missing tenant key: assert non-null count equals input count and reject the batch; never default to a tenant. Cache leak: seed a canary tenant with unique strings, query as another tenant, assert zero rows. Replay: idempotency on (tenant_id, source_position); re-run the same offset range and assert accepted counts are unchanged. Hot tenant: watch per-tenant queue-wait p99, not just cluster CPU.

Alerts carry tenant_id and the metric, routed to that tenant's owner, never another tenant's rows. Severity is consequence-based: one tenant's failed freshness check blocks that tenant's publish, not the platform's.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Migrate from ad hoc data checks to a governed quality platform.

Answer

The 90-second answer. Assume the goal is fewer escaped defects per quarter, not a tidier catalogue. Don't migrate checks; migrate decisions. Pick the 10–20 datasets whose failure pages someone, and for those only, replace the ad hoc script with a versioned assertion that has an owner, a severity, and a result row you can query. Everything else stays where it is until it earns promotion. The migration is done when the old check is deleted and the new one has fired in production at least once, not when the YAML parses.

Assumptions to state out loud: you have a scheduler you already trust (Airflow, Dagster, dbt Cloud), a warehouse with a queryable results table, and at least one consumer who will tell you whether an alert was useful. Without the last one you are building a platform nobody reads.

Why contracts and assertion IDs, not more checks. The failure mode of ad hoc checks isn't coverage, it's that a check is a script with no identity: you can't tell whether it ran, whether it was waived, or whether the same rule exists in three dashboards under three names. A stable assertion ID (orders.freshness.updated_at.max_lag_2h) gives you a row per execution in a results table, so "did it run" and "did it pass" become one SQL query instead of Slack archaeology. dbt does this with store_failures: true and severity: warn|error; Great Expectations does it with checkpoints writing to a validation store; Soda does it with warn/fail thresholds in SodaCL. The mechanism is the same: the check's outcome is data, so you can measure it.

Worked example (figures illustrative). Inventory returns 3,200 checks across 900 tables. Query the scheduler's run history for 180 days:

bucketcountaction
never fired1,310 (41%)delete after owner sign-off
fired, never actioned980 (31%)demote to warn, or delete
fired and paged someone410 (13%)port first, with fixtures
duplicate of another check500 (16%)keep the one with an owner

Port the 410. For each, replay 90 days of history against both old and new implementations and diff the pass/fail sets. If the new check disagrees on more than a handful of partitions, the port is wrong, not the data.

Failure modes, with signals.

  • Validator outage. The check platform is down; pipelines keep publishing. Detection: freshness of the results table itself. Alert if no result row for a dataset in 2× its expected cadence. Blast radius: silent bad data for the outage window, so you need a replay path.
  • Schema evolution. A column rename turns 40 checks into errors, not failures. Detection: error-rate spike per dataset, distinct from fail-rate. Cost: if errors page, on-call learns to ignore the platform.
  • Backfill. A three-year backfill re-runs every assertion and pages on historical violations. Detection: assertion runs with a partition older than the publication SLA. Fix: suppress alerts for backfill runs, keep the results.
  • Permissions. The validator's service account can read prod but not the quarantine schema, so replay fails at 3am. Detection: a canary dataset whose replay runs on every deploy.

Trade-offs and when not to do this. With fewer than ~50 checks, one consumer, and no on-call rotation, a governed platform is overhead: a cron job and a Slack channel is the right answer. If your checks are mostly non-deterministic (distribution drift, anomaly detection), porting them into a pass/fail framework loses the thing that made them useful: keep those in a separate tier with their own alert budget. And don't convert every old threshold into a blocker on day one: a check that has never paged anyone has not earned the right to wake someone up.

Success: escaped harmful defects per quarter down, mean time from bad publish to detection down, checks that fired and were actioned up. The migrated-rule count is not a metric.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Establish ownership and governance for data-quality controls.

Answer

The 90-second answer

Assume: several teams publish into a shared warehouse, one platform team runs the orchestrator, and at least one control is regulated. Governance is then a mapping from each control to exactly one accountable human, plus a bounded way to say "not now."

The split that survives contact with production:

ArtefactAccountableWhy
Source contract (schema, freshness, nullability)Producing teamThey can change the code that breaks it
Grain, semantics, severity, publish/no-publishData-product ownerOnly they know what a wrong number costs
Assertion execution, evidence retention, alert deliveryPlatformSame mechanism for every product; thresholds are not theirs
Declared requirement ("<1% error by 07:00")Consuming teamOtherwise they inherit someone else's definition of correct

Why it works: each row is owned by whoever can actually fix the failure. What breaks without it: platform teams drift into owning business thresholds, so every severity debate becomes a ticket queue; or producers own semantics, so a renamed column silently changes a revenue number.

Every critical rule carries rationale, scope, expected behaviour, owner, version, action on failure, runbook link and review date. Keep that record next to the code (dbt meta/config, or a YAML file in the same repo as the model) so it is reviewed in the same pull request.

Waivers. Authenticated, version-specific, time-bounded, reasoned, visible. Example policy numbers, tune to your risk appetite: default expiry 30 days, max 90 with a named approver, at most 5 open waivers per product, and any waiver on a regulated control needs a second approver. Cumulative limit: if open waivers cover more than 10% of a product's critical controls, the product owner is paged, not emailed.

Escalation. Unresolved warning older than 2 business days → product owner. Quarantine older than 24h on a critical control → on-call. Ownership absent (no owner, or the owner left) → platform owner assigns a temporary owner within 1 business day and the gap is tracked.

Metrics. Control coverage (share of critical datasets with at least one owner and one assertion), warning age, waiver age, mean time to resolution, escaped defects (bad data reached a consumer), stale owners (no review in 180 days).

Trade-offs. Full governance (per-rule owners, approval gates, separation of duties) is right when a wrong number is externally reported, regulated, or feeds money movement. For an internal exploratory table a lighter model wins: one owner per dataset, assertions in CI, no waiver process, no approval gate. Deciding criterion: blast radius × reversibility. If a bad value is cheap to detect and cheap to correct, don't build a committee.

Failure modes and detection.

  • Owner exists on paper, never responds → measure waiver age and MTTR per owner; a name with no activity in 90 days is stale.
  • Waiver becomes permanent → alert on waivers past expiry and count them in the coverage metric.
  • Separation of duties collapses (same person writes and approves a regulated rule) → audit log of rule/severity/waiver changes, reviewed quarterly.

Worked check (hypothetical). An orders freshness control: owner = Orders producer, severity critical, threshold 07:00 UTC. Day 1 the pipeline lands at 07:40. Assertion fails → warning to the producer's channel. No ack in 2 business days → product owner. Still open 24h past critical → on-call pages. Producer opens a waiver: "upstream vendor maintenance, expires in 14 days, approved by product owner." Coverage drops by one control; waiver age is tracked. If the vendor slips, the waiver expires and the control fails loudly again rather than silently.

Governance earns its keep when it makes the next decision faster: who decides, by when, with what evidence. If a process can't answer those three, cut it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Respond to a data-quality incident after bad data reached consumers.

Answer

First I'd ask two questions: is the bad data still being written, and are any consumers making irreversible decisions from it? Assume a warehouse stack: Airflow for orchestration, dbt for transforms, Great Expectations for tests, OpenLineage for lineage, and a BI layer. My lead answer: contain the writer, freeze evidence, reconstruct blast radius from lineage plus query logs, repair with a versioned backfill, then fix the control that failed.

If the writer is still active, pause the Airflow DAG or Kafka consumer at the exact offset. Don't delete the bad partition. Mark affected tables and views invalid or stale in the catalog. Invalidate the BI cache; otherwise a rollback won't change what users see. Preserve source manifests, raw snapshots, dbt run artifacts, test results, query history, and consumer export files under a read-only role or object-lock bucket.

For blast radius, use OpenLineage to get downstream models, then query information_schema or Snowflake ACCESS_HISTORY for actual reads. Lineage is often incomplete for ad-hoc queries and CSV exports, so ask owners to confirm. Identify the last trusted version by comparing control totals per partition. Classify consumers. A dashboard can take a degraded corrected version. A billing or regulatory export needs a retraction and a corrected file. If a consumer already joined bad data into their own table, a rollback on our side doesn't fix theirs; give them a diff and a corrected snapshot.

Repair from a reproducible source snapshot, not by patching the bad table. Fix the logic in a new dbt model version, e.g. orders_daily_v2, and backfill a bounded interval with idempotent writes. Reconcile control totals: row count, sum, distinct keys. Validate representative metrics before republishing. Resume incremental processing from the exact boundary, not from 'now'.

Root cause is usually one of: missing rule, wrong rule, stale reference data, bad threshold, skipped validator, or a publication race. Don't just tighten thresholds; that creates alert fatigue. Add a test for the specific failure, e.g. expect_column_mean_to_be_between on amount_usd with a 5% band, and assign an owner. If privacy data was exposed, review access logs and rotate credentials.

Hypothetical trace: orders_daily for 2024-06-01 to 2024-06-03. A currency conversion UDF used a stale FX table. 12% of 4.2M rows have amount_usd inflated by 10%. Three dashboards and two CSV exports consumed it. At 09:12, a Great Expectations checkpoint fails: mean amount_usd is 312 vs expected 280-300. At 09:15 I pause the Airflow DAG. I query OpenLineage and information_schema: downstream models finance_revenue, sales_dashboard, exports finance_20240603.csv. I snapshot orders_raw partitions 2024-06-01 to 2024-06-03 to orders_raw_incident_20240603. I fix the FX table, rerun dbt --select orders_daily+ into orders_daily_v2. Backfill 4.2M rows in 18 minutes with 8 workers. Reconcile: expected sum 1,284,000.00, actual 1,412,000.00, after repair 1,284,000.00. Publish corrected version, invalidate BI cache, notify consumers via Slack #data-incidents and Jira ticket. Resume DAG from 2024-06-04.

Decision table for rollback vs degraded:

SituationActionWhy
Dashboard only, no irreversible decisionPublish corrected version, invalidate cacheUsers see right number without losing history
Billing or regulatory exportRetract, issue corrected file, track acknowledgementWrong money or compliance number must be formally withdrawn
Consumer already joined bad dataSend diff and corrected snapshotTheir table is outside our rollback boundary
Source snapshot missingDocument retention gap, don't fake repairA repair without source is not reproducible

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a data-quality strategy for a business-critical analytical product.

Answer

Core answer

Assume the product is a daily revenue and funnel dashboard that finance and pricing act on: a wrong number costs a pricing decision, not a page view. So the strategy is: name the decision each dataset serves, make the producer contract the first line of defence, run cheap checks before expensive ones, and make the publication boundary the enforcement point.

Concretely, in order:

  1. Contract at the producer. Schema registry (Avro/Protobuf) with backward-compatible evolution, plus typed dbt source declarations. A column rename fails CI, not the dashboard.
  2. Structural checks. Row count against the source manifest, null rate on keys, uniqueness of the declared grain.
  3. Semantic checks. Referential integrity to dimensions, cross-field rules (refund ≤ order total), time invariants (event_time ≤ ingest_time ≤ now + 5 min clock skew).
  4. Reconciliation. Source-to-target counts segmented by day and by tenant.
  5. Metric anomaly detection. Only on the published metric, against its own history.

Why that order: each layer costs 10–100× the previous one. A row-count check on 200M rows is a metadata read; a cross-field rule is a full scan; an anomaly model needs months of history. Running them in this order kills most defects before you pay for a scan.

Worked reconciliation (illustrative figures)

Orders table, 40M rows/day, 12 tenants:

segmentsource counttarget countdeltatolerance (0.01%)
tenant A18,400,00018,400,00001,840
tenant B9,120,0009,119,412−588912
tenant C2,300,0002,300,0000230

Tenant B is inside tolerance, but the delta is one-sided and persistent across runs: that is a warning, not a pass. Hard fail is delta > 0.01% or any delta on a monetary sum.

Enforcement

Block publication when the defect breaks grain, identity, or a monetary total: a duplicate order ID, or revenue off by more than 0.1%, means the dashboard is wrong, not stale. Quarantine when the defect is bounded and non-monetary: write bad rows to a dead-letter table keyed by run ID, publish the good partition, and show a banner with the row count and a fix deadline. Warn when it is cosmetic, e.g. a null in an optional dimension attribute.

Failure modes

  • Silent schema drift. Producer adds a nullable column; downstream SELECT * shifts. Detect with a contract test in CI plus a schema hash compared every run. Cost: a day of wrong numbers before anyone notices.
  • Late-arriving data. A backfill lands after the daily publish. Detect with watermark lag: alert if max(event_time) is more than 2 hours behind wall clock at publish time.
  • Check rot. Rules pass because the partition is empty. Detect by asserting row count > 0 and tracking coverage: the share of partitions where at least one check actually executed. A check that never fires is worse than no check.
  • Alert fatigue. Track precision per rule; retire any rule below 50% precision over 30 days.

Trade-offs

Blocking is safe but stops the product; quarantine keeps it live but risks someone reading a partial number. Decide by blast radius: a human who can see the banner → quarantine; an automated pricing job → block. Don't build this at all for a dataset with one consumer and no decision attached: a nightly row-count check and a Slack alert is enough. Layered reconciliation earns its cost above roughly 10 consumers, or any monetary decision.

Curated: · Written: · Reviewed:

Difficulty: Hard