concurrency · race-conditions · debugging
Why race conditions are so hard to debug
Race conditions are hard to debug: each request can look correct in isolation. Drive two sign-ups to see an invariant fail between check and insert.
Step by step
Two accounts have the same handle. That cannot happen
One handle per account. A check in the signup code enforces it, and that check is correct. Yet here are two rows.
The check is right there, and it works
The code asks the table whether the handle is free. A asks, and it is. Nothing looks wrong here, and nothing will for two more attempts.
Attempt 1 of 3. A takes it, B is refused
It passes. Run the two signups one after the other and the second is always rejected. A thousand runs, a thousand correct answers.
Attempt 2 of 3. Both at once, still correct
Still passing, and this rung teaches something. Our two requests landed three milliseconds apart, which is an eternity here. We never made anything happen at once.
So how do two rows exist?
The check is correct. We have watched it work twice. And production still has two rows.
Attempt 3 of 3. This time they truly overlap
Both requests ask. Both are told yes, because at the instant each one asks it is true. Neither has done anything wrong, and the defect has already happened.
A inserts, exactly as it did before
A behaves exactly as it did in the runs that worked. Trace only A and you find a clean, defensible sequence.
B inserts too, on an answer that expired
B is still holding the yes it was given. It never asked again. Two rows, no exception, no crash, and the ticket we started with.
Now read the logs. Both requests look perfect
A logged: checked, free, inserted. B logged the same. Both stories are complete, consistent, and correct.
A log records one actor. The bug is between two
The code describes one request. The bug is a relationship between two. A relationship is written down nowhere in a description of one.
So stop asking. Let the table refuse you
A unique index does not check and then act. It decides at the write, in the one place that sees every writer. No gap, so no window.
Any answer you hold is a photograph, not a promise
Every race has this shape. You asked something shared, were told the truth, then acted after it expired. Stop hunting races and start hunting gaps.
The explanation you have been given
Every answer to this question says the same thing: a race condition is a rare timing fluke, and rare things are hard to catch. That sounds right, it is the reason everyone repeats it, and it stopped me asking for years.
But it does not survive one question. Rare compared to what?
We are about to count the possibilities, and the answer is not what anyone expects. The bug is not rare at all. The correct behaviour is the accident.
Two threads, four steps, six possible worlds
Our signup does two things: ask whether the handle is free, then take it. Call them A1 and A2 for the first request, B1 and B2 for the second.
The machine can interleave those four steps however it likes, with one rule it cannot break: A1 must happen before A2, and B1 before B2. A request cannot insert before it has checked.
That leaves exactly six possible orderings. Not thousands. Six. So let us look at all of them.
text
A1 A2 B1 B2 B checks after A took it OK
A1 B1 A2 B2 both checked first DUPLICATE
A1 B1 B2 A2 both checked first DUPLICATE
B1 A1 A2 B2 both checked first DUPLICATE
B1 A1 B2 A2 both checked first DUPLICATE
B1 B2 A1 A2 A checks after B took it OK
Four of the six produce two rows. Two thirds of everything the machine is allowed to do with this code is broken, and only the two schedules where one request finishes completely before the other starts are safe.
Read that again, because it inverts the story we opened with. This is not a rare fluke that occasionally slips through. It is the majority outcome, and you have been getting away with it.
So why does it almost always work?
Because your machine does not choose uniformly among those six. It has no reason to. A scheduler is built to finish work, not to explore possibilities, so it hands one request a slice of CPU and lets it run until something makes it stop.
On a laptop, with one user, and no load, a request usually runs from check to insert without ever being interrupted. That is schedule one, every single time.
The other five need something to interrupt A between its check and its insert. A context switch. A slow disk, a garbage collection pause, a network hop, another thirty requests competing for the same core.
Your laptop offers almost none of that. Production offers all of it, continuously. Your development machine is the most biased scheduler you own, and it is biased precisely toward the two schedules that hide the bug.
Why the logs cannot help you
When it finally happens in production, you do the sensible thing and read the logs. Here is what you find.
Request A: checked, handle free, inserted, 200 OK. Request B: checked, handle free, inserted, 200 OK.
Both stories are complete, internally consistent, and correct. Neither log contains a defect, because neither request contains one.
This is the heart of it, and it is worth being precise. A log line records what one actor did. The defect here is not something either actor did. It is the order they did it in, and an order is a relationship between two actors.
A relationship between two things is written down nowhere in a faithful description of one of them.
Which is also why reading the code fails, and why it will keep failing however carefully you read. The source describes one request. You can read it a hundred times, and every time it will be correct, because it is correct. The bug lives in a dimension the file does not have.
Why looking at it makes it go away
So you try to catch it in the act. You add a log line between the check and the insert, deploy, and wait. It never happens again.
The folklore calls this a Heisenbug and leaves it there, as though the universe were being coy. The mechanism is duller and more useful than that.
A breakpoint stops one thread entirely, so the other finishes alone and you get schedule one. A debugger changes how threads are scheduled. And on your laptop, where you are trying to reproduce it, the extra work slows both requests in the same way. They stay exactly as far apart as they always were.
Every instrument you own perturbs the one variable that decides the outcome.
The part nobody tells you: you cannot confirm a fix
This is the deepest reason these are hard, and it is not really about threads at all. It is about what debugging is.
Debugging is the scientific method on a short loop. You form a hypothesis, run an experiment, and observe the result. Everything you know how to do rests on the experiment being repeatable.
A race condition removes repeatability, and the whole method collapses with it.
You cannot bisect, because a green run proves nothing. You cannot confirm a fix, because the test passed before the fix too. Absence of failure is not evidence of correctness here — it is the default state of a broken system.
That is why these bugs get closed as "could not reproduce" and reopened four months later. Not because engineers were careless. Because the only tool anyone was taught to use had quietly stopped working, and nothing announced it.
What to actually do
Three moves, and they attack different halves of the problem. The first makes the bug impossible. The second makes it findable. The third makes it loud.
1. Make the bad schedules impossible
Every one of the four broken orderings needs the same thing: a gap between asking and acting. Delete the gap and all four disappear at once.
That is what a unique index does. It does not check and then act. It decides at the moment of the write, in the one place that sees every writer, so there is no window for anything to slip into.
python
# Two steps, and a gap between them.
if not User.exists(handle):
User.create(handle)
# One step. No gap, so no schedule
# can get between anything.
try:
User.create(handle) # UNIQUE(handle)
except UniqueViolation:
return "handle taken"
- Let the owner decide. A unique index, or
UPDATE ... SET n = n + 1. No separate question, so no gap. Cheapest and usually right, and it needs the rule to be expressible where the data lives. - Lock around both steps. Always correct. It also serialises every caller through that section, including the overwhelming majority who would never have collided, and you pay for that on every request forever.
- Compare and swap. Write only if the value is still what you read, and retry when it is not. No lock, but you must be genuinely safe to retry, and a hot key can starve.
2. Make the bad schedule inevitable
If you cannot reproduce a bug, you cannot prove you fixed it. So stop hoping for the rare schedule and force it.
Put a deliberate delay in the gap, in a test, and the schedule you could not catch becomes the only one that can happen. The bug reproduces every single run.
python
def test_two_signups_race():
def claim():
free = not User.exists("dev")
barrier.wait() # both threads
# stop here, so both
# have checked before
# either inserts
if free: User.create("dev")
run_both(claim)
assert User.count("dev") == 1
That test fails reliably before the fix and passes reliably after it. You have turned a timing bug into an ordinary one, and every debugging habit you already have works again.
This is the move most articles skip, and it is the one that actually gets the bug closed.
3. Make it loud when it happens anyway
The worst property of this bug was never the duplication. It was the silence. Two rows sat in a table for weeks looking exactly like real data, and the system that created them reported success both times.
A constraint converts that silence into an exception with a stack trace and a timestamp. Even when you keep the check, add the constraint underneath it. The check is for the user experience. The constraint is for the truth.
The idea worth keeping
Every race condition, in every language, on every stack, has one shape.
You asked something shared a question. You were told the truth. Then you acted on the answer after it had stopped being true.
An answer from a shared system is a photograph, not a promise. It tells you what was, not what is, and the gap between those two things is where every one of these bugs lives.
So the next time something will not reproduce, change the question you are asking. Stop asking what is wrong with this code, because the answer is usually nothing.
Ask instead: what would have to be true at the same time for this to happen? The first question searches one actor. The second searches the orderings, and that is where the answer has been the whole time.