Sub topic 12
Scaling out: shared counters in a store such as Redis
This chapter assumes you can read Python, know what INCR and EXPIRE do in Redis, and understand that a load balancer spreads requests across several application servers. It also assumes you have seen the fixed window and token bucket limiters from earlier chapters.
Why per-process state breaks
Every limiter so far kept its counters in a Python dictionary or object. That works for one process. In production, a load balancer sends each client's requests to many servers, and each server has its own memory.
Suppose the limit is 100 requests per minute and you run 10 servers. If requests are spread evenly, each server sees about 10 requests from a client and allows all of them. The client can send roughly 1,000 requests per minute and never be rejected. The effective limit grows with the number of servers, and it changes whenever you scale up or down.
There are three ways to fix this:
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Divide the limit | Each of N servers enforces limit/N | No network calls | Wrong when load is uneven or N changes |
| Sticky routing | The load balancer sends one client to one server | Keeps local state | Uneven load, and a server failure loses state |
| Shared store | All servers read and write counters in one place | Accurate global limit | Adds latency and a dependency |
Most designs choose the shared store. Redis is the usual choice because it keeps data in memory, runs commands in a single thread, and expires keys by itself.
The shape of a Redis-backed limiter
Each application server stays stateless. For every request it builds a key from the client identity and the algorithm's time unit, asks Redis to update that key, and acts on the result.
Both servers touch the same key, so the count is global. The servers hold nothing between requests, so you can add or remove them freely.
A fixed window limiter on Redis
The fixed window counter maps well to Redis. The key includes the window index. A new window gets a new key, and old keys expire.
import time
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def allow(client_id, limit, window, now=None):
"""Return True if client_id is within `limit` requests per `window` seconds."""
now = time.time() if now is None else now
index = int(now // window)
key = f"rl:{client_id}:{index}"
pipe = r.pipeline(transaction=True) # sent to Redis as MULTI ... EXEC
pipe.incr(key)
pipe.expire(key, window * 2)
count, _ = pipe.execute()
return count <= limit
if __name__ == "__main__":
print([allow("alice", limit=3, window=60) for _ in range(5)])
# [True, True, True, False, False]Three details matter here.
- The key contains the window index. You never reset a counter. When the index changes, the next INCR creates a fresh key at 1.
- INCR and EXPIRE travel together. If you call INCR, and then your process crashes before EXPIRE, the key lives forever. A transactional pipeline sends both commands as one unit, so Redis runs them back to back with no other client's command in between.
- The TTL is twice the window. The key only needs to live until its window ends. The extra time is a safety margin, and it keeps the previous window's key available if you later move to a sliding window counter.
This code increments the counter even for rejected requests. That is fine for a fixed window, because the count only matters within its window. It would be wrong for a limiter that should charge only for allowed requests.
Why you should not read, then write
A tempting version looks like this:
count = int(r.get(key) or 0)
if count >= limit:
return False
r.set(key, count + 1)Two servers can both read 99, both decide the request is allowed, and both write 100. The limit is exceeded and no error appears. The fix is to let Redis do the read-modify-write in one command (INCR) or one script. The next chapter covers this in detail, including how to run the token bucket as a single Lua script. For now, the rule is that the check and the update must be one atomic step in the store.
Designing keys
Key design affects memory, speed, and correctness.
- Namespace the key. Use a prefix such as
rl:and include the limit's name, for examplerl:login:alice:28. Different limits for the same client must not share a counter. - Keep keys short and bounded. A raw URL path or user-agent string in the key lets an attacker create unlimited keys. Use the route template (
/users/{id}), not the concrete path. - Always set a TTL. Without expiry, memory grows with every client you have ever seen.
- Estimate memory. A small Redis key with an integer value takes on the order of 100 bytes with overhead. Ten million active clients, one key each, is about 1 GB. The sliding window log needs one entry per request, so it costs far more.
Latency and load
The limiter adds a network round trip to every request. In one data center this is usually well under a millisecond, but it sits on the critical path of every call. Consider these points:
- Set a short client timeout, such as 5 to 20 ms, and decide in advance what happens when it fires. The failure modes chapter covers that decision.
- Reuse connections with a pool. Opening a connection per request costs far more than the command.
- Send one script call or one pipeline per request, not several separate commands. Each extra round trip adds directly to latency.
- Watch for hot keys. A single abusive client, or a global limit on one key, sends all its traffic to one Redis shard.
Scaling Redis itself
A single Redis node handles many thousands of simple commands per second, which is enough for many services. Beyond that, you shard.
In Redis Cluster, keys are spread over hash slots, and one multi-key command must touch keys in the same slot. If one limiter check uses several keys, such as the current and previous windows of a sliding window counter, put a hash tag in braces so they land together: rl:{alice}:28 and rl:{alice}:27. Only the text inside the braces is hashed.
Replication adds another issue. Replicas copy data asynchronously. If the primary fails and a replica is promoted, the last few counter updates may be lost, so clients briefly get slightly more than their limit. For rate limiting this is usually acceptable. Do not read counters from replicas, because they lag behind.
Reducing round trips with local approximation
When Redis becomes the bottleneck, you can trade accuracy for load. Each server keeps a local counter and syncs to Redis every few hundred milliseconds, or takes a batch of tokens (say 10 at a time) from a shared bucket and spends them locally. The global limit is then enforced loosely: a client can exceed it by roughly the batch size times the number of servers. Use this only when the limit protects capacity, not when it enforces a contract or a billing quota.
Common errors
- Divided limits in disguise. Configuring "100 per minute" in each server's local memory and calling it global.
- Missing TTL. A crash between INCR and EXPIRE, or a forgotten EXPIRE, leaks keys.
- Unbounded key cardinality. Putting free-form input in the key.
- Reading from replicas. Stale counts let requests through.
- Treating Redis as always available. Every limiter call needs a timeout and a defined fallback.
Exercise
Your service runs on 8 servers behind a load balancer. Each server enforces "60 requests per minute per user" using an in-process dictionary. A user's requests are spread evenly. About how many requests per minute can this user send before any server rejects one, and what is the smallest change that makes the limit global?
Show answer
Each server allows 60 per minute, so the user can send about 8 × 60 = 480 requests per minute without a rejection. The smallest change is to move the counter into a shared store such as Redis, with a key like rl:user:window_index, updated by one atomic INCR (paired with an EXPIRE in the same transaction). All servers then increment the same counter.
Exercise
A teammate writes a limiter that does GET on the counter key, compares it with the limit, then does SET with count + 1. Under load, users exceed the limit slightly. Why does this happen, and how would you fix it?
Show answer
Two servers can read the same value (for example 99) before either writes, so both allow the request and both write 100. The read, check, and write are not atomic. Fix it by using a single atomic command such as INCR and comparing its returned value to the limit, or by running the whole check and update as one Redis Lua script.