Skip to main content
16

Rate limiting algorithms

MediumRate limitingAPIAlgorithms

How do you implement rate limiting? Compare the main algorithms.

TL;DR

Rate limiting caps how many requests a client (by user, API key or IP) can make in a period, to protect the service from abuse and overload and to enforce plan quotas. The main algorithms are fixed window (count per calendar minute; simple but allows bursts at window edges), sliding window (smooths the edges), token bucket (tokens refill at a steady rate, and each request spends one; allows controlled bursts), and leaky bucket (processes requests at a constant rate). Token bucket is the most common default. In a multi-instance service, keep the counters in a shared store like Redis with atomic operations.

Key points

AlgorithmBurstsMemoryNotes
Fixed windowUp to 2× at edges1 counterSimplest
Sliding window logNoneOne timestamp per requestExact but memory-heavy
Sliding window counterSmall2 countersGood approximation
Token bucketUp to bucket sizeTokens + timestampMost popular (AWS, Stripe)
Leaky bucketNone, smooth outputQueueTraffic shaping
  • Return 429 Too Many Requests with a Retry-After header and, ideally, RateLimit-* headers.
  • Do the check-and-increment atomically (a Lua script or INCR + EXPIRE in Redis) to avoid races.
  • Decide whether to fail open (allow traffic if Redis is down) or fail closed.
  • Put it where it's cheapest: API gateway or edge for coarse IP limits, application for per-user and per-plan limits.

Example

ts
// Fixed window with Redis: 100 requests per minute per user
const key = `rl:${userId}:${Math.floor(Date.now() / 60_000)}`
const count = await redis.incr(key)
if (count === 1) await redis.expire(key, 60)
if (count > 100) return res.status(429).set('Retry-After', '60').end()

Common follow-ups

  • What should clients do on 429? Retry after the Retry-After time, with exponential backoff and jitter.
  • Rate limiting vs throttling vs load shedding? Rate limiting rejects per client; throttling slows clients down; load shedding drops low-priority traffic when the whole system is overloaded.

What interviewers look for

Tip

Compare at least two algorithms with their burst behavior, then handle the distributed part: shared atomic counters and 429 with Retry-After.

  • Red flag: in-memory counters per instance behind a load balancer, which silently multiplies the limit.

Was this helpful?

Related questions