Transactions, Isolation Levels & Locking
Understand ACID guarantees, PostgreSQL isolation levels (Read Committed, Repeatable Read, Serializable), lost updates, optimistic vs pessimistic locking, and deadlocks.
TL;DR
ACID transactions group reads and writes into an all-or-nothing unit. PostgreSQL defaults to Read Committed, which allows lost updates on read-modify-write flows unless you use SELECT ... FOR UPDATE, optimistic version checks, or REPEATABLE READ / SERIALIZABLE with automatic retry on 40001.
Intent
Choose the right isolation level and locking strategy to prevent race conditions like lost updates and write skew without stalling concurrent throughput or causing deadlocks.
Problem
Two concurrent requests read balance = 100, subtract $20 and $30 in application code, and write 80 and 70 back to the database. Under default READ COMMITTED isolation, both COMMITs succeed—and $20 vanishes silently.
Solution
1. ACID in plain words
- Atomicity: Either every statement in the
BEGIN ... COMMITblock succeeds, orROLLBACKundoes all of them. - Consistency: Constraints (
CHECK,UNIQUE, foreign keys) hold at commit time. - Isolation: Controls what concurrent transactions can see of each other's uncommitted or newly committed writes.
- Durability: Once
COMMITreturns, writes are flushed to the WAL and survive crashes.
2. PostgreSQL isolation levels
PostgreSQL never allows dirty reads (reading uncommitted data), even at READ UNCOMMITTED (which behaves like READ COMMITTED in Postgres):
| Isolation level | Prevents | Still allows | Cost / behavior |
|---|---|---|---|
| Read Committed (default) | Dirty reads | Non-repeatable reads, phantom reads, lost updates on read-then-write | Lowest overhead; each query gets a fresh snapshot |
| Repeatable Read | Dirty, non-repeatable, and phantom reads; lost updates | Write skew (two transactions read overlapping sets and update disjoint rows) | Transaction-level snapshot; concurrent write to same row aborts with 40001 |
| Serializable | All of the above, including write skew | None (equivalent to serial execution) | Uses Serializable Snapshot Isolation (SSI); highest 40001 retry rate under contention |
3. Optimistic vs pessimistic locking
- Pessimistic (
SELECT ... FOR UPDATE): Locks the target row immediately so concurrent updaters wait in line. Best when contention is high and transactions are short (e.g., inventory or wallet balance). - Optimistic (
versioncolumn): Read the row withversion = 5, compute the new state, and runUPDATE accounts SET balance = $1, version = 6 WHERE id = $2 AND version = 5. IfrowCount === 0, someone else updated it first—retry. Best when conflicts are rare or a user edits a form over seconds.
4. Deadlocks
A deadlock occurs when Transaction A locks row 1 and waits for row 2, while Transaction B locks row 2 and waits for row 1. PostgreSQL's deadlock detector breaks the cycle after deadlock_timeout (default 1s) by aborting one transaction with SQLSTATE 40P01. Prevent deadlocks by always locking rows in a consistent order (e.g., ORDER BY id ASC).
Real-world analogy
▶ Flow: watch it work
Lost Update Race vs Pessimistic Row Lock
Press Start or tap any step dot to trace the path.
▸All steps (6)
Code
Compare a pessimistic FOR UPDATE transaction against an optimistic version update in SQL:
-- Pessimistic: lock the row for the duration of a short transaction (not run)
BEGIN;
SELECT balance_cents FROM accounts WHERE id = $1 FOR UPDATE;
UPDATE accounts SET balance_cents = balance_cents - $2 WHERE id = $1;
COMMIT;
-- Optimistic: no lock held during read; check version on write (not run)
UPDATE accounts
SET balance_cents = $1, version = version + 1
WHERE id = $2 AND version = $3;
-- If affected rows = 0, another writer won -> re-read and retryWhen you DON'T need this
- Single-statement atomic updates: If you can write
UPDATE accounts SET balance_cents = balance_cents - $1 WHERE id = $2 AND balance_cents >= $1, you don't need an explicitFOR UPDATEorSERIALIZABLEtransaction—PostgreSQL's single-statement row lock already serializes it. - Append-only analytics or read-only pages: Static reads don't need
SERIALIZABLEor row locks. - Cost / complexity trade-off: Stronger isolation (
SERIALIZABLE) and pessimistic locks eliminate subtle data corruption bugs at the cost of lock wait contention or40001retry logic in application code.
When to use / when to avoid
- Use atomic SQL updates or SELECT ... FOR UPDATE for short read-modify-write flows on balances or inventory.
- Use optimistic version checks for multi-step user edits across HTTP requests.
- Never hold a database transaction open while calling an external HTTP API or waiting for user input.
- Never enable SERIALIZABLE without adding a bounded retry loop for SQLSTATE 40001.
How to implement
Keep transactions short
Do HTTP calls, PDF generation, and slow I/O outside BEGIN ... COMMIT.
Pick the simplest concurrency guard
Prefer a single atomic UPDATE ... WHERE, then optimistic version, then FOR UPDATE or REPEATABLE READ / SERIALIZABLE.
Add bounded retries for 40001 and 40P01
Retry serialization (40001) and deadlock (40P01) errors with short jittered backoff (e.g., up to 3 attempts).
Pros / Cons
- Prevents silent lost updates, negative balances, and broken invariants under concurrency.
- Optimistic locking avoids holding DB locks across slow user think time.
- Pessimistic locks reduce concurrency on hot rows and can deadlock if lock order varies.
- Higher isolation levels require explicit retry handling in the application.
Relations
Check yourself
Check Yourself
1. Two transactions both read balance = 100 under PostgreSQL Read Committed, compute new values in app code, and issue UPDATE accounts SET balance = ... WHERE id = 1. What happens?
2. How do you prevent deadlocks when a transfer transaction locks both from_account and to_account?
Sources
Related Notes
Database Indexing & EXPLAIN ANALYZE
Understand B-tree indexes, composite column order, covering indexes with INCLUDE, write amplification trade-offs, and how to read PostgreSQL EXPLAIN ANALYZE.
ORM Pitfalls & When to Drop to SQL
Spot and fix N+1 queries, compare eager vs lazy loading, use raw-query escape hatches safely without SQL injection, and know when plain SQL wins.