Sub topic 3
Telling Clients About Limits and Operating a Distributed Limiter
Assume you know basic HTTP, Python, Redis, and load-balanced services. A rate limiter should reject excess work clearly, enforce one policy across service instances, and remain predictable when clocks or dependencies fail.
HTTP 429 and Retry-After
Return 429 Too Many Requests when a client exceeds its limit. Include Retry-After so the client knows when to try again. Its value can be a number of seconds or an HTTP date.
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 12
{"error":"rate_limit_exceeded","retry_after":12}Clients should wait before retrying. Add jitter, which is a small random delay, so many clients do not retry simultaneously. You can also expose RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset headers.
Shared State and Atomic Updates
With several application servers, an in-memory counter gives each server a different view. Store limiter state in a shared system such as Redis. The check, refill, and update must happen atomically, meaning no other request can observe a half-finished operation.
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local data = redis.call("HMGET", key, "start", "count")
local start = tonumber(data[1]) or now
local count = tonumber(data[2]) or 0
if now - start >= window then
start, count = now, 0
end
local allowed = count < limit
if allowed then count = count + 1 end
redis.call("HSET", key, "start", start, "count", count)
redis.call("EXPIRE", key, window)
return {allowed and 1 or 0, window - (now - start)}Run this as one Redis script, rather than reading and writing the hash in separate commands.
Clocks and Failure Behavior
Prefer the Redis server clock or a monotonic clock for elapsed intervals. Wall clocks can jump because of synchronization, causing early resets or excessive blocking.
If Redis is unavailable, failing open preserves availability but may allow overload. Failing closed protects the service but can reject valid traffic during an infrastructure outage. Choose per endpoint. Protect expensive or security-sensitive operations more strictly.
Layered Limits
Combine limits with different purposes:
- A token bucket can allow short per-second bursts.
- A daily quota can control total usage.
- A global cap can protect a shared database.
Reject a request when any required layer rejects it. Return the shortest useful retry time.
Testing and Monitoring
Inject a fake clock into limiter tests. Test window boundaries, bursts, concurrent requests, expired keys, and Redis errors. Monitor rejection rate, allowed rate, limiter latency, Redis failures, and keys with unusually high traffic. Alert when rejected traffic or fail-open decisions rise unexpectedly.
Exercise
Why should a distributed limiter use one atomic Redis operation?
Show answer
Separate read and write operations can race, allowing concurrent requests to spend the same remaining capacity.