Systemsfor Aravinda
0 / 78 core
Week 3 · Storage

Transactions and isolation

3 hours · core path

Read first: Choosing a database

In one sitting

A transaction is the unit that makes an invariant survive concurrency and a crash. Snapshot isolation stops dirty reads, non-repeatable reads, and phantoms, and it still allows write skew, which is how two bookings land on one seat. Serializable isolation, or a write to one conflicting row, is what closes that hole.

Two buyers can each run a transaction that looks correct and still sell the same seat twice. The disk did not drop a commit. Each buyer read a snapshot in which the seat was free, and each wrote a different row. The isolation level was too weak for the invariant you actually care about.

Which promises you can ask for is part of Choosing a database. This page is the contract itself: four words that are not synonyms, a ladder of anomalies, and the last seat as a schedule you can draw.

Core concepts

The four words, precisely

ACID is four promises. The marketing version collapses them into “safe.” The precise version tells you which bug you still have.

Atomicity is all-or-nothing for one transaction. You decrement the seats-left counter and insert the booking, or you do neither. A crash, a constraint failure, or an explicit abort leaves the earlier state, not a decremented counter with no booking and not a booking with the counter untouched. Atomicity says nothing about a second transaction running beside this one.

Consistency, inside ACID, means invariants. Seats sold never pass capacity. A balance does not go negative if that is your rule. The database does not know the rule. You encode it as a constraint, or you check it inside a transaction whose isolation makes the check still true at commit. This is not the C in CAP, PACELC, and what they actually say. That C is about whether replicas agree. You can commit a perfectly isolated transaction on a primary whose replica is still behind.

Isolation is the anomaly menu. It answers which interleavings of other transactions this one can observe. Weak isolation is a choice to allow a named anomaly because forbidding it costs aborts or waiting. You have to name the anomaly, or “read committed” is a sticker.

Durability means a committed write survives a crash of the database that acknowledged it. It does not mean every replica has the write. Under asynchronous Replication, the primary can acknowledge, then die, and failover can promote a replica that never saw the tail. The sale you just confirmed can disappear. Synchronous replication makes the commit wait until a replica has the write, and a slow replica stalls writers. Durability always has a boundary. Say which machines are inside it.

Atomicity and durability meet in the log. The database records the transaction’s effects, then records a commit. A crash before that commit record leaves the transaction uncommitted, so recovery drops the effects. A crash after the commit record is replayed, so the effects return. “Committed” is that record, not a feeling that the rows look finished.

The isolation ladder

For interviews, weakest to strongest: read uncommitted, read committed, repeatable read, snapshot isolation, serializable. Each stronger rung keeps what the weaker rungs already prevented and drops one more anomaly. Products reuse the names for different mechanisms. Ask which anomalies remain. The label on the dial is not the definition.

A dirty read sees another transaction’s write before that transaction commits. One transaction adds 40 to a balance and has not committed. Another reads the new balance and acts on it. The first then aborts. The second used a value that never existed. Read uncommitted allows this. Read committed stops it: you only see data some transaction has committed.

A non-repeatable read is two reads of the same row, inside one transaction, that disagree because another transaction committed an update in between. A checkout reads a price, computes tax, reads the price again, and the second read is a different number. Read committed allows this. Repeatable read stops it: a row you already read stays put for the rest of your transaction.

A phantom is a range that grows or shrinks. You count bookings for a show and get 399. Another transaction inserts a booking and commits. You count again and get 400. No row you already held had to change. A new row entered the range. On this ladder, repeatable read keeps the rows you already read stable and still allows the phantom. Snapshot isolation stops the phantom by giving you one snapshot for the whole transaction. Your second count matches your first.

Write skew is the anomaly snapshot isolation still allows. Two transactions each read a snapshot that satisfies an invariant, each writes a different item, and the two writes together break the invariant. Neither write conflicted with the other, so both commits succeed.

Level Prevents Still allows
Read uncommitted None of the four Dirty read, non-repeatable read, phantom, write skew
Read committed Dirty read Non-repeatable read, phantom, write skew
Repeatable read Dirty read and non-repeatable read Phantom, write skew
Snapshot isolation Those three Write skew
Serializable All four None of these four

