Money · Databases

Payment Reconciliation in SQL: Match Your Ledger to the Bank

Your ledger says one thing and the bank says another. Find out which lines differ, and why.

Part 3 of 3: Money in your database This is the last part.

The provider’s report shows 166.00 in card payments and a 10.00 refund. The bank shows one deposit of 150.28. Your ledger took 165.00. Is the ledger wrong, is the bank wrong, or are both right?

Both can be right. Three fees and a refund explain the gap between the payments and the deposit. The 1.00 between your ledger and the report is something else. You can’t tell from the totals. You have to match the records line by line and look at what is left over. That job is payment reconciliation.

Short version:

  • Every line in your ledger needs a partner in the provider’s report, and every payout needs a partner on the bank statement. What has no partner is a break, and you list the breaks.
  • Store the provider’s reference as soon as you have it. Without that key you are guessing on amount and date.
  • Fix a break with a new adjusting entry. Never edit an old row. Count open breaks by age and value every day.

This is part 3 of Money in your database. Part 1 covers how to store amounts, part 2 the ledger this post checks.

The problem: three records that should agree

External reconciliation compares your ledger with records you don’t own: the provider’s settlement report and your bank statement. This is the hard one.

Internal reconciliation is the cache check from part 2. Run it often. A row there is a bug in your own code.

Your ledger, the providers report and the bank statement. Lines match on the provider reference, payouts match to one deposit.

Accountants call the external check a bank reconciliation. OpenStax’s accounting textbook lists the usual causes, and they carry over to card payouts almost one to one.

Step 0: store the provider’s reference when you write the row

Matching needs a key that both sides know. The provider gives every payment, refund and dispute an id. Keep it next to your transaction. These examples use ids shaped like Stripe’s: ch_ for a charge, re_ for a refund and du_ for a dispute.

The ledger is the one from part 2. It forbids UPDATE on transactions, so the reference goes into an insert-only table once the provider answers:

CREATE TABLE provider_refs (
  transaction_id bigint NOT NULL UNIQUE REFERENCES transactions (id),
  provider_ref   text   NOT NULL,           -- ch_..., re_..., du_...
  kind           text   NOT NULL,           -- charge | refund | dispute | adjustment
  UNIQUE (provider_ref, kind)               -- the same provider payment can't be booked twice
);

The amount to match is the entry on the card_network account. A view puts the ledger in the shape of the provider’s report:

CREATE VIEW ledger_items AS
SELECT t.id,
       r.provider_ref,
       coalesce(r.kind, CASE WHEN e.amount_minor < 0 THEN 'charge' ELSE 'refund' END) AS kind,
       -e.amount_minor AS amount_minor,     -- money in is negative on card_network
       e.currency,
       t.created_at    AS posted_at
FROM transactions t
JOIN entries e  ON e.transaction_id = t.id
JOIN accounts a ON a.id = e.account_id AND a.name = 'card_network'
LEFT JOIN provider_refs r ON r.transaction_id = t.id;

Before the reference exists, the kind comes from the sign. You can’t put the provider call and your database write in one transaction, so the order is:

  1. Insert the transaction.
  2. Call the provider, with an idempotency key so a retry does not charge twice. Send your transaction id as metadata.
  3. When the answer comes back, insert the provider_refs row.

If the process dies after step 2, the transaction has no reference. Stripe’s itemized report can include metadata columns (payment_metadata[key]), so the report gives your id back and a repair job can insert the missing row. The fallback match below handles the rest. The outbox pattern is a good way to make step 2 reliable.

The pipeline

Six steps: import, normalize, match, classify, queue, fix with adjusting entries.

Outputs below are from Postgres 17 with small sample data. The report columns are the ones in Stripe’s itemized payout report, because that documentation is public. Other providers use other names for the same ideas.

1. Import the file as it came

Put every line in a raw table and change nothing. When your parser has a bug next month, you can parse the same bytes again.

CREATE TABLE provider_report_raw (
  id          bigserial   PRIMARY KEY,
  report_id   text        NOT NULL,        -- file name or report id
  line_no     int         NOT NULL,
  imported_at timestamptz NOT NULL DEFAULT now(),
  raw         jsonb       NOT NULL,        -- the row exactly as sent
  UNIQUE (report_id, line_no)
);

