Race Conditions: a Double Spend
A gift card holds 100 credits. The redeem endpoint checks the balance, then subtracts. Send it one request, and it works. Send it five requests in the same instant, and all five may read "100", all five pass the check, and the card pays out 500. Web servers handle requests concurrently, on threads, processes or many machines, and any code that does check, then act on shared state without making the two steps one atomic operation has a window where another request can slip in. Attackers widen the odds by sending requests together (HTTP/2 lets a tester deliver many requests in a single packet, the "single-packet attack"). Races turn up in redemptions, transfers, coupon use, likes and votes, sign-up limits and file processing. This lesson reproduces a double spend against a threaded toy server in your sandbox, then fixes it twice: with a lock, and with the method that also works across many servers, an atomic conditional update in the database.
Definitions
- Race condition: the result depends on the timing of concurrent operations. TOCTOU (time of check to time of use): the state checked is no longer the state used.
- Critical section: code that must not run concurrently with itself for the same resource.
- Lock / mutex: lets one thread at a time into a critical section. Works only inside one process.
- Atomic conditional update: one database statement that checks and changes at once, such as
UPDATE cards SET balance = balance - 100 WHERE id = 7 AND balance >= 100; the database's own locking makes it safe across any number of servers. Alternatives:SELECT … FOR UPDATEin a transaction, serializable isolation, unique constraints, optimistic locking with a version column. - Idempotency key: a client-supplied unique id per intended operation; the server performs each key once.
The double spend
The server below is a threaded WSGI app on 127.0.0.1 in your sandbox. To make the race window easy to hit and the transcript repeatable, the vulnerable handler waits 0.3 s between reading the balance and writing it, standing in for a slow database round trip or a payment-provider call. Five curl processes start at the same moment; their answers are collected and sorted so the order of arrival doesn't change the output.
cat > card.py <<'PY'
import json, sqlite3, sys, threading, time
from socketserver import ThreadingMixIn
from wsgiref.simple_server import make_server, WSGIServer, WSGIRequestHandler
MODE = sys.argv[1] # vulnerable | lock | atomic
db = sqlite3.connect("cards.db", check_same_thread=False, isolation_level=None)
db.executescript("DROP TABLE IF EXISTS cards; CREATE TABLE cards (id INTEGER PRIMARY KEY, balance INTEGER);"
"INSERT INTO cards VALUES (7, 100);")
lock = threading.Lock()
paid_out = []
class Threaded(ThreadingMixIn, WSGIServer):
daemon_threads = True
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def redeem(amount):
if MODE == "atomic":
cur = db.execute("UPDATE cards SET balance = balance - ? WHERE id = 7 AND balance >= ?", (amount, amount))
time.sleep(0.3) # the same slow step, after the atomic decision
return cur.rowcount == 1
balance = db.execute("SELECT balance FROM cards WHERE id = 7").fetchone()[0] # check
if balance < amount:
return False
time.sleep(0.3) # slow work between check and use
db.execute("UPDATE cards SET balance = ? WHERE id = 7", (balance - amount,)) # act
return True
def app(environ, start_response):
if environ["PATH_INFO"] == "/redeem":
if MODE == "lock":
with lock:
ok = redeem(100)
else:
ok = redeem(100)
if ok:
paid_out.append(100)
body = {"redeemed": ok}
else:
body = {"balance": db.execute("SELECT balance FROM cards WHERE id = 7").fetchone()[0], "paid_out": sum(paid_out)}
start_response("200 OK", [("Content-Type", "application/json")])
return [json.dumps(body).encode() + b"\n"]
make_server("127.0.0.1", 8000, app, server_class=Threaded, handler_class=Quiet).serve_forever()
PY
for mode in vulnerable lock atomic; do
rm -f cards.db
python3 card.py $mode &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/state && break; sleep 0.1; done
for n in 1 2 3 4 5; do curl -s -X POST http://127.0.0.1:8000/redeem > "r$n.txt" & done
wait $(jobs -p | tail -n 5)
printf '%-10s answers: %s | final: %s\n' "$mode" "$(sort r*.txt | uniq -c | tr -s ' \n' ' ')" "$(curl -s http://127.0.0.1:8000/state)"
kill %1; wait 2>/dev/null
donevulnerable answers: 5 {"redeemed": true} | final: {"balance": 0, "paid_out": 500}
lock answers: 4 {"redeemed": false} 1 {"redeemed": true} | final: {"balance": 0, "paid_out": 100}
atomic answers: 4 {"redeemed": false} 1 {"redeemed": true} | final: {"balance": 0, "paid_out": 100}
In the vulnerable mode all five requests read a balance of 100 before any of them wrote, so all five succeeded: 500 credits paid out from a 100-credit card, and the database still shows a balance of 0, so nothing looks wrong in the card table. With the lock, the requests went through the critical section one by one: the first succeeded, the other four saw 0. With the atomic update, the database made the decision: exactly one UPDATE matched balance >= 100, and the rest changed no row. The lock works only because this demo runs one process; production apps run many workers on many machines, which is why the database-level fix is the one to use.
How race conditions are detected
- Testing (in scope, on a test environment if possible, since successful races change real data): find operations with a limit (redeem once, withdraw up to the balance, one vote, one sign-up per invite) and send 10–30 identical requests at once. Burp Repeater's "send group in parallel" (single-packet attack over HTTP/2) and Turbo Intruder make the timing tight; then compare the side effects with the limit.
- Code review: read-then-write sequences on shared state (
if balance >= x: balance -= x),get_or_createwithout a unique constraint, counters updated in application code (count = count + 1after aSELECT), file checks followed by file use (os.path.existsthenopen). - Monitoring and reconciliation: ledgers that don't balance (paid out > loaded), duplicate redemptions of one code, bursts of identical requests from one session within milliseconds. The demo's
paid_outversusbalancemismatch is what a nightly reconciliation job would flag.
How races are fixed
- Make check and act one atomic step in the database: conditional
UPDATE … WHERE balance >= ?and check the affected row count; or a transaction withSELECT … FOR UPDATE. - Unique constraints for "at most once" rules (
UNIQUE(account_id, coupon_code)), and handle the constraint error as "already used". - Idempotency keys for payment-like operations, stored with a unique constraint.
- Keep slow work (calls to payment providers, e-mails) outside the critical section, after the atomic decision, as the atomic mode does.
- Locks (in-process, or distributed with care) only where the database can't express the rule.
Pitfalls
- Assuming the framework serialises requests: most run them in parallel; even single-threaded async servers interleave at every
await. - Fixing with a check in the front end ("disable the button after one click").
- Read-committed isolation (the default in PostgreSQL and many others) does not prevent this check-then-act race inside a transaction; you need row locks, conditional updates or serializable isolation.
Practice
1. Rewrite a "like" endpoint that does SELECT likes …; UPDATE posts SET likes = :n + 1 so it can't lose or double-count likes.
Store likes as rows with UNIQUE(post_id, user_id) (one like per user, enforced by the database) and count them, or at least use UPDATE posts SET likes = likes + 1 WHERE id = ? so the increment is atomic.
2. Why didn't the vulnerable run's card table show anything wrong?
Each request wrote balance - 100 computed from the same stale read, so the final balance is 0, as if one redemption happened. The damage is only visible by comparing the payouts (or ledger entries) with the balance, which is why reconciliation is a key detection control for races.
Test yourself
What is the root cause of the double spend?
- A slow database
- Check and act are separate steps on shared state, so concurrent requests all pass the check before any of them acts
- Missing authentication
- Integer overflow
Why is the in-process lock not enough in production?
- Locks are slow
- Production runs many workers and servers; a lock in one process doesn't stop requests handled by another
- Python has no locks
- Locks leak memory
What makes UPDATE cards SET balance = balance - 100 WHERE id = 7 AND balance >= 100 safe?
- It is fast
- The database checks and updates in one atomic statement; only one concurrent request can match
- It uses an index
- It is parameterised
How do testers make races likely to trigger?
- Send one request slowly
- Send many identical requests at the same instant (e.g. Burp's parallel group / single-packet attack)
- Use GET
- Clear cookies