Serializable means the outcome matches some order where the transactions ran one at a time. In any serial order the second booking would have seen the first. If your history has no such order, serializable isolation has to reject one of them. You pay in aborts and in coordination.

Write skew and the double-booking

Snapshot isolation gives each transaction a snapshot of committed state as of its start, and it rejects a second writer of the same item. People trust it with the last seat because of that second clause. The clause is true only when both buyers write the same item.

Capacity is 1. Bookings are rows. There is no counter. Both transactions start, and both snapshots contain zero bookings. Each counts, sees zero, and decides the seat is free. The first inserts a booking row and commits. The second inserts a different booking row and commits. Snapshot isolation has nothing to reject. The inserts did not write the same row, and each snapshot really did show a free seat. After both commits the count is 2. Each transaction, alone against its snapshot, looked consistent. Together they broke “bookings never pass capacity.”

That is write skew. The on-call pair is the same shape with different nouns. The invariant is that at least one engineer stays on call. Each reads a snapshot where the other is still on call, then each updates only their own row to off call. Different rows, both commits, nobody on call.

A phantom and a write skew are easy to swap on a whiteboard, and they are different bugs. A phantom is one transaction watching its own range change because someone else committed. One snapshot stops that. Write skew is two transactions, two snapshots, two disjoint writes, and an invariant that lived in the gap. Hiding phantoms inside one transaction does not close the gap.

Two guests who each see a room free and each insert a reservation are the same schedule. Design hotel reservation is that invariant on a calendar. The fix is to force a conflict the isolation level actually detects, or to use an isolation level that detects this one.

One row, or a real key

Make both buyers write one row, the seats-left counter for that show. Both snapshots read 1. Both try to set it to 0. That is a write-write conflict on one item. Snapshot isolation commits one writer and aborts the other. The aborted buyer retries. The new snapshot reads 0, and you say the show is sold out. You did not double-sell. You do have to handle the abort. A client that treats the abort as “maybe it worked” and inserts a fresh booking is a second bug. The retry needs an idempotency key so doing the purchase twice has the same effect as doing it once. Idempotency and the exactly-once myth is that contract: a natural idempotent write sets state, and an imposed one stores the client key with the result.

If seats are real keys, a unique constraint on show plus seat does the same job without serializable isolation. Both buyers insert seat 14. One commit wins. The other fails the constraint. The engine can see the conflict because both writes name the same key. A general-admission count has no seat id. The counter row is how you manufacture a conflict. The unique seat is how you manufacture one when the product already has seats. A constraint the database can see beats an invariant that exists only as a count in application code.

A single conditional update, decrement the counter where it is still positive, is one write to that same row. Under snapshot isolation the second writer aborts, so both decrements do not land. The statement does not protect a count in one statement and an insert in another unless those statements share a transaction that keeps the conflict. The schedule that double-books is exactly that split: a read of a predicate, then an insert of a new key.

When the booking and a “ticket sold” message both have to exist, write the booking and an outbox row in the same transaction. A publisher reads the outbox and puts the message on the bus. One database, so atomicity covers both rows. The consumer is still idempotent, because the publisher can send the message more than once. The outbox pattern and sagas is the next step once the charge lives in another service. There is no global rollback. A saga is a sequence of local transactions with a compensating action for each. If the booking commits and the charge fails, the compensation releases the seat. If the compensation fails too, the seat stays held and nobody was charged, and a person has to notice. A single-database transaction is the right answer when you still have one database. A transaction that must commit on two partitions is a different machine. It can block. That failure is the advanced note. Do not reach for it because a diagram has two boxes.

MVCC

Multiversion concurrency control, MVCC, keeps old versions of a row so readers do not block writers. A transaction reads the versions that were committed and visible at its snapshot, and a writer installs a new version beside them instead of overwriting the bytes a reader still needs. Writers still conflict with writers: if another transaction has committed a newer version of a row you are also writing, snapshot isolation aborts you, which is the check that saves the single-row last seat and the check that never runs when two inserts create two new keys. Old versions stay until no snapshot can still read them, so a transaction left open across a payment call or a confirmation page pins those versions for the whole wait, and any locks it holds make everyone else wait on a network call or a person. Keep the transaction around the database statements, and talk to the payment service outside it.

