Reconciliation

Part of the free LogicWiz Data Engineering course, Module 7: Data quality and testing. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 10:05 on Tuesday. Tess is closing the first half of June. The payment provider's report says captured payments total $8,514.73. The warehouse says order lines total $9,421.98. The gap is $907.25, and she needs to know which orders are behind it by lunch.

You'll learn to

  • Compare source and target with counts, sums and hash totals
  • Find the exact rows that differ, in both directions
  • Compare huge tables by fingerprints, bucket by bucket
  • Reconcile at the right grain, so errors cannot cancel out

Learn

One number tells you nothing

$907.25 is a single number. It could be one missing order. It could be twenty small errors, some up and some down. Nothing in it says where to look.

Comparing two things that should agree is called reconciliation: a source and its copy, or two systems that describe the same sales. You go down three levels, from cheap to precise.

  • Counts: rows in, rows out.
  • Sums: a total that must match, such as revenue.
  • Hash totals: a fingerprint of all the values.

When a level disagrees, you go down to which rows differ. Start with the easier pair: the shop's order lines and the warehouse's copy of them.

Three levels, then the rows

Four steps in a row: compare counts, compare sums, compare hash totals, then diff the rows; each step costs more than the last and catches more.

Read it left to right: each level costs more than the one before, and catches something the one before cannot.

Count and sum: source against warehouse

SELECT 'source' AS side, COUNT(*) AS lines, SUM(qty * unit_price) AS revenue
FROM order_items
UNION ALL
SELECT 'warehouse', COUNT(*), SUM(amount)
FROM dw.fact_sales;

dw.fact_sales is the warehouse copy of the order lines, with a few problems planted in it. One line and $17.55 are missing. That much the totals show. They do not show the rest.

The sum agreed, and the data was wrong

A count and a sum can both agree while the data is wrong. Two values that change in opposite directions cancel out in a sum.

A hash total catches that. A hash turns any text into a short fingerprint: md5 gives 32 characters, and changing one digit of the input changes all of them. So join each row's key and values into one string and hash it. Then combine the row hashes in a way that does not depend on row order. In Postgres: md5(string_agg(row_hash, '' ORDER BY row_hash)). Equal fingerprints mean equal contents.

Compute it per group (per day, per file), and a mismatch also tells you where to look.

Two lines changed, and the day still adds up

The order lines of 6 June on the source and in the warehouse. The count matches, the sum matches because one line is 5 dollars higher and another 5 dollars lower, and only the hash total differs.

  1. Count. 13 lines on the source for 6 June, 13 in the warehouse. The count check passes.

  2. Sum. $582.09 on each side. The sum check passes too. One line is $5 too high and another $5 too low, and the two cancel out.

  3. Hash each row. Each row's key and amount become one fingerprint. Eleven fingerprints are equal on both sides. Two are not, because a different amount gives a completely different hash.

  4. Hash total. Sort the 13 row hashes and hash the list: one fingerprint for the whole day. The two sides disagree. Only this level sees the problem.

Watch the box on the right: it is the verdict of each level. It stays green for the count and the sum, and turns red only when the rows are hashed.

Count, sum and hash per day

WITH source_rows AS (
  SELECT o.order_ts::DATE AS day, i.qty * i.unit_price AS amount,
    md5(i.order_id || '|' || i.line_no || '|' || (i.qty * i.unit_price)) AS row_hash
  FROM order_items AS i
  JOIN orders AS o ON o.order_id = i.order_id
),
target_rows AS (
  SELECT o.order_ts::DATE AS day, f.amount,
    md5(f.order_id || '|' || f.line_no || '|' || f.amount) AS row_hash
  FROM dw.fact_sales AS f
  JOIN orders AS o ON o.order_id = f.order_id
),
s AS (
  SELECT day, COUNT(*) AS lines, SUM(amount) AS revenue,
    md5(string_agg(row_hash, '' ORDER BY row_hash)) AS fingerprint
  FROM source_rows GROUP BY day
),
t AS (
  SELECT day, COUNT(*) AS lines, SUM(amount) AS revenue,
    md5(string_agg(row_hash, '' ORDER BY row_hash)) AS fingerprint
  FROM target_rows GROUP BY day
)
SELECT s.day,
  s.lines = t.lines AS same_count,
  s.revenue = t.revenue AS same_sum,
  s.fingerprint = t.fingerprint AS same_hash
FROM s
JOIN t ON t.day = s.day
WHERE s.fingerprint <> t.fingerprint
ORDER BY s.day;

