Two withdrawals both read balance 100. How do you stop overdrafts?
Question
An accounts(id, balance) wallet starts at (1, 100). Two concurrent requests call withdraw(conn, 1, 60) and withdraw(conn, 1, 70) against the same database.
- Explain how the starter
withdrawloses an update (leaving30or40while approving130total) or fails withSQLITE_BUSY_SNAPSHOTunder SQLiteBEGIN DEFERRED. Also explain how an unguardedSET balance = balance - ?overdrafts to-30. - Fix
withdrawwith an atomic guardedUPDATEand aCHECK (balance >= 0)constraint, using two SQLite WAL connections in a temporary directory. - Compare SQLite
BEGIN IMMEDIATEwith PostgreSQLREAD COMMITTED(SELECT ... FOR UPDATE) andREPEATABLE READ.
def withdraw(conn, account_id, amount): row = conn.execute( "SELECT balance FROM accounts WHERE id = ?", (account_id,), ).fetchone() if row is None or row[0] < amount: return False conn.execute( "UPDATE accounts SET balance = ? WHERE id = ?", (row[0] - amount, account_id), ) conn.commit() return True
Show hints (3)
- "SPOT THE GAP"
Between
SELECTandUPDATE, another connection can commit a withdrawal. Both requests read100and passrow[0] >= amountbefore either writes. - "MOVE THE GUARD"
Combine the check and debit in one statement:
UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?. Inspectcursor.rowcount. - "COMPARE LOCKING MODELS"
SQLite takes a database write lock with
BEGIN IMMEDIATE. PostgreSQL uses row locks (SELECT ... FOR UPDATE) underREAD COMMITTED, or aborts stale writes with40001underREPEATABLE READ.
Show checked explanation
Move the balance check into one atomic UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ? and add CHECK (balance >= 0). Return cursor.rowcount == 1. That removes the read-then-write race in both SQLite and PostgreSQL READ COMMITTED.
from contextlib import closing import sqlite3 import tempfile def withdraw(conn, account_id, amount): q = "UPDATE accounts SET balance=balance-? WHERE id=? AND balance>=?" with conn: return conn.execute(q, (amount, account_id, amount)).rowcount == 1 with tempfile.TemporaryDirectory() as d: with (closing(sqlite3.connect(f"{d}/w.db", timeout=5.0)) as c1, closing(sqlite3.connect(f"{d}/w.db", timeout=5.0)) as c2): c1.executescript( "PRAGMA journal_mode=WAL; CREATE TABLE accounts (id INT PRIMARY " "KEY, balance INT NOT NULL CHECK (balance >= 0)); " "INSERT INTO accounts VALUES (1, 100);") print(withdraw(c1, 1, 60), withdraw(c2, 1, 70), c1.execute("SELECT balance FROM accounts").fetchone()[0])
True False 40
Author-checked on SQLite 3.49.1 and CPython 3.12.10: ran the starter lost-update race, unguarded overdraft, BEGIN DEFERRED SQLITE_BUSY_SNAPSHOT failure, guarded atomic UPDATE, and BEGIN IMMEDIATE across two WAL connections in a temporary directory. PostgreSQL semantics checked against official documentation. Checked by an editor other than the author.
Walkthrough
When two requests run the starter at once, both read balance = 100 and pass the Python check (100 >= 60 and 100 >= 70). What breaks next depends on the transaction model:
- Autocommit reads (or PostgreSQL
READ COMMITTEDwithout row locks): Request 1 writes40. Request 2 overwrites it with30. Both returnTrueand dispense130from100(a lost update). If both instead ranSET balance = balance - ?without a guard orCHECK, the balance would overdraft to-30. - SQLite
BEGIN DEFERREDin WAL mode: Each connection opens a read snapshot atSELECT. After Request 1 commits40, Request 2 tries to upgrade its stale snapshot to a write lock. SQLite fails it immediately withSQLITE_BUSY_SNAPSHOT(database is locked), ignoringbusy_timeout, because retrying cannot change its open snapshot.
Why the guarded UPDATE works. One UPDATE ... SET balance = balance - ? WHERE id = ? AND balance >= ? checks and debits under SQLite's write lock. Under PostgreSQL READ COMMITTED, the second UPDATE waits for the first row lock, then re-evaluates WHERE balance >= 70 on the committed 40, finds false, and updates 0 rows. CHECK (balance >= 0) protects the schema against any buggy query.
Multi-statement transactions. When a withdrawal must also insert a ledger row, lock before reading. In SQLite, start with BEGIN IMMEDIATE so the second writer waits on busy_timeout and then reads 40:
BEGIN IMMEDIATE; UPDATE accounts SET balance = balance - 60 WHERE id = 1 AND balance >= 60; COMMIT;
| Strategy | Engine | Concurrent 60 + 70 from 100 |
|---|---|---|
Guarded UPDATE + CHECK | SQLite & PostgreSQL READ COMMITTED | One gets rowcount = 1, other gets 0, balance 40 or 30 |
BEGIN IMMEDIATE + busy_timeout | SQLite WAL | Second writer waits, reads committed 40, rejects 70 |
SELECT ... FOR UPDATE | PostgreSQL READ COMMITTED | Row lock blocks second FOR UPDATE until commit, then returns 40 |
Snapshot + retry on 40001 | PostgreSQL REPEATABLE READ | Second writer aborts with 40001; app retries and rejects 70 |
Common mistakes
- Checking
if balance >= amountin Python after a plainSELECT. Two concurrent requests both read100and approve130total. - Using SQLite
BEGIN DEFERREDfor read-modify-write transactions. Two readers upgrading to writers hitSQLITE_BUSY_SNAPSHOTinstead of waiting onbusy_timeout. - Omitting
CHECK (balance >= 0)onaccounts. One unguardedUPDATEelsewhere in the codebase can silently overdraft the wallet to-30. - Assuming PostgreSQL
REPEATABLE READretries conflicts automatically. It raises SQLSTATE40001, so your code must roll back and retry.
Follow-up questions
- "How does PostgreSQL SELECT ... FOR UPDATE differ from SQLite BEGIN IMMEDIATE?"
SELECT ... FOR UPDATElocks only matching rows, so other accounts update in parallel. SQLite allows one writer per database file, soBEGIN IMMEDIATElocks the whole database for writes while WAL readers continue. - "What if a transfer debits account 1 and credits account 2 in one transaction?" In PostgreSQL, lock both rows in a fixed primary-key order (lowest
idfirst) withSELECT ... FOR UPDATE. That prevents deadlocks when two opposite transfers run at once. - "How do you prevent a timed-out client retry from debiting the wallet twice?" Record an idempotency key in a ledger table inside the same transaction as the guarded
UPDATE. Retries then detect the committed key instead of debiting again.
What a strong answer covers
Replaces check-then-update with one guarded UPDATE plus CHECK (balance >= 0), explains SQLite BEGIN DEFERRED snapshot failures versus BEGIN IMMEDIATE, and contrasts PostgreSQL READ COMMITTED row locks with REPEATABLE READ 40001 retries.
Open in interactive practice deck →