Design an Ordering Service That Prevents the Last Item from Being Oversold
NetappSoftware Engineer · OnsiteLast updated
This question tests the ability to design a high-concurrency reservation system that prevents race conditions and overselling using database transactions and distributed locking strategies.
System Design: Last-Item Inventory Service
Design a backend service for a food-ordering platform that prevents the 'overselling' of the last available unit of an item (e.g., a limited-edition daily special). When multiple users attempt to purchase the final unit simultaneously, the system must ensure exactly one order succeeds while others fail gracefully.
Requirements
Functional:
- Users must be able to reserve the last unit of an item.
- The system must process payment after a successful reservation.
- Downstream tasks (kitchen notification) should only trigger once the purchase is finalized.
Non-Functional:
- Consistency: Absolutely zero overselling allowed.
- Availability: The system should remain responsive under high concurrent load.
- Latency: Reservation attempts should return a result quickly, even if many users are contending for the same item.
Expectations
Your design should cover:
- The API interface for placing an order.
- Database schema and isolation level choices for inventory tracking.
- How to handle retries and prevent double-charging if a payment service times out.
- The flow of data between the Inventory, Payment, and Order microservices.
Hints
Hint 1
Consider using database-level atomic operations or 'Compare-and-Swap' (CAS) patterns rather than application-level read-modify-write cycles.
Hint 2
Think about the difference between a 'soft reservation' (placing a temporary hold) and a 'hard commit' (finalizing the order).
Hint 3
Evaluate whether a distributed lock (e.g., Redis/Redlock) is necessary or if optimized database constraints are sufficient for the given throughput.
Follow-up questions
- How would you handle a scenario where a user successfully reserves an item but the payment service fails repeatedly?
- If the item has 1,000 units instead of just 1, how would your design change to reduce contention on the database row?
- How would you implement a 'waitlist' feature for users who attempted to purchase the last unit but failed?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.