Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Storage and transactions · Lesson 4 of 11

Transactions and isolation levels

What ACID really promises, the anomalies that appear when transactions overlap, how locking and MVCC implement each isolation level, and the patterns (atomic updates, locks, constraints, retries) that keep concurrent code correct.

ConceptCore31 min readUpdated

  • 1 sequence flow
  • 9 code samples
  • 8 interviewer follow-ups
  • 4 self-checks

Read first: Storage engines and indexes

By the end you will be able to
  • State what each ACID property guarantees, and which one is really the application's job.
  • Name the anomalies concurrent transactions can cause (non-repeatable read, phantom, read skew, lost update, write skew) and which isolation level allows which.
  • Explain how locking and MVCC implement isolation, and why snapshot isolation still allows write skew.
  • Pick the cheapest tool that closes a race (atomic update, lock, constraint, version column, serializable with retry), and handle deadlocks and serialization failures.

6 code samples (321 lines), collapsed so the explanation stays in focus.

A transaction groups several reads and writes into one unit that either happens completely or not at all, and that behaves as if it ran alone. The first half of that sentence is easy to build. The second half, "as if it ran alone", is the expensive part, and databases sell it in strengths called isolation levels. Most production bugs in this area come from not knowing which strength you are actually getting.

HLD

What a transaction promises

The four letters of ACID are worth reading carefully, because one of them is not what it looks like.

  • Atomicity: all of a transaction's writes happen or none do. If a statement fails or the connection drops before commit, nothing is left half done. "Abortability" would be a better name. It has nothing to do with concurrency.
  • Consistency: your rules about the data hold: balances never go negative, every order has a customer. The database enforces the rules you declare (constraints, foreign keys, unique indexes), but most rules live in application code. This is the odd letter: it is a property of your application, which the other three properties make possible.
  • Isolation: concurrent transactions do not see each other's half-finished work. How strictly is the isolation level.
  • Durability: once commit returns, the data survives a crash. On one machine that is the write-ahead log from the storage engines lesson; across machines it usually means enough replicas have the write.

Transactions are not only for money. Any change that must keep several rows in step (an order and its stock, a booking and its payment, a user and their unique name) needs one. Statements outside an explicit transaction usually run in autocommit mode, each as its own tiny transaction, which is why a check in one statement and an action in the next are not protected from each other.

HLD

Anomalies: what goes wrong when transactions overlap

Isolation is easiest to understand by the bugs it prevents. Each anomaly below is a concrete interleaving of two transactions.

AnomalyWhat happensExample
Dirty readYou read data another transaction has not committedRead a balance that is rolled back a moment later
Dirty writeYou overwrite another transaction's uncommitted dataTwo transactions each set half of an order's fields
Non-repeatable readReading the same row twice gives two answersA price changes between two reads in one checkout
PhantomRunning the same query twice returns different rowsA count of open tasks changes mid-report
Read skewTwo related rows are read at different momentsRead account A before a transfer and B after it: the total is wrong
Lost updateTwo read-modify-write cycles overlap and one write vanishesTwo requests both read 100, add 10 and 20, and the result is 110 or 120, not 130. Over HTTP the fix is an ETag (see API design)
Write skewTwo transactions read the same data, decide, and write different rowsTwo doctors both go off call because each saw the other still on
Double bookingWrite skew where the thing read is "no row exists"Two users both see the room free and both book it

Dirty writes and dirty reads are prevented by every serious engine at its default level, so the interesting anomalies are the rest. Write skew and double booking deserve most of your attention, because the usual defences do not catch them: neither transaction writes a row the other writes, so there is nothing to conflict on.

Fig. Write skew with two doctors
Fig. Write skew with two doctors

HLD

Isolation levels: what each one allows

The SQL standard defines four levels by which of three phenomena (dirty read, non-repeatable read, phantom) they allow: Read Uncommitted, Read Committed, Repeatable Read and Serializable. The definition is flawed. A 1995 paper (Berenson and colleagues, "A Critique of ANSI SQL Isolation Levels") showed that it is ambiguous, says nothing about lost update or write skew, and does not describe snapshot isolation, the level that PostgreSQL implements as "Repeatable Read" and Oracle as "Serializable". The result is that a level's name does not tell you what you get. You have to look up your database.

The samples later in this lesson build a small multi-version store with three levels, run each anomaly as a scripted interleaving, and report whether it happened:

AnomalyRead CommittedSnapshot isolationSerializable
Non-repeatable readpossiblepreventedprevented
Phantompossiblepreventedprevented
Read skewpossiblepreventedprevented
Lost updatepossibleaborts one writeraborts one writer
Write skewpossiblepossibleaborts one transaction
Double bookingpossiblepossibleaborts one transaction

