Overview
Nine in the morning. Someone in the operations group chat asks: why is yesterday’s GMV report empty?
I check the scheduler. Three jobs, all successful. The ETL log has no ERROR, just one informational line: processed 0 records. Watermarks advanced normally to 23:59 yesterday. Four green curves on the dashboard.
Then I look at the target table. Yesterday’s partition: zero rows.
This is the classic failure mode of data reliability. Every metric that monitors “did the job run” is green, while the data never arrived. When software availability breaks, users complain within a minute. Data does not. It sits there quietly until some consumer looks up one day and notices the numbers are wrong. That “one day” is usually measured in days, not minutes.
I have spent years building ops platforms and performing production data repair, and I have been through this a few times. The pattern is always the same: after the incident, when we finally add monitoring, we realize we had been measuring the wrong thing all along - the scheduler’s success callback, not the data itself.
This article covers three things:
- Why “job success” and “data availability” are two different concepts, and which silent failures live in the gap between them.
- How to break data reliability into four measurable SLIs, what signal each one uses, and where each one can be faked.
- Once you know data is missing, how to repair it safely - the idempotency of the backfill itself often determines the final cost of an incident more than the monitoring does.
A three-day reporting outage ties all three together at the end, followed by a rollout order sorted by return on effort.
The intended reader is an SRE, data platform engineer, or on-call engineer with some background. I explain each term in plain language before using it, but I will not re-teach SRE fundamentals.
Three Ways Data Reliability Differs from Software Reliability
Before building anything, accept one thing: data reliability cannot copy the playbook for software availability. Three fundamental differences drive the monitoring design.
| Dimension | Software availability | Data reliability | Impact on monitoring design |
|---|---|---|---|
| Who finds the failure | Users, seconds to minutes | Downstream consumers, hours to days | Data needs machine-issued assertions, not feedback |
| Reversibility of repair | Rollback, restart, minutes | Correcting consumed data, possibly irreversible | Monitoring must fire earlier, plus a stop-the-bleeding switch |
| Ownership boundary | Mostly within your team | Half the upstream is not yours | Alerts must be attributable to a responsible party |
The first difference matters most. When software breaks, users give you feedback within seconds, and that feedback is your strongest monitor. When data breaks, nobody shouts. The downstream consumer may look at the report three days later, and their first reaction to an empty page is usually “the page is broken”, not “the data never arrived”.
Which means the data side has no “users will find it for me” path. It has to assert on itself. A system waiting for messages is, in the data domain, a system without monitoring.
The second difference forces you to give downstream a kill switch. Software problems end with a rollback. Data problems do not. If downstream has already shipped the wrong numbers - emails sent, models trained, replenishment orders placed - correcting the source table does not undo the business damage.
So data monitoring has to do more than detect. It has to be able to stop downstream consumption. In practice I added a table-level status flag in the warehouse: when a partition is judged FAIL, downstream jobs check the flag and skip. Crude, but it works.
The third difference determines alert routing. When a software SLI drops, the on-call engineer has the authority to change their own system. When data is late, half the time the cause is an upstream DDL or a semantic change in a business system, and all on-call can do is make a phone call. Data alerts must therefore identify “which upstream, which stage”, otherwise on-call is just forwarding a message nobody claims.
Why “Job Success” Is Not “Data Available”
Start with what a traditional pipeline monitors:
| Metric | Question it answers | Sensitive to “data is wrong”? |
|---|---|---|
| Job status finished/success | Did the process exit? | Not at all |
| Job duration | Is it slower? | Weakly correlated |
| Retry count | Was there flapping? | Weakly correlated |
| ERROR line count | Did it throw? | Insensitive (silent loss throws nothing) |
| Throughput records/s | Volume per unit time | Sensitive, if you have a baseline per partition |
All five answer “how did the job execute”. None answers “did the data arrive, is it complete, is it correct”.
The gap is this: job success only guarantees the code path finished. A finished code path can process zero records, filter out an entire batch, or write field A into field B.
Three kinds of silent failure
I group the silent failures I have seen, plus the ones that recur in public postmortems, into three categories. All three leave job status green.
First: missing rows, up to and including zero.
- Upstream adds a field. The parser reads a fixed schema, hits an unknown key, and drops the entire batch. No error, because it processed only “records it understood”.
- A data-quality filter is written too aggressively and removes records that are malformed but legally valid. In one public postmortem, a single rule silently dropped 12% of legitimate transactions for three weeks before anyone noticed.
- Incremental sync computes the watermark wrong, jumps to a future timestamp, and misses data forever after.
Second: duplicates.
Upstream claims exactly-once, but the target is a non-idempotent append. One network blip triggers a retry, and the same batch is written twice. The deduplication logic exists in the repository, just not on the actual write path. The result is not missing data but doubled revenue - harder to catch, because the report looks better.
Third: wrong values with a correct shape.
Milliseconds stored as seconds, off by a factor of a thousand. Amounts switching from yuan to cents. An FX rate table from a stale reference snapshot. Not a single row missing, every column present, every number wrong.
This one is the nastiest, because row-count checks, null-rate checks, and freshness checks all pass.
What the public postmortems say
layline.io published an analysis of 50 data pipeline postmortems (May 2026) that categorized the failure modes. Two numbers stuck with me:
- Schema drift - upstream changes the data format and downstream does not know - accounts for 38%, the single most frequent cause.
- Silent data loss accounts for 19%: the pipeline reports success, dashboards are green, SLAs are met, yet data is missing or duplicated.
That matches my own experience. The primary cause of data incidents is not “the program crashed”. It is “the program very smoothly did the wrong thing”.
So the first design principle follows directly: measure the data, not the job.
Four Data SLIs: Turning “Is the Data Right” into Numbers
Software availability has SLIs, such as request success rate. Data has them too, just along different dimensions.
I use four, which cover the three failure shapes above:
| SLI | One-line definition | How to compute | What it catches |
|---|---|---|---|
| Freshness | How old is the data | Event time to queryable time, P95/max | Late arrival, stalled pipeline, scheduler never fired |
| Completeness | Did everything that should arrive, arrive | Actual partitions/rows / expected partitions/rows | Zero rows, missing rows, missing partitions |
| Correctness | Are the values themselves right | Null rate, value ranges, enum set, quantile drift | Column misalignment, unit errors, over-aggressive filters |
| Consistency | Do cross-table or cross-system numbers reconcile | Same-metric difference on both sides | Duplicate writes, missed updates, definition drift |
Why they must be computed separately
Some teams like to merge everything into a single “data quality score” from 0 to 100 and alert below 80.
I do not recommend it. Not because it looks bad, but because the four dimensions map to four completely different repair actions:
- Freshness drops - check upstream production, the scheduler, and source database load. You do not backfill, you chase.
- Completeness drops - data is missing. Backfill, and find out why.
- Correctness drops - code or mapping is wrong. Stop the bleeding (halt downstream consumption), correct the data, fix the code.
- Consistency drops - reconcile to locate the divergence. Could be duplicates, timing, or a definition mismatch.
Merging into a score means the alert only says “quality down 12 points”, and the on-call engineer has to redo the entire attribution step. You threw away the most valuable part of the signal.
There is a more practical reason too: the measurement cost of the four differs by an order of magnitude. Freshness can be computed from partition metadata in milliseconds. Consistency requires querying both sides, possibly minutes of expensive scans. Mix them and you will end up running the expensive one at the frequency of the cheap one, crush the warehouse, and make everyone hate the monitoring.
Per-partition, not table averages
This is a mistake I made early on, and it deserves its own paragraph.
My first implementation made completeness table-level: today’s row count divided by the 7-day average, threshold 90%. Looked reasonable.
The problem: a three-day zero-output streak moved the table-level metric by less than 1%, never touching the threshold. Meanwhile the business was missing three days of data.
I switched to per-partition assertions: compute pass/fail for each ds partition, alert if any critical partition fails. The metric stopped being “this table is 99.7% healthy” and became “2026-11-29, 11-30 and 12-01 are missing”.
Small change, large effect. Table-level averages are for management reporting. Per-partition assertions are for on-call.
Recommendation 1: compute and alert data SLIs at partition granularity; use table-level aggregates only for trend display. Reason: only partition granularity can tell you which day is missing, and that determines backfill scope and impact assessment.
Freshness: The Cheapest Signal and the Easiest to Fake
Freshness is the cheapest metric and the first one you should build. It is also the one most prone to green-light illusions.
Table freshness vs column freshness
Datadog’s observability knowledge base draws a distinction that I learned the hard way in a real incident:
| Metric | What it looks at | When it lies to you |
|---|---|---|
| Table freshness | Timestamp of the last write (write metadata) | When someone backfills or compensates into an old partition, the table “was just written”, so the metric looks fresh |
| Column freshness | Max value of a business time column (e.g. order_time) | Almost never lies; costs a read of the data |
Concrete scenario: incremental sync has pulled nothing new for three days, but on day two someone manually ran a historical reload into yesterday’s partition. Now:
- Table freshness: written 30 minutes ago - green.
- Column freshness: max business time is still three days ago - red.
Guess which one saves you.
Recommendation 2: use column freshness as the primary metric; treat table freshness as a supporting signal only. Reason: any write, including reloads and repairs, refreshes table freshness, while column freshness tracks business time and cannot be fooled by a write.
The check must live outside the thing it checks
The second way freshness lies is worse: putting the freshness check in the last step of the same DAG.
It feels natural - the data loaded, so check freshness. But this design has a fatal flaw: if the DAG never starts, the check never runs, so no alert fires.
Scheduler down, upstream dependency stuck, queue saturated, cron with the wrong timezone - in all these cases the job is never triggered. And the “check” is part of the job, so the check never runs either.
In software reliability this is called a dead man’s switch problem, and the standard fix is a heartbeat: an external system records a pulse periodically, and if the primary system misses N periods, you alert. I built exactly this on Prometheus for a similar case (Related: Prometheus self-monitoring blind spots and a three-level heartbeat fallback). The logic is identical.
Recommendation 3: run data freshness probes on an independent scheduler (a separate cron, a small standalone service, or a CI scheduled job), never inside the monitored DAG. The probe itself must have a heartbeat: alert if it produces nothing for two periods. Reason: a check that dies with its subject is not a check.
Freshness with dbt: config and two traps
If your warehouse uses dbt, source freshness is the cheapest implementation. The config looks like this:
# models/sources.yml
version: 2
sources:
- name: ods
schema: ods
loaded_at_field: updated_at # column used to judge freshness
freshness:
warn_after: {count: 6, period: hour}
error_after: {count: 12, period: hour}
tables:
- name: orders
filter: "ds >= date_sub(current_date, interval 3 day)" # scan only recent partitions
- name: payments
loaded_at_field: pay_time # per-table override: different time column
freshness:
warn_after: {count: 1, period: hour}
error_after: {count: 2, period: hour}
Two traps:
Trap 1: dbt build does not run source freshness by default. It is a separate command, dbt source freshness. Plenty of teams configure the YAML, assume CI covers it, and it never executes. Schedule it as its own task and wire its exit code into the alerting path. Also note dbt source freshness --select source:ods lets you scope it, which is useful during a backfill window when you do not want to be paged.
Trap 2: filter is not optional. Without it, dbt scans the entire source table to compute max(updated_at). On a multi-hundred-terabyte ODS table, run once a day, the warehouse admin will come looking for you. Restrict the scan to recent partitions and the cost drops by orders of magnitude.
Setting thresholds: match consumer expectations, not “fresher is better”
A one-hour threshold sounds safe, but in practice it is noisy. The right basis is not the technical ceiling, it is when downstream needs the data:
| Data type | Consumption | Suggested warn / error |
|---|---|---|
| Risk and fraud streaming features | Second-level decisions | 1min / 5min |
| Operations real-time dashboard | Hourly viewing | 30min / 2h |
| Daily report (published at 08:00) | Morning meeting | 5h / 7h |
| Weekly business analysis | Monday morning | 24h / 48h |
If the daily report is published at 08:00, data arriving late before 08:00 is still fixable. There is no reason to wake someone at 2 a.m. Conversely, if a fraud feature is ten minutes late, the business has already taken the hit.
Do not forget time zones
This is the freshness bug I see most often in small teams: event time stored in UTC, thresholds computed in local time.
Two outcomes. Either the monitor is permanently red (always eight hours off) and the team mutes it, or it is permanently green (the eight hours happen to fall inside the threshold) and it never reacts when something is actually wrong.
One rule: store UTC, and convert explicitly in the query. Do not rely on session timezone, and do not rely on client defaults.
-- Partition integrity and freshness together, explicit timezone, no session default dependence
SELECT
ds,
COUNT(*) AS rows_cnt,
MAX(order_time) AS max_event_time_utc,
TIMESTAMP_DIFF(CURRENT_TIMESTAMP(), MAX(order_time), MINUTE) AS lag_minutes_utc
FROM dwd.orders
WHERE ds BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 2 DAY) AND CURRENT_DATE()
GROUP BY ds
ORDER BY ds DESC;
(That is BigQuery syntax. Hive/Spark use unix_timestamp() arithmetic, MySQL uses TIMESTAMPDIFF(MINUTE, ...). The logic is the same.)
Breaking the lag apart: from event to queryable
A single total number for freshness is not enough. “Yesterday’s data was 45 minutes late” does not tell you who to call. It could be slow CDC capture, Kafka backlog, jobs waiting on resources, or a commit that hung.
I split the path into four segments, each with its own timestamp:
| Stage | Timestamp column | Segment lag meaning | Typical failure |
|---|---|---|---|
| Event occurred | event_time | - | Upstream clock skew, manually edited business time |
| Ingested | _ingest_ts | ingest − event | CDC down, log collection throttled, source DB overloaded |
| Processed | _process_ts | process − ingest | Queue backlog, resource wait, insufficient task concurrency |
| Committed | _commit_ts | commit − process | Too many small files, slow metadata commit, lock contention |
The technique is unglamorous but effective: add three audit timestamp columns to the detail table. It costs 24 bytes per row and buys you the ability to attribute any latency to a specific stage.
-- Segmented lag: see at a glance which stage the 45 minutes went into
SELECT
ds,
COUNT(*) AS rows_cnt,
APPROX_QUANTILES(TIMESTAMP_DIFF(_ingest_ts, event_time, SECOND), 100)[OFFSET(50)] AS p50_ingest_lag_s,
APPROX_QUANTILES(TIMESTAMP_DIFF(_process_ts, _ingest_ts, SECOND), 100)[OFFSET(50)] AS p50_queue_lag_s,
APPROX_QUANTILES(TIMESTAMP_DIFF(_commit_ts, _process_ts, SECOND), 100)[OFFSET(50)] AS p50_commit_lag_s
FROM dwd.orders
WHERE ds = '${bizdate}'
GROUP BY ds;
Output from one real debugging session:
| ds | p50_ingest_lag_s | p50_queue_lag_s | p50_commit_lag_s |
|---|---|---|---|
| 2026-11-28 | 38 | 2100 | 45 |
One glance: ingestion is fine, 35 minutes were spent queueing on the compute side. Go straight to the YARN/K8s queue and task concurrency instead of walking the pipeline from the source.
Recommendation 7: add
_ingest_ts,_process_tsand_commit_tsaudit timestamps to detail tables and compute freshness per segment instead of a single total lag. Reason: total lag tells you “it is slow”, segmented lag tells you “who to call” - the most expensive piece of information in data on-call.
The cost is real and worth stating: three extra timestamp columns grow storage slightly, and the write path must populate them correctly. As a bonus, backfills and reloads naturally stamp them with the current time, which is exactly how you identify reloaded data later. Cheaper than the debugging alternative.
Completeness: Three Layers of Reconciliation
Completeness answers “did everything that should arrive, arrive”. The hard part is not the SQL. It is where the expected value comes from.
Three layers, increasing in cost and in trustworthiness.
Layer 1: your own baseline
Today’s partition row count compared with history.
Simplest version: alert if today’s rows < median of the past 7 days × 0.6.
Two details worth calling out:
Use the median, not the mean. Campaigns and month-end settlements inflate the mean and cause healthy days to be misjudged. A median plus MAD (median absolute deviation) is more robust: insensitive to outliers, no normality assumption needed.
Do not compare with “the same day last week”. It sounds reasonable given weekly business cycles, but it is fragile: last week may have been a campaign day, or may itself have been broken. A polluted baseline produces a broken monitor.
Judge zero separately. This is, in my view, the highest-value single rule: if a critical partition has zero rows, fail immediately, ignore thresholds. In the outage above, had the reporting job failed on a zero-row partition, the problem would have surfaced at 08:00 on day zero instead of three days later.
Layer 2: source-to-target reconciliation
Comparing against yourself only catches “it suddenly got smaller”. To catch “it was already missing at the source”, you have to compare with the source.
Three alignments must hold, or the result is meaningless:
- Scope alignment: the source query conditions (timezone, soft-delete flags, tenant filters, business line) must match the target. The classic failure is source counting soft-deleted orders while the target filters them, a 2% gap, a permanent alert, and eventually a muted channel.
- Metric alignment:
countagainstcount,sum(amount)againstsum(amount). Do not compare source “order count” with target “order line count” - one-to-many will be wildly off. - Time alignment: source business time versus target partition key, left-closed right-open boundaries, documented on both sides.
-- Source vs target partition reconciliation: rows and amount, tiny tolerance allowed
WITH src AS (
SELECT ds,
COUNT(*) AS cnt,
SUM(pay_amount) AS amt
FROM ods.orders
WHERE ds = '${bizdate}'
AND is_deleted = 0
GROUP BY ds
),
tgt AS (
SELECT ds,
COUNT(*) AS cnt,
SUM(pay_amount) AS amt
FROM dwd.orders
WHERE ds = '${bizdate}'
GROUP BY ds
)
SELECT
COALESCE(src.ds, tgt.ds) AS ds,
COALESCE(src.cnt, 0) AS src_cnt,
COALESCE(tgt.cnt, 0) AS tgt_cnt,
COALESCE(tgt.cnt, 0) - COALESCE(src.cnt, 0) AS cnt_diff,
ROUND(ABS(COALESCE(tgt.amt,0) - COALESCE(src.amt,0)), 2) AS amt_diff,
CASE
WHEN tgt.ds IS NULL THEN 'FAIL_MISSING' -- target partition absent
WHEN src.cnt <> tgt.cnt THEN 'FAIL_COUNT'
WHEN ABS(COALESCE(tgt.amt,0) - COALESCE(src.amt,0)) > 1 THEN 'FAIL_AMOUNT'
ELSE 'PASS'
END AS verdict
FROM src FULL OUTER JOIN tgt ON src.ds = tgt.ds;
Each row of output is one partition verdict, ready to be written into a metrics table. Note FAIL_MISSING as its own category: when the target partition does not exist, a difference-based check reports “100% missing”, which looks like a data quality problem but is actually a job that never ran. Different repair path, so different verdict.
Layer 3: business-level reconciliation
Compare the report number with the number the business system believes in. Report GMV against the order center’s GMV. Financial revenue against the finance system.
The benefit: business stakeholders understand this layer’s conclusions. “Partition completeness SLI dropped” gets no reaction. “The report is 12% below the order center” gets an immediate response.
The cost: it is hard to automate. Definitions live in people’s heads, and business systems change them. My approach is to reconcile only two or three critical metrics (GMV, order count, active users), confirmed manually once a month, without chasing automation.
Do not let monitoring crush the warehouse
The easiest way to write a row-count check is SELECT COUNT(*) FROM huge_table WHERE ds = .... At scale that statement is itself an incident: monitoring runs it every minute, and the DBA shows up asking who is scanning the full table.
Three alternatives, in my order of preference:
- Use table format metadata. Delta Lake and Iceberg partition statistics, Hive metastore row counts - often no data scan required.
- Persist statistics into a metrics table. The ETL writes one row per partition (
ds, cnt, amt, written_at) intometa.partition_metricsas a side effect; monitoring queries only that small table. - Add partition filters and clustered columns to minimize scan volume.
I pick option 2. Writing one small side table costs far less than a cluster permanently slowed by monitoring queries.
How to Write a Probe: A Runnable Integrity Check
Principles are done, so let’s write code. The worst pattern in data checking is a one-off SQL script plus a human reading results. A check should be an independent, schedulable task that emits metrics.
Why metrics instead of messages? Three reasons: messages are only noise, metrics can compute SLOs; messages have no history, metrics show trends; messages scatter across chat, metrics plug into your existing alerting path (Prometheus and Grafana both work).
This skeleton has been through several iterations and can be adapted directly:
# probe_partition_integrity.py
# Standalone probe: partition integrity check emitting Prometheus textfile metrics
import os
import time
from datetime import datetime, timedelta, timezone
import psycopg2 # swap in your warehouse driver
DS = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y%m%d")
OUT = "/var/lib/node_exporter/textfile/data_reliability.prom"
SQL = """
SELECT ds, COUNT(*) AS cnt, COALESCE(SUM(pay_amount), 0) AS amt
FROM dwd.orders WHERE ds = %s GROUP BY ds
"""
def probe() -> dict:
conn = psycopg2.connect(os.environ["DW_DSN"], connect_timeout=10)
try:
with conn.cursor() as cur:
cur.execute(SQL, (DS,))
row = cur.fetchone()
if row is None: # partition absent = hard failure, highest priority
return {"ds": DS, "rows": 0, "amt": 0.0, "exists": 0}
return {"ds": DS, "rows": row[1], "amt": float(row[2]), "exists": 1}
finally:
conn.close()
def emit(m: dict, elapsed: float) -> None:
lines = [
f'data_partition_exists{{ds="{m["ds"]}"}} {m["exists"]}',
f'data_partition_rows{{ds="{m["ds"]}"}} {m["rows"]}',
f'data_partition_amount{{ds="{m["ds"]}"}} {m["amt"]}',
f'data_probe_last_run_unixtime{{ds="{m["ds"]}"}} {int(time.time())}',
f'data_probe_duration_seconds {elapsed:.3f}',
]
tmp = OUT + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(tmp, OUT) # atomic replace, no half-written reads
if __name__ == "__main__":
t0 = time.time()
try:
metric = probe()
except Exception as e: # probe failure must also become a metric
metric = {"ds": DS, "rows": -1, "amt": 0.0, "exists": -1}
print(f"probe error: {e}", flush=True)
emit(metric, time.time() - t0)
Design details, all learned the hard way:
- Distinguish “partition absent” from “partition present with zero rows”. The first usually means the job never ran; the second usually means data never arrived. The
existsmetric separates them so alerts and troubleshooting paths differ. - Probe failure must emit a metric too (use
-1), otherwise a dead probe equals no monitoring. - Replace files atomically (
os.replace) so the exporter never reads a half-written file. - Always emit a heartbeat metric (
last_run_unixtime) and alert ontime() - last_run > 2 × interval. This is the antidote to the “dies with its subject” problem: when the probe stops emitting, the heartbeat goes stale and you get paged. - Schedule it independently: a systemd timer, a separate cron, or a small Deployment. Never attach it to the DAG it monitors.
The matching alert rules:
groups:
- name: data-reliability
rules:
- alert: DataPartitionMissing
expr: data_partition_exists == 0
for: 1m
labels: {severity: page}
annotations:
summary: "Partition {{ $labels.ds }} is absent, job likely produced nothing"
- alert: DataPartitionEmpty
expr: data_partition_rows == 0 and data_partition_exists == 1
for: 5m
labels: {severity: page}
annotations:
summary: "Partition {{ $labels.ds }} has zero rows"
- alert: DataProbeStale
expr: time() - max(data_probe_last_run_unixtime) > 7200
for: 5m
labels: {severity: page}
annotations:
summary: "Data probe silent for over 2 hours, check the probe itself"
DataPartitionEmpty and DataProbeStale together are, I think, the whole high-value core: one blocks silent zero-row output, the other blocks “the monitor went blind”.
Correctness and Consistency: Distribution Checks and Reconciliation
Row counts and freshness can both look fine while the data is entirely wrong. This layer catches “correct shape, wrong values”.
Distribution checks: four cheap signals
None of these require understanding the business meaning:
| Signal | What it catches | Alerting |
|---|---|---|
| Null rate | Upstream field vanished, join failed | Critical field null rate > 0 alerts; non-critical > baseline × 3 |
| Zero/negative rate | Unit change, sign flip, dirty data | Above historical quantile threshold |
| Enum set drift | Upstream semantic change (new status value) | Any value unseen in the past 30 days triggers info level |
| Quantile drift | Unit error, precision loss | p50/p99 change > 30% versus baseline |
Enum set drift is, I think, badly underrated. It costs almost nothing and surfaces upstream semantic changes earliest. Say the order status enum gains PARTIAL_REFUND_PENDING, and downstream CASE WHEN does not cover it. Those orders fall into the “unknown” bucket, the “other” column in the report quietly grows, and nobody gets an error. But the numbers are wrong.
The implementation is simple: compare today’s distinct status with the union of the past 30 days, and send a low-priority note when a new value appears. It does not interrupt anyone, but it leaves a trail.
Reconciliation: run the accounting identity across tables
Consistency checking is essentially finding a relation that must hold and reconciling it automatically. Business stakeholders defined these relations long ago; they just never made it into code:
- GMV = order amount − refund amount + freight adjustment
- Closing inventory = opening inventory + inbound − outbound
- Detail aggregation = summary table’s value for the day
- Successful payments ≤ orders placed
-- Reconciliation: does the daily summary GMV equal the recomputed detail value?
SELECT
s.ds,
s.gmv_amt AS summary_gmv,
d.gmv_amt AS detail_gmv,
ROUND(s.gmv_amt - d.gmv_amt, 2) AS diff,
CASE WHEN ABS(s.gmv_amt - d.gmv_amt) > 0.01 THEN 'FAIL' ELSE 'PASS' END AS verdict
FROM dws.trade_summary_daily s
JOIN (
SELECT ds,
SUM(pay_amount) - SUM(refund_amount) + SUM(freight_adj) AS gmv_amt
FROM dwd.order_detail
WHERE ds = '${bizdate}'
GROUP BY ds
) d ON s.ds = d.ds
WHERE s.ds = '${bizdate}';
Keep a tolerance of 0.01 for floating point, never use =. I learned this one the hard way: mixing DECIMAL and DOUBLE gave a 1e-10 difference, the reconciliation failed daily, and eventually everyone learned to ignore it.
Do not write 200 rules
The most common move for a new team is to deploy a rules engine, configure 200 rules, and then… nobody reads the alerts anymore.
Rule count and data reliability are not linearly related. Past roughly 20 rules, on-call starts reading only the red ones. Past 50, they read none.
My approach is to start with exactly three: hard failure on zero-row critical partitions, row-count baseline deviation, amount/primary-key reconciliation. Those three cover the vast majority of real incidents I have been part of. Add the rest one at a time, on the principle of “one incident, one rule” - every rule then traces back to a real lesson, which is why the team will respect it.
Recommendation 4: start data quality with 3 rules, add exactly 1 rule per incident, and document for each rule which incident it came from. Reason: a rule’s credibility comes from having caught something, not from its count.
Idempotency: The Foundation of Backfill
Discovering missing data is only the beginning. Next you repair it, and the repair action itself is the second-largest source of data reliability risk.
I have been burned on production data repair, so my stance here is blunt: the idempotency of the backfill script determines the final cost of an incident more than monitoring sensitivity does. Monitoring makes you discover early; idempotency makes you dare to fix.
(I wrote a longer piece on that defense line: Related: Five layers of defense and seven pitfalls in production data repair. Here I only cover what is directly relevant to reliability.)
Three write strategies compared
| Strategy | Safe to re-run | Cost | Overwrites newer data | Concurrency safety | Suitable for |
|---|---|---|---|---|---|
| Append | No | Lowest | N/A | Poor | Append-only, naturally immutable logs |
| Partition overwrite (INSERT OVERWRITE) | Yes | Medium (rewrites partition) | No (whole partition replaced) | Serialize per partition | Per-partition backfill - my default |
| MERGE / upsert | Depends on your conditions | Medium-high | Possible with out-of-order arrival | Conflicts need retry | History retention, cross-partition updates, CDC |
Recommendation 5: default backfills to partition overwrite, not MERGE. Reason: partition overwrite is idempotent by construction - running once or three times yields the same result, and a failed rerun needs no cleanup. MERGE’s idempotency depends on you writing every condition correctly, and a wrong condition produces “data that looks fine but is the wrong version”, which is harder to diagnose than an error. The cost is that backfill granularity must match partition granularity: daily partitions mean daily backfills, not half-days. I consider that trade worth taking.
Three real boundaries of MERGE
If you genuinely need MERGE - CDC merges, cross-partition updates - three things must be handled, or “idempotent” is just on paper.
Boundary 1: multiple source rows per key.
The Delta Lake documentation notes explicitly that MERGE results are undefined when the source has multiple rows matching one target row; newer versions raise an error, forcing you to deduplicate first. So deduplicate with ROW_NUMBER() and specify a deterministic tie-breaker (latest update first). Without determinism, each run orders rows differently, so results differ - which is no longer idempotency, it is randomness.
-- Deduplicate: one row per key, newest update wins, id as deterministic tie-breaker
WITH src_dedup AS (
SELECT *
FROM (
SELECT
s.*,
ROW_NUMBER() OVER (
PARTITION BY s.order_id
ORDER BY s.updated_at DESC, s.id DESC
) AS rn
FROM stage.orders_incremental s
) t
WHERE rn = 1
)
MERGE INTO dwd.orders AS tgt
USING src_dedup AS src
ON tgt.order_id = src.order_id
WHEN MATCHED AND src.updated_at > tgt.updated_at THEN -- prevents stale overwrite
UPDATE SET *
WHEN NOT MATCHED THEN
INSERT *;
Boundary 2: stale rows overwriting fresh ones.
Without the src.updated_at > tgt.updated_at predicate, an out-of-order old record overwrites the new value. The symptom is “some orders’ status went backwards”, invisible in the report, discovered only when the business reconciles. The predicate costs almost nothing, and without it MERGE degrades from idempotent to last-write-wins.
Boundary 3: concurrent conflicts.
Two backfills MERGEing the same partitions at once will very likely hit a write conflict (Delta raises concurrent write conflicts; Iceberg has commit conflicts). Depending on the implementation, retry or fail. I prefer serializing per partition: add a partition-level lock, or simply backfill one partition at a time.
Before backfilling, verify downstream is idempotent too
This step gets skipped most often.
You backfill the 2026-11-29 partition. If the downstream summary job uses INSERT INTO rather than INSERT OVERWRITE, the backfill adds a day instead of replacing one. Next day the business sees GMV at twice the real value.
The correct order:
- Confirm downstream repeated execution on the same partition is idempotent (or rerun the downstream overwrite logic first).
- Then run the upstream backfill.
- Immediately run reconciliation and confirm the difference is zero.
Backfill execution checklist
Backfill is a high-risk action, so I fixed it into a checklist to follow every time. Put it in the runbook; do not rely on memory:
- Confirm scope: which partitions, which downstream tables, which reports and business decisions are affected. No scope, no action.
- Confirm downstream idempotency: overwrite or append? If append, change it first or include downstream in the backfill scope.
- Notify consumers: if someone is reading numbers downstream, say in advance that 11-29 to 12-01 is being repaired and numbers may move. This saves half the explanation cost later.
- Freeze or throttle: pause related scheduled jobs during backfill so they do not concurrently write the same partition.
- Snapshot affected partitions (optional but advised): at minimum record pre-backfill row counts and amounts as a rollback baseline.
- Run serially: one partition at a time, not a dozen in parallel. You need to be able to stop.
- Reconcile immediately after: source-to-target plus business-level reconciliation, zero difference before calling it done.
- Log the backfill: a dedicated table with fixed fields
who / when / scope / reason (which alert or ticket) / result / reconciliation diff.
Step 8 is frequently skipped, but it is an audit requirement and the only way to know “where did we get to last time”. Our repair incident taught us this: incomplete logs meant we backfilled partitions a second time that had already been repaired.
Recommendation 8: maintain a dedicated backfill log table with fixed, mandatory fields. Reason: traceability of data repair matters as much as commit history in code; without it, the next incident repeats the same way.
Anatomy of a Campaign-Season Reporting Outage
The categories and principles above, tied together with an incident. Details are sanitized; the sequence and magnitudes are faithful.
Context: an e-commerce platform, campaign season, daily report chain. Source order database → ODS → DWD → DWS summary → report. The report publishes at 08:00 and is read in the morning meeting.
Timeline:
| Time | What happened | Who noticed |
|---|---|---|
| D0 02:10 | Online DDL on the source order DB adds a channel_code column | Nobody |
| D0 02:15 | Sync job succeeds, processed 0 records (parser reads a fixed schema; the unknown field causes the whole batch to be skipped) | Nobody |
| D0 08:00 | Reporting job succeeds, produces an empty partition, page shows “no data” | Nobody |
| D1–D3 | Operations manually paste last week’s numbers into the report; the empty table is treated as a page bug, not a data bug | Nobody |
| D3 15:20 | Business asks: why is this week’s GMV down 12% week over week? | Business |
| D3 16:00 | Found D0–D2 partitions with COUNT(*) = 0; three job histories all green | Me |
| D3 18:30 | Parser fixed (map by field name, tolerate new fields), three partitions backfilled | - |
| D3 21:00 | Reconciled against the order center; GMV difference zero | - |
Four root causes:
- Monitoring watched exit codes only. Success meant success; nobody measured records processed or whether the partition had data.
- No per-partition completeness assertion. The table-level metric moved less than 1%, against a 90% threshold, so it could never fire.
- The report treated empty data as a normal value. The reporting job received zero rows and rendered “no data”, returning success. That was the step that most needed to fail in the whole chain.
- Manual number-patching masked the failure. Operations filled the report with last week’s data, which erased the strongest signal - “the numbers look wrong” - for three days. Worth remembering: well-intentioned workarounds are the enemy of monitoring.
Fixes:
- The parser switched to a schema registry plus name-based field mapping, ignoring unknown fields instead of dropping the batch. This is exactly why schema drift is 38% of the postmortem corpus: the default behavior is too dangerous.
- Backfill used partition overwrite; we first verified the DWS summary job also overwrites, then backfilled the three partitions.
- Added three rules: hard failure on zero-row critical partitions, source-to-target reconciliation, GMV reconciliation.
- Moved the freshness probe to an independent scheduler, and made the reporting job fail on empty partitions.
That last item deserves its own emphasis, because the decision is counterintuitive:
Recommendation 6: when a report or summary job encounters an empty critical partition, it should fail outright rather than emit an empty result. Reason: an empty result gets propagated downstream as normal data, expanding the blast radius from one partition to the whole reporting system; a failure only delays output, and the business will immediately ask why, surfacing the problem the same day. I take the failure trade every time.
The cost is occasional false failures - say a business line genuinely had zero orders that day (unlikely, but possible for certain lines on holidays). Handle it with a whitelist: only critical partitions of critical business lines fail hard; niche lines degrade to an alert.
Using Error Budgets in the Data Domain
Software reliability has error budgets, and data can use them too - but you cannot copy 99.9%.
Data has specific properties: the upstream is not under your control (source DDL, upstream outages), repair is expensive (backfills), and consumer tolerance varies enormously (finance versus exploratory analysis).
So I tier by consumer:
| Tier | Typical case | Freshness SLO | Completeness SLO | Correctness requirement |
|---|---|---|---|---|
| Tier 1 | Billing, settlement, external reports | 99% (hourly window) | 100% partitions mandatory | Zero tolerance on amounts |
| Tier 2 | Operations daily report, real-time dashboard | 99% | 99% | Alert above 0.1% difference |
| Tier 3 | Exploratory analysis, ad hoc queries | 95% | 95% | None |
Tier 1’s “zero tolerance on amounts” is deliberately not a percentage, because one amount error costs far more than ten late arrivals.
The real purpose of an error budget is not performance review. It turns “upstream is late again” from an argument into a quantified conversation. Two consecutive weeks burning 80% of the Tier 1 freshness budget means the proposal to add a buffer layer or switch to event-driven delivery is no longer an SRE opinion - it is data.
Consume budgets by burn rate, not by “one missed day pages everyone”. Multi-window burn rate alerting (1 hour, 6 hours, 3 days) separates “one late arrival” from “steady degradation”. That pattern is mature in software SLOs, and my gating design used the same structure (Related: Making reliability a hard product constraint with three-level gates).
Rollout Order: What to Build First
Data reliability tends to become a pile of tools. Here is my ordering by return on effort - the sequence I actually follow:
| Phase | Build | Effort | Roughly covers |
|---|---|---|---|
| P0 | Hard failure on zero-row critical partitions; column-level freshness probe on an independent scheduler plus probe heartbeat | 1 week | Silent zero rows, scheduler never fired |
| P1 | Row-count baseline deviation (median + MAD); source-to-target row and amount reconciliation | 2–3 weeks | Missing rows, partial duplicates |
| P2 | Schema compatibility checks (new fields do not drop batches); enum set drift; backfills switched to partition overwrite | 1–2 months | Schema drift, wrong values, backfill contamination |
| P3 | Tiered data SLOs with error budgets; one upstream-delay drill per quarter | Ongoing | Upstream degradation, playbook validity |
P0 has the best return: a zero-row hard-fail rule takes a day to build and blocks the most common incident class. Do not start with a data quality platform.
Common Traps
A list, all either personally experienced or recurring in postmortems:
- Storing UTC but computing thresholds in local time. Eight hours off; permanently red or permanently green.
- Table freshness green while column freshness has been dead for three days. Any reload refreshes table-level timestamps.
- Putting the check inside the monitored DAG. The scheduler dies, the check dies, both go silent together.
- Nobody reading the dead letter queue. DLQ depth should be a first-class SLI, not a log to review “when there is time”.
- Over-aggressive filters. Dropping valid records while catching invalid ones; one public postmortem lost 12% of legitimate transactions for three weeks.
- Monitoring queries crushing the warehouse. Full-table
COUNT(*)every minute. - Non-idempotent backfills. Repairing one day turns into duplicating one day, which is harder to explain than missing data.
- Watermarks on
max(updated_at)with future timestamps present. The watermark jumps to the future and data is missed forever, with every job green. This trap has a name - the two-clocks problem: business time versus processing time, never separated. - Comparing floats with
=. Reconciliation fails daily until someone mutes it.
Summary
Three sentences:
- Job success is necessary, not sufficient. Measure the state of the data, not the scheduler’s callback.
- Four separate SLIs or nothing. Freshness, completeness, correctness and consistency map to four repair actions; collapsing them into one score throws away attribution. And per-partition beats table-level every time.
- The repair action must itself be idempotent. Default to partition overwrite, write all three MERGE conditions, and verify downstream idempotency before backfilling.
If you can only build one thing, build “fail on zero-row critical partitions plus an independent column-level freshness probe”. Together they are under two days of work and block most of the silent data incidents I have seen.
One last opinion: the most expensive part of data reliability is not the monitoring tooling. It is admitting your data might be wrong. Most teams are not incapable of writing checks - they assume “the job succeeded, so the data arrived”, and therefore never look at row counts in the partition.
Admit it can be wrong, and monitoring finally has somewhere to live.
References & Acknowledgments
This article draws on the following public material. Thanks to the original authors:
- What I Learned From Reading 50 Data Pipeline Postmortems — layline.io, pattern statistics across 50 pipeline postmortems (38% schema drift, 19% silent data loss, over-aggressive filters, non-idempotent targets causing duplicate writes, retention gaps)
- What is Data Freshness? — Datadog Knowledge Center, the distinction between table and column freshness, and why freshness monitoring must be independent of the monitored job
- Add sources to your DAG (source freshness) — dbt Labs, semantics of
warn_after/error_after/loaded_at_field/filterand thedbt source freshnesscommand - Table updates and deletes (MERGE) — Delta Lake documentation, MERGE semantics, duplicate source keys and concurrent write conflicts
- MERGE INTO — Databricks documentation, upsert and the need for pre-deduplication
- Apache Iceberg — Spark writes — Apache Iceberg documentation, partition overwrite behavior and MERGE INTO
- The Lie of Two Clocks: Why Incremental Sync Drops Data — Todd Zhang, analysis of data loss caused by conflating business time with processing time in incremental sync
- Three pitfalls of a daily data pipeline: idempotency, time zones, and retries — Tencent Cloud Developer Community, practical experience with idempotent writes, timezone errors and retry amplification
- How we reloaded 500 million rows rejected by the quality gateway — Habr (Lamoda engineering), large-scale reload of records rejected by a data quality gateway
Thanks to these teams and authors for publishing their documentation and postmortems. The framework and data citations here come from those materials plus my own production experience.