Skip to content
Commitwise
Menu
Databases

Transactions, isolation and locking

BEGIN, COMMIT and ROLLBACK, what happens after an error inside a transaction, isolation levels and the anomalies each one allows (lost updates, phantoms, write skew), SELECT FOR UPDATE, optimistic locking, deadlocks and SKIP LOCKED job queues. Database-level answers to every concurrency question.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A transfer debits one account and the server crashes before crediting the other. Two support agents edit the same order and one agent’s change silently disappears. Two doctors each check that someone else is on call, then both go home. A nightly job and a migration wait for each other until one is killed.

All of these are about transactions: how a database keeps several changes together, and what concurrent users can see of each other. This lesson covers it at the database level, with PostgreSQL behavior and notes on MySQL. How Spring’s @Transactional maps onto it (propagation, rollback rules, proxies) is in Transactions.

New to some of these? Open what you need, or skip ahead.

Basics:Changing data

INSERT, UPDATE and DELETE change rows; UPDATE … SET stock = stock - 1 WHERE id = 7 AND stock > 0 reads and changes a value in one step, and the database reports how many rows changed. See SQL basics.

Basics:What is a race condition?

A race condition is a bug where the result depends on the timing of threads: run the same code twice and get different answers. It usually happens when two threads read and change the same data at the same time. Races hide in tests, which rarely run things truly in parallel, and show up under production load.

Part Not started

Transactions: all or nothing

Moving 100 from account A to account B is two statements. If the server crashes between them, the money has left A and never reached B.

A transaction groups statements so they behave as one:

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;
  • BEGIN starts it.
  • COMMIT makes every change permanent at once. Other users see none of them before this moment, and all of them after.
  • ROLLBACK throws all of them away. So does a crash, or losing the connection, before COMMIT.

That’s the “A” in ACIDACIDAtomic, Consistent, Isolated, Durable: the guarantees a database transaction gives.Open in glossary →: atomic, all or nothing.

Without BEGIN, each statement is its own little transaction, committed immediately. That’s called autocommit, and it’s how most tools and drivers start.

Two habits:

  • Keep transactions short. While a transaction is open, the rows it changed stay locked, and others who want to change them wait.
  • Never wait for something slow inside a transaction: a user clicking a button, an email being sent, an HTTP call to a payment provider. Do that before or after.

Predict the output

In PostgreSQL, the INSERT fails with a unique-constraint error. What happens to the UPDATE on the next line?

BEGIN;
INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana');  -- email already exists
UPDATE products SET stock = stock - 1 WHERE id = 7;
COMMIT;
-- place an order: all three changes or none
BEGIN;
INSERT INTO orders (customer_id, total) VALUES (42, 19.80) RETURNING id;      -- say it returns 1001
INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (1001, 7, 2, 9.90);
UPDATE products SET stock = stock - 2 WHERE id = 7 AND stock >= 2;            -- 0 rows → ROLLBACK
COMMIT;

-- continue after an expected error
BEGIN;
SAVEPOINT before_tag;
INSERT INTO tags (name) VALUES ('sql');          -- may violate UNIQUE
ROLLBACK TO SAVEPOINT before_tag;                -- only if it failed
INSERT INTO lesson_tags (lesson_id, tag) VALUES (5, 'sql');
COMMIT;

Money that disappears

Spot the bugA transfer endpoint

Tap the line with the bug.

-- called by the app, autocommit is on
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';

-- the app logs the transfer, then:
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';

Deep diveIdle in transaction: the session that held a lock for an hourInterview favorite

At 14:02 every checkout starts timing out. pg_stat_activity shows hundreds of sessions waiting on a lock, all behind one session in state idle in transaction, open since 13:05. A developer had opened a transaction in a console, run UPDATE products SET … WHERE id = 7 to fix a typo, and gone to lunch. Product 7 is the bestseller; every order that touches it waits for that row lock, then the connection pool fills up, then the whole app stops.

The same shape appears in code: a request opens a transaction, updates a row, then calls a payment API that hangs for 60 seconds. Under load, the pool is exhausted by sessions doing nothing.

