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

LetterMeaningOne-line
A AtomicAll steps commit or noneTransfer debit + credit together
C ConsistentDB rules hold (constraints)Balance never negative if CHECK forbids it
I IsolatedConcurrent txs don't corrupt each otherThis lesson
D DurableCommitted data survives crashWAL / replication

Full bank-teller analogy lives in lesson 08. Here we zoom into I.


Concurrency anomalies

AnomalyWhat goes wrongExample
Dirty readRead uncommitted data from another txSee someone else's half-finished transfer
Non-repeatable readSame row reads differently in one txRead balance 100, other tx withdraws, read balance 80
Phantom readSame query returns new rows in one txSELECT available seats returns extra or missing rows
Lost updateTwo txs overwrite each otherTwo 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.

LevelDirty readNon-repeatable readPhantom readTypical use
READ UNCOMMITTEDPossiblePossiblePossibleRare; rough analytics only
READ COMMITTEDNoPossiblePossibleDefault on many systems
REPEATABLE READNoNoPossible*Long reports in one tx
SERIALIZABLENoNoNoMoney, seats, inventory when strongest needed

* Postgres REPEATABLE READ blocks many phantom cases via MVCC; MySQL InnoDB behavior differs slightly โ€” know your engine.

Defaults (awareness)

DatabaseDefault isolation
PostgreSQLREAD 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

ScenarioSuggested approach
Social like counterAtomic increment โ€” eventual OK (lesson 11)
Bank transferTransaction + lock account rows
Last ticket / last unitSELECT โ€ฆ FOR UPDATE or conditional UPDATE
Read report in one txREPEATABLE 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;
ProsCons
Prevents oversell on scarce rowsHolds connections; risk of deadlocks
Easy to reason about in interviewsHot 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 forBad for
Low contention edits (profile update)Last seat on a sold-out show
Read-heavy catalog with occasional writesHot 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
PreventionHandling
Lock rows in consistent order (always A before B)Catch deadlock error, retry transaction
Shorter transactionsExponential backoff on retry
Avoid locking multiple tables when possibleLog 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:

ToolPrevents
UNIQUE constraintDuplicate username, duplicate idempotency key
CHECK constraintNegative inventory if enforced at DB
Foreign keyOrphan 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.

PatternWhen
Writes + critical reads โ†’ primaryJust placed order โ€” show confirmation
Reads โ†’ replicaPublic catalog, OK if 1 s stale
Read-your-writesRoute 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.

ApproachIdeaTrade-off
2PC (two-phase commit)Coordinator: prepare all, then commit allSlow, fragile โ€” rare in modern microservices
SagaChain of local txs + compensating stepsCharge fails โ†’ release inventory
Outbox patternWrite business row + event in same local txAsync 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
WrongRight
Read qty in Redis, decrement in SQL laterConditional UPDATE in one transaction on primary
Default isolation, read-modify-write in appLock or single UPDATE โ€ฆ WHERE qty >= 1
Retry payment without idempotencySame 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;
CheckWhy
balance >= 10 on debitConsistent + business rule in one tx
Both updates in one txAtomic โ€” no money vanishes mid-transfer
Read balance on primary after transferReplica lag won't show wrong balance

Feature โ†’ transaction pattern (quick map)

FeaturePattern
E-commerce checkoutTx + conditional inventory UPDATE + idempotency
Seat bookingFOR UPDATE on seat row or SERIALIZABLE
Wallet transferTx on both account rows, same DB
Like counterUPDATE posts SET likes = likes + 1 โ€” lost likes OK
Cross-service checkoutSaga + outbox, not 2PC
Analytics rollupBatch 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

MistakeBetter
"We use Postgres so we're safe"Default isolation + read-modify-write still races
Cache inventory count for checkoutAuthoritative decrement on primary in tx
Long transactions holding locksKeep txs short; move email/notifications outside
SERIALIZABLE everywhereKills throughput; use only where needed
Ignore deadlock errorsRetry tx with backoff
Distributed monolith with 2PC "for simplicity"Saga + idempotent steps
Idempotency only at payment, not order createDedup 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