All Blogs
Race Condition Vulnerabilities in APIs: What They Are and How They Work

Quick Overview: Race condition vulnerabilities let concurrent API requests slip through the gap between a check and an update. The blog explains what they are, why APIs are prone to them and how they work, then covers real-world targets, attacker techniques, why they are hard to detect, how to test for them, and the best practices that prevent them.
Two requests. One account. Same milliseconds.
That’s all it can take for an API to approve a $400 withdrawal twice from a $500 balance. There’s no malicious payload and no stolen credentials. The two requests are perfectly valid, arrive together, and slip through the gap between a check and an update.
Hitting that gap is easier than most teams assume. PortSwigger Research showed that 30 requests sent from Melbourne to Dublin can be squeezed into an execution window of under one millisecond. That turns timing flaws that once seemed theoretical into real-world, repeatable exploits.
That’s the trouble with race condition vulnerabilities in APIs. They hide in business logic, look fine in code review, and stay invisible to scanners that send one request at a time.
Here’s how they work, where they show up, and why finding them takes advanced API penetration testing, not another routine scan.
Valid requests, broken rules. Uncover the race condition flaws hiding between check and update. Find My Race Windows
On this Page
- What are Race Condition Vulnerabilities in APIs?
- Why APIs are Prone to Concurrency Vulnerabilities
- How API Race Condition Vulnerabilities Work
- Real-World API Operations Vulnerable to Race Conditions
- How Attackers Exploit Race Conditions in APIs
- Why API Race Conditions are Hard to Detect
- How to Test APIs for Race Condition Vulnerabilities?
- Best Practices to Prevent Race Condition Flaws in APIs
- How ZeroThreat Helps Detect Race Condition Vulnerabilities
- To Wrap Up
What are Race Condition Vulnerabilities in APIs?
A race condition vulnerability in an API is a flaw where an endpoint handles concurrent requests against the same shared resource without proper synchronization. Because the requests overlap, the API makes decisions based on data that is already out of date. This lets an attacker perform an action more times, or in a different order, than the application should allow.
Most API race conditions come from a check-then-act pattern. The API first reads a value, such as an account balance, a coupon’s status, or a usage counter. It then updates that value in a separate step. The gap between the check and the update is called the race window. If a second request reads the same value inside that window, both requests pass the check before either one records its change. This pattern is known as a time-of-check to time-of-use (TOCTOU) flaw.
Example: A gift card API holds a balance of $100. A user sends two $100 redemption requests at the same moment. Both requests check the balance, both see $100, and both are approved before the first deduction is saved. The application has now honored $200 of purchases against a $100 card.
Also, you should note that, not every race condition is a security issue. Concurrency bugs often cause duplicate records or inconsistent data with no attacker involved. The issue becomes a vulnerability when someone can trigger it deliberately to break one of those rules.
Race conditions fall under CWE-362 (Concurrent Execution using Shared Resource with Improper Synchronization). TOCTOU flaws are tracked separately as CWE-367. In practice, API race conditions behave more like business logic flaws than injection bugs. Each request is well formed, properly authenticated, and passes input validation on its own. The weakness appears only when the requests arrive together, so testing one request at a time does not reveal it.
Why APIs are Prone to Concurrency Vulnerabilities
APIs are prone to concurrency vulnerabilities because they are built to handle many requests at the same time. Those requests often run across several servers that share the same data. Most API business logic quietly assumes that requests for one resource arrive one after another. In production, they rarely do, and race conditions appear in the gap between that assumption and real runtime behavior.
- Concurrent Processing by Design: API servers use thread pools, async event loops, and worker processes to handle many requests at once. Two requests for the same record can run at the same time unless the code explicitly serializes them.
- Stateless Request Handling: Each API request is processed on its own, with no built-in awareness of other in-flight requests from the same user. The server cannot tell that an identical request is already halfway through processing.
- Shared Databases and Caches: Multiple instances and services read and write the same database rows and cache keys. Even a briefly stale cached value gives concurrent requests enough time to act on outdated state.
- Read-Then-Write Application Logic: Developers often read a value, check it in code, and write the result back in a separate query. Without row locks or atomic updates, common isolation levels let two transactions read the same value.
- Microservices and Distributed Transactions: A single business operation, such as checkout, may span inventory, payment, and order services. The check runs in one service, and the update in another, and no single transaction protects both steps.
- Asynchronous and Queued Processing: Webhooks, message queues, and background jobs often finalize state after the API has already responded. This widens the race window, and automatic retries can process the same event more than once.
- Multi-Step Stateful Workflows: Flows like checkout, password reset, and MFA verification span several API calls. Each step assumes the previous one finished cleanly, so parallel or out-of-order calls can break state transitions.
- Direct Programmatic Access: An API accepts requests from scripts and custom clients, not just a UI with buttons. HTTP/2 lets a client multiplex many requests over one connection, so they can reach the server almost simultaneously.
- Missing Idempotency Controls: Many endpoints lack idempotency keys or unique database constraints on actions meant to happen once. Without them, the API treats every duplicate request as a new, legitimate operation.
Any one of these factors can open a race window. In most production APIs, several of them exist at once.
Race conditions pass code review and dodge scanners. Put your API workflows under attacker-style testing. Run API Pentesting
How API Race Condition Vulnerabilities Work
API race condition vulnerabilities exploit the time gap between when an API checks a condition and when it acts on that check. If two or more requests land inside that gap, each one sees the same unchanged state, passes the same check, and applies its own update. Together they break the rule the check was supposed to enforce.
The flaw is never in a single request. It appears in how the application’s internal states line up when several requests are processed at once. Four things explain how that happens: the code pattern behind it, the window it opens, how requests collide inside that window, and why timing decides whether the attack succeeds.
1. The Check-Then-Act Pattern
Most API race conditions start with logic that reads a value, makes a decision in application code and writes a new value in a later step. This is the time-of-check to time-of-use (TOCTOU) pattern:

