Skip to content

Rate Limiting

Rate limiting bounds how much work one actor can impose on a system in a time window. It protects availability, enforces fair use, makes abuse expensive, and gives you a lever for cost control. It is also a distributed-systems problem the moment you have more than one instance.

Rate limiting controls request rate per key — user, API key, IP, tenant, endpoint. Token bucket is the general-purpose algorithm: a bucket of capacity C refills at R per second, and a request costs tokens. Leaky bucket smooths output at a constant rate. Fixed windows are trivial but allow 2× the limit at the boundary. Sliding window counters approximate better for little cost. With many instances, keep the counters in Redis and use a Lua script so check-and-decrement is atomic. Return 429 with Retry-After and rate-limit headers, and never use it as your only defence against overload.

Capacity C, refill R tokens/second. Each request takes one token; if none, reject.

tokens = min(C, tokens + (now - last_refill) * R)
if tokens >= 1: tokens -= 1; allow
else: reject, retry_after = (1 - tokens) / R
  • Allows bursts up to C, sustains R.
  • State is two numbers per key. Cheap and the right default.
  • C = R gives a smooth rate; large C gives burst tolerance.

A queue of fixed depth drained at a constant rate. Requests that arrive when the queue is full are rejected.

  • Output is perfectly smooth, which protects a fragile downstream.
  • Adds latency: a request may queue before being processed.
  • Use it when the downstream needs a steady rate, not when the client wants responsiveness.

Token bucket limits arrival; leaky bucket shapes departure. In an interview, say which problem you are solving.

INCR key, set expiry to the window length, reject when the count exceeds the limit.

  • One counter, one round trip, trivially fast.
  • The boundary problem: with a limit of 100/minute, a client can send 100 at 00:59 and 100 at 01:00 — 200 in two seconds. Real bursts are worse than the nominal limit.

Store the timestamp of every request in a sorted set, drop those older than the window, count.

  • Exact.
  • Memory grows with the limit: 10,000 requests/hour per key is 10,000 entries. Not viable at scale for large limits.

Weight the previous window by the fraction of the current window already elapsed.

estimate = prev_count * (1 - elapsed/window) + curr_count
  • Two counters, constant memory, close to exact for reasonable limits.
  • Good default when fixed windows are too coarse for the accuracy you need.
Algorithm Burst Memory Accuracy Use
Token bucket Configurable O(1) Good General API limits
Leaky bucket None (smooth) O(queue) Good Protecting fragile downstreams
Fixed window 2× at boundary O(1) Poor at edges Cheap coarse limits
Sliding log Exact O(limit) Exact Small limits, strict quotas
Sliding counter Approximate O(1) Good High-volume APIs

With ten app servers, an in-process counter allows ten times the limit. Options:

Centralised counter (Redis). The standard. One INCR per request, or a Lua script for multi-step logic.

-- token bucket, atomic
-- KEYS[1] = bucket key
-- ARGV: capacity, refill_per_sec, now_ms, cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
if tokens < cost then
local retry = math.ceil((cost - tokens) / rate)
return {0, retry}
end
redis.call('HMSET', KEYS[1], 'tokens', tokens - cost, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
return {1, 0}

Why Lua: GET, compare, SET as separate commands is a race. Two requests can both read tokens = 1 and both proceed. The script runs atomically inside Redis’s single-threaded command loop.

Details that bite:

  • Clock skew. Use the Redis server’s time (TIME) or now_ms passed in, consistently. Mixing node clocks produces negative refills.
  • Key expiry. Always set a TTL, or the key space grows without bound and Redis evicts something important.
  • Hot keys. A single extremely active key hits one Redis shard. Shard the counter (allow limit/N per shard and sum) or enforce locally with a global safety margin.
  • Redis unavailable. Decide the failure mode in advance: fail-open (allow, protecting availability) or fail-closed (deny, protecting the downstream). For abuse prevention, fail-open with a local fallback limiter is usually right.

Gossip / local counters with a global sync. Each node limits locally at limit/N and periodically reconciles. Approximate, no central hop, tolerates partitions. Used at very high scale; harder to reason about.

Gateway-level limiting. Done at the edge (API gateway, CDN, load balancer) before the request reaches your service. Cheapest place to reject, and it protects everything behind it.

Key Good for Caveat
API key Server-to-server clients One key may serve many users
User id Authenticated fairness Requires auth before limiting
IP Unauthenticated abuse NAT and mobile carriers share IPs; IPv6 gives one user many
Tenant SaaS plan limits Needs per-tenant budgets
Endpoint + key Expensive operations More keys, more memory

Usually combine: a coarse per-IP limit for unauthenticated traffic, a per-user limit for authenticated, and a per-endpoint cost multiplier. A search query or a report export should cost more than a read by id. That is weighted or cost-based limiting: cost is an argument to the script, not always 1.

HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 12
Content-Type: application/problem+json
{"type":"https://api.example.com/problems/rate-limited","title":"Rate limit exceeded",
"status":429,"detail":"Retry in 12 seconds.","code":"rate_limited"}

Rules:

  • 429, not 403 or 503. 503 means the service is failing and triggers failover behaviour.
  • Always send Retry-After. A client without it will hammer you immediately.
  • Document the limits per endpoint before launch, not in an incident.
  • Do not leak whether the limit is per-user or per-IP in a way that helps an attacker map them.

These get conflated:

  • Rate limit — per-actor quota. Rejects the noisy client.
  • Concurrency limit — cap on in-flight requests per instance. Protects against slow requests, which rate limits do not see.
  • Load shedding — when the system is saturated, reject the least valuable requests (by priority, or randomly) to keep the rest fast. This is what saves you in an incident.
  • Backpressure — slow producers down via queues, 429s, or bounded buffers.
  • Throttling — deliberately slowing responses instead of rejecting.

A rate limit does not protect you from 10,000 distinct users arriving at once. That is capacity planning and load shedding.

  1. Why does a fixed window allow double the limit, and how do you show it?
  2. How do you rate limit at 100k rps without a Redis round trip on every request?
  3. What is the failure mode when Redis is down, and which do you choose?
  4. How would you implement “10 requests per second, burst of 50” per API key?
  5. How do you make an expensive endpoint cost 10 tokens instead of 1?
  6. Why is a per-IP limit ineffective against a distributed attack?
  • “Rate limiting prevents DDoS.” It helps with application-layer abuse. Volumetric attacks are absorbed upstream, and a botnet has thousands of IPs.
  • “One global limit is enough.” Different endpoints have wildly different costs.
  • “In-process counters are fine, we have one server.” Until you have two, and then the limit silently doubles.
  • “GET and SET is atomic enough.” It is not. Use Lua or a single atomic command.
  • “429 means the client is broken.” It means slow down. Returning 400 confuses every retry library.