It's dinnertime. A restaurant's order pops up on the phones of every courier in the area at the same moment. Ali taps "Accept," and Ayşe does the same 25 milliseconds later. That's a gap too short for the human eye to notice. Both phones show the same message: "The order is yours." Both couriers hop on their motorbikes and head for the same restaurant.
From the software's point of view, this hardly looks like a bug; the system worked and answered both people. But for a customer, a restaurant, and two couriers, it's a real problem: one made a wasted trip, and someone was left waiting for nothing. This post explains how something like this can happen and how engineers prevent it with certainty. The most interesting part comes at the end: why even systems that use a "lock" sometimes get it wrong.
Selling the Last Seat to Two People
Imagine a bus company with two ticket counters. Two passengers, at two different counters, ask for the last empty seat at the same moment. Both clerks look at their screens: "Seat 7 is free." Both issue the ticket. The system records one name, then the other. The result: two tickets for the same seat.
The problem isn't careless clerks. The problem is the brief moment between checking "is it free?" and writing "it's taken now." If someone else checks during that moment, they see it as free, too. Engineers call this a "race condition": an outcome that depends on who acted a millisecond earlier.
We worked through this moment step by step in the courier example. Ali's request reaches the server at the 140-millisecond mark. The server asks the database: "Is this order unassigned?" The answer is yes. It takes the server 50 milliseconds to get that answer and record the assignment. Ayşe's request arrives at 160 milliseconds and asks the same question. Ali's record hasn't been written yet, so the answer is yes again. A 30-millisecond window is enough to give the same order to two people.

