Lessons / Rule 6

🏁 Two Requests at Once

Protect data when operations run simultaneously.

FreeData Integrity8 min read
Check-then-write is a lie under concurrency.

Two people, one last seat. Who gets it?

If two people grab the last concert seat at the same instant, only one can have it. The system must decide β€” not both "think" they got it.

πŸ’‘ Key ideas

  • Two requests can happen at the same moment
  • "Check then create" can both pass at once
  • The database should enforce the final rule

πŸ› οΈ How to apply it

  • Add a unique rule in the database.
  • Handle the "already exists" case gracefully.

Reading level: 🐣 Simple

"If not exists, create" β€” the classic race condition.

Assume two or more requests can execute the same operation simultaneously. Never rely on application-level check-then-create alone; it fails under concurrency.

πŸ’‘ Key ideas

  • Use unique constraints, transactions, upserts and conflict handling
  • Use locks only where justified and bounded
  • The database must enforce critical uniqueness rules wherever possible

πŸ› οΈ How to apply it

  • Push uniqueness into the schema, then translate the constraint error into a business response
  • Handle duplicate-entry recovery so retries and races converge

⚠️ Common pitfalls

  • Believing a millisecond gap protects you β€” the gap is where the race lives

Reading level: πŸš€ Standard

Concurrency bugs are invisible until exactly the wrong moment.

Lost updates, write skew, phantom reads and double-inserts arise from interleaving. The fix is to make the critical section atomic: via constraints, conditional writes, version columns or serialisable isolation.

πŸ’‘ Key ideas

  • Prefer optimistic concurrency (version/CAS) for low contention
  • Use conditional writes: UPDATE ... WHERE version = n, and check rows affected
  • Beware distributed locks: they leak and expire; make operations idempotent too

πŸ› οΈ How to apply it

  • Design the invariant, then choose the cheapest mechanism that enforces it
  • Test with real concurrent load, not just sequential unit tests

⚠️ Common pitfalls

  • Read-modify-write on a counter without atomic increment
  • Assuming a lock you acquired will be released (crashes leave it held)

Reading level: 🧠 Deep

Try it yourself

The Race for the Last Seat β€” a live simulator for this principle.

Quick check

Community

Ask a question, share your own analogy, or help someone else get it.