VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Data Architecture & Reliability

Data Reconciliation Pipelines - Building the Safety Net

Your Pipeline Ran Successfully. Your Numbers Are Wrong. Reconciliation Pipelines Are How You Catch This Before Your Stakeholders Do.

Data Architecture & ReliabilityAirflow & Orchestration
Data quality checks validate one dataset. Reconciliation validates the business itself. When two systems that should agree don’t, a well-designed reconciliation pipeline catches the gap before your stakeholders do.

TL;DR

  • Reconciliation compares independently-derived totals — source system vs warehouse, or two stages of the same pipeline — and catches drift that no schema check or null check can see
  • Revenue reconciliation is the highest-value reconciliation to build first — it is the number every stakeholder eventually checks against a second source
  • Timing differences (in-flight transactions, timezone boundaries, late-arriving events) are the most common cause of false-positive reconciliation failures — handle them explicitly, don’t just widen the tolerance
  • Zero-tolerance reconciliation (exact match required) fails constantly on legitimate timing noise; a calibrated tolerance based on actual historical variance is what makes the check trustworthy
  • The alert needs to answer “how much, since when, and where do I look” — a reconciliation failure with no delta breakdown gets ignored after the first false alarm

A reconciliation check that fires constantly gets ignored. A reconciliation check that never fires isn’t protecting anything. The tolerance threshold is the whole job.


The revenue dashboard showed $511,200 for the day. The payments processor’s own report showed $482,910.
A 5.9% gap. Nobody had built a check for it, because the pipeline itself had never thrown an error. Every row that existed in the source had made it to the warehouse. The problem was rows that existed twice.
A retry in the ingestion job, combined with a missing idempotency key, had been double-counting a subset of transactions for eleven days.
It surfaced because a finance analyst, closing the books for the month, cross-checked the two numbers by hand — a task she did once a month, not once a day.
A reconciliation job running daily would have caught the discrepancy on day one, not day eleven of a monthly cycle.

Your Pipeline Ran Successfully. Your Numbers Are Wrong.

Schema checks catch structural problems. Null rate checks catch missing values. Distribution drift checks catch statistical shifts. None of these catch the specific failure where a pipeline runs correctly, produces the right shape of output, and the values are simply wrong relative to an independent source of truth.

Reconciliation is the check built specifically for that failure. It doesn’t look at the data in isolation — it compares two independently-derived numbers that should agree, and treats disagreement as the signal.


Source-to-Destination Count Reconciliation

Choosing the Right Comparison Point

The simplest reconciliation compares row counts between a source system and its downstream copy. The comparison point matters — comparing the wrong two things produces a check that either never fires or fires constantly for reasons that have nothing to do with real problems.

Good comparison points:
source database row count → landing zone row count
landing zone row count → warehouse table row count
Kafka topic message count → consumer's processed count
Bad comparison points:
source database (live, still receiving writes)
→ warehouse (snapshot taken hours ago)
This comparison will show a "discrepancy" every time
simply because the source kept moving after the snapshot.

Always compare against a point-in-time boundary both sides agree on — a specific partition, a specific timestamp cutoff, a specific batch ID — not “the current state of the source” against “whatever landed downstream.”

Implementation

from pyspark.sql import functions as F
from datetime import date, timedelta

def reconcile_row_counts(
source_conn,
warehouse_spark,
business_date: date,
tolerance_pct: float = 0.005
):
"""
Compare row counts for a specific business date between
the source system and the warehouse table.
"""

source_count = source_conn.execute(f"""
SELECT COUNT(*) FROM transactions
WHERE transaction_date = '{business_date}'
"""
).scalar()

warehouse_count = warehouse_spark.sql(f"""
SELECT COUNT(*) FROM warehouse.transactions
WHERE transaction_date = '{business_date}'
"""
).collect()[0][0]

delta = abs(source_count - warehouse_count)
delta_pct = delta / source_count if source_count > 0 else 0

