TExcelTAD
Home › System Design › Design a Rate Limiter

Design a Rate Limiter

The Rate Limiting Algorithms lesson built token buckets and sliding windows on one machine. This case study turns them into a distributed rate-limiting service for a public API: many gateway servers, shared limits, configurable rules and graceful failure.

1. Requirements

Functional

  • Limit requests per client by rules such as "free tier: 100 requests/minute per API key", "login: 5 attempts/15 min per account", "global: 20,000 requests/s to the search endpoint".
  • Rejected requests get 429 Too Many Requests with Retry-After and X-RateLimit-Remaining headers.
  • Rules can change without redeploying.

Non-functional

  • Adds less than ~1 ms to each request.
  • Limits are accurate across all gateway instances (a client can't get N times the limit by hitting N servers).
  • Highly available: if the limiter fails, the API should keep working (fail open) for most endpoints.

2. Estimates

python · try it yourself
api_requests_per_s = 200_000
gateways = 40
active_keys = 5_000_000            # API keys / users seen in the last hour
bytes_per_counter = 64             # key name + value + overhead for a token bucket in Redis
rules_per_request = 2              # e.g. per-key + per-endpoint

redis_ops = api_requests_per_s * rules_per_request
memory_gb = active_keys * rules_per_request * bytes_per_counter / 1e9
print(f"limiter checks: {redis_ops:,}/s across {gateways} gateways ({redis_ops // gateways:,}/s each)")
print(f"memory for counters: {memory_gb:.2f} GB")
print(f"Redis shards at ~100k ops/s each: {-(-redis_ops // 100_000)}")
limiter checks: 400,000/s across 40 gateways (10,000/s each)
memory for counters: 0.64 GB
Redis shards at ~100k ops/s each: 4

Memory is tiny; the challenge is the request rate and the network round trip per check.

3. High-level design

text
client --> [ API gateway  + limiter middleware ] --> backend services
                     |   local rule cache (refreshed from the rule store)
                     v
          [ Redis cluster: counters / buckets, sharded by key ]
                     ^
          [ rule store (config service / DB) ] <-- admins edit rules

The limiter runs inside the gateway (no extra network hop to a separate service), loads rules into memory, and keeps counters in a shared Redis cluster so that all gateways see the same counts. Each check is one atomic Redis operation, usually a small Lua script that reads, updates and sets an expiry in one step, which avoids race conditions between gateways.

4. Rules

python · try it yourself
RULES = [
    # (name, match function, key function, limit, window seconds)
    ("login-per-account", lambda r: r["path"] == "/login", lambda r: f"login:{r['account']}", 5, 900),
    ("free-tier",  lambda r: r["tier"] == "free", lambda r: f"key:{r['api_key']}", 100, 60),
    ("pro-tier",   lambda r: r["tier"] == "pro",  lambda r: f"key:{r['api_key']}", 2_000, 60),
    ("search-global", lambda r: r["path"].startswith("/search"), lambda r: "global:search", 20_000, 1),
]

def matching_rules(request):
    return [(name, key_fn(request), limit, window)
            for name, match, key_fn, limit, window in RULES if match(request)]

req = {"path": "/search?q=lamp", "tier": "free", "api_key": "k-123", "account": None}
for rule in matching_rules(req):
    print(rule)
('free-tier', 'key:k-123', 100, 60)
('search-global', 'global:search', 20000, 1)

A request is allowed only if every matching rule allows it.

5. The shared counter, with atomic updates

The model below simulates Redis as one dictionary shared by three gateway instances, using a sliding window counter per key (the two-counter approximation). The check_and_increment function stands in for the Lua script: it runs atomically.

python · try it yourself
class FakeRedis:
    def __init__(self):
        self.data, self.ops = {}, 0

    def check_and_increment(self, key, limit, window, now):   # "Lua script": atomic
        self.ops += 1
        w = int(now // window)
        prev = self.data.get((key, w - 1), 0)
        cur = self.data.get((key, w), 0)
        estimate = prev * (1 - (now % window) / window) + cur
        if estimate >= limit:
            return False, 0
        self.data[(key, w)] = cur + 1
        return True, int(limit - estimate - 1)

redis = FakeRedis()

class Gateway:
    def __init__(self, name):
        self.name = name

    def handle(self, api_key, now, limit=5, window=60):
        ok, remaining = redis.check_and_increment(f"key:{api_key}", limit, window, now)
        return f"{self.name} t={now:4.1f} -> " + (f"200 (remaining {remaining})" if ok else "429 Retry-After: later")

gateways = [Gateway("gw1"), Gateway("gw2"), Gateway("gw3")]
for i in range(7):                                  # the client's requests are spread over gateways
    print(gateways[i % 3].handle("k-123", now=10 + i * 0.5))
print("redis ops:", redis.ops)
gw1 t=10.0 -> 200 (remaining 4)
gw2 t=10.5 -> 200 (remaining 3)
gw3 t=11.0 -> 200 (remaining 2)
gw1 t=11.5 -> 200 (remaining 1)
gw2 t=12.0 -> 200 (remaining 0)
gw3 t=12.5 -> 429 Retry-After: later
gw1 t=13.0 -> 429 Retry-After: later
redis ops: 7

Because all three gateways share one counter, the client gets exactly 5 requests per window, not 15.

6. Cutting latency with local batching

A Redis round trip (~0.3-1 ms) per request is acceptable for many APIs, but at very high rates gateways can pre-fetch quota: each gateway takes a small batch of tokens from Redis and spends them locally, going back only when its batch runs out. It's slightly less accurate (unused local tokens are "stranded") and much cheaper:

python · try it yourself
def run(batch, requests=1_000, gateways=4, limit=600):
    shared = limit
    local = [0] * gateways
    allowed = redis_calls = 0
    for i in range(requests):
        g = 0 if i % 10 < 7 else i % 10 - 6        # gw0 gets 70% of the traffic
        if local[g] == 0 and shared > 0:            # refill this gateway's local batch
            take = min(batch, shared)
            shared -= take
            local[g] += take
            redis_calls += 1
        if local[g] > 0:
            local[g] -= 1
            allowed += 1
    stranded = sum(local)
    return allowed, redis_calls, stranded

print("batch  allowed  redis calls  stranded tokens")
for batch in [1, 10, 50, 200]:
    allowed, calls, stranded = run(batch)
    print(f"{batch:5} {allowed:8} {calls:12} {stranded:16}")
batch  allowed  redis calls  stranded tokens
    1      600          600                0
   10      600           60                0
   50      600           12                0
  200      400            3              200

With batches of 10 or 50, Redis traffic drops ten- to fiftyfold and the client still gets exactly its 600 requests. With batches of 200, the quiet gateways grab tokens they never use: 200 tokens are stranded and the busy gateway rejects requests the client was entitled to. Keep batches small relative to the limit, and give local tokens a short expiry so unused ones return to the pool.

7. Failure handling

Failure Behaviour
Redis shard unreachable Fail open (allow) for normal endpoints, with a local in-memory fallback limiter per gateway; fail closed for sensitive ones (login, payments)
Hot key (one client hammering) Its counter lives on one shard; local pre-checks or a deny-list at the edge absorb floods
Clock differences Use Redis server time (TIME) inside the script, not gateway clocks
Rule store down Keep using the last loaded rules

Trade-offs

Decision Choice Alternative
Where the limiter runs In the gateway A separate service (extra hop) or in each backend (duplicated)
Algorithm Sliding window counter / token bucket Fixed window (bursty), sliding log (memory-heavy)
State Central Redis, atomic Lua Local-only counters (inaccurate with many gateways)
Accuracy vs cost Local batches for hot paths One Redis call per request

Test yourself

Why must rate-limit counters be shared between gateway instances?

  1. To save memory
  2. Otherwise a client spreading requests over N gateways gets up to N times the limit
  3. Redis requires it
  4. To make rules configurable

Why is the check implemented as one atomic Lua script in Redis?

  1. Lua is faster than Python
  2. Separate read and write commands from different gateways could race and overshoot the limit
  3. Redis can't store numbers otherwise
  4. To encrypt the counter

If the rate limiter's store is unavailable, what is a sensible default for a product search endpoint?

  1. Reject all requests
  2. Fail open, perhaps with a local fallback limit
  3. Restart all gateways
  4. Switch to the sliding log algorithm