Projects / Bank ledger / Phase 3
Phase 3 of 4 · about 2.5 hours
Make it fast on a million rows
You end with a ledger of a million entries, and the numbers that show what two indexes did.
Everything so far was fast because the tables were tiny. Real ledgers are not tiny. Let's find out what happens.
Step 3.1: Load a million entries (about 45 minutes)
This script adds 1,000 customer accounts and 500,000 transfers, which is 1,000,000 entries. Read it once before you run it.
INSERT INTO accounts (owner, currency)
SELECT 'Customer ' || n, 'USD' FROM generate_series(1, 1000) n;
CREATE TEMP TABLE customers AS
SELECT id, row_number() OVER (ORDER BY id) AS n
FROM accounts WHERE owner LIKE 'Customer %';
-- Bulk load: the balance check would run once per row, so switch it off for the load only.
ALTER TABLE entries DISABLE TRIGGER entries_balanced;
INSERT INTO transfers (idempotency_key, memo)
SELECT 'seed-' || n, 'generated' FROM generate_series(1, 500000) n;
WITH seed AS (
SELECT id AS transfer_id, row_number() OVER (ORDER BY id) AS rn
FROM transfers WHERE idempotency_key LIKE 'seed-%'
)
INSERT INTO entries (transfer_id, account_id, amount_cents)
SELECT s.transfer_id, c.id, v.sign * (50 + s.rn % 5000)
FROM seed s
CROSS JOIN LATERAL (VALUES (-1, s.rn % 1000 + 1), (1, (s.rn + 7) % 1000 + 1)) AS v(sign, k)
JOIN customers c ON c.n = v.k;
ALTER TABLE entries ENABLE TRIGGER entries_balanced;
ANALYZE;
It takes about ten seconds. Two things to notice:
- We turned the balance check off for the load, then on again. That is the one place we step around our own guard, so we check the result by hand.
ANALYZErefreshes PostgreSQL's statistics so it can plan queries well.
SELECT count(*) AS entries FROM entries;
SELECT sum(amount_cents) AS ledger_total FROM entries;
entries
---------
1000004
ledger_total
--------------
0
A million entries, and the total is still zero.
Step 3.2: Measure before you fix anything (about 45 minutes)
Never optimise on a hunch. Ask PostgreSQL how it runs a query. EXPLAIN ANALYZE runs the query and prints the plan it used, with real timings. We turn off parallel workers so the plan is easy to read.
First, the balance of one customer:
SET max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT sum(amount_cents) FROM entries WHERE account_id = 500;
Look for these lines in the output:
-> Seq Scan on entries (actual time=21.019..41.949 rows=1000 loops=1)
Buffers: shared hit=8334
Execution Time: 42.045 ms
Seq Scan means PostgreSQL read the whole table, about 8,000 pages, to find a thousand rows. Now the latest 20 entries for the same account, the kind of query a statement page runs:
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id, transfer_id, amount_cents, created_at
FROM entries WHERE account_id = 500
ORDER BY created_at DESC LIMIT 20;
-> Sort (actual time=39.972..39.973 rows=20 loops=1)
Sort Key: created_at DESC
-> Seq Scan on entries (actual time=20.004..39.866 rows=1000 loops=1)
Execution Time: 40.002 ms
Same story: a full scan, then a sort. And one more, because it matters most. How long does a transfer take on the big table?
\timing on
SELECT transfer('slow-1', 500, 501, 100, 'timing test');
Time: 60.188 ms
Sixty milliseconds for one transfer. Why? Our deferred balance check looks up the entries for the transfer by transfer_id, and nothing indexes that column. Foreign keys do not create indexes in PostgreSQL. The table scan is hiding inside the trigger.
Write the three numbers down: about 42 ms, 40 ms and 60 ms.
Step 3.3: Add two indexes (about 30 minutes)
An index is a sorted shortcut, like the index of a book. Ours:
CREATE INDEX entries_account_created_idx ON entries (account_id, created_at DESC);
CREATE INDEX entries_transfer_idx ON entries (transfer_id);
The first one is a multicolumn index. It sorts entries by account, and within each account newest first. That fits the statement query exactly: jump to the account, read 20 rows in order, stop. It also helps the balance query, which only needs the account part. The second index fixes the hidden scan in the balance check.
Step 3.4: Measure again (about 30 minutes)
Run the same three things:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT sum(amount_cents) FROM entries WHERE account_id = 500;
-> Index Scan using entries_account_created_idx on entries (actual time=0.056..0.147 rows=1001 loops=1)
Execution Time: 0.264 ms
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id, transfer_id, amount_cents, created_at
FROM entries WHERE account_id = 500
ORDER BY created_at DESC LIMIT 20;
-> Index Scan using entries_account_created_idx on entries (actual time=0.030..0.036 rows=20 loops=1)
Execution Time: 0.058 ms
SELECT transfer('fast-1', 500, 501, 100, 'timing test');
Time: 3.712 ms
The sort has vanished from the second plan: the index already hands rows back newest first. Indexes are not free, though. They take space and make every write a little slower:
SELECT pg_size_pretty(pg_relation_size('entries')) AS entries,
pg_size_pretty(pg_relation_size('entries_account_created_idx')) AS account_idx,
pg_size_pretty(pg_relation_size('entries_transfer_idx')) AS transfer_idx;
entries | account_idx | transfer_idx
---------+-------------+--------------
65 MB | 7176 kB | 19 MB
Phase 3 done
Here is the scoreboard from the runs above. Yours will differ, but the shape should match:
| Query | Before | After |
|---|---|---|
| Balance of one account | 42 ms (full table scan) | 0.26 ms (index scan) |
| Latest 20 entries | 40 ms (scan and sort) | 0.06 ms (index scan) |
One transfer() call | 60 ms | 3.7 ms |
Same data, same queries, a hundred times faster, for the price of about 26 MB of indexes.