knaxuslearn · build · ship

Projects / Bank ledger / Phase 4

Phase 4 of 4 · about 2.5 hours

Make it survive a crowd

You end with twenty transfers fired at the same moment against an account that can only afford ten, and exactly ten go through.

Everything so far ran one statement at a time. Real systems do not. Let's add a rule and then break it with two people at once.

Step 4.1: Refuse to overdraw (about 20 minutes)

Fill in the empty assert_funds hook. It checks the payer's balance and refuses if there is not enough, unless the account is allowed to go negative:

CREATE OR REPLACE FUNCTION assert_funds(p_from bigint, p_to bigint, p_amount bigint)
RETURNS void LANGUAGE plpgsql AS $$
BEGIN
  IF NOT (SELECT allow_negative FROM accounts WHERE id = p_from)
     AND (SELECT COALESCE(sum(amount_cents), 0) FROM entries WHERE account_id = p_from) < p_amount
  THEN
    RAISE EXCEPTION 'insufficient funds in account %', p_from;
  END IF;
END;
$$;

Make a new customer, Dana, give her $100.00 and try to take $200.00:

INSERT INTO accounts (owner, currency) VALUES ('Dana', 'USD');
SELECT transfer('fund-dana', 1, (SELECT id FROM accounts WHERE owner = 'Dana'), 10000, 'opening deposit');
SELECT transfer('too-much', (SELECT id FROM accounts WHERE owner = 'Dana'),
                            (SELECT id FROM accounts WHERE owner = 'Ben'), 20000);
ERROR:  insufficient funds in account 1006

It works, one transfer at a time.

Step 4.2: Break it with two people (about 35 minutes)

Now two people each try to spend $80.00 of Dana's $100.00 at the same moment. You need two terminals. In each, export the three PG... variables from the start of this project. Save these two files:

-- race_a.sql
BEGIN;
SELECT transfer('race-a', (SELECT id FROM accounts WHERE owner = 'Dana'),
                          (SELECT id FROM accounts WHERE owner = 'Ben'), 8000);
SELECT pg_sleep(3);
COMMIT;

race_b.sql is identical, except the key is 'race-b'. The pg_sleep(3) holds the transaction open for three seconds, which makes the overlap easy to hit. Run psql ledger -f race_a.sql in terminal A, wait one second, and run psql ledger -f race_b.sql in terminal B. Then look at Dana:

SELECT owner, balance_cents FROM account_balances WHERE owner = 'Dana';
 owner | balance_cents
-------+---------------
 Dana  |         -6000

Dana spent $160 and had $100. Both transfers checked her balance before either had committed, and both saw $100.00. This is a race condition: the check and the write were two separate steps, and another transaction slipped in between. The check is correct. The timing is the bug. And no test that runs one thing at a time would ever have caught it.

Step 4.3: Fix it with a row lock (about 20 minutes)

We need the second transaction to wait for the first. A row lock does that. SELECT ... FOR UPDATE locks the row until the transaction ends, and anyone else who asks for the same row has to queue. We lock the payer's account row before reading the balance:

CREATE OR REPLACE FUNCTION assert_funds(p_from bigint, p_to bigint, p_amount bigint)
RETURNS void LANGUAGE plpgsql AS $$
BEGIN
  PERFORM 1 FROM accounts WHERE id = p_from FOR UPDATE;

  IF NOT (SELECT allow_negative FROM accounts WHERE id = p_from)
     AND (SELECT COALESCE(sum(amount_cents), 0) FROM entries WHERE account_id = p_from) < p_amount
  THEN
    RAISE EXCEPTION 'insufficient funds in account %', p_from;
  END IF;
END;
$$;

Make a fresh account, Gus, with $100.00, and repeat the two-terminal race with Gus in place of Dana (use 'gus-a' and 'gus-b' as keys). The second terminal now waits about two seconds and then fails:

ERROR:  insufficient funds in account 1007
SELECT owner, balance_cents FROM account_balances WHERE owner = 'Gus';
 owner | balance_cents
-------+---------------
 Gus   |          2000

One transfer won and one was refused. After the first transaction committed, the second one read the balance again and saw the truth.

Step 4.4: Find the next bug, a deadlock (about 35 minutes)

