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.
The counter is 99 of 100, and two workers each read 99 and approve. What must change?
Run the check and update atomically against shared state, so only the first worker consumes the last slot and the second receives a throttle decision.
Use this as a guide for self review; written answers are not graded.Keep in mind
- The quota decision and state mutation must be atomic.
- Counter expiry and store-failure policy are part of correctness.