INSERT INTO provider_report_raw (report_id, line_no, raw)
VALUES ('rpt_1', 1, '{"source_id": "ch_001", "reporting_category": "charge",
  "gross": "100.00", "fee": "3.20", "net": "96.80", "currency": "eur",
  "created_utc": "2026-11-10 09:14:05", "automatic_payout_id": "po_001"}')
ON CONFLICT (report_id, line_no) DO NOTHING;   -- importing a file twice is harmless

2. Normalize

Turn that row into something you can compare with the ledger: integer minor units, an upper-case currency code, and UTC timestamps. Stripe’s report columns are in major units, so the first job is a conversion that needs the decimal places per currency (part 1 covers why).

CREATE TABLE currency_exponent (currency char(3) PRIMARY KEY, exp int NOT NULL);
INSERT INTO currency_exponent VALUES ('USD', 2), ('EUR', 2), ('JPY', 0), ('KWD', 3);

CREATE TABLE provider_lines (
  id           bigserial   PRIMARY KEY,
  raw_id       bigint      NOT NULL REFERENCES provider_report_raw (id),
  provider_ref text        NOT NULL,
  kind         text        NOT NULL,
  gross_minor  bigint      NOT NULL,
  fee_minor    bigint      NOT NULL,
  net_minor    bigint      NOT NULL,
  currency     char(3)     NOT NULL,
  occurred_at  timestamptz NOT NULL,
  payout_ref   text,
  UNIQUE (provider_ref, kind)
);

INSERT INTO provider_lines
  (raw_id, provider_ref, kind, gross_minor, fee_minor, net_minor,
   currency, occurred_at, payout_ref)
SELECT r.id,
       r.raw->>'source_id',
       r.raw->>'reporting_category',
       round((r.raw->>'gross')::numeric * power(10::numeric, x.exp))::bigint,
       round((r.raw->>'fee')::numeric   * power(10::numeric, x.exp))::bigint,
       round((r.raw->>'net')::numeric   * power(10::numeric, x.exp))::bigint,
       upper(r.raw->>'currency'),
       (r.raw->>'created_utc')::timestamp AT TIME ZONE 'UTC',
       nullif(r.raw->>'automatic_payout_id', '')
FROM provider_report_raw r
LEFT JOIN currency_exponent x ON x.currency = upper(r.raw->>'currency')
WHERE r.report_id = 'rpt_1'
ON CONFLICT (provider_ref, kind) DO NOTHING;

Three details matter. The LEFT JOIN is on purpose. A currency missing from currency_exponent gives NULL, the NOT NULL column rejects it, and the import stops. An inner join would drop that row silently, and you would find out as a break weeks later.

power(10::numeric, ...) keeps the math in numeric. power(10, ...) returns a float.

And created_utc is read as UTC, not as the server’s time zone. Stripe says it uses UTC for processing, except in Asia-Pacific markets, so decide the time zone of every timestamp once, here.

3. Match

Rule one is exact: same provider reference, same kind, same amount, same currency. A match goes in its own table. Both sides are UNIQUE, so one line can only be matched once.

CREATE TABLE recon_matches (
  ledger_id        bigint      NOT NULL UNIQUE REFERENCES transactions (id),
  provider_line_id bigint      NOT NULL UNIQUE REFERENCES provider_lines (id),
  rule             text        NOT NULL,   -- ref | amount_date | adjusted
  matched_at       timestamptz NOT NULL DEFAULT now()
);

INSERT INTO recon_matches (ledger_id, provider_line_id, rule)
SELECT l.id, p.id, 'ref'
FROM ledger_items l
JOIN provider_lines p ON p.provider_ref = l.provider_ref AND p.kind = l.kind
WHERE l.amount_minor = p.gross_minor AND l.currency = p.currency
  AND NOT EXISTS (SELECT 1 FROM recon_matches m WHERE m.ledger_id = l.id);

Rule two is the fallback, for rows that never got a reference. It matches on amount, currency and a date window, and only when the answer is unique in both directions:

WITH open_ours AS (
  SELECT l.* FROM ledger_items l
  WHERE l.provider_ref IS NULL
    AND NOT EXISTS (SELECT 1 FROM recon_matches m WHERE m.ledger_id = l.id)
), open_theirs AS (
  SELECT p.* FROM provider_lines p
  WHERE NOT EXISTS (SELECT 1 FROM recon_matches m WHERE m.provider_line_id = p.id)
    AND NOT EXISTS (SELECT 1 FROM provider_refs r
                    WHERE r.provider_ref = p.provider_ref AND r.kind = p.kind)
), candidates AS (
  SELECT o.id AS ledger_id, t.id AS provider_line_id,
         count(*) OVER (PARTITION BY o.id) AS per_ours,
         count(*) OVER (PARTITION BY t.id) AS per_theirs
  FROM open_ours o
  JOIN open_theirs t
    ON t.kind = o.kind AND t.currency = o.currency AND t.gross_minor = o.amount_minor
   AND t.occurred_at BETWEEN o.posted_at - interval '1 day'
                         AND o.posted_at + interval '1 day'
)
INSERT INTO recon_matches (ledger_id, provider_line_id, rule)
SELECT ledger_id, provider_line_id, 'amount_date'
FROM candidates
WHERE per_ours = 1 AND per_theirs = 1;

The per_ours = 1 AND per_theirs = 1 filter stops a guess. With two identical ledger rows and one provider line, it matches nothing and leaves both open. A person decides. That is slower than guessing, but a wrong guess hides a real break.

4. Find what is left: FULL OUTER JOIN

Join the rows that have no match, from both sides. A FULL OUTER JOIN keeps the rows that have no partner on either side, in one query. The PostgreSQL docs describe it: an inner join first, then every unmatched row of each table, with nulls for the other side.

CREATE VIEW recon_diff AS
WITH open_ours AS (
  SELECT l.* FROM ledger_items l
  WHERE l.kind <> 'adjustment'
    AND NOT EXISTS (SELECT 1 FROM recon_matches m WHERE m.ledger_id = l.id)
), open_theirs AS (
  SELECT p.* FROM provider_lines p
  WHERE NOT EXISTS (SELECT 1 FROM recon_matches m WHERE m.provider_line_id = p.id)
)
SELECT coalesce('l' || o.id, 'p' || t.id)       AS item_key,
       o.id                                     AS ledger_id,
       t.id                                     AS provider_line_id,
       coalesce(o.provider_ref, t.provider_ref) AS provider_ref,
       coalesce(o.currency, t.currency)         AS currency,
       o.amount_minor                           AS our_minor,
       t.gross_minor                            AS their_minor,
       coalesce(o.posted_at, t.occurred_at)     AS item_at,
       CASE WHEN t.id IS NULL THEN 'missing_theirs'
            WHEN o.id IS NULL THEN 'missing_ours'
            ELSE 'amount_diff' END              AS shape
FROM open_ours o
FULL OUTER JOIN open_theirs t
  ON t.provider_ref = o.provider_ref AND t.kind = o.kind;

On my sample data, SELECT ledger_id, provider_ref, our_minor, their_minor, shape FROM recon_diff ORDER BY item_at returns:

 ledger_id | provider_ref | our_minor | their_minor |     shape
-----------+--------------+-----------+-------------+----------------
         3 | ch_003       |      4000 |        4100 | amount_diff
           | du_001       |           |       -2000 | missing_ours
         6 | ch_008       |      6000 |             | missing_theirs
           | ch_009       |           |         900 | missing_ours
         7 |              |      3300 |             | missing_theirs
         5 | ch_007       |      5000 |             | missing_theirs

Row 7 never got a reference, so only amount and date could match it.

Filter in a subquery or CTE before the join, not after. If you add WHERE o.posted_at >= ... after a full join, every row with no ledger side has a null there and is thrown away. That removes exactly the “missing on our side” rows you wanted. The Postgres docs warn about this: a restriction in WHERE is applied after the join. I ran that mistake on the sample data. Both ch_009 and du_001 vanished.

Look at open items, not at a date window. “All rows from 10 November on both sides” gives false breaks for any payment that sits on one side of a midnight. A row stays in the open list until it is matched.

5. Classify

