// web security

Race Condition Vulnerability: Single-Packet Tests, Real Fixes

Race condition vulnerability concept: many synchronized HTTP/2 requests converging on one shared database record

A race condition vulnerability lets concurrent requests break a rule the business depends on, such as one coupon per customer or a balance that never goes negative. HTTP/2 single-packet delivery is how testers reproduce these bugs on demand. It is a test technique, not a fix: the fix lives in the database transaction, not the gateway.

The short answer

  • A race condition vulnerability lets concurrent requests break a shared invariant such as a balance, quota, uniqueness rule or workflow state.
  • Test by releasing synchronized requests (an HTTP/2 single-packet attack, or last-byte sync over HTTP/1.1) and then inspecting database side effects across many trials.
  • The main bug classes are limit overruns, multi-endpoint races and partial-construction bugs.
  • Fix them with atomic conditional writes, unique constraints, correct locking, state machines and idempotency keys enforced by a unique constraint, not with rate limits.

Key takeaways

  • A race condition vulnerability is a broken shared invariant under concurrency, so the test plan lists invariants before endpoints.
  • An HTTP/2 single-packet attack tightens arrival, but per-session locks and single-threaded workers can still serialize execution.
  • Limit overruns, multi-endpoint races and partial-construction bugs need different request shapes and different atomic fixes.
  • Rate limits, CAPTCHAs and idempotency keys do not provide atomicity. Conditional writes, unique constraints and locks taken before the check do.
  • Evidence is side effects across repeated trials. A 200 OK proves nothing either way.

What is a race condition vulnerability in a web application?

A race condition vulnerability is a concurrency flaw: two or more requests interleave so that a shared invariant breaks. Typical invariants are a balance that never goes negative, a coupon redeemed once, one vote per user, or a seat sold to one buyer.

MITRE’s CWE list files the general case under CWE-362, concurrent execution using a shared resource with improper synchronization. Check-then-act is CWE-367, time-of-check time-of-use (TOCTOU). Workflow abuse maps to CWE-841, frequency-control failures to CWE-799, and CWE-840 is the broader business-logic category.

The vulnerable shape rarely changes:

coupon = load(code)
if not coupon.used: # check
 apply_discount(cart)
 coupon.used = True # act + commit
 save(coupon)

The race window is the gap between the check and the commit. The test lands several state-changing requests inside that window before any of them writes. List invariants before you list endpoints: the invariant is the target, and each endpoint is just a way to reach it.

How does a single-packet attack work against web race conditions?

Naive parallel requests miss races because network jitter spreads arrivals wider than the race window. Threads open sockets, finish TLS and get scheduled apart, so requests land milliseconds apart and a fast handler commits in the gap.

Technique How requests are released Arrival spread Main caveat
Naive parallel threads Independent connections, sent when each thread runs Wide, variable Jitter dominates; false negatives are common
Last-byte synchronization (HTTP/1.1) All but the final byte sent, then final bytes flushed together Narrower Separate TCP packets; proxies may buffer or reorder
HTTP/2 single-packet attack Final frames of many streams packed into one TCP packet Tightest Needs HTTP/2 to the edge; the server may still serialize

A single-packet attack puts the final frames of many HTTP/2 requests into one TCP packet, so the server receives every completion at once. It works because HTTP/2 multiplexes many streams over one connection, as RFC 9113 specifies.

Open one connection, send the headers and most of each body on its own stream, and hold back the DATA frame that carries END_STREAM. Then write every withheld frame in a single socket write. No request completes until that packet arrives, so client-side jitter drops out.

James Kettle of PortSwigger popularized the technique in his 2023 research, Smashing the state machine: the true potential of web race conditions. Burp Suite added practical support alongside that work, in Repeater’s parallel tab-group send and in Turbo Intruder.

Single-packet delivery controls arrival, not execution. A single-threaded worker, middleware, a load balancer or a database lock can still serialize the work. PHP’s default file-based sessions lock per session ID, so requests sharing a cookie run one after another. If timings come back sequential, retry with a separate valid session per request.

What is last-byte synchronization, and when should you use it?

Last-byte synchronization sends every request except its final byte, then releases the final bytes together. Use it when the path is not HTTP/2 end to end, or as a second opinion over HTTP/1.1. It is the looser fallback in the table above.

Over HTTP/1.1 each request needs its own connection, so the final bytes still leave as separate TCP packets. A reverse proxy or CDN that buffers usually widens the arrival spread, though some proxies flush together and narrow it. Warm each connection with one harmless GET first, so setup and backend wake-up stay out of the measurement.

Single-packet attack concept for race condition vulnerability testing: many HTTP/2 streams arriving at the same instant
Single-packet delivery removes network jitter from the race.

What is a limit overrun, multi-endpoint, or partial-construction race?

What is a limit overrun race condition?

