01. THE DOUBLE-BUY PROTECTION

Race Condition in Inventory

The Setup

Imagine your e-commerce platform is launching a limited-edition drop. You have exactly 1 unit left in the warehouse. Your database reflects this: stock = 1.

The Incident

At exactly 12:00:00.001 PM, two separate customers, Alice and Bob, click the "Place Order" button at the exact same millisecond.

Thread A:

Reads the database. Database says, "Yes, we have 1 item."

Thread B:

Reads a microsecond later. Database still says, "Yes, we have 1 item."

Execution:

Alice updates stock to 0. Bob updates stock to 0. Both receive success!

The Aftermath

The database shows stock = 0. To the system, everything looks fine. However, you have two successful orders and only one physical item to ship. This is a Race Condition.

The Technical Challenge

In a high-concurrency environment, the Application Layer cannot be trusted to manage stock counts using the standard "Read-Modify-Save" pattern.

Your Mission:

Move the decision-making to the Database Layer as a single, unbreakable Atomic Action.

Key Terminology

Race ConditionOutcome depends on the timing of unpredictable threads.
AtomicityAn operation that happens completely or not at all.
Data IntegrityEnsuring DB "truth" matches warehouse reality.
InventoryService.java
1// ❌ VULNERABLE CODE (The "Double Buy" Bug)
2public void checkout(Long id, int qty) {
3 Product product = repository.findById(id).get(); // Read
4
5 if (product.getStock() >= qty) {
6 product.setStock(product.getStock() - qty); // Modify
7 repository.save(product); // Save
8 }
9}
10// Problem: Between 'Read' and 'Save', another thread
11// can change the data!
Simulation Console

> Status: System Ready

> Strategy: vulnerable

Awaiting execution trigger.
Success Rate0%

Requests

5,000

Lost Sales

0