High-Concurrency Inventory Deduction: Preventing Overselling in Practice
This article examines how to build an inventory deduction system that avoids both overselling and underselling under high concurrency. Using a "sold out while supplies last" scenario as a reference, it covers defining the single source of truth, setting the atomic boundary for deduction, explaining inventory states to users, and the pitfalls of single-layer database updates. It then presents a layered design with cache pre-deduction and asynchronous persistence, discusses balancing consistency against underselling, and lists observability metrics and load-testing recommendations.}
1. Why Inventory Systems Are Hard: The “While Supplies Last” Problem
A recent public response about whether a railway customer service platform would discontinue low-priced meals sparked discussion. The core message was that different trains offer meals at different price points on a “while supplies last” basis, and that low-priced options are not being uniformly removed; if an item shows as sold out, passengers can ask on-site whether other low-priced choices remain.
From a technical perspective, this is a textbook high-concurrency inventory problem: many SKUs, shallow stock per SKU, sudden demand spikes, and fragmented channels (an online ordering page, handheld terminals used by onboard staff, and station counters). If state is not synchronized across all of them, users get contradictory experiences: “there is clearly stock, but my order failed” or “it says sold out, yet payment went through.” Using this scenario as a model, this article discusses how to design an inventory deduction system that does not oversell, does not undersell, and remains explainable.
2. Problem Modeling: Three Questions You Must Answer
- Where is the source of truth for inventory? A database, a cache, or a specific shard? There must be exactly one.
- Where is the atomic boundary for deduction? Deduct at order creation, or only after payment succeeds?
- How are states explained externally? Sold out, reserved pending payment, and released must be understandable to both customer service and users.
Most production incidents are not algorithm errors. They come from these three points never being written down as an agreement, so each component ends up implementing its own version.
3. The Classic Single-Layer Approach and Its Pitfalls
The most direct method is to perform the deduction in the database with a single conditional update:
UPDATE stockSET remain = remain - 1, version = version + 1WHERE sku_id = #{skuId}AND remain > 0;
Checking whether the number of affected rows is 1 confirms the deduction succeeded. This combines the “check” and the “modify” into one atomic operation, avoiding the race condition of read-then-write.
There are three common pitfalls. First, putting the remain > 0 check in application code, which turns it back into read-modify-write. Second, hot rows causing row-lock queuing, which makes throughput drop sharply. Third, retrying immediately after a failure, which amplifies lock contention. In practice, limit the number of retries and add backoff.
4. A Layered Architecture: Cache Pre-Deduction Plus Asynchronous Persistence
When a meal category has only a few dozen portions but thousands of requests arrive in an instant, a single-database approach gets dragged down by lock waits. The common industry pattern is to layer the design:
- The access layer applies rate limiting and per-user deduplication to block duplicate submissions.
- The cache layer performs pre-deduction with an atomic script, acting as the first gate.
- A message queue takes over successful requests, absorbing the peak, and persists them to the database serially.
- The database serves as the final source of truth and executes the conditional final deduction.
- A reconciliation job periodically compares cache and database differences and corrects them.
Illustrative logic for cache pre-deduction:
if cached_remain is nil: load from dbresult = atomic_decr_if_positive(sku_key)if result == success: enqueue(order_task)else: return sold_out
The key point is that the cache is only an “admission ticket,” not the ledger. Every pre-deduction must have a timeout-based recovery mechanism, so that a user who orders and never pays does not create a permanent hold.
5. Balancing Consistency Against Underselling
Underselling also hurts the experience. If the cache shows stock but the database has reached zero, users run into payment failures. Mitigations include: keeping the pre-deducted amount slightly below the real stock to leave a buffer; immediately restoring the cache and raising an alert when persistence fails; and having the reconciliation job make one-way corrections based on the database, while outputting a difference report for operations to review.
It should be clear that an inventory system pursues eventual consistency, not strong real-time synchronization. External wording should match this. For example, replacing absolute statements with “currently sold out; please ask on-site whether other options are available” reduces misunderstanding.
6. Observability and Load-Testing Recommendations
Metrics that must be instrumented: deduction success rate, time to sell out, cache-to-database difference count, message backlog length, and lock wait duration. For load testing, construct a combination of “shallow stock + high concurrency + long-tail slow requests” and watch for an avalanche. Also verify that the recovery logic behaves correctly under fault injection.
7. Conclusion
“While supplies last” is a business rule; in a system it becomes an inventory consistency contract. Write down the three things clearly, the source of truth, the atomic boundary, and the state explanation, then back them with layered deduction and reconciliation. That way, during peak periods you keep the books accurate and users see a sold-out message they can understand.
