Writing API Tests That Catch Race Conditions Early
Race conditions are the kind of bug that makes teams distrust their own test suites. The test passes a hundred times in a row, then fails once in CI with no obvious cause, and everyone shrugs and reruns it. That's the tell. When a failure is intermittent and timing-dependent, you're almost certainly looking at a concurrency problem — and the instinct to "just retry it" is exactly the wrong response. I've seen teams spend days chasing what turned out to be a shared counter, a non-atomic read-modify-write on a balance field, or a status transition that two requests could trigger simultaneously. The bug was always there; the tests just weren't designed to find it.
The hard truth about race conditions in APIs is that sequential tests — one request, wait for response, assert, repeat — will almost never surface them. By definition, a race condition requires two or more operations to overlap in time. If your test suite fires requests one at a time, you're only testing the happy path through a single thread of execution. That's necessary but not sufficient. To catch these bugs early, you need to deliberately introduce concurrency into your test design, and you need to assert on the outcomes that should be impossible if the API is correct.
This article walks through the patterns I reach for when I want a test suite to actively hunt race conditions rather than accidentally stumble across them. The techniques aren't exotic — they use Python's standard concurrency primitives and the same requests-based patterns you're probably already using. What changes is the intent behind the test design and the specific assertions you write.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Designing Concurrent Request Patterns That Actually Stress the API
The first thing to get right is how you fire concurrent requests. Python's threading module and concurrent.futures.ThreadPoolExecutor are both practical choices. I prefer ThreadPoolExecutor for test code because it gives you a clean way to collect results and exceptions without managing thread lifecycle manually. The key technique is a barrier — you want all threads to be ready before any of them fires, so you're actually testing simultaneous access rather than rapid sequential access.
import threading
import concurrent.futures
import requests
BASE_URL = "https://api.example.com"
def claim_voucher(voucher_id, user_id, barrier):
barrier.wait() # all threads block here until every one is ready
response = requests.post(
f"{BASE_URL}/vouchers/{voucher_id}/claim",
json={"user_id": user_id},
)
return response.status_code, response.json()
def test_voucher_can_only_be_claimed_once():
voucher_id = "VOUCHER-001"
num_concurrent = 10
barrier = threading.Barrier(num_concurrent)
with concurrent.futures.ThreadPoolExecutor(max_workers=num_concurrent) as executor:
futures = [
executor.submit(claim_voucher, voucher_id, f"user-{i}", barrier)
for i in range(num_concurrent)
]
results = [f.result() for f in concurrent.futures.as_completed(futures)]
status_codes = [r[0] for r in results]
success_count = status_codes.count(200)
conflict_count = status_codes.count(409)
assert success_count == 1, f"Expected exactly 1 successful claim, got {success_count}"
assert conflict_count == num_concurrent - 1, (
f"Expected {num_concurrent - 1} conflicts, got {conflict_count}"
)
The threading.Barrier is the detail that matters most here. Without it, your threads start at slightly different times and the "race" never actually happens — the first request completes before the second one even connects. With the barrier, all ten threads are sitting at the starting line together, and the claim endpoint has to handle genuinely simultaneous requests. If the API uses a database-level lock or an atomic compare-and-swap, one request wins and the rest get a 409 Conflict. If it doesn't, you'll see two or more 200 OK responses — and that's your bug.
This same pattern applies to any operation that should be idempotent under concurrency: inventory decrements, seat reservations, token generation, account creation with a unique email. The assertion shape is always the same — you're counting outcomes and verifying that exactly one succeeded. If you're dealing with order-of-operations bugs more broadly, the barrier pattern generalizes well there too, since many of those bugs are really just race conditions wearing a different hat.
Asserting on Invariants, Not Just Status Codes, After a Concurrent Run
Status codes tell you what the API said it did. Invariant checks tell you whether the system state is actually consistent afterward. These are different things, and in race condition testing, the second one is where the real signal lives. I've seen APIs return the right status codes during a concurrent run and still end up with corrupted state — a balance that was debited twice, a counter that incremented only once when it should have incremented ten times, or a record that exists in two conflicting states simultaneously.
After any concurrent test run, add a follow-up request to read the authoritative state and assert against it:
def test_concurrent_inventory_decrement_stays_consistent():
product_id = "PROD-42"
initial_stock = 10
num_concurrent = 10 # attempt to purchase all 10 units simultaneously
barrier = threading.Barrier(num_concurrent)
def purchase(barrier):
barrier.wait()
return requests.post(
f"{BASE_URL}/products/{product_id}/purchase",
json={"quantity": 1},
)
with concurrent.futures.ThreadPoolExecutor(max_workers=num_concurrent) as executor:
futures = [executor.submit(purchase, barrier) for _ in range(num_concurrent)]
responses = [f.result() for f in concurrent.futures.as_completed(futures)]
success_count = sum(1 for r in responses if r.status_code == 200)
# Now verify the actual state matches what the API reported
stock_response = requests.get(f"{BASE_URL}/products/{product_id}")
assert stock_response.status_code == 200
remaining_stock = stock_response.json()["stock"]
assert remaining_stock == initial_stock - success_count, (
f"Stock inconsistency: {success_count} purchases reported success "
f"but stock went from {initial_stock} to {remaining_stock}"
)
assert remaining_stock >= 0, "Stock went negative — oversell race condition detected"
The second assertion — remaining_stock >= 0 — is the one that catches the classic oversell bug. If the API isn't using optimistic locking or a proper atomic decrement, you'll end up with negative stock even though every individual purchase response looked fine. That's a real production failure mode, and sequential tests will never find it.
One thing worth noting: if your test environment uses a shared database, these tests can interfere with each other if they run in parallel. I scope concurrent race condition tests to isolated resources — a dedicated test voucher ID, a product seeded fresh per test run — so that two concurrent test suites don't accidentally race each other. This is also why good logging matters; when a concurrent test fails, you need enough context to reconstruct what happened. Clear, structured output from your test run is what separates a debuggable failure from a mystery. If your logging setup isn't already giving you that, it's worth investing in better logging practices for failed API tests before you start writing concurrency tests at scale.
Integrating Race Condition Tests Into CI Without Making Your Pipeline Flaky
Here's the tension: race condition tests are inherently probabilistic. Whether a race fires depends on thread scheduling, network latency, and database load — all of which vary between your laptop, your CI runner, and production. If you write a test that only catches the bug 30% of the time, you've built a flaky test, not a safety net. The goal is to design tests that are reliably sensitive to the bug, not just occasionally sensitive.
A few practices that help:
- Run the concurrent scenario multiple times within a single test. If one concurrent burst has a 40% chance of catching the bug, three bursts in the same test get you to roughly 78%. Use a loop, reset state between iterations, and fail if any iteration shows the invariant violation.
- Keep the concurrency level proportional to what the environment can handle. Ten threads on a CI runner with a shared database is usually fine. A hundred threads might just cause timeouts that mask the real assertion. Start modest and tune up if the environment supports it.
- Tag these tests and run them deliberately. In pytest, mark them with something like
@pytest.mark.concurrencyand run them as a separate stage in CI — after unit and integration tests pass, but before deployment to staging. This keeps them from slowing down your fast feedback loop while still catching the bugs before they ship.
# pytest.ini or pyproject.toml
[pytest]
markers =
concurrency: marks tests that fire concurrent requests to detect race conditions
# Run only concurrency tests in a dedicated CI stage
# pytest -m concurrency --tb=short -v
It's also worth being deliberate about what you're testing vs. what you're load-testing. Race condition tests are about correctness under concurrency — did the API maintain its invariants? Load tests are about performance under volume. They overlap but they're not the same. A race condition test with ten threads that runs in two seconds belongs in your test suite. A sustained load test with five hundred virtual users belongs in a performance testing tool. Conflating them produces tests that are slow, environment-dependent, and hard to maintain.
Finally, if you're writing these tests for an API you're still learning, it helps to map out the operations that share mutable state before you write a single line of test code. Any endpoint that reads a value and then writes it back — balance updates, counter increments, status transitions, reservation holds — is a candidate. That mapping exercise is also a good time to check whether the API's documented behavior actually specifies what should happen under concurrency; a lot of APIs don't, and that gap is itself a finding worth raising. When you're working through chained request dependencies, you'll often find the same endpoints that create ordering bugs are the same ones vulnerable to race conditions — they're two symptoms of the same underlying design pressure.