Sub topic 13
Avoiding race conditions with atomic operations and scripts
This chapter assumes you know the token bucket and fixed window algorithms from earlier chapters. It also assumes you can read basic Python and have used Redis commands such as GET, SET, and INCR. Lua is introduced only as far as the example needs.
Why a correct algorithm can still be wrong
Once limiter state moves into a shared store, many application servers read and write the same counters at the same time. An algorithm that is correct in one process can then admit more traffic than the limit allows.
The usual cause is a read-modify-write sequence made of separate steps:
- Read the current count or token balance.
- Decide whether the request fits.
- Write the new value.
If two servers both finish step 1 before either reaches step 3, they decide from the same stale value. Both spend the same token.
import redis
r = redis.Redis(decode_responses=True)
def allow_naive(key, limit):
"""BROKEN under concurrency: read, decide, and write are separate steps."""
count = int(r.get(key) or 0)
if count >= limit:
return False
r.set(key, count + 1)
return TrueSuppose the limit is 10 and the stored count is 9. Two servers each read 9, each see room for one more request, and each write 10. Both requests pass, so 11 requests were admitted. With dozens of servers and a burst of traffic, the overshoot can be large. It is also the hardest to see exactly when the limiter matters most, during a spike.
Option 1: a single atomic command
An operation is atomic if no other client can observe or change the data halfway through it. Redis executes commands one at a time, so every individual command is atomic.
For a fixed window counter, INCR does the whole read-modify-write inside Redis. It increments the value and returns the new one, so the decision comes from the returned number and not from a stale read.
import time
import redis
r = redis.Redis(decode_responses=True)
def allow_fixed_window(key, limit, window, now=None):
now = time.time() if now is None else now
index = int(now // window)
counter_key = f"rl:{key}:{index}"
pipe = r.pipeline(transaction=True) # wraps the commands in MULTI/EXEC
pipe.incr(counter_key)
pipe.expire(counter_key, window * 2)
count, _ = pipe.execute()
return count <= limitTwo details matter here.
- Each caller gets a distinct value from
INCR. Only the firstlimitcallers receive a count at or below the limit, however many servers are racing. INCRandEXPIREare separate commands. If a client crashed between them, the key would never expire and would leak memory.MULTI/EXECmakes the pair run together without other clients' commands in between.
This approach counts rejected requests too, because INCR runs before the check. That is usually acceptable for a fixed window, but it means a client that keeps retrying holds its own counter above the limit until the window ends.
Option 2: optimistic locking with WATCH
Some algorithms need more than one value. A token bucket stores a token count and a timestamp, and no single command updates both. Redis offers WATCH for this case. The client watches the key, reads it, computes the new state, and sends a MULTI/EXEC transaction. If another client changed the key after the WATCH, the transaction is aborted and the client retries.
This is correct, but it has costs:
- Each attempt needs several network round trips.
- Under contention many attempts fail and retry, so latency rises just when load is highest.
- You must write the retry loop and decide when to give up.
For a hot key, such as a popular API key during a burst, optimistic locking performs poorly.
Option 3: a server-side script
The better fit for multi-field algorithms is a Lua script. Redis runs a script as one unit: no other command runs while it executes. The script can read the bucket, refill it, decide, and write the result, all in one round trip.
Save the token bucket script from this tutorial as token_bucket.lua:
-- 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 allowedThen call it from Python. register_script computes the script's SHA-1 hash and sends EVALSHA. If Redis has not cached the script, for example after a restart, the client falls back to sending the full text.
from pathlib import Path
import redis
r = redis.Redis(decode_responses=True)
token_bucket = r.register_script(Path("token_bucket.lua").read_text())
def allow(key, capacity=5, refill_rate=1, cost=1):
result = token_bucket(keys=[f"rl:bucket:{key}"], args=[capacity, refill_rate, cost])
return result == 1
print([allow("alice") for _ in range(7)]) # first 5 True, then FalseWhat the script gets right
- No interleaving. Between the
HMGETand theHSET, no other client can touch the bucket. - One time source. The script reads
TIMEfrom the Redis server, so every application server shares one clock. This avoids skew between servers, which a later chapter covers. - Bounded memory. The
EXPIREis set to twice the time a full refill takes. An idle bucket would be full anyway, so deleting it loses nothing. - One round trip. The client sends one request and gets one answer.
Rules for writing limiter scripts
- Keep scripts short. Redis is single-threaded for command execution, so a slow script blocks every client. Avoid loops over large collections. A sliding window log that trims thousands of entries is a risk here.
- Declare every key in
KEYS. In Redis Cluster, all keys a script touches must hash to the same slot. A per-client key satisfies this. A script that also updates a global counter does not, unless you use hash tags such as{alice}in the key names. - Pass values as arguments. Do not build the script text per call, because each distinct text is cached separately.
- Return simple values. Integers, or a small array such as
{allowed, remaining, retry_after_ms}, are enough for building response headers.
Choosing between the options
| Approach | Round trips | Fits | Main risk |
|---|---|---|---|
| Single command (`INCR`) | 1 | Fixed window counter | Only works for one-value state |
| `WATCH` and retry | 2 or more per attempt | Rare multi-field updates | Retry storms on hot keys |
| Lua script | 1 | Token bucket, sliding window counter | Slow scripts block Redis |
Common mistakes
- Doing
GETthenSETfrom the application and assuming Redis makes it safe. Redis only makes each command atomic, not your sequence. - Setting a time-to-live in a separate, unprotected call after
INCR, which can leak keys on a crash. - Taking
nowfrom each application server's clock and writing it into shared state. Servers whose clocks differ will refill the bucket inconsistently. - Testing only with one client. Race conditions appear only under concurrency, so test with many parallel workers hitting one key and assert that the number admitted never exceeds the limit plus capacity.
Exercise
A limiter stores a token bucket as two Redis keys, tokens and ts. Each server does GET tokens, GET ts, computes the refill in Python, and then does SET tokens and SET ts. The limit is 100 requests per second, but load tests show about 130 requests per second getting through. Why does this happen, and what is the smallest change that fixes it?
Show answer
The four steps are separate commands, so two servers can read the same token balance, both approve a request, and both write back a balance that spent only one token. Extra requests slip through under concurrency. The smallest fix is to move the whole read, refill, decide, and write sequence into one Lua script, with the bucket in a single hash key, and call it with EVALSHA. Redis then runs it without interleaving, and it also gives every server the same clock through TIME.
Exercise
Why is INCR followed by a separate EXPIRE call risky, and how do you remove the risk without using a script?
Show answer
If the client crashes or loses its connection between the two calls, the counter exists without a time-to-live and is never deleted. This leaks memory and can block the client permanently once it passes the limit. Sending both commands in a MULTI/EXEC transaction, for example pipeline(transaction=True) in redis-py, makes them run together.