Two days differ. On 3 June everything disagrees: order 1016's line is missing. On 6 June the count and the sum agree, and only the hash notices.

What each level catches

ProblemCountSumHash total
A row is missing (order 1016)differsdiffersdiffers
A row is loaded twicediffersdiffersdiffers
One value changedsamediffersdiffers
Two values changed, +$5 and -$5 (orders 1030 and 1031)samesamediffers

Counts are cheapest and catch the most common failures. Hashes cost more and catch everything. Many teams check counts and sums on every run and hashes nightly.

Which rows? Ask in both directions

A mismatch says that something differs. Tess needs to know which rows. EXCEPT answers it: it returns the rows of the first query that the second query does not have.

  • source EXCEPT target: rows the source has that are missing or different in the target.
  • target EXCEPT source: rows the target has that are extra or different.

Always run both directions. One direction alone hides half the problems: a row loaded twice, or one that should have been deleted, only shows from the target side. Compare the key and the values you care about, so a changed amount appears once in each direction.

Which rows differ

SELECT 'only in source' AS side, order_id, line_no, amount
FROM (
  SELECT order_id, line_no, qty * unit_price AS amount FROM order_items
  EXCEPT
  SELECT order_id, line_no, amount FROM dw.fact_sales
) AS a
UNION ALL
SELECT 'only in warehouse', order_id, line_no, amount
FROM (
  SELECT order_id, line_no, amount FROM dw.fact_sales
  EXCEPT
  SELECT order_id, line_no, qty * unit_price FROM order_items
) AS b
ORDER BY order_id, line_no, side;

Order 1016 appears only on the source side: missing. Orders 1030 and 1031 appear on both sides with different amounts: changed. Three problems, five rows, and each one is something a person can act on.

A billion rows: move fingerprints, not rows

EXCEPT both ways needs both tables in one engine. Between Postgres and Snowflake that would mean copying a billion rows across the network only to compare them.

Do it the other way round. Each side sorts its rows into buckets by a hash of the key, and works out a count and a hash total per bucket. You compare those few small rows. Buckets that agree are finished. Buckets that disagree are split into smaller buckets, and you repeat until a bucket is small enough to copy and diff.

It is how you would find one wrong page in two copies of a thick book: compare a word count per chapter first, then per page of the chapter that differs.

Narrowing 1 billion rows down to the 3 that differ

A tree. One billion rows are split into 1,024 buckets; 1,021 match and three differ. Each bad bucket is split into 1,024 sub-buckets; 1,023 match and one differs, and only its 954 rows are copied and compared row by row.

  1. Bucket both sides. Each system puts every row into one of 1,024 buckets and works out a count and a hash per bucket. Only those 2 x 1,024 small rows cross the network.

  2. Compare bucket by bucket. 1,021 buckets agree on count and hash. About 997 million rows are proven equal without moving one of them. Three buckets differ.

  3. Split the bad buckets. 977,000 rows are still too many to copy. Each bad bucket is cut into 1,024 sub-buckets and fingerprinted again. In bucket 517, 1,023 of them match.

  4. Copy the last few rows. One sub-bucket of about 954 rows is left in each bad bucket. Now pull those rows from both sides and run EXCEPT both ways. The bad rows are in there.

Follow the red branch down: at each level the green part is finished for good. 1,000,000,000 / 1,024 is about 977,000 rows per bucket, and / 1,024 again is about 954.

Data moved to find 3 bad rows in 1 billion (100-byte rows)

Bars compare the megabytes moved by copying every row against two levels of bucket fingerprints and the rows of the three mismatched sub-buckets.

The two green bars are too short to see next to the red one: two levels of fingerprints plus three small sets of rows come to under 1 MB, against a 100 GB copy.

Make equal rows hash equal

Two details decide whether a fingerprint can be trusted.

How you combine the row hashes. Sorting them and hashing the list is exact, but it sorts every row. A sum of 64-bit row hashes is cheap and still notices a row loaded twice. XOR is as cheap, but two copies of the same row cancel to zero, so a doubled load disappears. Always compare the count too.

How you turn a row into text. Both sides must write equal values the same way: 10.5 and 10.50, timestamps in UTC at one precision, a marker for NULL, and a separator that cannot occur in the data. In Postgres NULL || 'x' is NULL, so a row with any NULL hashes to NULL and silently drops out of the total.

Bucketed fingerprints, then a diff of the bad buckets only

