AlgoViz

Isolation levels

medium 26 min

Isolation decides what transactions that run at the same time may see of each other.

Video lesson · Chapter 1 of 5

Alice reads a price that vanishes

0:00 / 3:33

Isolation levels in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Isolation is the I in ACID. It decides what one transaction may notice of others that run at the same time.

The strongest promise is serializable: the result is the same as if the transactions had run one after another in some order. Weaker levels allow certain surprises, called anomalies, and let more work run at once.

The SQL standard names four levels. Databases implement them in different ways, and the same name can mean different things. The anomalies are the real language; the names are only labels.

Why it exists

Running transactions one at a time is safe and slow. Most of them touch different rows and would never have disturbed each other, so a database lets them overlap.

Overlap brings surprises: a value that is taken back, a row that changes between two reads, a count that no longer fits. Some programs do not care. Others pay money on the basis of such a value.

Levels let each transaction choose. A page view can live with little. A rule such as "at least one doctor on call" needs the strongest.

A short history

  1. 1992

    The SQL-92 standard defines four levels through three phenomena: dirty read, non-repeatable read and phantom.

  2. 1995

    Berenson, Bernstein, Gray, Melton and the O'Neils publish A Critique of ANSI SQL Isolation Levels. It shows gaps in the definitions and describes snapshot isolation.

  3. 2011

    PostgreSQL 9.1 adds a true serializable level. Before that, asking for serializable gave a snapshot.

Words to know

Anomaly
A result that could not happen if transactions ran one at a time.
Dirty read
Reading a value that is not committed.
Non-repeatable read
The same row gives two values in one transaction.
Phantom
The same query matches different rows in one transaction.
Lost update
A write based on an old read removes somebody else's change.
Write skew
Two transactions read the same facts, write different rows, and break a rule together.
Snapshot
A view of the database as of one moment.
Serializable
Equal to some one-at-a-time order.

How it works

Step through the idea, or press Play.

Step 1 of 3

Name the anomaly. What could go wrong if another transaction runs in between

Understand it

Start here

Counting fish in a busy pond

Sam has to write down how many fish are in the pond. Noor is at work on the other side and adds and removes fish. What Sam writes depends on the rules between them.

How many fish?
Count5I count 5SamNoor

The photo is fast but may be old. The gate is strict but makes others wait.

The problem

Safe and slow, or fast and risky

One at a time, or together

More isolation

  • Easier to reason about
  • Fewer surprises
  • More waiting or retries

More concurrency

  • More done at once
  • Half-written or changing values
  • The program must protect itself

Anomalies

What can go wrong

Five anomalies

AnomalyWhat happensCaused by
Dirty readYou read x = 100, then the writer rolls back to 50Reading uncommitted data
Non-repeatable readThe same row gives 50, then 100Somebody updated it and committed
Phantom readThe same count gives 5, then 6Somebody inserted or deleted matching rows
Lost updateTwo sales from 10 leave 9Read, compute, write without protection
Write skewTwo doctors leave, nobody is on callEach read what the other was about to change
The first three are in the SQL standard. The last two break real programs just as often.

Which anomaly is it?

Levels

The four levels

  • Read uncommitted

    Allows everything. For rough counts where dirty values do no harm. Some databases never really offer it.

  • Read committed

    No dirty reads. Other surprises are possible. A good default for most short transactions.

  • Repeatable read

    Rows you have read stay the same. The standard still allows phantoms. For reports that must agree with themselves.

  • Serializable

    Equal to one at a time. For rules over several rows. Expect waiting or retries.

What each level allows

LevelDirtyNon-repeatablePhantomWrite skew
Read uncommittedPossiblePossiblePossiblePossible
Read committedNoPossiblePossiblePossible
Repeatable read (standard)NoNoPossibleDepends on the database
Snapshot isolationNoNoNoPossible
SerializableNoNoNoNo
Snapshot isolation is not in the standard. It has none of the three named phenomena and is still not serializable.

Three levels in one system

Users reach three services. A nightly report at repeatable read uses one snapshot of old row versions as of 01:00. Checkout at read committed takes a new snapshot per query from the newest versions. An on-call rota at serializable is checked and may abort. All use one database machine.
The level belongs to the transaction. One database serves all three at once.

Names

The same name, different behaviour

Defaults

DatabaseDefaultWorth knowing
PostgreSQLRead committedRead uncommitted acts like read committed. Repeatable read is a snapshot without phantoms
MySQL InnoDBRepeatable readPlain reads use one snapshot. Locking reads of a range use gap or next-key locks
SQL ServerRead committedWith locks by default, or with row versions if the database option is on
OracleRead committedOffers read committed, serializable and read-only
SQLiteSerializableOne writer at a time (without shared-cache read uncommitted)
CockroachDBSerializableApplications handle retry errors
Checked against each product's documentation.

