Capstone - A Banking Ledger

Article · 5:00

Double-entry invariants, concurrent transfers and point-in-time recovery, assessed on evidence rather than on the code alone.

The system. A banking ledger supporting accounts in multiple currencies, transfers between them, and statements for a period. It must satisfy three invariants at all times:

  1. Every transfer's entries sum to zero. Money is conserved.
  2. No account's derived balance disagrees with its recorded balance.
  3. No account goes below its permitted minimum, under any interleaving of concurrent requests.

What is assessed. The curriculum's weighting is 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical and 30% capstone. The capstone is marked on three things, and the code is only part of the first.

Correctness under concurrency. Not that the happy path works - that the invariants survive a hostile concurrent workload. Your test must include opposite-direction transfers between the same pair of accounts, which is the case that produces deadlocks and lost updates.

Measured performance against a declared baseline. Declare the baseline first, in writing, then measure against it. "Transfers complete in p99 under 50 ms at 200 concurrent clients on this instance size" is a claim that can be checked. "It is fast" is not.

A defensible account of failure modes. What happens when the primary dies mid-transfer? When the disk fills? When a replica falls behind? When somebody runs the wrong UPDATE? For each: what the system does, what the customer sees, and what the operator does about it.

The deliverables, in full: architecture diagram; data model with the reasoning for the model you chose over the one you rejected; source code; a reproducible test dataset; a benchmark report with p50, p95 and p99 against the declared baseline; a security review covering roles, RLS, TLS and the denials you tested; a recovery runbook with measured RPO and RTO; and a short design defence.

The design defence is where most marks are lost. It is not a summary of what you built. It is an argument for why these choices are right for these requirements, including the trade you made that you are least comfortable with. A capstone with no acknowledged trade-off has not been examined by its author.

-- ================= The three invariants, as runnable assertions =====
-- Put these in CI. An invariant you cannot check on demand is an
-- invariant you are hoping for.

-- 1. Every transfer balances.
SELECT transfer_id, sum(amount_minor) AS imbalance
FROM ledger.entry
GROUP BY transfer_id
HAVING sum(amount_minor) <> 0;
-- Expected: zero rows.

-- 2. Recorded balances agree with derived balances.
SELECT a.id, a.balance_minor AS recorded,
       coalesce(sum(e.amount_minor), 0) AS derived
FROM ledger.account a
LEFT JOIN ledger.entry e ON e.account_id = a.id
GROUP BY a.id, a.balance_minor
HAVING a.balance_minor <> coalesce(sum(e.amount_minor), 0);
-- Expected: zero rows.

-- 3. No account below its minimum.
SELECT id, balance_minor FROM ledger.account WHERE balance_minor < 0;
-- Expected: zero rows.

-- ================= The concurrency test that matters ================
-- Opposite directions between the SAME pair. This is the case that
-- produces deadlocks and lost updates, and a test suite without it
-- is testing the happy path twice.
--
--   pgbench -c 50 -j 4 -T 120 -f transfer_a_to_b.sql -f transfer_b_to_a.sql
--
-- transfer_a_to_b.sql:
--   \set amount random(1, 100)
--   SELECT ledger.transfer(1, 2, :amount, 'bench-' || :client_id || '-' || :scale);
--
-- After the run, all three invariant queries must still return nothing.

-- ================= Declare the baseline BEFORE measuring ============
--
--   Instance:    4 vCPU, 16 GB, gp3 500 GB
--   Dataset:     1,000,000 accounts, 50,000,000 entries
--   Workload:    80% statement reads, 20% transfers
--   Claim:       transfers        p99 < 50 ms at 200 concurrent clients
--                statement reads  p99 < 20 ms
--                throughput       > 2,000 transfers/second sustained
--
-- Then measure, and report what you actually got - including the
-- percentile that missed.

SELECT round(mean_exec_time::numeric, 2) AS mean_ms,
       round((total_exec_time / calls)::numeric, 2) AS per_call_ms,
       calls, left(query, 60)
FROM pg_stat_statements
WHERE query LIKE '%ledger.transfer%'
ORDER BY calls DESC;

-- ================= The failure modes, and the evidence ==============
--
-- Each of these is a row in your report: what happens, what the
-- customer sees, what the operator does.
--
--   primary dies mid-transfer
--     in-flight transactions roll back; the WAL replays on recovery;
--     an async replica may be behind by its measured lag
--     -> measure that lag and state it as the RPO
--
--   disk fills
--     writes fail; archiving stops first if archive_command is broken
--     -> alert on pg_stat_archiver.failed_count and free space
--
--   replica falls behind
--     reads served from it become stale; a failover now loses more
--     -> alert on pg_last_xact_replay_timestamp
--
--   wrong UPDATE in production
--     replicates instantly to every standby
--     -> PITR to the moment before, which is the ONLY recovery
--
-- Verify after every recovery with the three invariant queries above,
-- not by checking that the server started.

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course The order the modules build in, how the laboratories are assessed, and the habits that make the difference between finishing and understanding. 2 min read

Discussion

No questions on this topic yet. Sign in to ask the first one.