The code is correct when requests arrive one at a time. It fails under concurrency because the decision rests on a value that another request can change before the write happens. Nothing ties the check and the update together as a single atomic operation.
2. The Race Window
The race window is the period between the check and the write. During that time, the application is in an inconsistent state: the decision has been made, but the record still shows the old value.
The window is often only milliseconds wide, but several factors make it wider:
- Slow work between the check and the write, such as payment gateway calls, email delivery or file processing
- Multiple database round trips instead of one atomic query
- Reads served from a cache or replica that lags behind the primary database
- Coordination across services or instances before the final write
A wider window means more concurrent requests can fit inside it, so the flaw becomes easier to exploit.
3. The Requests Collision
Take a withdrawal API where an account holds $500 and two requests each ask to withdraw $400:
- Request A reads the balance as $500 and passes the check.
- Request B reads the balance before A has written its update. It also sees $500 and passes the check.
- Request A pays out $400 and writes the new balance of $100.
- Request B pays out $400 and also writes $100, overwriting A’s update.

The API has paid out $800 from a $500 account, yet the final balance reads $100 as if only one withdrawal happened. This is called a lost update: the second write silently erases the first, and nothing in the logs looks unusual. Each request was valid, authenticated, and processed correctly on its own.
4. Why Timing Matters for Race Conditions to Work
An attack succeeds only when concurrent requests reach the server inside the same race window. Network jitter spreads out arrival times, which is why race conditions often look intermittent: the same pair of requests may collide once and miss ten times.
Modern protocols have made this timing far more reliable. The single-packet attack, which PortSwigger Research first demonstrated at Black Hat USA 2023, uses HTTP/2 to complete 20 to 30 requests at once inside a single TCP packet, removing the effect of network jitter. As a result, a race window of about a millisecond can be hit consistently from a remote network. A flaw that looks theoretical in code review can therefore be practical to exploit.
Real-World API Operations Vulnerable to Race Conditions
Race conditions can appear in any API operation that enforces a limit, a balance or a one-time rule on shared state. The riskiest operations move money, hand out value or change access. In those, a single successful collision has a direct financial or security impact. Bug bounty programs have repeatedly confirmed the operations below.
Payments and Fund Transfers
Transfer and withdrawal endpoints that check a balance and then debit it in separate steps let parallel requests spend the same funds more than once. Security researcher Egor Homakov demonstrated this against Starbucks by exploiting a race condition on its gift card page to generate an unlimited amount of value.
Gift Card and Coupon Redemption
Single-use codes rely on a “redeemed” flag that is often set only after the credit or discount is applied, so concurrent requests all see the code as unused. In one public HackerOne report against reverb.com, a researcher bought a single $25 gift card and redeemed it seven times.
Inventory and Limited-Stock Orders
Flash sales, ticketing, and booking APIs check stock or seat availability before decrementing it. When hundreds of checkout requests arrive together, each one sees the item as available. The system then oversells limited stock or assigns the same seat or time slot to several buyers.
Payouts, Rewards, and Credits
Referral bonuses, cashback, loyalty points, and platform payouts are usually triggered by a status change such as “approved” or “completed”. On HackerOne itself, sending multiple requests to confirm a retest at the same time paid a user multiple times for that one retest.
Votes, Likes, and Follows
Social and rating endpoints enforce “one per user” by looking up an existing record before inserting a new one. Racing those requests inflates counters, rankings, and reviews. Public reports describe following the same user multiple times and upvoting a single report repeatedly to raise its rank.
Login and Rate Limits
Attempt counters for logins, OTP entry, and API quotas are typically read, compared to a threshold, and then incremented. Requests sent in one burst are all checked against the same count. This lets an attacker try far more passwords or codes than the limit is meant to allow.
One-Time Tokens and OTPs
Password reset links, email verification codes, and MFA codes should stop working after their first use. If the API marks a token as used only after the protected action completes, parallel requests can consume the same token more than once before the invalidation is saved.
Annual pentests can’t catch what ships next week. Compare plans built for continuous API security testing. Check Out Pricing
How Attackers Exploit Race Conditions in APIs
Attackers exploit race conditions in APIs by sending several valid requests to the same operation at almost the same moment, so they all land inside one race window. No malicious payload is needed. The work is in finding the right endpoint, timing the requests precisely, and confirming that a business rule broke.
Step 1: Find a Limit-Enforcing Endpoint
Attackers start by looking for endpoints that enforce a rule on shared state, such as one coupon per account, a balance check, a stock count or a single-use token. Any operation that should succeed only once, or only up to a limit, is a likely target.
Step 2: Map the Normal Request Flow
Next, they send the request normally, one at a time, to record how the API behaves. This baseline shows which response means success, which means rejection, and whether the operation spans several calls, such as applying a coupon and then confirming an order.
Step 3: Send Requests in Parallel
The attacker then sends many copies of the same request at the same instant, or a set of related requests to different endpoints. HTTP/2 multiplexing and the single-packet attack make the requests arrive within a millisecond or so of each other, so they all fall inside one race window.
Step 4: Look for Anomalies
The attacker compares the responses and the resulting state with the baseline. Signs of a successful race include:
- more than one success where only one should be allowed
- a balance or counter that doesn’t add up
- duplicate records
- unexpected server errors caused by concurrent writes
Step 5: Repeat and Scale the Attack
Because race outcomes depend on timing, attackers repeat the burst until the collision happens reliably. Once it works, they increase the number of parallel requests or chain endpoints together to maximize the gain, such as redeeming one gift card dozens of times or stacking discounts.
From the server’s point of view, every one of these requests is authenticated and well formed. That is why this activity rarely stands out in logs or monitoring.
Why API Race Conditions are Hard to Detect
API race conditions are hard to detect because the flaw appears only when specific requests overlap inside a window that may last a few milliseconds. No single request is malicious on its own, so most testing and monitoring methods never see a problem.
- Non-Deterministic Behavior: The same requests may collide once and then process normally the next ten times. That makes the bug hard to reproduce or confirm.
- Sequential Scanning: Most automated vulnerability scanners send one request at a time, which never opens a race window.
- Correct-Looking Code: Each function passes code review on its own. The flaw is in the timing between operations, not in any single line.
- Unrealistic Test Environments: Low-traffic staging setups running a single instance rarely reproduce production-level concurrency.
- No Attack Signature: Web Application Firewalls (WAFs) and logs see authenticated, well-formed requests with no payload to flag.
The damage usually surfaces later, in financial reconciliation or customer complaints, long after the requests were processed.
How to Test APIs for Race Condition Vulnerabilities?
Testing APIs for race condition vulnerabilities means sending concurrent requests to state-changing endpoints and checking whether business rules still hold. Standard scanners send one request at a time, so this needs a targeted approach: choose the right endpoints, synchronize the requests, reproduce the result, and prove its impact. Always test with authorization, using dedicated test accounts in an environment that mirrors production.

