Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 12 / Stage 3

Transactions and concurrency

Goal: Keep data correct when many sessions write at once — ACID in practice, MVCC's row versions, isolation levels and their anomalies, locks, the FOR UPDATE / SKIP LOCKED patterns, and deadlocks you can explain. Time: ~2.5 hours

What you will learn

  • What each ACID letter buys you, concretely
  • BEGIN / COMMIT / ROLLBACK / SAVEPOINT
  • MVCC: why readers and writers don't block each other
  • Isolation levels: Read Committed, Repeatable Read, Serializable
  • The anomalies: lost updates, non-repeatable reads, phantoms, write skew
  • Row and table locks, and reading pg_locks
  • SELECT ... FOR UPDATE and SKIP LOCKED — safe reservations and job queues
  • Deadlocks: how they happen, how Postgres resolves them, how you avoid them
  • Advisory locks

The multi-session demos in this part show two psql windows side by side — every transcript below is from a real pair of sessions against shopdb. Open two terminals and replay them; concurrency only becomes intuition through your own fingers.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Three of these need two psql terminals on shopdb side by side — that's the lesson. Reset afterwards with psql -d shopdb -f shopdb.sql.


Exercise 1: The savepoint rescue

What to do: In one transaction: log a good row, set a savepoint, run a statement that fails (cast 'boom' to integer), roll back to the savepoint, log a recovery row, commit. Both good rows must survive.

Sample output:

      note       
-----------------
 row 1 ok
 row 2 recovered
(2 rows)

💡 Hint: without the savepoint, the error aborts the whole transaction and nothing commits.


Show the solution to Exercise 1
-- Exercise 1: The savepoint rescue (single session, runnable)
BEGIN;
CREATE TEMP TABLE batch_log (note text);
INSERT INTO batch_log VALUES ('row 1 ok');
SAVEPOINT risky;
INSERT INTO batch_log VALUES ('boom'::integer::text);  -- fails on purpose
ROLLBACK TO SAVEPOINT risky;
INSERT INTO batch_log VALUES ('row 2 recovered');
COMMIT;
SELECT * FROM batch_log;

Exercise 2: The atomic fix

What to do: Sell two units of product 1 using the write form that cannot lose updates, proving each decrement with RETURNING. Then put the stock back.

Sample output:

 stock 
-------
    14
(1 row)

 stock 
-------
    13
(1 row)

💡 Hint: SET stock = stock - 1 — the subtraction happens at write time, against the current row version. No read, no gap, no race.


Show the solution to Exercise 2
-- Exercise 2: The atomic fix (single session, runnable)
-- SET stock = stock - 1 computes from the row's current version AT WRITE
-- TIME, so there is no read-modify-write gap to race through. Two sales:
UPDATE products SET stock = stock - 1 WHERE product_id = 1 RETURNING stock;
UPDATE products SET stock = stock - 1 WHERE product_id = 1 RETURNING stock;
-- Two decrements, both landed. Put it back:
UPDATE products SET stock = stock + 2 WHERE product_id = 1 RETURNING stock;

Exercise 3: Lost update, live

What to do (two terminals): Reproduce the lost update exactly as in the lesson — both sessions read 15, both write 14, one sale evaporates. Then repeat with FOR UPDATE on both reads and watch session B block until A commits, read 14, and write 13. Narrate to yourself what changed.

💡 Hint: the solution file holds the full choreography as a side-by-side script. The blocking pause in round two is the fix working.


Show the solution to Exercise 3
-- Exercise 3: Lost update, live — TWO TERMINALS, both on shopdb.
-- Type session A's column in one window, session B's in the other, top to
-- bottom. (Transcript of a real run is in the lesson, section 5/7.)
--
-- SESSION A                                  -- SESSION B
-- BEGIN;
-- SELECT stock FROM products
--   WHERE product_id = 1;      -- see 15
--                                            -- BEGIN;
--                                            -- SELECT stock FROM products
--                                            --   WHERE product_id = 1;  -- also 15!
-- UPDATE products SET stock = 14
--   WHERE product_id = 1;
-- COMMIT;
--                                            -- UPDATE products SET stock = 14
--                                            --   WHERE product_id = 1;
--                                            -- COMMIT;
-- SELECT stock FROM products WHERE product_id = 1;   -- 14: one sale vanished
--
-- NOW THE FIX: repeat with FOR UPDATE on both SELECTs. B's SELECT blocks
-- until A commits, then returns 14, and B writes 13. No lost update.
-- Afterwards reset:  UPDATE products SET stock = 15 WHERE product_id = 1;
SELECT 'two-terminal drill - see comments' AS note;

Exercise 4: The job queue

What to do (two terminals): Build the three-job queue table from the solution file, then run the same SKIP LOCKED claim in both terminals inside open transactions. A gets send_email, B gets resize_image — nobody waits, nobody collides.

