Skip to main content
04

Design a rate limiter

MediumToken bucketSliding windowRedisMiddleware

Design a rate limiter: a component that caps how many requests a client can make in a time window, for example 100 requests per minute per API key, and rejects the rest.

A typical framing: "Our public API gets abused by a few clients. Design a rate limiter we can put in front of every endpoint, with different limits per plan. First as a class in one process, then tell me what changes when we run 50 API servers."

TL;DR

Pick an algorithm, wrap it in a small interface, and put it in middleware (or the API gateway). The common choices:

  • Token bucket: tokens refill at a steady rate up to a capacity; each request takes one. It allows short bursts and is cheap (two numbers per client). The usual default.
  • Sliding window counter: weights the previous window's count to approximate a true sliding window. Smooth limits with tiny memory.
  • Fixed window: simplest, but allows up to 2× the limit around window boundaries.
  • Sliding window log: exact, but stores a timestamp per request.

With many servers the state must be shared: keep it in Redis and update it atomically with a Lua script, so two servers can't both read "99" and both allow request 100. Rejected requests get 429 Too Many Requests with Retry-After and RateLimit-* headers. Decide whether to fail open or fail closed when Redis is unavailable.

1. Requirements

Questions worth asking:

  • Limit by what: API key, user, IP, endpoint, or a combination?
  • Which limits: per second, per minute, per day? Different per plan?
  • Are short bursts acceptable?
  • One server or many? How much extra latency can the limiter add?
  • What should happen if the limiter's store is down?

Functional

  • Allow or reject each request according to the rules for its key.
  • Several rules can apply at once (10/second and 1,000/day).
  • Tell clients their remaining quota and when to retry.

Non-functional

  • Low latency: about a millisecond per check.
  • Accurate across many servers.
  • Highly available: the limiter shouldn't take the API down.

2. Entities and classes

Loading diagram...

The algorithm (RateLimiter), the rules (RuleResolver, e.g. from config per plan) and the storage (in memory or Redis) are separate, so each can change on its own.

3. API

ts
type Rule = { limit: number; windowMs: number }
type Decision = { allowed: boolean; remaining: number; retryAfterMs: number }

interface RateLimiter {
  check(key: string, rule: Rule, cost?: number): Promise<Decision>
}

The HTTP contract:

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

4. Core logic

Token bucket, in memory

ts
class TokenBucketLimiter implements RateLimiter {
  private buckets = new Map<string, { tokens: number; updatedAt: number }>()
  constructor(private now = () => Date.now()) {}

  async check(key: string, rule: Rule, cost = 1): Promise<Decision> {
    const refillPerMs = rule.limit / rule.windowMs
    const now = this.now()
    const bucket = this.buckets.get(key) ?? { tokens: rule.limit, updatedAt: now }

    // Refill lazily: no timers, just compute what accumulated since the last call.
    bucket.tokens = Math.min(rule.limit, bucket.tokens + (now - bucket.updatedAt) * refillPerMs)
    bucket.updatedAt = now

    const allowed = bucket.tokens >= cost
    if (allowed) bucket.tokens -= cost
    this.buckets.set(key, bucket)

    return {
      allowed,
      remaining: Math.floor(bucket.tokens),
      retryAfterMs: allowed ? 0 : Math.ceil((cost - bucket.tokens) / refillPerMs),
    }
  }
}

Two numbers per key, no background timers. Idle buckets can be evicted (an LRU or a TTL), because a missing bucket simply means "full".

Sliding window counter

ts
// Weighted estimate of requests in the last `windowMs`.
const elapsed = (now % windowMs) / windowMs // how far into the current window we are
const estimate = previousCount * (1 - elapsed) + currentCount
const allowed = estimate < limit

It assumes the previous window's requests were evenly spread, which is accurate enough in practice and needs only two counters per key.

Middleware

ts
async function rateLimit(req: Request, next: () => Promise<Response>) {
  const rule = rules.rulesFor(req) // e.g. by plan and endpoint
  const key = `${req.apiKey}:${req.routeId}`
  const decision = await limiter.check(key, rule)
  if (!decision.allowed) {
    return new Response(null, {
      status: 429,
      headers: { 'Retry-After': String(Math.ceil(decision.retryAfterMs / 1000)) },
    })
  }
  const res = await next()
  res.headers.set('RateLimit-Remaining', String(decision.remaining))
  return res
}

5. Edge cases and extensions

  • Many servers: an in-memory limiter per server gives each client N times the limit. Keep counters in Redis and make read-check-update atomic with a Lua script (or INCR + EXPIRE for a fixed window). A plain "read, then write" from the app has a race.
  • Latency: one Redis round trip per request. For very high traffic, allow some inaccuracy: each server keeps a local counter and syncs with Redis every few hundred milliseconds.
  • Redis down: fail open (allow everything) keeps the API up but removes protection; fail closed protects the backend but causes an outage. Fail open with a conservative local limiter is a common middle ground.
  • Clock differences between servers: use Redis's clock (TIME inside the script) rather than each server's.
  • Hot keys: one huge customer hammers one Redis key. Shard their counter, or limit them closer to the edge.
  • Where to enforce: at the edge (API gateway, CDN) for abuse and DDoS by IP; in the service for business rules per plan. Both are common.
  • Costly endpoints can take more than one token (cost).

Common follow-ups

  • "Token bucket vs. leaky bucket?" Token bucket allows bursts up to the bucket size. Leaky bucket processes requests at a constant rate from a queue, smoothing traffic but adding delay; it suits traffic shaping more than API quotas.
  • "Why does fixed window allow 2× the limit?" With 100/minute, a client sends 100 requests at 00:59 and 100 more at 01:00: both windows are within their limit, but 200 requests arrived in two seconds.
  • "How do you rate-limit unauthenticated traffic?" By IP (or IP range), knowing that many users can share one IP behind a corporate NAT. Combine with CAPTCHAs or bot detection at the edge.

What interviewers look for

  • Knowing several algorithms and their trade-offs (bursts, memory, accuracy).
  • A clean separation of algorithm, rules and storage.
  • Atomic updates in a shared store across servers, and awareness of the race.
  • Correct HTTP semantics: 429, Retry-After, rate-limit headers.
  • A deliberate fail-open vs. fail-closed decision and where to enforce limits.

Was this helpful?