TOCTOU and Concurrent Request Interleavings
Lay out requests A and B to distinguish duplicate gift-card claims from wallet updates that overwrite each other.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
A gift card should add its value to a wallet once. Request A checks that the card is unused. Before A marks it used, request B checks the same thing. Both may now believe they can continue.
| Moment | Request A | Request B |
|---|---|---|
| 1 | Reads unused | |
| 2 | Reads unused | |
| 3 | Credits the wallet | |
| 4 | Tries to credit the wallet too |
This is a race condition: the overlap matters to the result. TOCTOU stands for time of check to time of use—the state can change between a check and its effect.
We'll inspect the final card, wallet, and records. Two successful responses do not by themselves tell us whether credit was duplicated or one update was lost.
Name the invariant before scheduling requests
For a one-time gift card, at most one successful redemption may consume the card, and the wallet must receive exactly the authorized credit once. For two different valid cards, both accepted credits must appear in the wallet and ledger. These are related but different invariants. A system can duplicate redemption records while losing one balance update.
// Unsafe original redemption outline.
const card = await cards.findByCode(code);
if (!card || card.used) throw invalidCard();
const wallet = await wallets.findById(actor.walletId);
await wallets.setBalance(wallet.id, wallet.balanceMinor + card.valueMinor);
await cards.markUsed(card.id, actor.userId);
await audit.insertRedemption(card.id, wallet.id);
return { ok: true };
List the reads and writes separately. Locate commit boundaries, transaction wrappers, locks, conditional predicates, and uniqueness constraints. JavaScript being single-threaded in one process does not serialize asynchronous database operations across requests or replicas.
Follow two requests through the same finite right.
Check. A and B can pass the same read before either writes.
A: used == false
B: used == false
Effect. Absolute writes may lose a credit; later reads may permit duplicate value.
A reads 100 -> writes 120
B reads 100 or 120 -> writes 120 or 140
Mark. Marking used after the effects does not retroactively serialize them.
await cards.markUsed(card.id);
await audit.insertRedemption(card.id);
Review question: Explain the schedule and durable outcome, not just the number of requests.