result = {
"business_date": str(business_date),
"source_count": source_count,
"warehouse_count": warehouse_count,
"delta": delta,
"delta_pct": delta_pct,
"passed": delta_pct <= tolerance_pct
}

if not result["passed"]:
raise ReconciliationError(
f"Row count mismatch for {business_date}: "
f"source={source_count:,}, warehouse={warehouse_count:,}, "
f"delta={delta:,} ({delta_pct:.2%}) exceeds tolerance {tolerance_pct:.2%}"
)

return result

# Run for a date that is fully settled — not today, which is still receiving data
reconcile_row_counts(source_conn, spark, business_date=date.today() - timedelta(days=1))

Reconciling yesterday’s data rather than today’s is deliberate — today’s partition is still receiving writes from both systems, and comparing a moving target produces noise, not signal.


Revenue Reconciliation Patterns

Why Revenue Needs Its Own Reconciliation

Row count reconciliation catches missing or duplicated records. It does not catch a record that exists exactly once in both systems but has the wrong value — a currency conversion error, a discount applied twice, a refund recorded as a charge. Revenue reconciliation compares the sum, not the count, and catches an entirely different failure class.

Handling Timing Differences

The most common cause of false-positive revenue reconciliation failures is not a bug — it’s a transaction that was in-flight (authorized but not settled) at the moment one side of the comparison was taken. This needs to be handled explicitly rather than papered over with a loose tolerance.

def reconcile_revenue(
source_conn,
warehouse_spark,
business_date: date,
tolerance_pct: float = 0.01
):
"""
Compare total revenue between source payments system and warehouse,
excluding transactions still in a non-final state.
"""

# Only compare settled transactions — pending/authorized transactions
# legitimately exist in the source but haven't landed in the warehouse yet
source_revenue = source_conn.execute(f"""
SELECT SUM(amount) FROM transactions
WHERE transaction_date = '{business_date}'
AND status = 'settled'
"""
).scalar() or 0.0

warehouse_revenue = warehouse_spark.sql(f"""
SELECT SUM(amount) FROM warehouse.transactions
WHERE transaction_date = '{business_date}'
AND status = 'settled'
"""
).collect()[0][0] or 0.0

delta = abs(source_revenue - warehouse_revenue)
delta_pct = delta / source_revenue if source_revenue > 0 else 0

result = {
"business_date": str(business_date),
"source_revenue": round(source_revenue, 2),
"warehouse_revenue": round(warehouse_revenue, 2),
"delta": round(delta, 2),
"delta_pct": delta_pct,
"passed": delta_pct <= tolerance_pct
}

if not result["passed"]:
raise ReconciliationError(
f"Revenue mismatch for {business_date}: "
f"source=${source_revenue:,.2f}, warehouse=${warehouse_revenue:,.2f}, "
f"delta=${delta:,.2f} ({delta_pct:.2%}) exceeds tolerance {tolerance_pct:.2%}"
)

return result

Filtering to status = 'settled' on both sides is what separates a meaningful check from one that fails every day because of transactions still working their way through authorization. Reconcile only what both systems consider final.

Implementation — Reconciling by Dimension, Not Just Total

A total-level match can hide offsetting errors — one merchant overcounted, another undercounted, netting to a small overall delta that passes tolerance while both underlying numbers are wrong. Reconciling by a meaningful dimension catches this:

def reconcile_revenue_by_merchant(source_conn, warehouse_spark, business_date, tolerance_pct=0.01):
source_by_merchant = dict(source_conn.execute(f"""
SELECT merchant_id, SUM(amount)
FROM transactions
WHERE transaction_date = '{business_date}' AND status = 'settled'
GROUP BY merchant_id
"""
).fetchall())

warehouse_by_merchant = dict(
warehouse_spark.sql(f"""
SELECT merchant_id, SUM(amount) as total
FROM warehouse.transactions
WHERE transaction_date = '{business_date}' AND status = 'settled'
GROUP BY merchant_id
"""
).collect()
)