1. Identify Candidate Endpoints and Shared State
Start from the API inventory or OpenAPI specification. Flag every state-changing operation (POST, PUT, PATCH, DELETE) that enforces a limit, a balance, or a one-time rule. For each one, note the shared resource it reads and writes, such as a balance row, coupon record or verification token. Test first the endpoints that do slow work between the check and the write, such as payment gateway calls, and multi-step flows where two endpoints touch the same state.
2. Send Synchronized Concurrent Requests
Record a sequential baseline first. Then send 20 to 30 identical requests timed to arrive together. Where the API supports HTTP/2, use single-packet delivery. For HTTP/1.1, use last-byte synchronization, which holds back the final byte of each request and releases them all at once to reduce network jitter.
Run these tests against infrastructure that matches production concurrency: multiple instances behind a load balancer, with the same database isolation settings. A single-instance staging server can hide the flaw entirely. Also test multi-endpoint races by pairing related requests, such as applying a coupon and checking out.
3. Reproduce the Race Condition Reliably
One anomaly is not proof. Repeat each test several times and record how often the collision occurs. Reset the state between runs, for example by issuing a fresh coupon or restoring the test balance, so results stay comparable. Vary the number of parallel requests to find the point where the race starts to appear. A measurable success rate turns an intermittent glitch into a verified finding that developers can debug.
4. Validate Exploitability and Impact
Confirm that the race broke a real business rule and didn’t just produce a noisy response. Check the backend state directly for...
- duplicate records
- a balance that doesn’t sum up
- a token that was accepted twice
- a counter that went above its limit
Then express the impact in business terms, such as how much money, stock, or access a single test account gained. Capture request timestamps, responses, and before-and-after state as evidence, so the finding can be prioritized and retested after the fix.
Once a race condition is fixed, add the concurrent test case to your regression suite, so the fix stays in place as the code changes.
Best Practices to Prevent Race Condition Flaws in APIs
Most race conditions come from one habit: the API checks something and then acts on it in a separate step. Close that gap and most of the risk goes with it. Here’s how to do that in practice.
- Make the Check and Update Atomic: Replace read-then-write logic with a single conditional query, such as UPDATE accounts SET balance = balance - 400 WHERE id = 42 AND balance >= 400. If no row is updated, reject the request.
- Lock Rows Before Changing Them: When the logic can’t fit in one query, wrap it in a transaction and use SELECT ... FOR UPDATE on the rows involved. Keep these transactions short so the locks don’t slow everything down.
- Let the Database Enforce One-Time Rules: Add unique constraints for rules like one redemption per user per coupon. A duplicate insert then fails at the database, however many requests arrive at once.
- Require Idempotency Keys on Critical Endpoints: Payments, orders, and transfers should accept a client-generated key and store it with the result. A repeated key returns the original response instead of running the operation again.
- Use Optimistic Concurrency Where Locks Are Too Heavy: Add a version column to the record and include it in the update condition. If another request changed the row first, the update fails, and the client can safely retry.
- Consume Tokens Before Acting on Them: Mark one-time tokens, OTPs, and reset links as used with a conditional update first, then perform the action. Never invalidate them after the protected step has completed.
- Don’t Rely on In-Memory Locks in Scaled Services: A mutex protects only one instance. Across multiple instances, use database locks or a distributed lock with an expiry, and treat it as a backup to atomic data operations.
- Keep Slow Work Out of the Race Window: Reserve the balance or stock first, then call payment gateways or send emails. Every external call between the check and the write widens the window.
- Don’t Treat Rate Limiting as a Fix: Rate limits reduce request volume, but 20 parallel requests still fit under most thresholds. They’re a useful extra layer, not a substitute for atomic logic.
- Test for Concurrency in CI: Use automated pentesting that sends parallel requests to limit-enforcing endpoints on every release. A refactor can quietly reintroduce a race condition that was fixed months ago.
How ZeroThreat Helps Detect Race Condition Vulnerabilities
Race conditions hide in stateful workflows, so ZeroThreat starts there. Its API discovery feature finds shadow, undocumented, and dynamic endpoints, and authenticated security testing covers login flows and access control across user roles, permissions, and sessions. That keeps balance, coupon, and token endpoints within the test scope.
Next, ZeroThreat analyzes real user workflows and state changes, and detects logic gaps that enable misuse, repetition, or sequence manipulation. Its Playwright-driven Application Journeys test multi-step processes for workflow bypasses, race conditions, replay scenarios, and parameter manipulation. These are exactly the gaps that sequential scanners miss.
Every finding then goes through proof-based vulnerability validation, so teams see evidence of real abuse rather than noise. AI-powered remediation guidance is created based on your tech stack, and individual issues can be re-scanned to verify fixes, which confirms that the race window is actually closed.
Concurrent requests can quietly break your business rules. Find the race window in APIs before anyone else does. Test My APIs Now
To Wrap Up
Race conditions turn valid API requests into real business risk. When a check and an update run as separate steps, parallel requests can land in the same race window and break limits on balances, coupons, stock, and tokens.
Prevention starts in the data layer. Make checks and updates atomic, enforce one-time rules with database constraints, require idempotency keys on critical endpoints, and keep concurrency tests in every release so fixed flaws stay fixed.
In concurrent systems, security depends on timing as much as logic. APIs designed for parallel requests and tested under real concurrency leave attackers far less room to race through, however fast their requests arrive.
This makes detection harder because every request looks legitimate. The only solution is to test your application regularly with synchronized concurrent requests. That’s where you can test your APIs with ZeroThreat, probing authenticated workflows and business logic the way attackers abuse them, with proof behind every finding.
Frequently Asked Questions
Does rate limiting prevent API race conditions?
No. Rate limiting caps request volume over a time window, but a race condition needs only a handful of requests arriving within milliseconds. Most of these bursts fit comfortably under sensible thresholds. Treat rate limiting as defense in depth, and fix the root cause with atomic updates, row locks or unique constraints.
Where do race conditions fit in the OWASP API Security Top 10?
Can DAST tools detect race condition vulnerabilities in APIs?
Are GraphQL APIs more exposed to race conditions?
Can race conditions happen in single-threaded runtimes like Node.js?
Explore ZeroThreat
Automate security testing, save time, and avoid the pitfalls of manual work with ZeroThreat.


