The first two articles were about correctness: zero values, errors, transactions committed in strange places, and flow bugs that nobody could see. This one is about numbers, and the number is embarrassing.
After the user transaction service was rewritten and cut over, everything was correct. Characterisation tests passed, no orphan events remained, and not one of the flow bugs came back. Then I ran a load test, and the result was 10.2 transactions per second.
Not 10,200. Ten. With sixty concurrent clients, a p99 of two thousand four hundred milliseconds, and the most annoying part of all: the database was sitting at twelve percent CPU. It was not busy. It was waiting.
Peak demand was already four hundred and eighty transactions per second. Which means this service was not just slow, it had been failing to meet demand for a long time, and the queue was being hidden by clients silently retrying.
Ten RPS, and a database that was not busy
The first thing I did was stop guessing and start measuring. Three tools were enough:
-- who is waiting on what
SELECT wait_event_type, wait_event, count(*)
FROM pg_stat_activity
WHERE state <> 'idle'
GROUP BY 1, 2
ORDER BY 3 DESC;
-- which rows are being fought over
SELECT relation::regclass, mode, count(*)
FROM pg_locks
WHERE NOT granted
GROUP BY 1, 2
ORDER BY 3 DESC
LIMIT 20;
And from Go, pprof with the block profile, not cpu. The CPU profile for this service was nearly empty: less than one core was doing any work. What was full was waiting, and waiting does not show up in a CPU profile.
The measurements:
- 71 percent of request time was spent waiting for locks.
- Of all balance updates, 84 percent touched three rows. Three wallets.
- One audit insert took 8 ms, and the audit table had six indexes over one point two billion rows.
- One commit spent 1.1 ms just on
fsync. - The connection pool was set to 100 while the database’s
max_connectionswas 40. The rest queued inside the pool, invisible in every metric I had.
Those three wallets were not a coincidence. One was the platform’s collection wallet, one was a large merchant wallet, and one was the settlement account. Every user transaction coming through the payment gateway ended up touching one of them. So even with ten thousand distinct users, the write path narrowed to three rows.
And here is where my first mistake lived: I thought this was a database problem. It was a design problem. One balance row means one writer at a time. That is not a property of PostgreSQL, it is arithmetic. No database can run two updates to the same row concurrently without making the result untrustworthy.
Three roads I took, all dead ends
Before reaching the right answer I spent almost four weeks on three approaches that all sound reasonable on paper. I am writing them down not to look persistent, but because I suspect a lot of teams are repeating them right now.
Attempt one: sub-balances
The idea is simple: if one balance row is contested, split it. A single wallet balance is represented by thirty-two rows, each holding part of the money. A debit touches one sub-balance chosen in rotation, so thirty-two transactions can proceed at once.
CREATE TABLE wallet_sub_balance (
wallet_id BIGINT NOT NULL,
bucket_no SMALLINT NOT NULL,
amount BIGINT NOT NULL,
PRIMARY KEY (wallet_id, bucket_no)
);
The result was real: throughput went from 10 to 90 RPS. Almost nine times. I was happy for about two days.
Then the problems arrived one at a time, and all of them were about money that has to add up.
Buckets run empty. One debit in seven found its chosen bucket short, and had to move funds from another bucket. That move needed two more locks, and under load the “fast” debit became three operations.
The balance became an aggregate. Every balance read turned into a SUM over thirty-two rows. p99 balance read climbed to 300 ms, and the app’s home screen calls it on every refresh.
Reconciliation exploded. The nightly job that used to take four hours took nine, because it now had to match thirty-two times as many rows against the external ledger.
And the decisive one: audit was still serial. After sub-balances, the 71 percent of waiting dropped to 34, but the rest moved to the audit insert that still ran synchronously inside the same transaction. So even with the balance no longer contested, throughput stayed pinned in the nineties. I added parallelism in one place and the bottleneck moved to another. That pattern would repeat twice more.
Attempt two: locking in the database
If the row is contested, lock it earlier and harder. That was my first instinct.
BEGIN;
SELECT amount FROM wallet WHERE id = $1 FOR UPDATE;
UPDATE wallet SET amount = amount - $2 WHERE id = $1;
INSERT INTO audit_log (...) VALUES (...);
COMMIT;
This had been there since the Java version, so nothing new. What I added was an advisory lock so two requests for the same wallet would not even reach the row lock queue:
SELECT pg_advisory_xact_lock(hashtext('wallet:' || $1));
The result: 10 to 12 RPS. In numbers, nothing meaningful changed.
What changed was the kind of failure. For transfers between wallets, two requests could lock two rows in opposite order:
Request A: lock wallet 17, then wallet 42
Request B: lock wallet 42, then wallet 17
Deadlock. PostgreSQL detects it and aborts one transaction, so no data is corrupted, but it produced 14 deadlocks per hour, each triggering a retry. A retry means doing the same work twice, on a system already saturated.
The textbook fix, order locks by wallet id, did remove the deadlocks. Throughput stayed the same, because the problem was never the order. The problem was that the number of writers per row was still one.
Attempt three: locking in Redis
This is the one that looks most convincing in an architecture diagram, and disappointed the most in production.
func (l *Locker) Acquire(ctx context.Context, key string, ttl time.Duration) (string, error) {
token := uuid.NewString()
ok, err := l.rdb.SetNX(ctx, key, token, ttl).Result()
if err != nil {
return "", fmt.Errorf("acquire lock: %w", err)
}
if !ok {
return "", ErrLockBusy
}
return token, nil
}
With release through Lua so we never delete somebody else’s lock:
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
Throughput: 11 RPS. Up by one.
What I got in exchange was three new problems.
An extra network hop. Every transaction now needed two round trips to Redis before touching the database, and the lock still had to be waited for. I had not removed the queue, I had moved it further away.
The lock could vanish mid-work. A three-second TTL, and one GC pause or one slow query is enough to outlive it. My logs recorded six lock-lost events per day. In staging, one of those ended in a double debit, and I only found it because an invariant test happened to compare total balance against the ledger. It never happened in production, because we stopped before it could.
And most importantly: a distributed lock adds no parallelism. It only guarantees that one person works at a time. If the work itself takes 90 ms, you still get eleven per second. There is no way to lock your way to speed.
The thing I was locking was a queue
After three failures I rewrote the question. Not “how do I lock faster”, but “why does this transaction need a lock at all”.
The answer was in the definition of the work. One transaction, in both the Java and Go versions, did five things in sequence inside a single database transaction:
- Read the balance.
- Compute the new balance.
- Write the new balance to the same row.
- Write the audit record.
- Commit, which means one
fsync.
Four of those five did not need to be on the critical path. Step 3 existed because we stored state, when what we actually had was events. Step 4 existed because audit was treated as part of the transaction, when audit is a record, not a precondition for money moving. Step 5 was repeated for every transaction, when one fsync can protect two hundred.
The fix that finally worked has four parts, and not one of them is a smarter lock.
Ledger, not balance
The first and largest change: stop updating the balance on the transaction path.
A balance is the sum of events. If I store the events, I do not need to update the result on every transaction. All I need is a fast way to read it.
CREATE TABLE ledger_entries (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
wallet_id BIGINT NOT NULL,
direction SMALLINT NOT NULL, -- 1 debit, -1 credit
amount BIGINT NOT NULL,
kind TEXT NOT NULL,
reference TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX ledger_idempotency_idx
ON ledger_entries (wallet_id, idempotency_key);
Now the write path is only INSERT. No row is updated, so nothing is contested. Two transactions for the same wallet can land at the same time because both write new rows on different pages, and PostgreSQL does not need to make either wait.
The important part is that unique index: idempotency is no longer guarded by a lock, it is enforced by a constraint. If a client sends the same Idempotency-Key twice, the second one produces no row.
INSERT INTO ledger_entries (wallet_id, direction, amount, kind, reference, idempotency_key)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (wallet_id, idempotency_key) DO NOTHING
RETURNING id;
For transfers between wallets, two entries are still written in one transaction, because money must not appear in two places. What changed: two INSERTs on two different rows, instead of two UPDATEs on the same rows. Deadlocks disappeared on their own, because there is no locked row to wait for.
The balance itself is projected by a separate job:
CREATE TABLE balance_projection (
wallet_id BIGINT PRIMARY KEY,
amount BIGINT NOT NULL,
last_ledger_id BIGINT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
WITH delta AS (
SELECT wallet_id,
sum(direction * amount) AS change,
max(id) AS last_id
FROM ledger_entries
WHERE id > $1
GROUP BY wallet_id
)
INSERT INTO balance_projection (wallet_id, amount, last_ledger_id)
SELECT wallet_id, change, last_id FROM delta
ON CONFLICT (wallet_id) DO UPDATE
SET amount = balance_projection.amount + EXCLUDED.amount,
last_ledger_id = EXCLUDED.last_ledger_id,
updated_at = now();
The job runs every two hundred milliseconds, processes a batch, and stores its cursor. Because one projection row is only touched by one job, there is no contention at all. It is also the first place in this project where a bulk UPDATE turned out to be cheaper than per-transaction updates: one statement for thousands of entries, one fsync.
The consequence has to be accepted deliberately: a balance read from the projection can lag by up to two hundred milliseconds. For history pages and reports that is fine. For the “my balance right now” screen just after a user transacts, it is not, and the answer to that is in the next section.
Redis to prevent, not to lock
Redis did end up in the design, but not as a lock. It is a guard that keeps a balance from ever going negative, and crucially, that guard never makes the caller wait.
var debitGuard = redis.NewScript(`
local bal = tonumber(redis.call("GET", KEYS[1]))
if bal == nil then
return -1 -- cache miss, let the database decide
end
local amount = tonumber(ARGV[1])
if bal < amount then
return 0 -- insufficient funds
end
redis.call("DECRBY", KEYS[1], amount)
return 1
`)
Three possible outcomes, none of which is “wait”: -1 means the cache does not know, so the request goes to the slower but correct database path; 0 means rejected; 1 means proceed.
The difference from a lock is fundamental. A lock asks “may I come in?”, and if the answer is no, the caller waits or fails. This script asks “is the balance sufficient?”, answers immediately, and changes the number in one atomic operation. There is no lock owner, no TTL, no lock to lose. If Redis dies, every request falls through to -1 and the system stays correct, only slower. That is a property no lock ever gave me.
To read a balance right after writing, I do not wait for the projection. The Redis value was already decremented at debit time, so the number the user sees matches their own transaction even while the database projection is a few hundred milliseconds behind. On a cache miss, the read falls back to the projection and the user may see a slightly stale number. That is the trade-off I chose and wrote into the docs: read-your-writes for the writer, eventually consistent for everyone else.
One writer per wallet
With the ledger, no row is contested. But one thing can still wreck everything: an fsync per commit, and a database connection queue if every request commits on its own.
The answer has two layers, and both are about collecting work, not locking.
First, a single writer per wallet inside the process. Not a lock, but a rule about who may work: each wallet maps to one of sixty-four goroutines by hash, so operations for one wallet are always ordered without any database lock.
type Router struct {
shards [64]chan entry
}
func (r *Router) Send(ctx context.Context, e entry) error {
shard := fnv32(e.WalletID) % uint32(len(r.shards))
select {
case r.shards[shard] <- e:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
Second, group commit. Each goroutine collects entries for a one-millisecond window or until it has two hundred, then writes them all in one transaction.
func (w *writer) run(ctx context.Context) {
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
buf := make([]entry, 0, 200)
flush := func() {
if len(buf) == 0 {
return
}
if err := w.insertBatch(ctx, buf); err != nil {
w.log.Error("insert batch failed", "count", len(buf), "err", err)
}
buf = buf[:0]
}
for {
select {
case e := <-w.in:
buf = append(buf, e)
if len(buf) == cap(buf) {
flush()
}
case <-ticker.C:
flush()
case <-ctx.Done():
flush()
return
}
}
}
The result: commits per second dropped from ten to five, while transactions per second went up a hundredfold. One fsync now protects two hundred entries, so that 1.1 ms is amortised into almost nothing.
One thing to guard: because the response is sent only after the batch commits, the minimum latency for a single transaction is now about one millisecond instead of zero. I pay that happily, because p99 went from two thousand four hundred milliseconds to forty-five.
Audit that does not have to wait
That 8 ms audit insert was not because the table was big. It was because six indexes had to be updated per row, and the table was never partitioned. Checking pg_stat_user_indexes, four of the six indexes had never been used once in thirty days.
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE relname = 'audit_log'
ORDER BY idx_scan;
What I did:
- Partitioned the audit table by month, so its indexes stay small and inserts stop touching cold index pages.
- Dropped the four unused indexes. Inserts went from 8 ms to 0.9 ms.
- Wrote audit through the same batch as the ledger, so one
fsynccovers both. Down to 0.4 ms per row. - Moved audit reads to a replica, and heavy report queries to a warehouse, off the transaction database.
What I did not do: send audit to Kafka synchronously inside the request. That would bring back the problem I fixed in part two, with a fancier name.
The consistency I accepted
Every change above has a price, and I would rather write it down than pretend otherwise.
| What changed | Guarantee now |
|---|---|
| Balance read from projection | Up to 200 ms behind for other readers |
| Debit validated in Redis | If Redis is down, validation falls back to the database (slower, still correct) |
| Ledger is the source of truth | Every balance correction must be a new entry, never an UPDATE |
| Response sent after batch commit | Minimum latency ~1 ms per transaction |
| Audit partitioned by month | Cross-month queries are slower, moved to the warehouse |
One thing I refused from the start: turning synchronous_commit off for the balance table. That would raise throughput very easily, and it would also mean a transaction reported as successful can vanish if the server dies. If I need that much speed, I would rather change the design than change the promise made to users.
Reconciliation still runs nightly, and it is now a more useful tool: because the ledger is never mutated, every gap between projection and ledger means a bug, not the side effect of updates overwriting each other.
Numbers
All measured on a single 8-vCPU node, PostgreSQL 16, load replayed from production logs and scaled up until clients began retrying:
| Metric | Before | After |
|---|---|---|
| Sustained throughput | 10 RPS | 1,150 RPS |
| p99 transaction | 2,400 ms | 45 ms |
| Lock wait | 1,800 ms average | 0 |
| Commits per second | 10 | 5 (200 entries per batch) |
| Audit insert | 8 ms | 0.4 ms |
| Database CPU | 12% | 38% |
| Deadlocks | 14 per hour | 0 |
| Balance lag | 0 | ≤200 ms |
And the table I find more honest, the three failed attempts:
| Attempt | Result | Cause |
|---|---|---|
| Sub-balances, 32 buckets | 10 → 90 RPS | Rebalancing, balance became an aggregate, audit still serial |
| Row lock + advisory lock | 10 → 12 RPS | Queue moved to the lock manager, 14 deadlocks per hour |
| Redis lock | 10 → 11 RPS | Extra hop, lock could be lost, no added parallelism |
One thing worth stating plainly: the Go version was also 10 RPS before this design change. I rewrote the service in a faster language and got exactly the same number, because the bottleneck was never the runtime. Had I stopped there and blamed Go, I would have written the wrong article.
What I would do differently
Measure waiting time from day one, not just CPU. The CPU profile for this service was empty, and that was the clue. Low CPU with high latency means the problem is not capacity, and adding servers will not help.
Count writers per row, not requests per second. The useful number was not “a thousand requests”, it was “three rows receive 84 percent of updates”. From there the decision becomes obvious.
Do not store state when what you have is events. A ledger is not a fintech-specific pattern. Whenever a number is continuously updated and its history also matters, writing events and projecting the result is almost always cheaper.
Treat a lock as a symptom of a queue, not as a tool. Every lock I added only moved the queue somewhere else. What actually removed the queue was reducing what had to happen inside the boundary.
Test with clients that retry. Ten RPS looks like twenty if half the requests are retries. My first load test was wrong because it did not model real client behaviour, and the initial number looked better than reality.
Closing
Of this whole rewrite, this part changed how I design the most. Not because I learned a new trick, but because I learned that the three “tricks” I trusted only moved the problem: sub-balances moved it to reconciliation, row locks moved it to the lock manager, and the Redis lock moved it to the network.
A Lock Never Made Anything Faster
If your service is stuck at a number that makes no sense while the database sits idle, do not look for a better lock. Find out what work you are actually locking. In my case the answer was a balance that should not have been updated on the transaction path, an audit record that should not have been waited for, and a commit that should not have happened a hundred times per second. Once all three left the critical path, ten transactions per second became one thousand one hundred and fifty, and I did not add a single lock to get there. 🐹
Comments
comments powered by Disqus