Skip to main content
← Back to Patterns

Reconcile source and warehouse data without trusting matching totals

By Ivan Richter LinkedIn

Last updated:

8 min read

In brief

Reconcile the same population at the same source cutoff using controls computed independently of the warehouse load.

  • Compare counts and amounts to locate discrepancies.
  • Match keys and individual values to catch missing rows or errors that cancel in the total.
On this page

Two invoice amounts are wrong. One increased from 100 to 110 minor units, and another decreased from 200 to 190. The row count and total are unchanged. A reconciliation that checks only those two numbers reports success.

We’d start with independent source controls, compare the same declared population at a compatible source boundary, and keep a path from aggregate differences to exact keys and values. Counts and totals only screen. Both can match perfectly while rows differ.

For a small team, this can be a pair of SQL queries and a stored comparison result. First decide what agreement means. If the source query, captured data, and warehouse model refer to different states or grains, more checks mostly produce more confusing failures.

Write the comparison contract first

Choose one source population and one target representation. For example, take every invoice header in tenant north’s complete export generation 42, including canceled invoices, represented once in a warehouse invoice table.

The comparison key is tenant plus invoice ID. Amounts stay in the source currency and minor units. The target may rename fields, but it must preserve the selected source values.

Record the source boundary, target generation, schema or projection version, filter definition, and key with each run.

State which columns the comparison covers. Comparing amount and status says nothing about an omitted customer reference. If the target intentionally excludes canceled invoices, either compare an equally filtered source population or report the exclusion as a separate expected transformation.

A model at invoice-line grain can’t be compared directly with a header count. Aggregate its line values to the intended header meaning, or reconcile the line representation against independent source lines. Don’t join several child tables and hope a final DISTINCT repairs the comparison. The reference calculation needs a defensible grain of its own.

Reconciliation checks that the pipeline preserved or intentionally transformed the source contract. Whether the source record was right is a separate question: a faithfully replicated wrong tax amount is still wrong.

Compare states that could reasonably agree

A source query at 10:00 and a warehouse query at 10:05 can disagree when the warehouse already contains changes from 10:03. Exact reconciliation has to identify the same source state on both sides.

A bounded export makes this manageable. Compute source controls while reading the same consistent snapshot used by the export, keep them outside the transformation path, and attach them to the export generation.

Once that export is published, compare its controls with a frozen target generation derived from it. If the target is being overwritten continuously, materialize a bounded comparison input or use a supported historical read at the matching target version.

Two systems can show the same wall-clock timestamp and hold different source commits.

A live CDC replica that keeps no historical states may have no cheap exact comparison boundary. You can compare stable subsets, coordinate a brief source boundary, or retry mismatches after known replication progress. Report the run as pending or inconclusive while alignment is unresolved. A fixed sleep isn’t evidence that capture has caught up.

Make the source check independent of the failure path

Computing both “source total” and “warehouse total” from the landed table can’t detect rows that the extractor never landed. Reading both through the same filtered transformation can’t detect that transformation’s accidental filter. The reference needs a path that bypasses the defect you’re trying to catch.

For an export, we’d have the producer compute controls from the source snapshot, then store the signed-off query definition, boundary, and result with the manifest. The warehouse computes its controls from the published representation. The comparison job joins the two results.

The job must also know which source populations were expected, including tenants with legitimately zero records. Otherwise an entirely missing control record can look like agreement.

You don’t need a second production pipeline. A reviewed source query with a simpler projection is often enough.

What breaks independence is importing the model’s eligibility function into the reference query just to avoid duplicated SQL. If that function contains the defect, both sides reproduce it. Keep intentional mappings small. For example, the warehouse might map source status C to canceled. The source reference can apply that documented mapping, with examples reviewed independently.

For each declared source population, keep total rows, distinct non-null keys, null-key count, and the important measures grouped by dimensions that can localize a defect. Tenant, currency, source status, and a stable key range often do that better than one total for the whole table. Use the same grouping definitions on both sides.

The following query is a control projection for a single frozen invoice input. In BigQuery, comparison.invoices should already contain only the accepted boundary being tested. Run the equivalent projection independently against the source snapshot, with dialect-appropriate types. Here invoice IDs are unique within tenant, currency is required, and amount_minor is an integer amount in that currency’s declared minor unit.

SELECT
  tenant_id,
  currency,
  COUNT(*) AS row_count,
  COUNT(DISTINCT invoice_id) AS distinct_keys,
  COUNTIF(invoice_id IS NULL) AS null_keys,
  COUNTIF(amount_minor IS NULL) AS null_amounts,
  SUM(CAST(amount_minor AS NUMERIC)) AS total_minor
FROM comparison.invoices
GROUP BY tenant_id, currency;

Check non-null tenant and currency separately. Check key uniqueness at tenant-plus-invoice grain before trusting the grouped counts. A duplicated invoice appearing under two currencies can evade a uniqueness check performed only inside each currency bucket.

