Katkat

Design an Ordering Service That Prevents the Last Item from Being Oversold

NetappSoftware Engineer · Onsite

Last 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:

  1. Users must be able to reserve the last unit of an item.
  2. The system must process payment after a successful reservation.
  3. Downstream tasks (kitchen notification) should only trigger once the purchase is finalized.

Non-Functional:

  1. Consistency: Absolutely zero overselling allowed.
  2. Availability: The system should remain responsive under high concurrent load.
  3. 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?