knaxuslearn · build · ship

Projects / Bank ledger / Phase 2

Phase 2 of 4 · about 2.5 hours

Transfers that never break the books

You end with a transfer() function that moves money, can be retried safely, and a ledger that always adds up to zero.

Step 2.1: Every transfer must add up to zero (about 35 minutes)

Today nothing stops an entry that takes $5 from Asha and gives Ben only $3. We want the database to refuse that. A normal CHECK only sees one row, so we use a constraint trigger: a function that runs when rows are inserted. Ours is deferred, which means it waits until the end of the transaction. That lets us insert both entries of a transfer first, and then checks the pair.

CREATE FUNCTION check_transfer_balanced() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF (SELECT sum(amount_cents) FROM entries WHERE transfer_id = NEW.transfer_id) <> 0 THEN
    RAISE EXCEPTION 'transfer % does not sum to zero', NEW.transfer_id;
  END IF;
  RETURN NULL;
END;
$$;

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

NEW is the row that was just inserted. Now try to cheat:

BEGIN;
INSERT INTO transfers (idempotency_key) VALUES ('lopsided') RETURNING id \gset
INSERT INTO entries (transfer_id, account_id, amount_cents) VALUES (:id, 2, -500);
INSERT INTO entries (transfer_id, account_id, amount_cents) VALUES (:id, 3,  300);
COMMIT;

SELECT count(*) AS lopsided_rows FROM transfers WHERE idempotency_key = 'lopsided';

The COMMIT fails, and the whole transaction is rolled back:

ERROR:  transfer 3 does not sum to zero
CONTEXT:  PL/pgSQL function check_transfer_balanced() line 4 at RAISE
 lopsided_rows
---------------
             0
(1 row)

Nothing from the lopsided transfer survived. Your transfer number may differ.

Step 2.2: History cannot be rewritten (about 25 minutes)

A ledger is append-only: you add new entries to fix mistakes, and you never edit old ones. Make the database enforce it:

CREATE FUNCTION forbid_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  RAISE EXCEPTION '% on % is not allowed: the ledger is append-only', TG_OP, TG_TABLE_NAME;
END;
$$;

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

CREATE TRIGGER transfers_append_only
  BEFORE UPDATE OR DELETE ON transfers
  FOR EACH ROW EXECUTE FUNCTION forbid_change();

We will try it out at the end of the phase, once there are entries to protect.

Step 2.3: The transfer function (about 45 minutes)

Now one function to do the whole job. It does four things:

  1. Reject silly input (a zero amount, or paying yourself).
  2. Record the transfer. If the idempotency key was already used, return the earlier transfer and move nothing.
  3. Call assert_funds, a hook for money rules that is empty for now and gets its real body in Phase 4.
  4. Write the two entries.
CREATE FUNCTION assert_funds(p_from bigint, p_to bigint, p_amount bigint) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
  RETURN;
END;
$$;

CREATE FUNCTION transfer(
  p_key    text,
  p_from   bigint,
  p_to     bigint,
  p_amount bigint,
  p_memo   text DEFAULT NULL
) RETURNS bigint
LANGUAGE plpgsql AS $$
DECLARE
  v_id bigint;
BEGIN
  IF p_amount <= 0 THEN
    RAISE EXCEPTION 'amount must be positive, got %', p_amount;
  END IF;
  IF p_from = p_to THEN
    RAISE EXCEPTION 'cannot transfer to the same account';
  END IF;

  INSERT INTO transfers (idempotency_key, memo)
  VALUES (p_key, p_memo)
  ON CONFLICT (idempotency_key) DO NOTHING
  RETURNING id INTO v_id;

  IF v_id IS NULL THEN
    -- Same key as an earlier call: report that transfer and move nothing.
    SELECT id INTO v_id FROM transfers WHERE idempotency_key = p_key;
    RETURN v_id;
  END IF;

  PERFORM assert_funds(p_from, p_to, p_amount);

  INSERT INTO entries (transfer_id, account_id, amount_cents)
  VALUES (v_id, p_from, -p_amount),
         (v_id, p_to,    p_amount);

  RETURN v_id;
END;
$$;

ON CONFLICT ... DO NOTHING is the key line. If the key already exists, the insert quietly does nothing and v_id stays empty, which is how we know it is a retry.

Step 2.4: A balances view (about 20 minutes)

We never store a balance. A balance is just the sum of an account's entries, so it cannot drift out of step with them. A view is a saved query that looks like a table:

CREATE VIEW account_balances AS
SELECT a.id, a.owner, COALESCE(sum(e.amount_cents), 0) AS balance_cents
FROM accounts a
LEFT JOIN entries e ON e.account_id = a.id
GROUP BY a.id, a.owner;

Step 2.5: Use it (about 25 minutes)

Fund Asha with $100.00 from the bank. Then Asha pays Ben $25.00, and the app retries the very same request:

SELECT transfer('fund-asha', 1, 2, 10000, 'opening deposit');
SELECT transfer('pay-001', 2, 3, 2500, 'lunch');
SELECT transfer('pay-001', 2, 3, 2500, 'lunch');
SELECT * FROM account_balances ORDER BY id;
SELECT sum(amount_cents) AS ledger_total FROM entries;

The retry returns the same transfer number, and Ben was paid once:

 transfer
----------
        4
 transfer
----------
        5
 transfer
----------
        5

 id |         owner         | balance_cents
----+-----------------------+---------------
  1 | Bank (funding source) |        -10000
  2 | Asha                  |          7500
  3 | Ben                   |          2500

 ledger_total
--------------
            0

The bank is at minus $100 because it handed out $100. The three balances add up to zero, and so does the whole ledger. Now try to rewrite history:

UPDATE entries SET amount_cents = 1 WHERE id = (SELECT min(id) FROM entries);
DELETE FROM entries WHERE id = (SELECT min(id) FROM entries);
ERROR:  UPDATE on entries is not allowed: the ledger is append-only
ERROR:  DELETE on entries is not allowed: the ledger is append-only

Phase 2 done

You can move money, retry safely, and the ledger always adds up to zero. The books can only grow, never be edited.