Reconciliation - Complete Deep Dive
Prerequisites: Idempotency, Consistency Models Used in: Payment System, Digital Wallet, Stock Broker
What is Reconciliation?
Reconciliation is a background job — a reconciler — that independently recomputes or re-fetches what the truth should be, compares it against what your system currently believes, and then either repairs the difference or raises it for a human to look at. The word for a single mismatch it finds is a break.
The important word is independently. A reconciler that asks the same service, through the same code path, that produced the data in the first place will cheerfully confirm its own bugs. A real reconciler goes around the normal path: it reads the bank’s settlement file instead of your payments table, or it re-sums the ledger rows from scratch instead of trusting the cached balance.
Real-world analogy: A shop’s till. All day the cashier rings up sales and the register’s running total climbs to £4,312. At closing the manager empties the drawer and counts the actual notes and coins by hand — £4,298. Neither number is wrong by malice; a customer was short-changed, a refund was given from the drawer without being rung up. Counting the cash is the reconciler: an independent measurement of the same quantity. The £14 gap is the break, and the manager now has to decide whether it is a known timing quirk, a mistake to correct, or a pattern worth investigating.
Why Drift Is Inevitable
The instinct on seeing a mismatch is to find the bug and fix it so it never happens again. That instinct is wrong, and letting go of it is the whole conceptual shift. Drift is a permanent property of distributed systems, not a defect you can eliminate. Every one of these produces drift even when every line of your code is correct:
- Partial failures. You charged the card and crashed before writing the row. The money moved; your database does not know. No retry policy prevents this, because the crash can land in any gap between two writes.
- Lost webhooks. The payment provider fired
charge.succeededat your endpoint during a deploy and got a 502. They retry a few times, then give up. Their state advanced; yours did not. - At-least-once duplicates. Your queue redelivered a message and the dedup key had already expired. See delivery semantics for why duplicates are a certainty rather than a risk.
- Cache and replica staleness. A read replica is 400ms behind the primary. A cached aggregate was computed before the last three writes. Anything that reads from them sees a past that no longer exists.
- Clock skew. Two services disagree about what “end of day” means by 80ms, so a transaction lands in yesterday on one side and today on the other. Both are internally consistent. They do not match.
- Bugs that already shipped. A release two months ago mis-rounded 0.5 cents on one code path. You fixed the code; the fix did not go back and repair the 1.4 million rows it already wrote.
- Third parties who simply disagree. The carrier says the parcel was delivered Tuesday. Your tracking row says in transit. Nobody made a mistake you can point at.
flowchart LR
SRC["Independent source of truth<br/>bank file or provider API<br/>or recomputed aggregate"] --> CMP["Comparator"]
SYS["What your system believes"] --> CMP
CMP --> BRK{"Difference found"}
BRK -->|"No"| OK["Record a clean run"]
BRK -->|"Yes"| CLS["Classify the break"]
CLS --> REP["Repair automatically"]
CLS --> ALR["Raise for a human"]
Because drift is continuous, reconciliation is not a cleanup script you write after an incident. It is a permanent organ of the system, as load-bearing as the write path. Teams that treat it as optional discover their drift when a customer does.
The Three Jobs, Kept Distinct
A reconciler does three things, and collapsing them is the most common design mistake.
| Job | What it means | Can it be wrong |
|---|---|---|
| Detect | Compare the two sides, emit a list of breaks | Cheap and safe. Worst case is a false alarm. |
| Classify | Decide what kind of break each one is | Where the judgment lives |
| Repair | Change state to resolve the break | Dangerous. It writes. |
Build and ship detect first, on its own, and let it run for weeks while you only look at the output. You will learn that most of what it flags is not a problem — it is normal timing. If you had wired repair straight to detect, your reconciler would have spent those weeks “fixing” transactions that were mid-flight and perfectly healthy.
Auto-repair without classification is how a reconciler becomes the outage. A job that sees a payment marked pending locally and succeeded upstream, and auto-marks it succeeded, sounds helpful — until a provider API glitch returns succeeded for the wrong id and the reconciler settles ten thousand orders that were never paid. It will do it faster and more consistently than any human error ever could, because that is what jobs are good at. Only classes you have seen, understood, and can describe in one sentence get an auto-repair path. Everything else goes to a human queue.
Continuous Sweeps vs Periodic Full Passes
There are two shapes of reconciler, they catch different bugs, and serious systems run both.
Continuous reconciliation is a sweeper that runs every minute or two over rows changed recently — “everything touched in the last 15 minutes, excluding the last 60 seconds.” It is cheap because the working set is tiny, and it catches the common cases fast: the lost webhook, the crash mid-write, the stuck state.
Periodic full reconciliation is a heavy pass over everything, usually nightly or at end of day, often against a file the counterparty produces on their own schedule. It is expensive and slow, and it is the only thing that catches the slow silent class: the row that drifted eight months ago and sits outside every recent-change window, or the aggregate that is off by one cent per transaction in a way no single comparison reveals.
| Continuous sweep | Periodic full pass | |
|---|---|---|
| Scope | Recently changed rows | Everything, or a full date range |
| Cadence | Every 1 to 5 minutes | Nightly, or end of day |
| Detection lag | Minutes | Up to a day |
| Catches | Stuck states, lost callbacks, crash gaps | Old drift, systematic errors, slow leaks |
| Cost | Low | High, run it off-peak on a replica |
| Misses | Anything older than its window | Anything urgent |
Running only the sweep means old drift accumulates forever outside the window; running only the nightly pass means a stuck payment sits broken for twenty hours. Neither alone is sufficient, and the two together cost very little more than the expensive one. Two practical notes: exclude the most recent minute from the sweep, because rows written seconds ago are legitimately mid-flight and including them generates nothing but noise, and run the full pass against a read replica or a columnar copy rather than the primary, because a full-table scan on a live OLTP database at 2am is its own incident.
The State Machine Timeout Pattern
If you take one reusable thing from this page, take this: any row sitting in a non-terminal state past its deadline is a break.
It needs no external system, no file from a counterparty, no recomputation. It only needs your own table and a clock. Every workflow has states that are supposed to be transient — pending, authorizing, in_transit, awaiting_capture — and every transient state has a duration past which staying there is impossible rather than slow.
-- The single most reusable reconciliation query in existence.
SELECT id, status, updated_at, NOW() - updated_at AS stuck_for
FROM payments
WHERE status IN ('pending', 'authorizing', 'capturing')
AND updated_at < NOW() - INTERVAL '15 minutes'
ORDER BY updated_at;
A payment authorizing for fifteen minutes is not slow — authorization takes two seconds. Something ate the callback, or the process that owned that row died holding it. The query is four lines and it catches crashed workers, lost webhooks, dropped queue messages, and expired locks all at once, without knowing anything about why.
Make it general by writing the deadline into the row at each transition rather than hardcoding intervals, so one query covers every state in the machine:
SELECT * FROM payments
WHERE state_deadline < NOW()
AND status NOT IN ('succeeded', 'failed', 'refunded');
Terminal states get a null deadline and drop out of the scan, and a partial index on state_deadline excluding terminal rows keeps this fast at any table size. This pattern is the backstop under every saga and every durable execution workflow — it is what turns “the orchestrator crashed” from a stuck order into a flagged break.
Reconciling Against an External System of Record
When the other side is a payment rail, a bank settlement file, a shipping carrier, or an exchange, one rule governs everything: their number wins.
This is not deference, it is physics. The money is in their system. The parcel is on their van. The trade is on their book. If your ledger says a charge settled at $25.00 and the bank’s file says $24.97 after an interchange adjustment, your row is wrong by definition, and no argument changes what the bank will actually pay you. Your job is to match their truth, record why you differed, and never overwrite theirs.
The practical shape is a three-way split over a shared key — their reference id, your reference id, or an idempotency key you sent them precisely so this join would be possible:
flowchart TD
FILE["Counterparty file or API<br/>for the settlement date"] --> JOIN["Match on shared reference id"]
MINE["Your rows for the same date"] --> JOIN
JOIN --> BOTH["In both<br/>compare amount and status"]
JOIN --> THEIRS["Only on their side<br/>you missed an event"]
JOIN --> OURS["Only on your side<br/>you believe something they do not"]
BOTH --> MATCH["Amounts agree<br/>clean"]
BOTH --> DIFF["Amounts differ<br/>break"]
Each arm means something different and needs a different response. Only on their side is usually a lost webhook — you can safely ingest it. Only on your side is the scary one: you think a charge exists that the provider has no record of, which may mean you shipped goods for money that never moved. In both but different is often a fee, an FX adjustment, or a partial refund you have not modelled yet.
Build the join on a key you control. Sending your own idempotency key as the provider’s reference field — see delivery semantics — means reconciliation is a join rather than a fuzzy match on amount and timestamp. Teams that skip this end up matching on amount + date + last four digits, which breaks the first time a customer buys the same thing twice in one day.
Classifying Breaks
Three buckets. Keep them separate and label every break with one.
Timing differences resolve themselves. A transfer initiated at 23:59:58 lands in your file today and theirs tomorrow. A read replica is 300ms stale. The correct action is wait and re-check, and a break in this class must disappear within a bounded window. The discipline: a timing break that is still present on the next run has been misclassified, and should escalate automatically rather than being re-forgiven forever.
True discrepancies are real and will not fix themselves. A duplicate charge. A payment the provider never received. An amount that genuinely differs. These need action, from a human or from a reviewed auto-repair path.
Unexplained is the bucket everyone wants to pretend does not exist, and the most important one to keep. A break you cannot place is a signal that your model of the system is incomplete. The count of unexplained breaks is the single best health metric a reconciler produces. Rising unexplained usually means a new product flow, a provider API change, or a fresh bug — and because you cannot explain it, you must not auto-repair it.
| Class | Action | Resolves on its own | Safe to auto-repair |
|---|---|---|---|
| Timing | Wait, re-check next run | Yes, within a bounded window | Nothing to repair |
| True discrepancy | Repair or raise | No | Only for reviewed known classes |
| Unexplained | Investigate, always alert | No | Never |
Safe Repair Requires Idempotency
A reconciler is the most retried code you will ever write. It runs every minute, over overlapping windows, often concurrently with the live path that is also mutating those rows, and it is frequently re-run by hand after an incident. If a repair is not idempotent, the reconciler stops being a safety net and becomes a duplicate-generating machine with a cron schedule.
-- Not idempotent. Run the reconciler twice, credit the user twice.
UPDATE accounts SET balance = balance + 25.00 WHERE id = 42;
-- Idempotent. The unique key makes the second run a no-op,
-- and the balance is derived from the ledger rather than incremented.
INSERT INTO ledger_entries (dedup_key, account_id, amount_cents, reason)
VALUES ('recon:settlement_2026_10_27:txn_9f12', 42, 2500, 'settlement_adjustment')
ON CONFLICT (dedup_key) DO NOTHING;
Two rules make repairs safe. First, every repair carries a stable key derived from the break, not from the run — recon:<source>:<their_reference> rather than a fresh UUID each pass, so the same break repaired twice is one effect. Second, repair by appending a correcting entry, never by editing history. Changing a past row destroys the evidence of what happened; appending an adjustment leaves both the original and the correction visible, which is what anyone investigating actually needs. The deeper treatment of both is in idempotency.
Making the Reconciler Observable
A silent reconciler is worse than no reconciler, because it buys you confidence you have not earned. Three rules.
Emit the break count by class as a metric, every run. Not a log line — a metric, dimensioned by source and class, so you can graph it. recon.breaks{source=stripe,class=unexplained}. A reconciler whose output you cannot graph is a reconciler nobody looks at.
Alert on the rate, not the existence. A healthy payment reconciler finds breaks on every single run; that is it doing its job. Alerting on “breaks > 0” trains the team to ignore the page within a week. Alert on the shape instead:
| Alert on | Why it means something |
|---|---|
| Unexplained breaks above baseline | Your model of the system just went stale |
| Repair volume rising run over run | Something upstream is actively broken |
| A timing break still open after N runs | It was never a timing break |
| The reconciler did not run | The most dangerous alert, and the one most often missing |
| Oldest open break ageing past SLA | Breaks are arriving faster than they are cleared |
Never let it silently fix a growing number of rows. This is the failure that looks like success. A reconciler quietly repairing 200 rows a day, then 2,000, then 40,000, is not a well-functioning safety net — it is an undiagnosed bug in the write path with a janitor hiding it. Put a hard ceiling in the code: if a run would repair more than some threshold, it stops, repairs nothing, and pages a human. A reconciler that refuses to act on a 50,000-row discrepancy is behaving correctly, because at that volume the reconciler is far more likely to be wrong than the data is. See observability for the surrounding metric and alerting design.
The Audit Trail Requirement
Every repair writes a durable record of what it changed and why. No exceptions, including for repairs you consider trivial.
CREATE TABLE reconciliation_repairs (
id BIGSERIAL PRIMARY KEY,
run_id UUID NOT NULL, -- which reconciler run
source TEXT NOT NULL, -- which independent truth
break_class TEXT NOT NULL, -- timing | discrepancy | unexplained
entity_type TEXT NOT NULL,
entity_id TEXT NOT NULL,
expected JSONB NOT NULL, -- what the source said
observed JSONB NOT NULL, -- what we believed
action_taken TEXT NOT NULL, -- repaired | flagged | ignored
dedup_key TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Three reasons this is not bureaucracy. Debugging: when a balance is wrong, the first question is always “did anything other than the normal path touch this row,” and without the trail you cannot answer it. Trust: a reconciler nobody can audit will eventually be turned off by someone who does not believe it. Obligation: in regulated domains an unexplained automated adjustment to a customer’s money is a finding, and “the job fixed it” is not an acceptable answer to an auditor. Note that dedup_key is UNIQUE here — the audit row and the idempotency guard are the same record, so the trail cannot drift from the repairs it describes.
A Worked Payment Reconciler
Concretely, for a service that charges cards through a provider.
Independent sources. Three, deliberately: the provider’s settlement file for the date, which is authoritative on money actually moved; the provider’s API, for per-charge status; and a recomputation of each account balance by summing its ledger rows from scratch, which is independent of the cached balance column.
Continuous sweep, every minute. Two queries — payments in a non-terminal state past state_deadline, which catches crashed workers and lost webhooks, and payments whose local status disagrees with the provider’s API status for rows touched in the last hour excluding the last 60 seconds.
Nightly full pass. Join the provider’s settlement file for yesterday against local payment rows on the idempotency key that was sent as the provider reference, producing the three arms — matched, provider-only, local-only — plus amount mismatches. Separately, re-sum every ledger account changed yesterday and compare against the cached balance.
Classification rules, as narrow as possible.
| Break | Class | Action |
|---|---|---|
Local pending, provider succeeded, file agrees |
Discrepancy, known | Auto-repair. Append the ledger entry keyed on the provider reference, advance local status. |
Local pending, provider has no such charge, older than 1 hour |
Discrepancy, known | Auto-repair. Mark failed, release any reservation. |
| In the file, no local row at all | Unexplained | Alert. Money moved for something we have no record of. Never auto-created. |
Local succeeded, absent from the file, settled today |
Timing | Wait. Escalate if still absent tomorrow. |
| Amount differs by a known fee code | Discrepancy, known | Auto-repair as a fee adjustment entry. |
| Amount differs by anything else | Unexplained | Alert. |
| Cached balance differs from the ledger re-sum | Discrepancy | Auto-repair the cache, which is derived data, and alert if the gap exceeds a threshold. |
Two of the seven rows alert rather than repair, and both are cases where repairing would mean inventing state. That ratio is the point: the narrowness of the auto-repair list is the safety property, and every rule on it earned its place by being observed, understood, and reviewed first.
When to Use / When NOT to Use
✅ Build a reconciler when:
- Money, inventory, or any quantity that must balance crosses a service boundary
- An external system of record exists whose truth you must match
- You have multi-step workflows that can stall, which is every saga
- You maintain derived or cached aggregates that could drift from their source
- Being wrong is expensive and being wrong silently is unacceptable
❌ Skip it when:
- The data has a single writer and a single store, with no derived copies
- Drift is cosmetic, for example a view counter that is off by three
- The entire state is trivially recomputable on read, so there is nothing to drift
- You have not yet built detection — in which case build detection, not repair
Common Interview Questions
Q1: Why do you need a reconciler if your writes are already transactional?
Transactions protect one database. They do nothing the moment state spans two systems. You cannot put a card charge at a payment provider and a row in your own Postgres into one transaction, so there is always a window where one happened and the other did not. Add lost webhooks, at-least-once duplicates, stale replicas and bugs that already wrote bad rows, and you have continuous drift that no amount of local transactional correctness prevents. Reconciliation is the mechanism that notices.
Q2: Should a reconciler fix what it finds automatically?
Only for break classes you have seen, understood, and can describe in one sentence — and only idempotently. Auto-repair wired straight to detection is how a reconciler causes an incident: one bad provider response and it confidently settles ten thousand unpaid orders at machine speed. Ship detection alone first and watch its output for weeks, promote individual classes to auto-repair as you come to understand them, and route everything unexplained to a human. Also cap repair volume per run, so a run facing 50,000 breaks stops and pages instead of acting.
Q3: Continuous or periodic — which one, and why?
Both, because they catch different bugs. The continuous sweep runs every minute over recently changed rows and catches urgent cases — stuck states, lost callbacks, crash gaps — within minutes, but it is structurally blind to anything older than its window. The nightly full pass is the only thing that finds drift from eight months ago or a systematic one-cent error, but it is twenty hours too slow for a stuck payment. Run the sweep on the primary, the full pass off-peak on a replica, and exclude the most recent minute from the sweep so mid-flight rows do not generate noise.
Q4: What is the most reusable reconciliation pattern you know?
The state machine timeout. Any row in a non-terminal state past its deadline is a break. It needs no external system and no recomputation — just your own table and a clock — and in four lines of SQL it catches crashed workers, lost webhooks, dropped queue messages and expired locks without knowing why any of them happened. Store the deadline on the row when each transition occurs, give terminal states a null deadline, and one indexed query covers the whole machine.
Q5: Your reconciler quietly repairs a few hundred rows a day and the graph is climbing. Is it working?
No — it is masking a live bug in the write path. A reconciler is a safety net for residual drift, not a substitute for correct writes, and a rising repair rate is the symptom of something upstream actively breaking. The right response is to alert on the repair rate and on unexplained breaks rather than on breaks existing at all, treat a climbing trend as a page, and enforce a per-run repair ceiling that halts the job. And alert on the reconciler failing to run, which is the most dangerous gap and the one teams most often forget.
Navigation
| ← Durable Execution | Microservices vs Monolith → |
| All Concepts | HLD Designs |