download

Two withdrawals both read balance 100. How do you stop overdrafts?

SQL~12 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Explain how the starter withdraw loses an update (leaving 30 or 40 while approving 130 total) or fails with SQLITE_BUSY_SNAPSHOT under SQLite BEGIN DEFERRED. Also explain how an unguarded SET balance = balance - ? overdrafts to -30.
  2. Fix withdraw with an atomic guarded UPDATE and a CHECK (balance >= 0) constraint, using two SQLite WAL connections in a temporary directory.
  3. Compare SQLite BEGIN IMMEDIATE with PostgreSQL READ COMMITTED (SELECT ... FOR UPDATE) and REPEATABLE READ.
"CODE · PYTHON"
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)
  1. "SPOT THE GAP"

    Between SELECT and UPDATE, another connection can commit a withdrawal. Both requests read 100 and pass row[0] >= amount before either writes.

  2. "MOVE THE GUARD"

    Combine the check and debit in one statement: UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?. Inspect cursor.rowcount.

  3. "COMPARE LOCKING MODELS"

    SQLite takes a database write lock with BEGIN IMMEDIATE. PostgreSQL uses row locks (SELECT ... FOR UPDATE) under READ COMMITTED, or aborts stale writes with 40001 under REPEATABLE 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.

"SOLUTION · PYTHON"
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])
"OUTPUT"
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 COMMITTED without row locks): Request 1 writes 40. Request 2 overwrites it with 30. Both return True and dispense 130 from 100 (a lost update). If both instead ran SET balance = balance - ? without a guard or CHECK, the balance would overdraft to -30.
  • SQLite BEGIN DEFERRED in WAL mode: Each connection opens a read snapshot at SELECT. After Request 1 commits 40, Request 2 tries to upgrade its stale snapshot to a write lock. SQLite fails it immediately with SQLITE_BUSY_SNAPSHOT (database is locked), ignoring busy_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:

"SQL"
BEGIN IMMEDIATE;
UPDATE accounts SET balance = balance - 60 WHERE id = 1 AND balance >= 60;
COMMIT;
StrategyEngineConcurrent 60 + 70 from 100
Guarded UPDATE + CHECKSQLite & PostgreSQL READ COMMITTEDOne gets rowcount = 1, other gets 0, balance 40 or 30
BEGIN IMMEDIATE + busy_timeoutSQLite WALSecond writer waits, reads committed 40, rejects 70
SELECT ... FOR UPDATEPostgreSQL READ COMMITTEDRow lock blocks second FOR UPDATE until commit, then returns 40
Snapshot + retry on 40001PostgreSQL REPEATABLE READSecond writer aborts with 40001; app retries and rejects 70

Common mistakes

  • Checking if balance >= amount in Python after a plain SELECT. Two concurrent requests both read 100 and approve 130 total.
  • Using SQLite BEGIN DEFERRED for read-modify-write transactions. Two readers upgrading to writers hit SQLITE_BUSY_SNAPSHOT instead of waiting on busy_timeout.
  • Omitting CHECK (balance >= 0) on accounts. One unguarded UPDATE elsewhere in the codebase can silently overdraft the wallet to -30.
  • Assuming PostgreSQL REPEATABLE READ retries conflicts automatically. It raises SQLSTATE 40001, so your code must roll back and retry.

Follow-up questions

  • "How does PostgreSQL SELECT ... FOR UPDATE differ from SQLite BEGIN IMMEDIATE?" SELECT ... FOR UPDATE locks only matching rows, so other accounts update in parallel. SQLite allows one writer per database file, so BEGIN IMMEDIATE locks 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 id first) with SELECT ... 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 →

Original OfferVibe question. SQLite Transactions · SQLite Isolation · SQLite SQLITE_BUSY_SNAPSHOT · PostgreSQL Transaction Isolation · Python sqlite3 Transactions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.