Snapshots

A photograph of the data

Like a photo of a whiteboard at the start of a meeting: others go on writing, and you keep looking at your photo. The database keeps old versions of rows and shows each transaction those committed before its snapshot. How versions are stored and cleaned is in concurrency control.

Which version is seen

v(s)=max⁡{ c∈C:c≤s }C={95,105,110}, s=100⇒95v(s) = \max\{\, c \in C : c \le s \,\} \qquad C = \{95, 105, 110\},\ s = 100 \Rightarrow 95
C holds the commit times of the versions of one row and s is the snapshot time. The versions of 105 and 110 do not exist for this transaction.
  • Reads do not wait

    A reader uses an old version while a writer makes a new one.

  • Writers are not blocked by readers

    A long report does not stop an update.

  • One moment

    All queries of a transaction agree with each other.

  • The price

    Old versions need space and cleaning, and the view may be old.

In PostgreSQL the snapshot of a repeatable read transaction is taken at its first statement, not at BEGIN. At read committed every statement gets a new one.

Write skew

When a photo is not enough

A hospital needs at least one doctor on call. Alice and Bob are both on call. Each opens the page, sees two names, decides the other one covers, and leaves. They change different rows, so nothing conflicts, and nobody is left.

Both leave

Snapshot isolation allows this. Serializable aborts one of the two.

Four cures

CureHowCost
SerializableThe database notices and aborts oneRetries
Lock what you readSELECT ... FOR UPDATE on both rowsWaiting; does not cover rows that do not exist yet
Make it one rowA counter per shift that both must changeA hot row
A constraintLet the database hold the ruleOnly for rules it can express

Using it

Set the level and retry

SQL
-- one report, one snapshotBEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY;SELECT COUNT(*), SUM(amount) FROM orders WHERE status = 'pending';SELECT region, SUM(amount) FROM orders WHERE status = 'pending' GROUP BY region;COMMIT;-- look at the current level, and set a default for the sessionSHOW transaction_isolation;SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED;
PostgreSQL. The level must be set before the first query of the transaction.
Python
import randomimport timefrom psycopg2 import errorsfrom psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLEdef transfer(conn, src, dst, amount, tries=3):    # set the level before the transaction starts; the driver sends BEGIN itself    conn.set_session(isolation_level=ISOLATION_LEVEL_SERIALIZABLE)    for attempt in range(tries):        try:            with conn.cursor() as cur:                cur.execute("SELECT balance FROM accounts WHERE id = %s", (src,))                row = cur.fetchone()                if row is None or row[0] < amount:                    raise ValueError("insufficient funds")                cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amount, src))                cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, dst))                if cur.rowcount != 1:                    raise ValueError("no such account")            conn.commit()                      # the failure may come here too            return        except (errors.SerializationFailure, errors.DeadlockDetected):            conn.rollback()            if attempt == tries - 1:                raise            time.sleep(random.uniform(0, 0.05 * 2 ** attempt))        except Exception:            conn.rollback()            raise
psycopg2: the whole transaction is retried, and every path rolls back.

SELECT ... FOR UPDATE locks the rows it reads, at any level. FOR SHARE lets others read with a lock too, NOWAIT fails at once, and SKIP LOCKED passes over locked rows. These belong to concurrency control.

What retries cost

E=11−pp=0.2:;E=1.25 runs,P(3 fail)=0.23=0.8%E = \frac{1}{1 - p} \qquad p = 0.2:; E = 1.25 \text{ runs}, \qquad P(\text{3 fail}) = 0.2^3 = 0.8\%
p is the chance that one run aborts, assumed to be the same each time. Under real contention p grows with load, so wait a random moment between runs.

Decide

Which level should I use?

Choosing a level

WorkLevel
Most short transactionsRead committed
Reports and exportsRepeatable read or snapshot
Money and rules over rowsSerializable, or explicit locks
Rough live figuresRead uncommitted if dirty values are fine, or a snapshot that costs no locks

Summary

The whole topic in one minute.

Isolation levels decide which anomalies a transaction may meet. Read committed stops dirty reads, repeatable read keeps rows stable, and serializable makes the result equal to a one-at-a-time order. Names differ between databases, so check what yours really does.

Snapshots let reads run without waiting, yet they allow write skew. For most work use the default with atomic updates. Use one snapshot for reports, and serializable with retries when a rule spans several rows.

  • Isolation decides what transactions see of each other.
  • Read committed stops dirty reads; repeatable read keeps rows stable; serializable equals one at a time.
  • A snapshot shows one moment without waiting, and still allows write skew.
  • Names differ: read your database's manual.
  • Retry the whole transaction after a serialization failure.
  • Prefer one atomic update to read, compute, write.

Sources