Dashboard

What Is a Race Condition? Examples and How to Fix One

A race condition is a timing bug that only appears under concurrent use. A worked overselling example shows why it slips past tests and how to fix it.

Carlo Zuercher
Carlo Zuercher
Staff Engineer, Platform
24 October 20261 min read

A race condition is a bug where the outcome of your code depends on the timing of two or more operations that run at the same time. Each step looks correct on its own, but when two requests interleave, one of them acts on information that is already out of date.

MITRE's entry for this weakness, CWE-362, describes code that needs temporary, exclusive access to a shared resource, where a timing window exists in which another concurrent code sequence can modify it.

A worked example: the last item in stock

Say your shop has one unit of a product left and the checkout code does this:

python
stock = db.get_stock(product_id)      # check
if stock > 0:
    db.set_stock(product_id, stock - 1)  # act
    create_order(product_id)

Two customers click buy within the same few milliseconds. Here is one possible timeline:

Step

Customer A

Customer B

Stock in database

1

reads stock: 1

1

2

reads stock: 1

1

3

sets stock to 0, creates order

0

4

sets stock to 0, creates order

0

Both orders went through, and you sold one item twice. No error appeared, no test failed, and the database ended up in a perfectly valid state of zero.

Why tests and demos miss it

Race conditions need concurrency to show up. A developer clicking through the app alone will never trigger step 2 landing inside step 1's window. An automated test that runs requests one after another passes every time. The bug waits until a sale, a launch or a retry storm puts real traffic on the route.

That is why it is worth knowing the pattern by name, especially when you review code you did not write yourself. The tell is a **check-then-act** sequence: read a value, decide, then write based on what you read, with nothing stopping another request in between.

The fix: make the check and the change one step

CWE-362's mitigations include using atomic operations and synchronisation, and minimising shared resources. For a typical web app, the practical version is to let the database do the check and the change in one statement:

sql
update products
set stock = stock - 1
where id = $1 and stock > 0;

Then look at how many rows changed. If the count is one, the customer got the item. If it is zero, someone else got there first and you show "sold out". The database serialises the two updates, so the second one sees the stock already at zero.

Other fixes exist, such as locking the row before you read it, or putting a unique constraint on something that must never repeat. The principle is the same: never leave a gap between deciding and doing.

Where else this pattern hides

  • Booking a time slot that someone else is booking

  • Applying a coupon that can be used once

  • Incrementing a counter by reading and writing it back

  • Paying twice because a user double-clicked, which idempotency keys address

  • Two background jobs processing the same record

If you are working through a feature like a shopping cart or low-stock alerts, the stock decrement is the place to look first.

What to ask your AI coding agent

Add this to the prompt: "Any code that reads a value and then updates it must be atomic. Use a single conditional UPDATE or a transaction with a row lock, and add a test that fires 20 simultaneous requests at the last item." Then run that concurrent test yourself. If the app oversells, you have found a race condition cheaply.

For how this fits into shipping a real product, see building an app with AI, and for query performance that makes windows shorter, see what a database index is. A faster query narrows the window but does not close it.

FAQ

What causes a race condition?

Two or more operations touch the same shared data at overlapping times, and the result depends on which finishes first.

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

In a race condition, the wrong result comes from bad timing. In a deadlock, operations wait on each other forever and nothing progresses.

Can a race condition happen in a single-user app?

Yes, for example when a user double-clicks a button or a retry fires while the first request is still running.

How do you test for a race condition?

Send many simultaneous requests at the same resource, such as 20 purchases of the last item, and check the final state.

How did this land?

About the author

Carlo Zuercher
Carlo Zuercher

Staff Engineer, Platform

Carlo works on the platform that turns prompts into running apps. He writes the engineering deep dives and the changelog notes worth reading.

Share

Get the next post in your inbox

One email a month. Product updates, engineering posts, and the best of Built with Swarmz.

I agree to receive emails about AI building tips and Swarmz product news. Unsubscribe any time.