Skip to content
Preptima
mediumCodingDesignConceptMidSenior

A flash sale decrements stock from many threads. Do you go optimistic or pessimistic, and how do you prove nothing oversold?

For one stock counter, optimistic locking with a compare-and-set loop fits: read, refuse at zero, and publish the decrement only if nobody changed the value meanwhile. A lock suits a larger critical section. Prove it by arguing each sale consumes one unit, plus a stress test seen to fail on the broken code.

5 min readUpdated 2026-10-10Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

For one stock counter, optimistic locking is the better default. A compare-and-set loop reads the count, refuses at zero, and publishes n - 1 only if the value is still n; if not, it re-reads and decides again. Pessimistic locking takes a lock, checks and decrements. It wins when the critical section covers several fields or real work. Proving no oversell needs both an argument and a stress test.

Was this answer helpful?

Likely follow-ups

  • Ten thousand threads hammer one SKU and the CAS loop burns CPU. How would you shard the stock without allowing an oversell?
  • Each buyer may take at most two units across the sale. Does a single AtomicInteger still work?
  • When can an ABA change break a compare-and-set loop, and why can a plain stock counter ignore it?
  • The in-memory count is right but the database row is not. Where does the decrement belong once there are two instances?

Related questions