A race condition is a bug where the result depends on timing: two things run at once, both touch the same data, and whoever gets there first decides what happens. The code is often correct line by line, which is why these bugs get through code review and tests, then turn up in production under load.
What makes it a race
Three ingredients have to be present together:
- Concurrency: two or more pieces of work overlap in time. They might be threads in one program, two web requests handled by different servers, or two background workers.
- Shared state: they read and write the same thing, such as a variable, a database row, a file or a cache key.
- At least one write: if everyone only reads, the order doesn't matter.
Take away any one of the three and the race goes away.
The order the steps run in is called an interleaving. With two requests of three steps each, there are many possible interleavings, and most of them are fine. The bug lives in the few that aren't, which is why the same code can work a thousand times and fail on the next run.
Check, then act
The most common shape is 'check, then act': read a value, decide something from it, then write. Selling the last item in a shop is the classic case.
- Request A reads the stock: 1 left.
- Request B reads the stock: still 1, because A hasn't written yet.
- A sells the item and sets the stock to 0.
- B, trusting the 1 it read earlier, sells the same item and also sets the stock to 0.
The stock ends at 0, which looks right, but two customers have paid for one item. Nothing crashed and no error was logged. Here is that interleaving step by step:
Two requests selling the last item
Step 1 of 5: Request A reads the stock and sees one item left.
Wondering how this was made? How we make these