LOAD-BEARINGfree
Low-level design dojoTier 13 · unit 22 of 31

Rate limiter class

A reusable rate limiter for an API tier. Different endpoints need different algorithms, limits are per API key, and it runs on many servers at once.

The API must tolerate short bursts from legitimate clients but cap the sustained rate. Which algorithm?

  • Fixed window counter
  • Token bucket
  • Leaky bucket
  • Sliding window log
Why

Token bucket accumulates up to a maximum while idle, so a burst is permitted, while the refill rate enforces the long-run average. Leaky bucket smooths output completely and would reject bursts a real client legitimately produces.

Assign each responsibility.

Define limit, window and burst size for an endpoint
RateLimitPolicy
Decide allow or reject for one incoming request
RateLimiter
Extract the identity to limit on (API key, else IP)
KeyResolver
Atomically increment and read the counter
Store
Implement token bucket vs sliding window arithmetic
RateLimitPolicy
Why

The algorithm is a policy object so a new one is a new class, not an edit. The store is abstracted because it is in-memory in tests and Redis in production — dependency inversion doing real work rather than ceremony.

Ten API servers each enforce 100 requests/min locally. What does a client actually get?

  • 100/min
  • Up to 1000/min
  • It depends on the algorithm
  • Exactly 10/min
Why

Local counters do not add up to a global limit. Either share the counter in Redis with an atomic operation, or divide the budget across nodes and accept unevenness when traffic is not perfectly balanced.

A rejected request should return:

  • 403 Forbidden
  • 429 with a Retry-After header
  • 200 with an error body
  • 503 Service Unavailable
Why

429 is the specific status, and Retry-After tells a well-behaved client exactly when to come back. A bare rejection makes clients retry immediately, which makes the overload worse.