Race condition

In software, a race condition is a defect in which the result depends on the timing or order of events the code does not control, such as which of two requests finishes first. The same code with the same inputs can be right on one run and wrong on the next, because the order changed.

The longer version

MITRE's Common Weakness Enumeration files the race condition as CWE-362, under the full name Concurrent Execution using Shared Resource with Improper Synchronization. Its description is of a code sequence that needs temporary, exclusive access to a shared resource while "a timing window exists in which the shared resource can be modified by another code sequence operating concurrently". Two ingredients make one: something shared, such as a variable, a database row, a file or a part of the screen, and two pieces of work that can reach it in either order. When the code is correct for only one of those orders, the other order is the bug.

Web applications produce races with no threads in sight, because every network request takes an unpredictable time. A search box sends a request for "red" and then one for "red shoes". If the first response comes back last, the page shows results for "red" under a box that says "red shoes". A customer taps Pay twice before the first response arrives, and two orders are created. On the server, two requests read a stock level of one, both find the item available and both sell it. In that last case the code checks a value and then acts on it, and the value changes in between.

A race is hard to reproduce because the losing order may need a slow network, a busy server or a mid-range phone before it appears. On a developer's laptop, talking to a local server, the first request always wins and the fault never shows. Adding a log line or opening the developer tools shifts the timing again, which is how a race turns into a heisenbug. What helps is the sequence itself: which requests were sent, in what order they were answered and what the user did in between. The fix is to make the order irrelevant, by ignoring or cancelling a response that is no longer the latest, disabling a button while its request is in flight and having the server treat a repeated submission as one.

Most races take one of a few recognisable shapes, and GeeksforGeeks names five: read-modify-write, check-then-act, initialisation, visibility and order violation. Read-modify-write is the lost update. Two threads, or two requests, read a counter of 10, each adds one and each writes back 11, so one increment disappears. Check-then-act is the stock example above, and in security work it is called time of check to time of use (TOCTOU). Vaadata's penetration testers describe exploiting it by sending many requests in the same instant, for example to redeem a single-use discount code several times before the application records that it has been used. The database is where most of these meet in a web product, because every request that touches the same row is a concurrent timeline, whether or not the code ever mentions a thread.

Common questions

What is a race condition in simple terms?

A race condition is a bug in which two operations run at nearly the same moment and the outcome depends on which one finishes first. When the code handles only one of the two orders, the other order gives a wrong result, and it may appear once in many runs.

What is an example of a race condition in a web application?

One example is a search box that sends a request on every keystroke. When the answer to an earlier, shorter query arrives after the answer to the later one, the page shows stale results. A form submitted twice by a double click, creating two records, is another.

Why is a race condition hard to reproduce?

The failing order of events depends on timing that changes from run to run: network latency, server load and the speed of the device. A developer on a fast machine and a local network may never see the slow response that triggers the fault, and a debugger or extra logging changes the timing once more.

What is the difference between a race condition and a heisenbug?

A race condition is a cause: code whose result depends on timing nobody controls. A heisenbug is a symptom: a bug that changes or vanishes when someone tries to observe it. A race can produce a heisenbug, because observing a program alters its timing, but a race can also fail in plain view on every slow connection.

How do you prevent a race condition?

Prevention means removing the dependence on order. In a browser that can mean cancelling or ignoring responses that are no longer current and disabling a control while its request is pending. On a server it means making the check and the action a single step, with a transaction, a lock or a unique constraint, so that a second request cannot slip between them.

What are the types of race conditions?

Common types are read-modify-write, where two updates overwrite each other and one is lost; check-then-act, where a condition changes between the check and the action that relies on it; order violation, where one step runs before another it depends on; and visibility races, where one thread does not see a value another has written. Time of check to time of use (TOCTOU) is the security name for check-then-act.

What is a race condition in a database?

A database race happens when two transactions read and write the same rows at overlapping times and the result depends on which commits first. Two orders that both read a stock level of one and both sell the item are the classic case. A row lock, a conditional update that checks the value in the same statement, a unique constraint or a stricter isolation level turns the check and the write into one step.

Is a race condition a security vulnerability?

A race condition becomes a vulnerability when the check it slips past is a security or business rule. MITRE catalogues it as CWE-362, and attackers exploit it by firing many requests at once, for instance to redeem a single-use voucher twice or to withdraw the same balance twice before the application records the first attempt.

How do you fix a race condition in Java?

Java offers several tools. A synchronized method or block lets one thread at a time into the critical section, an explicit Lock does the same with more control, and atomic classes such as AtomicInteger make an operation like an increment indivisible. The volatile keyword makes a write visible to other threads but does not make a compound action such as counter++ atomic.

Bug reports that arrive ready to triage.

Collect replay, console, network and browser context with the Free plan.

<script src="…/widget.js" data-key="pb_pub_…">