CHECK-THEN-ACT

if (!exists) insert — still racy

L212 MINRACE CONDITIONS
PREDICT

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.”

▶ SIMULATION
THREAD A
saw: —
row: —
idle
DATABASE · users
(empty)
rows for alice@…: 0
compute() calls: 0
lock: free
THREAD B
saw: —
row: —
idle
✓ at most one row per email
SCHEDULE
01[A]A: SELECT id FROM users WHERE email = 'alice@example.com'
02[B]B: SELECT id FROM users WHERE email = 'alice@example.com'
03[A]A: if none: INSERT (email, token='tok-a1f3')
04[B]B: if none: INSERT (email, token='tok-b7c9')
Start of double insert scenario. 4 steps.
// 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));

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.

BREAK IT NOT YET

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

FIX IT NOT YET

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.

Mental model:

a check is a fact about the past. By the time you act on it, it is a guess. If the act depends on the check, the two must be one indivisible step, and only the owner of the state can make them one: a unique index, putIfAbsent, a compare-and-swap, or a lock held across both. Any if (!exists) in your code is a question you should have let the store answer.

IN PRODUCTION

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.

IN INTERVIEWS

“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.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: DEADLOCK →