Lost Update Interview: Wallet Balance Wrong Under Load

Two requests read the same balance and both write. Fix the lost update with an atomic UPDATE, SELECT … FOR UPDATE or a version check.

In this chapter

Interview: wallet balance is wrong under load

More on Ticket interviews

Keep learning

Overview

SELECT balance → 100 Snapshot read. No lock. Also reads 100. App computed 100 − 30. Waits for A’s row lock… … then writes 50 B overwrites A. The −30 is lost. Balance 50, should be 20. Two charges succeeded, one was erased. REPEATABLE READ did not prevent it. Read and write in one statement, on the latest row. Waits for A’s row lock. COMMIT → 70 A done. reads latest 70 → writes 20 An UPDATE always works on the newest committed version, not B’s snapshot. COMMIT → 20 Balance 20. The database does the arithmetic on the current value. The WHERE guard also prevents going negative. SELECT balance FOR UPDATE → 100 Locking read: X lock on the row. SELECT balance FOR UPDATE Blocks until A commits. A releases the lock. → reads 70 (latest) A locking read sees the latest committed value. Balance 20. Correct, at the cost of holding a lock while the app thinks. Keep that gap tiny. SELECT balance, version → 100, v5 Plain read. UPDATE … SET balance=70, version=6 WHERE version=5 → 1 row A wins. UPDATE … WHERE version=5 → 0 rows Version moved. B knows its read is stale. retry: read 70, v6 → write 20, v7 Correct after one retry. Read, then write Atomic UPDATE SELECT … FOR UPDATE Version column Balance 100. Two charges at once: −30 and −50. Charge A (−30) Charge B (−50) Play step 1 Next step Show all = script.beats.length ? ( Dirty read Non-repeatable read Phantom (plain SELECT) ✓ snapshot Lost update (read → write) ✓ (locks) Write skew

Wallet balance is wrong under load

The code uses a transaction at REPEATABLE READ, and money still disappears. Why, and how do you fix it? lost update snapshot vs locking read isolation anomalies optimistic locking write skew Two charges succeed, but the balance drops only once.

Customers charged twice, but balance only dropped once

312 wallets: charges add up to more than the balance drop. Each time, one user paid from two devices within a second. The code already uses a transaction. bad wallets REPEATABLE READ money missing Restated: two charges read the same balance. The second write erases the first.

The charge code

Read, compute in the app, write back an absolute value.

Why doesn’t the transaction protect it?

Is there a transaction? read charge.ts Yes. So the question is what it locks. Does the SELECT take a lock? InnoDB rules No. A plain SELECT reads a snapshot. Both read 100 without waiting. What does the UPDATE write? look at line 5 A fixed number from a stale read. The second write overwrites the first. Does REPEATABLE READ stop this? isolation table No. It gives a stable snapshot. It does not detect lost updates. Plain SELECT Reads an old snapshot. Takes no lock. Both charges see 100. UPDATE / FOR UPDATE Locks the row. Reads the newest committed value.

One statement, guarded

The database does the maths on the newest value, under a lock. The WHERE clause is the balance check. No gap to race in. CHECK constraint is a second safety net. The parallel test proves the rule holds.

No AI from here

Which anomalies does each isolation level prevent in InnoDB? READ UNCOMMITTED READ COMMITTED REPEATABLE READ Only SERIALIZABLE stops lost updates and write skew in InnoDB. REPEATABLE READ gives a stable snapshot. Next-key locks (row + gap locks) block most phantoms. For lost updates, use FOR UPDATE, an atomic UPDATE, or SERIALIZABLE. SERIALIZABLE makes reads take shared locks: more waiting, more deadlocks. RR ≠ no lost updates cost of SERIALIZABLE A plain SELECT reads a snapshot. What does the UPDATE read? The newest committed row, under a lock — not the snapshot. UPDATE, DELETE and FOR UPDATE are all locking reads. So “balance − 30” uses the newest value. That is why the atomic UPDATE works. Snapshot SELECT plus absolute UPDATE mixes two versions of the row. consistent read vs current read Snapshot from when the transaction began. No lock. consistent read UPDATE · DELETE · FOR UPDATE Latest committed row. Locked. current read What is write skew? Give an example. Two transactions each pass a check, write different rows, and together break the rule. Example: “one doctor must be on call”. Both see 2, both leave. Now 0. No row was overwritten, so locks on written rows do not help. Fix: FOR UPDATE on the rows the rule reads, a constraint, or SERIALIZABLE. different rows written lock what the rule reads Dr. Alice Dr. Bob on call COUNT on call → 2 OK to leave rule broken Different rows, no overwrite, and still a broken rule. How does PostgreSQL behave differently here? PostgreSQL errors out instead of silently losing the update. Its REPEATABLE READ fails if the row changed after your snapshot. The error is “could not serialize access”. The app retries. Its SERIALIZABLE (SSI, conflict tracking) also catches write skew. MySQL RR Second UPDATE waits, then overwrites. Money lost quietly. PostgreSQL RR Second UPDATE fails. App retries with fresh data. Optimistic or pessimistic locking? Pessimistic (FOR UPDATE): lock first. Good for common conflicts and tiny gaps. Optimistic (version column): no lock, detect at write, retry. Good for rare conflicts. conflict rate length of the gap Lock, then work. Others wait. Work, then check version. Loser retries.

Fix it across the whole codebase

What do you change? Atomic guarded UPDATEs Correct at the default level, with short locks. Each read-modify-write must be rewritten. Deadlock risk Set SERIALIZABLE globally Fixes everything, but every read now takes a shared lock. Expect waits and deadlocks everywhere. SELECT … FOR UPDATE everywhere Correct and explicit. Easy to forget on one path, and locks are held during app code. Redis lock per user

Did you show these?

Called it a lost update Snapshot vs locking reads InnoDB RR does not stop lost updates Atomic guarded UPDATE + affected rows Write skew, with an example Optimistic vs pessimistic How PostgreSQL differs

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.