DHRUVANG Created with Sketch.
Published on

How Amazon Prevents Double-Selling: Row-Level Locking

Ever wondered how Amazon doesn't sell the same "last item" to two people at once? 🛒

I’ve been diving into ACID properties and Isolation in database transactions using Prisma and PostgreSQL, and it’s fascinating.

Imagine two users, Alice and Bob, clicking "Buy" on the very last iPhone at the exact same millisecond. Without proper isolation, the system might see "Stock: 1" for both, process both orders, and leave you with one very angry customer (and a duplicate inventory error).


How Do We Fix This? Row-Level Locking 🔒

Using Prisma’s Interactive Transactions, we can ensure that when Alice starts her purchase:

  1. The database locks that specific row: Using a query equivalent to SELECT FOR UPDATE.
  2. Bob’s request is told to wait in line: Bob's transaction blocks and waits for Alice's lock to clear.
  3. Release lock on completion: Once Alice’s order is confirmed and stock hits 0, her transaction commits, and the lock is released.
  4. Bob sees updated state: Bob finally gets access, reads "Stock: 0," and the system gracefully handles the "Out of stock" error.

Key Takeaways

  • Atomicity: It’s all or nothing. No half-finished orders.
  • Isolation: Transactions don’t trip over each other or read dirty states.
  • Prisma $transaction: Makes complex locking logic readable, manageable, and type-safe.

Understanding the difference between "Physical" vs "Logical" schemas is one thing, but seeing how they handle real-world concurrent collisions is where the database magic really happens!

#WebDevelopment #Backend #CodingTips #SoftwareEngineering #SystemDesign