Skip to content
System Design Lab
Real Problems

400 Phones Sold, 100 in Stock: Race Conditions in a Flash Sale

A flash sale sold three times the available stock without a single error. The code checked stock, then saved stock − 1 — and hundreds of buyers did it at once. Reproduce it, then fix it properly.

Intermediate 4 min read· Updated 2026-11-18

What you will learn

  • Recognise check-then-act and lost-update race conditions.
  • Reproduce overselling under concurrent load.
  • Compare atomic updates, optimistic locking and reservations.
  • Pick the right fix for high-contention hot rows.

Symptoms

  • A flash sale of 100 phones ends with ~400 confirmed orders.
  • The stock column still shows units left; it never reached zero.
  • No errors, no exceptions, no deadlocks in any log.
  • In normal traffic the same code had worked for years.

System context

Flash-sale buy…Flash-sale buyersCheckoutCheckoutstock rowread → check → wr…stock row
Checkout reads the stock row, does some work, then writes the new quantity.
The bug
@Transactional
public void buy(long productId) {
    Product p = products.findById(productId).orElseThrow();   // reads qty = 7
    if (p.getQty() <= 0) throw new SoldOutException();
    pricing.applyCoupons(p);                                   // ~30 ms of other work
    p.setQty(p.getQty() - 1);                                  // writes qty = 6
    orders.create(p);
}   // 20 buyers who all read 7 all write 6 — and all get an order

Root cause

  1. Check-then-act: the check (qty > 0) and the write happen at different times. Between them, other buyers read the same value.
  2. Lost update: each buyer writes read value − 1, overwriting the decrements of everyone who read the same number.
  3. @Transactional does not help: at the default READ COMMITTED isolation two transactions may read the same row and both commit their writes.
  4. Under normal traffic, purchases of the same product rarely overlap. A flash sale makes them overlap by design.

Interactive reproduction

400 buyers arrive in about a second. Compare Units sold and Sold without stock across the three scenarios, then drag the work between read and write to zero in A: the window shrinks, but the bug does not go away.

Loading simulation…

Solution alternatives

OptionOversells?Under heavy contentionNotes
Atomic conditional UPDATENoFast — one short row lock per buyerBest default for counters and stock.
Pessimistic lock (SELECT … FOR UPDATE)NoBuyers queue on the row lockKeep the transaction short; never call other services while holding it.
Optimistic locking (@Version)NoMostly conflicts and retries; many give upGreat when conflicts are rare (editing a profile), poor for hot rows.
Reservation / queueNoSmooth: requests processed in orderReserve with expiry, confirm on payment; or put purchases on a queue per product.
SERIALIZABLE isolationNoSerialization failures to retryCorrect, but needs retry logic everywhere.

Recommended fix

Let the database do the check and the decrement in one statement
@Modifying
@Query("UPDATE Product p SET p.qty = p.qty - 1 WHERE p.id = :id AND p.qty > 0")
int decrementIfAvailable(@Param("id") long id);

@Transactional
public void buy(long productId) {
    if (products.decrementIfAvailable(productId) == 0) throw new SoldOutException();
    orders.create(productId);     // same transaction: no order without a decrement, and vice versa
}

Advanced For very hot items, even one row lock per buyer can become the bottleneck. Split stock into several rows ("buckets") and decrement any bucket with stock, or pre-load the stock into Redis and use an atomic DECR / Lua script as an admission gate before the database.

Verification strategy

  • Concurrency test: start N threads behind a latch, all buying the same product; assert orders == initial stock.
  • Run it against a real database (Testcontainers) — in-memory fakes do not reproduce isolation behaviour.
  • Add a database constraint as a last line of defence: CHECK (qty >= 0).

Monitoring and prevention

  • Reconcile orders against stock movements after every sale event.
  • Alert when stock goes negative or orders exceed stock for any product.
  • Code review rule: read-modify-write of a shared counter in application code is a red flag.

Lessons learned

  • A transaction does not make read-then-write safe by itself.
  • Push the invariant ("never below zero") into the statement or a constraint, where the database enforces it atomically.
  • Test concurrency with real concurrency; normal traffic hides races for years.

Further reading

Related topics