CREATE VIEW src AS
SELECT order_id, line_no, qty * unit_price AS amount,
  ('x' || substr(md5(order_id || '-' || line_no), 1, 8))::bit(32)::bigint % 16 AS bucket
FROM order_items;
CREATE VIEW tgt AS
SELECT order_id, line_no, amount,
  ('x' || substr(md5(order_id || '-' || line_no), 1, 8))::bit(32)::bigint % 16 AS bucket
FROM dw.fact_sales;

-- 1. Per bucket and side: a count and a sum of 60-bit row hashes
CREATE VIEW fp AS
SELECT 'source' AS side, bucket, COUNT(*) AS n,
  SUM(('x' || substr(md5(order_id || '|' || line_no || '|' || amount), 1, 15))::bit(60)::bigint) AS h
FROM src GROUP BY bucket
UNION ALL
SELECT 'target', bucket, COUNT(*),
  SUM(('x' || substr(md5(order_id || '|' || line_no || '|' || amount), 1, 15))::bit(60)::bigint)
FROM tgt GROUP BY bucket;

SELECT bucket, MIN(n) AS fewer_rows, MAX(n) AS more_rows
FROM fp
GROUP BY bucket
HAVING MIN(n) <> MAX(n) OR MIN(h) <> MAX(h) OR COUNT(*) = 1
ORDER BY bucket;

-- 2. Pull rows only from the buckets that differ
WITH bad AS (
  SELECT bucket FROM fp GROUP BY bucket
  HAVING MIN(n) <> MAX(n) OR MIN(h) <> MAX(h) OR COUNT(*) = 1
)
SELECT 'only in source' AS side, order_id, line_no, amount
FROM (SELECT order_id, line_no, amount FROM src WHERE bucket IN (SELECT bucket FROM bad)
      EXCEPT
      SELECT order_id, line_no, amount FROM tgt WHERE bucket IN (SELECT bucket FROM bad)) AS a
UNION ALL
SELECT 'only in warehouse', order_id, line_no, amount
FROM (SELECT order_id, line_no, amount FROM tgt WHERE bucket IN (SELECT bucket FROM bad)
      EXCEPT
      SELECT order_id, line_no, amount FROM src WHERE bucket IN (SELECT bucket FROM bad)) AS b
ORDER BY order_id, line_no, side;

Step 1 returns one row per bucket that disagrees: 32 small rows were compared, not 401. Step 2 reads only those buckets' rows and finds the same five rows as the full diff above. ('x' || hex)::bit(60)::bigint turns hex digits into a number. Between real systems both sides must use the same hash and write each value as the same text.

Remember: count, then sum, then hash, each at a grain such as a day. Then diff the rows in both directions.

Back to the $907.25

Now the two systems Tess is comparing. Order lines say what customers bought. The payments file says what was charged. For each order, the captured amount should equal the order's total.

So reconcile order by order, not in total. The level you compare at is called the grain. At the order grain the difference stops being one alarming number. It falls into a few groups, and each group has an owner.

Orders against payments, per order, with pandas

import pandas as pd

items = pd.read_csv('data/order_items.csv')
orders = pd.read_csv('data/orders.csv')
payments = pd.read_json('data/payments.jsonl', lines=True)

items['amount'] = items['qty'] * items['unit_price']
ordered = items.groupby('order_id')['amount'].sum().rename('ordered')
captured = payments[payments['status'] == 'captured'].groupby('order_id')['amount'].sum().rename('captured')

rec = orders.set_index('order_id')[['status']].join(ordered).join(captured).fillna(0)
rec['gap'] = (rec['captured'] - rec['ordered']).round(2)
print('ordered:', round(rec['ordered'].sum(), 2), '| captured:', round(rec['captured'].sum(), 2))

gaps = rec[rec['gap'] != 0]
print(gaps.groupby('status')['gap'].agg(['count', 'sum']).round(2))
print(gaps[gaps['status'] != 'cancelled'])

One row per order, with what was ordered and what was captured; fillna(0) turns "no payment" into 0. The gaps group by status: 9 cancelled orders, and two shipped orders that need a person.

The $907.25, split by cause

Three bars: cancelled orders with nothing captured account for 972.25 dollars, order 1047 shipped and never paid for 26.25 dollars, and order 1033 charged twice for 91.25 dollars in the other direction.

Each bar is the size of one group's gap. Two pull captured below ordered and one pushes it above: 972.25 + 26.25 - 91.25 = 907.25.

The $907.25, explained