💡 Hint: remove SKIP LOCKED and repeat: B now waits on A — correct, but a queue that serialises its workers.


Show the solution to Exercise 4
-- Exercise 4: The job queue — TWO TERMINALS.
-- Setup (either session):
DROP TABLE IF EXISTS jobs;
CREATE TABLE jobs (
  id     integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  task   text NOT NULL,
  status text NOT NULL DEFAULT 'queued'
);
INSERT INTO jobs (task) VALUES ('send_email'), ('resize_image'), ('build_report');
-- Then in BOTH terminals at once (inside BEGIN ... COMMIT):
--   UPDATE jobs SET status = 'running'
--   WHERE id = (SELECT id FROM jobs WHERE status = 'queued'
--               ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1)
--   RETURNING id, task;
-- A claims job 1, B claims job 2 — same statement, no collision, no waiting.

Exercise 5: Deadlock on purpose

What to do (two terminals): Lock product 1 then 2 in session A, product 2 then 1 in session B. Read the deadlock detected DETAIL aloud — it names the cycle. Then state the prevention rule and prove it: same experiment, both sessions in id order, no deadlock (just a polite queue).

💡 Hint: Postgres waits deadlock_timeout (1s default) before checking, so the error takes a moment — that pause is the detector working.


Show the solution to Exercise 5
-- Exercise 5: Deadlock on purpose — TWO TERMINALS.
-- SESSION A                                  -- SESSION B
-- BEGIN;                                     -- BEGIN;
-- UPDATE products SET stock = stock          -- UPDATE products SET stock = stock
--   WHERE product_id = 1;                    --   WHERE product_id = 2;
-- UPDATE products SET stock = stock
--   WHERE product_id = 2;   -- waits...
--                                            -- UPDATE products SET stock = stock
--                                            --   WHERE product_id = 1; -- cycle!
-- Within ~1s one session gets:
--   ERROR:  deadlock detected
--   DETAIL: Process ... waits for ShareLock on transaction ...; blocked by ...
-- and its transaction rolls back; the other completes normally.
-- Prevention: both sessions touch rows in the SAME order (1 then 2) —
-- they queue instead of cycling. COMMIT/ROLLBACK both windows to clean up.
SELECT 'two-terminal drill - see comments' AS note;

Exercise 6: The one-report gate

What to do: Claim advisory lock 20260101 ("tonight's report"). From a second terminal, try to claim it — refused (f). Release in the first and try again — granted. One number, one running report, no table involved.

Sample output (first terminal):

 nightly_report_claimed 
------------------------
 t
(1 row)

💡 Hint: pg_try_advisory_lock / pg_advisory_unlock. In pooled apps prefer pg_advisory_xact_lock, which can't leak past COMMIT.

Show the solution to Exercise 6
-- Exercise 6: The one-report gate (runnable; pair with a second terminal)
-- First claim wins:
SELECT pg_try_advisory_lock(20260101) AS nightly_report_claimed;
-- In a SECOND terminal this returns f while the first holds it:
--   SELECT pg_try_advisory_lock(20260101);
-- Done: release (true = it was yours to release).
SELECT pg_advisory_unlock(20260101) AS released;

Common mistakes

Mistake What happens Fix
Read-modify-write without locks Lost updates under load SET x = x - 1, or FOR UPDATE
Long transactions (open psql BEGINs) Lock queues, bloat, VACUUM starvation Keep transactions statement-short
Continuing after a mid-transaction error current transaction is aborted forever ROLLBACK (or savepoints around risky steps)
Polling a queue with plain FOR UPDATE Workers serialise behind one row SKIP LOCKED
Locks taken in ad-hoc order Deadlocks under load One global lock order + retries
Serializable without retry logic "Random" errors in production Serialization failures are retries by design

Quick recap

  • ACID in plain words: statements land together or not at all, the rules keep holding, isolation is a dial you choose, and committed means crash-safe.
  • Savepoints unwind partial work; errors abort transactions until ROLLBACK.
  • Under MVCC, writes make new row versions, readers and writers never block each other, and VACUUM collects the debris.
  • Read Committed takes a snapshot per statement, Repeatable Read one per transaction, and Serializable behaves as-if-serial at the price of retries.
  • Lost updates are your bug to prevent: atomic writes or FOR UPDATE; SKIP LOCKED turns locks into a job queue.
  • A deadlock is a detected cycle with one chosen victim, and a global lock order prevents it; advisory locks serialise ideas, not rows.

Checklist

Before Part 13, make sure you can:

  • Demonstrate the savepoint rescue, and explain the aborted-transaction rule.
  • Reproduce the lost update in two psql windows, then fix it both ways.
  • Say what each isolation level freezes, and who must retry.
  • Claim jobs from two windows with SKIP LOCKED, no collisions.
  • Cause a deadlock on purpose, read its DETAIL, and state the prevention rule.

Read more: the official transactions tutorial, transaction isolation chapter, and explicit locking chapter.

Search the guide