A worked example

You are selling the last seat of one show. Say the assumptions.

  • Quiet traffic on the event pages is 1,000,000 requests a day. A planning assumption for the exercise, not a measured product.
  • The on-sale is 20,000 purchase attempts in one minute. Also an assumption. It is a spike, not the 2x to 5x peak you would put on a smooth day.
  • Each check-then-write spends 20 ms inside the database transaction. An assumption for a few statements, not a measured query plan.
  • One seat is left. Buyers overlap inside that 20 ms window.
  • One primary. Isolation is snapshot isolation. How you replicate the commit is a separate choice, and replication is not what creates this bug.

A day has 86,400 seconds. The interview shortcut is about 100,000 seconds.

quiet day
  1,000,000 / 86,400 = 11.6 requests/s
  shortcut: 1,000,000 / 100,000 = 10 requests/s

on-sale minute, assumption
  20,000 / 60 = 333 attempts/s
  333 / 11.6 = about 29 times the quiet per-second rate

overlapping attempts, Little's law
  concurrency = arrival rate * time in the transaction
  333 * 0.020 = 6.7

About seven purchase attempts are in flight together during the spike. That is arrival rate times time, not bad luck. While the show is down to the last few seats, several of those seven will read “free.”

The schema that double-books. Bookings are insert-only rows. There is no counter. Buyers A and B both snapshot a count of zero. A inserts booking 501 and commits. B inserts booking 502 and commits. Different primary keys, so snapshot isolation finds no write-write conflict. Both calls return success. You have two bookings and one seat. The symptom shows up at the door: two confirmations, one chair.

The schema that does not. One row holds seats left, and the value is 1. A and B both read 1 and both try to write 0. Same row. Snapshot isolation commits one and aborts the other. The client treats the abort as “try again or tell the user no,” not as a timeout to ignore. On retry the snapshot reads 0. One confirmation goes out.

The schema that also does not, when seats have ids. Seat 14 is a key. A unique constraint on the show and the seat rejects the second insert. The second transaction fails the constraint even if you did not buy serializable isolation, because the conflict is a write the engine can see. This does nothing for a bare capacity count. There is no second key. You are back to the counter row, or to serializable isolation.

flowchart TD
  buyerA[Buyer A]
  buyerB[Buyer B]
  count[Each counts zero bookings]
  insertA[Inserts booking A]
  insertB[Inserts booking B]
  result[Both commit and capacity is broken]
  buyerA --> count
  buyerB --> count
  count --> insertA
  count --> insertB
  insertA --> result
  insertB --> result

The diagram is the failing schema. If both arrows wrote one seats-left row, the second commit would stop at the conflict instead of reaching the bottom.

The on-call pair is the same picture. Each person reads that the other is still on call and writes only their own row. Draw it when someone says snapshot isolation is serializable. The ladder says it stops dirty reads, non-repeatable reads, and phantoms, and it still allows this.

Design ticket sales is where the last seat meets a cache and a queue of buyers. The transaction on this page is the decision you want already made before those boxes. A cached copy of seats left does not make the invariant true. The commit does.

Tradeoffs

Choice What you gain What you spend
One counter row every buyer updates Snapshot isolation aborts the second writer, so the last seat is sold once That row is hot, and every sale of that show waits on it
Unique key per seat The engine rejects a double insert without serializable isolation No help for a capacity count that has no seat id
Serializable isolation Write skew is rejected, including count-then-insert More aborts and more coordination on the rows you touch
One database for the whole invariant A real atomic commit and a real rollback Load and schema change sit on that database
A saga across two services Each service keeps a short local transaction Compensating actions, and a compensation can fail
Asynchronous replication after commit The primary acknowledges without waiting for the replica Failover can lose the tail, so the sale you confirmed is gone