Not every leftover is a problem. ch_007 was posted a moment ago, and the provider may simply not have it yet. Put each leftover in a break table with a state. A break is keyed by the ledger row, or by the provider line when we have no row, because a row with no reference has no provider_ref to key on:

CREATE TABLE recon_breaks (
  id               bigserial   PRIMARY KEY,
  item_key         text        NOT NULL,   -- 'l' + ledger id, else 'p' + provider line id
  ledger_id        bigint      REFERENCES transactions (id),
  provider_line_id bigint      REFERENCES provider_lines (id),
  provider_ref     text,                   -- NULL for a row that never got a reference
  shape            text        NOT NULL,   -- missing_theirs | missing_ours | amount_diff
  status           text        NOT NULL DEFAULT 'open',   -- waiting | open | resolved
  currency         char(3)     NOT NULL,
  diff_minor       bigint      NOT NULL,   -- their amount minus ours: what to add to the ledger
  item_at          timestamptz NOT NULL,   -- when the money moved, not when we found the break
  resolved_by      bigint      REFERENCES transactions (id),
  resolved_at      timestamptz,
  note             text
);

CREATE UNIQUE INDEX recon_breaks_live ON recon_breaks (item_key)
  WHERE status <> 'resolved';

-- close breaks that matching has cleared since the last run
UPDATE recon_breaks b
SET status = 'resolved', resolved_at = now(), note = 'cleared by matching'
WHERE b.status <> 'resolved'
  AND NOT EXISTS (SELECT 1 FROM recon_diff d
                  WHERE d.item_key = b.item_key AND d.shape = b.shape);

INSERT INTO recon_breaks
  (item_key, ledger_id, provider_line_id, provider_ref, shape, status,
   currency, diff_minor, item_at)
SELECT item_key, ledger_id, provider_line_id, provider_ref, shape,
       CASE WHEN shape <> 'amount_diff' AND item_at > now() - interval '3 days'
            THEN 'waiting' ELSE 'open' END,
       currency, coalesce(their_minor, 0) - coalesce(our_minor, 0), item_at
FROM recon_diff
ON CONFLICT (item_key) WHERE status <> 'resolved'
DO UPDATE SET status = EXCLUDED.status, diff_minor = EXCLUDED.diff_minor;

You can run this every day. The partial unique index plus ON CONFLICT means a break is created once and then updated. A waiting row becomes open by itself when it gets old enough, and closes when the line arrives and matches. An amount that differs is never waiting, because time does not fix it.

The 3 days is a placeholder. Use the provider’s documented settlement time plus some slack, counted in business days. Stripe lists 2 business days for the US as the starting point.

6. Queue and fix

A person finds the cause of each open row and fixes it with a new transaction. Here the provider charged 41.00 and our row says 40.00:

BEGIN;

WITH adj AS (
  INSERT INTO transactions (idempotency_key, description, entry_count)
  VALUES ('recon-ch_003-adjust', 'ch_003: provider charged 41.00, we booked 40.00', 2)
  RETURNING id
), legs AS (
  INSERT INTO entries (transaction_id, account_id, currency, amount_minor)
  SELECT adj.id, v.account_id, 'EUR', v.amount_minor
  FROM adj, (VALUES (1, -100), (2, 100)) AS v(account_id, amount_minor)
), ref AS (
  INSERT INTO provider_refs (transaction_id, provider_ref, kind)
  SELECT id, 'ch_003', 'adjustment' FROM adj
)
UPDATE recon_breaks b
SET status = 'resolved', resolved_by = adj.id, resolved_at = now(),
    note = 'provider charged 41.00, our row says 40.00'
FROM adj
WHERE b.provider_ref = 'ch_003' AND b.shape = 'amount_diff' AND b.status <> 'resolved';

INSERT INTO recon_matches (ledger_id, provider_line_id, rule)
SELECT l.id, p.id, 'adjusted'
FROM ledger_items l
JOIN provider_lines p ON p.provider_ref = l.provider_ref AND p.kind = l.kind
WHERE l.provider_ref = 'ch_003' AND l.kind = 'charge';

COMMIT;

The adjustment is a balanced pair of entries, as in part 2. The old rows stay as they were, and the break points at the new transaction. Editing ledger rows would delete the evidence of the period you already reported. Late or corrected lines go into the next open period. Keep the report you already sent.

