Skip to Content
Mengty Learns
Architecture

Transactions, Isolation Levels & Locking

Understand ACID guarantees, PostgreSQL isolation levels (Read Committed, Repeatable Read, Serializable), lost updates, optimistic vs pessimistic locking, and deadlocks.

explanationintermediateTested with postgresql 19.x (docs)Updated Nov 27, 2026

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

TL;DR

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 ... COMMIT block succeeds, or ROLLBACK undoes 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 COMMIT returns, 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 levelPreventsStill allowsCost / behavior
Read Committed (default)Dirty readsNon-repeatable reads, phantom reads, lost updates on read-then-writeLowest overhead; each query gets a fresh snapshot
Repeatable ReadDirty, non-repeatable, and phantom reads; lost updatesWrite skew (two transactions read overlapping sets and update disjoint rows)Transaction-level snapshot; concurrent write to same row aborts with 40001
SerializableAll of the above, including write skewNone (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 (version column): Read the row with version = 5, compute the new state, and run UPDATE accounts SET balance = $1, version = 6 WHERE id = $2 AND version = 5. If rowCount === 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

Overview of Lost Update Race vs Pessimistic Row Lock. 6 steps.
Overview6 steps in this flow

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 retry

When 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 explicit FOR UPDATE or SERIALIZABLE transaction—PostgreSQL's single-statement row lock already serializes it.
  • Append-only analytics or read-only pages: Static reads don't need SERIALIZABLE or row locks.
  • Cost / complexity trade-off: Stronger isolation (SERIALIZABLE) and pessimistic locks eliminate subtle data corruption bugs at the cost of lock wait contention or 40001 retry logic in application code.

When to use / when to avoid

When to use
  • 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.
When to avoid
  • 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

Pros
  • Prevents silent lost updates, negative balances, and broken invariants under concurrency.
  • Optimistic locking avoids holding DB locks across slow user think time.
Cons
  • 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