A one-time action has three moments: check, decide, commit. If another request can enter between check and commit, both can believe they are first.
The server reads state, waits, then writes. Two concurrent requests both read the unused state and both commit. The invariant 'used once' is enforced by timing rather than by an atomic operation.
We test state, not timing. Attackers ask what happens between two instructions.
What is actually at stake?
Before touching a payload, map the assets, the actors and the boundary that is supposed to protect them. A finding only becomes a vulnerability when you can connect the failed boundary to a real asset.
Assets
- Gift balances and coupons
- Inventory and reservations
- One-time approval or invitation tokens
- Vote, like and quota counters
Actors
- Customer replaying a checkout or redemption
- Automated client sending parallel requests
- Attacker with many accounts or sessions
- Insider exploiting batch jobs
Trust boundaries
- Check to commit
- Read to write
- One-time token to first use
- Application lock to database lock
- Multiple instances to shared state
Abuse cases
- Redeem a coupon twice in parallel
- Withdraw more than the balance
- Reserve the last item from two sessions
- Approve the same request twice
- Exceed a rate limit enforced in process memory
Follow the decision, not the payload
Every family has a moment where trusted data becomes an authorization, parsing or state decision. Learn to point at that moment in the request path.
- 01
Check
The handler reads a balance, quota or status and decides the action is allowed.
- 02
Wait
Time passes while another request performs the same check using the same starting state.
- 03
Act
Both requests write. Without a lock or conditional update, both succeed.
- 04
Commit
The database records an impossible state, such as a negative balance or duplicate redemption.
- 05
Reconcile
The loss is discovered later from a ledger or inventory mismatch, not from an HTTP error.
Two refunds, one payment
Composite case study from public race-condition disclosuresA composite case based on a common payment pattern: refund eligibility was read from the payment row, then a refund row was inserted in a separate transaction.
A tester sent two refund requests concurrently. Both read the payment as refundable before either inserted its refund, and the customer received double the amount.
Direct financial loss and a corrupted ledger. Repeated at scale, the pattern becomes a reliable cash-out primitive rather than a one-off glitch.
The eligibility check and the refund insert were not atomic, and there was no unique constraint or idempotency key per refund.
Use a serializable transaction or row lock, make the write conditional on the remaining balance, add a unique idempotency key, and reconcile the ledger.
Read it as a chain: discovery → failed decision → impact → fix. Then ask which link would have broken earliest.
A repeatable testing sequence
- Find one-time actions: coupons, withdrawals, votes, bookings, resets.
- Send two or more identical requests concurrently.
- Look for delays, non-atomic reads and missing unique constraints.
- Confirm the duplicate success in the ledger or flag.
Where smart people get fooled
- A single request never proves the race.
- The UI disabling a button does not protect the API.
- Logging after the write is not a lock.
What would the logs show?
A control is stronger when someone can see it fail. These signals are starting points for a detection rule, not a complete SIEM use case.
- Multiple identical requests arriving within milliseconds
- Duplicate ledger entries for one payment or coupon
- Balances or inventory dropping below zero
- The same idempotency key used across different operations
- Spikes in retries around a one-time action
index=payments sourcetype=ledger | bucket _time span=1s | stats count sum(amount) by _time, account_id, operation | where count > 1 | join account_id [search index=accounts sourcetype=balances | where balance < 0]Fix the decision, then prove it stays fixed
- Use atomic transactions, row locks or conditional updates.
- Add unique constraints and idempotency keys.
- Make the check and the commit one indivisible operation.
SELECT used FROM coupons WHERE code = ?;
-- if used = 0, later:
UPDATE coupons SET used = 1 WHERE code = ?;UPDATE coupons
SET used = 1, used_at = now()
WHERE code = :code AND used = 0
RETURNING id;
-- zero rows means the coupon was already consumedMake the state transition part of the write and check the affected row count. Add a unique constraint on the business event so the database enforces the invariant even if the application races.
Regression tests a reviewer would ask for
Parallel coupon
GivenA coupon has one use remaining
WhenTwo requests redeem it at the same time
ThenExactly one succeeds and the ledger records one redemption
Parallel refund
GivenA payment is refundable once
WhenTwo refunds are submitted concurrently
ThenThe total refunded never exceeds the payment
Inventory
GivenOne item remains
WhenTwo sessions reserve it simultaneously
ThenOne reservation succeeds and inventory never becomes negative
Distributed instances
GivenThe app runs on multiple nodes
WhenRequests hit different instances
ThenThe control uses shared atomic state, not in-process memory
What this finding is not
Strong testers kill their own findings before someone else does. These are the shortcuts that turn a real bug into a weak report — or a false alarm into a wasted escalation.
- Sequential duplicate requests are rejected: the control may still fail under concurrency; test parallel execution.
- One request returns 409: inspect the final state, not only the response of the losing request.
- The UI disables the button: an HTTP client can send many requests directly.
- The race succeeds only occasionally: that is still a vulnerability; timing windows are often reproducible with enough attempts.
Terms you should be able to use precisely
- Race condition
- A failure caused by the timing of concurrent operations on shared state.
- TOCTOU
- Time-of-check to time-of-use: the state changes between validation and action.
- Atomic update
- A single operation that checks and changes state indivisibly.
- Idempotency key
- A unique client key that lets the server deduplicate repeated operations.
- Row lock
- A database lock that prevents concurrent modification of the same row.
- Lost update
- Two writers read the same value and one overwrites the other's change.
Answer these without reciting a payload
Why doesn't a database transaction alone prevent double-spending?
The transaction must use an appropriate isolation level or lock, and the check and write must be in the same transaction. Two separate transactions can both read the old state.
How do you test a race condition reliably?
Send many equivalent requests in parallel, repeat the attempt, and inspect the final state and ledger. Vary timing and use multiple sessions if needed.
What is the strongest defense for a one-time action?
A database-enforced unique constraint or conditional update on the state transition, combined with an idempotency key and reconciliation.
Can you separate the mechanism from the payload?
Four questions, graded on the server. Answers and explanations are released only after you submit, and signed-in learners keep a best score.
سباق التزامن لا يظهر دائمًا كخطأ؛ قد تنجح الطلبات كلها وتبدو الواجهة سليمة، بينما تكون الحالة النهائية مستحيلة.
المشكلة أن التحقق والتنفيذ ليسا ذرّيين. اجعل الشرط جزءًا من الكتابة نفسها، أو استخدم قفل صف/معاملة مناسبة، وأضف قيدًا فريدًا على الحدث ومفتاح تكرار. لا تعتمد على قفل داخل الذاكرة إذا كان التطبيق يعمل على أكثر من خادم، وافحص السجل المالي والمخزون بعد الاختبار المتوازي.
Can two requests both pass the check before either writes?