guides · 2026-11-14
Race Conditions in Checkout and Balance Code: The Double-Spend Your Tests Never Catch
Published 2026-11-14 · Reviewed 2026-11-14 · By the Ingenious AI team
The short answer
A balance checked in one step and spent in a later step can be spent twice by two requests arriving together — the classic time-of-check/time-of-use race. Generated checkout, coupon and credit code is full of read-then-write sequences with no atomicity. Fix with single atomic updates guarded by the condition (UPDATE ... WHERE balance >= price), unique constraints for one-time artefacts, and idempotency keys on payment actions.
Check your own app free: paste your code or enter your site URL on the Vibe-Code Audit homepage — the free scan checks for exposed secrets, injection flaws, XSS patterns, missing headers and exposed .env/.git paths, with a copy-paste fix for every finding. No credit card.
Why your tests cannot see it
Unit tests run one request at a time, and the code is correct one request at a time: read balance (100), check (≥ 60), deduct (40). Send two 60-unit purchases simultaneously and both read 100, both pass, both deduct — the account ends at -20 having sold two items for one balance. No line is 'wrong'; the composition is. AI generators produce this shape relentlessly because tutorials teach the readable read-check-write sequence and omit the concurrency chapter. Vibe-Code Audit's TOCTOU detector family covers the signatures: balance read-then-write without atomicity, non-atomic findOne-then-save, file check-then-use, and predictable temp files — the patterns are recognisable precisely because the fix requires a construct the naive code never contains.
The valuable targets
Anywhere a scarce thing is consumed: wallet and credit balances, coupon and gift-card redemption (one code, two simultaneous checkouts), limited-stock purchases, free-trial and referral-bonus grants keyed on 'has this user claimed?', vote and like counters that gate payouts, and file workflows where existence checks precede writes (symlink races in shared temp directories). Attackers automate concurrency cheaply — twenty parallel requests is a one-line script — and the payoff is literal money, which is why this class, obscure in blog posts, is routine in fraud.
Single-use artefacts deserve special mention: a password-reset or verification token checked-then-invalidated in two steps can be redeemed twice in the window; the invalidation must be atomic with the check.
The atomic toolbox
Push the condition into the mutation. SQL: UPDATE wallets SET balance = balance - :price WHERE id = :id AND balance >= :price, then check the affected-row count — zero rows means insufficient funds, and the database's own locking makes the sequence indivisible. MongoDB: findOneAndUpdate with the condition in the filter performs the same trick. One-time artefacts: a unique database constraint on the redemption record converts the second insert into an error — constraints are the race-proofing that cannot be forgotten by the next refactor, because they live below the code. Payment actions additionally need idempotency keys so a retried request (yours or the provider's) cannot double-charge. Distributed locks exist for genuinely cross-resource cases, but reach for them last: they add failure modes the atomic primitives do not have.
Testing under concurrency
Write the test that fires N parallel requests at the scarce resource and asserts the invariant afterwards: total deducted never exceeds the balance, exactly one redemption exists, stock never goes negative. Run it in CI with modest N (10–25) — races that need thousands of attempts are still worth catching at the pattern level by scan, but most generated-code races fire within a handful of parallel calls, which is why attackers love them. When the test fails intermittently, you have not got a flaky test; you have the bug, photographed.
Worked example: CoinJar Rewards, a loyalty platform
CoinJar Rewards (fictional), holding user balances for about 12,000 members, redeemed points with a read-check-write sequence an AI assistant had written. A scan's TOCTOU checks flagged the balance path and a findOne-then-save in the coupon service. The team wrote a 20-parallel-request test against staging: a 100-point balance funded 11 simultaneous 60-point redemptions before anyone believed the report. Fixes were mechanical — a guarded atomic UPDATE for balances, a unique constraint on (coupon_id, user_id) redemptions, idempotency keys on the payout action — and the parallel test now asserts exactly one success. The same sweep found the reset-token check/invalidate pair, fixed by making redemption a single conditional update.
Your five-action checklist
- List every consume-a-scarce-thing flow: balances, coupons, stock, trials, bonuses, one-time tokens.
- Replace read-check-write with atomic conditional mutations (guarded UPDATE / findOneAndUpdate) and verify affected-row counts.
- Add unique database constraints for one-time artefacts so duplicates fail at the storage layer, below any code path.
- Attach idempotency keys to payment and payout actions so retries cannot double-apply.
- Write a parallel-request test (10–25 concurrent) per flow asserting the invariant, and run it in CI permanently.
What is Race condition / TOCTOU?
a flaw where correctness depends on timing: the code checks a condition (balance sufficient, coupon unused, file absent) and acts on it later, leaving a window in which concurrent requests all pass the check before any of them acts. The result is duplicated effects the sequential logic 'proved' impossible.
Sources
- OWASP Top 10, the OWASP Foundation's standard awareness list of the most critical web application security risks: owasp.org, 2021
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command, MITRE's weakness entry for SQL injection and its mitigations: cwe.mitre.org, 2026
- OWASP Cheat Sheet Series — Secrets Management, OWASP's best-practice guide to storing, rotating and auditing secrets: cheatsheetseries.owasp.org, 2026
Frequently asked questions
My app is small. Can attackers really be bothered?
Concurrency scripts are generic and cheap — the same tool tests thousands of small apps. Small is not a defence; unpatched read-then-write is an invitation that costs the attacker nothing to accept.
Does an ORM transaction fix this automatically?
Only with the right isolation and structure — a transaction wrapping a read-then-write at default isolation can still interleave in many databases. The guarded atomic update is explicit and portable; do not rely on transaction vibes.
What about in-memory locks in a single-process app?
They work until you scale to two processes or the app restarts mid-flight — and generated code rarely implements them anyway. Prefer database-level atomicity and constraints, which hold regardless of deployment shape.
How do I find races that scanners miss?
Follow the money-shaped data: any field that only decreases (balance, stock, remaining uses) or any boolean that flips once (redeemed, claimed). Read those code paths for separate check and act steps — the gap is the race.
Related guides
- Web Cache Poisoning and Deception: Making Your CDN Serve the Attack to Everyone
- DOM Clobbering: How a Form Field Named 'config' Silently Replaces Your JavaScript Objects
- Math.random() Is Not a Token Generator: Weak Randomness in Reset Links and Session IDs
- Session Cookies Without HttpOnly, Secure and SameSite: What Each Missing Flag Costs You
- Second-Order Injection: The Payload That Waits in Your Database Until It Reaches a Sink
- What Happens When Your .env File Is Publicly Exposed?
- 7 Security Mistakes AI Coders Keep Making
- Supply-Chain Attacks in the AI-Coding Era
- Secret Hygiene: Stop API Key Leaks
- What Code Scanners Can't Find
- Bolt.new Pre-Deploy Security Checklist
- Cursor-Generated Code Review Checklist
Browse the full library on the guides index, run the checks in the launch audit, or compare plans on pricing.
Informational explainer, not a security guarantee. Scan your code free before every deploy.