A ledger at scale: hot accounts, balances, sharding
Two accounts take nearly half the entries and most of the transactions. A balance row on either one turns eight threads into a queue; append the entry, derive the balance, or split the account
Owoleaf's ledger has one account, settlement_bank, in 77% of the first 20,000 postings. Eight threads post them. Every posting takes 1 ms to commit, and a row lock is held until the commit. Design A updates a balance row for every account a posting touches. Design B only appends entries, and locks nothing but the customer's own wallet row. About how many times more postings a second does B manage?
A double-entry ledger is a set of entries that sum to zero. Making it fast is a question about which rows many transactions have to touch at once. The double-entry chapter said balances are derived, and promised a comparison of the options once the ledger had to carry load. This is that comparison. It assumes you can write the posting function from the wallet ledger project and that you know why a retried posting needs an idempotency key. It does not teach locks from the beginning: the Databases course does, in locking and deadlocks and isolation levels.
Where the entries go
A hot account is one that a large share of transactions must touch. In a payments ledger the hot accounts are not customers. They are the company’s own accounts, the ones every kind of transaction has to move money through. You do not need a model to find them. Count.
Owoleaf’s ledger at scale 0.1 holds 191,103 entries in 79,827 posted transactions, on 2,005 accounts. Step 1 prints this:
| Account | Entries | Share of entries | Transactions touching it | Share of transactions |
|---|---|---|---|---|
settlement_bank |
56,007 | 29.31% | 56,007 | 70.16% |
fee_revenue |
31,275 | 16.37% | 31,275 | 39.18% |
card_clearing |
10,454 | 5.47% | 10,454 | 13.10% |
| all 1,996 wallets that ever posted | 93,192 | 48.77% | – | – |
The busiest of the 1,996 wallets has 776 entries. The average wallet has 47. settlement_bank has 56,007: seventy-two times the busiest customer, about 1,200 times the average one. Two accounts out of 2,005 take 45.7% of all entries.
There are two shares and they answer different questions. The share of entries says how much of the table’s growth lands on an account. The share of transactions says how many transactions have to coordinate through it, and that is the one that limits throughput. They differ because each of these accounts appears at most once in a transaction (the two columns are equal), while a transaction has 2.4 entries on average (191,103 ÷ 79,827). So settlement_bank is in 29% of the entries but 70% of the transactions. Every NIP funding and every NIP payout posts one leg to the settlement account.
Does it get better with size? At scale 1 (20,000 customers, 1,946,042 entries, 816,463 posted transactions) the same script prints settlement_bank at 30.25% of entries and 72.11% of transactions, and fee_revenue at 16.08% and 38.33%. The wallets grow in number; the hot accounts do not. The share stays put because it is set by the shape of the business: more customers means more postings, and every one still ends at the same few company accounts. Only the busiest wallet moves, from 776 entries to 2,470. A bank with 9.2 million customers has the same two hot accounts, with far more traffic through each.
A balance row is a lock
The obvious design stores a balance next to each account and updates it with every posting. A reader gets the balance in one lookup. A write inserts the entries and runs UPDATE accounts SET balance_kobo = balance_kobo + ? WHERE id = ? for each leg, all inside one database transaction, so the two stay in step.
The cost is in what that UPDATE does. In PostgreSQL row-level locks are released at the end of the transaction, and an UPDATE locks the rows it changes, so a second writer of the same row waits; plain reads do not wait (this rests on a search summary of the manual)as of 2026-11. So a transaction that updates settlement_bank holds that row until its commit finishes. The next transaction that wants it waits. Throughput on that row is the inverse of the time the lock is held, and the time includes the commit: the flush of the log to disk, and the round trip to the client if the client sends COMMIT as a separate message.
The ceiling is arithmetic you can do before writing code:
postings a second ≤ 1 / (share of postings touching the row × seconds the lock is held)
With 77% of postings touching settlement_bank and a 1 ms commit, that is 1 ÷ (0.771 × 0.001) = 1,297 a second. (Step 3 prints 1,296; the difference is rounding in the share.) It does not matter whether you have 8 threads or 800. The threads are queueing, not working. Adding application servers lengthens the queue and raises the latency each posting sees.
Three things make it worse.
- The lock covers more than the legs you meant. If the posting also updates
fee_revenue, it holds two hot rows at once, and a transaction that hassettlement_bankwaits forfee_revenuewhile the next one waits for it. Here 39% of transactions touchfee_revenue, so even if you sharded the first, the second becomes the ceiling. - Lock order. Two postings that take the same two rows in opposite orders deadlock, and the database aborts one. The cure is a fixed order, by account id, in every code path. The lab’s postings are sorted for this reason. The lesson on database deadlocks shows the failure.
- Read-modify-write. A posting that reads the balance, adds in application code and writes back, without a lock or a version check, loses an update when two run together. It is the shape of the bug in check-then-act.
SET balance_kobo = balance_kobo + ?does the addition inside the database, under the lock.
Notice what the balance row buys. It lets the database refuse a debit that would take a wallet below zero, in one statement. Keep that in mind: it matters for wallets and not for the settlement account.
Append the entry, derive the balance
The alternative is the design the earlier chapters already used for wallets: the entries are the truth and a balance is a sum. A posting only inserts entries. An insert into a table with a growing primary key does not fight with another insert over a row, because there is no shared row to fight over: each transaction writes new rows. The hot account stops being hot at the write.
Reading is where you pay. The sum of 56,007 entries is slow. Step 5 prints it: summing all of settlement_bank takes about 9.8 ms on the machine this chapter was written on. Summing the busiest wallet’s 776 entries takes 0.15 to 0.23 ms across runs. Both are fine for an audit and too slow for a balance shown to treasury every second.
A snapshot fixes that. At some moment, store each account’s balance together with the id of the last entry it includes. A balance is then the latest snapshot plus the sum of the entries with a higher id. The lab’s snapshot job folds the entries since the last snapshot into the new one, so its own cost stays small: twenty snapshots in a 100,000-posting run took 0.11 s in all on the machine this chapter was written on.
Two rules keep a snapshot correct.
- Cut by entry id, never by time. “Everything before 14:00:00” is not a set a database can name. Entries become visible when their transactions commit, not when they get a timestamp, so an entry stamped 13:59:59.9 can appear after a snapshot taken at 14:00:00 and be missed for ever. Entry ids are assigned in one order and the snapshot says “up to id n”, so what is included is exact. In the lab the snapshot runs inside a write transaction, so no commit can slip in below the cut. In a database that lets writers commit out of order, the cut must be at an id below which every transaction has finished.
- A snapshot is a cache. If it ever disagrees with the entries, the entries win and you rebuild it. The lab checks, after each run, that the snapshot-plus-delta balance of every account equals the sum of its entries.
The cost of the delta depends on how far behind the snapshot is. Step 5 measures it for settlement_bank:
| Snapshot behind by | Its own entries to add | Time to read the balance |
|---|---|---|
| 0 entries | 0 | 1.4 µs |
| 1,000 | 287 | 44.7 µs |
| 10,000 | 2,758 | 490.1 µs |
| 50,000 | 13,774 | 2,465.8 µs |
Reads are linear in the entries since the snapshot, as you would expect, and the delta is a fraction of the ledger’s entries because only 29% of them are on this account. A snapshot every 400 postings or so (1,000 entries) keeps a balance read near 50 µs; one every 4,000 postings or so (10,000 entries) keeps it near half a millisecond. These times belong to one machine; the proportions do not.
What do you lose? Two things, and both are real.
- The in-statement floor check. A wallet must not go below zero (invariant 4 of
check.py). Without a balance row, the posting reads snapshot plus delta for the wallet and compares. Two simultaneous debits to one wallet could both read the same balance and both pass. So you still serialise a wallet’s own postings, with a lock on one small row for that wallet or a per-wallet sequence number. That row is cold: 1,996 wallets share the traffic, and the busiest has 776 of 191,103 entries. The model in the lab locks exactly that and nothing else. The hot accounts need no floor, because an asset account such as the settlement account is allowed to be negative: that is an overdraft at the partner bank, which treasury watches and the ledger does not forbid. - One number per row. A balance row is one place to look. Reconciliation and reporting now read snapshots and deltas, and every report has to use the same cut or two reports disagree. The reconciliation chapter compares the ledger’s settlement account to the bank’s statement, and it should read the balance at a named entry id, not “now”.
Splitting the account
A third design keeps the balance row and splits the hot account. settlement_bank becomes K sub-accounts, say settlement_bank:0 to settlement_bank:15, all real accounts in the chart. A posting picks one, for example by its transaction number modulo K, and updates only that row. The account’s balance is the sum of the K rows. This is sharding an account, not sharding the database: the data does not move to other machines, the single hot row becomes several. The Databases course covers sharding a table across servers, which solves a different problem (data too large for one machine).
Contention drops in proportion. With K sub-accounts, about 1/K of the postings meet on any one row, so the ceiling rises about K times. The row-lock model in step 4 measures it at 1 ms a commit: 2,110 postings a second with 2 sub-accounts, 3,993 with 4, 6,623 with 8 and 6,956 with 16, against 1,062 with none and 7,143 for append-only.
The costs are specific.
- Reads sum K rows. One lookup becomes K. At 16 that is small. At 1,000 it is the snapshot problem again.
- Floors need all the shards. A rule such as “never below zero” needs the sum, which means locking all K rows, which puts the queue back. Sharding suits accounts without a floor: settlement, fee revenue, clearing.
- Every hot account needs its own K.
fee_revenueis in 39% of transactions, so it needs splitting too, or it becomes the ceiling. In the model the three hot accounts all use the same K. - Choosing K is a capacity decision. Pick it from the arithmetic: peak postings a second times the share on the account times the lock time gives the number of concurrent holders you expect; K should comfortably exceed it. K can usually be raised later by adding sub-accounts for new postings. Lowering it means summing old ones away.
Splitting removes the queue and keeps a balance column everywhere, so existing code that reads a balance changes least. Append-only removes the lock altogether and changes every reader. Neither is free, and they combine: some ledgers append entries to sharded hot accounts and snapshot each shard.
What SQLite shows, and what it does not
The lab runs both designs on a real database, SQLite, because every learner has it. You must read the result carefully. In its WAL mode (write-ahead logging) SQLite allows only one writer at a time, though readers carry on while it writesas of 2026-11. The lock is on the whole database, so there are no row locks to wait on. In effect every account is a hot account, and eight threads queue however you design the schema.
The benchmark still shows something: how much work each design does while it holds the one lock, and how a shared machine disturbs the numbers. Here is what happened when this chapter was written, on a four-core virtual machine that other jobs were using at the same time:
| 100,000 postings, 8 threads | Design A (balance row) | Design B (append plus snapshots) |
|---|---|---|
| run 1 | 5,108 a second | 5,596 |
| run 2 | 2,760 | 6,286 |
| run 3 | 2,603 | 5,885 |
| run 4 | 2,139 | 3,200 |
B was ahead in all four pairs, by 1.1 to 2.3 times. Within each design the numbers moved by about a factor of two between runs, as much as the gap between the designs, which is the shared machine. With a single thread the first time, A managed 5,796 and B 5,126; a later rerun on a slower, busier machine gave 2,807 and 6,987. One run cannot say which design wins at one thread. Read this as: on a database with one writer, how you update balances matters less than how many writers you have, and a gap of this size is below what one run can prove. Run each pair three times, alternately, and compare ratios, not absolute rates.
Machine-dependent: every postings-a-second figure in this chapter, every read time in microseconds, the time to generate scale 1 (41 s here, 715 MB), and the length of a real sleep. Not machine-dependent: the entry and transaction shares (they come from the seed), the arithmetic of the ceiling, the final balances, and the ordering of the model’s results (A far below B, C rising with K). A row-lock database changes the picture again: it queues only the transactions that share a row, which is what the model in the lab imitates and SQLite cannot.
Where it goes wrong
- The snapshot cut by time. Covered above: an entry committed late is never added. The symptom is a hot balance that is wrong by one posting’s amount, and only after a busy hour. Reconcile each snapshot against the full sum in a nightly job, on a replica.
- A balance column and entries that disagree. Someone fixes a wrong balance with
UPDATE accounts SET balance_kobo = ..., with no entry behind it. The next full recompute shows a difference nobody can explain. The entries are the truth: repair the balance by posting a correcting entry, as in the double-entry chapter. - A dashboard that sums. A finance screen refreshing every second with
SUM(kobo)over the settlement account’s whole history is 9.8 ms of work a second per viewer in this lab, and scales with history. Serve it from the snapshot and delta. - Sub-accounts nobody sums. After sharding, a report that reads
settlement_bankand finds nothing, or one of sixteen rows, understates the account by 15 parts in 16. Give the parent account a view that sums its children and forbid reading the sub-accounts directly. - Retries on a hot account. A client that retries a timed-out posting without an idempotency key posts twice, and a hot account makes timeouts likelier. The key from the idempotency chapter is still unique per posting.
- Replaying history into a new design. When you migrate from balance rows to snapshots, rebuild the snapshots from the entries and compare every account before switching. The lab’s check does this on every run.
What published ledgers say
Three vendors and one paper describe ledgers built around this problem. Read their numbers as their authors’ claims, not as measurements you can reproduce here.
Square’s engineering team describes a service called Books in which Books is built on double-entry accounting and its balances change only through accounting transactions (this rests on a search summary of the post)as of 2026-11: the append-only shape, in a payments company’s words. Stripe describes its Ledger as an immutable, auditable log and says that, with its data quality platform, it supports more than 99.9999% explainability of money movementas of 2026-11, a vendor claim about its own system. TigerBeetle’s documentation names the problem this chapter measured: hot accounts, especially business income and expense accounts, are a bottleneck under row locking, and TigerBeetle says it gives strong consistency without row locks (this rests on a search summary of the page)as of 2026-11. That is a database vendor’s description of its own product and of the alternative it was built to avoid. The paper that gives the idea its general form is Helland’s “Immutability Changes Everything” (CIDR 2015), which makes the case for immutable, append-only data in large systems. None of these tells you which to choose for your volume. The arithmetic in this chapter, with your own commit time and your own shares, does.
You work in labs/finance. You create four small files there: shares.py, hotbench.py, rowlocks.py and balread.py. Money is integer kobo in every file: debits are positive and credits negative, so each posting sums to zero and a wallet, which is a liability, has a negative balance. The benchmarks write to a scratch database in your system’s temporary folder and never touch data/. Timings depend on your machine, so yours will differ from the ones below; the shares, the balances and the ordering of the results will not.
1. Count the entries and the transactions per account. Save shares.py:
"""Who takes the entries? Share of entries, and of transactions, per account."""
import sqlite3, sys
path = sys.argv[1] if len(sys.argv) > 1 else "data/finance.sqlite"
db = sqlite3.connect(path)
entries = db.execute("SELECT COUNT(*) FROM entries").fetchone()[0]
txns = db.execute("SELECT COUNT(DISTINCT transaction_id) FROM entries").fetchone()[0]
print(f"{entries:,} entries in {txns:,} posted transactions on "
f"{db.execute('SELECT COUNT(*) FROM accounts').fetchone()[0]:,} accounts")
print(f"{'account':18}{'entries':>10}{'share':>8}{'transactions':>14}{'share':>8}")
for code, n, t in db.execute("""
SELECT a.code, COUNT(*), COUNT(DISTINCT e.transaction_id)
FROM entries e JOIN accounts a ON a.id = e.account_id
WHERE a.type != 'liability' GROUP BY a.code ORDER BY 2 DESC"""):
print(f"{code:18}{n:>10,}{100 * n / entries:>7.2f}%{t:>14,}{100 * t / txns:>7.2f}%")
w, wa = db.execute("""SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entries e
JOIN accounts a ON a.id = e.account_id WHERE a.type = 'liability'""").fetchone()
print(f"{'all wallets':18}{w:>10,}{100 * w / entries:>7.2f}% across {wa:,} accounts, "
f"mean {w / wa:,.0f} entries each")
code, n = db.execute("""SELECT a.code, COUNT(*) FROM entries e JOIN accounts a ON a.id = e.account_id
WHERE a.type = 'liability' GROUP BY a.code ORDER BY 2 DESC LIMIT 1""").fetchone()
print(f"busiest wallet: {code}, {n:,} entries")cd labs/finance
ls data/finance.sqlite >/dev/null 2>&1 || python3 generate.py
python3 shares.py191,103 entries in 79,827 posted transactions on 2,005 accounts
account entries share transactions share
settlement_bank 56,007 29.31% 56,007 70.16%
fee_revenue 31,275 16.37% 31,275 39.18%
card_clearing 10,454 5.47% 10,454 13.10%
processing_expense 174 0.09% 174 0.22%
share_capital 1 0.00% 1 0.00%
all wallets 93,192 48.77% across 1,996 accounts, mean 47 entries each
busiest wallet: wallet:1731, 776 entriesTwo accounts take 45.7% of the entries and, between them, sit in most transactions. The column to watch is the fourth: settlement_bank is in 70.16% of the transactions. If you also have time, repeat at scale 1. It takes about 41 seconds and writes about 715 MB, so put it in /tmp and delete it. The output was 1,946,042 entries in 816,463 posted transactions on 20,005 accounts, settlement_bank 30.25% of entries and 72.11% of transactions, fee_revenue 16.08% and 38.33%, and a busiest wallet of 2,470 entries.
python3 generate.py --scale 1 --out /tmp/atlas-s1
python3 shares.py /tmp/atlas-s1/finance.sqlite
rm -rf /tmp/atlas-s12. Post 100,000 transactions on SQLite from 8 threads, two ways. Save hotbench.py. It replays the lab ledger’s own postings (cycling through its 79,827 to reach 100,000), so the hot accounts are the ones you counted in step 1. Design A inserts the entries and updates a balance row for every leg. Design B inserts the entries and nothing else, and takes a snapshot every 5,000 postings inside the timed run. Each posting is one BEGIN IMMEDIATE transaction, which asks for the write lock at the start. Afterwards it checks that every account’s balance, from the column or from snapshot plus delta, equals the sum of its entries.
"""Post the same 100,000 transactions from 8 threads two ways and time them.
A balance row: INSERT the entries, UPDATE accounts.balance_kobo for every leg, in one transaction.
B append-only: INSERT the entries and nothing else; a snapshot of every balance is taken
every SNAP_EVERY postings, inside the same timed run.
Money is integer kobo. Debit is positive, credit negative, so every posting sums to 0.
Usage: python3 hotbench.py [A|B] [threads] [postings] [--sync FULL|NORMAL]
"""
import os, sqlite3, sys, threading, time, tempfile
SRC = "data/finance.sqlite"
SNAP_EVERY = 5_000
SCHEMA = """
CREATE TABLE accounts (id INTEGER PRIMARY KEY, code TEXT NOT NULL, balance_kobo INTEGER NOT NULL DEFAULT 0);
CREATE TABLE entries (id INTEGER PRIMARY KEY, txn INTEGER NOT NULL, account_id INTEGER NOT NULL, kobo INTEGER NOT NULL);
CREATE INDEX entries_acct ON entries (account_id, id);
CREATE TABLE snapshots (account_id INTEGER NOT NULL, upto_entry INTEGER NOT NULL, balance_kobo INTEGER NOT NULL,
PRIMARY KEY (account_id, upto_entry));
"""
def load_postings(n):
"""The legs of every posted transaction in the lab ledger, as (account_id, signed kobo)."""
src = sqlite3.connect(SRC)
postings, cur, last = [], [], None
for txn, acct, direction, kobo in src.execute("""
SELECT e.transaction_id, e.account_id, e.direction, e.amount_kobo
FROM entries e ORDER BY e.transaction_id, e.id"""):
if txn != last and cur:
postings.append(cur); cur = []
last = txn
cur.append((acct, kobo if direction == "debit" else -kobo))
if cur: postings.append(cur)
accounts = src.execute("SELECT id, code FROM accounts").fetchall()
out = [postings[i % len(postings)] for i in range(n)] # cycle the ledger to reach n
return accounts, out
def connect(path, sync):
db = sqlite3.connect(path, isolation_level=None, timeout=120)
db.execute("PRAGMA journal_mode=WAL")
db.execute(f"PRAGMA synchronous={sync}")
return db
def snapshot(db):
"""Cut at the highest entry id and fold the entries since the last cut into new balances."""
cut = db.execute("SELECT COALESCE(MAX(id),0) FROM entries").fetchone()[0]
prev = db.execute("SELECT COALESCE(MAX(upto_entry),0) FROM snapshots").fetchone()[0]
db.execute("""INSERT INTO snapshots SELECT account_id, ?1, SUM(b) FROM (
SELECT account_id, kobo AS b FROM entries WHERE id > ?2 AND id <= ?1
UNION ALL SELECT account_id, balance_kobo FROM snapshots WHERE upto_entry = ?2)
GROUP BY account_id""", (cut, prev))
def run(design, threads, n, sync):
accounts, postings = load_postings(n)
path = os.path.join(tempfile.mkdtemp(), "bench.sqlite")
setup = connect(path, sync)
setup.executescript(SCHEMA)
setup.executemany("INSERT INTO accounts (id, code) VALUES (?, ?)", accounts)
setup.close()
lock, nxt = threading.Lock(), [0]
waits, holds, counts = [0.0] * threads, [0.0] * threads, [0] * threads
snaps = [0.0]
def worker(w):
db = connect(path, sync)
while True:
with lock:
i = nxt[0]; nxt[0] += 1
if i >= n: break
legs = sorted(postings[i]) # fixed account order
t0 = time.perf_counter()
db.execute("BEGIN IMMEDIATE") # wait here for the write lock
t1 = time.perf_counter()
db.executemany("INSERT INTO entries (txn, account_id, kobo) VALUES (?, ?, ?)",
[(i, a, k) for a, k in legs])
if design == "A":
db.executemany("UPDATE accounts SET balance_kobo = balance_kobo + ? WHERE id = ?",
[(k, a) for a, k in legs])
if design == "B" and (i + 1) % SNAP_EVERY == 0:
ts = time.perf_counter(); snapshot(db); snaps[0] += time.perf_counter() - ts
db.execute("COMMIT")
t2 = time.perf_counter()
waits[w] += t1 - t0; holds[w] += t2 - t1; counts[w] += 1
db.close()
t = time.perf_counter()
ts = [threading.Thread(target=worker, args=(w,)) for w in range(threads)]
[x.start() for x in ts]; [x.join() for x in ts]
wall = time.perf_counter() - t
db = connect(path, sync)
truth = dict(db.execute("SELECT account_id, SUM(kobo) FROM entries GROUP BY account_id"))
if design == "A":
got = dict(db.execute("SELECT id, balance_kobo FROM accounts"))
else:
snap = db.execute("SELECT COALESCE(MAX(upto_entry),0) FROM snapshots").fetchone()[0]
got = dict(db.execute("""SELECT account_id, SUM(b) FROM (
SELECT account_id, balance_kobo AS b FROM snapshots WHERE upto_entry = ?1
UNION ALL SELECT account_id, kobo FROM entries WHERE id > ?1) GROUP BY account_id""", (snap,)))
ok = all(got.get(a, 0) == truth.get(a, 0) for a, _ in accounts)
zero = sum(truth.values()) == 0
rows = db.execute("SELECT COUNT(*) FROM entries").fetchone()[0]
print(f"design {design} threads {threads} postings {n:,} synchronous={sync}")
print(f" wall {wall:6.2f} s {n / wall:9,.0f} postings/s entries {rows:,}")
print(f" mean wait for the write lock {1000 * sum(waits) / n:7.3f} ms mean time holding it {1000 * sum(holds) / n:6.3f} ms")
if design == "B": print(f" snapshots: {n // SNAP_EVERY}, {snaps[0]:.2f} s in all")
print(f" balances match the entries: {ok} entries sum to zero: {zero}")
return n / wall, path
if __name__ == "__main__":
a = [x for x in sys.argv[1:] if not x.startswith("--")]
sync = "FULL"
if "--sync" in sys.argv: sync = sys.argv[sys.argv.index("--sync") + 1]; a = [x for x in a if x != sync]
design = a[0] if a else "A"
threads = int(a[1]) if len(a) > 1 else 8
n = int(a[2]) if len(a) > 2 else 100_000
run(design, threads, n, sync)python3 hotbench.py A
python3 hotbench.py Bdesign A threads 8 postings 100,000 synchronous=FULL
wall 19.58 s 5,108 postings/s entries 239,995
mean wait for the write lock 1.365 ms mean time holding it 0.191 ms
balances match the entries: True entries sum to zero: True
design B threads 8 postings 100,000 synchronous=FULL
wall 17.87 s 5,596 postings/s entries 239,995
mean wait for the write lock 1.247 ms mean time holding it 0.174 ms
snapshots: 20, 0.11 s in all
balances match the entries: True entries sum to zero: TrueThe output above is one run on one machine; every rate, wait and time in it will differ on yours. The two results that do not move: balances match the entries: True for both designs, and 239,995 entries, which is the 79,827 postings’ legs cycled up to 100,000 postings. The rate is the one that moves. Run each design three or four times, alternately: here B was ahead of A in all four pairs, between 1.1 and 2.3 times, while each design’s own rate swung between 2,139 and 5,108 (A) and 3,200 and 6,286 (B) on a machine shared with other jobs. Run python3 hotbench.py A 1 and python3 hotbench.py B 1 for one thread: A managed 5,796 a second and B 5,126 on that run (a rerun on a slower machine gave 2,807 and 6,987, so do not read a winner into one thread), and the wait is 0.004 ms, because nobody else wants the lock. Eight threads on SQLite wait about 1.3 ms to do 0.2 ms of work. SQLite allows one writer, so this is not a row lock, and it cannot show a hot row. Step 3 does.
3. Model the row locks. Save rowlocks.py. It is a model, not a database: each balance row has a lock, a posting takes the locks of the rows it updates in id order, sleeps 1 ms to stand for the commit, and releases them. Design A locks every account a posting touches. Design B locks only the wallet. It prints the ceiling that the arithmetic predicts.
"""A model of row locks, not a database. 8 threads post transactions from the lab ledger.
Each balance row has one lock. A posting takes the lock of every row it updates, in order,
then 'commits' (sleeps COMMIT_MS, standing in for the log flush and the network round trip)
and releases them all. Row locks are held to the end of the transaction, as in PostgreSQL.
A balance row: every leg updates a balance row, so every leg's account is locked.
B append-only: only a wallet's own row is locked (the check that it stays at or above zero);
the entries of the hot accounts are inserted with no row to fight over.
C sharded: as A, but each hot account is split into SHARDS sub-accounts, and a posting
updates the one its transaction number picks.
Usage: python3 rowlocks.py [A|B|C] [threads] [postings] [commit_ms] [shards]
"""
import sys, threading, time
sys.path.insert(0, ".")
from hotbench import load_postings
HOT = ("settlement_bank", "fee_revenue", "card_clearing")
def run(design, threads, n, commit_ms, shards=1):
accounts, postings = load_postings(n)
wallet = {a for a, code in accounts if code.startswith("wallet:")}
hot = {a for a, code in accounts if code in HOT}
locks = {(a, b): threading.Lock() for a, _ in accounts for b in range(shards if a in hot else 1)}
lock, nxt = threading.Lock(), [0]
waited = [0.0] * threads
def worker(w):
while True:
with lock:
i = nxt[0]; nxt[0] += 1
if i >= n: break
rows = sorted({(a, i % shards if design == "C" and a in hot else 0)
for a, _ in postings[i] if design != "B" or a in wallet})
t0 = time.perf_counter()
for r in rows: locks[r].acquire()
waited[w] += time.perf_counter() - t0
time.sleep(commit_ms / 1000) # commit: the locks are held through it
for r in rows: locks[r].release()
t = time.perf_counter()
ts = [threading.Thread(target=worker, args=(w,)) for w in range(threads)]
[x.start() for x in ts]; [x.join() for x in ts]
wall = time.perf_counter() - t
extra = f" shards {shards}" if design == "C" else ""
bank = next(a for a, code in accounts if code == "settlement_bank")
share = sum(any(a == bank for a, _ in p) for p in postings) / n
print(f"model {design} threads {threads} postings {n:,} commit {commit_ms} ms{extra}")
print(f" wall {wall:6.2f} s {n / wall:8,.0f} postings/s mean wait for row locks {1000 * sum(waited) / n:6.3f} ms")
print(f" {100 * share:.1f}% of postings touch settlement_bank; one row at {commit_ms} ms a commit "
f"caps a design that locks it at {1000 / (share * commit_ms):,.0f}/s; "
f"{threads} threads with no queue would reach {1000 * threads / commit_ms:,.0f}/s")
if __name__ == "__main__":
a = sys.argv[1:]
run(a[0] if a else "A", int(a[1]) if len(a) > 1 else 8, int(a[2]) if len(a) > 2 else 20000,
float(a[3]) if len(a) > 3 else 1.0, int(a[4]) if len(a) > 4 else 16)python3 rowlocks.py A
python3 rowlocks.py Bmodel A threads 8 postings 20,000 commit 1.0 ms
wall 18.82 s 1,062 postings/s mean wait for row locks 6.410 ms
77.1% of postings touch settlement_bank; one row at 1.0 ms a commit caps a design that locks it at 1,296/s; 8 threads with no queue would reach 8,000/s
model B threads 8 postings 20,000 commit 1.0 ms
wall 2.80 s 7,143 postings/s mean wait for row locks 0.028 ms
77.1% of postings touch settlement_bank; one row at 1.0 ms a commit caps a design that locks it at 1,296/s; 8 threads with no queue would reach 8,000/sCheck the arithmetic by hand: 1,000 ms ÷ (0.771 × 1.0 ms) = 1,297 a second (the script’s 1,296 uses the unrounded share). A measured 1,062, below its ceiling, because sleep(0.001) really lasts about 1.07 ms here and a lock changing hands costs a little. B measured 7,143, below 8,000 for the same reason. The mean wait for row locks is 6.4 ms against 0.03 ms: A’s threads spend 6.4 ms queueing to do 1 ms of commit. The share line prints for B as well, but it only limits designs that lock the row. The seconds and rates are from one run; yours will differ with the machine, and the 77.1% and the ceilings will not.
4. Split the hot accounts. Design C is A with each hot account (settlement_bank, fee_revenue, card_clearing) divided into K sub-accounts; a posting updates the one its transaction number picks. Sweep K:
for k in 2 4 8 16; do python3 rowlocks.py C 8 20000 1.0 $k | grep -E "^model|wall"; donemodel C threads 8 postings 20,000 commit 1.0 ms shards 2
wall 9.48 s 2,110 postings/s mean wait for row locks 2.683 ms
model C threads 8 postings 20,000 commit 1.0 ms shards 4
wall 5.01 s 3,993 postings/s mean wait for row locks 0.893 ms
model C threads 8 postings 20,000 commit 1.0 ms shards 8
wall 3.02 s 6,623 postings/s mean wait for row locks 0.090 ms
model C threads 8 postings 20,000 commit 1.0 ms shards 16
wall 2.88 s 6,956 postings/s mean wait for row locks 0.035 msThe ceiling rises about with K and then stops mattering: 1,062 with none, 2,110, 3,993, 6,623, 6,956, against 7,143 for append-only. Past K = 8 the row is no longer the limit; the eight threads are. The model does not charge sharding for its costs: a read of the balance sums K rows, and a floor on the whole account cannot be checked on one row. Those are in the chapter, not in the numbers. As in step 3, the seconds and rates will differ on your machine; the order of the rows should not.
5. Read a derived balance. Save balread.py. It copies the lab’s 191,103 entries into memory, then times the balance of settlement_bank and of the busiest wallet, first as a sum of all entries, then as a snapshot plus the entries since, with the snapshot 0, 1,000, 10,000 and 50,000 entries behind the end of the ledger.
"""What reading a balance costs when it is derived: full sum, snapshot plus delta, stored row."""
import sqlite3, time
src = sqlite3.connect("data/finance.sqlite")
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE entries (id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL, kobo INTEGER NOT NULL);
CREATE INDEX entries_acct ON entries (account_id, id);
CREATE TABLE snapshots (account_id INTEGER, upto_entry INTEGER, balance_kobo INTEGER, PRIMARY KEY (account_id, upto_entry));
""")
db.executemany("INSERT INTO entries VALUES (?, ?, ?)", src.execute(
"SELECT id, account_id, CASE direction WHEN 'debit' THEN amount_kobo ELSE -amount_kobo END FROM entries"))
bank = src.execute("SELECT id FROM accounts WHERE code = 'settlement_bank'").fetchone()[0]
wallet = src.execute("""SELECT account_id FROM entries e JOIN accounts a ON a.id = e.account_id
WHERE a.code LIKE 'wallet:%' GROUP BY account_id ORDER BY COUNT(*) DESC LIMIT 1""").fetchone()[0]
last = db.execute("SELECT MAX(id) FROM entries").fetchone()[0]
def timed(sql, args, reps=200):
t = time.perf_counter()
for _ in range(reps):
v = db.execute(sql, args).fetchone()[0]
return v, (time.perf_counter() - t) / reps * 1e6
FULL = "SELECT SUM(kobo) FROM entries WHERE account_id = ?"
DELTA = """SELECT COALESCE((SELECT balance_kobo FROM snapshots WHERE account_id = ?1 AND upto_entry = ?2), 0)
+ COALESCE((SELECT SUM(kobo) FROM entries WHERE account_id = ?1 AND id > ?2), 0)"""
n_bank = db.execute("SELECT COUNT(*) FROM entries WHERE account_id = ?", (bank,)).fetchone()[0]
n_wallet = db.execute("SELECT COUNT(*) FROM entries WHERE account_id = ?", (wallet,)).fetchone()[0]
print(f"settlement_bank: {n_bank:,} entries busiest wallet: {n_wallet:,} entries ledger: {last:,} entries")
v, us = timed(FULL, (wallet,)); print(f"wallet, sum all its entries: {us:8.1f} us balance {v:,} kobo")
v, us = timed(FULL, (bank,)); print(f"settlement_bank, sum all its entries: {us:8.1f} us balance {v:,} kobo")
for behind in (0, 1_000, 10_000, 50_000):
cut = last - behind
db.execute("DELETE FROM snapshots")
db.execute("INSERT INTO snapshots SELECT account_id, ?1, SUM(kobo) FROM entries WHERE id <= ?1 GROUP BY account_id", (cut,))
delta = db.execute("SELECT COUNT(*) FROM entries WHERE account_id = ? AND id > ?", (bank, cut)).fetchone()[0]
v2, us = timed(DELTA, (bank, cut))
print(f"settlement_bank, snapshot {behind:>6,} entries behind: {us:8.1f} us {delta:>6,} of its entries to add same balance: {v2 == v}")python3 balread.pysettlement_bank: 56,007 entries busiest wallet: 776 entries ledger: 191,103 entries
wallet, sum all its entries: 233.9 us balance -5,646,075 kobo
settlement_bank, sum all its entries: 9845.4 us balance 17,189,646,589 kobo
settlement_bank, snapshot 0 entries behind: 1.4 us 0 of its entries to add same balance: True
settlement_bank, snapshot 1,000 entries behind: 44.7 us 287 of its entries to add same balance: True
settlement_bank, snapshot 10,000 entries behind: 490.1 us 2,758 of its entries to add same balance: True
settlement_bank, snapshot 50,000 entries behind: 2465.8 us 13,774 of its entries to add same balance: TrueThe microsecond timings are from one run and will differ on your machine; the balances and entry counts will not. The settlement account’s balance is 17,189,646,589 kobo, ₦171,896,465.89, the same figure check.py prints for the ledger’s settlement account. The wallet’s is -5,646,075 kobo: Owoleaf owes that customer ₦56,460.75. Every row says same balance: True: the snapshot is a cache of the sum, never a different number. The times are your machine’s. The proportions are not: a full sum of the hot account costs tens of times a wallet’s, and a snapshot that is close to the end of the ledger costs almost nothing.
Make the commit slower and watch which design suffers. In step 3 change nothing but the command line: python3 rowlocks.py A 8 4000 5 and python3 rowlocks.py B 8 4000 5 (5 ms a commit, 4,000 postings). The arithmetic now says A is capped at 1,000 ÷ (0.802 × 5) = 249 a second. On one run it measured 223 a second, with a mean row-lock wait of 30.6 ms, while B measured 1,465 a second with a wait of 0.28 ms (a rerun gave 225 and 1,480), against a no-queue ceiling of 1,600. A slower commit, a remote database or a cross-region replica lengthens the time the hot row is held, so the same ledger code that was adequate in one data centre can fall below its peak in another. Then raise the threads to 32 for A and see the rate stay where it was: the threads are queueing, not working.
Template
# Ledger capacity review: <ledger or account>
Author · Reviewers (head of engineering, finance controller) · Date · Decision needed by <date>
## Decision asked
<Go or no-go on which change, for which accounts, by when, from whom.>
## Load
- Measured: <what you observed, where, when; transactions a second, latency, CPU>
- Expected: <peak a second, from where the forecast comes>
- Assumptions: <anything not measured, labelled as such>
## Hot accounts
| Account | Share of entries | Share of transactions | Ceiling = 1 / (share x lock seconds) | Below the peak? |
|---|---|---|---|---|
Why each is hot: <the business reason>
## Design chosen
<Append-only with snapshots, or sharded account, or both. Which accounts, and why this over the alternatives.>
Alternatives not chosen: <each, with the reason>
## What it costs
- Reads: <how a balance is read now, and its measured cost>
- Correctness: <what the balance row used to enforce that now needs another check>
- Complexity: <who changes code, what runs that did not before>
## Invariants and how they are checked
| Invariant | Check | Who runs it, how often |
|---|---|---|
## Rollout and rollback
<Side by side, comparison before switching, how to go back.>
## How this could be wrong
<One way, and what would show it.>
## Go / no-go
<Recommendation, conditions, owner, date. Signed: <name, role>> WORKED EXAMPLE
Northmere Bank, month-end salary peak. Tobiloba, an engineer on the core ledger, writes this review. Ebiye, who runs finance operations, reviews it for finance. At a real bank the ledger’s owner writes it; the head of engineering and the finance controller sign.
Decision asked. Go or no-go on making settlement_bank and fee_revenue append-only (scope: those two accounts; wallets unchanged), decided within two weeks so it lands before month end, five weeks away.
Load. Measured: on salary day posting latency climbs from milliseconds to seconds while the database sits at 15% CPU. Expected: a peak of 2,000 postings a second. Assumptions: a 2 ms lock; Northmere’s own shares are not yet counted, so the review borrows the shape the lab counted on Owoleaf’s ledger.
Hot accounts. settlement_bank: about 70% of transactions (70.16% in the lab), so the ceiling is 1 / (0.70 × 0.002) = 714 a second. fee_revenue: 39.18%, so 1 / (0.3918 × 0.002) = 1,276. Both are below the peak. card_clearing: 13.10%, 3,817; it can wait.
Design. Append-only with snapshots cut by entry id, for both accounts; wallets keep one small row for their floor. The lab model at a 1 ms commit measured 1,062 a second with balance rows and 7,143 append-only. Sharding into 16 reached 6,956 but keeps a balance row on each, so not chosen.
Cost. Reads: 44.7 µs with a snapshot 1,000 entries behind, against 9,845.4 µs to sum all 56,007 entries. Correctness: the settlement account needs no floor, since an overdraft at the partner bank is allowed and treasury watches it. Complexity: every balance reader changes.
Invariants. Entries sum to zero, and each balance equals the sum of its entries (the lab prints True for both). Tobiloba’s team runs that comparison nightly on a replica, and rolls out side by side, comparing every account before switching.
How this could be wrong. If Northmere’s settlement share is nearer 50% than 70%, the ceiling is about 1,000, and the count would show it.
Go, conditional on that count by the end of week one. Owner: Tobiloba. Signed: head of engineering and finance controller.
Now you
You are the engineer who owns Owoleaf’s ledger, now 200 people. The database replica is moving to a second region, so a commit will hold its row for 5 ms instead of 1 ms (an assumption: say so). At scale 1 your lab printed settlement_bank in 72.11% of transactions and fee_revenue in 38.33%. The step 3 break box measured 223 postings a second for balance rows at 5 ms and 1,465 for append-only, on a 4,000-posting run where 80.2% of postings touched settlement_bank. Finance forecasts 300 postings a second at the December peak (also an assumption). Check every figure against what your own lab printed. Write the capacity review. The head of engineering and the finance controller will read it, and it supports a go or no-go on the region move before the December peak.
Self-check
Northmere Bank's core ledger updates a balance column on every account. On salary day about 70% of postings touch the settlement account, a commit holds its row for about 2 ms, and the peak is 2,000 postings a second against a ceiling near 714. Tobiloba must stop the queueing before the next month end, which is five weeks away. Treasury, through Ebiye, reads that balance every minute and has no floor on it. Which change do you make first?
- POST Books, an immutable double-entry accounting database service (Square) Square, 2019
A payments company's account of a ledger whose balances are running totals of changes. Read it for the immutable, double-entry design in one company's words. It is Square's own description of its own service.
- POST Ledger: Stripe's system for tracking and validating money movement Stripe
Stripe's engineering account of its ledger and the data-quality checks that sit beside it, including how it measures how much money movement is explained. A vendor's claims about its own system. Read it for the design reasoning and skip the figures.
- DOC Performance (TigerBeetle documentation) TigerBeetle
A database built for ledgers, describing the hot-account problem and its own answer in its own documentation. Read the passage on hot accounts and row locks, and treat its comparisons as the vendor's. This chapter confirmed the page from a search summary, and the page itself was not fetched.
- DOC Data Modeling (TigerBeetle documentation) TigerBeetle
How the same vendor models accounts and transfers: a fixed schema of two record types, both immutable once written. Read it next to the append-only section above. It is a vendor's guidance for its own product.
- PAPER Immutability Changes Everything (Helland, CIDR 2015) Pat Helland, 2015
The paper behind the idea of appending and deriving. Read it for the argument that data kept as an append-only log can be viewed in many ways, which is the idea behind a balance derived from entries. The link is the conference's own copy; the paper was also reprinted in Communications of the ACM in January 2016. Read: The whole paper; it is short, so read it through once.
- DOC Write-Ahead Logging (SQLite documentation) SQLite
The database's own explanation of WAL mode, including why it allows one writer at a time while readers carry on. Read it before trusting any multi-threaded SQLite benchmark, this chapter's included. Skip the checkpointing detail on a first pass.
- DOC Explicit Locking (PostgreSQL documentation) PostgreSQL Global Development Group
The row-level lock modes and when an UPDATE takes them, from the database's own manual. Read the row-level locks section for when they are released. Skip table-level and advisory locks here.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.