Skip to content
Mohammad Kazim
Colour theme

Hire me
← All posts
  • Redis
  • Python
  • Concurrency

One booking, one winner: a Redis lock

Two operators assign the same booking at the same moment. A short lock decides who goes first.

Mohammad Kazim · · 1 min read

Illustrative screen with sample content.

In AirLynk, a personal ride-booking project, an operator assigns a driver to a booking. If two requests arrive together, both can read the booking as unassigned and both can write. Checking the state first is not enough, because the check and the write are separate steps.

Set only if absent, and always expire

Redis can set a key only when it does not exist, and give it a lifetime in the same command. Whoever creates the key holds the lock. Everyone else gets a conflict and can retry.

booking_service.py
lock_key = f"lock:booking_assign:{booking_id}"

lock_acquired = await self.redis.set(lock_key, "locked", nx=True, ex=10)
if not lock_acquired:
    raise ConflictError("Booking is currently being modified")

try:
    ...  # check the state, assign the driver, publish the event
finally:
    await self.redis.delete(lock_key)
  • nx=True makes creation the contest, so there is exactly one winner.
  • ex=10 releases the lock even if the process dies halfway.
  • The state check happens inside the lock, not before it.

What I would tighten next

If the work ever outlives the ten seconds, another request can take the lock, and the first one would then delete a lock it no longer owns. The fix is to store a unique token as the value and delete the key only when the token still matches, in one atomic script. A database constraint on the final write is the second line of defence.

Related case studyAirLynk: a ride-booking backend

Keep reading