Video in progress
How do you model money movement in a payment system, and why do you need reconciliation?
I don't update the balance as a single field: every movement is at least two immutable entries in a double-entry ledger, with debits and credits summing to zero. Reconciliation compares our ledger against the bank and provider reports and finds the differences.
📖 Answer
UPDATE accounts SET balance = balance - 100: with this approach, a year later you can't answer "why is the balance like this?". There's no history, and when a mistake is corrected it leaves no trace.
Double-entry:
CREATE TABLE ledger_entries (
id bigint PRIMARY KEY,
txn_id uuid NOT NULL,
account_id bigint NOT NULL,
amount numeric(19,4) NOT NULL, -- + credit, - debit
currency char(3) NOT NULL,
created_at timestamptz NOT NULL
);
-- SUM(amount) = 0 must hold for every txn_id
A customer pays 100: customer account −100, merchant account +97, fee account +3. Entries are never modified; if there's a mistake, you add a reversing transaction. The balance is the sum of the entries (or a materialized snapshot for fast reads).
For money use BigDecimal or a long in minor units, not double. The currency always sits next to the amount.
Why reconciliation: even if your system is correct, the outside world can be wrong. The provider accepted the payment but the callback never came; the bank charged twice; after a timeout the state is unclear. Every day (or hour) you take the provider's report and compare it with the ledger by external_id:
- we have it, they don't;
- they have it, we don't;
- the amount or status differs.
Each difference is either fixed automatically or lands in an operator queue. In practice a payments team spends a lot of its time on exactly these differences.
One more rule: payment states form a state machine (CREATED → PENDING → SUCCEEDED/FAILED), transitions are allowed only in permitted directions, and every transition is written to the audit log.
Sign up to mark studied questions and save your progress.