System design · Token bucket, distributed state

How to design a distributed rate limiter

Run a token bucket per client key in Redis, updated atomically with a Lua script, and return HTTP 429 with a Retry-After header when the bucket is empty. The deep half of the question is enforcing one limit across a fleet without races, and deciding what happens when the limiter fails.

Updated · 4 min read

Each gateway server checks shared counters in a Redis cluster, updated atomically and sharded by client ID. Allowed requests go to the services; the rest get HTTP 429.

Rate Limiter architecture diagram

Each gateway server checks shared counters in a Redis cluster, updated atomically and sharded by client ID. Allowed requests go to the services; the rest get HTTP 429.

The short version

  • Enforce limits at the API gateway so rejected traffic costs almost nothing.
  • Token bucket is the usual default: cheap, with controlled bursts. A sliding window counter gives a smooth, near-exact limit.
  • Behind a load balancer, per-server counters multiply the limit. Keep counters in Redis and make read-check-write atomic.
  • Reject with HTTP 429 and Retry-After.
  • If Redis is down, choose fail open or fail closed on purpose. A local in-memory fallback limit degrades gradually.

Clarifying questions to ask first

  • Who is limited, and by what rule? (Assume per API key, say 100 requests per minute, with per-user, per-IP and per-endpoint rules possible.)
  • Are short bursts acceptable? (Assume yes, up to a set burst size.)
  • One server or a fleet? (Assume a fleet behind a load balancer, so one limit must hold across every server.)
  • What if the limiter's store goes down? (Assume the service stays available, with protection degrading gradually.)
  • How much latency can it add? (Well under a millisecond in-process, a few milliseconds over the network.)

Where the rate limiter sits

As early as possible, usually the API gateway or a middleware layer in front of every service. Services can keep their own limits for internal protection, but the edge limit stops abusive clients before the backend.

Choosing an algorithm

AlgorithmHow it worksTrade-off
Fixed window counterCount requests per clock window (e.g. per minute)Cheap; allows up to 2× the limit around window boundaries
Sliding window logStore a timestamp per request; count those in the last windowExact; memory grows with the limit
Sliding window counterWeight the previous window's count by how much of it overlapsClose to exact with two counters per client
Token bucketTokens refill at a steady rate up to a capacity; each request spends oneAllows controlled bursts; two numbers per client
Leaky bucketRequests drain from a queue at a fixed rateSmooths output; adds queueing delay

Token bucket in detail

Each client has a capacity (the burst size) and a refill rate. On each request, add the tokens earned since last time, cap at capacity, and allow if at least one remains.

tokens = min(capacity, tokens + (now - last_refill) * refill_rate)
last_refill = now
if tokens >= 1:
    tokens -= 1
    allow()
else:
    reject(retry_after = (1 - tokens) / refill_rate)

The distributed problem

Each server behind a load balancer sees only part of a client's traffic. With per-server counters, a client spread across ten servers gets ten times its limit, so the counter must be shared. Sharing creates a race: two servers both read 99 of 100 and both allow. The read-check-write has to be atomic.

  • Fixed window: INCR a key such as rate:{client}:{minute} with EXPIRE on first use. INCR is atomic.
  • Token bucket or sliding window: run the whole sequence in a Lua script, which Redis executes atomically.
  • Shard counters across a Redis cluster by client ID.
  • For very high-volume clients, servers can take small batches of tokens locally and sync periodically, trading a little accuracy for fewer round trips.

Telling clients, and failing

Reject with HTTP 429 Too Many Requests and a Retry-After header. Many APIs also send X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset so clients slow down early.

If Redis is unreachable, failing open keeps the service up but unprotected; failing closed protects it but makes the limiter the outage. Most public APIs fail open with a generous local in-memory limit per server, so protection degrades instead of vanishing.

Common traps

  • Calling the bucket's capacity the per-minute limit. Capacity sets the immediate burst and refill rate the sustained traffic; state both.
  • Choosing a sliding window log without counting its timestamps. Memory grows with the limit for every client; the two-counter approximation is usually enough.
  • Keying counters by API key alone when endpoints have different limits. Include the rule or endpoint in the key.
  • Drawing a leaky bucket as if it just rejects. Its queue makes accepted requests wait; check that against the latency budget.
  • Ignoring the fixed window's boundary: a client can spend its full limit at the end of one window and again at the start of the next.

Follow-up questions interviewers ask

  • "How do you stop two servers both allowing the last request?" Atomic read-check-write: INCR, or a Lua script.
  • "How do you keep the limiter from adding latency?" Enforce at the gateway and batch tokens locally for the heaviest clients.
  • "What does a rejected client receive?" A 429 with Retry-After and the limit, remaining and reset headers.

Frequently asked questions

What is the best rate limiting algorithm?

+

Token bucket is the common default because it's cheap and allows controlled bursts. A sliding window counter suits limits that must be smooth and close to exact.

How do you rate limit across multiple servers?

+

Keep the counter in a shared store such as Redis and update it atomically, with INCR for fixed windows or a Lua script for token bucket and sliding window.

What HTTP status code does a rate limiter return?

+

429 Too Many Requests, ideally with a Retry-After header saying when to try again.

What happens if the rate limiter's Redis goes down?

+

Failing open keeps the service available but unprotected; failing closed protects it but causes an outage. Most systems fail open with a local in-memory fallback limit.

Now fix it yourself.

Run the design under real traffic and see what breaks first. No signup.