A limit overrun happens when parallel requests each pass a quantity, balance, quota or frequency check before any of them updates the shared counter. Every request reads the old value, so the limit applies per request instead of once per burst. Common targets:

  • Coupons, referral bonuses and signup credits
  • Gift-card and wallet balances, withdrawal and transfer limits
  • Votes, likes and reviews
  • Inventory, seats and reservations
  • API quotas and login or 2FA attempt counters

Take a gift card with a $50 balance and send 20 redemptions of $50 in one packet. If three commits land, the card has paid out $150, and every response may look normal. Read the ledger, not the status line.

Run same-user and cross-user variants. Two accounts racing for the last unit of stock take a different code path than one account racing itself, and a lock scoped to the user misses the cross-user case.

What is a multi-endpoint race condition?

A multi-endpoint race breaks an invariant that each endpoint enforces correctly on its own, because two endpoints read or change the same state. Testing one route at a time never makes them collide.

Checkout is the textbook case. Payment validates the cart total and charges it while an add-to-cart request inserts another item. If the order is built from the cart after the charge was calculated, the buyer gets two items for the price of one. Similar pairs include applying a coupon while checkout finalizes, redeeming a referral while the referred account is still being created, and fetching an uploaded file while the malware scan is still pending.

Simultaneous arrival does not guarantee overlap in the critical section, because handlers run at different speeds. Send the slow request first, offset the fast one, and vary the ordering. In API penetration testing, mapping every route that touches the state usually finds the sibling endpoint nobody locked.

What is a partial-construction bug, and why does it matter?

A partial-construction bug makes an object, token, account, order or workflow row reachable before it is fully initialized. A parallel request can use the half-built record, and when that record is a token or account, the race can bypass authentication.

A common registration flow inserts the user row, then writes the API key or verification token in a second query. Between those writes the token column is null or empty. A concurrent request that sends an empty value, or a parameter the framework coerces to null (an empty array, say), can match the row.

Race the create against the consume, and send the consumer what a half-built row would hold: null, empty string, zero and default enum values. Reset tokens issued before they bind to a user follow the same pattern.

How do you test for race conditions safely and reproducibly?

To test safely, work from a known starting state, use canary accounts that cannot cause real loss, repeat trials, and inspect side effects rather than responses. Races are probabilistic, so one run proves little.

  1. Get written scope. Prefer staging. In production, agree on canary accounts, low amounts, timing and rollback.
  2. Name the invariant and the record that proves it: a ledger row, a coupon flag, sent mail or an audit entry.
  3. Baseline one request and record the correct end state.
  4. Burst with a single-packet group. Start small and scale; use separate sessions if a per-session lock appears.
  5. Repeat and record the hit rate.
  6. Read state, not responses. Every call can return 200 while one commit was allowed, or 500 after the write landed.

Which tools can send parallel or single-packet requests?

Burp Repeater can send a tab group in parallel for a quick check. For scripted bursts, Turbo Intruder’s single-packet race template queues each request on the BURP2 engine under one named gate, then calls openGate to release the group. For regression runs in CI, a small custom HTTP/2 client does the same job.

Prove the setup on a deliberately vulnerable endpoint first, such as a lab or a staging route you broke on purpose. A clean result means something only after the same setup has produced a known race.

Do rate limits or CAPTCHAs prevent race conditions?

No. Rate limits and CAPTCHAs govern how often requests arrive. They do not make the checked operation atomic. A cap of 10 requests a minute still lets 10 requests share one packet, and all 10 can pass the same check.

Limiters are often racy themselves. If the limiter reads a counter, compares it, then increments it, a single-packet burst overruns it the same way it overruns a coupon, which adds a CWE-799 finding to the original bug. A CAPTCHA verified now and marked spent later can authorize the entire burst.

Disabled buttons and click debouncing do nothing against a raw HTTP/2 client. Gateway limits are abuse controls, not concurrency controls. If a report proposes one as the remediation, challenge it before the ticket closes.

How do locking and idempotency fix race conditions?

Locking and atomic writes fix a race by making the check and the update a single step. An idempotency key fixes a narrower case: the same request retried or replayed. Pick the control from the invariant you are protecting.

UPDATE accounts
 SET balance = balance - :amount
 WHERE id = :id AND balance >= :amount;
-- 0 rows affected = reject

Where should the lock sit?

For a balance or quota, use a conditional update like the one above and reject the call when zero rows change. Use a unique constraint for one vote, one redemption or one email, and handle the constraint error instead of letting it surface as a 500.

SELECT … FOR UPDATE fits multi-step logic on one aggregate only if the lock is taken before the check. A version column works for low-contention edits when a mismatch is rejected or retried. An in-process mutex stops working the moment a second instance serves traffic.

When does an idempotency key fail?

