SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

Transaction Isolation Levels

How much can two transactions see of each other? Dirty reads, repeatable reads and the levels that stop them.

⏱ 16 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Isolation is the "I" in ACID. It answers one question: when two transactions run at the same time, how much of each other's work are they allowed to see?

  • Perfect isolation (serializable) makes it look as if transactions ran one after another. It is the safest and the slowest.
  • Weaker levels let transactions overlap more, which is faster, but allows odd results called anomalies: dirty reads, non-repeatable reads, phantoms, lost updates and write skew.
  • You choose a level per transaction or per database. Every level is a trade: more safety costs more waiting or more retries.

02Concept: What is it?

A busy database runs thousands of transactions at once. If each one had to wait for the previous one to finish, nothing would be fast. So the database lets them overlap. Overlapping is where trouble starts: one transaction may read data that another is halfway through changing.

The SQL standard describes four isolation levels. Each level is defined by which problems it still allows.

LevelDirty readNon-repeatable readPhantom read
Read uncommittedPossiblePossiblePossible
Read committedPreventedPossiblePossible
Repeatable readPreventedPreventedPossible (in the standard)
SerializablePreventedPreventedPrevented

Two more problems matter in real systems but are not in that table: a lost update (two writers overwrite each other) and write skew (two transactions each check a rule, then both break it together).

Two transactions on one row
πŸ“–T1 readsbalance = 100
→↓time passes
✏️T2 writes + commitsbalance = 50
→↓time passes
πŸ“–T1 reads again100 or 50?
T2 changes the row between two reads of T1. What T1 sees on the second read depends on the isolation level.
🧠Stronger is not free
A stronger level does not make the database smarter. It makes it block transactions that might clash, or abort one of them and ask you to retry. Either way you pay in speed.

03Real-Life Example

🍡Two Clerks and One Ledger
Two clerks share one paper ledger. Clerk A starts adding up a column of numbers. In the middle, clerk B crosses out a number and writes a new one. If A keeps going, the total mixes old and new numbers. The shop can handle this in different ways: A works from a photocopy made at the start (a snapshot), or A locks the page so B must wait, or A is allowed to peek at B's unfinished scribbles (dangerous). Each choice is an isolation level.
Two clerks
Isolation levels
B’s unfinished scribbles
Uncommitted data (a dirty read if you read it)
Looking at the same line twice and seeing a change
A non-repeatable read
A new line appears in the column you are adding up
A phantom row
Both clerks start from 100 and each write their own total
A lost update
Making a photocopy at the start
A snapshot (repeatable read)
Locking the page
Locks (serializable by locking)
Telling a clerk β€œredo your work”
A transaction abort and retry
Lost update, step by step
1️⃣Both read 100
→↓
2️⃣T1 writes 110
→↓
3️⃣T2 writes 120overwrites T1
→↓
❌Should be 130T1 +10 is gone

04Why Do We Need It?

πŸ’ΈCorrect money
Balances, stock counts and seat bookings must not be silently wrong because two users clicked at once.
⚑Speed on purpose
Full isolation is slow. A choice of levels lets you pay for safety only where it matters.
🧩Predictable code
If you know what your level allows, you know which bugs to look for and which checks to add.
πŸ›‘οΈBusiness rules
Rules like β€œat least one doctor on call” can break when two transactions check them at the same time.
πŸ“ŠStable reports
A long report needs a steady view. A snapshot stops the numbers moving under it.
πŸ”Fewer surprises
Many production bugs that appear only under load are isolation bugs.
Concurrency makes databases fast and also makes them tricky. Isolation levels let you choose how much trickiness you will accept.

05Where Do We Use It?

🏦Payments and banking
Transfers and balances need high isolation, or explicit locks and checks.
🎟️Booking and inventory
Two buyers must not get the last seat or the last item.
πŸ“ˆReports and analytics
A snapshot read gives a report one consistent view while writes continue.
🧾Order systems
Checking stock, then creating an order, must act as one safe step.
πŸ₯Rules across rows
β€œAt least one on call” style rules are the classic write skew case.
πŸ—„οΈEvery SQL database
PostgreSQL, MySQL, SQL Server, Oracle and others all offer levels, with different details.

06Types / Parts / How It Works

The problems (anomalies)

