Money · PostgreSQL

Double-Entry Ledger in Postgres: Enforce the Rules in the Database

A balance column tells you where you ended up. A ledger tells you how you got there, and the database can check the sums.

The first version of a wallet is one column.

UPDATE accounts SET balance_minor = balance_minor - 800 WHERE id = 2;

That statement is fine. The trouble starts later, when someone asks why a merchant has 12.40 and not 12.70. The column holds the result of every change and the memory of none.

A ledger keeps the changes instead. Every movement of money is a row that never changes, and a balance is the sum of the rows. Postgres can check those sums for you.

Short version:

  • Every transaction is two or more entries that add up to zero in each currency. A deferred constraint trigger checks that at COMMIT, so a buggy caller cannot save an unbalanced transaction.
  • Entries are never updated or deleted. A mistake is fixed with a new transaction that reverses the old one.
  • Lock the account rows in id order before you check a balance. Do not lock accounts that every transaction touches, such as the fee account, or they become a queue.

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

Why one balance column is not enough

Left: one balance column showing 1240 with no explanation. Right: the entries behind it, +970, +1070 and -800, which add up to 1240.

A wrong number in one column can only be overwritten, and the old value is gone. With entries you add them up and compare, and a fix is a new row.

Double entry as signed rows

Double-entry bookkeeping has one rule: every transaction has at least two sides, and the sides cancel out (history). In a database that becomes:

  • A transaction is a group of entries.
  • An entry is a signed amount on one account: plus raises its balance, minus lowers it.
  • For each transaction, and for each currency, the entries add up to zero.

Amounts are whole numbers in minor units (cents), as in part 1. Example: a customer pays 10.00 by card. The merchant gets 9.70 and we keep a 0.30 fee.

A card payment of 10.00 as three entries that sum to 0, and the refund as the same entries with the signs flipped.

The money comes from somewhere, so there is an account for the outside world, card_network. Its balance goes negative as money comes in, which is fine. A useful side effect: add up every entry in the database and you get zero for each currency, always. The refund is a second transaction with the signs flipped. Nothing is edited.

In accounting books each entry is a debit or a credit, and which one raises a balance depends on the account type (Modern Treasury’s primer explains it). A signed number does the same job, and if your accountants want debit and credit columns, derive them from the sign and the account type in a report.

The schema

CREATE TABLE accounts (
  id            bigint  GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name          text    NOT NULL,
  currency      char(3) NOT NULL,
  kind          text    NOT NULL CHECK (kind IN ('user', 'house', 'external')),
  balance_minor bigint  DEFAULT 0,   -- cached sum of entries; NULL means "not cached"
  UNIQUE (id, currency),
  CONSTRAINT user_has_balance CHECK (kind <> 'user' OR balance_minor IS NOT NULL),
  CONSTRAINT no_overdraft     CHECK (kind <> 'user' OR balance_minor >= 0)
);

