Dealing with Contention
🔒 Contention occurs when multiple processes compete for the same resource simultaneously. This could be booking the last concert ticket, bidding on an auction item, or any similar scenario. Without proper handling, you get race conditions, double-bookings, and inconsistent state. This pattern walks you through solutions from simple database transactions to more complex distributed coordination, showing when optimistic concurrency beats pessimistic locking and how to scale beyond single-node constraints.
The Problem​
Consider buying concert tickets online. There's 1 seat left for The Weeknd concert. Alice and Bob both want this last seat and click "Buy Now" at exactly the same moment. Without proper coordination, here's what happens:
- Alice's request reads: "1 seat available"
- Bob's request reads: "1 seat available" (both reads happen before either write)
- Alice's request checks if 1 ≥ 1 (yes, there is a seat available), proceeds to payment
- Bob's request checks if 1 ≥ 1 (yes, there is a seat available), proceeds to payment
- Alice gets charged $500, seat count decremented to 0
- Bob gets charged $500, seat count decremented to -1
Both Alice and Bob receive confirmation emails with the exact same seat number. They both show up to the concert thinking they own Row 5, Seat 12. One of them is getting kicked out, and the venue has to issue a refund while dealing with two very angry customers.