How to answer:

  • Find it: SELECT pid, state, xact_start, wait_event_type, query FROM pg_stat_activity ORDER BY xact_start and pg_blocking_pids(pid) to see who blocks whom. Terminate with pg_terminate_backend(pid).
  • Prevent it: idle_in_transaction_session_timeout (kill sessions idle inside a transaction after, say, 30 s), lock_timeout for app and migration roles, statement_timeout; autocommit or read-only defaults in consoles.
  • Design: no network calls inside transactions; reserve with a status (PENDING), call the provider outside, then confirm in a second short transaction (and reconcile with an outbox or job if the confirmation is lost).
  • Side effects: long transactions also stop vacuum from removing dead rows anywhere in the database, so a forgotten session causes bloat even without locks.
  • Statements autocommit unless inside BEGIN … COMMIT. A crash or disconnect before COMMIT rolls back.
  • PostgreSQL: an error aborts the whole transaction; use savepoints to recover. MySQL rolls back only the statement.
  • Long or idle transactions hold locks, pool connections and old row versions: idle_in_transaction_session_timeout, lock_timeout, statement_timeout.
  • No network calls inside transactions; one database per transaction, outbox/sagas across services.
SET lock_timeout = '2s';
BEGIN;
SAVEPOINT s1;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A' AND balance >= 100;
-- 0 rows? ROLLBACK; otherwise:
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;

Check this part

  1. The server crashes after the first of two UPDATEs inside BEGIN, before COMMIT. What is saved?

  2. Why not call a payment API inside a database transaction?

  3. In PostgreSQL, how do you continue a transaction after an expected unique violation?

  4. What does a session left "idle in transaction" for an hour cause?

A transaction groups statements so they all take effect at COMMIT or none do after ROLLBACK or a crash. Without BEGIN each statement is its own transaction. In PostgreSQL an error aborts the whole transaction until ROLLBACK; savepoints undo part of it. Keep transactions short and never wait on users or slow calls inside them.

Part Not started

Isolation levels and anomalies

Many transactions run at the same time. Isolation is about what one of them sees of the others while they’re still running. Perfect isolation (as if they ran one after another) is slow, so databases offer levels, each allowing some surprises.

The surprises, called anomalies:

  • Dirty read: you see another transaction’s change before it commits, and then it rolls back. You acted on data that never existed.
  • Non-repeatable read: you read a row twice in your transaction and get different values, because someone committed a change in between.
  • Phantom: you run the same query twice and get new rows the second time (“orders today” grew).
  • Lost update: two transactions read the same value, both change it, and one change overwrites the other.

The standard levels, from weakest to strictest:

LevelWhat you seeDefault in
Read Uncommittedeven uncommitted changes (PostgreSQL treats it as Read Committed)rarely used
Read Committedeach statement sees data committed before that statement startedPostgreSQL, Oracle, SQL Server
Repeatable Readthe whole transaction sees one snapshot from its first statementMySQL (InnoDB)
Serializablethe result is as if transactions ran one at a timeopt-in
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- ...
COMMIT;

Stricter levels are safer, but the database may refuse to commit a transaction that conflicts with another, and the app must then retry it.

How PostgreSQL implements the levels, which is what senior interviews probe:

  • Read Committed (default): a new MVCCMVCCMulti-version concurrency control: writers create new row versions so readers never wait for them.Open in glossary → snapshot per statement. An UPDATE that finds a row changed by a concurrent committed transaction re-evaluates its WHERE on the new version and proceeds. Lost updates are possible with app-side read-modify-write; single-statement updates (SET x = x - 1) are safe.
  • Repeatable Read = snapshot isolation: one snapshot per transaction, so no non-repeatable reads and, unlike the SQL standard’s minimum, no phantoms either. If you update a row that someone else changed after your snapshot, you get could not serialize access due to concurrent update (SQLSTATE 40001): lost updates are detected, not allowed. Write skew is still possible.
  • Serializable = Serializable Snapshot Isolation (SSI): tracks read/write dependencies and aborts one transaction (40001) when a cycle could make the result non-serializable. Low blocking, but expect retries, and reads in serializable transactions should be declared READ ONLY where possible.
  • MySQL InnoDB Repeatable Read (default) differs: plain SELECTs read a snapshot, but UPDATE, DELETE and locking reads (FOR UPDATE) see the latest committed rows and take next-key/gap locks to prevent phantoms. So “read in a snapshot, then update based on it” can still lose updates there.
  • Retrying must re-run the whole transaction (including the reads), with backoff and a cap; make it idempotent. Spring’s @Retryable around a @Transactional method, or a loop in the repository.
  • Isolation is not the only tool: often an atomic statement, a constraint, or explicit locking (next part) is simpler than raising the level.

Predict the output

PostgreSQL, default Read Committed. Transaction A reads Ana's balance (100). Meanwhile B sets it to 50 and commits. A reads it again in the same transaction. What does A see?