The hot counter is the honest cost of the fix that works under snapshot isolation. More partitions do not cool that row. Partitioning and sharding spreads different shows onto different partitions. It cannot split the last seat of one show across ten databases and keep a single decrement. If one show is so hot that conflicts on one row dominate, give the seats real keys and let the unique constraint reject the loser. Do not shard a single integer and hope the counts add up.

Serializable isolation is the name to say when the invariant is a predicate over many rows and you cannot invent a conflicting write. More transactions abort and retry. At 333 attempts per second, unbounded retries become the load. A retry needs a limit and an idempotency key.

Pitfalls

  • Calling snapshot isolation serializable. The symptom is a double-booking you cannot reproduce single-threaded, because it needs two snapshots.
  • Check-then-insert against a count, with the insert as a new primary key. The symptom is two rows that each looked legal in the snapshot that created them.
  • Treating an abort as success, or retrying by inserting a new booking id. The symptom is one buyer holding two seats, which is your bug.
  • Holding the transaction open across a payment call or a user pause. The symptom is old versions you cannot discard, a stuck pool of connections, and waits as long as the remote call.
  • Picking read uncommitted so a report “does not need to be exact.” The symptom is a total that includes a transaction which then aborted, so the number describes a state you never committed.
  • Confirming the sale by reading a replica. The symptom is a buyer who committed on the primary, reads a lagging copy that does not show the booking, and purchases again. A read-your-writes check needs the primary, a session token, or a version check. The invariant was enforced where the commit landed, not on every replica at that instant.
  • Splitting one invariant across two services and drawing a happy arrow between them. The symptom is the booking committed and the charge did not, with no single abort that undoes both.

In the interview

In the first five minutes, name the invariant in a sentence a product manager would recognize: one seat, one booking. Name the isolation level, and say whether the two buyers write the same row or two new rows. Give the number: at a few hundred attempts per second, several transactions overlap inside a 20 ms transaction, so the race is the steady state of the spike, not a freak schedule. The bottleneck is the row everyone must conflict on, or the lack of such a row. The honest tradeoff is aborts and a hot row, against a double-booking.

Skip a proof of serializability. Skip a commit that spans the seat and the payment unless they ask why that protocol blocks. The aside is that failure. Early-career interviewers want the path, the overlap arithmetic, the bottleneck row, and one tradeoff you will defend. The question that usually follows is “two people click the last seat at the same time, what do they each see?” Walk the snapshot. If both insert, both succeed, and you say so before they do. If both update one row, one aborts, and you say what the client does with the abort.

Check yourself

Two transactions under snapshot isolation each count zero bookings, then each inserts its own booking row. What does each transaction observe, and what is true after both commit?

Each snapshot really does contain zero bookings, so each check passes. The inserts are different rows, so there is no write-write conflict and snapshot isolation commits both. That is write skew. Afterward the count is 2. If the capacity was 1, the invariant is already false, and no later read inside either transaction was going to notice, because each transaction had finished against its own snapshot.

The same two buyers both decrement one seats-left row from 1 to 0 under snapshot isolation. What changes?

They now write the same item. Snapshot isolation commits one writer and aborts the other. The aborted transaction retries against a snapshot that already shows 0, and that buyer is told the seat is gone. You still have to handle the abort. Ignoring it, or inserting a second booking with a fresh id, puts the double sale back in through the client.

A teammate says the system is consistent because every replica will catch up. Which ACID word did they reach for, and which idea did they mean?

They used the ACID word consistency and meant replica convergence. Inside ACID, consistency means invariants: the seat count still holds after a commit. Replicas catching up is a replication question. Eventual catch-up does not tell you whether two concurrent bookings were allowed to break capacity, and it does not tell you whether a failover lost the tail.

Why does a unique constraint on show and seat stop a double insert when a count-then-insert does not?

Both inserts name the same key, so the constraint gives the engine a conflict it can reject. One commit wins and the other fails. A count-then-insert writes a new key after reading a predicate. Snapshot isolation never sees a conflicting write, so both commits stand. The constraint moved the invariant out of application code and into a key.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Spanner, OSDI 2012, Corbett and others; Garcia-Molina and Salem, 1987.