Summary#
A transaction is a group of reads and writes the database treats as one unit. ACID describes its guarantees: Atomicity (all or nothing), Consistency (rules and invariants hold), Isolation (concurrent transactions do not see each other's half-done work) and Durability (committed data survives crashes, thanks to the write-ahead log). Full isolation is expensive, so databases offer isolation levels that allow some anomalies: dirty reads, non-repeatable reads, phantoms, lost updates and write skew. Most databases implement isolation with MVCC (multiple row versions) and snapshot isolation. Defaults differ: PostgreSQL uses Read Committed; MySQL InnoDB uses Repeatable Read. Know which anomalies your level allows, and protect critical invariants with locks, constraints or Serializable.
Why It Exists#
Two problems break data without transactions. Failures: a server crashes halfway through moving money between accounts, leaving money debited but not credited. Concurrency: two requests read the same balance, both subtract, and one update is silently lost. Transactions let application code pretend each operation runs alone and completes fully, while the database handles crashes and interleaving. This page builds on Relational Databases.
How It Works#
Atomicity, consistency, isolation, durability#
- Atomicity: if any statement fails, or the client disconnects before
COMMIT, every change in the transaction is rolled back. There is no partial result. ("Abortability" is a better name.) - Consistency: the transaction moves the database from one valid state to another. The database enforces declared rules (keys,
CHECK, foreign keys); other invariants ("total money is unchanged") depend on the application writing correct transactions. This "C" is different from the C in CAP, which is about replicas agreeing. - Isolation: concurrent transactions behave as if they ran in some order, to the degree the isolation level promises.
- Durability: once
COMMITreturns, the data survives crashes and power loss. In replicated systems, durability often also means "written to more than one machine".
ACID in depth#
The idea of a transaction as a unit of work is older than the acronym. Jim Gray's 1981 paper "The Transaction Concept: Virtues and Limitations" described transactions as atomic, consistent and durable. In 1983 Theo Härder and Andreas Reuter added isolation and coined ACID in "Principles of Transaction-Oriented Database Recovery". The four letters are not equally precise, and each hides real engineering.
Atomicity is really about undo. A transaction that touches 50 rows may have changed 30 of them when it fails, because of a constraint violation, a deadlock, a crash or a lost client connection. Atomicity means the database can undo those 30 changes as if they never happened. Different engines achieve this differently. InnoDB records the old value of each change in an undo log and applies those records backwards on rollback. PostgreSQL never overwrites rows: it marks the transaction as aborted in its commit log, so every new row version it wrote becomes invisible at once, and vacuum cleans up later. Either way, the application only needs one rule: if anything fails, the whole transaction is gone and can be retried from the start.
Notice that atomicity says nothing about concurrency. It is about failure. Many people confuse it with "atomic operations" in multithreaded programming, which is closer to isolation.
Consistency is mostly your job. The database checks the rules you declare: primary keys, unique indexes, foreign keys, CHECK constraints and triggers. Everything else, such as "debits equal credits" or "a seat is sold at most once", holds only if every transaction that touches the data is written correctly. Härder and Reuter themselves treated the C as a property of the application's transactions rather than of the engine. The practical lesson is to push as many invariants as possible into declared constraints, because the database enforces them for every code path, including the hotfix script someone runs at 2 a.m.
The word "consistency" means at least three different things in system design, which causes endless confusion:
| Term | Meaning | Where it comes up |
|---|---|---|
| C in ACID | Data obeys the application's invariants | Single-database transactions |
| C in CAP | Every read sees the latest write (linearizability) | Replicated and distributed systems |
| Eventual or causal consistency | Rules about when replicas converge and in what order | Replication, caches, CDNs |
Isolation is the expensive letter. Perfect isolation (serializability) means the outcome equals some one-at-a-time ordering of the transactions. Achieving it needs either waiting (locks) or aborting and retrying (optimistic checks), and both cost throughput under contention. That is why databases offer weaker levels, covered below.
Durability is a spectrum, not a switch. "Committed data survives" depends on which failures you mean:
- Process crash: the data is in the operating system's page cache, which survives the database process restarting.
- Machine crash or power loss: the log must be fsynced to stable storage before commit returns.
- Disk loss: the data must be on more than one disk, through RAID, a replicated cloud volume or a replica.
- Data-centre loss: the commit must reach another site, through synchronous replication across zones or regions.
Each step adds latency. A local fsync takes tens to hundreds of microseconds on NVMe. A synchronous copy to another availability zone adds about 1-2 ms. A copy to another region adds tens of milliseconds. Payment systems typically commit synchronously to at least two zones. Analytics pipelines may accept a few lost seconds.
A worked transfer. Moving 100 dollars from account A to B, with double-entry ledger rows for auditability:
BEGIN;
UPDATE accounts SET balance = balance - 100
WHERE id = 'A' AND balance >= 100; -- 0 rows -> insufficient funds
-- application checks row count = 1, else ROLLBACK
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
INSERT INTO ledger_entries (txn_id, account_id, amount)
VALUES ('t-981', 'A', -100), ('t-981', 'B', 100);
COMMIT;All four writes commit together or not at all. The conditional WHERE balance >= 100 makes the check and the debit one atomic statement, so two concurrent withdrawals cannot both pass the check. The ledger rows are append-only: corrections are new entries, never edits. You can therefore always prove how a balance was reached, which is the core of auditability. A CHECK (balance >= 0) constraint and a unique txn_id per account add a second line of defence against bugs and duplicate retries.
Autocommit. Without an explicit BEGIN, most drivers run each statement as its own transaction. A single UPDATE is therefore already atomic and isolated as one statement. Problems start when application code issues several dependent statements without a surrounding transaction, or opens a transaction and forgets to close it, which holds locks and old row versions indefinitely.
Write-ahead log#
Databases do not overwrite data pages in place at commit time; that would need many random writes. Instead they append every change to a sequential write-ahead log (WAL; InnoDB calls it the redo log), and fsync it to disk before confirming the commit. Data pages are updated in memory and written to disk later, at a checkpoint.
After a crash, the database replays the log from the last checkpoint: committed changes are redone, uncommitted ones are discarded or undone. Sequential log writes are fast, which is why one commit costs roughly one fsync (well under a millisecond on NVMe). Many databases also group commit: several transactions share one fsync. The same log feeds replication and change data capture.
Write-ahead logging in depth#
Härder and Reuter also gave us the vocabulary for how a database moves changed pages between memory and disk. Two choices define the design space:
- Steal or no-steal: may a page changed by an uncommitted transaction be written to disk, for example to free buffer space? Allowing it ("steal") keeps memory use bounded, but then recovery must be able to undo those changes.
- Force or no-force: must every page a transaction changed be written to disk at commit? Requiring it ("force") makes commits slow, with many random writes. Not requiring it ("no-force") means recovery must be able to redo committed changes whose pages never reached disk.
Almost every serious engine chooses steal plus no-force, because it is the fastest combination, and pays for it with a log that supports both undo and redo. That is the write-ahead log, and the "write-ahead" rule is the one invariant that makes it safe: a log record must be on disk before the data page it describes.
Each log record gets a log sequence number (LSN), its byte position in the log. Every data page stores the LSN of the last change applied to it. During recovery the database compares the two. If a page's LSN is already at or past a record's LSN, the change is already on the page and is skipped. Otherwise it is reapplied. This makes redo idempotent: replaying the same log twice, for instance after a crash during recovery, gives the same result.
The commit path looks like this:
Group commit in numbers. Suppose an fsync takes 0.5 ms. One connection committing serially can do at most about 2,000 commits per second. With 50 concurrent connections, a single fsync can carry the commit records of everyone who committed in that half-millisecond window, so the server can reach tens of thousands of commits per second while each client still waits about one fsync. On a cloud network volume with a 2 ms fsync, the single-connection ceiling falls to about 500 commits per second. This is why batching writes into fewer transactions, or adding concurrency, often helps more than faster CPUs.
Torn pages. A database page is usually 8 KB (PostgreSQL) or 16 KB (InnoDB), but a disk may guarantee atomic writes only for 4 KB or even 512-byte sectors. A crash mid-write can leave half a new page and half an old one: a torn page, which log replay alone cannot fix, because redo records assume a valid starting page. PostgreSQL's answer is full_page_writes: the first change to a page after each checkpoint logs the entire page image, so recovery can restore it whole. InnoDB uses a doublewrite buffer: pages are first written to a separate area, then to their real location, so one intact copy always exists. Both cost extra write volume, often a noticeable share of WAL size right after checkpoints.
Durability knobs and what they actually risk:
| Setting | Default | If relaxed |
|---|---|---|
PostgreSQL synchronous_commit | on | off: commits return before fsync. A crash loses up to about three times wal_writer_delay (200 ms by default) of commits, but never corrupts data |
PostgreSQL fsync | on | off: a crash can corrupt the database. Never in production |
MySQL innodb_flush_log_at_trx_commit | 1 | 2: written to the OS on commit, fsynced about once per second. An OS crash loses about 1 s. 0 risks about 1 s even on a database crash |
MySQL sync_binlog | 1 | Higher values batch binlog fsyncs. Replicas may then miss transactions the primary committed |
Note the PostgreSQL detail: relaxing synchronous_commit loses recent transactions but keeps the database consistent, while turning off fsync can leave it unrecoverable. The two are often confused.
The log beyond recovery. Because the WAL is a complete ordered record of changes, it is reused for physical streaming replication, for point-in-time recovery (base backup plus archived WAL), and through logical decoding for change data capture into Kafka or a search index. In payment systems that must "never lose a transaction", the combination of synchronous replication of the WAL to another zone, continuous WAL archiving to object storage and an append-only ledger table is a common design for both durability and auditability.
Anomalies#
These are the things that go wrong when transactions interleave.
| Anomaly | What happens | Example |
|---|---|---|
| Dirty read | Reading another transaction's uncommitted data | You see a balance that is then rolled back |
| Non-repeatable read | Reading the same row twice gives different values, because someone committed in between | A report reads a balance at the start and end and the numbers do not match |
| Phantom | Re-running a query returns a different set of rows, because someone inserted or deleted matching rows | "Count bookings for room 7 at 10:00" changes mid-transaction |
| Lost update | Two transactions read, modify and write the same row; one overwrites the other | Two clicks each add 1 to a counter; it goes up by 1 |
| Write skew | Two transactions read the same data, each makes a decision based on it and updates different rows; together they break an invariant | Two doctors both go off call, leaving nobody on call |
Lost update, step by step:
Fixes: an atomic update (UPDATE ... SET stock = stock - 1), SELECT ... FOR UPDATE, or a version check. See Concurrency Control and Locking.
Write skew is subtler, because the two transactions never touch the same row:
Each transaction was correct on its own snapshot. The same pattern appears in double booking a meeting room (both check "no overlapping booking", both insert), usernames claimed twice when there is no unique constraint, and spending limits exceeded by parallel purchases.
Anomalies in depth#
The table above lists the five anomalies interviewers ask about. The full picture comes from "A Critique of ANSI SQL Isolation Levels" (Berenson, Bernstein, Gray, Melton, O'Neil and O'Neil, SIGMOD 1995). It showed that the SQL standard's English definitions were ambiguous, added the missing phenomena, and named snapshot isolation. Its labels are still used:
| Code | Name | Pattern (w = write, r = read, c = commit) |
|---|---|---|
| P0 | Dirty write | T1 writes x, T2 overwrites x before T1 commits or aborts |
| P1 | Dirty read | T2 reads x written by T1 before T1 finishes |
| P2 | Non-repeatable (fuzzy) read | T1 reads x, T2 changes x and commits, T1 reads x again |
| P3 | Phantom | T1 reads rows matching a condition, T2 inserts or deletes a matching row |
| P4 | Lost update | T1 reads x, T2 writes x, T1 writes x based on its stale read |
| A5A | Read skew | T1 reads x, T2 updates x and y and commits, T1 reads y and sees an inconsistent pair |
| A5B | Write skew | T1 reads x and y, T2 reads x and y, T1 writes x, T2 writes y, both commit |
Dirty writes are prevented at every level in real databases, because writers always lock the rows they change until commit. If they did not, rollback would be impossible to define: undoing T1's write would also erase T2's.
Read skew is the everyday face of non-repeatable reads. A transfer moves 100 from account A to B. A report at Read Committed reads A before the transfer and B after it, and so concludes the bank holds 100 more than it really does. Each statement saw committed data, but the two statements saw different moments. Snapshot-based Repeatable Read fixes this, because both reads use one snapshot. That matters for backups, reports, and any multi-step read that must add up.
Phantoms are about conditions, not rows. Locking every row you read cannot stop a phantom, because the problem row does not exist yet. Protecting against phantoms means locking the condition itself: a range of an index ("all bookings for room 7 between 10:00 and 11:00") or a predicate. InnoDB does this with next-key and gap locks on index ranges. PostgreSQL's Serializable tracks predicate reads with SIREAD locks. Without an index on the condition, both may fall back to coarse locks covering the whole table, which is one more reason to index the columns your check queries filter on.
Lost updates hide in application code. The pattern "read a value, compute in the application, write it back" appears all the time: incrementing a like counter, decrementing stock, appending to a JSON array in a column, updating a running average. At Read Committed, two concurrent requests can both read the old value. Four standard fixes, from simplest to most general:
- Atomic update in SQL:
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock > 0. The database reads and writes under the row lock in one step. - Locking read:
SELECT ... FOR UPDATE, then compute, thenUPDATE. Use it when the computation cannot be expressed in SQL. - Compare-and-set with a version column:
UPDATE ... SET v = v + 1, ... WHERE id = 42 AND v = 7. Zero rows updated means someone else won, so re-read and retry. This is optimistic concurrency control. - A stronger isolation level that detects the conflict and aborts: PostgreSQL Repeatable Read or Serializable.
Worked example: keeping an average rating correct. A review site shows each business's average rating in search results, so recomputing AVG(stars) over thousands of reviews on every search is wasteful. Store rating_sum and rating_count on the business row and update them in the same transaction that inserts the review:
BEGIN;
INSERT INTO reviews (business_id, user_id, stars, body)
VALUES (77, 1234, 4, '...'); -- UNIQUE (business_id, user_id)
UPDATE businesses
SET rating_sum = rating_sum + 4,
rating_count = rating_count + 1
WHERE id = 77;
COMMIT;
-- average = rating_sum / rating_count, computed on readBecause the update is relative (+ 4, + 1), two simultaneous reviews cannot overwrite each other, at any isolation level. A version that read the old average, computed a new one in the application and wrote it back would lose reviews under concurrency. The unique constraint stops one user reviewing twice even if they double-click. For a very popular business, every review now updates one hot row. At extreme rates you would batch the increments, for example applying them from a queue every few seconds, and accept a slightly stale average.
Write skew in many disguises. The pattern is always the same: read a set of rows, decide, write somewhere else. Examples:
- On-call doctors: at least one doctor must stay on call. Each transaction checks the count and removes a different doctor.
- Meeting rooms: each transaction checks "no overlapping booking" and inserts a new booking row.
- Usernames: each checks "name not taken" and inserts, which a unique index fixes trivially.
- Spending limits: each sums today's purchases, sees room under the limit, and inserts a purchase.
- Game moves: two players move different pieces onto the same square.
Three general fixes exist when the database's level allows write skew:
- Use Serializable and retry on failure.
- Lock the rows you read with
SELECT ... FOR UPDATE, which works when the rows you check already exist, as with the doctors. - Materialise the conflict: when the check is about absence, as with free rooms, create rows that represent the thing being contended, such as one row per room per 15-minute slot, and lock or uniquely constrain them. This turns an invisible conflict into a row-level one that ordinary locks can catch. It feels artificial, so prefer Serializable or a constraint (a PostgreSQL exclusion constraint on time ranges) when available.
Isolation levels#
The SQL standard defines four levels by which anomalies they prevent. Real databases differ in the details, so this table shows common behaviour:
| Level | Dirty read | Non-repeatable read | Phantom | Lost update | Write skew |
|---|---|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible | Possible | Possible |
| Read Committed | Prevented | Possible | Possible | Possible | Possible |
| Repeatable Read / Snapshot | Prevented | Prevented | Mostly prevented for reads (snapshot) | Postgres: prevented (aborts); MySQL: possible | Possible |
| Serializable | Prevented | Prevented | Prevented | Prevented | Prevented |
- Read Uncommitted is rarely used; PostgreSQL treats it as Read Committed.
- Read Committed: each statement sees data committed before it began. Simple and fast, but two reads in one transaction can disagree.
- Repeatable Read: in PostgreSQL and MySQL this is based on a snapshot: the whole transaction sees the database as of its first read. PostgreSQL aborts a transaction that tries to update a row changed by a concurrent committed transaction ("could not serialize access"), which prevents lost updates. MySQL instead lets the second update proceed on the latest row version, so read-modify-write cycles can still lose updates unless you use locking reads.
- Serializable: the result equals some serial order of the transactions. It is the only level that prevents write skew in general.
Isolation levels in depth#
Two ways to implement isolation. Historically, databases used two-phase locking (2PL): a transaction takes shared locks for reads and exclusive locks for writes, and releases them only at the end. Writers block readers and readers block writers, which is correct but slow under contention, and deadlocks are common. Modern engines use MVCC for reads and locks only for writes. Under MVCC each level is mostly a statement about which snapshot a read uses and what happens when two writers collide:
| Level (PostgreSQL) | Snapshot taken | Concurrent update of the same row |
|---|---|---|
| Read Committed | New snapshot per statement | Wait for the other writer, then re-check the row's latest version and continue |
| Repeatable Read | One snapshot at the first statement | Wait. If the other writer committed, abort with a serialization error |
| Serializable | One snapshot plus read tracking | As Repeatable Read, and also abort dangerous read-write patterns |
Read Committed's re-check, explained. In PostgreSQL, when an UPDATE ... WHERE stock > 0 finds a row locked by another transaction, it waits. If that transaction commits, PostgreSQL re-evaluates the WHERE clause against the new version of that row (internally called EvalPlanQual) and updates it only if it still matches. This is why the atomic UPDATE ... SET stock = stock - 1 WHERE stock > 0 pattern is safe even at Read Committed. The subtle part is that other rows in the same statement were read from the statement's original snapshot, so complex multi-row updates at Read Committed can still see a mix of old and new data.
MySQL's Repeatable Read is two levels in one. InnoDB distinguishes consistent reads (plain SELECT, served from the transaction's snapshot, or read view) from current reads (UPDATE, DELETE, SELECT ... FOR UPDATE and FOR SHARE, which read the latest committed version and lock it). Within one transaction a plain SELECT can therefore show stock = 10 while an UPDATE ... SET stock = stock - 1 operates on the latest value, say 7, and leaves 6. Reads are repeatable, but writes use fresh data without aborting. That avoids serialization errors but means a read-then-write in application code can lose updates unless the read is a locking read. Current reads also take next-key locks (a row lock plus a lock on the gap before it in the index), which block inserts into scanned ranges. That prevents phantoms for locking reads, at the cost of more lock waits and deadlocks than PostgreSQL's design.
Here is the PostgreSQL Repeatable Read behaviour that prevents a lost update by aborting:
Read Uncommitted in practice. PostgreSQL silently upgrades it to Read Committed. In SQL Server and MySQL it really does return uncommitted data. It is sometimes used (often through WITH (NOLOCK) hints in SQL Server) for rough monitoring queries that must not wait on locks, but results can include rows that are later rolled back, and with lock-based scans even rows read twice or skipped. It is almost never appropriate for business logic.
The cost of each level in numbers. On a low-contention workload, the difference between Read Committed and Serializable in PostgreSQL is often modest: SSI's tracking costs some CPU and memory, frequently in the range of a few to tens of percent. The real cost appears with contention. If 5% of transactions conflict and each conflict aborts one of them, you redo that work and add latency to those requests. With hot rows (a single counter updated by everyone), abort rates can climb sharply, and then explicit locking or a redesign (sharded counters, queued updates) works better than optimistic Serializable.
MVCC#
Multi-version concurrency control keeps several versions of each row instead of locking rows for reads. Each version is tagged with the transaction that created it (and the one that deleted or replaced it). A reader chooses the versions visible to its snapshot; a writer creates a new version. So readers never block writers and writers never block readers. Only writers to the same row wait for each other.
- PostgreSQL stores new row versions in the table itself; old versions are removed later by VACUUM. Long-running transactions keep old versions alive and cause table bloat.
- MySQL InnoDB and Oracle update the row in place and keep old versions in an undo log, rebuilding older versions for readers that need them.
MVCC in depth#
MVCC stops being magic once you see the bookkeeping. Here is PostgreSQL first, because its design is easy to inspect.
Row versions carry transaction IDs. Every transaction that writes gets a 32-bit transaction ID (XID). Every row version (a "tuple") stores two hidden fields: xmin, the XID that created it, and xmax, the XID that deleted or replaced it (0 if still current). An UPDATE is really "set xmax on the old version and insert a new version with xmin = me". You can see these fields with SELECT xmin, xmax, * FROM accounts.
A snapshot is three numbers and a list. When a statement (at Read Committed) or a transaction (at Repeatable Read and above) starts, PostgreSQL records:
xmin: the oldest XID still running; everything older has finished;xmax: the next XID to be assigned; everything at or above it has not started from this snapshot's point of view;xip: the list of XIDs in between that were still in progress.
A row version is visible to the snapshot if its creator committed and is "in the past" for this snapshot (below xmax and not in xip), and its deleter is either absent, aborted, or not yet in the past. Commit status is looked up in the commit log (pg_xact) and cached on the tuple as hint bits, so later readers do not repeat the lookup.
Worked example. Transaction 205 updates account A from 500 to 400 and commits. A report that took its snapshot while 205 was still running has 205 in its xip list, so it still sees version 1 (500), even though version 2 exists. A new transaction sees version 2. Nobody waited on a lock to read.
The price: garbage. Version 1 is dead once no snapshot can see it, but it still occupies space in the table and in every index that points at it. VACUUM (usually autovacuum) finds such dead tuples, marks their space reusable and removes their index entries. It also maintains the visibility map, which records pages where every tuple is visible to everyone. Index-only scans use it to skip heap visits. If vacuum cannot keep up, or if one long-running transaction pins an old snapshot, dead tuples pile up. Tables and indexes grow (bloat), scans read more pages, and caches hold less useful data. A forgotten transaction in an idle in transaction session for six hours on a busy database can leave tens of millions of dead tuples. Setting idle_in_transaction_session_timeout and alerting on the age of the oldest transaction are standard defences.
XID wraparound. With 32-bit XIDs, comparisons work on a circle of about 4.3 billion values, where "the past" is the 2^31 (about 2.1 billion) XIDs behind the current one. A tuple older than that would suddenly look like it was in the future and vanish. To prevent this, vacuum freezes old tuples, marking them as visible to everyone regardless of XID. Autovacuum forces an aggressive freezing pass when a table's oldest unfrozen XID passes autovacuum_freeze_max_age (200 million by default). If freezing still falls dangerously behind, PostgreSQL stops assigning new XIDs, so writes stop until a vacuum completes. A database burning 10,000 write transactions per second consumes 2 billion XIDs in about 55 hours, which is why busy systems must keep autovacuum healthy.
InnoDB does the same job differently. Each clustered-index record has hidden fields: DB_TRX_ID (the last transaction that changed it) and DB_ROLL_PTR, a pointer into the undo log to the previous version. Updates happen in place, and the old values move to undo. A reader whose read view cannot see the current version follows the roll pointer chain backwards, rebuilding older versions until it finds a visible one. A background purge thread deletes undo records once no read view needs them. The InnoDB counterpart of PostgreSQL bloat is a long history list length: undo that cannot be purged because an old transaction is still open. Readers walking long chains get slower, and undo tablespace grows.
| Aspect | PostgreSQL | InnoDB |
|---|---|---|
| Where old versions live | In the table heap itself | In the undo log |
| Current version lookup | May need to skip dead versions | Always the in-place record |
| Old snapshot read | Direct, the version is in the heap | Rebuilt by walking undo |
| Cleanup | VACUUM | Purge thread |
| Symptom of long transactions | Table and index bloat | Long history list, slow reads |
| Rollback cost | Cheap, mark aborted | Expensive, apply undo records |
Oracle also uses undo segments. Its classic error ORA-01555 snapshot too old appears when a long query needs an undo record that has already been overwritten: the same trade-off, surfaced as a failed query instead of growing storage.
Snapshot isolation#
Snapshot isolation is MVCC applied to a whole transaction: it reads from a consistent snapshot taken at its start, and its writes become visible atomically at commit. If two concurrent transactions write the same row, one must abort ("first committer wins"). This prevents dirty reads, non-repeatable reads, read phantoms and lost updates on the same row, which is why it is very popular. It does not prevent write skew, because write skew involves different rows.
Serializable Snapshot Isolation (SSI), used by PostgreSQL's Serializable level, adds tracking of read/write dependencies between concurrent transactions and aborts one when a dangerous pattern appears. It gives true serializability without locking reads, at the cost of some aborts that the application must retry. MySQL's Serializable instead uses locks: plain reads become shared-locking reads (when autocommit is off), so concurrent writers wait.
Note that Oracle's level named "Serializable" is actually snapshot isolation, so it can allow write skew. Names are not reliable across vendors; check the documentation.
Snapshot isolation and SSI in depth#
First committer wins versus first updater wins. The original definition of snapshot isolation says that when two concurrent transactions write the same row, the one that commits first wins and the other aborts at its commit. Real implementations detect the conflict earlier. In PostgreSQL the second writer waits on the row lock. If the first commits, the second aborts immediately, and if the first aborts, the second proceeds. The effect is the same, but nobody wastes time on doomed work.
Why write skew slips through. Snapshot isolation checks only write-write conflicts. In the on-call example, Alice's transaction writes Alice's row and Bob's writes Bob's row. No row is written twice, so no conflict is detected, yet each transaction's decision was based on a read the other one invalidated. That kind of dependency, "T1 read something that T2 then overwrote", is a read-write antidependency (rw-conflict).
The key theorem. Alan Fekete and colleagues showed in 2005 ("Making Snapshot Isolation Serializable", ACM TODS) that every non-serializable execution under snapshot isolation contains a cycle with two consecutive rw-antidependency edges between concurrent transactions: a "pivot" transaction that both reads something another transaction later writes and writes something a third transaction read. Michael Cahill, Uwe Röhm and Alan Fekete turned this into an algorithm in "Serializable Isolation for Snapshot Databases" (SIGMOD 2008). Track rw-antidependencies at runtime, and abort a transaction when it would become such a pivot. This is Serializable Snapshot Isolation (SSI). Dan Ports and Kevin Grittner described its implementation in PostgreSQL 9.1 in "Serializable Snapshot Isolation in PostgreSQL" (VLDB 2012).
How PostgreSQL tracks reads. Serializable transactions take SIREAD locks, which are not really locks because they never block anyone. They record "this transaction read this tuple, this page, or this relation". When another transaction writes something covered by a SIREAD lock, PostgreSQL records an rw-edge. If a transaction ends up with both an incoming and an outgoing rw-edge to concurrent transactions, one transaction in the structure is aborted with SQLSTATE 40001. To bound memory, fine-grained SIREAD locks are promoted to coarser ones (tuple to page to relation) when there are many of them. That produces false positives: aborts where no real anomaly existed. The design accepts some unnecessary retries in exchange for never blocking.
Practical tips for SSI.
- Declare read-only transactions as
READ ONLY. PostgreSQL can then optimise, and aSERIALIZABLE READ ONLY DEFERRABLEtransaction waits for a "safe" snapshot and then runs with no risk of aborting, which suits long reports. - Index the columns used in your check queries. A sequential scan takes a relation-level SIREAD lock, so any write to the table becomes a conflict.
- Keep serializable transactions short and retry them automatically. Each retry should re-run the reads, not reuse old results.
A surprising read-only anomaly. Under plain snapshot isolation, even a transaction that only reads can observe a state that no serial order would produce. Fekete, O'Neil and O'Neil described this in 2004 with a bank example: a read-only report sees a deposit and a withdrawal in a combination that implies a fee should or should not have been charged, contradicting what was actually committed. It is rare, but it shows that "it only reads" is not automatically safe without true serializability.
Write skew fixed by SSI, step by step:
Defaults in Postgres and MySQL#
| Database | Default level | Implementation |
|---|---|---|
| PostgreSQL | Read Committed | MVCC; Repeatable Read = snapshot isolation; Serializable = SSI |
| MySQL InnoDB | Repeatable Read | MVCC with undo logs; locking reads use next-key locks to block phantoms |
| Oracle | Read Committed | MVCC; "Serializable" = snapshot isolation |
| SQL Server | Read Committed | Locking by default; optional snapshot-based modes (RCSI, Snapshot) |
Setting a level per transaction:
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; -- PostgreSQL syntax
SELECT count(*) FROM doctors WHERE shift_id = 7 AND on_call;
UPDATE doctors SET on_call = false WHERE id = 1 AND shift_id = 7;
COMMIT; -- may fail with SQLSTATE 40001: retry the whole transactionDefaults in depth: what they mean for your code#
Why the defaults differ. PostgreSQL chose Read Committed: few surprises, almost no serialization errors, and good behaviour for short web transactions. MySQL's InnoDB chose Repeatable Read, partly for historical replication reasons. Older statement-based binlog replication needed repeatable behaviour so that replicas replaying statements reached the same result. Gap locking at Repeatable Read prevented inserts that would make a replica diverge. With row-based binlogs, now the default, that reason has faded, and many MySQL deployments switch to Read Committed to reduce gap-lock waits and deadlocks.
Setting the level. It can be set per server, per session or per transaction. Per transaction is clearest, because the level then lives next to the code that depends on it.
-- PostgreSQL
BEGIN ISOLATION LEVEL REPEATABLE READ;
SET default_transaction_isolation = 'serializable'; -- for the session
-- MySQL (applies to the NEXT transaction in this session)
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
START TRANSACTION;
SET SESSION transaction_isolation = 'READ-COMMITTED';Portability traps. The same application can behave differently after a database migration:
- MySQL to PostgreSQL: code that relied on repeatable reads within a transaction now sees changing data at Read Committed. A read-then-write may need
FOR UPDATE. - PostgreSQL to MySQL: code that relied on Repeatable Read's serialization errors to prevent lost updates will no longer get them. Updates silently apply to the latest version instead.
- Oracle "Serializable": this is snapshot isolation, so write skew is still possible.
- SQL Server: the default Read Committed uses locks, so readers block behind writers. With
READ_COMMITTED_SNAPSHOTturned on (the default in Azure SQL Database), it behaves more like PostgreSQL's MVCC.
ORMs and frameworks. Most ORMs inherit the database default and do not mention isolation at all. Spring's @Transactional(isolation = ...), Django's select_for_update() and Rails' lock! are the usual escape hatches. A common bug pattern is an ORM model loaded, modified in memory and saved, which is a read-modify-write lost update waiting to happen. ORMs that support optimistic locking with a version column (JPA @Version, Rails lock_version) turn it into a detected conflict instead.
Distributed SQL defaults. CockroachDB defaults to Serializable (it later added Read Committed as an option), and Google Spanner provides strict serializability for read-write transactions. They chose strong defaults because anomalies across regions are harder to reason about, and they pay for it with retries under contention.
Choosing an isolation level#
- Default to Read Committed (Postgres) or Repeatable Read (MySQL) for most work, and know what they allow.
- Fix lost updates with atomic updates (
SET x = x + 1),SELECT ... FOR UPDATEor version columns, rather than raising the level for the whole system. - Protect invariants with constraints when possible: a
UNIQUEindex stops double usernames at any level; PostgreSQL exclusion constraints stop overlapping bookings. - Use Serializable for transactions that check-then-write across rows (write skew risk): bookings, limits, on-call rules. Build automatic retries for serialization failures.
- Use Repeatable Read / snapshot for consistent reports that read many tables and must see one point in time.
Choosing an isolation level in depth#
A practical decision path for one transaction:
Worked case: a quick-commerce inventory service. Imagine a grocery delivery app that serves items from nearby distribution centres. Two very different workloads hit the same inventory data:
- Availability checks ("which items can be delivered to me in 30 minutes?") are frequent, perhaps tens of thousands per second, and can tolerate data a second or two stale. Show an item as available, and if it sells out at checkout, the order step tells the user.
- Orders must never sell the same last unit twice.
A strong design splits them. Orders run on the primary in a short transaction that decrements stock with an atomic conditional update (... SET qty = qty - 2 WHERE item = $1 AND dc = $2 AND qty >= 2) and inserts the order rows. Read Committed is enough, because the conditional update closes the race. Availability queries go to read replicas, accepting replication lag of milliseconds to seconds. Because users only ever query centres near them, the inventory table can be partitioned by region, for example a region ID derived from the leading digits of the postal code, so each query touches one or two partitions instead of the whole dataset. The isolation choice and the consistency choice are made per workload, not per database.
Isolation versus distributed consistency. Isolation levels describe how concurrent transactions interact on one logical database. Once replicas and caches enter the picture, you also choose a consistency model for reads:
| Model | Promise | Typical use |
|---|---|---|
| Strong (linearizable) | Every read reflects the latest committed write | Balances, inventory at checkout, locks |
| Causal | Effects never appear before their causes, for example a reply before its post | Comments, chat, collaborative apps |
| Read your writes | A user always sees their own updates, others may lag | Profile edits, settings, posting content |
| Eventual | Replicas converge over time with no ordering promise | DNS, like counts, view counters, recommendations |
A system can run Serializable transactions on its primary and still show a user stale data if their next read hits a lagging replica. Read-your-writes is typically implemented by routing a user's reads to the primary for a short window after they write, or by waiting until a replica has replayed past the LSN of the user's last commit. See Consistency Models.
Rules of thumb that survive interviews and production:
- Make the common path safe by construction: atomic updates and constraints, which work at every level.
- Reserve Serializable for the few transactions whose invariant spans rows, and give them a retry loop.
- Use snapshot reads for anything that sums or compares across rows for reporting.
- Never let a transaction wait on a human, a network call to another service, or a long computation.
- Document the isolation assumption next to the code. The next engineer, or the next database migration, will need it.
Transactions outside the classic single-node database#
ACID transactions used to be the main thing that separated relational databases from NoSQL stores. That line has blurred, but the guarantees and their limits differ a lot, and interviewers like to probe them.
Amazon DynamoDB offers TransactWriteItems and TransactGetItems, which group up to 100 items, across tables in the same account and region, into one all-or-nothing operation. Each transactional write costs about twice the capacity of a normal write, because the service runs a prepare and a commit step. Transactions conflict with concurrent writes to the same items and fail rather than wait, so clients must retry. Conditional expressions on single items (attribute_not_exists(pk), or version = :v) are the cheaper and more common tool for preventing lost updates.
MongoDB has supported multi-document ACID transactions on replica sets since version 4.0 and on sharded clusters since 4.2. They use snapshot isolation. With write concern majority, a committed transaction survives the loss of a minority of replicas. The documentation itself recommends modelling data so that most updates touch one document, which is always atomic, and keeping multi-document transactions short, because a transaction that runs too long is aborted (60 seconds by default).
Apache Cassandra has no general multi-row transactions. Its lightweight transactions (INSERT ... IF NOT EXISTS, UPDATE ... IF col = value) run a Paxos round among replicas to make a compare-and-set on one partition linearizable. They cost several round trips, so they suit rare, important operations such as claiming a username, not hot paths. Batches that target a single partition are applied atomically, which is why designs that need "two rows change together" in Cassandra often put both rows in one partition.
Google Spanner provides strictly serializable read-write transactions across shards and regions. It uses two-phase locking and two-phase commit over Paxos-replicated groups, and assigns commit timestamps from TrueTime, a clock API that returns an interval with bounded uncertainty, typically a few milliseconds. A transaction waits out that uncertainty before its commit becomes visible ("commit wait"), which guarantees that timestamps respect real-time order. CockroachDB follows a similar path without special clock hardware, using hybrid logical clocks and serializable isolation by default, and resolving clock uncertainty with occasional read restarts.
The common lesson: wherever multi-item transactions exist outside a single node, they cost extra round trips, capacity or latency, and they abort more readily under contention. Designs therefore still try to keep the data that must change together on one partition, so that most writes need no distributed coordination at all.
Large and long-running changes#
Some work is too large for one transaction: backfilling a new column on 500 million rows, deleting a year of old events, or recalculating every account's tier. One giant transaction would hold locks for hours, pin an old snapshot (bloat in PostgreSQL, a long history list in InnoDB), generate a huge burst of WAL that replicas must replay, and, if it fails at 95%, roll back everything.
The standard approach is to chunk the work into many small transactions: process 1,000 to 10,000 rows per batch, keyed by primary-key ranges (WHERE id > $last AND id <= $last + 5000), commit, record progress, and pause briefly when replication lag or database load rises. Each batch must be idempotent, so a rerun after a crash simply repeats the last chunk safely. The overall change is then not atomic, so the application must tolerate a period where some rows are migrated and some are not. That is usually acceptable, and far safer than a multi-hour lock.
Savepoints help within a single transaction: SAVEPOINT s1, attempt a step, and ROLLBACK TO SAVEPOINT s1 if it fails, keeping the earlier work. They are useful for "try to insert, and on a unique violation do something else" inside a larger transaction, since in PostgreSQL any error otherwise aborts the entire transaction. Each savepoint has some overhead, and very many of them in one transaction can slow PostgreSQL down, so avoid creating one per row in a long loop.
When to Use It#
- Any operation that changes several rows or tables that must stay consistent: transfers, orders with line items, bookings.
- Check-then-act logic ("if seats remain, book one") under concurrency.
- Reports that must reflect a single point in time.
When NOT to Use It#
- Do not hold transactions open while calling external services or waiting for users; locks and old versions pile up.
- Do not use Serializable everywhere without retries; abort rates rise under contention.
- Do not wrap a single-row atomic update in elaborate locking; one statement is already atomic.
How to Implement It#
- Keep transactions short: read, decide, write, commit, in milliseconds.
- Use atomic SQL for counters and balances; add
CHECK (stock >= 0)as a guard. - Lock deliberately with
FOR UPDATEon the rows you will change, in a consistent order to avoid deadlocks. - Set Serializable per transaction where invariants span rows, and retry on error 40001 with backoff.
- Monitor long-running transactions, lock waits, deadlocks and (in Postgres) table bloat.
| Technology | Fits when |
|---|---|
| PostgreSQL | SSI Serializable, exclusion constraints, strong defaults |
| MySQL InnoDB | Repeatable Read with locking reads; very common in web stacks |
| CockroachDB, Google Spanner | Serializable distributed transactions across nodes and regions |
| DynamoDB transactions | Multi-item ACID within one table or region, limited item counts |
Testing for concurrency bugs#
Race conditions rarely show up in unit tests, because tests run one request at a time. Three habits catch them before production does.
- Reproduce by hand with two sessions. Open two
psqlormysqlterminals, runBEGINin both, and step through the statements in the interleaving you fear. This takes minutes and shows exactly what your level allows. - Run a contention test. Fire hundreds of concurrent requests at the same row or invariant, for example 500 parallel purchases of an item with stock 100. Then assert the invariant: exactly 100 sold, stock 0, no negative values. Tools such as
pgbenchwith a custom script, k6, or a small multithreaded test harness work well. - Check invariants continuously. Schedule queries that verify the rules the code assumes: ledger entries sum to zero per transaction, no seat has two bookings, no balance is negative. Alert when one fails. A violated invariant found in an hour is a bug report. Found in a quarter, it is a data-repair project.
When a test fails only under load, look first for read-modify-write in application code, missing unique constraints, and transactions that read at one level but whose authors assumed another.
Trade-offs#
| Level | Gain | Cost | Pick when |
|---|---|---|---|
| Read Committed | Fast, few aborts | Non-repeatable reads, lost updates, write skew | General OLTP with careful SQL |
| Repeatable Read / Snapshot | Consistent view per transaction | Write skew; long snapshots bloat storage | Reports, multi-read logic |
| Serializable | No anomalies | Aborts and retries (SSI) or blocking (locks); lower throughput | Bookings, money, invariants across rows |
| Atomic SQL updates and constraints | Safe at every level, no retries | Only covers rules expressible in one statement or schema | Counters, stock, uniqueness |
| Explicit locks (FOR UPDATE) | Predictable, no aborts | Waiting, deadlocks, lower concurrency on hot rows | Frequent conflicts on known rows |
Common Pitfalls#
- Assuming "Repeatable Read" means the same thing in every database.
- Read-modify-write in application code (
read balance; balance -= 10; write) without locks or atomic updates. - No retry logic for serialization failures and deadlocks.
- Long transactions blocking VACUUM and causing bloat in Postgres.
- Calling external services, such as payments or email, inside a database transaction.
- Retrying only the failed statement instead of the whole transaction after a 40001 error.
- Leaving sessions
idle in transaction, which pins old snapshots and blocks cleanup. - Turning off
fsyncfor speed, which risks corruption rather than just losing recent commits.
Real-World Examples#
PostgreSQL added Serializable Snapshot Isolation in version 9.1, making its Serializable level truly serializable without read locks.
Google Spanner provides externally consistent (strictly serializable) transactions across data centres, using synchronised clocks with bounded uncertainty (TrueTime).
Jepsen analyses by Kyle Kingsbury have repeatedly found databases whose real isolation under network faults was weaker than documented, which is why teams with strict needs test their own invariants. Payment platforms commonly keep money in append-only, double-entry ledger tables inside ACID databases, so every balance can be recomputed and audited from its entries.
In the Interview#
Answering transaction questions in an interview#
Interviewers use contention problems (ticket booking, auctions, inventory, wallets) to see whether you know where races hide. A strong answer has three layers.
- Name the race precisely. "Two users can both see seat 14C as free and both book it. That's a check-then-act race, and at Read Committed both transactions would succeed."
- Fix it at the narrowest point. "A unique constraint on (event_id, seat_id) in the bookings table makes the second insert fail, whatever the isolation level. The service turns that error into 'seat just taken'." Or: "Decrement stock with a conditional atomic update and check the row count."
- Say what it costs and when you would change it. "Every booking for a hot event now contends on the same few rows. For a big on-sale, I'd put a reservation step with a short hold in front of it, and possibly a virtual waiting room, rather than raise the isolation level."
Follow-ups worth preparing:
- "What does the database guarantee if the server crashes right after COMMIT returns?" The commit record was fsynced to the WAL first, so recovery redoes it. If replication is asynchronous and the primary's disk is lost, the last few transactions may be gone unless you commit synchronously to a replica.
- "Your transaction calls the payment provider. Where does that call go?" Outside the database transaction. Record the intent (a pending payment row) in one transaction, call the provider with an idempotency key, then record the result in a second transaction. Reconcile pending rows that never completed. See Idempotency.
- "How would you do this across two services' databases?" A single ACID transaction cannot span them cheaply. Use a saga with compensating actions, or the transactional outbox to publish events atomically with the local write. See Distributed Transactions.
- "Optimistic or pessimistic locking?" Optimistic, using version checks or SSI, when conflicts are rare. Pessimistic (
FOR UPDATE) when conflicts are frequent and retries would waste work.
Mistakes that cost points: assuming ACID removes all races, raising the whole database to Serializable instead of fixing one transaction, forgetting retry logic, holding a transaction open during a network call, and quoting "Repeatable Read" semantics as if every database implemented them the same way.
Deep Dive: Isolation beyond one nodeShow
Replication changes the picture. Reading from an asynchronous replica can show data older than what your own transaction just committed. Isolation levels describe one node; for replicas you also need read-your-writes or session guarantees. See Replication.
Serializable vs linearizable. Serializability is about transactions over many objects behaving as some serial order. Linearizability is about single operations appearing to happen at one instant in real time. Strict serializability combines both. Spanner and FoundationDB offer it; most single-node databases at Serializable are strictly serializable in practice.
Commit latency and durability settings. synchronous_commit = off in Postgres, or innodb_flush_log_at_trx_commit = 2 in MySQL, skip waiting for fsync at commit. Throughput rises, but a crash can lose the last fraction of a second of commits. This is a reasonable choice for some data (analytics events), not for payments.
Retry design. Serializable and deadlock aborts are normal events. Wrap transactions in a function that retries the whole transaction (not just the failing statement) with backoff, and keep side effects (emails, external calls) out of the transaction or make them idempotent.
Deep Dive: The formal theory behind isolation levelsShow
Serializability graphs. Represent each committed transaction as a node, and draw an edge from T1 to T2 whenever T1's operation must come before a conflicting operation of T2. Three edge types exist:
- wr (T2 reads what T1 wrote), a read dependency;
- ww (T2 overwrites what T1 wrote), a write dependency;
- rw (T2 overwrites what T1 read), an antidependency.
A history is conflict-serializable exactly when this graph has no cycle. Any topological order of the graph is then an equivalent serial order.
Defining levels by forbidden cycles. Atul Adya's 1999 MIT PhD thesis, "Weak Consistency: A Generalized Theory and Optimistic Implementations for Distributed Transactions", recast the isolation levels as rules about which cycles are forbidden, rather than as lists of forbidden operation patterns tied to locking. Roughly:
| Level | Forbidden |
|---|---|
| PL-1 (like Read Uncommitted) | Cycles made only of ww edges, which are dirty writes |
| PL-2 (like Read Committed) | Also reads of aborted or intermediate data, and cycles of ww and wr edges |
| PL-2.99 (like Repeatable Read) | Also cycles with item-level rw edges, but predicate rw edges are still allowed, so phantoms remain |
| PL-3 (Serializable) | Any cycle at all |
Because these definitions say nothing about locks, they apply equally to MVCC and optimistic systems. Modern testing tools build on this: they record histories from real databases and search for forbidden cycles. Projects such as Jepsen (Kyle Kingsbury) have used this approach to find isolation bugs in many production databases, including cases where a system advertised a level it did not provide under faults.
Snapshot isolation in this picture. Snapshot isolation forbids ww cycles and the wr anomalies, but allows cycles that contain two adjacent rw edges. That is exactly the write skew shape, and exactly what SSI detects. It also explains why the anomaly table at the top of this page is a simplification: levels form a partial order, not a ladder. Snapshot isolation and ANSI Repeatable Read (implemented with locks) are incomparable. Snapshot isolation prevents phantoms on reads but allows write skew, while lock-based Repeatable Read allows phantoms but prevents write skew on the rows it read.
Why this matters to practitioners. When a vendor says "Repeatable Read", ask two questions. Which cycles can still occur? And does the engine detect conflicts by blocking or by aborting? The answers predict both your anomalies and your error handling.
Key Takeaways#
- ACID: all-or-nothing, rules preserved, isolated from concurrent work, durable after commit via the write-ahead log.
- Anomalies to know: dirty read, non-repeatable read, phantom, lost update, write skew.
- MVCC lets readers and writers proceed without blocking; snapshot isolation is popular but allows write skew.
- PostgreSQL defaults to Read Committed; MySQL InnoDB to Repeatable Read; names mean different things across vendors.
- Prevent anomalies with atomic updates, locks, constraints, or Serializable plus retries where invariants span rows.
- Durability has levels: process crash, machine crash, disk loss and site loss each need a stronger, slower commit.
- WAL with steal and no-force, LSNs on pages and full-page images makes recovery fast, idempotent and safe from torn pages.
- PostgreSQL keeps row versions in the heap and needs vacuum and freezing. InnoDB keeps them in undo and needs purge.
- SSI makes snapshot isolation serializable by aborting pivot transactions with two adjacent read-write dependencies.