Sub topic 13
Avoiding race conditions with atomic operations and scripts
This chapter assumes you know the token bucket algorithm, basic Redis commands, and that several application servers share one Redis instance behind a load balancer.
The race
The in-process TokenBucket from earlier is not safe once state lives in Redis. A naive limiter does three steps: read the token count, decide, then write the new count. Two servers can interleave these steps.
This is a read-modify-write race. The limiter allows more traffic than configured, and the error grows with concurrency, which is exactly when you need the limit most.
Options for atomicity
| Approach | How it works | Limits |
|---|---|---|
| Single atomic command | `INCR` on a fixed window key | Only fits counters, not refill logic |
| Optimistic transaction | `WATCH` the key, then `MULTI`/`EXEC`, retry on conflict | Extra round trips and retries under contention |
| Lua script | Redis runs the whole script without interleaving other commands | Script must stay short |
For a fixed window limiter, INCR alone is enough. It increments and returns the new value in one step, so you compare the result with the limit. Set EXPIRE when the result is 1. A crash between the two calls can leave a key with no expiry, so put both in a script if that matters.
A token bucket needs a read, a refill calculation, a decision, and a write. Use a Lua script.
The token bucket as a Redis script
Redis executes a script as one unit. No other client command runs in the middle. The script below does the refill, the check, and the write together.
-- KEYS[1] = bucket key
-- ARGV[1] = capacity, ARGV[2] = refill rate (tokens per second), ARGV[3] = cost
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local data = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(data[1])
local ts = tonumber(data[2])
if tokens == nil then
tokens = capacity
ts = now_ms
end
local elapsed_ms = math.max(0, now_ms - ts)
tokens = math.min(capacity, tokens + (elapsed_ms / 1000) * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now_ms)
redis.call('EXPIRE', key, math.ceil(capacity / rate) * 2)
return allowedThree details matter:
- The script reads time with
TIMEon the Redis server. All servers share one clock, so client clock skew cannot change the result. math.max(0, ...)protects against the clock moving backward.EXPIREremoves idle buckets. Aftercapacity / rateseconds an idle bucket is full again, so deleting it loses nothing. The factor of 2 adds margin.
Common errors
- Splitting the script into several calls. Reading with
HMGETin one call and writing in another brings the race back. - Using client time. Passing
nowfrom the application reintroduces skew between servers. - Slow scripts. Redis is single-threaded for command execution, so a long script blocks every client. Keep scripts to a few commands with no loops over large data.
- Cluster key placement. In Redis Cluster, every key a script touches must be passed in
KEYSand live in the same hash slot. A per-client bucket uses a single key, so this is satisfied.
Exercise
Two servers run a limiter that does GET, compares, then SET on a Redis counter. Why can it allow more requests than the limit, and what is the smallest change that fixes it for a fixed window counter?
Show answer
Both servers can GET the same value before either SETs, so both allow a request that only one should have been allowed. Replace the GET/SET pair with INCR, which increments and returns the new count atomically, then reject when the returned value exceeds the limit.
Exercise
Why does the Lua token bucket call redis.call('TIME') instead of accepting the current time as an argument?
Show answer
A time passed from the application depends on each server's clock, so skewed clocks give inconsistent refill calculations. Using the Redis server's clock gives every request the same time source.