BigQuery’s COUNT behavior makes the null-key check necessary: COUNT(DISTINCT invoice_id) doesn’t count null values. A sum can ignore null amounts the same way.

Keep null counts visible, because converting every missing amount to zero erases the difference between an unknown amount and a real zero.

A control total can’t mix EUR and USD amounts. Don’t round every row to displayed precision unless that’s the declared transformation.

For measured floating-point data, define an absolute or relative tolerance from the measurement contract and record it with the run. Raising a tolerance until a failed import passes changes the acceptance rule after seeing the result.

Join the independently produced control rows with a full outer join on the population and bucket keys. Investigate a missing bucket on either side. For each measure, keep the source value, target value, and difference along with the boundary identifiers. A dashboard showing only “three checks failed” leaves the next person to reconstruct the evidence.

Escalate to keys and exact values

The two incorrect invoices, now 110 and 190, still total 300. They can also sit in the same tenant and currency bucket, where more grouping won’t separate them. To confirm that selected fields are equal, compare rows by their validated unique key.

Stage bounded source and target comparison inputs with identical projections and aligned boundaries. The following BigQuery query reports missing rows and differing values. It needs non-null, unique tenant-plus-invoice keys on both sides and comparable amount types. Validate those first, or the join can multiply mismatches.

SELECT
  COALESCE(s.tenant_id, t.tenant_id) AS tenant_id,
  COALESCE(s.invoice_id, t.invoice_id) AS invoice_id,
  s.amount_minor AS source_amount_minor,
  t.amount_minor AS target_amount_minor,
  s.status AS source_status,
  t.status AS target_status
FROM comparison.source_invoices AS s
FULL OUTER JOIN comparison.target_invoices AS t
  ON s.tenant_id = t.tenant_id
  AND s.invoice_id = t.invoice_id
WHERE s.invoice_id IS NULL
  OR t.invoice_id IS NULL
  OR s.currency IS DISTINCT FROM t.currency
  OR s.amount_minor IS DISTINCT FROM t.amount_minor
  OR s.status IS DISTINCT FROM t.status;

IS DISTINCT FROM counts a null on one side as a difference, while an ordinary inequality can yield null and miss the mismatch. Presence is part of the comparison too, so keep the missing-row predicates.

Bidirectional EXCEPT DISTINCT can help with a small projected dataset, but it removes multiplicity. If the target contains an extra identical copy of a row, the sets can still match under BigQuery’s set-operation semantics. Pair set differences with key and row-count checks, or compare grouped row multiplicities when duplicate rows are legitimate.

For large populations, compare bounded key ranges and keep completion state for every range. Row hashes can reduce transfer, but only after both sides agree on serialization: column order, null representation, decimal scale, Unicode, and timestamp precision. A hash mismatch doesn’t say which field differs, so fetch the rows for disputed ranges. Matching hashes still fall short of proof that the inputs are identical. When hashes are the final check, record that in the result.

Narrow a mismatch down before repairing it

Start with the comparison metadata: different scope versions, boundaries, or projections make the result incomparable. Repair that setup before treating a difference as data loss.

If alignment is valid, compare source controls with raw landing, where missing keys point toward extraction, delivery, or decoding. If raw landing agrees but the modeled target doesn’t, inspect transformation eligibility, joins, decimal conversion, and update/delete handling. A correct model with a wrong published generation points toward publication or serving selection. Test each lead before acting on it.

Keep a bounded sample of mismatched keys and exact before/after values, plus the full mismatch count. Store it under access restrictions that suit the source data. The evidence should survive a rerun, especially if the underlying source keeps changing.

An empty mismatch file is only a pass when the comparison completed every intended scope.

Separate matched, mismatched, pending, and incomparable results, and record coverage alongside each: all rows, selected columns, named partitions, or a sample. A pending partition should stay visible after the partitions that finished turn green.

Don’t repair the destination automatically from an unexplained mismatch.

The repair can hide a bad reference query while introducing a new data error. First confirm which side is authoritative and whether the comparison itself is correct. Then repair the bounded affected population, rerun the same controls against aligned state, and keep both results.

Budget for the check you need

Exact row comparisons read and move data. Their cost belongs in the pipeline’s operating budget, including load on the source.

Run coarse controls for each accepted batch. Schedule deeper comparisons by what an omission would cost and how likely anything else is to catch it. Require stronger coverage for a connector replacement or a corrective backfill than for routine screening, and record the required coverage with the result.

Before enabling the check on real data, seed a fixture with offsetting amount errors, a duplicated key replacing a missing key, a missing tenant, and a null-valued attribute. Confirm which controls catch each defect and which pass. Keep at least one case where totals agree and rows differ.

More in this domain: Data

Browse all

Related patterns