Transactions and ACID from the outside
Two psql sessions, one stock count: watch a rollback undo everything, a dirty read fail to happen, and a sale vanish, then stop it three ways
inventory.on_hand for product 1 is 10. Two psql sessions, both at Postgres's default isolation level, each run BEGIN; SELECT on_hand FROM inventory WHERE product_id = 1; and both see 10. Each then runs UPDATE inventory SET on_hand = 9 WHERE product_id = 1; COMMIT; one after the other. What is on_hand afterwards?
A transaction is a promise the database makes about a group of statements. You say BEGIN, run reads and writes, and say COMMIT. The database promises four things about that group, and the four have names: atomicity, consistency, isolation and durability. Most engineers can recite the acronym. Fewer can say what each letter does not promise, and that is where the bugs live.
This chapter treats the database as a black box. You run two psql sessions against the shop, side by side, and watch what each promise does and does not cover. The machinery inside, multi-version concurrency control, snapshots, row locks, the anomaly catalogue, comes in module D2: the chapters on isolation levels and anomalies and MVCC, snapshots and vacuum. Here you need only the behaviour, which is what your application sees.
ACID, one letter at a time
The acronym is from Haerder and Reuter in 1983, building on Jim Gray’s 1981 paper on the transaction concept. Each letter is a separate guarantee with a separate price.
A is for abort
Atomicity means that if a transaction does not commit, none of its writes happen. It does not matter why it did not commit: you typed ROLLBACK, a statement raised an error, the client disconnected, or the server lost power halfway through. Afterwards, the database looks as if the transaction never started.
That is all atomicity says. It says nothing about other sessions running at the same time; that is isolation. Martin Kleppmann suggests the word “abortability” would have been clearer, and he is right. The useful consequence is that you can write a checkout as five statements (decrement stock, insert the order, insert three order items) and never have to clean up after a failure between statement two and statement three. The database cleans up for you.
Postgres is strict about this in one way that surprises people coming from MySQL. If any statement inside a transaction raises an error, the whole transaction is marked aborted. Every later statement fails with ERROR: current transaction is aborted, commands ignored until end of transaction block, and COMMIT replies ROLLBACK. If you want to recover from one failing statement and carry on, you set a SAVEPOINT before it and ROLLBACK TO SAVEPOINT after the error.
There is one write atomicity does not undo: sequences. nextval() on orders_id_seq is never rolled back, so a rolled-back insert leaves a gap in the order ids. That is deliberate. Making sequences transactional would force every inserting session to wait for every other one to commit. Gaps in ids are normal; never build a business rule on their absence.
What it costs. In Postgres a rollback is cheap: the aborted transaction’s row versions stay in the table, marked dead, and vacuum removes them later. The cost is deferred. A workload that aborts half its transactions writes twice the rows it keeps and leaves vacuum twice the work.
C is for constraints, and for your code
Consistency is the odd letter. It means that a transaction takes the database from one valid state to another, where “valid” is defined by invariants: every order item points at a real order, stock is never negative, an order’s total equals the sum of its items.
The database can enforce only the invariants you declare: PRIMARY KEY, UNIQUE, FOREIGN KEY, NOT NULL, CHECK, and triggers. The rest are yours. The shop declares that order_items.order_id references orders, so no transaction can commit an orphan item. Nothing declares that orders.total_cents equals the sum of its items, so a buggy checkout can commit a wrong total and the database will store it without complaint. The D1 project writes a script that checks exactly that.
So C is the one property that is mostly the application’s job. The database’s part is to give you A and I, so that if each transaction is correct on its own, the combination stays correct.
What it costs. Every declared constraint is a check on every write. A foreign key insert does an index lookup on the referenced table and takes a FOR KEY SHARE lock on the referenced row. A foreign key with no index on the referencing column makes every delete of a parent row scan the child table: delete a customer and Postgres reads all of orders to check nothing points at it.
I is for isolation, and it comes in levels
Isolation means that concurrent transactions do not see each other’s half-finished work. The strongest version, serializable, promises that the result is the same as if the transactions had run one at a time in some order. Anything weaker allows named anomalies: specific interleavings where concurrent transactions produce a result no serial order could.
SQL defines four levels. Postgres implements three distinct ones and defaults to the weakest of those:
| Level you ask for | What Postgres gives | Dirty read | Non-repeatable read | Lost update (read-modify-write) |
|---|---|---|---|---|
| READ UNCOMMITTED | READ COMMITTED | never | possible | possible |
| READ COMMITTED (default) | READ COMMITTED | never | possible | possible |
| REPEATABLE READ | snapshot isolation | never | never | detected: error 40001 |
| SERIALIZABLE | serializable snapshot isolation | never | never | detected: error 40001 |
A dirty read is reading another transaction’s uncommitted write. Postgres never allows it, even when you ask for READ UNCOMMITTED; the docs say so in one line, and you will check it in the lab. A non-repeatable read is running the same SELECT twice inside one transaction and getting different answers, because another transaction committed in between. At READ COMMITTED each statement sees the data as committed when that statement started, so the second SELECT sees the new commit. A lost update is the Predict above: two read-modify-write cycles interleave and one write overwrites the other.
The isolation level is set per transaction: BEGIN ISOLATION LEVEL REPEATABLE READ;, or SET default_transaction_isolation = 'repeatable read' for a session, a role or the whole server. MySQL’s InnoDB defaults to REPEATABLE READ and Oracle to READ COMMITTED; the same name does not mean the same behaviour across engines, which is what Kleppmann’s Hermitage project tests.
What it costs. Stronger isolation means more waiting or more retries. At READ COMMITTED a write blocks other writers of the same row until commit. At REPEATABLE READ and SERIALIZABLE, conflicts that READ COMMITTED would have let through become errors, and your code must catch SQLSTATE 40001 and run the whole transaction again. On a hot row that can halve throughput; the lab measures it.
D is for the disk
Durability means that once COMMIT returns, the transaction survives a crash. In Postgres that is the write-ahead log: COMMIT writes a commit record to the WAL and, with the defaults fsync = on and synchronous_commit = on, waits for it to be flushed to stable storage before replying. The data pages can be written later; recovery replays the WAL.
Durability is about one machine’s disk. It says nothing about the disk dying, which is what replicas and backups are for (module D4), and nothing about a replica having the data, which is what synchronous_standby_names is for (module D3).
What it costs. One WAL flush per commit, which is the first chapter’s fsync bill: around 0.1 to 2 ms on an SSD, 5 to 10 ms on a spinning disk. Postgres amortises it with group commit (several sessions committing at once share one flush), and you can trade it away per transaction with SET LOCAL synchronous_commit = off. Then COMMIT returns before the flush, and a crash can lose transactions committed in the last three times wal_writer_delay (200 ms by default), so about 600 ms of commits. The database stays consistent; the most recent commits are gone. For a page-view counter that is a good trade. For a payment it is not.
The lost update, and why BEGIN does not stop it
The checkout bug from the Why has a precise shape. The application reads a value, computes a new one in its own memory, and writes the result back as a literal:
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1; -- app sees 10
-- app computes 10 - 1 = 9
UPDATE inventory SET on_hand = 9 WHERE product_id = 1;
COMMIT;
At READ COMMITTED nothing connects the SELECT to the UPDATE. Each is a separate statement with its own view of the data. Run two of these concurrently and both read 10, both write 9, and both commit. The database has done exactly what it was told. The bug is that the application told it the wrong thing: “set it to 9” instead of “subtract one”.
The simulation below runs the same interleaving with an account balance, step by step, and then three fixes against the same schedule. Watch the invariant line at the bottom. In LOST UPDATE it goes red the moment the second client writes, because the balance no longer reflects both deposits. Then step through the three FIX scenarios and watch what changes: in ATOMIC UPDATE there is no read in the application at all; in FOR UPDATE the second client is BLOCKED until the first commits; in VERSION CHECK the second write matches zero rows and the client must re-read.
-- Client 1 (+50) and Client 2 (-30) both run, autocommit:
SELECT balance FROM accounts WHERE id = 7; -- both see 100
-- ...app computes new balance in memory...
UPDATE accounts SET balance = 150 WHERE id = 7; -- C1
UPDATE accounts SET balance = 70 WHERE id = 7; -- C2: +50 is gone-- 1. Push the arithmetic into the database (atomic):
UPDATE accounts SET balance = balance + 50 WHERE id = 7;
-- 2. Lock the row for the read-modify-write (pessimistic):
BEGIN;
SELECT balance FROM accounts WHERE id = 7 FOR UPDATE;
UPDATE accounts SET balance = 150 WHERE id = 7;
COMMIT;
-- 3. Version check, retry on 0 rows (optimistic):
UPDATE accounts SET balance = 150, version = 2
WHERE id = 7 AND version = 1; Each client runs a SELECT then an UPDATE. Order the four statements so that one committed write disappears from the balance.
GOAL: both clients commit and balance != 120
Three fixes, and what each costs
Fix 1: let the database do the arithmetic
UPDATE inventory SET on_hand = on_hand - 1
WHERE product_id = 1 AND on_hand >= 1
RETURNING on_hand;
The read and the write are now one statement. When two sessions run it at once, the second blocks on the first one’s row lock. When the first commits, Postgres re-reads the newly committed version of the row, re-checks the WHERE clause against it, and applies on_hand - 1 to the new value. No decrement is lost. The AND on_hand >= 1 turns the stock check into part of the same atomic step: if stock is gone, the UPDATE matches zero rows, RETURNING returns nothing, and the application knows to refuse the sale.
This is the fix to reach for first. It needs no change of isolation level, holds the row lock for the duration of one statement plus the rest of the transaction, and never raises a retryable error. Its limit is that the whole decision has to fit in SQL. If the application must call a fraud service between reading and writing, it does not fit.
Fix 2: lock the row when you read it
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1 FOR UPDATE;
-- app logic, possibly slow
UPDATE inventory SET on_hand = 9 WHERE product_id = 1;
COMMIT;
FOR UPDATE takes the row lock at read time. A second session running the same SELECT blocks until the first commits, then reads the new committed value (9), and computes from that. The read-modify-write becomes a critical section around one row.
The cost is that the lock is held for as long as your application takes between the SELECT and the COMMIT. If that includes a network call that takes 2 seconds, every other buyer of that product waits 2 seconds, and if the application crashes without closing the connection, they wait until Postgres notices. Two knobs bound the damage: lock_timeout (default 0, meaning wait forever) makes a blocked statement fail after a set time, and idle_in_transaction_session_timeout (default 0, off) kills sessions that sit inside an open transaction doing nothing. Lock rows in a consistent order (for example, sorted by product_id when a basket has several) or two baskets can deadlock; the deadlock lesson shows how.
Fix 3: raise the isolation level and retry
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT on_hand FROM inventory WHERE product_id = 1;
UPDATE inventory SET on_hand = 9 WHERE product_id = 1;
COMMIT;
At REPEATABLE READ the transaction reads from a snapshot taken at its first statement. If another transaction commits a change to the same row after that snapshot, this transaction’s UPDATE fails with ERROR: could not serialize access due to concurrent update, SQLSTATE 40001. The lost update is turned into an error. The application catches it, rolls back, and runs the whole transaction again from BEGIN, reading the new value.
This fix covers code you did not think about: every read-modify-write in the transaction is protected, not only the one you spotted. The cost is retries. Under low contention they are rare and nearly free. On a hot row, a flash-sale product, they pile up: in the lab, eight clients hammering one row at REPEATABLE READ retry thousands of times and run at about half the throughput of the atomic UPDATE. And the retry loop must be in your code; an ORM that wraps a request in a transaction without one turns every conflict into a 500 for the user.
| Fix | Holds a lock across app logic | Retries needed | Works when the decision needs app code | Best for |
|---|---|---|---|---|
SET x = x - 1 WHERE x >= 1 |
no | no | no | counters, stock, balances |
SELECT ... FOR UPDATE |
yes | no | yes | short critical sections on known rows |
| REPEATABLE READ + retry | no | yes, on conflict | yes | complex transactions, low contention |
SERIALIZABLE extends fix 3 to anomalies that involve rows no one updated (write skew), at the cost of more false-positive aborts. Module D2 covers it.
What the client sees, and what it should do
A transaction is a property of a connection. Two things follow that bite in production.
First, a connection pool in transaction mode (PgBouncer’s pool_mode = transaction) gives you a different server connection for each transaction. Everything you set with plain SET leaks or vanishes between transactions; use SET LOCAL inside the transaction. The connections chapter in D2 covers the rest.
Second, the window between BEGIN and COMMIT is a resource. Every open transaction holds its row locks, and an open transaction that has written anything, or any REPEATABLE READ transaction, holds back the horizon below which vacuum may remove dead rows, across the whole database. A transaction left open by a crashed worker or a debugger paused on a breakpoint does damage proportional to how long it stays open. SELECT pid, state, xact_start, left(query, 60) FROM pg_stat_activity WHERE state LIKE 'idle in transaction%'; lists them, and the lab’s break makes one on purpose.
The rule that covers most application code: keep transactions short, do the arithmetic in SQL where you can, lock with FOR UPDATE where you cannot, and when you raise the isolation level, write the retry loop in the same commit.
Open two terminals in labs/databases and connect both to the shop:
docker compose exec db psql -U atlas shopIn A, reset product 1 to a known stock level and confirm the default isolation level:
UPDATE inventory SET on_hand = 10 WHERE product_id = 1;
SHOW default_transaction_isolation;UPDATE 1 and read committed. Every transaction in this lab runs at READ COMMITTED unless the step says otherwise.1. Atomicity: a rollback undoes everything.
In A:
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;
INSERT INTO orders (customer_id, status, total_cents, created_at)
VALUES (1, 'placed', 1999, now()) RETURNING id;
SELECT on_hand FROM inventory WHERE product_id = 1;
ROLLBACK;
SELECT on_hand FROM inventory WHERE product_id = 1;
SELECT count(*) FROM orders WHERE customer_id = 1 AND total_cents = 1999;on_hand is 9 and the insert returns an id. After ROLLBACK, on_hand is 10 and the count is 0: both writes are gone. Now run SELECT last_value FROM orders_id_seq; and compare with the id you saw: the sequence did not roll back. The next order gets the following id and a gap is left.Now make an error abort the transaction:
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;
SELECT 1 / 0;
SELECT on_hand FROM inventory WHERE product_id = 1;
COMMIT;
SELECT on_hand FROM inventory WHERE product_id = 1;ERROR: division by zero, then ERROR: current transaction is aborted, commands ignored until end of transaction block for the SELECT, and COMMIT prints ROLLBACK. Stock is still 10. Postgres refuses to commit a transaction in which anything failed.2. A dirty read that does not happen, and a non-repeatable read that does.
In A, start a transaction and change the row without committing:
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;In B, ask for the weakest level there is and read the row twice:
BEGIN ISOLATION LEVEL READ UNCOMMITTED;
SHOW transaction_isolation;
SELECT on_hand FROM inventory WHERE product_id = 1;read uncommitted, and on_hand is 10. A’s uncommitted 9 is invisible even though you asked to see uncommitted data. Postgres accepts READ UNCOMMITTED and runs it as READ COMMITTED.In A, COMMIT;. Then in B, inside the same transaction, repeat the read:
SELECT on_hand FROM inventory WHERE product_id = 1;
COMMIT;BEGIN ISOLATION LEVEL REPEATABLE READ; in B and the second read stays at the first value, because the transaction reads from one snapshot.3. A lost update, by hand and then at scale.
Reset: UPDATE inventory SET on_hand = 10 WHERE product_id = 1;. Then run these in the order shown, alternating terminals:
-- A
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1;
-- B
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1;
UPDATE inventory SET on_hand = 9 WHERE product_id = 1;
COMMIT;
-- A
UPDATE inventory SET on_hand = 9 WHERE product_id = 1;
COMMIT;
SELECT on_hand FROM inventory WHERE product_id = 1;UPDATE 1, both COMMITs succeed, and the final value is 9. Two sales, one decrement. Nothing errored, nothing blocked, and nothing in any log would tell you.Now make it happen at the rate of a real launch. Write a pgbench script that does the same read-modify-write, and run it with 8 concurrent clients, 200 sales each:
docker compose exec -T db sh -c 'cat > /tmp/rmw.sql' <<'EOF'
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1 \gset
UPDATE inventory SET on_hand = :on_hand - 1 WHERE product_id = 1;
COMMIT;
EOF
docker compose exec db psql -U atlas shop -c "UPDATE inventory SET on_hand = 100000 WHERE product_id = 1;"
docker compose exec db pgbench -U atlas -n -c 8 -t 200 -f /tmp/rmw.sql shop
docker compose exec db psql -U atlas shop -c "SELECT 100000 - on_hand AS recorded_sales, 1600 AS actual_sales FROM inventory WHERE product_id = 1;"number of transactions actually processed: 1600/1600 and 0 failed. The query reports something like recorded_sales = 212 against 1600 actual. On a laptop most sales vanish, and the number changes every run. That is the Why section, measured.4. Fix 1: the atomic UPDATE.
docker compose exec -T db sh -c 'cat > /tmp/atomic.sql' <<'EOF'
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1 AND on_hand >= 1;
EOF
docker compose exec db psql -U atlas shop -c "UPDATE inventory SET on_hand = 100000 WHERE product_id = 1;"
docker compose exec db pgbench -U atlas -n -c 8 -t 200 -f /tmp/atomic.sql shop
docker compose exec db psql -U atlas shop -c "SELECT 100000 - on_hand AS recorded_sales FROM inventory WHERE product_id = 1;"recorded_sales = 1600, every run. Throughput (tps) is about the same as the broken version, a few thousand per second on a laptop: correctness cost nothing here because the work was always serialised on the row lock; the broken version only skipped the arithmetic.5. Fix 2: SELECT FOR UPDATE, and what blocking looks like.
Reset to 10. In A:
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1 FOR UPDATE;In B:
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = 1 FOR UPDATE;Open a third psql (or use a new tab) and look at the wait:
SELECT pid, state, wait_event_type, wait_event, left(query, 60) AS query
FROM pg_stat_activity WHERE datname = 'shop' AND pid <> pg_backend_pid();wait_event_type = Lock, wait_event = transactionid: it is waiting for A’s transaction to end, not for a table lock.In A: UPDATE inventory SET on_hand = 9 WHERE product_id = 1; COMMIT;
UPDATE inventory SET on_hand = 8 WHERE product_id = 1; COMMIT; and the stock is 8. No sale lost.6. Fix 3: REPEATABLE READ and a retry.
Reset to 10. In A:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT on_hand FROM inventory WHERE product_id = 1;In B, commit a sale in one statement: UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;
Back in A:
UPDATE inventory SET on_hand = 9 WHERE product_id = 1;ERROR: could not serialize access due to concurrent update. A’s snapshot is out of date, and Postgres refuses to let it write. ROLLBACK; and run A’s transaction again from BEGIN: the SELECT now sees 9 and the update writes 8.pgbench can play the retrying application. --max-tries retries transactions that fail with a serialization error:
docker compose exec -T db sh -c 'cat > /tmp/rr.sql' <<'EOF'
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT on_hand FROM inventory WHERE product_id = 1 \gset
UPDATE inventory SET on_hand = :on_hand - 1 WHERE product_id = 1;
COMMIT;
EOF
docker compose exec db psql -U atlas shop -c "UPDATE inventory SET on_hand = 100000 WHERE product_id = 1;"
docker compose exec db pgbench -U atlas -n -c 8 -t 200 --max-tries=50 -f /tmp/rr.sql shop
docker compose exec db psql -U atlas shop -c "SELECT 100000 - on_hand AS recorded_sales FROM inventory WHERE product_id = 1;"total number of retries), a handful of transactions (well under 1%) failing even after 50 tries, and a fraction of the tps of step 4, between a quarter and a half. recorded_sales equals the number of transactions processed exactly: every committed sale is counted, and the failed ones were never committed. Correct, and expensive on a hot row.BEGIN; SELECT on_hand FROM inventory WHERE product_id = 1 FOR UPDATE; and walk away from the terminal. Now rerun step 4’s pgbench: it hangs, all 8 clients waiting on A. Every buyer of product 1 is stuck behind one idle session. Press Ctrl-C, then in B run SET lock_timeout = '2s'; followed by UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 1;: it fails after 2 seconds with canceling statement due to lock timeout, which is a failure your application can handle. Finally run ALTER SYSTEM SET idle_in_transaction_session_timeout = '10s'; SELECT pg_reload_conf(); and wait: A’s session is terminated, its lock released, and the next statement in A reports the connection was closed. Set it back with ALTER SYSTEM RESET idle_in_transaction_session_timeout; SELECT pg_reload_conf();.Your shop's checkout decrements stock for every item in the basket and inserts the order, in one transaction, at READ COMMITTED. A flash sale is next week: one product will get about 300 checkouts per second for ten minutes. Between reading stock and writing the order, the code calls a fraud-scoring API that takes 50 to 300 ms. You have one sprint. What do you change?
- DOC PostgreSQL 17 documentation: Transaction Isolation
The authority for everything in the lab: the table of levels and anomalies, the one line saying READ UNCOMMITTED behaves as READ COMMITTED, and exactly what an UPDATE does when it finds a row changed by a concurrent transaction. Read 13.2.1 and 13.2.2 now; 13.2.3 belongs to module D2.
- PAPER The Transaction Concept: Virtues and Limitations Jim Gray, 1981
Where the transaction as a programming abstraction was stated clearly for the first time, by the person who built much of it. Short and readable; skip the later sections on nested and long-lived transactions until D5. Read: the first half: the contract model and the definitions of atomicity, consistency and durability.
- PAPER A Critique of ANSI SQL Isolation Levels Berenson, Bernstein, Gray, Melton, O'Neil, O'Neil, 1995
Shows that the SQL standard's definitions of isolation levels are ambiguous, defines the anomalies properly, and introduces snapshot isolation. The vocabulary every later isolation discussion uses. Read: sections 1 to 3, then the definition of the lost update as phenomenon P4.
- POST Hermitage: Testing the 'I' in ACID Martin Kleppmann, 2014
Runs the same two-session tests you ran in the lab against Postgres, MySQL, Oracle and SQL Server, and shows that the same level name means different things in each. Read the post and the results table; the repository has the exact scripts.
- PAPER ACIDRain: Concurrency-Related Attacks on Database-Backed Web Applications Todd Warszawski, Peter Bailis, 2017
The paper behind the Why: real inventory and voucher bugs in deployed shops, all caused by read-modify-write at weak isolation. Skip the formal anomaly-detection machinery on a first read. Read: sections 1 and 2 for the attack model, then the e-commerce case studies.
- DOC PostgreSQL 17 documentation: Explicit Locking
The row-level lock modes behind FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE, which foreign keys take, plus the section on deadlocks. Read 13.3.2 and 13.3.4; the table-lock matrix can wait.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.