The last INSERT matters. Without it, the next daily run finds ch_003 again, because the original ledger row is still unmatched.

Payouts: match the group, not the line

Your bank never sees the 4 lines. It sees one deposit.

Three charges of 100.00, 25.00 and 41.00 and a refund of 10.00, less fees of 5.72, make one payout of 150.28 and one bank deposit of 150.28.

Stripe’s docs say an automatic payout “can include funds from multiple transactions”, and each report row carries an automatic_payout_id. So two more checks work on the group. First, do the lines in a payout add up to the payout?

CREATE TABLE provider_payouts (
  payout_ref   text    PRIMARY KEY,
  amount_minor bigint  NOT NULL,
  currency     char(3) NOT NULL,
  arrives_on   date    NOT NULL
);

SELECT po.payout_ref, po.amount_minor AS payout_amount,
       sum(p.net_minor) AS lines_net, count(*) AS lines,
       po.amount_minor - sum(p.net_minor) AS difference
FROM provider_payouts po
JOIN provider_lines p ON p.payout_ref = po.payout_ref
GROUP BY po.payout_ref, po.amount_minor;
 payout_ref | payout_amount | lines_net | lines | difference
------------+---------------+-----------+-------+------------
 po_001     |         15028 |     15028 |     4 |          0

Second, is there one bank line for the payout? Match on amount, currency and a short window after the arrival date. Stripe documents a payout_reference_token column that “displays on the beneficiary’s bank statement”, which helps when your bank shows it.

CREATE TABLE bank_lines (
  id           bigserial PRIMARY KEY,
  amount_minor bigint    NOT NULL,
  currency     char(3)   NOT NULL,
  booked_on    date      NOT NULL,
  narrative    text
);

SELECT po.payout_ref, po.amount_minor, b.id AS bank_line, b.booked_on
FROM provider_payouts po
LEFT JOIN bank_lines b
  ON b.amount_minor = po.amount_minor AND b.currency = po.currency
 AND b.booked_on BETWEEN po.arrives_on - 1 AND po.arrives_on + 3;

A NULL in bank_line means a payout that was announced and has not landed.

Group lines by automatic_payout_id, not by report dates: the report groups a payout by when it affects the Stripe balance, not by when it reaches your bank. For manual and instant payouts Stripe says it “can’t identify which transactions are included”, so that grouping is yours to build.

The kinds of breaks

These are the usual kinds of break. Netted payouts and duplicates are covered above, in the payout checks and the unique key in step 0.

Six kinds of break: timing, netted payout, FX, partial refund or chargeback, duplicate, and provider wrong or late.

Timing

Charge ch_004 is posted at 23:59:30 on Nov 10 in our ledger and 00:00:01 on Nov 11 in the report. Daily totals differ on both days. Matching on the reference finds no break.

Daily totals show two breaks for one payment, and they cancel out a day later. Matching on the reference shows none, which is the main reason to match lines and not totals.

FX differences

When a payment is converted, there are two amounts and a rate. Stripe’s balance transaction has an exchange_rate field, and the amounts are in the smallest unit of each currency. Never convert one side to compare. Store both amounts and the rate, and compare each in its own currency.

Later events can convert at a different rate. Stripe’s dispute docs give an example: a 100 EUR purchase that was 113.74 USD for the customer, disputed months later, has the chargeback debited as 107.86 EUR, not 100, because the rate moved. The difference is a real cost. Book it as an FX entry, not as a rounding error.

Partial refunds and disputes

A refund is a line with its own id (re_...), not a change to the charge. Two partial refunds are two lines. Match each by its own reference and sign.

A dispute is slower. Stripe debits the disputed amount plus a dispute fee, and the docs say the whole process can take 2 to 3 months. Give that item its own note or status, so you can tell it from a break nobody has looked at. Providers can also hold back part of a payout as a reserve. It shows up as a separate line that you must match too.

The provider’s report is wrong or late

Stripe notes that report data has its own processing schedule, so a payout can reach your bank before its lines are ready. That is not an import failure.

Reports can also change. ON CONFLICT DO NOTHING is right for a file you import twice. It is wrong for a provider that corrects a line, because the new amount is thrown away. Keep both raw rows and ask for the lines that changed:

SELECT raw->>'source_id' AS ref, raw->>'reporting_category' AS kind
FROM provider_report_raw
GROUP BY 1, 2
HAVING count(DISTINCT (raw->>'gross', raw->>'fee', raw->>'net', raw->>'currency')) > 1;

I ran this on a second report where one amount changed. It returned only that line.

The bank can be wrong too. In the textbook’s example the bank error only adjusts the bank side, so there is no journal entry. A break can end with “nothing to book”, so the queue needs a way to close it with a note and no entry.

Tolerances

Some teams allow “a few cents” of difference so the queue stays short. That is a trap as a blanket rule: a fee rate set wrong by a cent per payment passes every time. A tolerance needs a named cause and a hard cap.

Case Rule
Our amount against their gross, same currency Exact. These are integers, so there is nothing to round
Fees Exact. You book them from the report, so they match by construction
Converted payout total, rounded per line by one side and on the total by the other A few minor units can differ. Cap it per payout in minor units, never as a percentage
Timing Not a tolerance. It is a wait with an age limit

A percentage cap hides the most money on your largest payments. An allowed difference still gets written down. Match it with the rule name tolerance, book the difference to a rounding account with an adjusting entry, and count how much goes there each day. A rounding account that grows every week is a bug with a name.

What to measure

Run the reconciliation every day, right after the report import. Then read four numbers per currency from the break table:

Number What it tells you
Open count How big the queue is, and whether it grows
Age buckets Whether the queue is fresh noise or old problems
Oldest open item The one that is about to be forgotten
Total unmatched value How much money is in doubt
SELECT currency,
       count(*) FILTER (WHERE now() - item_at <  interval '1 day')  AS under_1d,
       count(*) FILTER (WHERE now() - item_at >= interval '1 day'
                          AND now() - item_at <  interval '3 days') AS d1_to_3,
       count(*) FILTER (WHERE now() - item_at >= interval '3 days'
                          AND now() - item_at <  interval '7 days') AS d3_to_7,
       count(*) FILTER (WHERE now() - item_at >= interval '7 days') AS over_7d,
       min(item_at)::date    AS oldest,
       sum(abs(diff_minor))  AS gross_unmatched_minor,
       sum(diff_minor)       AS net_unmatched_minor
FROM recon_breaks
WHERE status <> 'resolved'
GROUP BY currency;
 currency | under_1d | d1_to_3 | d3_to_7 | over_7d |   oldest   | gross_unmatched_minor | net_unmatched_minor
----------+----------+---------+---------+---------+------------+-----------------------+---------------------
 EUR      |        1 |       0 |       2 |       3 | 2026-11-10 |                 17300 |              -15300

Group by currency, as in part 1. Keep the gross and the net: the net can be zero while two big breaks cancel each other.

Alert on two things, and set the limits yourself:

  • The oldest open item is older than your own limit, in days.
  • No report has arrived in the last day: SELECT max(imported_at) FROM provider_report_raw.

The second one matters most. When an import fails, every ledger row becomes “missing on their side”. Alert on the missing file, not only on the breaks.

Questions people ask

What is the difference between payment reconciliation and bank reconciliation? Bank reconciliation compares your books with the bank statement. Payment reconciliation adds the provider in the middle, so you match ledger lines to the provider’s lines, and then the provider’s payout to the bank deposit.

How often should I run it? Run the external check once a day, after the provider’s report arrives. Stripe’s reports are daily, so running it more often adds nothing there.

What if the provider gives no reference I can store? Send your own id as metadata or a reference field, if there is one, so it comes back in the report. Without one you only have amount, currency and date, and you will do more manual work.

Should reconciliation write to the ledger? Only through adjusting entries, and only after a person or a reviewed rule agrees. Keep the reconciliation tables separate. They hold opinions about the ledger, not money.

Cheat sheet

Cheat sheet: store the provider reference, import raw, normalize to minor units and UTC, match on reference first, full outer join over unmatched rows, match payouts as groups, fix with adjusting entries, exact tolerances, watch age and value.

Further reading

Written by Rafi Loom

Backend engineer who builds high-volume systems that move money. More about Rafi