-- session A
BEGIN;
SELECT balance FROM accounts WHERE id = 'ana';   -- 100

    -- session B
    UPDATE accounts SET balance = 50 WHERE id = 'ana';   -- autocommit

SELECT balance FROM accounts WHERE id = 'ana';   -- ?
COMMIT;
-- a consistent report across several queries
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT count(*) FROM orders WHERE created_at >= date '2026-11-01';
SELECT sum(total) FROM orders WHERE created_at >= date '2026-11-01';   -- same snapshot, numbers agree
COMMIT;

-- a rule that spans several rows, with retry in the app on SQLSTATE 40001
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM shifts WHERE day = date '2026-11-15' AND on_call;
UPDATE shifts SET on_call = false WHERE doctor_id = 7 AND day = date '2026-11-15';
COMMIT;

Worked example: a lost update, step by step

Two support agents edit order 1001’s note at the same time. The app reads the order, the agent edits the text, the app writes it back.

TimeAgent A’s transactionAgent B’s transactionnote in the database
1reads note: “Leave at door”Leave at door
2reads note: “Leave at door”Leave at door
3writes “Leave at door. Fragile!” and commitsLeave at door. Fragile!
4writes “Leave at door. Ring twice” and commitsLeave at door. Ring twice
  1. Both read the same version at times 1 and 2. Neither has changed anything yet, so there’s nothing to block.
  2. A writes and commits at time 3. The database is happy: one row, one update.
  3. B writes and commits at time 4. B’s text was built from the version it read at time 2, which doesn’t include “Fragile!”.
  4. A’s change is gone. No error, no warning. The parcel isn’t marked fragile.
  5. The fix isn’t a different SQL statement, because the app combines the text. It’s detecting the conflict: optimistic locking with a version number (next part), or locking the row when it’s read for editing.
Deep diveWrite skew: two doctors go off callInterview favorite

Rule: at least one doctor must be on call each day. Two doctors, both on call, both feel ill and click “go off call” at the same moment. Each transaction runs:

BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM shifts WHERE day = '2026-11-15' AND on_call;   -- 2: fine, someone else stays
UPDATE shifts SET on_call = false WHERE day = '2026-11-15' AND doctor_id = $me;
COMMIT;

Both see 2, both update different rows, and there’s no write-write conflict for snapshot isolation to detect. Both commit; nobody is on call. This is write skew: each transaction’s decision was based on data the other changed.

Fixes, and when each fits:

  • SERIALIZABLE: PostgreSQL’s SSI notices that each transaction read what the other wrote and aborts one with 40001; the app retries it, sees 1, and refuses. The most general fix; requires retry logic everywhere it’s used.
  • Lock what you read: SELECT … FROM shifts WHERE day = … AND on_call FOR UPDATE locks both rows, so the second transaction waits and then sees the first one’s change (in Read Committed, re-run the count after acquiring the lock).
  • Materialize the conflict: a row per day (on_call_days(day, count)) that both transactions must update, turning write skew into an ordinary write-write conflict.
  • Constraint, when the rule fits one: uniqueness, exclusion constraints, or a CHECK on a counter row.

The classic examples to cite: meeting room double-booking, usernames claimed in two tables, a balance spread over several rows going negative.

  • PostgreSQL: Read Committed (default, per-statement snapshot), Repeatable Read (snapshot isolation, no phantoms, detects lost updates with 40001), Serializable (SSI, aborts with 40001). No dirty reads at any level.
  • MySQL InnoDB RR (default): snapshot for plain reads, latest rows + gap locks for writes and locking reads.
  • Write skew survives snapshot isolation: SERIALIZABLE, FOR UPDATE on what you read, a materialized conflict row, or a constraint.
  • Retry the whole transaction on 40001 with backoff; keep it idempotent.

Check this part

  1. What is a lost update?

  2. What is PostgreSQL's default isolation level?

  3. Under PostgreSQL REPEATABLE READ, you update a row another transaction changed and committed after your snapshot. What happens?

  4. Two transactions each read a count, then update different rows, breaking a rule across rows. What is it and what stops it?

Isolation levels decide what a transaction sees of concurrent ones: Read Committed sees each statement's latest committed data, Repeatable Read one snapshot, Serializable behaves like one-at-a-time. Weaker levels allow non-repeatable reads, phantoms, lost updates and write skew. PostgreSQL defaults to Read Committed, MySQL to Repeatable Read; stricter levels require retrying on serialization errors.

Part Not started

Locks: FOR UPDATE, optimistic locking and deadlocks