CREATE TABLE transactions (
  id              bigint      GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  idempotency_key text        NOT NULL UNIQUE,
  description     text        NOT NULL,
  entry_count     int         NOT NULL CHECK (entry_count >= 2),
  reverses        bigint      UNIQUE REFERENCES transactions (id),
  created_at      timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE entries (
  id             bigint  GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  transaction_id bigint  NOT NULL REFERENCES transactions (id),
  account_id     bigint  NOT NULL,
  currency       char(3) NOT NULL,
  amount_minor   bigint  NOT NULL CHECK (amount_minor <> 0),
  FOREIGN KEY (account_id, currency) REFERENCES accounts (id, currency)
);

CREATE INDEX entries_transaction_idx ON entries (transaction_id);
CREATE INDEX entries_account_idx     ON entries (account_id, id);
Three tables: accounts, transactions and entries. Entries point to transactions by transaction_id and to accounts by account_id and currency together.

Three accounts for the examples:

INSERT INTO accounts (name, currency, kind) VALUES
  ('card_network', 'EUR', 'external'),  -- id 1
  ('merchant_42',  'EUR', 'user'),      -- id 2
  ('fees',         'EUR', 'house');     -- id 3

Why each column is there:

  • kind says who the account belongs to. user accounts hold customer money and must never go below zero. house accounts are ours, such as fees. external accounts stand for the outside world, such as a card network.
  • The entry carries currency and a foreign key on (account_id, currency), so an entry in USD cannot land on a EUR account.
  • amount_minor <> 0 rejects empty entries.
  • entry_count is how many entries the transaction says it has. The idempotency section shows why it is there.
  • reverses points at the transaction a refund undoes. It is UNIQUE, so a transaction can be reversed once.
  • balance_minor is a cache. The entries are the truth.
  • GENERATED ALWAYS AS IDENTITY ids can have gaps, because a rolled-back transaction still uses a number. Gaps are not missing money.
  • Part 3 adds the provider’s reference for each transaction, in its own insert-only table.

Make the database enforce the rules

Rules that live only in application code last until a second code path writes to the ledger. I would rather have Postgres say no.

Rule 1: every transaction balances

The check cannot run on each insert, because after the first entry of a payment the transaction is out of balance for a moment. So it runs at COMMIT. A constraint trigger with DEFERRABLE INITIALLY DEFERRED does that: Postgres queues the call and fires it when the transaction ends.

CREATE FUNCTION assert_transaction_ok(tx_id bigint) RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
  expected int;
  actual   int;
  off      record;
BEGIN
  SELECT entry_count INTO expected FROM transactions WHERE id = tx_id;
  SELECT count(*) INTO actual FROM entries WHERE transaction_id = tx_id;

  IF actual <> expected THEN
    RAISE EXCEPTION 'transaction % has % entries, expected %',
      tx_id, actual, expected
      USING ERRCODE = 'check_violation';
  END IF;

  SELECT currency, sum(amount_minor) AS total INTO off
  FROM entries
  WHERE transaction_id = tx_id
  GROUP BY currency
  HAVING sum(amount_minor) <> 0
  ORDER BY currency
  LIMIT 1;

  IF FOUND THEN
    RAISE EXCEPTION 'transaction % does not balance: % is off by %',
      tx_id, off.currency, off.total
      USING ERRCODE = 'check_violation';
  END IF;
END $$;

CREATE FUNCTION check_transaction() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  CASE TG_TABLE_NAME
    WHEN 'entries'      THEN PERFORM assert_transaction_ok(NEW.transaction_id);
    WHEN 'transactions' THEN PERFORM assert_transaction_ok(NEW.id);
  END CASE;

  RETURN NULL;
END $$;

CREATE CONSTRAINT TRIGGER entries_balance
  AFTER INSERT ON entries
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW EXECUTE FUNCTION check_transaction();

CREATE CONSTRAINT TRIGGER transactions_balance
  AFTER INSERT ON transactions
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW EXECUTE FUNCTION check_transaction();

Two triggers, because there are two ways to get it wrong. The one on entries catches wrong sums. The one on transactions catches a transaction saved with no entries at all, because then no entry row ever fires a trigger. A constraint trigger has to be AFTER ... FOR EACH ROW, so the check runs once per entry and reads the same rows each time. The entries_transaction_idx index keeps that cheap.

The sum is grouped by currency, so a EUR surplus cannot hide behind a USD deficit, and ORDER BY currency makes the error name the same currency every time. Try to save an unbalanced payment:

BEGIN;
INSERT INTO transactions (idempotency_key, description, entry_count)
VALUES ('bad-1', 'unbalanced', 2);

INSERT INTO entries (transaction_id, account_id, currency, amount_minor)
SELECT id, v.account_id, 'EUR', v.amount_minor
FROM transactions, (VALUES (1, -1000), (2, 900)) AS v(account_id, amount_minor)
WHERE idempotency_key = 'bad-1';
-- INSERT 0 2: the inserts are accepted

COMMIT;
-- ERROR:  transaction 1 does not balance: EUR is off by -100

The inserts go through. The COMMIT fails and nothing is saved. A ledger that cannot refuse an unbalanced transaction is a spreadsheet.

Rule 2: history is never edited

CREATE FUNCTION reject_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  RAISE EXCEPTION '% on % is not allowed: post a reversing transaction instead',
    TG_OP, TG_TABLE_NAME
    USING ERRCODE = 'restrict_violation';
END $$;

CREATE TRIGGER entries_immutable
  BEFORE UPDATE OR DELETE ON entries
  FOR EACH ROW EXECUTE FUNCTION reject_change();

CREATE TRIGGER entries_no_truncate
  BEFORE TRUNCATE ON entries
  FOR EACH STATEMENT EXECUTE FUNCTION reject_change();

Add the same two triggers on transactions. TRUNCATE needs its own statement-level trigger, because it does not fire the row triggers. The trigger stops a mistake. It does not stop a person with enough rights, who can disable a trigger. So also take the rights away from the role your application uses:

CREATE ROLE ledger_app LOGIN;
GRANT SELECT, INSERT ON transactions, entries TO ledger_app;
GRANT SELECT ON accounts TO ledger_app;
GRANT UPDATE (balance_minor) ON accounts TO ledger_app;

With this role, posting a payment works, and UPDATE entries, DELETE FROM transactions, TRUNCATE entries and UPDATE accounts SET kind = ... fail with permission denied. The application can change one column of accounts, the cached balance, and nothing else.

Post a transaction

One payment is six steps in one database transaction. This is what your code sends:

BEGIN;

-- 1. Record the decision first. No row back means we have seen this key.
INSERT INTO transactions (idempotency_key, description, entry_count)
VALUES ('pay-1001', 'card payment, order 1001', 3)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;

-- 2. Lock every cached account we will change, lowest id first.
SELECT id, kind, balance_minor FROM accounts
WHERE id IN (1, 2, 3) AND balance_minor IS NOT NULL
ORDER BY id
FOR NO KEY UPDATE;
-- 3. App code: for each 'user' row, if balance_minor + change < 0,
--    ROLLBACK and answer "insufficient funds".

-- 4. Insert the entries.
INSERT INTO entries (transaction_id, account_id, currency, amount_minor)
SELECT t.id, v.account_id, 'EUR', v.amount_minor
FROM transactions t,
     (VALUES (1, -1000), (2, 970), (3, 30)) AS v(account_id, amount_minor)
WHERE t.idempotency_key = 'pay-1001';

-- 5. Move the cached balances by the net change per account.
UPDATE accounts a
SET balance_minor = a.balance_minor + d.delta
FROM (
  SELECT e.account_id, sum(e.amount_minor) AS delta
  FROM entries e
  JOIN transactions t ON t.id = e.transaction_id
  WHERE t.idempotency_key = 'pay-1001'
  GROUP BY e.account_id
) d
WHERE a.id = d.account_id AND a.balance_minor IS NOT NULL;

-- 6. The deferred triggers run here. Any failure rolls everything back.
COMMIT;

The refund copies the original entries with the signs flipped. Only steps 1 and 4 change:

-- 1.
INSERT INTO transactions (idempotency_key, description, entry_count, reverses)
VALUES ('refund-1001', 'refund of order 1001', 3,
        (SELECT id FROM transactions WHERE idempotency_key = 'pay-1001'))
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;

-- 4.
INSERT INTO entries (transaction_id, account_id, currency, amount_minor)
SELECT t.id, e.account_id, e.currency, -e.amount_minor
FROM transactions t
JOIN entries e ON e.transaction_id = t.reverses
WHERE t.idempotency_key = 'refund-1001';

Steps 2, 3 and 5 are the same as for the payment.

Reversing can fail, and it should. Say the merchant already withdrew 8.00 of their 9.70. The payout is a transaction like any other:

INSERT INTO transactions (idempotency_key, description, entry_count)
VALUES ('payout-1', 'merchant payout', 2);

INSERT INTO entries (transaction_id, account_id, currency, amount_minor)
SELECT id, v.account_id, 'EUR', v.amount_minor
FROM transactions, (VALUES (2, -800), (1, 800)) AS v(account_id, amount_minor)
WHERE idempotency_key = 'payout-1';

Now the refund would take the merchant to -8.00. Its step 5 UPDATE stops with a no_overdraft violation and nothing is saved. The refund waits until the money is back, or you move it through a house account. Both are business decisions.

Balances: add them up, or cache them

There are two ways to read a balance. SUM(amount_minor) over the entries is always right but gets slower as entries pile up, and it cannot enforce “no overdraft” without a lock. A cached balance_minor is one row to read and takes a CHECK, but it is only right if every writer updates it, and every write takes a row lock.

My default is both. Cache the balance on accounts where you enforce a limit or read it often, such as customer accounts. Skip it on accounts that everything writes and few read. The entries are the truth, and this query should return no rows:

SELECT a.id, a.balance_minor AS cached, coalesce(sum(e.amount_minor), 0) AS from_entries
FROM accounts a
LEFT JOIN entries e ON e.account_id = a.id
WHERE a.balance_minor IS NOT NULL
GROUP BY a.id
HAVING a.balance_minor <> coalesce(sum(e.amount_minor), 0);

Set one balance wrong by hand and it lists exactly that account. Run it on a schedule and alert on any row. Part 3 builds on checks like it.

One trap with “balance as of a time”. created_at uses now(), which in Postgres is the time the transaction started, not the time it committed. A report as of 12:00 can miss a transaction that started at 11:59:59 and committed at 12:00:01. Store the time the money moved in its own column (for example effective_at), and close a period on that column after a safety margin.

Concurrency: the lost update

One thing a balance column gets right: balance_minor = balance_minor - x cannot lose an update. The race is in the step before it, “read the balance, decide, then write”. The merchant has 10.00. Two payouts of 8.00 arrive together. Each request reads the balance, sees enough, and writes.

Two requests both read a balance of 1000, both pass the check for 800, and both insert minus 800, leaving the merchant at minus 600.

With two psql sessions that each read the merchant’s entries, sleep a second, then insert, both saw enough_funds = t. The merchant ended at -600. Every rule from the last section passed, because each transaction was balanced.

The fix is the lock in step 2 of the posting flow. Change the read to:

SELECT balance_minor FROM accounts WHERE id = 2 FOR NO KEY UPDATE;

Session B now waits at that line until A commits. In READ COMMITTED, the default, a locking SELECT that waited returns the updated row (see the Read Committed section of the isolation docs). In my run B saw balance = 200, said no, and the ledger stayed at 200.

Three things about this lock:

  • FOR NO KEY UPDATE, not FOR UPDATE. Inserting an entry makes Postgres take FOR KEY SHARE on the account row, to check the foreign key, and FOR UPDATE blocks that. I ran it with each lock held on one account for two seconds and an entry inserted for it from another session. With FOR UPDATE the insert waited about 1.6 seconds. With FOR NO KEY UPDATE it took 0.07. The locks post lists which row locks conflict.
  • The CHECK is a backstop. If a code path forgets the lock but updates with balance_minor = balance_minor - 800 (not a value computed in the app), the second UPDATE waits, re-reads the row, and fails no_overdraft. You get an error instead of “insufficient funds”, but not a negative balance.
  • Serializable also works. With BEGIN ISOLATION LEVEL SERIALIZABLE on the same racy code, one session fails with could not serialize access due to read/write dependencies among transactions. The docs say to retry the whole transaction, and I prefer the lock because in the normal case there is nothing to retry.

Lock order

If request A locks account 2 and then 4, and request B locks 4 and then 2, both wait for each other.

Opposite lock order ends in a deadlock. Locking in id order makes B wait, and both succeed.

I ran the first case and got this about a second later:

ERROR:  deadlock detected
CONTEXT:  while locking tuple (0,4) in relation "accounts"

The docs call a consistent lock order the best defence. In the posting flow that is the ORDER BY id in step 2: one statement, one order, for every caller. With it, the same two sessions never failed. Keep a retry on error 40P01 as well, in case one code path breaks the rule. The locks post explains how deadlocks are detected.

The hot account problem

Every card payment has an entry for card_network and one for fees. With a cached balance on those accounts, every payment locks the same two rows, so payments to different merchants run one after another.

Six payments queue on one fees row, or spread over four fee sub-accounts.

I ran two payments for different merchants together, each holding its transaction open for one second. With cached balances on card_network and fees, both finished in 2.1 seconds. With no cache on those two, both finished in 1.1 seconds. The sleep is artificial: it makes a queue of a few milliseconds per payment visible. It is not a benchmark.

You have three options:

Option How Cost
Do not cache it UPDATE accounts SET balance_minor = NULL WHERE id IN (1, 3); Reading the balance needs a SUM. No lock: the entry insert only takes a shared key lock on the row
Split it fees_0 to fees_3, picked from a hash of the idempotency key, mod 4 Contention on fees drops by about 4. It helps only if card_network is also uncached or split, because every payment still locks it. The fee total is a sum over four accounts
Roll it up later Keep a snapshot of the balance, add the entries since Reads stay cheap, but the snapshot job needs care, see below

With the split, two payments using fees and fees_1 finished in 1.1 seconds, but only because card_network had no cached balance. With card_network cached it was still about 2.1 seconds, because both payments lock it.

Accounts that need an overdraft check belong to users, and a user account is rarely hot. The hot ones (fees, the card network, a bank) are ours and have no limit to enforce, so not caching is usually the right answer.

The roll-up has a trap. Do not snapshot “everything up to entry id N”. Ids come from a sequence, and the order of ids is not the order of commits: an entry can take id 100, commit after id 105, and so appear after a snapshot taken at 105. Snapshot by a point in time with a safety margin, or hold a lock while you do it.

Idempotency: the key lives on the transaction

A retried request must not post the money twice. The unique idempotency_key on transactions is the whole mechanism, used in step 1 of the posting flow. The idempotency keys post covers how a client chooses and sends the key. On the ledger side:

  • INSERT ... ON CONFLICT (idempotency_key) DO NOTHING RETURNING id returns a row for the first request and no row for a replay. No row means: stop, roll back, and answer with the stored result.
  • Two requests with the same key at the same time are fine. With two sessions on one key, the second INSERT waited on the unique index until the first one committed, then returned no row. One transaction, two entries.
  • The decision is recorded before the money moves, in the same database transaction as the entries, so the key never exists without them.

Now the odd column from the schema. Run the whole posting script twice, ignoring the “no row back” answer. Step 4 finds the old transaction by its key and adds three more entries to it. They still sum to zero, so a check on the sum alone passes. Without entry_count, the entries double and the cached balances triple: the merchant shows 2910 in the cache and 1940 in the entries. With it, the second COMMIT fails with transaction 2 has 6 entries, expected 3.

If a replay arrives with the same key but different amounts, answer with an error, not a quiet success. Compare the request with what you stored; the idempotency post shows how with a hash.

When it breaks

The rules above stop bad data and races. A few mistakes still get through.

What the database cannot check

A balanced ledger can still be wrong. The sums can be right and the accounts the wrong ones, or the fee 3% instead of 2.9%. Nothing in the schema checks that a reversal mirrors the original. The refund above copies it with a SELECT, and that is a convention. The ledger is also only a record of what you think happened. Whether the card network really paid you is the subject of part 3.

Questions people ask

Do I need double entry, or is a balance column enough? If money only changes in one place and you never have to explain a number, a column is enough. Add entries as soon as money moves between parties. Adding them later means inventing history for the money already there.

How do I handle several currencies and conversions? Each currency balances by itself, so a conversion has a house account in each currency. Converting EUR 10.00 at 1.0949 gives USD 10.949, which does not fit in cents. The user gets 10.94, and the entries balance per currency:

EUR  user_eur  -1000
EUR  fx_eur    +1000
USD  fx_usd    -1094
USD  user_usd  +1094

The 0.9 of a cent is not money anyone holds, so it cannot be an entry. Keep it in the conversion record from part 1. Whole-cent differences show up later, when your FX provider settles a batch of conversions at its own rounding. Book those to a house account such as fx_rounding, as their own transaction.

A transaction with only EUR minus 1000 and USD plus 1000 fails at COMMIT with EUR is off by -1000, because the two currencies do not cancel each other.

How do I show a pending payment? Post a pending payment as entries on a separate pending account, and move it to the real account with a second transaction when it settles. Nothing is edited, so the history shows both steps. The available balance is the posted balance minus the holds.

Should I build this or use an existing ledger? If the rules above are all you need, this is about a page of SQL and you own it. For something already built, pgledger is an open-source double-entry ledger for Postgres. Read its schema first: cached balances, the sign convention and locking are the choices that matter.

Cheat sheet

Double-entry ledger in Postgres cheat sheet. Rule: each transaction sums to zero per currency. Money: signed bigint minor units. Check at COMMIT: deferred constraint trigger. History: triggers reject UPDATE and DELETE, revoke the rights, fix with a reversal. Idempotency: unique key on transactions, ON CONFLICT DO NOTHING, entry_count. Balance: a cached column on user accounts, SUM for the rest. Locks: FOR NO KEY UPDATE, ORDER BY id. Hot accounts: no cache or split into sub-accounts. Check daily: cache against SUM of entries.

Further reading

Next in the seriesPayment Reconciliation in SQL: Match Your Ledger to the Bank
Written by Rafi Loom

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