API Tests That Catch Race Conditions Early, Agents Included
Race conditions make teams distrust their own test suites. A test passes again and again, then fails once in CI with no obvious cause, and everyone reruns it. That's the tell. An intermittent, timing-dependent failure is very often a concurrency problem, and "just retry it" is exactly the wrong response. I've seen these turn out to be a shared counter, a read-modify-write on a balance, or a status change two requests could trigger at once. The bug was always there. The tests weren't designed to find it.
Sequential tests, one request then wait then assert, will almost never surface a race, because a race needs operations to overlap. To find these bugs early you have to introduce concurrency on purpose and assert on outcomes that should be impossible if the API is correct.
Two agent-shaped reasons make this more urgent. Coding agents fix "flaky" tests by adding retries and sleeps, which buries exactly these bugs. And AI agents that call your API can send duplicate or parallel requests when they retry a tool call. In this article I'll show the concurrency patterns I use with pytest, the invariant checks that matter, how I keep these tests stable in CI, and how I test agent-driven duplicates.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Fire requests that really overlap
I use concurrent.futures.ThreadPoolExecutor because it collects results and exceptions cleanly. The detail that matters most is a threading.Barrier: every worker waits at the starting line, then all fire together. Without it, the first request often finishes before the second one connects and the race never happens.
import threading
from concurrent.futures import ThreadPoolExecutor
import requests
def fire_together(n, call):
"""Run call(i) in n threads that all start at the same moment."""
barrier = threading.Barrier(n)
def worker(i):
barrier.wait(timeout=10)
return call(i)
with ThreadPoolExecutor(max_workers=n) as pool:
return list(pool.map(worker, range(n)))
def test_voucher_claimed_only_once(api_base_url, auth_headers, fresh_voucher):
def claim(i):
return requests.post(f"{api_base_url}/vouchers/{fresh_voucher}/claim",
json={"user_id": f"user-{i}"},
headers=auth_headers, timeout=10)
codes = [r.status_code for r in fire_together(10, claim)]
assert codes.count(200) == 1, f"Expected exactly one successful claim: {codes}"
assert codes.count(409) == 9, f"Expected the rest to conflict: {codes}"
max_workers must be at least the barrier size, or the barrier waits forever; the timeout turns that mistake into a clear error instead of a hang. I use plain requests calls per thread rather than sharing one Session across threads, because a shared session isn't something I want to rely on as thread-safe. The 409 is whatever your API documents for a lost race; the shape of the assertion is what matters: count outcomes and check exactly one winner.
The same pattern fits anything that must happen once: inventory decrements, seat reservations, account creation with a unique email, coupon redemptions.
Assert on invariants, not only status codes
Status codes tell you what the API said it did. A follow-up read tells you whether the system is actually consistent. I've seen the right codes come back during a concurrent run and the state still end up wrong: a balance debited twice, a counter that moved once instead of many times.
def test_concurrent_purchases_keep_stock_consistent(api_base_url, auth_headers,
product_with_stock):
product_id, initial = product_with_stock(10)
def buy(_):
return requests.post(f"{api_base_url}/products/{product_id}/purchase",
json={"quantity": 1}, headers=auth_headers, timeout=10)
successes = sum(r.status_code == 200 for r in fire_together(15, buy))
stock = requests.get(f"{api_base_url}/products/{product_id}",
headers=auth_headers, timeout=10).json()["stock"]
assert stock >= 0, f"Stock went negative ({stock}): oversell race"
assert successes <= initial, f"{successes} purchases succeeded with {initial} in stock"
assert stock == initial - successes, (
f"{successes} purchases reported success but stock went {initial} -> {stock}")
Firing more buyers than there are units is deliberate. If the API doesn't decrement atomically, you'll see more successes than stock or a negative count, even though every individual response looked fine. That's the classic oversell, and no sequential test finds it.
Notice the fixtures seed a fresh voucher and product per test. Concurrency tests that share resources race each other as well as the API, and then you can't tell which race you caught. I cover the trade-offs in how much test data isolation is actually enough.
Keep them sensitive without making CI flaky
Race tests are probabilistic. Whether the race fires depends on scheduling, network and database load, which all differ between your laptop and a CI runner. A test that only sometimes catches the bug is a flaky test, not a safety net. What helps:
- Repeat the burst inside one test. Reset state, fire again, and fail if any iteration breaks the invariant. Each repetition is another chance for the race to show itself.
- Keep concurrency modest. A burst of ten or so is usually enough. Push too hard on a shared CI environment and you get timeouts that hide the real assertion.
- Mark and stage them. Register a marker and run these as their own CI step after the fast checks.
# pytest.ini
[pytest]
markers =
concurrency: fires concurrent requests to detect race conditions
# CI step
pytest -m concurrency --tb=short -v
Keep correctness and load separate. A race test asks whether invariants hold under overlap and finishes quickly. A sustained load test asks about performance and belongs in a performance tool.
When one of these does fail intermittently, treat it as a finding, not noise. A retry turns it green and hides the bug. I talk about where retries are and aren't legitimate in retrying an API call in tests without hiding real failures.
Agents: the retry reflex and the duplicate tool call
Ask a coding agent to "fix the flaky test" and the common results are a time.sleep(), a retry decorator, or a lower thread count until the race stops firing. All three make CI green and the bug invisible. I write it into the agent's instructions file (.github/copilot-instructions.md for Copilot, or your agent's equivalent):
## Concurrency tests (tests/concurrency/)
- An intermittent failure here is a suspected race condition in the API, not test flakiness.
- Never add sleeps, retries or reduce the worker count to make these pass.
- Report the failing invariant and the observed status codes in the PR instead.
The other side is testing agents that call your API. When a model's tool call times out, the agent loop often retries it, and some agents issue several tool calls in parallel. From the API's point of view, that's two identical requests arriving close together. If the operation isn't idempotent, the user gets charged twice.
The barrier helper covers this directly. Fire the same request, with the same idempotency key if your API supports one, from several threads at once, and assert exactly one effect:
def test_duplicate_tool_call_creates_one_order(api_base_url, auth_headers):
key = "agent-run-123-step-4"
def create(_):
return requests.post(f"{api_base_url}/orders",
json={"sku": "WIDGET-42", "qty": 1},
headers={**auth_headers, "Idempotency-Key": key},
timeout=10)
responses = fire_together(5, create)
order_ids = {r.json()["id"] for r in responses if r.status_code in (200, 201)}
assert len(order_ids) == 1, f"Duplicate requests created {len(order_ids)} orders"
Header name and response codes vary by API, so match your own contract. The point is that "the agent might retry" becomes a concrete, repeatable test rather than a worry.
Where to start
Before writing any of this, list the endpoints that read a value and write it back: balances, counters, status transitions, reservations. Check whether the API documentation says anything about concurrent behaviour. Often it doesn't, and that gap is a finding worth raising. If you want to build tests like these in a full pytest suite with VS Code and GitHub Copilot, my API testing courses cover the foundations.