When a transaction changes a row, it locks that row until COMMIT or ROLLBACK. Another transaction that wants to change the same row waits. Readers don’t wait: they see the last committed version.

That covers single statements. For “read, decide, then write” there are two approaches:

Pessimistic locking: lock the row when you read it, so nobody can change it until you’re done.

BEGIN;
SELECT stock FROM products WHERE id = 7 FOR UPDATE;    -- others who want this row now wait
-- the app decides based on stock...
UPDATE products SET stock = stock - 2 WHERE id = 7;
COMMIT;

Optimistic locking: don’t lock; add a version column, and only write if nobody changed the row since you read it.

SELECT id, note, version FROM orders WHERE id = 1001;          -- version = 7

UPDATE orders SET note = 'Leave at door. Fragile!', version = version + 1
WHERE id = 1001 AND version = 7;                               -- 0 rows → someone else changed it

If the UPDATE changes 0 rows, the app tells the user “this order was changed, please reload”. Optimistic lockingOptimistic lockingDetecting that someone else changed a record since you read it, and failing your update instead of overwriting theirs.Open in glossary → suits screens where people edit for minutes; pessimistic locking suits short operations with a lot of competition for the same row.

Locks bring one danger, the deadlockDeadlockTwo transactions each hold a lock the other needs, so neither can continue.Open in glossary →. Transaction 1 locks row A and wants row B; transaction 2 locks row B and wants row A. Both wait forever. The database notices, cancels one of them with an error, and the other continues. The fix: always lock rows in the same order (for example, by id).

  • Row lock modes (PostgreSQL): FOR UPDATE (delete or change any column), FOR NO KEY UPDATE (taken by ordinary updates that don’t change keys; doesn’t block foreign key checks), FOR SHARE, FOR KEY SHARE (taken by FK checks). Inserting a child takes FOR KEY SHARE on the parent, which is why heavy child inserts can contend with FOR UPDATE on parents.
  • Waiting policy: NOWAIT fails immediately, SKIP LOCKED skips locked rows (queues, below), lock_timeout bounds the wait.
  • Table-level locks from DDL: ALTER TABLE takes ACCESS EXCLUSIVE. It waits behind any long query on the table, and every later query queues behind it, so a two-second ALTER can stall the app for minutes. Run migrations with SET lock_timeout = '3s' and retry.
  • Deadlocks: PostgreSQL checks after deadlock_timeout (1 s), aborts one transaction with SQLSTATE 40P01, and logs both queries. Causes: inconsistent lock order (sort ids before batch updates), FK checks, and UPDATE … WHERE id IN (…) touching rows in physical order that differs between sessions. Retry the victim.
  • Optimistic vs pessimistic: optimistic needs no held locks and scales for low contention and long think times (JPA @Version, ETags with If-Match in HTTP APIs); under high contention it wastes work on retries. Pessimistic serializes access cheaply for hot rows but can’t span user think time.
  • Advisory locks (pg_advisory_xact_lock(key)) lock an application-defined number, e.g. “only one instance runs the billing job”, without a table row.

Predict the output

Session 1 updates account A, then B. Session 2, at the same moment, updates B, then A. Each runs in a transaction. What happens?

-- session 1                                  -- session 2
BEGIN;                                        BEGIN;
UPDATE accounts SET balance = balance - 10    UPDATE accounts SET balance = balance - 5
  WHERE id = 'A';                               WHERE id = 'B';
UPDATE accounts SET balance = balance + 10    UPDATE accounts SET balance = balance + 5
  WHERE id = 'B';                               WHERE id = 'A';
COMMIT;                                       COMMIT;
-- pessimistic: lock both accounts in a fixed order (by id), then transfer
BEGIN;
SELECT id, balance FROM accounts WHERE id IN ('A', 'B') ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;

-- optimistic: write only if the version is still the one we read
UPDATE orders
SET note = $1, version = version + 1
WHERE id = $2 AND version = $3;      -- 0 rows: conflict, tell the user

-- fail fast instead of waiting
SELECT * FROM seats WHERE id = 14 FOR UPDATE NOWAIT;

Practice: reserve a seat

Exercisemedium

Two people, one seat

A cinema app has seats(id, showing_id, reserved_by), where reserved_by is NULL while the seat is free. Write the SQL to reserve seat 14 for user 99 so that, if two users click at the same moment, exactly one gets the seat and the other is told it’s taken. Do it without SELECT … FOR UPDATE.

›