How Often Does This Happen?
To find out, we wrote a small simulation. Several couriers accept an order at the same time. The couriers' taps are spread randomly across a two-second window; each request's trip over the mobile network takes 150 milliseconds on average, with some variation. We then repeated the same order 100,000 times and counted how many orders were given to two or more couriers. The sample data is synthetic; the goal isn't to measure a real operation but to show how the mechanism behaves.
| Method (double assignments per 10,000 orders) | 2 couriers | 3 couriers | 5 couriers |
|---|---|---|---|
| Check first, then write (10 ms in between) | 92 | 146 | 227 |
| Check first, then write (50 ms in between) | 460 | 703 | 1,078 |
| Check first, then write (200 ms in between) | 1,838 | 2,620 | 3,911 |
| Conditional write in a single step | 0 | 0 | 0 |
The table teaches two lessons. First, the longer the gap between the check and the write, the faster the errors grow. When the system is busy, or when the server consults another service in between (to verify the courier's location, for example), that gap can easily reach 200 milliseconds. At that point, about 39 percent of orders that five couriers race for go to more than one person.
Second, small percentages produce big numbers. If we assume 1,000 orders a day end up in a three-courier race, a 50-millisecond gap means about 70 double assignments a day. Each one is a complaint call, a wasted courier trip, and a meal going cold.
Why Doesn't It Show Up in Testing?
The developer tries the feature on their own machine: they accept with one phone, and everything works. They try again with a second phone a few seconds later, and get an "order already taken" warning. The bug only appears when two requests collide within milliseconds, and that moment almost never occurs during testing.
In the simulation we forced that moment on purpose: we squeezed 50 accept requests into the same 5 milliseconds. With the "check first, then write" method, all 50 of the 50 couriers were told "the order is yours." A bug that stays silent in the field for days gets caught on the first try in a properly built test.
The Solution: Ask and Answer in a Single Move
Back to the ticket counter. The simplest way to solve the problem is, instead of telling the clerks "check first, then write," to set a single rule: put the seat in the passenger's name only if the ledger still shows it as free. Checking and writing are no longer two separate steps. The ledger puts two simultaneous requests in line; the first gets written, and when the second arrives nothing changes because the seat is taken, so the clerk says "sorry, it's sold."
In databases, this is called a "conditional update." The server doesn't ask "is this order unassigned?" as a separate question. It sends the database a single command: "Assign this order to Ali, but only if it still has no courier." The database tells it how many records it changed. If the answer is 1, the order is Ali's. If the answer is 0, someone else was faster. The PostgreSQL documentation describes this behavior explicitly: a second transaction trying to change the same row at the same time waits for the first one to finish, then rechecks the condition against the updated data.

The zeros in the last row of the table aren't luck. With a conditional update, it's logically impossible for two people to get the same order, because there's no moment left between the "is it free?" question and the "it's taken now" record for anyone else to slip into.
What About a Lock?
Sometimes the work doesn't fit into a single database command. During assignment, a route is calculated, the restaurant is notified, and the courier's balance is updated. To keep multiple servers from touching the same order at the same time, a "lock" is used: a server that wants to work on the order first takes the key, then hands it back when it's done.
If the server crashes after taking the key, the key stays with it forever. That's why distributed locks have an expiration time. Redis's official documentation recommends exactly this: the lock is taken with a key that drops on its own after, say, 30 seconds. For extra safety, it also describes a method called "Redlock," which requires acquiring the lock on at least three of five independent Redis servers.
It's a sensible-sounding design. But in 2016, distributed systems researcher Martin Kleppmann, in an article titled "How to do distributed locking," pointed out an overlooked weakness in this approach.
The Sleeping Server
Think of a hotel room key card. Your card stops working at noon. You fall asleep in the room, noon passes, and the front desk gives the room to another guest. Then you wake up and, still thinking the room is yours, start putting your things in the closet.
Servers fall asleep, too. Programs running in languages like Java periodically pause all their work to clean up memory. The network can hang for a few seconds, and a virtual machine can be suspended. Kleppmann notes that such pauses are known to last several minutes at times, and that in one outage at GitHub, network packets were delayed by about 90 seconds. The paused program isn't aware of any of this; when it wakes up, it carries on from where it left off.
We simulated this scenario step by step. The lock has a 10-second lifetime. Server A takes the lock, reads the order, and, while getting ready to assign it to Mehmet, pauses for 12 seconds. At the 10-second mark, the lock expires. Server B takes the lock and assigns the order to Ayşe. At 12.4 seconds, A wakes up and, believing it still holds the lock, writes the order to Mehmet. Ayşe was already on her way, and now Mehmet heads out, too.
The Ticket Number Idea
The solution Kleppmann proposes resembles the take-a-number machine at a bank. Every time the lock is granted, it comes with a number larger than the previous one: A gets number 33, B gets number 34. The system that stores the data asks for this number with every write request and applies one rule: if I've already seen 34, I reject a request that arrives with 33. This number is called a "fencing token."
Now it no longer matters at all what the server that wakes up believes. The decision is made by the storage system, which doesn't trust clocks or timeouts and simply compares two numbers. The Redis documentation reaches the same conclusion today: where correctness matters, it recommends using a fencing token and not assuming that a lock stays held for as long as the program that took it is alive.

Four Things That Break It in Real Life
1. "No Response" Is Not the Same as "It Didn't Happen"
Ali accepts, the server makes the assignment, but on its way back to Ali's phone the response is lost when the signal drops in an elevator. The app waits a while and resends the request. This time the server says "the order belongs to someone else," even though the order really does belong to Ali now. Ali sees an error message and lets the order go; the order sits there with nobody taking it. As Stripe's article on payment systems explains, a client can't know whether a request that timed out was processed or not. The fix is to give every accept request a unique ID and have the server recognize a repeat with the same ID and say "yes, it's already yours."
2. Double Taps on the Phone
A courier presses the button wearing gloves, on the move; when the screen doesn't react right away, they press it again. The app sends two requests. Disabling the button on the first tap is a good habit, but it isn't enough, because the network layer can also repeat requests. The real safeguard has to be on the server: a second request from the same courier for the same order must not create a second assignment.
3. Server Clocks Don't Agree
A clock decides whether a lock has expired, and no two computers' clocks are ever exactly the same. The Redis documentation states plainly that Redis doesn't use a monotonic clock for expiry, and that a server clock jumping forward can hand a lock to more than one program at the same time. Clock synchronization reduces this risk but doesn't eliminate it. Answering "who accepted the order first?" by looking at the phones' clocks is even riskier; users themselves can change those clocks.
4. Races Don't Test Themselves
As we saw above, an ordinary test almost never catches this bug. The right test fires dozens of requests at the same order simultaneously and asks a single question at the end: how many people were told "the order is yours"? If the answer is more than one, the system will make double assignments in the field, no matter how tidy it looks on paper.
Does Every Business Need This?
In systems where couriers don't pick orders themselves and a dispatcher or a single planning program makes the assignments, races are much rarer, because there's only one hand making the decision. For a small business working with a handful of couriers, a double assignment may also be a problem that gets sorted out with an occasional phone call.
But when orders are shown to many couriers at once on a "first to accept gets it" basis, the system runs on more than one server, and payment depends on the assignment, this isn't optional; it's a basic requirement. The good news is that most of the solution isn't expensive infrastructure, but a single, correctly written database command and a good test that pushes it hard. Distributed locks and ticket numbers come into play when the work truly spans more than one system.
On our Courier and delivery software page, we explain how order assignment, the courier app, and the server side are designed together.
For developers: conditional assignment with Spring Data JPA
In Spring Data JPA (the current version at the time of writing is 4.1.2), an update query is defined with @Modifying and @Query and returns the number of changed rows as an int. If the result is 0, the order went to someone else; on a repeated request, if the order's owner is already this courier, it should count as a success. The second query carries the fencing token rule into storage using the same logic.
public interface CourierOrderRepository extends JpaRepository<CourierOrder, Long> {
@Modifying
@Query("update CourierOrder o set o.courierId = ?2 where o.id = ?1 and o.courierId is null")
int assignIfFree(Long orderId, Long courierId);
@Modifying
@Query("update CourierOrder o set o.courierId = ?2, o.fenceToken = ?3 "
+ "where o.id = ?1 and o.fenceToken < ?3")
int assignWithFence(Long orderId, Long courierId, Long token);
}
Sources
- Martin Kleppmann, "How to do distributed locking," February 8, 2016: martin.kleppmann.com
- Redis documentation, "Distributed Locks with Redis": redis.io
- PostgreSQL 18 documentation, "Transaction Isolation": postgresql.org
- Brandur Leach, "Designing robust and predictable APIs with idempotency," Stripe, 2017: stripe.com/blog
- Spring Data JPA reference documentation, "Modifying Queries": docs.spring.io
Note: The courier names, timings, and double-assignment counts in this post come from a small simulation we wrote ourselves; the sample data is synthetic and does not represent a real customer's operation. The taps spread across two seconds, the 150-millisecond average network latency, and the 1,000 daily orders that end up in a race are assumptions. The 10-second lock lifetime and the 12-second pause in the lock scenario are illustrative.
Cover photo: wal_172619 / Pixabay