One lock fixed one bug. Two locks can cause another. Suppose Eli pays Fay at the same moment Fay pays Eli. Each transaction locks its own payer first and then needs the other person's row. Each ends up waiting for the other. That is a deadlock, and PostgreSQL resolves it by cancelling one of them.

Set up two accounts, then save a small script that fires one-dollar transfers in alternating directions:

INSERT INTO accounts (owner, currency) VALUES ('Eli', 'USD'), ('Fay', 'USD');
SELECT transfer('fund-eli', 1, (SELECT id FROM accounts WHERE owner = 'Eli'), 10000);
SELECT transfer('fund-fay', 1, (SELECT id FROM accounts WHERE owner = 'Fay'), 10000);
#!/bin/bash
# swap.sh: ./swap.sh N   (even N: Eli pays Fay, odd N: Fay pays Eli, $1.00 each)
if [ $(($1 % 2)) -eq 0 ]; then FROM=Eli; TO=Fay; else FROM=Fay; TO=Eli; fi
psql ledger -q -t -A \
  -c "SELECT transfer('swap-$1', (SELECT id FROM accounts WHERE owner = '$FROM'), (SELECT id FROM accounts WHERE owner = '$TO'), 100)" \
  >/dev/null 2>>swap.err && echo ok || echo failed

Make it executable with chmod +x swap.sh, then fire 40 of them at once:

: > swap.err
seq 1 40 | xargs -P 40 -I{} ./swap.sh {} | sort | uniq -c
grep -c deadlock swap.err
      7 failed
     33 ok
7

Every one of these transfers was valid. Some were cancelled anyway. Your count will differ from run to run, but it should not be zero. grep shows the message deadlock detected.

Step 4.5: Lock in a fixed order (about 25 minutes)

The standard cure is a rule: everyone takes locks in the same order. If every transaction locks the lower account id first, nobody can end up holding the second lock while waiting for the first. Lock both accounts, lowest id first:

CREATE OR REPLACE FUNCTION assert_funds(p_from bigint, p_to bigint, p_amount bigint)
RETURNS void LANGUAGE plpgsql AS $$
BEGIN
  -- Lock both accounts, lowest id first, so racing transfers queue up instead of deadlocking.
  PERFORM 1 FROM accounts WHERE id IN (p_from, p_to) ORDER BY id FOR UPDATE;

  IF NOT (SELECT allow_negative FROM accounts WHERE id = p_from)
     AND (SELECT COALESCE(sum(amount_cents), 0) FROM entries WHERE account_id = p_from) < p_amount
  THEN
    RAISE EXCEPTION 'insufficient funds in account %', p_from;
  END IF;
END;
$$;

Run the same 40 swaps again (change the keys in swap.sh from swap- to swapb- first, or the idempotency keys will recognise them as retries):

: > swap.err
seq 1 40 | xargs -P 40 -I{} ./swap.sh {} | sort | uniq -c
grep -c deadlock swap.err
     40 ok
0

All 40 succeed. They queue up instead of colliding.

Step 4.6: The final test (about 15 minutes)

Make Hal with $100.00. Then twenty people try to take $10.00 each from Hal's account, all at once. He can only afford ten:

INSERT INTO accounts (owner, currency) VALUES ('Hal', 'USD');
SELECT transfer('fund-hal', 1, (SELECT id FROM accounts WHERE owner = 'Hal'), 10000);
#!/bin/bash
# burst.sh: ./burst.sh N   (one transfer of $10.00 from Hal to Ben)
psql ledger -q -t -A \
  -c "SELECT transfer('burst-$1', (SELECT id FROM accounts WHERE owner = 'Hal'), (SELECT id FROM accounts WHERE owner = 'Ben'), 1000)" \
  >/dev/null 2>&1 && echo ok || echo refused
chmod +x burst.sh
seq 1 20 | xargs -P 20 -I{} ./burst.sh {} | sort | uniq -c
     10 ok
     10 refused
SELECT owner, balance_cents FROM account_balances WHERE owner = 'Hal';
SELECT sum(amount_cents) AS ledger_total FROM entries;
 owner | balance_cents
-------+---------------
 Hal   |             0

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

Exactly ten went through, Hal is at zero and never below, and the whole ledger still adds up to zero.

Phase 4 done

Twenty people at once, and the books stayed right. You have just built, in about 10 hours, the core of what every payments system has to get right.