CHECK-THEN-ACT
if (!exists) insert — still racy
Two signup requests for alice@example.com arrive one millisecond apart. The handler does SELECT by email and, if no row, INSERT. There is no unique index. How many rows can exist afterwards?
The handler looks, decides, then mutates. Look: SELECT by email. Decide: no row, so this is a new user. Mutate: INSERT. Two requests run the same three steps. If both look before either mutates, both decide “new” and both insert. The individual statements are atomic. The sequence is a TOCTOU bug one level up: the thing checked is the table’s state, and it changes between the check and the act.
The fix is to hand the decision to the thing that holds the state. A unique index makes the database refuse the second insert. putIfAbsent makes the map do the check and the put under one lock. Your code stops asking “does it exist?” and starts saying “insert this unless it exists.”
// signup handler, two requests for the same email
if (!db.find({ email })) { // check
db.insert({ email, token: newToken() }); // act — both requests get here
}
// same shape in memory:
if (!cache.containsKey(k)) cache.put(k, compute(k));// Collapse check + act into one atomic step.
INSERT INTO users (email, token) VALUES ($1, $2)
ON CONFLICT (email) DO NOTHING; -- needs a UNIQUE index
SELECT id FROM users WHERE email = $1; -- whoever won, use that row
// in memory:
cache.putIfAbsent(k, compute(k)); // may compute twice, stores once
cache.computeIfAbsent(k, compute); // computes once, under the map's lock The invariant strip tracks at most one row per email. In DOUBLE INSERT it goes red on the last step and the table shows both tokens. In FIX: UNIQUE INSERT the threads check in the same order, B’s insert writes 0 rows because of the conflict, and the strip stays green; notice compute() still ran twice. In FIX: LOCK, lock(email) has to be a lock every handler on every server shares, such as pg_advisory_xact_lock on a hash of the email. An in-process mutex only orders the requests that land on the same process.
Two signup requests for the same email. Each does a SELECT then a conditional INSERT. Order the four steps so the table ends with two rows for one email.
GOAL: both threads finish and two rows exist for the email
Rewrite getOrCreate so two concurrent calls for the same key leave exactly one row and both calls return that row. The grader tries every interleaving of the two callers’ database calls.
Signup and idempotency-key handlers, “create if missing” in every ORM, cache fill (get then set), coupon and invite redemption, mkdir after exists, os.path.exists before open. Symptoms: duplicate rows, double charges, double work.
“Is this code thread-safe?” with a containsKey / put pair on a ConcurrentHashMap. Say no, name the interleaving, and give the atomic replacement. Then say what the atomic version does not fix: putIfAbsent still computes twice; computeIfAbsent computes once but holds the bucket lock while it does.
USED IN
Chapters that build on this lesson.
- A ledger at scale: hot accounts, balances, shardingPayments
- Agentic payments: AI agents that pay, mandates, tokens and liabilityPayments
- Idempotency and moving money exactly oncePayments
- Integrating a payment provider: charges, verification, webhooksPayments
- Project: a double-entry ledger for a walletPayments
- Transfers and virtual accountsPayments
- Wallets and stored value: design and regulationPayments
- Test data, environments and flaky testsQA and Quality Engineering