LESSON 05 · Concurrency

Make each decision atomic

A read, check, and write sequence can approve too many simultaneous requests.

SYSTEM VIEW

The decision path

Diagram view
Swipe or scroll to explore the full diagram
One slot cannot be spent twiceConcurrent workers must check and change shared state as a single atomic decision.One slot cannot be spent twicearrivesarrivesfirstnextWorker Arequest oneWorker Brequest twoAtomic decisioncheck + mutate togetherAllowconsumes slot 100Rejectcounter is fullA separate read, check, then write loses the race at the threshold.
Concurrent workers must check and change shared state as a single atomic decision.
Trace the quota decision before a request reaches the API.
THE IDEA

How it works

Two limiter workers can both read a counter below the threshold and both approve. With a limit of 100 and a counter at 99, the race runs like this: worker A reads 99, worker B reads 99, A writes 100, B writes 100. Two requests passed, so 101 were admitted while the counter says 100. The check and counter change must form one atomic operation, which no other request can interleave with. When one process owns a counter, a local atomic variable is enough; the problem appears once workers share state.

In Redis, INCR is atomic and returns the new value, so a fixed window can increment first and reject when the result exceeds the limit. A token bucket reads and writes several fields, so it needs a short Lua script, which Redis runs without interleaving other commands. Keep scripts short, because Redis executes commands one at a time and a slow script delays everyone. Calling increment after a separate read does not solve the race.

Use expiry to reclaim counters, but set it consistently with the algorithm. If a process dies between INCR and a separate EXPIRE, the key never expires and that client stays blocked, so set both together. Preserve enough state for the chosen window or token refill. Monitor store latency because every enforced request may depend on this path. If the store fails, an explicit fail-open (allow) or fail-closed (reject) policy should reflect the endpoint: availability may dominate for low-risk reads, while expensive or abuse-sensitive operations may need protection.

DECISION POINT

The counter is 99 of 100, and two workers each read 99 and approve. What must change?

Write a sentence or two to unlock the guidance. Committing first is what makes it stick.

Keep in mind

  • The quota decision and state mutation must be atomic.
  • Counter expiry and store-failure policy are part of correctness.
CHECK YOUR UNDERSTANDING

Put it into practice.

1 OF 3
DiagnoseQUESTION 01

A 1,000-per-minute limit admits exactly 1,000 with one worker, but about 1,040 with eight workers sharing one Redis counter. What is the likely bug?

Choose an answer. You’ll see the explanation once you get it right.

Next lesson

0 of 3 checkpoints answered correctly to complete this lesson.