What the three levels mean:

  • Read Committed shows each statement the data committed before that statement began. It never shows uncommitted data, but two statements in one transaction can see different worlds.
  • Snapshot isolation gives the transaction one consistent snapshot, taken when it starts, for all its reads. It prevents every anomaly above that is about reading, and it stops lost updates by making the second writer of a row fail. It does not stop write skew.
  • Serializable means the outcome is the same as if the transactions had run one at a time in some order. It is the only level that stops write skew, and the price is that transactions can be aborted and must be retried.

What the major databases do under these names (defaults as of writing; check your version):

DatabaseDefault levelWhat its stronger levels really are
PostgreSQLRead CommittedRepeatable Read is snapshot isolation. Serializable is serializable snapshot isolation (SSI), which can abort with a serialization failure
MySQL (InnoDB)Repeatable ReadPlain reads use a snapshot; writes and locking reads see the latest committed rows. Serializable turns plain reads into locking reads
OracleRead Committed"Serializable" is snapshot isolation, so write skew is possible
SQL ServerRead Committed, using locks (Azure SQL Database defaults to row versioning)Snapshot is opt-in; Serializable uses range locks
CockroachDB, SpannerSerializableSpanner adds external consistency, a real-time ordering guarantee

The practical lesson: "we use Repeatable Read" means different things on PostgreSQL and MySQL. On PostgreSQL a read-then-write that loses a race fails with a serialization error. On MySQL the same code can silently overwrite the other transaction's change, because the write is applied to the latest row, not the snapshot you read.

LLD

How databases implement isolation

Locking

