Case study: Distributed rate limiter

Topic 3 of 15 in Week 7: Classic case studies13 min readIntermediateFree course

Overview

A rate limiter decides, for each request, whether the client is within its allowed rate. Week 6 covered the algorithms; this case study designs the full distributed system: where it runs, where counters live, how rules are configured and what happens when parts fail.

Try the exercise first: 45 minutes, then compare.

1. Requirements

Functional

  • Limit requests per client identity (API key, user ID or IP) and optionally per endpoint, according to configurable rules (for example 100 per minute for free plans, 5,000 per minute for paid ones).
  • Reject excess requests with a clear error and information on when to retry.
  • Rules can change without redeploying gateways.

Non-functional

  • Low added latency (a few milliseconds at most).
  • Accurate enough: small overshoot is acceptable, large overshoot is not.
  • Highly available: the limiter must not take the API down.
  • Scale: 500,000 requests per second across 50 gateway instances.

2. Estimates

Text
checks       : 500,000 / s (one per request)
active keys  : say 10M API keys/users; each counter ~100 bytes → ~1 GB in memory
Redis        : ~100k simple ops/s per node → ~5–10 shards, plus replicas

3. Interface

Most often the limiter is a library or middleware inside the gateway:

Text
allow(identity, route) → {allowed: bool, remaining: int, reset_at: time}

Rejected responses:

Text
HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1764850212

4. Data model

Text
rules (config DB, cached in gateways):
  plan | route pattern | limit | window | burst
counters (Redis):
  key "rl:{api_key}:{rule_id}" → {tokens, last_refill}   (TTL = idle timeout)

5. High-level design

Distributed rate limiter. Clients send requests to gateway instances 1 to 3, each running limiter middleware. Each gateway checks a Redis cluster holding atomic token buckets implemented with Lua scripts, and loads limits per plan and route from a rules configuration store. Allowed requests go on to backend services; rejected requests receive 429 with Retry-After. The key is the user or API key plus route, with one token bucket per key; rules are cached locally and refreshed. If Redis is unreachable, the gateways fail open with a local per-instance limit and alert.

For each request, the gateway identifies the client, finds the matching rules in its local cache, runs one atomic Redis operation per rule, and either forwards the request or returns 429.

6. Deep dives

Choosing the algorithm

  • Token bucket: two numbers per key, allows short bursts, enforces the average. Good default for APIs.
  • Sliding-window counter: two counters per key, smooth, close to exact per-window limits. Good when the contract says “N per minute”.
  • Fixed window: simplest, but allows double bursts at window edges.
  • Sliding log: exact but stores every timestamp; too much memory at this scale.

Atomic updates

Fifty gateways may update the same key simultaneously. Reading the value, deciding and writing it back in separate steps lets two requests both take the last token. Make it atomic:

  • Lua script in Redis: compute refill from elapsed time, check, decrement and save in one step on the server.
  • For fixed windows, INCR plus EXPIRE is atomic enough.

Use Redis server time (or pass the gateway’s time consistently) to avoid clock-skew effects.

Latency and hot keys

One Redis round trip is about a millisecond inside a data centre. To cut further:

  • shard counters by key across a Redis cluster (keys for one client land on one node),
  • pipeline checks for multiple rules into one round trip,
  • for extremely high-volume keys, give each gateway a small local allowance (a slice of the limit) and sync with Redis periodically, trading a little accuracy for speed.

Failure behaviour

If Redis is slow or down:

  • Fail open: allow requests (protects availability), applying a coarse per-instance local limit so abuse is still bounded. Usual choice for general API traffic.
  • Fail closed: reject (protects backends and security), appropriate for login attempts or expensive operations.

Set a tight timeout on the limiter call so a slow Redis can’t slow every request. Replicate Redis shards with automatic failover; counters lost in a failover simply restart, a minor inaccuracy.

Rules management

Store rules in a database with an admin UI or config files in Git. Gateways cache them and refresh every few seconds (or subscribe to change notifications). Validate rules before rollout; a bad rule can reject all traffic.

Multiple regions

A global limit needs coordination across regions, which costs latency. Common approaches: split the limit per region (each region allows its share), or count locally and sync asynchronously, accepting brief overshoot.

7. Trade-offs and bottlenecks

  • Accuracy vs latency: local allowances and regional splits are faster but less exact.
  • Fail open vs closed: availability vs protection.
  • Redis memory is bounded by active keys; idle counters must expire.

8. Follow-up questions

  • Rate-limit by IP for anonymous traffic? Same design, but beware shared IPs (offices, mobile carriers) and spoofed headers.
  • Different costs per endpoint? Use weighted tokens (an export costs 10 tokens).
  • Quotas per month? A separate, durable counter in a database, updated asynchronously, alongside the short-window limiter.

Recap

A distributed rate limiter runs in the gateway path, looks up cached rules, and performs one atomic check-and-update per rule against counters in a sharded Redis cluster, returning 429 with helpful headers when limits are exceeded. Token buckets or sliding windows provide the algorithm; Lua scripts provide atomicity; local fallbacks and a fail-open or fail-closed policy keep the limiter from becoming a single point of failure.

Exercise

Design it yourself (45 minutes)

Set a 45-minute timer and design a rate-limiting service for a public API platform: limits per API key and per endpoint (e.g. 100 requests/minute for free keys, 5,000 for paid), configurable rules, 50 gateway instances handling 500,000 requests per second in total, and less than 5 ms added latency. Use the framework, then compare.

Text
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates:
5. API / interface:
6. Data model (counters, rules):
7. High-level design:
8. Deep dives (algorithm, atomicity, failures):
9. Trade-offs and bottlenecks:

Summary

  • Enforce limits in the gateway path with a shared, fast store so all instances agree.
  • Token bucket allows bursts and is cheap to store; sliding-window counters give smooth per-window limits.
  • Make check-and-update atomic (Redis Lua scripts) to avoid races between gateway instances.
  • Cache rules locally, return 429 with Retry-After and rate-limit headers, and expire idle counters.
  • Decide fail-open vs fail-closed, and accept small inaccuracy across regions in exchange for latency.