Sub topic 12
Scaling out: shared counters in a store such as Redis
This chapter assumes you know the fixed window and token bucket algorithms from earlier chapters. It also assumes you can read basic Python and know what a key-value store such as Redis is.
Why per-process state breaks
The limiters so far keep their counters in a Python dictionary. That works with one process. Behind a load balancer, each server has its own dictionary. A limit of 100 requests per minute then becomes 100 per minute per server. With 10 servers, a client can send up to 1,000.
You have three ways to handle this:
| Approach | How it works | Main drawback |
|---|---|---|
| Split the limit | Each of N servers enforces limit / N | Wrong when traffic is uneven or N changes |
| Sticky routing | The load balancer sends each client to one server | Breaks on failover and rebalancing, and creates hot servers |
| Shared store | All servers read and write the same counters | Adds a network call and a new dependency |
Most production limiters use the shared store. Redis is a common choice because it is fast, holds data in memory, and supports key expiry.
A shared fixed window limiter
The key for each counter combines the client identity and the window index. Redis INCR adds one to the counter and returns the new value. If the key does not exist, Redis creates it with the value 0 first. EXPIRE removes old windows so memory does not grow without bound.
import time
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def allow(client_id, limit, window):
index = int(time.time() // window)
key = f"rl:{client_id}:{index}"
pipe = r.pipeline(transaction=True) # sends MULTI ... EXEC
pipe.incr(key)
pipe.expire(key, window * 2)
count, _ = pipe.execute()
return count <= limit
print([allow("alice", limit=3, window=60) for _ in range(5)])Running this against a local Redis server prints [True, True, True, False, False]. The exact output differs only if the minute rolls over during the call.
The code sends INCR before checking the limit. It does not read the count and then write it back. Two servers that both read 99 and both write 100 would each admit a request that should have been rejected. A single INCR is atomic on the Redis server, so concurrent callers each get a distinct value.
Design points
- Key naming. Prefix keys (
rl:) and include the client ID, so limiter keys never collide with other data. - Expiry. Set a time to live (TTL) on every key. Without it, one key per client per window stays in memory forever.
- Round trips. Each check costs one network round trip, so keep Redis close to the app servers and reuse connections.
- Hot keys. One very busy client maps to one key on one Redis node. Sharding spreads different clients across nodes but cannot split a single key.
- Multi-step algorithms. Token bucket and sliding window counter need a read, a calculation, and a write.
INCRalone cannot do that. The next chapter covers how to make those steps atomic.
Exercise
A service runs on 4 servers, each with an in-memory fixed window limiter set to 100 requests per minute per client. What is the most requests per minute a single client can get through if the load balancer spreads its requests evenly, and how does moving the counter into Redis change it?
Show answer
Each server admits up to 100, so the client can send up to 400 requests per minute. With a shared Redis counter, all four servers increment the same key, so the total across the fleet stays at 100 per window. The limit still allows a boundary burst, as fixed windows always do.