What you'll learn: By the end of this lesson you will be able to state what each letter of ACID promises and does not promise, choose between PostgreSQL's Read Committed, Repeatable Read and Serializable levels by the anomalies each allows, explain a lost update and a write skew and the fixes for each, say why a serialization failure is an instruction to retry and not a bug, and use a lab that shows everything one database connection can show about transactions while being plain about what two real sessions would add.
Picture two envelopes on a desk, one holding Alice's money and one holding Bob's, and a clerk moving 80 coins from one to the other. If the phone rings halfway through, Alice's envelope is lighter and Bob's is not heavier: the money is gone. A transaction is the rule that the clerk finishes both moves or puts everything back. Now add a second clerk counting the coins in both envelopes while the first is mid-move. What may the second clerk see? That question is isolation, and most of the confusion about databases lives in its answer.
This lesson is the foundation for the MVCC, locking and Spring transaction lessons later in this module (plain text for now). It gives the definitions and the behaviour of the isolation levels, not their internals.
Verified with the PostgreSQL 18 documentation and PGlite 0.6.1 (a WebAssembly build that reports PostgreSQL 19.0), on 2026-12-01.
The core idea
A transaction groups several statements into one all-or-nothing unit. ACID names four promises around it: atomicity (all or nothing), consistency (declared rules hold at commit), isolation (concurrent transactions do not see each other's half-finished work, to a degree you choose) and durability (a commit that was reported survives a crash). The isolation level is the dial: each level above the default forbids more anomalies and, in PostgreSQL, asks the application to retry more failures.
Three illustrations run through the lesson, each labelled:
- Minimal example: a two-row wallet table with a
CHECK (balance >= 0)rule, in the lab. - Realistic example: ShopStream reserving stock during checkout, in "In practice".
- Failure example: write skew, where two transactions each follow the rule and together break it.
ACID, one letter at a time
Atomicity
The PostgreSQL tutorial puts it directly: a transaction "bundles multiple steps into a single, all-or-nothing operation", and "if some failure occurs that prevents the transaction from completing, then none of the steps affect the database at all". Two details matter in practice. First, PostgreSQL "treats every SQL statement as being executed within a transaction": without BEGIN, each statement gets its own implicit one. A single UPDATE that fails on one row therefore changes no row (lab section 2). Second, SAVEPOINT lets you undo part of a transaction: rolling back to it discards the changes made after it and keeps the earlier ones, and the savepoint stays defined (lab section 3).
Figure 1. A transaction and what an error does to it. How to read this: after an error inside a transaction, PostgreSQL rejects further commands with SQLSTATE 25P02 until you roll back, either all the way or to a savepoint. The lab shows both the error code and the recovery.
The lab's first section shows the aborted state: after the failing update, even a plain select returns 25P02, and rolling back restores both balances. Application code can hide this: a swallowed exception in the middle of a transaction produces a baffling "current transaction is aborted" a few statements later.
Consistency
In ACID, consistency means that a committed transaction leaves the database satisfying the rules you declared: CHECK, NOT NULL, UNIQUE, foreign keys. It is not the "consistency" of the CAP theorem, which is about replicas agreeing; the CAP lesson and consistency models cover that meaning.
The lab's CHECK (balance >= 0) fails with 23514 (check_violation) when a debit would go negative. Two refinements are worth knowing. NOT NULL and CHECK are always checked immediately, per row; UNIQUE, PRIMARY KEY and foreign keys can be declared DEFERRABLE, in which case a deferred constraint is "not checked until transaction commit". The lab inserts a payment before its account exists, adds the account, and commits cleanly; with a payment whose account never appears, the failure arrives at COMMIT as 23503 and nothing is stored.
The limit of this letter matters more than its definition. The database enforces only the rules it can see. "At least one courier stays on shift" is not a constraint you can declare on one row, so the application must protect it with the isolation level or an explicit lock (write skew, below).
Isolation
Isolation is the letter with options, so it has its own section next.
Durability
PostgreSQL's tutorial states the guarantee: updates are "logged in permanent storage (i.e., on disk) before the transaction is reported complete". The mechanism is write-ahead logging: "changes to data files ... must be written only after those changes have been logged", so after a crash the database "can recover ... using the log", and data pages need not be flushed at every commit. The setting synchronous_commit controls how much WAL processing completes before success is reported; its default is on, and with off there can be "a delay between when success is reported to the client and when the transaction is later guaranteed to be safe against a server crash".
PGlite keeps its database in memory inside one process, so the lab can show none of this: there is no crash to survive. The lab prints a line saying so instead of pretending.
Isolation levels and the anomalies they allow
The SQL standard defines four levels in terms of three phenomena, and PostgreSQL's documentation adds a fourth anomaly.
| Phenomenon | Definition (PostgreSQL documentation) |
|---|---|
| Dirty read | "A transaction reads data written by a concurrent uncommitted transaction." |
| Nonrepeatable read | A transaction re-reads data and finds it modified by another transaction that committed since the first read. |
| Phantom read | A re-executed query returns a different set of rows satisfying its condition because of another recently committed transaction. |
| Serialization anomaly | "The result of successfully committing a group of transactions is inconsistent with all possible orderings of running those transactions one at a time." |
| Level | Dirty read | Nonrepeatable read | Phantom read | Serialization anomaly |
|---|---|---|---|---|
| Read uncommitted | not in PostgreSQL | possible | possible | possible |
| Read committed (default) | not possible | possible | possible | possible |
| Repeatable read | not possible | not possible | not in PostgreSQL | possible |
| Serializable | not possible | not possible | not possible | not possible |
PostgreSQL accepts all four level names but "internally only three distinct isolation levels are implemented": Read Uncommitted behaves like Read Committed. The lab shows a quirk worth knowing: show transaction_isolation inside begin isolation level read uncommitted prints read uncommitted, the name you asked for, although the documented behaviour is Read Committed.
Read Committed
"A statement can only see rows committed before it began." Each statement inside the transaction gets a fresh snapshot, so two SELECTs in one transaction can disagree. When an UPDATE finds a row that a concurrent transaction changed, it waits for that transaction and, if it committed, re-evaluates its WHERE clause against the new version of the row and proceeds if it still matches. That makes UPDATE accounts SET balance = balance - 30 safe, because the arithmetic is applied to the latest value. It also means a statement can see a combination of old and new rows that never existed together; the documentation's example is a DELETE that "will have no effect even though there is a website.hits = 10 row before and after the UPDATE".
Repeatable Read
A query "sees a snapshot as of the start of the first non-transaction-control statement in the transaction, not as of the start of the current statement". Re-reads are stable. The price is that an update that conflicts with a concurrent committed change fails with could not serialize access due to concurrent update, and "applications using this level must be prepared to retry transactions due to serialization failures". The documentation also notes that only updating transactions might need a retry: "read-only transactions will never have serialization conflicts". It warns that enforcing business rules at this level "is not likely to work correctly without careful use of explicit locks".
Serializable
Serializable "emulates serial transaction execution for all committed transactions". PostgreSQL uses predicate locks that "do not cause any blocking", so they cannot cause deadlocks; instead, when a pattern of reads and writes could not have happened in any serial order, one transaction is rolled back with could not serialize access due to read/write dependencies among transactions. The SQLSTATE of all serialization failures is 40001 (serialization_failure). Two rules from the documentation: data read in a Serializable transaction "not be considered valid until the transaction which read it has successfully committed", and the environment needs "a generalized way of handling serialization failures".
Figure 2. A nonrepeatable read, as the documentation describes the levels. How to read this: this is an illustration of documented semantics, not captured output. PGlite is one connection, so this lab cannot run the two sessions; a real PostgreSQL server with two psql sessions can.
Lost update and write skew
Two anomalies deserve names because they are the ones real code meets.
Lost update. Two sessions each read a balance of 100, compute their new value in the application and write it back. One debit is overwritten. At Read Committed it happens whenever the read and the write are separate statements, because nothing detects the conflict; the documentation says Repeatable Read and Serializable fail the later writer with a serialization error instead.
Write skew. Two transactions each read an overlapping set of rows, each decides it is safe to change a different row, and together they break a rule neither saw broken. The documentation's Serializable example is two transactions that each sum one class and insert a row into the other class; Repeatable Read lets both commit, Serializable rolls one back.
The lab replays both. Be precise about what that means: PGlite has one connection, so the "two sessions" are scripted. Each session's read is held in a script variable, which is exactly the state two overlapping sessions would hold, and the writes are then issued one after another. The lab shows the damage and the fixes that do not need concurrency to demonstrate. It does not show what the database would do with two live transactions, and no output in this lesson claims to.
Fixes, in the order to try them:
- Do the arithmetic in the database.
UPDATE ... SET balance = balance - 30is one statement; at Read Committed a concurrent change makes it wait and re-evaluate, as above. - Compare and set. Add a
versioncolumn and writeWHERE id = 1 AND version = 1. A stale writer matches zero rows, notices, re-reads and retries. This is optimistic concurrency, and it is visible on one connection because the loser's row count is 0. - Lock while deciding.
SELECT ... FOR UPDATElocks the rows so that other transactions cannot lock, change or delete them until the transaction ends; row locks block only writers and lockers, not readers. The lab runs the syntax; the waiting only exists with two sessions. - Serializable plus a retry loop. Let PostgreSQL detect the dependency and be ready for
40001.
Pseudocode.
repeat up to N times:
begin transaction at the chosen isolation level
run the reads and writes
commit
if success: stop
if SQLSTATE is 40001 (or a deadlock): roll back, wait with backoff and jitter, retry the WHOLE transaction
otherwise: roll back and raise
The loop must retry the whole transaction, not the failed statement, and everything in it must be safe to run twice, which connects to idempotent operations and retries with backoff and jitter.
Choosing a level: the trade-offs
Figure 3. Which protection fits which race. How to read this: start with the cheapest tool, one conditional statement, and move down only when the rule needs more. Each lower answer costs more in retries or lock waits.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Read Committed with single-statement updates | the default; no retries for conflicts | statements can see different snapshots; read-then-write logic can lose updates | a rule spans several statements or rows |
Read Committed plus SELECT ... FOR UPDATE |
explicit, local protection | lock waits and possible deadlocks; you must remember every place | many code paths touch the data |
Optimistic version column |
no locks held while the user thinks | the loser must retry; needs a column | contention is high and retries pile up |
| Repeatable Read | stable snapshot for reports and multi-statement reads | update conflicts fail and need retries; write skew still possible | the invariant spans rows another transaction can change |
| Serializable | the database finds serialization anomalies | retries on 40001; read-only and short transactions matter |
the application cannot retry safely |
A practical rule from the documentation for Serializable: declare transactions READ ONLY when possible, keep them short, use a connection pool, and avoid leaving connections "idle in transaction". SERIALIZABLE READ ONLY DEFERRABLE is the one case where a Serializable transaction waits to get a safe snapshot, after which it runs without the usual overhead and without any chance of a serialization failure, which suits long reports.
Build it: ACID on one connection
This is the minimal example, a lab you can run. It uses PGlite, real PostgreSQL compiled to WebAssembly and running in-process; the build reports PostgreSQL 19.0 (PGlite 0.6.1) and the links here are the PostgreSQL 18 documentation, the course's target version. The data is two illustrative wallet rows in cents. PGlite is a single in-memory connection.
Goal. See atomicity, savepoints, consistency rules, the isolation-level settings and their rules, and the scripted lost update and write skew.
Setup. From examples/postgres-labs:
node --test labs/isolation-levels/test.mjs
cd labs/isolation-levels && node run.mjs
The first command runs 8 assertions. The code is in examples/postgres-labs/labs/isolation-levels/.
Sections 1 to 3: atomicity. A debit that violates the rule aborts the transaction; a single failing statement changes nothing; a savepoint keeps earlier work.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
## 1. Atomicity: a transaction that fails part-way leaves no trace
> begin
ok
> update accounts set balance = balance - 80 where id = 1
ok affected=1
> update accounts set balance = balance + 80 where id = 2
ok affected=1
> update accounts set balance = balance - 80 where id = 1
ERROR 23514: new row for relation "accounts" violates check constraint "accounts_balance_check"
> select balance from accounts where id = 1
ERROR 25P02: current transaction is aborted, commands ignored until end of transaction block
> rollback
ok
balances after rollback: [100,50]
## 2. Atomicity of a single statement: bob would go negative, so alice's row is not changed either
> update accounts set balance = balance - 60
ERROR 23514: new row for relation "accounts" violates check constraint "accounts_balance_check"
balances: [100,50]
## 3. A savepoint undoes part of a transaction and keeps the rest
> begin
ok
> update accounts set balance = balance - 30 where id = 1
ok affected=1
> savepoint after_first_debit
ok
> update accounts set balance = balance - 80 where id = 1
ERROR 23514: new row for relation "accounts" violates check constraint "accounts_balance_check"
> rollback to after_first_debit
ok
> update accounts set balance = balance + 30 where id = 2
ok affected=1
> commit
ok
balances: [70,80]
Read the aborted transaction: 23514 on the third update, then 25P02 for a harmless select, then rollback and both balances back at [100,50]. In section 3, rollback to after_first_debit discards only the failed 80 coin debit; the first debit and Bob's credit commit, giving [70,80]. The lab's section 4 also shows that a create table inside a transaction vanishes on rollback (to_regclass returns null).
Section 5: consistency checked at commit.
Expected output, captured from a real run (same build):
## 5. Consistency beyond CHECK: a foreign key checked at COMMIT instead of at each statement
> create table payments (id int primary key, account_id int references accounts(id) deferrable initially deferred, amount int not null)
ok
> begin
ok
> insert into payments values (1, 99, 10)
ok affected=1
> insert into accounts values (99, 'carol', 0, 1)
ok affected=1
> commit
ok
> begin
ok
> insert into payments values (2, 77, 10)
ok affected=1
> commit
ERROR 23503: insert or update on table "payments" violates foreign key constraint "payments_account_id_fkey"
> select id from payments order by id
ok rows=[{"id":1}]
The first transaction inserts the payment before its account and still commits, because the foreign key is deferred; the second fails at commit with 23503 and leaves only payment 1.
Section 6: isolation settings and their rules.
Expected output, captured from a real run (same build):
## 6. Isolation level settings and their rules
> show transaction_isolation
ok rows=[{"transaction_isolation":"read committed"}]
> begin isolation level read uncommitted
ok
> show transaction_isolation
ok rows=[{"transaction_isolation":"read uncommitted"}]
> rollback
ok
> begin isolation level repeatable read
ok
> show transaction_isolation
ok rows=[{"transaction_isolation":"repeatable read"}]
> select 1 as first_query
ok rows=[{"first_query":1}]
> set transaction isolation level serializable
ERROR 25001: SET TRANSACTION ISOLATION LEVEL must be called before any query
> rollback
ok
> begin isolation level serializable read only deferrable
ok
> show transaction_isolation
ok rows=[{"transaction_isolation":"serializable"}]
> show transaction_read_only
ok rows=[{"transaction_read_only":"on"}]
> show transaction_deferrable
ok rows=[{"transaction_deferrable":"on"}]
> insert into accounts values (100, 'dave', 0, 1)
ERROR 25006: cannot execute INSERT in a read-only transaction
> rollback
ok
Note four things: the default is read committed; read uncommitted is accepted and reported under that name; set transaction isolation level serializable after a first query fails with 25001, as the documentation's "cannot be changed after the first query" rule says; and a write inside serializable read only deferrable fails with 25006.
Sections 7 and 8: scripted lost update and write skew. These are not concurrent output.
Expected output, captured from a real run (same build):
## 7. Scripted lost update (NOT concurrent: each session's read is held in this script, as two overlapping app sessions would hold it)
session A read balance 100; session B read balance 100
> update accounts set balance = 100 - 30 where id = 1
ok affected=1
> update accounts set balance = 100 - 50 where id = 1
ok affected=1
final balance: 50 (two debits of 30 and 50 from 100 should leave 20)
fix 1: let the database do the arithmetic in one statement
> update accounts set balance = balance - 30 where id = 1
ok affected=1
> update accounts set balance = balance - 50 where id = 1
ok affected=1
final balance: 20
fix 2: optimistic check with a version column (compare and set)
> update accounts set balance = 70, version = version + 1 where id = 1 and version = 1
ok affected=1
> update accounts set balance = 50, version = version + 1 where id = 1 and version = 1
ok affected=0
session B matched 0 rows, so it re-reads and retries:
> update accounts set balance = 70 - 50, version = version + 1 where id = 1 and version = 2
ok affected=1
final balance: 20
The read-then-write version ends at 50 instead of 20; the in-database arithmetic and the version check both end at 20, and the version-check loser matched zero rows and retried.
Expected output, captured from a real run (same build):
## 8. Scripted write skew (NOT concurrent): each courier checks 'at least one other courier is on shift' against the same snapshot
> create table shifts (courier text primary key, store_id int not null, on_shift boolean not null)
ok
> insert into shifts values ('ana', 7, true), ('ben', 7, true)
ok affected=2
ana's transaction sees 2 couriers on shift; ben's transaction sees 2
> update shifts set on_shift = false where courier = 'ana'
ok affected=1
> update shifts set on_shift = false where courier = 'ben'
ok affected=1
couriers on shift afterwards: 0 (the rule said at least 1)
The two UPDATEs touch different rows, so no row lock makes either wait. Whether the engine lets both commit depends on the isolation level and needs two sessions to observe.
## 9. Durability
not shown: this engine keeps the database in memory in one process, so there is no crash to survive and no log flush to wait for.
Both couriers saw 2 on shift and both stepped off, leaving 0. The lab then states what it cannot show: whether the engine would let both commit depends on the isolation level and needs two live sessions.
What two real sessions would add. At Read Committed, session A's second SELECT would show session B's committed change. At Repeatable Read, a concurrent update of the same row would fail with could not serialize access due to concurrent update. At Serializable, one of the two write-skew transactions would fail with could not serialize access due to read/write dependencies among transactions (SQLSTATE 40001). With FOR UPDATE, the second session would wait. The PostgreSQL documentation describes each; this lab does not capture them.
Break it. In run.mjs, change fix 1 of section 7 to read the balance into a variable and write variable - 30: the final balance goes back to 50. Restore it and rerun the tests.
In practice: ShopStream reserves stock during checkout
This is the realistic example, an educational scenario on ShopStream, the course's running grocery marketplace. Every number is illustrative.
This is a realistic scenario, not a case history.
The situation
A store has 3 units of a popular item left. Checkout runs a transaction that reads the stock row, checks that the quantity requested is available, subtracts it and creates the order line. During a promotion, two shoppers each ask for 2 units within the same moment. Both read 3, both pass the check, and both orders are accepted: the store has promised 4 units it does not have.
Starting architecture
Figure 4. The checkout transaction. How to read this: stock and orders live in the same PostgreSQL database, so one transaction can cover both. The bug is not in the transaction boundary but in how the stock row is read and written inside it.
Options considered
| Option | Effect | Risk |
|---|---|---|
| A. Keep read, check, write; switch to Serializable | PostgreSQL detects the conflict and fails one order with 40001 |
every order path needs a retry loop; contention shows up as failures |
B. One conditional statement: UPDATE stock SET units = units - 2 WHERE ... AND units >= 2 |
the check and the write are one statement; zero rows updated means sold out | fits a single-row rule only |
C. SELECT ... FOR UPDATE on the stock row first |
the second checkout waits | lock waits under promotion load; deadlocks if two items are locked in different orders |
The decision
Option B for the stock count, at the default Read Committed: it is one statement, the second checkout waits for the first and re-evaluates the condition, and "zero rows updated" becomes a clean "sold out" answer. The rule that spans rows ("every store keeps at least one courier on shift") is the write-skew shape, so that one path uses Serializable with a retry loop, backoff and jitter, and a cap on attempts.
Rollout and verification
Before enabling Serializable anywhere, the retry wrapper ships first and is tested with a forced 40001. Verification watches counts: orders accepted versus units available per item after a promotion, serialization failures per minute on the courier path, retries that exhausted their cap, and sessions left idle in a transaction. The reconciliation query "accepted units never exceed stock plus returns" runs after each promotion.
The 2 a.m. failure
The pager shows a spike of failed courier updates right after a deploy. A new endpoint calls the same transaction from a loop without the retry wrapper, and under load a fraction of calls fail with 40001 and surface as errors to the operator console. The failure is not the database misbehaving: the documentation says Serializable applications must be ready to retry. The checks are the count of 40001 errors by endpoint and whether that endpoint uses the shared wrapper. The mitigation is routing the endpoint through the wrapper; the lasting fix is a lint or a test that fails any Serializable transaction not run through it.
Architect's notes
- Say which "consistency" you mean. ACID consistency is declared rules at commit; CAP consistency is replicas agreeing.
- Prefer one conditional statement over read, check, write. It removes the race at the cheapest level.
- Treat
40001as normal. A path that can fail with it needs a bounded retry of the whole transaction. - Keep transactions short and read-only when possible. It lowers conflicts and, at Serializable, overhead.
- Know what your test environment cannot show. One connection will not reveal a race; write a two-session test against a real server before relying on a level.
Common mistakes
- Equating ACID consistency with CAP consistency.
- Assuming Repeatable Read prevents all anomalies. Write skew is still possible; the documentation warns about business rules.
- Retrying only the failed statement. The whole transaction must be retried.
- Swallowing an exception inside a transaction. Later statements fail with
25P02. - Expecting
READ UNCOMMITTEDto read uncommitted data. PostgreSQL treats it as Read Committed. - Leaving sessions idle in a transaction. The documentation advises avoiding it, especially at Serializable.
Key takeaways
- A transaction is all-or-nothing; a single statement is also atomic, and savepoints undo part of a transaction.
- ACID consistency means declared rules hold at commit; deferred constraints are checked at
COMMIT. - PostgreSQL has three distinct levels; Read Uncommitted is Read Committed.
- Read Committed uses a new snapshot per statement; Repeatable Read one snapshot per transaction; Serializable adds detection of serialization anomalies.
- Repeatable Read and Serializable can fail with
40001-class errors, and the answer is to retry the whole transaction. - Lost updates are fixed by arithmetic in SQL, version checks or locks; write skew needs Serializable or explicit locking.
- One connection can show atomicity, constraints and settings, but not concurrent anomalies or durability.
Practice exercises
Exercise 1 (20 min). For each of the four phenomena in the table, name the lowest PostgreSQL level at which it cannot happen.
Exercise 2 (45 min). Add a deferred UNIQUE constraint to the lab and show a swap of two values that fails when immediate and succeeds when deferred.
Exercise 3 (1 hour). Using a real PostgreSQL server (outside this lab) and two psql sessions, run the write-skew scenario at Repeatable Read and at Serializable and record both outputs. Compare with the lesson's "what two real sessions would add".
Exercise 4 (2 hours). Write the retry wrapper in your language of choice for 40001, with bounded attempts, backoff and jitter, and a test that forces the error.
Related reading
- Databases basics: tables, indexes and transactions in one page.
- Distributed transactions: what changes when a transaction spans services.
- CAP theorem and PACELC: the other meaning of consistency.
- Consistency models: linearizability and weaker models.
- Timeouts, retries, backoff and jitter: how to retry safely.
- Idempotent and commutative operations: why retries must be safe.
- Later lessons in this module (plain text): MVCC, locking (optimistic, pessimistic and deadlocks),
@Transactionalin Spring.
Official documentation
- PostgreSQL 18, Transactions: atomicity, savepoints, durability.
- PostgreSQL 18, Transaction isolation: the levels, phenomena, retries.
- PostgreSQL 18, SET TRANSACTION: setting a level, read-only and deferrable.
- PostgreSQL 18, SET CONSTRAINTS: deferred constraints.
- PostgreSQL 18, Write-ahead logging and WAL configuration: durability.
- PostgreSQL 18, Error codes:
25P02,23514,23503,40001.