failures = []
all_merchants = set(source_by_merchant) | set(warehouse_by_merchant)

for merchant_id in all_merchants:
src = source_by_merchant.get(merchant_id, 0.0)
wh = warehouse_by_merchant.get(merchant_id, 0.0)
delta_pct = abs(src - wh) / src if src > 0 else (1.0 if wh > 0 else 0.0)

if delta_pct > tolerance_pct:
failures.append({
"merchant_id": merchant_id, "source": src,
"warehouse": wh, "delta_pct": delta_pct
})

if failures:
raise ReconciliationError(
f"{len(failures)} merchant(s) failed reconciliation: {failures[:5]}"
)

This catches the offsetting-error case a total-only check misses, at the cost of more compute and more granular alerting to manage.


Setting Tolerance Thresholds That Work

Why Zero Tolerance Fails

An exact-match requirement fails on nearly every run for reasons that have nothing to do with real problems: floating point rounding across systems, a transaction settling one second after the comparison window closed, currency conversion rates fetched at slightly different moments. A reconciliation check that fires on every run trains everyone to ignore it — exactly the failure mode mostly was built to prevent in the previous post's expectation suites.

Calibrating Tolerance by Comparison Type

Row count reconciliation:      0.1% – 0.5% tolerance
(near-zero legitimate variance expected; a real gap should show clearly)
Revenue reconciliation:        0.5% – 1.5% tolerance
(accounts for in-flight transactions, rounding, minor timing differences)
Cross-currency revenue:        1% – 2% tolerance
(exchange rate timing differences are unavoidable)
Dimension-level (per-merchant): often needs a higher tolerance than
the aggregate check, because smaller totals have proportionally
more room for a single delayed transaction to swing the percentage

These are starting points, not universal constants — calibrate against your own historical data. Run the reconciliation for 30 days without failing the pipeline, log the actual deltas observed, and set the tolerance just above the normal noise band. A tolerance set from a guess rather than observed history will be wrong in one direction or the other.


Alerting on Reconciliation Failures

What the Alert Needs to Contain

A reconciliation alert that says “reconciliation failed” without a delta breakdown forces the person who receives it to re-run the entire investigation from scratch. The alert should contain everything needed to start triaging immediately.

def send_reconciliation_alert(result: dict, channel: str = "#data-quality-alerts"):
message = (
f"🔴 Reconciliation failed: {result.get('name', 'transactions')}\n"
f"Date: {result['business_date']}\n"
f"Source: {result.get('source_revenue', result.get('source_count')):,}\n"
f"Warehouse: {result.get('warehouse_revenue', result.get('warehouse_count')):,}\n"
f"Delta: {result.get('delta'):,} ({result['delta_pct']:.2%})\n"
f"Tolerance: exceeded\n"
f"Runbook: https://wiki.company.com/reconciliation-failures"
)
post_to_slack(channel, message)

Escalation Based on Delta Size

Not every reconciliation failure deserves the same urgency. A delta just over tolerance is different from a delta ten times the tolerance — the alert routing should reflect that.

def route_reconciliation_alert(result: dict):
severity_ratio = result["delta_pct"] / result.get("tolerance_pct", 0.01)

if severity_ratio > 5:
# Major discrepancy — page on-call immediately
trigger_pagerduty(
summary=f"Major reconciliation failure: {result['delta_pct']:.2%} delta",
severity="critical"
)
elif severity_ratio > 1:
# Exceeds tolerance but not dramatically — Slack alert, business hours triage
send_reconciliation_alert(result)
# severity_ratio <= 1 means it passed — no alert

A minor breach that gets a Slack message and a major one that pages someone at 2 AM are both correct responses to reconciliation failure — as long as the routing distinguishes them.


Scheduling Reconciliation Jobs

Frequency vs Cost

Reconciliation jobs that query the source system directly add load to systems that may not be provisioned for analytical queries — particularly production transactional databases. Daily reconciliation, scheduled during a low-traffic window, is the right default for most pipelines. Real-time reconciliation is occasionally justified for very high-value, very high-risk pipelines (large payment flows) but carries meaningfully more operational cost and source-system load.

