18. Transactions, Isolation & Concurrency
Big picture: Two users clicking "Buy" on the last item, or two tabs transferring money at once โ without transactions and the right isolation, your database can silently corrupt data. This lesson teaches how databases keep concurrent requests from stepping on each other, and what to say in interviews when money or inventory is on the line.
Lesson 08 introduced ACID with a bank transfer. Lesson 11 mapped features to strong vs eventual consistency. This lesson goes deep on isolation levels, locking, race conditions, and when single-database transactions aren't enough.
Prerequisites: 08. Databases, 09. Replication & Sharding, 11. CAP & Consistency, 04. Clients, Servers & APIs (idempotency)
Read next: 19. Single Sign-On โ narrate checkout and booking with the right consistency story.
Learning goals
By the end of this lesson you will be able to:
- Explain ACID with focus on Isolation and common concurrency bugs
- Name the four classic anomalies (dirty read, non-repeatable read, phantom read, lost update)
- Compare isolation levels and know typical defaults (Postgres, MySQL)
- Choose pessimistic vs optimistic locking for inventory and seats
- Recognize deadlocks and how apps should handle them
- Combine transactions + unique constraints + idempotency keys for correctness
- Explain why distributed transactions are hard and what sagas are (awareness)
Why "just use a transaction" isn't always enough
A transaction guarantees atomicity (all-or-nothing) and durability (survives crash). But many requests can run transactions at the same time. Isolation defines how much one transaction sees of another's in-progress work.
Lost update โ the classic interview bug:
Inventory: 1 item left
Tab A Tab B
READ stock = 1 READ stock = 1
WRITE stock = 0 โ WRITE stock = 0 โ
Result: 2 orders, 1 item โ oversold
Both reads saw 1. Neither update knew about the other. You need isolation + locking (or a constraint that makes one write fail).
Interview phrase: "Checkout runs in a transaction with row-level lock โ or an atomic UPDATE โฆ WHERE quantity >= 1 โ so two concurrent buyers can't both pass."
ACID recap โ isolation is the hard one
| Letter | Meaning | One-line |
|---|---|---|
| A Atomic | All steps commit or none | Transfer debit + credit together |
| C Consistent | DB rules hold (constraints) | Balance never negative if CHECK forbids it |
| I Isolated | Concurrent txs don't corrupt each other | This lesson |
| D Durable | Committed data survives crash | WAL / replication |
Full bank-teller analogy lives in lesson 08. Here we zoom into I.
Concurrency anomalies
| Anomaly | What goes wrong | Example |
|---|---|---|
| Dirty read | Read uncommitted data from another tx | See someone else's half-finished transfer |
| Non-repeatable read | Same row reads differently in one tx | Read balance 100, other tx withdraws, read balance 80 |
| Phantom read | Same query returns new rows in one tx | SELECT available seats returns extra or missing rows |
| Lost update | Two txs overwrite each other | Two buyers both think stock was 1 |
Not every database uses identical names for every edge case โ but interviewers expect you to recognize the scenarios.
Isolation levels (SQL standard)
Higher isolation = fewer anomalies, usually more locking, retries, or latency.
| Level | Dirty read | Non-repeatable read | Phantom read | Typical use |
|---|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible | Rare; rough analytics only |
| READ COMMITTED | No | Possible | Possible | Default on many systems |
| REPEATABLE READ | No | No | Possible* | Long reports in one tx |
| SERIALIZABLE | No | No | No | Money, seats, inventory when strongest needed |
* Postgres REPEATABLE READ blocks many phantom cases via MVCC; MySQL InnoDB behavior differs slightly โ know your engine.
Defaults (awareness)
| Database | Default isolation |
|---|---|
| PostgreSQL | READ COMMITTED |
| MySQL (InnoDB) | REPEATABLE READ |
Interview phrase: "Postgres default is READ COMMITTED โ fine for many apps, but last-item checkout needs explicit locking or SERIALIZABLE for that transaction."
Choosing a level โ practical guide
| Scenario | Suggested approach |
|---|---|
| Social like counter | Atomic increment โ eventual OK (lesson 11) |
| Bank transfer | Transaction + lock account rows |
| Last ticket / last unit | SELECT โฆ FOR UPDATE or conditional UPDATE |
| Read report in one tx | REPEATABLE READ or snapshot export |
Pessimistic locking โ lock first, then act
Pessimistic: assume conflict will happen โ hold a lock so others wait or fail.
BEGIN;
SELECT quantity FROM inventory
WHERE product_id = 'sku-42'
FOR UPDATE; -- row lock until COMMIT
UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 'sku-42';
INSERT INTO order_items (...);
COMMIT;
| Pros | Cons |
|---|---|
| Prevents oversell on scarce rows | Holds connections; risk of deadlocks |
| Easy to reason about in interviews | Hot global rows become bottlenecks |
Alternative โ single atomic statement:
UPDATE inventory
SET quantity = quantity - 1
WHERE product_id = 'sku-42' AND quantity >= 1
RETURNING quantity;
-- 0 rows updated โ sold out, return 409 to client
Still run inside a transaction with order insert โ the conditional UPDATE is the critical guard.
Optimistic locking โ assume conflict is rare
Optimistic: read with a version; commit only if version unchanged.
-- read: version = 7, stock = 5
UPDATE inventory
SET quantity = quantity - 1, version = version + 1
WHERE product_id = 'sku-42' AND version = 7;
-- 0 rows updated โ someone else won; retry or return 409
| Good for | Bad for |
|---|---|
| Low contention edits (profile update) | Last seat on a sold-out show |
| Read-heavy catalog with occasional writes | Hot row pummeled by flash sale |
Interview phrase: "Optimistic locking with a version column โ retry on conflict. For the last unit of inventory I'd use pessimistic row lock or conditional UPDATE."
See also lesson 21 LLD concurrency section.
Deadlocks โ when locks wait on each other
Tx 1: lock row A โ waiting for row B
Tx 2: lock row B โ waiting for row A
โ Database detects deadlock, aborts ONE transaction
| Prevention | Handling |
|---|---|
| Lock rows in consistent order (always A before B) | Catch deadlock error, retry transaction |
| Shorter transactions | Exponential backoff on retry |
| Avoid locking multiple tables when possible | Log and alert if deadlock rate spikes |
Not the same as: application-level race without locks โ deadlocks require circular wait on locks.
Beyond the transaction: constraints and idempotency
Transactions fix concurrent correctness inside one database. Also use:
| Tool | Prevents |
|---|---|
| UNIQUE constraint | Duplicate username, duplicate idempotency key |
| CHECK constraint | Negative inventory if enforced at DB |
| Foreign key | Orphan order lines |
| Idempotency key (lesson 04) | Double charge on client retry |
CREATE UNIQUE INDEX orders_idempotency_key ON orders (idempotency_key);
BEGIN;
INSERT INTO orders (idempotency_key, ...) VALUES ('abc-123', ...);
-- duplicate key โ return existing order, no second charge
COMMIT;
Stack pattern for checkout:
1. Idempotency key dedup (API layer)
2. BEGIN transaction
3. Lock or conditional UPDATE inventory
4. INSERT order
5. COMMIT
6. Async payment with its own idempotency
Read replicas and transactions (connecting lesson 09)
A transaction on the primary is strongly consistent on that node. Reading from a replica in the same user flow can show stale data.
| Pattern | When |
|---|---|
| Writes + critical reads โ primary | Just placed order โ show confirmation |
| Reads โ replica | Public catalog, OK if 1 s stale |
| Read-your-writes | Route user to primary after write (lesson 11) |
Interview trap: "We use transactions" but all reads hit a lagging replica โ user still sees inconsistent UX.
Distributed transactions โ when one DB isn't enough
In a monolith + one Postgres, BEGIN โฆ COMMIT covers inventory + order in one shot.
In microservices (lesson 14), payment DB and inventory DB are separate โ no single ROLLBACK across both.
| Approach | Idea | Trade-off |
|---|---|---|
| 2PC (two-phase commit) | Coordinator: prepare all, then commit all | Slow, fragile โ rare in modern microservices |
| Saga | Chain of local txs + compensating steps | Charge fails โ release inventory |
| Outbox pattern | Write business row + event in same local tx | Async notify other service reliably |
Interview phrase: "Single DB โ ACID transaction. Split services โ saga with reserve/charge/compensate; idempotent steps so retries are safe."
Worked example โ flash sale, last item
Requirements: 1 unit left; huge concurrent traffic; no oversell.
1. One inventory row per SKU (hot row โ shard or queue at edge if needed)
2. Checkout API:
BEGIN;
UPDATE inventory SET qty = qty - 1
WHERE sku = X AND qty >= 1
RETURNING qty;
-- if no row โ 409 Sold out
INSERT order (...);
COMMIT;
3. Idempotency-Key on POST /checkout
4. Rate limit + queue at edge โ protect DB from tx stampede
5. Do NOT use cached inventory for purchase decisions
| Wrong | Right |
|---|---|
| Read qty in Redis, decrement in SQL later | Conditional UPDATE in one transaction on primary |
| Default isolation, read-modify-write in app | Lock or single UPDATE โฆ WHERE qty >= 1 |
| Retry payment without idempotency | Same idempotency key on retry |
For scale context, see case study 44. Flash Sale / Big Billion Days.
Worked example โ money transfer (single database)
BEGIN;
UPDATE accounts SET balance = balance - 10
WHERE id = 'A' AND balance >= 10;
UPDATE accounts SET balance = balance + 10
WHERE id = 'B';
-- if either UPDATE affects 0 rows โ ROLLBACK
COMMIT;
| Check | Why |
|---|---|
balance >= 10 on debit | Consistent + business rule in one tx |
| Both updates in one tx | Atomic โ no money vanishes mid-transfer |
| Read balance on primary after transfer | Replica lag won't show wrong balance |
Feature โ transaction pattern (quick map)
| Feature | Pattern |
|---|---|
| E-commerce checkout | Tx + conditional inventory UPDATE + idempotency |
| Seat booking | FOR UPDATE on seat row or SERIALIZABLE |
| Wallet transfer | Tx on both account rows, same DB |
| Like counter | UPDATE posts SET likes = likes + 1 โ lost likes OK |
| Cross-service checkout | Saga + outbox, not 2PC |
| Analytics rollup | Batch job, no interactive SERIALIZABLE |
Check your understanding
1. Two users buy the last item with READ COMMITTED and no locking. What happens?
Both can read quantity = 1, both decrement to 0, both insert orders โ oversold. Fix with row lock, conditional UPDATE, or stronger isolation on that transaction.
2. When prefer optimistic vs pessimistic locking?
Optimistic (version column): low contention, conflicts rare, OK to retry. Pessimistic (FOR UPDATE): scarce resources (last seat, last SKU) where retry storm is unacceptable.
3. Why can't you ROLLBACK across payment service and inventory service in one step?
Each service has its own database. There's no single transaction log spanning both unless you use distributed coordination (2PC/saga). On failure mid-flow you need compensation (release inventory) not one global ROLLBACK.
4. Transaction committed on primary but user reads replica and sees old data โ is the transaction broken?
No โ the transaction worked on the primary. Replication lag causes stale reads. Use read-your-writes routing or read from primary after write for that user session.
Common beginner mistakes
| Mistake | Better |
|---|---|
| "We use Postgres so we're safe" | Default isolation + read-modify-write still races |
| Cache inventory count for checkout | Authoritative decrement on primary in tx |
| Long transactions holding locks | Keep txs short; move email/notifications outside |
| SERIALIZABLE everywhere | Kills throughput; use only where needed |
| Ignore deadlock errors | Retry tx with backoff |
| Distributed monolith with 2PC "for simplicity" | Saga + idempotent steps |
| Idempotency only at payment, not order create | Dedup at every side-effecting step |
Recap
- Isolation controls what concurrent transactions see โ prevents lost updates and dirty reads.
- Levels: READ COMMITTED is common default; scarce resources need locks or SERIALIZABLE.
- Pessimistic = lock first; optimistic = version check on commit.
- Deadlocks happen with circular locks โ detect, abort one, retry.
- Stack transactions + UNIQUE + idempotency for checkout correctness.
- Replicas don't inherit your tx isolation on the read path โ mind lag.
- Multiple services โ sagas/outbox, not one big ROLLBACK.
Previous: 17. Authentication & Authorization
Next: 19. Single Sign-On