← Lessons

quiz vs the machine

Gold1380

System Design

Oversell Prevention

Keeping two buyers from claiming the last unit.

4 min read · core · beat Gold to climb

What oversell is

Oversell happens when concurrent requests both read the same available count, both decide stock exists, and both deduct. You sold ten units but only had nine.

Techniques

  • Atomic conditional update: deduct only where available is greater than or equal to the requested quantity, in a single statement. If zero rows change, reject.
  • Row locking: lock the inventory row, read, deduct, commit. Simple but serializes hot rows.
  • Reserved counters: increment a reserved column atomically and compare against on hand.
  • Optimistic version: read a version, write back only if the version is unchanged, retry on conflict.

Why naive code fails

A read then write in two steps leaves a window where another request slips in. The fix is to make the check and the deduction one indivisible operation so the database decides the winner.

Key idea

Prevent oversell by folding the availability check and the deduction into one atomic operation so only one concurrent request can win the last unit.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the root cause of oversell?

2. What does an atomic conditional deduct do when stock is gone?