An idempotency key works only with a unique constraint on the key, scoped to operation and user. Store a hash of the payload with the recorded response and replay that response on a duplicate. A check-then-insert on the idempotency table recreates the race the key was meant to stop.

The Idempotency-Key header is a convention popularized by Stripe and described in an IETF HTTP API working group draft, not a finished standard. Either way, it will not stop two different clients from racing a shared balance or a one-time coupon.

What about distributed locks and isolation levels?

On Redis or etcd, lock expiry is a failure mode: a paused client can wake up and write after its lease lapsed. Issue fencing tokens and reject stale ones at the write. When no single transaction spans the services, model the operation as a reservation with a pending state that other services refuse to consume.

No isolation level is a set-and-forget fix. READ COMMITTED, the default in PostgreSQL and SQL Server, does not stop check-then-act races or write skew. MySQL InnoDB defaults to REPEATABLE READ, and a plain SELECT followed by an UPDATE can still race without a locking read.

PostgreSQL’s SERIALIZABLE level aborts conflicting transactions. That protects the data only if the application catches the serialization failure and retries; otherwise load turns an integrity bug into failed requests.

Which control closes which bug class?

Bug class Control that closes it Common false fix
Limit overrun Conditional write or unique constraint Rate limit, button debounce
Multi-endpoint race One transaction or lock on the shared aggregate, used by every route Locking only the endpoint that was reported
Partial construction Insert the finished object in one transaction, or refuse pending rows Validating the token format
Cross-service race Reservation state machine plus fencing tokens Lock with expiry and no fencing

How do you report a race condition with convincing evidence?

Report the broken invariant, the hit rate and the exact conditions. Race findings get dismissed faster than most, so the side effects have to make the case without you in the room.

  • Invariant and starting state: a coupon with one use left, or a $50 balance on the canary account.
  • Technique: single-packet over HTTP/2 or last-byte sync, request count, sessions and tool.
  • Hit rate: for example, 7 of 50 trials produced a duplicate redemption.
  • Side-effect proof: ledger rows, duplicate order IDs, mail and audit entries with timestamps.
  • Affected paths: every endpoint that touches the same state, not only the one you raced.

Score severity from impact and repeatability. A few hits across fifty trials on an uncapped balance is still critical. After the fix, rerun the same setup for the same trial count and require zero violations, sibling endpoints included. Our API penetration testing checklist lists the related business-flow checks.

Can serverless or autoscaling applications have race conditions?

Yes, often more of them. Autoscaling and serverless remove the accidental serialization of a single process: each invocation can be its own worker, so a burst one process would have queued runs in parallel. In-memory locks do not cross those workers. Conditional writes and unique constraints in the shared store still close the bug; reserved concurrency only changes how often requests overlap.

How are race conditions different from duplicate requests or retries?

A retry repeats one logical request, usually after a timeout, and an idempotency key collapses those copies into one outcome. A race is two operations that overlap before either commits, often from different users or endpoints. A passing retry test does not clear that overlap, so schedule both tests: they fail in different code.

Limit overrun race condition illustrated as many simultaneous hands claiming a single gift card
Limit overruns: every request passes the check before any request updates the counter.
Partial-construction bug concept: a half-built object accessed before initialization, a race condition vulnerability
A half-built record can be used before its security fields exist.

FAQ

What is a TOCTOU race condition in a web app?

TOCTOU (time-of-check time-of-use, CWE-367) is a race where the app checks a condition, such as an unused coupon, and acts on it in a later step. A concurrent request that lands between the check and the commit sees the old state and passes the check too.

Does HTTP/3 support single-packet race attacks?

HTTP/3 multiplexes streams over QUIC (RFC 9114), so a similar synchronized release is possible in principle. Race-testing tools are still built around HTTP/2. Confirm which protocol you actually reached before you treat a negative result as meaningful.

How many requests should a race condition test send?

There is no fixed number. Start with a small group, increase until the hit rate stabilizes, and repeat the trial. Success depends on the server, the framework, session locking and the database, not on a magic parallel count.

Are race conditions just double-submitted forms?

No. A double submit is one client repeating one action. A race condition vulnerability is any interleaving that breaks a shared invariant, including two users, two endpoints, or a read that overlaps a half-finished insert. Client-side click limits cover none of those.

Which control should close a balance check first?

Start with a conditional update that changes the row only when the balance still covers the amount, and reject a zero-row result. Add a unique constraint when the rule is one redemption or one row per key, and move to SERIALIZABLE with retries only for rules that span several rows.

agent::offense tests business-logic and concurrency flaws by hand, with single-packet harnesses and side-effect evidence your developers can reproduce. See our web application penetration testing service for scope and approach.



// get started

Work with AgentOffense

Tell us about your target and goals. We’ll reply with scope and a fixed-price quote — usually within one business day.

./request_engagement