GroupOrdersGapVerdict
Cancelled: lines exist, nothing captured9-$972.25Expected: revenue should exclude cancelled orders
Order 1047: shipped, never paid1-$26.25Problem: chase the payment
Order 1033: charged twice1+$91.25Problem: refund the customer
Total11-$907.25

Order 1058 has no lines and no payment, so its gap is 0 and a per-order comparison does not flag it. The "orders without lines" check of Lesson 7.1 does: reconciliation and checks work together.

The trap: trusting totals. Totals that match can still be wrong, and totals that differ tell you nothing. Reconcile at a grain (per day, per order, per file), compare in both directions, and save the result as a table with the run time. Then a mismatch is a list of keys someone can act on, not one alarming number.

Finance teams reconcile the warehouse against the payment provider (Stripe, Adyen) every month, order by order. Data teams automate source-to-target reconciliation after each load: datacompy (a Python library) and Datafold's data diff compare tables row by row, dbt's audit_helper package compares a rewritten model with the old one, and Great Expectations and Soda can compare row counts across two sources. The bucket method is a Merkle-tree idea. Datafold's open-source data-diff (no longer maintained since 2024) worked this way: checksum key-range segments on both databases, bisect the segments that disagree, and download rows only below a threshold.

Numbers to remember

WhatNumber or ruleGood to know
Sorted row hashes, hashed againexactSorts every row. md5(stringagg(rowhash, '' ORDER BY rowhash)) in Postgres
Sum of 64-bit row hashes, modulo 2^64cheapStreams, merges across partitions, and still sees a duplicated row
XOR of row hashescheap, blind to pairsA row loaded twice XORs to zero, so always compare the count too
Snowflake HASHAGGorder-insensitiveIts docs say duplicate rows change the result
Separator between valuesone that cannot occur in the data'ab' || 'c' equals 'a' || 'bc'
Same text on both sidesfixed decimal scale, UTC at one precision, a token for NULLIn Postgres a NULL in the concatenation makes the whole hash NULL, and stringagg and SUM skip it
1 billion rows in 1,024 bucketsabout 977,000 rows a bucketSplit by 1,024 again: about 954. 1,024 fingerprints are a few tens of kilobytes
Copying 1 billion 100-byte rows100,000 MBTwo levels of fingerprints: 0.26 MB. The rows of 3 sub-buckets, both sides: 0.57 MB

What changed at SwiftKart

By lunch Tess has her answer, and it is not one number. Nine cancelled orders explain $972.25: expected, and the revenue report should leave them out. Order 1047 shipped without being paid, so someone chases $26.25. Order 1033 was charged twice, so the customer gets $91.25 back.

The pipeline now reconciles after every load: counts and sums per day on each run, hash totals every night, and the results saved with the run time.

All of this assumes both sides still have the same columns. Lesson 7.4 is about the morning they do not: one column is renamed, another appears, and the load carries on regardless.

In one line

Reconcile two sides with counts, sums and hash totals at a grain, then diff the rows both ways to find which keys are missing, extra or changed.

Interview corner

How do you reconcile a pipeline's output with its source?

Start cheap: row counts and key totals per day or per partition. Where they differ, diff the rows both ways on the key and the important values (EXCEPT or a full outer join). Add hash totals when values could change without moving counts or sums. Store the results with the run time so mismatches can be tracked and fixed.

Why reconcile at a grain instead of comparing grand totals?

Errors cancel out in totals, and a total difference does not say where to look. At the grain of a day or an order, each mismatch points to specific keys and usually to a cause: late rows, duplicates, a filter or a business rule like cancellations.

How would you prove a 2-billion-row table in Postgres matches its copy in Snowflake, and find any rows that differ?

I would not move the rows. Each side computes, per bucket of a hash of the key (say 4,096 buckets), a row count and an order-independent hash aggregate, such as a sum of 64-bit row hashes, over canonicalised values: fixed numeric scale, UTC timestamps, an explicit NULL token. Comparing 4,096 pairs is trivial; I recurse into mismatched buckets with sub-buckets until each holds a few thousand rows, then pull just those and diff them both ways. I avoid XOR aggregates, which cancel duplicates, and run the comparison on a consistent snapshot on each side, or excluding the last hour of changes.

What is a hash total?

A fingerprint of a set of rows: hash each row's key and values, combine the hashes in an order-independent way (sort, then hash), and compare one value between systems. It changes when any value changes, even when counts and sums still match, and it can be computed on each side without moving the data.