ProblemWhat happensExample
Dirty readYou read data another transaction has not committed yetT1 sets balance to 50 and rolls back. T2 read 50, which never existed.
Non-repeatable readYou read a row twice and get different valuesT1 reads 100. T2 commits 50. T1 reads 50.
Phantom readYou run the same range query twice and get different rowsCOUNT of open orders goes from 2 to 3.
Lost updateTwo read-then-write sequences overwrite each otherBoth add to 100. One +10 or +20 vanishes.
Write skewTwo transactions check a shared rule, then each change a different row, breaking the rule togetherBoth doctors leave, nobody is on call.

The levels and how databases achieve them

From weakest to strongest
Read uncommitted
πŸ‘€Sees drafts
⚑Fastest
Read committed
βœ…Only committed data
πŸ”„New snapshot per query
Repeatable read
πŸ“ΈOne snapshot per transaction
⚠️Write skew possible
Serializable
πŸ”’Looks one-at-a-time
🐒Waits or retries
Riskier Middle Safest
Each step up blocks or aborts more, and so gives up some speed.
TechniqueHow it worksCost
LockingReaders and writers take locks; others wait for the lock to be releasedWaiting, and the risk of deadlock
Snapshots (MVCC)Each transaction reads a consistent snapshot of old versions, so readers do not block writersExtra storage for old versions, and write conflicts still need handling
Serializable snapshot checksRun on snapshots, track dependencies, abort a transaction if a dangerous pattern formsAborts that you must retry
⚠️Names are not the same everywhere
The standard describes behaviour loosely, and products fill it in differently. For example, PostgreSQL's repeatable read is snapshot isolation (so it also stops phantoms), while it still allows write skew. Defaults also differ between products. Always read the documentation of the database you use.
VisualizerTwo transactions, five problems, four levelsPick a problem and a level, then step through the two overlapping transactions. Click any cell in the table to jump to it.
Problem to try
Isolation level
Can it happen?Read uncommittedRead committedRepeatable readSerializable
Dirty read
Non-repeatable read
Phantom read
Lost update
Write skew
Transaction T1
SELECT balance β†’ 100
Transaction T2
Database: committed: 100
Step 1 of 4
T1 reads the balance
T1 sees 100 and keeps working.
At Read committed a non-repeatable read can happen. Pick a stronger level to stop it, and expect more waiting or more retries in return.

A simplified teaching model. The first three rows follow the SQL standard table. Lost update and write skew are not in that table, so they show typical behaviour. Real databases differ: for example PostgreSQL never shows dirty reads and its repeatable read also stops phantoms, but it still allows write skew. Check your database documentation.

07How to Use It / Steps / Implementation

Choosing and using a level

  1. 1
    Start with the database default
    Most databases default to read committed or repeatable read. Know which one yours uses before you write code that depends on it.
  2. 2
    List the risky rules
    Find places where you read, decide, then write: stock checks, balances, uniqueness, β€œat least one” rules. These are where anomalies hurt.
  3. 3
    Raise the level only where needed
    Use a stronger level for the few transactions that need it, not for the whole system.
  4. 4
    Or lock exactly what you need
    SELECT ... FOR UPDATE locks the rows you read, which stops lost updates without raising the level for everything.
  5. 5
    Or use a version check
    UPDATE ... WHERE version = ? only succeeds if nobody changed the row since you read it. Retry if it affects zero rows.
  6. 6
    Retry aborted transactions
    At serializable (or on a deadlock) the database may abort you on purpose. Wrap the transaction in a retry loop with a short back-off.
  7. 7
    Keep transactions short
    Long transactions hold locks and old snapshots for longer, and cause more waiting and more clashes. Never wait for a user inside a transaction.
πŸ’‘Let the database enforce the rule
Constraints (unique, foreign key, check) are safe at any level for the rules they can express. Use them first, and use higher isolation only for rules a constraint cannot express.
⚠️Across several databases
Isolation only covers one database. Across services you need other tools, such as sagas and idempotent calls.

08Key Terms to Know

TermMeaning in easy words
IsolationHow much concurrent transactions can see of each other
AnomalyA wrong-looking result that overlapping transactions can cause
Dirty readReading data that another transaction has not committed
Non-repeatable readReading the same row twice and getting different values
Phantom readRunning the same range query twice and getting different rows
Lost updateTwo writers overwrite each other, so one change vanishes
Write skewTwo transactions each pass a check, then together break the rule
SnapshotA consistent view of the data as it was at one moment
SerializableThe result is as if transactions ran one after another
Abort / retryThe database cancels a transaction, and you run it again
DeadlockTwo transactions each wait for a lock the other holds

