AlgoViz

Race conditions and lost updates

medium 4 min

A race window opens when a decision uses an observation that another actor can invalidate.

Video lesson · Chapter 1 of 5

Two jobs disappear into one increment

0:00 / 3:12

Correctness: races on shared state

1:05Reel

Theory

Read or listen first. About 1 min.

What it is

An increment contains three actions. A worker reads a number, calculates the next value and writes it back. The calculation can already be stale when the write happens.

Follow the value of one counter

TimeWorker ARead 10Write 11Worker BRead 10Write 11Starting at 10, two writes leave 11.
A and B read 10. Each adds one privately and writes 11. The final value records only one increment.

Why it exists

Two completed requests should add two to the counter. A forced overlap lets you test that property on a schedule you can reproduce.

Words to know

Lost update
A write overwrites the effect of another successful operation that used the same starting value.

How it works

Step through the idea, or press Play.

Step 1 of 3

Read 10. Both increments begin at the same value.

Understand it

Worked example

Race conditions and lost updates in practice

Two workers read counter 10 and each writes 11. A barrier between the reads and writes makes the lost increment reproducible. An atomic increment or a lock around the whole update yields 12.

Related case

Sharing a worker pool safely

A thumbnail service has eight GPU slots. Two handlers both read “one free” before either records its claim. Which operation needs to be indivisible?

The workshop key rack
The workshop key rack1234567freeSeven machines are busy

Release once after completion.

Sources