← ELI5 · Nestor G Pestelos Jr

Software Engineering

What is a TOCTOU race condition?

The name is short for time-of-check to time-of-use. It's what happens when a program checks whether something is true, then acts as if it's still true — but something else changed it in between.

The name, unpacked

Time of check, then a gap, then time of use TIME OF CHECK the gap TIME OF USE

Two moments, with a real gap of time between them. The bug lives in the gap.

The parking spot

You see an empty spot, drive around the block, and another car takes it before you arrive You glance over: spot is empty you drive around the block to reach it another car pulls in first you arrive to nothing

You checked. You were right, at that moment. But acting on it took time, and the world kept moving during that time.

Why it's called a race

Your action and someone else's action are both racing to reach the same spot before the other one does the same shared thing (a spot, a file, a slot) your action the other action whichever one lands first wins — the loser acted on stale information

A "race condition" just means the outcome depends on timing that nobody controls.

What isn't a TOCTOU

A vending machine price tag that cannot change while you are buying is not a race, even though you checked it and then used it a price tag glued to the machine $1.50 nothing else can touch it you "check" it, then "use" it — but it was never going to change no gap, no other racer, no race

A real TOCTOU needs both: real elapsed time, and something else able to change the answer during it. A fixed answer read once — even described with "check, then use" words — is missing both.

Why this distinction matters

It's easy to describe ordinary code with race-condition language ("it looked available, then it wasn't") without an actual race existing underneath. The tell: run it again with the exact same input. A real race can come out differently each time. A fixed lookup gives the same answer every time — that's not a race, it's just a decision that was already made.

The fix: make it one step, not two

Instead of check then use as two separate steps with a gap, do check-and-claim as one single step nothing can interrupt TWO STEPS — A GAP EXISTS check use ONE STEP — NO GAP check-and-claim, together if the resource already changed, the single step fails cleanly instead of trusting a stale answer

Locking the spot the instant you check it — instead of checking, then driving over — is what closes the gap.

Sources: "CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition," Common Weakness Enumeration, MITRE Corporation. Longer, more technical version: Reference: TOCTOU Race Condition.

Back to top