09Pros, Cons and Trade-offs

βœ… Pros
  • Lets you trade speed for safety per use case
  • Stronger levels remove whole classes of bugs
  • Snapshot reads avoid blocking readers
  • Built into every major SQL database
  • Makes concurrency rules explicit
⚠️ Cons
  • Stronger levels mean more waiting or more aborts
  • Names and behaviour differ between databases
  • Weak levels hide bugs that appear only under load
  • Serializable needs retry logic in your code
  • Hard to test, because bugs depend on timing

Trade-offs

ChoiceWe gainWe lose
Read committedSpeed, simple and common defaultNon-repeatable reads, phantoms, lost updates unless you add locks
Repeatable read / snapshotA stable view inside a transactionWrite skew can still happen, and old versions use space
SerializableThe strongest safety, simple to reason aboutMore blocking or aborts, lower throughput
Explicit row locksPrecise control where you need itWaiting, and deadlocks if you lock in different orders
Optimistic version checkNo locks held, good when clashes are rareRetries when clashes are common
One big transactionEverything is all-or-nothingLong locks and more conflicts

10Common Problems and Mistakes

Common mistakes

  1. Assuming the default is enough. Read committed allows lost updates and non-repeatable reads, and many teams never notice until load rises.
  2. Read, decide, write without a guard. This pattern is the root of lost updates and write skew.
  3. Using the highest level everywhere. Throughput drops and retries pile up.
  4. No retry loop. Serializable and deadlock aborts are normal. Without a retry, they become user-visible errors.
  5. Long transactions. They hold locks and snapshots, and increase conflicts for everyone.
  6. Copying advice between databases. What "repeatable read" means in one product is not what it means in another.
  7. Testing only one request at a time. These bugs need two requests overlapping, so single-user tests never find them.

Things to watch

πŸ’€Deadlocks
Two transactions wait for each other. Lock in a fixed order and set timeouts.
πŸ”Retry storms
Many aborts can cause many retries at once. Add back-off and jitter.
🐌Long-running reads
A long snapshot keeps old row versions alive and bloats storage.
πŸ§ͺHidden skew
Rules that span rows are easy to forget. Review each one for write skew.

11Real-World Examples

🐘PostgreSQL
Uses snapshots for its levels, and can offer a serializable mode that aborts dangerous overlaps so you must retry.
🐬MySQL (InnoDB)
Uses snapshots and locks, and a different default level from PostgreSQL.
🏦Money transfers
A transfer debits one account and credits another inside one transaction, with a lock or version check on the balances.
🎫Ticketing
The last seat is protected with a row lock or a unique constraint.
🌍Distributed SQL
Systems such as Spanner-style databases offer strong isolation across machines, and pay in latency.
πŸ“ŠReporting on a live system
Reports run on snapshots so they can read for minutes without blocking writers.
πŸ“Note
Defaults and details change between versions. Treat this page as the concepts, and the documentation as the facts for your database.
Mini case: the last concert ticket
πŸ‘€Buyer 1
πŸ‘€Buyer 2
→↓both read: 1 left
πŸ”’Lock or version check
→↓one wins
βœ…Buyer 1 gets it
↩️Buyer 2 retries, sees 0
A lock or a version check turns a lost update into a safe retry.

12Related Topics to Read Next

ACID Transactions→

Isolation is the I in ACID.

Locking and MVCC→

The two main ways databases deliver isolation.

Relational Databases→

Where isolation levels are most used.

Write-Ahead Log (WAL)β†’

How durability works while transactions overlap.

BASE and PACELC→

What many systems choose instead of strict isolation.

The Problem with Distributed Transactions→

Isolation is much harder across several databases.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: how much overlapping transactions can see of each other (the I in ACID).
  • βœ”Levels: read uncommitted, read committed, repeatable read, serializable.
  • βœ”Problems: dirty read, non-repeatable read, phantom, lost update, write skew.
  • βœ”Standard table: each level up prevents one more of dirty, non-repeatable and phantom.
  • βœ”Snapshots: a stable view per transaction, but write skew can still happen.
  • βœ”Cost: stronger means more blocking or aborts, so always add a retry loop.
  • βœ”Cheap fixes: atomic UPDATE, SELECT FOR UPDATE, version column, constraints.
  • βœ”One line: "Choose the weakest level that still keeps your rules true."
← Previous
LSM Trees
Next β†’
Locking and MVCC