Accounting for DevelopersModule 4: Production financial systemsAdvanced4 min read
Building a Bank Reconciliation Engine
Design an automated bank reconciliation engine in SQL and TypeScript: idempotent bank feeds, exact and fuzzy matching, many-to-one payouts and exception queues.
Course outline (16 lessons)
Before this lesson:Journal and General Ledger Database DesignInvoice and Payment Lifecycle in Accounting Software
In this lesson · 6 sections
Your general ledger says Cash is $48,250, while your online bank portal shows $51,420. Neither number is necessarily wrong: banks and books run on different clocks. A bank reconciliation engine automatically pairs external bank statement lines against your internal postings to explain every single cent of difference.
Why bank balances and ledger balances differ
Differences always fall into two buckets:
- Timing differences (already in the ledger, not yet at the bank): deposits in transit or outgoing vendor transfers initiated on the 30th that clear on the 2nd. No new journal entry is needed—they clear next month.
- Unrecorded bank items (on the bank statement, missing from the ledger): monthly account fees, bank interest, bounced payments or a customer who wired cash without notifying billing. These require new balanced journal entries.
Bank ending + Deposits in transit − Outstanding payments = Book ending + Unrecorded inflows − Unrecorded outflows
- Deposits in transit
- cash receipts recorded in the ledger not yet cleared by the bank
- Outstanding payments
- payments recorded in the ledger not yet debited by the bank
- Unrecorded inflows/outflows
- bank interest, direct wires, fees or NSF charges needing ledger entries
Idempotent bank feed and match schema
Treat external bank lines as raw, immutable evidence separate from your postings. Link them through a many-to-many reconciliation_matches table so one bank payout can settle many postings (or vice versa):
CREATE TYPE recon_status AS ENUM ('unmatched', 'suggested', 'matched', 'reconciled', 'excluded');
CREATE TABLE bank_statement_lines (
id uuid PRIMARY KEY,
bank_account_id uuid NOT NULL REFERENCES accounts(id),
external_tx_id text NOT NULL, -- Plaid/ISO 20022/OFX unique ID
posted_date date NOT NULL,
amount_minor bigint NOT NULL, -- positive = cash in, negative = cash out
currency char(3) NOT NULL,
reference text,
counterparty text,
status recon_status NOT NULL DEFAULT 'unmatched',
UNIQUE (bank_account_id, external_tx_id)
);
CREATE TABLE reconciliation_matches (
id uuid PRIMARY KEY,
bank_statement_line_id uuid NOT NULL REFERENCES bank_statement_lines(id),
posting_id bigint NOT NULL REFERENCES postings(id),
matched_amount_minor bigint NOT NULL CHECK (matched_amount_minor <> 0),
match_rule text NOT NULL, -- 'exact_ref', 'fuzzy_window', 'many_to_one', 'manual'
confidence smallint NOT NULL CHECK (confidence BETWEEN 0 AND 100),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (bank_statement_line_id, posting_id)
);
Enforce in your matching service that the sum of matched_amount_minor for a bank line never exceeds its amount_minor, and only flip status to reconciled once a human or automated close job confirms the full statement balance.
Staged matching pipeline
Run matching rules in order from highest certainty to lowest, moving only high-confidence pairs straight to matched and queuing ambiguous ones as suggested:
- Stage 1 — Exact match (auto-match, confidence 100): identical
currencyandamount_minor, exact reference or payment ID, and|bank.posted_date − entry.effective_date| <= 3days. - Stage 2 — Fuzzy single match (suggest, confidence 70–95): exact
amount_minor, date within ±5 business days, and normalised counterparty/memo similarity above threshold. - Stage 3 — Many-to-one batch match (auto-match or suggest): group unmatched postings by settlement batch ID (or date + counterparty) whose sum equals one bank line—common for card payouts and bulk ACH collections.
- Stage 4 — Exception queue: leftover bank lines (fees, interest, unknown wires) prompt one-click journal entry creation; leftover old ledger postings flag stale or duplicate entries.
interface BankLine { id: string; date: string; amountMinor: bigint; reference?: string; }
interface CashPosting { postingId: bigint; date: string; amountMinor: bigint; reference?: string; }
function daysApart(a: string, b: string): number {
return Math.abs(Date.parse(a) - Date.parse(b)) / 86_400_000;
}
function scorePair(bank: BankLine, post: CashPosting): number {
if (bank.amountMinor !== post.amountMinor) return 0;
const gap = daysApart(bank.date, post.date);
if (gap > 5) return 0;
if (bank.reference && post.reference && bank.reference === post.reference) return 100;
return gap <= 2 ? 85 : 70; // exact amount within window -> suggest for review
}
Worked example
Harborline Supply (fictional) — April bank reconciliation
On 30 April, Harborline Supply’s operating bank statement closes at $51,420, while ledger account 1000 Cash shows $48,250. Running the engine surfaces five unmatched items:
| Side | Item | Amount | Action |
|---|---|---|---|
| Bank | Ending statement balance | $51,420 | Starting figure |
| Bank | Deposit in transit (recorded 30 Apr) | +$2,400 | Timing — no entry |
| Bank | Outstanding vendor transfers (29 Apr) | −$4,400 | Timing — no entry |
| Bank | Adjusted bank balance | $49,420 | Matches book |
| Ledger | Ending 1000 Cash balance |
$48,250 | Starting figure |
| Ledger | Unrecorded bank interest | +$45 | Post journal entry |
| Ledger | Unrecorded bank service fees | −$75 | Post journal entry |
| Ledger | Unrecorded direct customer wire (INV-412) |
+$1,200 | Post journal entry |
| Ledger | Adjusted book balance | $49,420 | Matches bank |
Harborline’s engine generates three balanced journal entries for the unrecorded bank items:
| Account | Debit (Dr) | Credit (Cr) |
|---|---|---|
| Cash | $45 | |
| Interest Income | $45 | |
| Total✓ Balanced | $45 | $45 |
| Account | Debit (Dr) | Credit (Cr) |
|---|---|---|
| Bank Charges Expense | $75 | |
| Cash | $75 | |
| Total✓ Balanced | $75 | $75 |
| Account | Debit (Dr) | Credit (Cr) |
|---|---|---|
| Cash | $1,200 | |
| Accounts Receivable | $1,200 | |
| Total✓ Balanced | $1,200 | $1,200 |
After posting, 1000 Cash equals $48,250 + $45 − $75 + $1,200 = $49,420, matching the adjusted bank balance exactly. Try reconciling statement lines yourself in the Bank Reconciliation Lab.
Real-world application
Modern treasury tools and accounting apps pull daily bank feeds via Open Banking, Plaid or ISO 20022 camt.053 files, auto-matching 80–95% of volume overnight so finance teams only spend time on exceptions. Continuous daily reconciliation catches duplicate payouts, missing processor settlements and fraud weeks before month-end close.
Recap
- Ingest bank feed lines into an immutable table guarded by
UNIQUE (bank_account_id, external_tx_id). - Connect bank lines and ledger postings through a many-to-many
reconciliation_matchestable to support batch settlements. - Run staged matching (exact → fuzzy → many-to-one → exception queue), posting balanced entries only for unrecorded bank items—not timing differences.
- Reconcile until
Adjusted bank balance === Adjusted book balanceto the minor unit.
Try it yourself
Active recall
Quick check · Test yourself
Work out each answer in your head first, then reveal the explanation and mark whether you got it right.
1Your ledger Cash balance is $48,250 and your bank statement shows $51,420. You find $2,400 of deposits in transit, $4,400 of outstanding vendor payments, $45 of unrecorded bank interest, $75 of bank fees and a $1,200 unrecorded customer wire. What is the reconciled cash balance?
Show worked answer
$49,420. Adjusted bank balance = $51,420 + $2,400 − $4,400 = $49,420. Adjusted book balance = $48,250 + $45 − $75 + $1,200 = $49,420. Both sides match to the cent.
2Why should bank statement ingestion require a unique constraint on (bank_account_id, external_tx_id)?
Show worked answer
Bank APIs and overlapping CSV exports frequently redeliver recent days of transactions. Without a unique external transaction key, re-importing creates duplicate bank lines that corrupt the cash reconciliation.
3A single $3,850 bank deposit settles three separate customer invoices ($1,200, $1,500 and $1,150). How should the database model this match?
Show worked answer
Use a many-to-many reconciliation_matches join table with three rows sharing the same bank_statement_line_id, each pointing to one ledger posting_id with its matched_amount_minor, where the three amounts sum to $3,850.
Key terms in this lesson
Lesson 10 of 16 · Accounting for Developers
Finished this lesson?
Mark it complete to track your progress through the course. Progress is saved in this browser only.
Previous lesson: Multi-Currency Ledgers and Foreign Exchange in Code
Connected lessons
Educational content only—not accounting, tax, legal or investment advice. See our editorial policy or report an error via our corrections policy.