DOUBLE SPEND

Two withdrawals, one balance, both approved

L215 MINMONEY
PREDICT

Tolu's Owoleaf wallet holds ₦10,000. Two ₦8,000 withdrawals arrive at the same moment. Each one runs SELECT balance, approves if the balance is at least ₦8,000, then runs UPDATE accounts SET balance = balance − 8000. Which final balances are possible?

A withdrawal has a funds check and a debit. The check is a read: is there enough? The debit is a write that depends on the answer. That is check-then-act with money in it. If two withdrawals both check before either debits, both see the same balance and both are approved.

The lost-update fix does not help here. With balance = balance − x no write is lost; both debits land, which is the problem. The fix is to make the check and the debit one step: a conditional UPDATE … WHERE balance >= x, a row lock held from the read to the commit, SERIALIZABLE isolation with a retry, or one writer per account so two withdrawals never run at once.

▶ SIMULATION
WITHDRAWAL A (₦8,000)
saw: —
idle
OWOLEAF LEDGER · Tolu, account 7
balance = ₦10,000
approved: ₦0 of ₦10,000
paid out by NIP: ₦0
row lock: free · queue: empty
WITHDRAWAL B (₦8,000)
saw: —
idle
✓ approved withdrawals ≤ the ₦10,000 in the wallet✓ balance never below ₦0
SCHEDULE
01[A]A: SELECT balance; approve if ≥ ₦8,000
02[B]B: SELECT balance; approve if ≥ ₦8,000
03[A]A: if approved: UPDATE SET balance = balance − 8000; pay out by NIP
04[B]B: if approved: UPDATE SET balance = balance − 8000; pay out by NIP
Start of double spend scenario. 4 steps.
-- Withdrawal A and B both run (autocommit):
SELECT balance FROM accounts WHERE id = 7;      -- both see 10000
-- app: 10000 >= 8000, approve
UPDATE accounts SET balance = balance - 8000
 WHERE id = 7;                                  -- atomic, and still -6000
INSERT INTO payouts ...;

Watch the two invariants. In DOUBLE SPEND, approved withdrawals ≤ ₦10,000 turns red at B’s check, before any money moves, and the balance goes red on the last debit. LUCKY TIMING passes only because B checked after A debited. Each FIX runs the same two requests at the same moment and ends at ₦2,000: in CONDITIONAL UPDATE the second statement matches 0 rows, in FOR UPDATE B waits for A’s lock and then sees ₦2,000, in SERIALIZABLE B’s UPDATE fails with a serialization error (SQLSTATE 40001 in PostgreSQL) and its retry declines, and in SINGLE WRITER one worker handles account 7’s requests in turn.

BREAK IT NOT YET

Tolu has ₦10,000. Each withdrawal checks the balance, then debits ₦8,000 with an atomic balance = balance − 8000. Order the four steps so the wallet ends below zero.

GOAL: both withdrawals finish and the balance is negative

FIX IT NOT YET

Rewrite withdraw so two concurrent ₦8,000 withdrawals never take the balance below ₦0, and both still succeed when the money is there. Return true if you debited. The grader starts from ₦10,000, ₦16,000 and ₦5,000 and tries every interleaving, checking the balance after every step.

In a real ledger the debit is a pair of journal entries, not a column update; payment ledger covers that. The rule is the same: the funds check reads the sum of the entries under the same lock or condition that writes the new ones. Add CHECK (balance >= 0) or its ledger equivalent as a backstop, so a code path that forgets the condition gets an error and not an overdrawn customer.

Mental model:

A funds check is a promise about money you have not taken yet. Two withdrawals can both be promised the same naira. Make the database keep the promise: the check and the debit are one step, either one conditional UPDATE, one locked transaction, or one writer per account. Atomic arithmetic alone moves money correctly; it does not decide whether the money should move.

IN PRODUCTION

Wallets and stored-value balances, gift cards, loyalty points, ad budgets, credit limits, inventory and seat holds, coupon redemption counts. Symptoms: a negative balance with every row in the audit log looking valid, usually after a burst of identical requests from one user, a double tap, or a retried job.

IN INTERVIEWS

“Two withdrawals hit the same account at once. Walk me through what can go wrong.” Name the interleaving (both read, both approve, both debit), point out that balance = balance − x alone does not stop it, and give the conditional UPDATE as the default fix. Then compare FOR UPDATE (simple, serialises the account), SERIALIZABLE (needs retries), and a single writer per account (high throughput per account, adds a queue). Mention a CHECK (balance >= 0) backstop and an idempotency key so a retried withdrawal is not a second one.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: AUTHORISE, CAPTURE, REFUND →