Rate limiting algorithms
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
| Algorithm | Bursts | Memory | Notes |
|---|---|---|---|
| Fixed window | Up to 2× at edges | 1 counter | Simplest |
| Sliding window log | None | One timestamp per request | Exact but memory-heavy |
| Sliding window counter | Small | 2 counters | Good approximation |
| Token bucket | Up to bucket size | Tokens + timestamp | Most popular (AWS, Stripe) |
| Leaky bucket | None, smooth output | Queue | Traffic shaping |
- Return
429 Too Many Requestswith aRetry-Afterheader and, ideally,RateLimit-*headers. - Do the check-and-increment atomically (a Lua script or
INCR+EXPIREin 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
// 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-Aftertime, 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.