The classic approach is two-phase locking: a transaction takes a shared lock to read a row and an exclusive lock to write it, and holds every lock until it commits (the "strict" form). Readers block writers and writers block readers, which keeps things simple and serializable and makes contention painful. Preventing phantoms needs locks on ranges of an index, not just on rows (InnoDB's next-key locks are an example). A transaction that waits for a lock held by one that waits for it forms a deadlock, which the database must detect and break.

Multi-version concurrency control

Most modern engines use MVCC. A write does not overwrite a row; it adds a new version stamped with the commit that created it. A transaction reads from a snapshot: for each row, the newest version committed at or before the snapshot. Readers never block writers and writers never block readers. Two writers of the same row still conflict.

commit time:   3            7            12           16
               |            |            |            |
balance:       500  ------> 400  ------> 450  ------> 460   (new versions)

a snapshot taken at time 5 reads 500, at 9 reads 400, at 15 reads 450
a writer adds a version and never edits one, so no reader waits for it
old versions are removed only when no snapshot can still ask for them
Fig. One key, four committed versions, and what each snapshot sees

Where the old versions live differs. PostgreSQL keeps them in the table as extra row versions and removes them with VACUUM. InnoDB updates the row in place and keeps the old versions in an undo log, which a purge thread trims. Either way, old versions cannot be removed while any snapshot might read them, which is why a forgotten transaction hurts (see long transactions).

Snapshot isolation and its hole

Under snapshot isolation a transaction that wants to commit a write checks whether another transaction committed a newer version of the same row since its snapshot. If so, the first committer wins and the later one aborts. That is what stops lost updates. But the check only compares the rows written. Alice and Bob each write their own row, so neither conflicts, even though each decision was based on rows the other changed. That gap is write skew.

Serializable

There are three ways to get a serializable outcome.

  • Run transactions one at a time. A single-threaded engine with short, in-memory transactions (often stored procedures) has no concurrency problems at all. VoltDB and Redis work this way, and it limits throughput to one core per partition.
  • Two-phase locking with range locks. Correct, and slow when transactions contend.
  • Optimistic detection. Run on snapshots and, at commit, abort any transaction that could not be ordered serially with the others. PostgreSQL's SSI tracks the read-write dependencies between concurrent transactions and aborts one when it finds a pivot: a transaction with both an incoming and an outgoing dependency among concurrent transactions. It can abort a transaction that would have been fine (a false positive), never one that breaks the rule.

The sample uses a simpler, more conservative cousin of SSI: at commit it re-checks everything the transaction read, and aborts if any of it changed. That is optimistic concurrency control with backward validation. It aborts more often than SSI would, but it never lets a write-skew outcome through.

A small database that reproduces every anomaly

Writes are buffered in the transaction until commit, so nothing is ever dirty. A Begin records the latest commit timestamp as the snapshot. Read Committed asks for the newest committed version at the moment of each read; the other levels ask for the newest version at or before their snapshot. Commit adds the first-committer-wins check for Snapshot and Serializable, and Serializable also validates its reads and scans. Real engines usually detect a write conflict when the update happens rather than at commit, and Read Committed works per statement, but the visible rules are the same.

C# · Isolation, SerializationFailure, Database, …123 lines
using System;
using System.Collections.Generic;
using System.Linq;

public enum Isolation { ReadCommitted, Snapshot, Serializable }

public sealed class SerializationFailure : Exception
{
    public SerializationFailure(string message) : base(message) { }
}

// A multi-version store. Every key keeps its versions, oldest first; a version is the value as of one commit.
public sealed class Database
{
    private readonly SortedDictionary<string, List<(long CommitTs, int Value)>> versions =
        new SortedDictionary<string, List<(long CommitTs, int Value)>>(StringComparer.Ordinal);
    private long clock;                                   // the timestamp of the latest commit

    public Transaction Begin(Isolation level) => new Transaction(this, level, clock);

    internal long Now => clock;

    // The newest version committed at or before `ts`. Pass long.MaxValue for the latest one.
    internal (long CommitTs, int Value)? Visible(string key, long ts)
    {
        if (!versions.TryGetValue(key, out var list)) return null;
        for (int i = list.Count - 1; i >= 0; i--) if (list[i].CommitTs <= ts) return list[i];
        return null;
    }

    internal SortedDictionary<string, int> Rows(string prefix, long ts)
    {
        var rows = new SortedDictionary<string, int>(StringComparer.Ordinal);
        foreach (var key in versions.Keys)
            if (key.StartsWith(prefix, StringComparison.Ordinal) && Visible(key, ts) is { } v) rows[key] = v.Value;
        return rows;
    }

    internal void Apply(Dictionary<string, int> writes)
    {
        long ts = ++clock;
        foreach (var write in writes)
        {
            if (!versions.TryGetValue(write.Key, out var list)) versions[write.Key] = list = new List<(long CommitTs, int Value)>();
            list.Add((ts, write.Value));
        }
    }

    public int? Latest(string key) => Visible(key, long.MaxValue)?.Value;

    public int VersionCount => versions.Values.Sum(list => list.Count);

    // Drop the versions no snapshot can see: per key, keep the newest version at or before the oldest snapshot still in use,
    // and everything newer than it. Returns how many versions were removed.
    public int Vacuum(long oldestSnapshot)
    {
        int removed = 0;
        foreach (var list in versions.Values)
        {
            int keepFrom = 0;
            for (int i = 0; i < list.Count; i++) if (list[i].CommitTs <= oldestSnapshot) keepFrom = i;
            list.RemoveRange(0, keepFrom);
            removed += keepFrom;
        }
        return removed;
    }
}

public sealed class Transaction
{
    private readonly Database db;
    private readonly Isolation level;
    private readonly long startTs;                                                   // the snapshot this transaction works from
    private readonly Dictionary<string, int> writes = new Dictionary<string, int>(); // buffered until commit: nobody sees them early
    private readonly Dictionary<string, long> pointReads = new Dictionary<string, long>();   // key -> commit timestamp of the version it saw
    private readonly List<(string Prefix, string Seen)> scans = new List<(string Prefix, string Seen)>();

    internal Transaction(Database db, Isolation level, long startTs) { this.db = db; this.level = level; this.startTs = startTs; }

    public long StartTs => startTs;

    // Read Committed looks at the newest committed data on every read. The other two levels keep the snapshot taken at Begin.
    private long ReadTs => level == Isolation.ReadCommitted ? db.Now : startTs;

    public int? Read(string key)
    {
        if (writes.TryGetValue(key, out int own)) return own;
        var version = db.Visible(key, ReadTs);
        pointReads[key] = version?.CommitTs ?? 0;
        return version?.Value;
    }

    public List<(string Key, int Value)> Scan(string prefix)
    {
        var rows = db.Rows(prefix, ReadTs);
        scans.Add((prefix, Describe(rows)));
        foreach (var write in writes) if (write.Key.StartsWith(prefix, StringComparison.Ordinal)) rows[write.Key] = write.Value;
        return rows.Select(r => (r.Key, r.Value)).ToList();
    }

    public void Write(string key, int value) => writes[key] = value;

    private static string Describe(SortedDictionary<string, int> rows) => string.Join(",", rows.Select(r => r.Key + "=" + r.Value));

    public void Commit()
    {
        if (writes.Count > 0 && level != Isolation.ReadCommitted)
            foreach (var key in writes.Keys)                     // first committer wins
                if ((db.Visible(key, long.MaxValue)?.CommitTs ?? 0) > startTs)
                    throw new SerializationFailure(key + " was changed by a transaction that committed after this one began");

        if (writes.Count > 0 && level == Isolation.Serializable)
        {
            foreach (var read in pointReads)                    // is everything this transaction read still the latest version?
                if ((db.Visible(read.Key, long.MaxValue)?.CommitTs ?? 0) != read.Value)
                    throw new SerializationFailure(read.Key + ", which this transaction read, has changed");
            foreach (var scan in scans)                         // and would the same scan return the same rows now?
                if (Describe(db.Rows(scan.Prefix, long.MaxValue)) != scan.Seen)
                    throw new SerializationFailure("the rows under " + scan.Prefix + " have changed");
        }
        db.Apply(writes);
    }
}

Each scenario below is a scripted interleaving that returns true when the anomaly happened, and the loop at the end asserts the table above.

C#104 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

Database Seed(params (string Key, int Value)[] rows)
{
    var db = new Database();
    var setup = db.Begin(Isolation.ReadCommitted);
    foreach (var row in rows) setup.Write(row.Key, row.Value);
    setup.Commit();
    return db;
}

bool TryCommit(Transaction t) { try { t.Commit(); return true; } catch (SerializationFailure) { return false; } }

bool NonRepeatableRead(Isolation level)
{
    var db = Seed(("x", 1));
    var reader = db.Begin(level);
    int first = reader.Read("x").Value;
    var writer = db.Begin(level);
    writer.Write("x", 2);
    writer.Commit();
    return reader.Read("x").Value != first;                    // the same query, two answers
}

bool Phantom(Isolation level)
{
    var db = Seed(("task:1", 1));
    var reader = db.Begin(level);
    int first = reader.Scan("task:").Count;
    var writer = db.Begin(level);
    writer.Write("task:2", 1);
    writer.Commit();
    return reader.Scan("task:").Count != first;                // a row appeared in the middle of the transaction
}

bool ReadSkew(Isolation level)
{
    var db = Seed(("a", 500), ("b", 500));
    var auditor = db.Begin(level);
    int a = auditor.Read("a").Value;
    var transfer = db.Begin(level);
    transfer.Write("a", 400);
    transfer.Write("b", 600);
    transfer.Commit();
    int b = auditor.Read("b").Value;
    return a + b != 1000;                                      // money appeared out of nowhere
}

bool LostUpdate(Isolation level)
{
    var db = Seed(("counter", 100));
    var first = db.Begin(level);
    var second = db.Begin(level);
    int seenByFirst = first.Read("counter").Value;
    int seenBySecond = second.Read("counter").Value;
    first.Write("counter", seenByFirst + 10);
    bool firstCommitted = TryCommit(first);
    second.Write("counter", seenBySecond + 20);
    bool secondCommitted = TryCommit(second);
    return firstCommitted && secondCommitted && db.Latest("counter") != 130;   // both were told "done", yet one increment is gone
}

bool WriteSkew(Isolation level)
{
    var db = Seed(("doctor:alice", 1), ("doctor:bob", 1));      // the rule: at least one doctor stays on call
    var alice = db.Begin(level);
    var bob = db.Begin(level);
    if (alice.Scan("doctor:").Count(d => d.Value == 1) >= 2) alice.Write("doctor:alice", 0);
    if (bob.Scan("doctor:").Count(d => d.Value == 1) >= 2) bob.Write("doctor:bob", 0);
    TryCommit(alice);
    TryCommit(bob);
    return db.Latest("doctor:alice") + db.Latest("doctor:bob") == 0;
}

bool DoubleBooking(Isolation level)
{
    var db = Seed(("room:1", 0));
    var carol = db.Begin(level);
    var dave = db.Begin(level);
    bool carolSawFree = carol.Scan("booking:room1:10:").Count == 0;
    bool daveSawFree = dave.Scan("booking:room1:10:").Count == 0;
    if (carolSawFree) carol.Write("booking:room1:10:carol", 1);
    if (daveSawFree) dave.Write("booking:room1:10:dave", 1);
    bool carolBooked = TryCommit(carol);
    bool daveBooked = TryCommit(dave);
    return carolBooked && daveBooked;                           // both got the room
}

var levels = new[] { Isolation.ReadCommitted, Isolation.Snapshot, Isolation.Serializable };
var scenarios = new (string Name, Func<Isolation, bool> Run, bool[] Expected)[]
{
    ("non-repeatable read", NonRepeatableRead, new[] { true, false, false }),
    ("phantom read",        Phantom,           new[] { true, false, false }),
    ("read skew",           ReadSkew,          new[] { true, false, false }),
    ("lost update",         LostUpdate,        new[] { true, false, false }),
    ("write skew",          WriteSkew,         new[] { true, true, false }),
    ("double booking",      DoubleBooking,     new[] { true, true, false }),
};
foreach (var scenario in scenarios)
    for (int i = 0; i < levels.Length; i++)
        Debug.Assert(scenario.Run(levels[i]) == scenario.Expected[i], $"{scenario.Name} at {levels[i]}");

Read the lost-update row carefully. At Snapshot and Serializable the anomaly did not "happen" because the second transaction was told to retry, not because the increments merged. The application still has to handle that failure.

LLD

Patterns that make concurrent code correct

Serializable is the only level that closes every gap, but you rarely need it everywhere. In order of preference:

1. Let the database do the arithmetic. The most common race is read, compute in the application, write back. Replace it with one statement.

sql
UPDATE stock SET quantity = quantity - 1 WHERE item_id = 42 AND quantity > 0;
-- one row affected: you got the item. Zero rows: it is sold out.

The row is locked while the statement runs, and the condition is checked against the latest committed row, so two buyers cannot both take the last item at Read Committed or above. The same shape fixes counters, balances and sequence numbers.

2. Lock what you are about to decide on. When the decision needs a read first, read with a lock.

sql
BEGIN;
SELECT balance FROM accounts WHERE id = 7 FOR UPDATE;   -- others wait here
-- decide in the application, then:
UPDATE accounts SET balance = balance - 100 WHERE id = 7;
COMMIT;

FOR UPDATE takes the row lock at read time. NOWAIT fails instead of waiting. SKIP LOCKED skips rows other transactions hold, which turns a table into a work queue: each worker takes different rows, SELECT id FROM jobs WHERE state = 'ready' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED (PostgreSQL 9.5+, MySQL 8.0+).

3. Check a version instead of holding a lock. Optimistic concurrency suits user edits, where a lock would be held across a human's coffee break.

sql
UPDATE profiles SET data = :new, version = version + 1 WHERE id = :id AND version = :seen;
-- zero rows affected: someone else saved first. Reload, merge or ask the user.

HTTP's ETag and If-Match headers are the same idea. It is cheap when conflicts are rare and wasteful when they are not.

4. Let a constraint be the referee. A unique index on (room, slot) makes a double booking impossible at any isolation level, because the database checks it atomically. PostgreSQL's exclusion constraints do the same for overlapping time ranges. INSERT ... ON CONFLICT DO NOTHING makes creation idempotent. Declare the rule and the database enforces it for every code path, including the ones you forgot.

5. Turn write skew into a write-write conflict. Write skew happens because the transactions write different rows. Make them write the same one: lock a parent row (the ward, the room-day), or keep a counter row that every transaction updates. Now first-committer-wins or a row lock catches it, even at snapshot isolation.

6. Use Serializable and retry. For rules that span many rows and have no natural lock, run at Serializable and accept that any transaction may fail with a serialization error (SQLSTATE 40001 in PostgreSQL). The application must retry the whole transaction from the beginning, because the snapshot it decided on is stale. The sample shows the doctors again: the second request fails, retries, sees that Alice is already off call, and is refused by the application's own rule.

C# · Both doctors ask to go off call at the same moment. At Serializable the loser fails…18 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// Both doctors ask to go off call at the same moment. At Serializable the loser fails, retries from scratch and is refused.
var clinic = Seed(("doctor:alice", 1), ("doctor:bob", 1));
var requestA = clinic.Begin(Isolation.Serializable);
var requestB = clinic.Begin(Isolation.Serializable);
Debug.Assert(requestA.Scan("doctor:").Count(d => d.Value == 1) == 2 && requestB.Scan("doctor:").Count(d => d.Value == 1) == 2);
requestA.Write("doctor:alice", 0);
requestB.Write("doctor:bob", 0);
requestA.Commit();
Debug.Assert(!TryCommit(requestB));                                   // serialization failure: the application must retry
var retryB = clinic.Begin(Isolation.Serializable);                    // a new transaction, a new snapshot
int onCallNow = retryB.Scan("doctor:").Count(d => d.Value == 1);
Debug.Assert(onCallNow == 1);                                         // Bob now sees that Alice has gone, so the rule refuses him
Debug.Assert(clinic.Latest("doctor:alice") + clinic.Latest("doctor:bob") == 1);

Retries have two rules. Limit them, with a little jitter, so a hot spot does not turn into a retry storm. And keep side effects out of the transaction (sending an email, calling a payment API): do them after commit, driven by an outbox row written in the same transaction, as the queues lesson describes, or a retry will do them twice.

LLD

Deadlocks

When transactions hold locks and wait for each other, they can wait forever. Transfer one: lock account A, then B. Transfer two: lock B, then A. Each now holds what the other needs. The database finds this by building a waits-for graph, with an arrow from each blocked transaction to the one holding what it needs, and looking for a cycle. It breaks the cycle by rolling back one victim (usually the one that has done the least work), which the application sees as an error to retry (PostgreSQL's 40P01; MySQL error 1213).

C# · Exclusive locks held until the transaction ends, and the "waits for" graph they create.42 lines
using System;
using System.Collections.Generic;
using System.Linq;

// Exclusive locks held until the transaction ends, and the "waits for" graph they create.
public sealed class LockTable
{
    private readonly Dictionary<string, string> holder = new Dictionary<string, string>();      // resource -> transaction holding it
    private readonly Dictionary<string, string> waitingOn = new Dictionary<string, string>();   // transaction -> resource it is blocked on

    // True if the lock is granted; false if the transaction now waits for whoever holds it.
    public bool Lock(string txn, string resource)
    {
        if (!holder.TryGetValue(resource, out var owner) || owner == txn) { holder[resource] = txn; waitingOn.Remove(txn); return true; }
        waitingOn[txn] = resource;
        return false;
    }

    public void ReleaseAll(string txn)
    {
        foreach (var resource in holder.Where(h => h.Value == txn).Select(h => h.Key).ToList()) holder.Remove(resource);
        waitingOn.Remove(txn);
    }

    // A blocked transaction points at the holder of what it needs. A cycle of such arrows is a deadlock: nobody in it can
    // ever proceed. The victim is the youngest transaction in the cycle (the largest id), which has done the least work.
    public string FindVictim()
    {
        foreach (var start in waitingOn.Keys)
        {
            var path = new List<string>();
            string current = start;
            while (current != null && !path.Contains(current))
            {
                path.Add(current);
                current = waitingOn.TryGetValue(current, out var resource) ? holder[resource] : null;
            }
            if (current != null) return path.Skip(path.IndexOf(current)).OrderBy(t => t, StringComparer.Ordinal).Last();
        }
        return null;
    }
}
C# · Two transfers lock the same two accounts in opposite orders.18 lines
using System;
using System.Diagnostics;

// Two transfers lock the same two accounts in opposite orders.
var locks = new LockTable();
locks.Lock("T1", "A");                                                // T1 moves money from A to B
locks.Lock("T2", "B");                                                // T2 moves money from B to A
bool t1GotB = locks.Lock("T1", "B");
bool t2GotA = locks.Lock("T2", "A");
Debug.Assert(!t1GotB && !t2GotA && locks.FindVictim() == "T2");       // T1 waits for T2 and T2 for T1: roll back the younger

// The same two transfers, each locking the account with the lower name first, cannot form a cycle.
var ordered = new LockTable();
Debug.Assert(ordered.Lock("T1", "A"));
Debug.Assert(!ordered.Lock("T2", "A") && ordered.FindVictim() == null);   // T2 waits, but T1 is not waiting for anything T2 holds
Debug.Assert(ordered.Lock("T1", "B"));
ordered.ReleaseAll("T1");                                             // T1 commits
Debug.Assert(ordered.Lock("T2", "A") && ordered.Lock("T2", "B") && ordered.FindVictim() == null);

Detection is the safety net. The cure is to make the cycle impossible: take locks in one global order (lowest account id first, parent before child), keep transactions short, and touch as few rows as you can. Always catch deadlock errors and retry a bounded number of times.

HLD

Long transactions and hot rows

Long transactions are expensive in every design. They hold locks that block others, they hold a connection, they make deadlocks likelier, and under MVCC they pin old versions: nothing created after the transaction began can be cleaned up while it might still read the older rows. The sample updates one key a thousand times while a report holds a snapshot, and shows that no version can be removed until the report ends.

C# · A long-running transaction keeps every version created after it began, because it may…16 lines
using System;
using System.Diagnostics;

// A long-running transaction keeps every version created after it began, because it may still ask for the old ones.
var busy = Seed(("hot", 0));
var report = busy.Begin(Isolation.Snapshot);                          // a report that runs for hours
for (int update = 1; update <= 1_000; update++)
{
    var writer = busy.Begin(Isolation.Snapshot);
    writer.Write("hot", update);
    writer.Commit();
}
Debug.Assert(busy.VersionCount == 1_001);
Debug.Assert(busy.Vacuum(report.StartTs) == 0);                       // nothing can be removed while the report might read version 0
Debug.Assert(report.Read("hot") == 0);                                // and it still sees the value it started with
Debug.Assert(busy.Vacuum(long.MaxValue) == 1_000 && busy.VersionCount == 1);   // once it is gone, all but the newest version go

In PostgreSQL this shows up as table bloat and a VACUUM that cannot reclaim space; in InnoDB as a growing undo history. Set idle_in_transaction_session_timeout, statement_timeout and lock_timeout (or the equivalents), never keep a transaction open across a user's think time or an external API call, and run long reports on a replica or from an exported snapshot.

A hot row is a queue. Writers to one row take turns, so the throughput of a contended row is one divided by the time the lock is held.

Example · estimate
lock held 2 ms (one local statement and commit):        ~500 updates/s
lock held 20 ms (a network call inside the transaction): ~50 updates/s
same counter spread over 16 rows, summed when read:      ~16x the rate
rule: throughput of one contended row = 1 / time the lock is held

The fixes are to shorten the time under the lock (do the slow work before or after the transaction), to spread the row into N rows and sum them on read, to give each key a single writer through a queue, or to allocate in blocks (a server reserves 100 units of stock at a time and sells them from memory).

HLD

Isolation is not the same as consistency

The word "consistency" is used for two different things. Isolation is about what concurrent transactions may observe, across many rows, at one logical moment. Consistency models such as linearizability, from the consistency and availability lesson, are about how recent a read of one object is when there are replicas. A database can be serializable and still return stale data from a replica, and a serializable order need not match the real-time order in which transactions finished (the time, clocks and ordering lesson shows how real-time order is obtained). Strict serializability adds the real-time order and is what Spanner provides as external consistency. When a design spans replicas or services, say which of the two properties you are claiming.

A transaction also ends at the edge of one database. When one business action touches several services, no isolation level helps, and the answer is to design for it: an outbox to publish events reliably, idempotent handlers, and compensating steps. The distributed transactions lesson covers two-phase commit, sagas and the inbox that makes a receiver idempotent.

HLD

Failure modes and edge cases

SituationWhat happensDefence
Check, then act, in application codeTwo requests both pass the checkAtomic update, row lock or a constraint
Retrying a serialization failure that already sent an emailThe email goes out twiceSide effects after commit through an outbox; idempotent handlers
A transaction left "idle in transaction"Locks held, old versions pinnedIdle and statement timeouts; never wait on a user inside a transaction
An ORM wraps a whole request in one transactionLong lock hold times and deadlocksNarrow the transaction to the statements that need it
Assuming Repeatable Read is the same everywhereSilent lost update on one engine, an error on anotherTest the behaviour you rely on; prefer atomic statements
Read replica lagA user does not see their own writeRead from the primary after a write (see the consistency lesson)
Unbounded deadlock retriesLivelock under loadA retry limit with jitter, and an alert on the rate
A long report on the primaryBloat, replica conflicts, slow queriesRun it on a replica or an exported snapshot

Senior depth

What senior interviews ask about transactions

Interviewer follow-upL5What is the difference between Read Committed and Repeatable Read? Give an example of a bug each allows.How to answer

At Read Committed each statement sees data committed before it began, so two reads in one transaction can differ: a price changes between the quote and the charge. At Repeatable Read (snapshot isolation in PostgreSQL) the whole transaction reads one snapshot, so those reads agree. The cost is that a read-then-write that loses a race must fail and be retried, and write skew is still possible. Add that the name means different things on PostgreSQL and MySQL.

Interviewer follow-upL5Two users try to buy the last item. How do you prevent overselling?How to answer

Never check then insert. Use one conditional statement, UPDATE stock SET quantity = quantity - 1 WHERE item_id = ? AND quantity > 0, and look at the rows affected. Alternatives are SELECT ... FOR UPDATE before the write, or a version column with a retry. For extreme demand on one item, route that item's purchases through a single writer or a queue, or reserve stock in blocks per server, and say that the hot row limits throughput to one over the lock time.

Interviewer follow-upL6Explain write skew with an example and say how you would prevent it.How to answer

Two transactions read overlapping data, each decides its write is safe, and they write different rows, so neither conflicts and the combined result breaks a rule: two doctors both go off call, two users both book the room. Snapshot isolation allows it. Prevent it with a unique or exclusion constraint where the rule can be declared, by locking a parent row so the transactions conflict, or by running at Serializable and retrying on failure.

Interviewer follow-upL6What is MVCC, and what problem does a long-running transaction cause?How to answer

MVCC keeps several versions of a row, each stamped by the commit that wrote it, so a transaction reads a consistent snapshot without blocking writers. Old versions can be removed only when no snapshot can still read them. A long transaction pins every version created after it started, so storage bloats (PostgreSQL's vacuum cannot reclaim space, InnoDB's undo log grows), scans slow down, and replicas can conflict. Keep transactions short, set timeouts, and run reports on a replica.

Interviewer follow-upL6Transfers between accounts sometimes deadlock. Why, and how do you fix it?How to answer

Two transfers in opposite directions lock the two accounts in opposite orders, each holding what the other needs. The database detects the cycle in its waits-for graph and rolls one back. Fix the cause by always locking in a fixed order (lowest account id first), keeping transactions short and touching fewer rows. Keep the safety net too: catch the deadlock error and retry a bounded number of times with jitter.

Interviewer follow-upL7When would you choose Serializable, and what must you do to run it in production?How to answer

When a rule spans several rows, has no natural lock or constraint, and a violation is costly: allocation against shared limits, cross-row invariants, financial rules. Everything must be built for aborts: retry the whole transaction with a limit and jitter, keep transactions short to reduce conflicts, keep side effects out of it, and monitor the serialization failure rate. Where contention is high, fall back to targeted locks or constraints on the few hot rules and leave the rest at a weaker level.

Interviewer follow-upL7A three-hour report makes the OLTP database slow. What is going on, and what do you do?How to answer

Probably the report's snapshot or locks. Under MVCC it pins old versions so vacuum or purge cannot reclaim space and the tables bloat; it may also hold locks or consume I/O. Move it to a replica (watching for replica query conflicts), or export a snapshot, or break it into keyset-paginated chunks that each run briefly. Set statement timeouts on the primary so a runaway query cannot hold things for hours.

Interviewer follow-upL7How do isolation levels relate to consistency models such as linearizability?How to answer

They answer different questions. Isolation says which interleavings of multi-row transactions are allowed, ending in serializability: the outcome equals some serial order. Linearizability says a single object behaves like one copy and reads see the latest write in real time. Serializable alone does not promise recency, and a linearizable register says nothing about multi-row transactions. Strict serializability combines them; Spanner provides it with synchronised clocks. Name which one the design needs.

HLD

Putting it into an answer

When a design involves money, stock or bookings, say where the race is and how you close it. Name the invariant ("a seat is sold once"), find the check-then-act gap, and pick the cheapest tool that closes it: a conditional update or a unique constraint first, a lock or a version check next, Serializable with retries for rules you cannot express as a constraint. Then say what you do on failure: retry the transaction, keep side effects behind an outbox, and give up politely after a limit.

Summary

A transaction makes several changes atomic and, to a degree set by the isolation level, invisible to others until commit. Atomicity and durability are the engine's work; consistency is the application's, using constraints the engine can enforce. Read Committed lets two reads in one transaction disagree. Snapshot isolation gives a stable snapshot and stops lost updates by aborting the second writer, but allows write skew when transactions write different rows. Serializable closes that gap, at the price of aborts and retries. MVCC achieves all this by keeping versions, which must be cleaned up, so long transactions are costly; locking achieves it by waiting, which creates deadlocks that detection resolves and a fixed lock order prevents. In practice close each race with the cheapest tool: an atomic update, a lock, a constraint, a version column, or Serializable with a retry loop. Spread hot rows, because their throughput is one over the lock time.

Check yourself

Try answering out loud before you reveal each answer.

QuestionTwo requests each read a counter of 100, add 10 and 20, and write it back. At Read Committed the result is 110 or 120. What stops that, and how does the fix differ between PostgreSQL's Repeatable Read and a single atomic statement?Reveal answer

The read-modify-write has a gap between the read and the write. At snapshot isolation (PostgreSQL's Repeatable Read) the second writer finds a newer committed version of the row and fails with a serialization error, so the application must retry. A single UPDATE counter SET value = value + 20 has no gap: the row is locked and the new value is computed from the latest committed row, so both increments apply and nothing needs retrying.

QuestionWhy does snapshot isolation allow two doctors to both go off call, although it prevents lost updates?Reveal answer

The first-committer-wins check only compares rows that both transactions wrote. Alice and Bob write different rows, so no conflict is detected, even though each decided from a count that the other changes. Serializable adds a check on what was read, a unique or exclusion constraint where the rule can be declared, or locking a shared parent row turns it into a conflict.

QuestionA transaction fails with a serialization error. What exactly should the application do, and what must it avoid?Reveal answer

Roll back and rerun the whole transaction from the start, because its snapshot and decisions are stale, with a retry limit and jitter. It must avoid side effects inside the transaction (emails, payment calls) that a retry would repeat; those belong after commit, driven by an outbox row written in the same transaction.

QuestionA forgotten transaction has been open for six hours. Why is the database getting bigger and slower even though that transaction only read data?Reveal answer

Under MVCC old row versions can be removed only when no snapshot can still read them. The open transaction's snapshot pins every version created since it began, so vacuum or purge cannot reclaim them, tables and indexes bloat and scans read dead versions. It may hold locks as well. Kill it, add idle-in-transaction and statement timeouts, and run long reads on a replica.

Sources and further reading

Lesson 4 of 11

Nice. Lock it in, then keep going.

Up next · Lesson 5Time, clocks and orderingWhy you cannot trust timestamps from different machines, and what to use instead. Happens-before, Lamport and vector clocks, hybrid logical clocks, TrueTime and commit wait, and the places where clocks quietly break real systems.

Send a message

It goes straight to my inbox. I usually reply within a few days.