Isolation levels
medium 26 minIsolation 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
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
1992
The SQL-92 standard defines four levels through three phenomena: dirty read, non-repeatable read and phantom.
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.
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.
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.
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
| Anomaly | What happens | Caused by |
|---|---|---|
| Dirty read | You read x = 100, then the writer rolls back to 50 | Reading uncommitted data |
| Non-repeatable read | The same row gives 50, then 100 | Somebody updated it and committed |
| Phantom read | The same count gives 5, then 6 | Somebody inserted or deleted matching rows |
| Lost update | Two sales from 10 leave 9 | Read, compute, write without protection |
| Write skew | Two doctors leave, nobody is on call | Each read what the other was about to change |
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
| Level | Dirty | Non-repeatable | Phantom | Write skew |
|---|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible | Possible |
| Read committed | No | Possible | Possible | Possible |
| Repeatable read (standard) | No | No | Possible | Depends on the database |
| Snapshot isolation | No | No | No | Possible |
| Serializable | No | No | No | No |
Three levels in one system
Names
The same name, different behaviour
Defaults
| Database | Default | Worth knowing |
|---|---|---|
| PostgreSQL | Read committed | Read uncommitted acts like read committed. Repeatable read is a snapshot without phantoms |
| MySQL InnoDB | Repeatable read | Plain reads use one snapshot. Locking reads of a range use gap or next-key locks |
| SQL Server | Read committed | With locks by default, or with row versions if the database option is on |
| Oracle | Read committed | Offers read committed, serializable and read-only |
| SQLite | Serializable | One writer at a time (without shared-cache read uncommitted) |
| CockroachDB | Serializable | Applications handle retry errors |
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
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
Four cures
| Cure | How | Cost |
|---|---|---|
| Serializable | The database notices and aborts one | Retries |
| Lock what you read | SELECT ... FOR UPDATE on both rows | Waiting; does not cover rows that do not exist yet |
| Make it one row | A counter per shift that both must change | A hot row |
| A constraint | Let the database hold the rule | Only for rules it can express |
Using it
Set the level and retry
-- 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;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() raiseSELECT ... 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
Decide
Which level should I use?
Choosing a level
| Work | Level |
|---|---|
| Most short transactions | Read committed |
| Reports and exports | Repeatable read or snapshot |
| Money and rules over rows | Serializable, or explicit locks |
| Rough live figures | Read 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.