Sub topic 16
Layering limits: per-second bursts, per-day quotas, global caps
This chapter assumes you know the fixed window counter and token bucket algorithms from earlier chapters. It also assumes you know how Redis scripts make updates atomic, and how a limiter key identifies a client.
Why one limit is not enough
A single rule such as "100 requests per minute" protects against one kind of problem. Real services face several kinds at once:
- A client sends 100 requests in one second. The average is fine, but the spike overloads a downstream database.
- A client stays under every short-term limit but sends steady traffic for 24 hours. This costs money or exhausts a paid allowance.
- Thousands of well-behaved clients each send a modest load, and together they exceed what the service can handle.
Each problem has a different time scale and a different owner. Layering means running several independent limits on the same request. The request is allowed only if every layer allows it.
The three common layers
| Layer | Typical algorithm | Key | Protects against | Typical rejection |
|---|---|---|---|---|
| Burst limit | Token bucket, per second | client | Spikes that overload dependencies | 429, retry in about a second |
| Quota | Fixed window, per day or month | client or plan | Overuse of a paid or fair-share allowance | 429, retry at the next window |
| Global cap | Token bucket, whole service | none (one shared key) | Total load beyond capacity | 429 or 503, retry soon |
The burst limit is a short window with a small capacity. The quota is a long window with a large count. The global cap uses a single key that every request touches.
Pick the algorithm for each layer from its job. A daily quota usually accepts the fixed window's boundary burst because the window is huge and the client sees a clear "resets at midnight UTC" rule. A burst limit benefits from the token bucket's smooth refill.
Evaluating layers: check everything, then charge
The main trap is charging layers one at a time. Suppose the burst layer passes and spends a token, then the daily quota rejects the request. The client lost a burst token and received nothing. Repeated rejections drain the burst allowance for no benefit.
Use two phases:
- Check every layer without changing state.
- If all layers pass, charge all of them. Otherwise charge none.
Evaluate all layers on rejection, not just the first failing one. You need every layer's wait time to build an honest Retry-After value. If the burst layer says "wait 1 second" but the daily quota is exhausted, a 1-second hint sends the client into a second, pointless 429. Report the layer with the longest wait.
A single-process layered limiter
This example takes the time as an argument so you can run it deterministically. It has a per-client burst bucket, a per-client daily quota, and a global bucket.
class Bucket:
"""Token bucket with an injectable clock. Not thread-safe."""
def __init__(self, capacity, rate):
self.capacity = capacity
self.rate = rate
self.tokens = float(capacity)
self.last = None
def _refill(self, now):
if self.last is not None:
elapsed = max(0.0, now - self.last)
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
self.last = now
def wait(self, now, cost=1):
"""Seconds until `cost` tokens are available (0 if available now)."""
self._refill(now)
missing = cost - self.tokens
return 0.0 if missing <= 0 else missing / self.rate
def take(self, cost=1):
self.tokens -= cost
class Quota:
"""Fixed window counter per key."""
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.state = {} # key -> (window_index, count)
def _count(self, key, now):
index = int(now // self.window)
window_index, count = self.state.get(key, (index, 0))
return count if window_index == index else 0
def wait(self, key, now):
if self._count(key, now) < self.limit:
return 0.0
return self.window - (now % self.window)
def take(self, key, now):
index = int(now // self.window)
self.state[key] = (index, self._count(key, now) + 1)
class LayeredLimiter:
def __init__(self, burst_capacity, burst_rate, daily_limit,
global_capacity, global_rate):
self.burst_capacity = burst_capacity
self.burst_rate = burst_rate
self.buckets = {}
self.daily = Quota(daily_limit, 86400)
self.global_bucket = Bucket(global_capacity, global_rate)
def check(self, key, now):
"""Return (allowed, reason, retry_after_seconds)."""
bucket = self.buckets.setdefault(
key, Bucket(self.burst_capacity, self.burst_rate))
waits = {
"burst": bucket.wait(now),
"daily": self.daily.wait(key, now),
"global": self.global_bucket.wait(now),
}
failing = {name: w for name, w in waits.items() if w > 0}
if failing:
reason = max(failing, key=failing.get)
return False, reason, failing[reason]
bucket.take()
self.daily.take(key, now)
self.global_bucket.take()
return True, None, 0.0
limiter = LayeredLimiter(burst_capacity=3, burst_rate=1, daily_limit=5,
global_capacity=100, global_rate=100)
for t in [0, 0, 0, 0, 1, 2, 3]:
print(t, limiter.check("alice", float(t)))The output shows three allowed requests at time 0, a burst rejection with a 1.0 second wait, allowed requests at times 1 and 2 (the fifth of the day), and a daily rejection at time 3 with a wait of 86397.0 seconds.
Ordering and key choice
Because all layers are read before any is charged, order does not affect correctness here. Order still matters for cost. Check the cheapest, most local layers first when you short-circuit in a distributed system. The per-client layers are usually cheaper than a contended global key.
Layers can use different keys. A common setup is a burst limit per API key, a quota per account (shared by all of that account's keys), and one global cap. Choose the key for each layer based on who should share the allowance.
Layering in a distributed store
In Redis, the check-then-charge logic must run in one atomic script. Otherwise two servers can both see "one token left" and both charge it. This script reads three keys, then writes only when every layer passes.
-- KEYS[1] = per-client burst bucket (hash)
-- KEYS[2] = per-client daily counter (string, key name includes the date)
-- KEYS[3] = global bucket (hash)
-- ARGV: 1 burst_cap, 2 burst_rate, 3 daily_limit, 4 daily_ttl_s,
-- 5 global_cap, 6 global_rate
local t = redis.call('TIME')
local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local function refilled(key, capacity, rate)
local d = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(d[1])
local ts = tonumber(d[2])
if tokens == nil then
return capacity
end
return math.min(capacity, tokens + math.max(0, now_ms - ts) / 1000 * rate)
end
local burst = refilled(KEYS[1], tonumber(ARGV[1]), tonumber(ARGV[2]))
local global = refilled(KEYS[3], tonumber(ARGV[5]), tonumber(ARGV[6]))
local used = tonumber(redis.call('GET', KEYS[2]) or '0')
local daily_limit = tonumber(ARGV[3])
if burst >= 1 and global >= 1 and used < daily_limit then
redis.call('HSET', KEYS[1], 'tokens', burst - 1, 'ts', now_ms)
redis.call('EXPIRE', KEYS[1], math.ceil(tonumber(ARGV[1]) / tonumber(ARGV[2])) * 2)
redis.call('HSET', KEYS[3], 'tokens', global - 1, 'ts', now_ms)
if redis.call('INCR', KEYS[2]) == 1 then
redis.call('EXPIRE', KEYS[2], tonumber(ARGV[4]))
end
return {1, 0, 0, 0}
end
return {0, burst < 1 and 1 or 0, used >= daily_limit and 1 or 0, global < 1 and 1 or 0}On rejection the script returns one flag per failing layer and writes nothing. The caller can then compute wait times and the Retry-After value.
Note the following:
- Redis Cluster: all keys in one script must hash to the same slot. A per-client key and a global key usually will not. Either use hash tags (which puts everything on one shard) or split the global cap into a separate step.
- Hot global key: one key receiving every request becomes a bottleneck. Common options are giving each node a local share of the global budget and refilling it in batches, or accepting that the global cap is approximate.
- Daily key naming: the application computes the date in the key name, so clients with skewed clocks near midnight can pick different keys. Use UTC and keep application clocks synchronized.
Common errors
- Charging layers one by one, which drains earlier layers on rejection.
- Returning the
Retry-Afterof the first failing layer instead of the longest. - Setting the burst limit above the downstream capacity, so the layer exists but protects nothing.
- Setting the global cap lower than the sum of guaranteed per-client quotas. Paying clients then hit the cap before their quota.
- Not telling clients which layer rejected them. A
dailyrejection needs a different client response than aburstone.
Exercise
A client has a burst bucket (capacity 10, 5 tokens per second) and a daily quota of 1000. It has used 1000 requests today, and its burst bucket is empty. A limiter reports only the first failing layer, checked in burst-then-daily order. What Retry-After does it send, and what does the client experience?
Show answer
It sends about 0.2 seconds, the time to refill one token. The client retries, passes the burst check, and is then rejected by the daily quota. It repeats this cycle until the next day. The limiter should evaluate all layers and return the longest wait, which is the time until the daily window resets.
Exercise
Why must a distributed layered limiter run the check and the charge in a single Redis script instead of running a GET for each layer, then decrementing from the application?
Show answer
Between the reads and the writes, another server can read the same state and also decide to allow. Both then charge the same token or count slot, so limits are exceeded. A script runs atomically, so no other command can run between the read and the write.