An UPDATE can check a condition and change the row in one step, and it reports how many rows it changed.

›

Which condition must still be true at the moment of writing for the reservation to be valid?

SolutionTry it yourself first
UPDATE seats
SET reserved_by = 99
WHERE id = 14 AND reserved_by IS NULL;

If it changes 1 row, user 99 has the seat. If it changes 0 rows, someone else got there first: show “seat taken”.

Why it’s safe: the second UPDATE waits for the first one’s row lock. When the first commits, the second re-checks reserved_by IS NULL on the updated row, finds it false, and changes nothing. A version that first runs SELECT reserved_by … and then UPDATE … WHERE id = 14 would let both users read NULL and both “win”.

Deep diveA job queue in a table with SKIP LOCKEDInterview favorite

Workers pick pending jobs from a jobs table. The naive version, SELECT … WHERE status = 'PENDING' LIMIT 1 FOR UPDATE, makes every worker lock the same first row: one works, the others wait for it, and throughput equals one worker.

SKIP LOCKED makes each worker take the first row nobody else holds:

WITH next AS (
    SELECT id FROM jobs
    WHERE status = 'PENDING' AND run_at <= now()
    ORDER BY run_at
    LIMIT 10
    FOR UPDATE SKIP LOCKED
)
UPDATE jobs j
SET status = 'RUNNING', locked_at = now(), attempts = attempts + 1
FROM next
WHERE j.id = next.id
RETURNING j.id, j.payload;

Ten workers each claim a different batch without blocking. Points that complete the answer:

  • Claim and commit quickly, then process outside the claiming transaction; mark DONE or FAILED in another short transaction. Holding the lock during processing ties up a connection per job.
  • Crashed workers leave rows RUNNING forever: a reaper resets rows whose locked_at is older than a timeout, so processing must be idempotent.
  • Index: a partial index ON jobs (run_at) WHERE status = 'PENDING' keeps the claim query fast as DONE rows pile up; archive or partition old jobs.
  • When to use it: tens to a few thousand jobs per second, transactional enqueueing with business data (the outbox pattern). Beyond that, or for fan-out to many consumers, a broker like Kafka or SQS fits better. Libraries built on this: Solid Queue (Rails), Oban (Elixir), pg-boss (Node.js), db-scheduler (Java).
  • Writes lock rows until the transaction ends; readers never wait (MVCC). FOR UPDATE / FOR NO KEY UPDATE / FOR SHARE / FOR KEY SHARE; NOWAIT, SKIP LOCKED, lock_timeout.
  • Conditional single-statement updates beat read-then-write; optimistic version checks for long think times; FOR UPDATE for hot short operations.
  • Deadlocks: consistent lock order, retry 40P01. DDL takes ACCESS EXCLUSIVE and queues everyone: migrations with lock_timeout + retry.
  • Job queues: FOR UPDATE SKIP LOCKED, short claim transactions, reaper, idempotent handlers, partial index.

Check this part

  1. What does SELECT … FOR UPDATE do?

  2. An optimistic UPDATE … WHERE id = 1001 AND version = 7 changes 0 rows. What does it mean?

  3. How do you prevent deadlocks between transfers in opposite directions?

  4. Why can a quick ALTER TABLE freeze an app for minutes?

UPDATE and DELETE lock the rows they change until the transaction ends. SELECT … FOR UPDATE locks rows you're about to change; optimistic locking checks a version column instead and retries on conflict. Deadlocks happen when two transactions lock rows in opposite orders; the database kills one. SKIP LOCKED turns a table into a job queue.

Key takeaways

  • A transaction (BEGIN … COMMIT) makes several changes happen together or not at all; a crash before COMMIT undoes them.
  • Keep transactions short and never wait on users or slow calls inside them.
  • Isolation levels decide what you see of others: PostgreSQL defaults to Read Committed, MySQL to Repeatable Read.
  • Lost updates come from read-then-write in the app: use a conditional UPDATE, a version column, or FOR UPDATE.
  • Deadlocks come from locking in opposite orders: lock in one order and retry.
  • PostgreSQL aborts the transaction on error (savepoints to recover); long or idle transactions block locks and vacuum.
  • Snapshot isolation prevents lost updates (40001) but not write skew; SERIALIZABLE, locking reads or a conflict row fix it. Retry whole transactions.
  • Lock modes, NOWAIT/SKIP LOCKED, lock_timeout for migrations, deadlock retry on 40P01.
  • Tables make good job queues up to a point with SKIP LOCKED, idempotent handlers and a reaper.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.