# Airflow DAG — reconciliation runs after the main pipeline,
# comparing yesterday's fully-settled data
with DAG("daily_reconciliation", schedule_interval="0 8 * * *") as dag:

reconcile_counts = PythonOperator(
task_id="reconcile_row_counts",
python_callable=lambda: reconcile_row_counts(
source_conn, spark, business_date=date.today() - timedelta(days=1)
),
)

reconcile_rev = PythonOperator(
task_id="reconcile_revenue",
python_callable=lambda: reconcile_revenue(
source_conn, spark, business_date=date.today() - timedelta(days=1)
),
)

Handling Late-Arriving Data

Some transactions settle days after they occur — refund processing, dispute resolution, delayed bank confirmations. A reconciliation job that only checks yesterday will never catch a discrepancy that emerges when a batch of delayed settlements lands three days later.

def reconcile_with_lookback(source_conn, warehouse_spark, lookback_days: int = 7):
"""
Re-check the last N days, not just yesterday, to catch
discrepancies introduced by late-arriving or delayed-settlement data.
"""

results = []
for days_back in range(1, lookback_days + 1):
check_date = date.today() - timedelta(days=days_back)
try:
result = reconcile_revenue(source_conn, warehouse_spark, check_date)
results.append(result)
except ReconciliationError as e:
results.append({"business_date": str(check_date), "error": str(e)})

failures = [r for r in results if "error" in r]
if failures:
raise ReconciliationError(f"{len(failures)} of {lookback_days} days failed: {failures}")

return results

A 7-day rolling re-check costs more compute than checking only yesterday, but it is what catches the specific failure mode where a correction, a late settlement, or a retroactive adjustment silently breaks a day that had passed reconciliation when it was first checked.


The Reconciliation Pipeline Checklist

Comparison design
□ Both sides of the comparison are settled/final, not still-moving data
□ The comparison point (date, batch ID) is unambiguous on both sides
□ Dimension-level reconciliation used where offsetting errors are a risk
Tolerance
□ Tolerance calibrated from observed historical variance, not a guess
□ Tolerance differs appropriately by check type (count vs revenue vs cross-currency)
□ Tolerance reviewed periodically as data volume and patterns change
Alerting
□ Alert includes source value, warehouse value, delta, and delta percentage
□ Alert links to a runbook or triage guide, not just a bare failure message
□ Severity-based routing — minor breaches don't page on-call at 2 AM
Scheduling
□ Reconciliation runs against fully-settled data, not the current day
□ A rolling lookback window re-checks recent days for late-arriving corrections
□ Source system query load from reconciliation is monitored, not assumed negligible
Ownership
□ A named owner reviews and updates tolerance thresholds over time
□ Reconciliation failures have a documented triage and escalation path

Final Takeaway

A pipeline that runs successfully has told you nothing about whether its output is correct — only that it completed. Reconciliation is the check that closes that gap, by refusing to trust any single system’s account of the truth and instead requiring two independent sources to agree.

The value of reconciliation is entirely in the tolerance threshold and the alert quality. Too tight, and it fires constantly until everyone ignores it. Too loose, and it never fires at all. Calibrated correctly, with an alert that tells the right person exactly what to check, it is the safety net that catches the discrepancy on day one instead of day eleven of a finance close.

📌 Core Principle

Two systems that are supposed to agree will eventually disagree. The question is not whether that happens. It is whether you find out from a reconciliation job or from a stakeholder.

Next in Series

Monitoring Data Pipelines - Metrics That Actually Matter

Your reconciliation safety net is in place.

Next: what to actually measure across your pipelines — the difference between metrics that tell you the pipeline ran and metrics that tell you it ran correctly, setting SLAs that mean something, avoiding alert fatigue, and designing dashboards that a stakeholder can actually use to answer “is my data okay right now.”