Interview Study Guide

Guide / System design Fundamentals

1.6 Rate limiting and load shedding

What rate limiting is, why every API needs it, the five algorithms with code, where to enforce it, the 429 contract, how clients must react, and how to build it distributed.

Created · Updated · 17 min read

Rate limiting caps how much work one caller can ask of your system in a window of time. It is both an interview question on its own (“design a rate limiter”, walked through in Top questions) and a building block in almost every other design.

Order in this page: Fundamentals (why, vocabulary, algorithms, placement, the 429 contract, client handling, distributed design, configuration) → Most asked questions → Senior-level questions → Quiz with answers.

Fundamentals#

1.6.1 What it is and why you need it#

Rate limiting = “at most N requests per window per key”. When the caller exceeds it, you reject (or delay) the extra work.

Why every public API has it:

ReasonExample
Availability / fairnessOne noisy client must not starve everyone else (noisy-neighbour protection)
Protect downstream systemsYour API is fast but the database, payment gateway or LLM provider is not
SecurityBrute-force logins, credential stuffing, OTP guessing, scraping, enumeration, cheap DoS
Cost controlLLM tokens, SMS and email sends, paid third-party calls cost money per request
MonetisationFree tier 60 req/min, paid tier 6,000 req/min (quotas)
Stability under bugsA client with a retry loop bug cannot melt your service

Related terms (interviewers like to see them separated):

TermMeaning
Rate limitMax requests per short window (per second/minute); protects capacity
QuotaMax usage per long period (per day/month); about billing and plans
ThrottlingSlow requests down (delay or queue) instead of rejecting
Concurrency limitMax requests in flight at once; better than rate when requests have very different durations
Load sheddingServer drops low-priority work when overloaded, regardless of who sent it
BackpressurePushing “slow down” signals upstream (bounded queues, TCP windows, 429/503)
Circuit breakerCaller stops calling a failing dependency (the mirror image: client-side protection)

1.6.2 What to limit by (the key)#

KeyGood forWeakness
API key / client IDB2B and developer APIs, plans and tiersA leaked key is a shared bucket
User ID (after auth)Per-account fairnessDoes not stop unauthenticated floods
IP addressUnauthenticated endpoints (login, signup), first line of defenceNAT and corporate proxies make many users one IP (false positives); attackers rotate IPs; IPv6 needs a /64 prefix key
Tenant / organisationMulti-tenant SaaSNeeds sub-limits per user inside the tenant
Endpoint / routeExpensive operations (/search, /export) get lower limits than cheap onesMore config
Cost / weightGraphQL query cost, LLM token count, batch size: a request costs N tokens, not 1Needs a cost model
Composite(user, endpoint), (tenant, region)Key cardinality grows

Most real systems layer several: a global IP limit at the edge, an API key limit in the gateway and per-endpoint, per-user limits in the service. For login: limit by account (stops distributed guessing against one user) and by IP (stops one attacker trying many accounts).

1.6.3 The five algorithms#

1. Fixed window counter. Count requests in the current minute bucket (key:2026-11-29T10:15); reset every minute.

  • Pros: trivial, one INCR + EXPIRE, tiny memory.
  • Cons: boundary burst: 100 requests at 10:15:59 and 100 more at 10:16:00 yields 200 in two seconds against a “100/min” limit.

2. Sliding window log. Store a timestamp for every request in a sorted set; drop entries older than the window; count the rest.

  • Pros: exact.
  • Cons: memory proportional to the limit × number of keys (storing 10,000 timestamps per user is expensive).

3. Sliding window counter. Keep counts for the current and previous fixed windows and weight the previous one: estimate = prev_count × (1 − elapsed/window) + current_count.

  • Pros: smooth, two counters per key, error of a few percent. A good default for “N per minute” limits.
  • Cons: approximate.

4. Token bucket. A bucket holds up to b tokens (capacity) and refills at r tokens per second. Each request removes one (or its cost). Empty bucket → reject.

  • Pros: permits bursts up to b while enforcing the average rate r; two numbers per key; supports variable cost. Used by Stripe, AWS and most gateways. The most common answer.
  • Cons: two parameters to explain; refill math must be atomic.

5. Leaky bucket. Requests enter a fixed-size queue and drain at a constant rate. Full queue → reject.

  • Pros: perfectly smooth output; protects a downstream that cannot take bursts (shaping traffic to a payment provider).
  • Cons: bursts become latency (queued) or drops; old requests may be served late; the queue needs memory.
AlgorithmAllows bursts?Memory per keyAccuracyBest for
Fixed window2× at boundariesO(1)PoorCheap coarse limits, quotas per day
Sliding logNoO(limit)ExactLow limits needing precision (login attempts: 5/min)
Sliding counterSmallO(1)~99%General API limits at scale
Token bucketYes, bounded by bO(1)Exact for ratePublic APIs, user-facing limits, variable cost
Leaky bucketNo (smoothed)O(queue)Exact outputShaping traffic toward a fragile dependency

Token bucket, atomic in Redis (Lua). The whole read-modify-write runs as one atomic script, so concurrent requests cannot both spend the same token:

-- 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 state  = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1])
local ts     = tonumber(state[2])
if tokens == nil then tokens = capacity; ts = now end

-- refill for the time that passed, never above capacity
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)

local allowed = 0
local retry_after_ms = 0
if tokens >= cost then
  tokens = tokens - cost
  allowed = 1
else
  retry_after_ms = math.ceil((cost - tokens) / rate * 1000)
end

redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) * 2)  -- idle keys vanish
return { allowed, math.floor(tokens), retry_after_ms }

Details worth saying: use Redis TIME (or a single clock) rather than each app server’s clock; set a TTL so idle keys are cleaned; the script returns Retry-After for free; with Redis Cluster keep a key’s data in one slot (one key per bucket does this naturally).

Sliding window log in Redis (exact; fine for low limits):

ZREMRANGEBYSCORE key 0 (now - window)    -- drop old
ZADD key now request_id                  -- record this request
ZCARD key                                -- count in window
EXPIRE key window
-- allow if count <= limit (wrap in MULTI or Lua so it is atomic)

1.6.4 Where to enforce it#

LayerWhat it limitsProsCons
CDN / WAF / edgePer-IP floods, bots, geographic blocksStops traffic before it reaches you; absorbs DDoSCoarse; no knowledge of users or plans
Load balancerConnections per IP, request size, slow-client timeoutsCheapCoarse
API gateway (Kong, Envoy, AWS API Gateway, NGINX)Per API key / plan / routeCentral policy, no app code, one place for headersAnother hop; limited business logic
Service middleware / sidecarPer user, per endpoint, cost-weightedKnows the business contextDuplicated across services unless a shared library or service is used
Inside dependenciesPer-connection pools, DB statement limits, bulkheadsLast line of defenceLate: damage already happened upstream
Client SDKClient throttles itselfReduces wasted callsCannot be trusted

Typical answer: coarse and cheap at the edge, identity-aware in the gateway, cost-aware in the service, and bounded queues and timeouts everywhere inside. Reject early: the further the rejection is from the expensive work, the cheaper it is.

1.6.5 The 429 contract: what the server returns#

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/errors/rate-limited",
  "title": "Rate limit exceeded", "status": 429,
  "detail": "100 requests per minute allowed. Retry in 12 seconds.",
  "code": "rate_limited", "request_id": "req_91ac" }
  • 429 Too Many Requests for per-caller limits; 503 Service Unavailable when the server is overloaded (load shedding), both with Retry-After.
  • Retry-After is seconds or an HTTP date. Add the RateLimit-* headers (IETF draft) or the older X-RateLimit-Limit/Remaining/Reset on every response, not just rejections, so clients can slow down before they are cut off.
  • Never silently drop requests or return 200 with an error body.
  • Do not count rejected requests against the caller unless you deliberately want to punish retries.
  • Use a different key for login/OTP endpoints and return the same generic error either way, so the limiter does not reveal whether an account exists.
  • Consider soft limits (warn, log, header) before hard limits (reject) when introducing limits on an existing API.

1.6.6 How clients must handle 429 and 503#

A well-behaved client is half the solution:

  1. Honour Retry-After. Wait at least that long.
  2. If absent, use exponential backoff with jitter: sleep = random(0, min(cap, base × 2^attempt)) (full jitter). Jitter prevents all clients retrying in lockstep.
  3. Limit retries (3–5) and total time. After that, surface an error to the caller.
  4. Retry only idempotent requests, or POSTs that carry an idempotency key (REST API design).
  5. Use a retry budget (retries ≤ 10% of calls) and a circuit breaker so a struggling server is not hammered.
  6. Throttle on your side with a client-side token bucket matched to the documented limits; batch requests; cache responses; prefer webhooks or bulk endpoints to polling.
  7. Never retry at several layers (browser, SDK, gateway, service): attempts multiply.
import random, time

def call_with_backoff(send, max_attempts=5, base=0.5, cap=30.0):
    for attempt in range(max_attempts):
        resp = send()
        if resp.status not in (429, 503):
            return resp
        retry_after = resp.headers.get("Retry-After")
        if retry_after:
            delay = float(retry_after)                                 # server knows best
        else:
            delay = random.uniform(0, min(cap, base * 2 ** attempt))   # full jitter
        time.sleep(delay)
    raise RuntimeError("still rate limited after retries")

1.6.7 Building it distributed#

ConcernApproach
Shared stateCounters in Redis, updated with an atomic Lua script. Each app server asking Redis adds ~0.5–1 ms
Too many Redis callsLocal pre-check + global sync: each node takes a lease of tokens (say 10% of the budget) and refreshes asynchronously. Accepts small over-admission for far fewer round trips
Hot keysA global limit on one key (e.g. a whole tenant) overloads a Redis shard: split into sub-buckets (key#0..#7) and sum, or limit locally per node at limit / nodes
Race conditionsNever read-then-write from the app; use a single script, INCR, or compare-and-set
Clock skewUse the Redis server time or logical windows, not each host’s clock
Redis downDecide per endpoint: fail-open (allow, risk of overload) for general traffic; fail-closed (reject) for security-critical limits like login; keep a coarse in-memory fallback limit per node
Multi-regionPer-region limits (limit / regions) with async reconciliation for approximate global limits; strict global limits cost cross-region latency, so only for billing-critical quotas
Atomic with the actionFor hard quotas (billable) charge the quota before the work and refund on failure; for abuse limits approximate is fine
Config changesLimits live in a config store with hot reload, per-plan overrides and emergency kill switches
ObservabilityMetrics: allowed vs limited per key, per route; alert on a sudden rise of 429s (a bug, an attack or a limit set too low)

Rate limit vs concurrency limit. A rate limit of 10 req/s lets 10 slow (5 s) requests pile up into 50 in flight. For endpoints with variable duration use a concurrency limit (max in-flight per key or per instance), or both. Adaptive concurrency limits (AIMD, as in TCP congestion control, or gradient-based like Netflix’s concurrency-limits) discover the safe level from observed latency.

Load shedding (server-wide). When CPU, queue depth or latency crosses a threshold, drop the lowest-priority work first (batch before interactive, free tier before paid, retries before first attempts) and return 503 quickly. Rejecting a request costs microseconds; serving it slowly may cost seconds of thread time and drags all requests down.

1.6.8 Configuration example (NGINX)#

# 10 requests/second per client IP, shared zone of 10 MB (~160K IPs)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=perip:10m;

server {
  location /api/ {
    limit_req zone=api burst=20 nodelay;   # token-bucket-like: 20 burst, then reject
    limit_conn perip 20;                    # max 20 concurrent connections per IP
    limit_req_status 429;
    proxy_pass http://backend;
  }
  location /login {
    limit_req zone=api burst=3;            # tight burst for credential endpoints
    limit_req_status 429;
    proxy_pass http://backend;
  }
}

burst is the bucket size; without nodelay NGINX delays excess requests (leaky bucket) up to the burst, with nodelay it serves the burst immediately and rejects beyond it (token bucket).

1.6.9 Special cases#

  • Login and OTP: 5 attempts per account per 15 minutes with exponential lockout, per-IP limit, CAPTCHA after repeated failures, and alerting on credential stuffing patterns (many accounts from one IP or one account from many IPs).
  • Expensive operations (exports, reports, ML inference): lower limits, queue them, return 202 and process asynchronously.
  • LLM APIs: limit tokens per minute (input + output estimated) as well as requests; reserve budget on request, true up after the response; per-user and per-tenant budgets; priority queues. See LLMOps.
  • GraphQL: limit query depth, complexity score and per-request cost; plain request counts are meaningless.
  • Webhooks you send: rate-limit per destination so a slow customer does not exhaust your workers (bulkheads).
  • Internal service-to-service: quotas per calling service so one team’s batch job cannot take down a shared dependency.

Most asked questions#

1. What is rate limiting and why do we need it? It bounds how much work a caller can submit per time window. It protects availability and fairness (noisy neighbours), downstream dependencies and costs, defends against brute force and scraping, and enforces plan tiers. Finish with the response contract: 429 + Retry-After.

2. Compare token bucket, leaky bucket and fixed window. Token bucket: bounded bursts at an average rate, two numbers per key, most common. Leaky bucket: constant output, smooths bursts via a queue, good when the downstream cannot take spikes. Fixed window: simplest and cheapest, but allows up to 2× the limit at window edges. Sliding window counter fixes the edge problem with two counters and slight approximation.

3. Design a distributed rate limiter. Requirements: limit per user/API key/IP, low latency (< 2 ms added), highly available, accurate enough. Components: limiter middleware in the gateway, config service for rules, Redis cluster with an atomic Lua token bucket, rule cache in the gateway. Return 429 + headers. Failure policy: fail-open by default, fail-closed for login. Scale: shard Redis by key; local lease to reduce round trips. Full walkthrough: Top questions.

4. What status code and headers do you return? 429 with Retry-After, RateLimit-Limit/Remaining/Reset, and a consistent error body. 503 with Retry-After for server-side overload.

5. Where do you place the rate limiter? Layered: CDN/WAF for IP floods, API gateway for per-key limits, service for per-user/endpoint/cost limits, plus bounded queues inside. As early as possible so rejected work is cheap.

6. How do you rate limit by IP when users sit behind a NAT? You cannot be exact: combine IP with a user or API key where authenticated, use generous IP limits for unauthenticated read endpoints and strict ones for login, use device fingerprints or cookies as additional keys, and rely on bot detection rather than lowering the IP limit.

7. How does a client handle 429? Wait for Retry-After, otherwise exponential backoff with jitter, cap retries, retry only idempotent requests, use a budget and a circuit breaker, and shape its own traffic client-side.

8. What happens if Redis is down? Choose by risk: fail-open with a local in-memory fallback limit for general APIs (availability matters), fail-closed for abuse-critical endpoints; alert; keep Redis highly available (replicas, Sentinel/Cluster) knowing async replication can lose a few counts, which only slightly over-admits.

Senior-level questions#

1. “Our limiter says 100/min but customers see bursts of 200 in a minute. Why?” Fixed window boundary effect (100 at the end of one window and 100 at the start of the next), or per-node local counters that are each allowed 100, or a token-bucket burst capacity set to 100 on top of 100/min refill. Fix by using a sliding window counter or token bucket with burst deliberately smaller than the rate, and make the per-node and global limits consistent.

2. “How do you rate limit across 5 regions with a global limit of 1000/min per customer?” Strict global enforcement requires cross-region coordination on every request (too slow). Options: split the budget (200 per region, or proportionally to observed traffic with periodic rebalancing), asynchronous gossip of usage with small over-admission, or route each customer’s writes to a home region. Billing-grade quotas are reconciled from usage logs after the fact, not enforced in the hot path.

3. “A customer says they are rate limited but their dashboard shows 10% of the limit. Debug it.” Check the limiter key (shared NAT IP, API key shared by services, a retry loop from a different integration), where the count is measured (gateway sees retries and health checks, client sees user actions), clock/window alignment, per-endpoint limits, burst settings, whether rejected requests count against them, and whether the customer is hitting a downstream limit (the provider’s 429 passed through). Use the request ID and limiter decision logs.

4. “Design limits for an LLM-backed API where one request can cost 100× another.” Limit on tokens, not requests: estimate input tokens + max_tokens up front, reserve that from a token bucket, refund the unused part after completion. Add concurrency limits per tenant, priority queues so interactive beats batch, per-tenant budgets/day, and global load shedding when the provider returns 429. Surface the remaining budget in headers.

5. “How do you avoid a thundering herd when limits reset?” Clients all waiting for Retry-After: 60 return together at second 60. Add jitter to Retry-After suggestions server-side, use sliding windows or token buckets (continuous refill, no single reset instant), and spread resets (per-key offset windows).

6. “Rate limiting costs us a Redis round trip on a 1 ms endpoint. Optimise.” Local token buckets per node at limit / N with periodic rebalancing; batch token leases from Redis (take 50 tokens, spend locally); probabilistic or sampled checks for non-critical limits; co-locate Redis; use pipelining; accept small over-admission. Measure p99 added latency to decide.

7. “How do you protect against distributed attackers rotating thousands of IPs?” Per-IP limits are useless. Add per-account and per-resource limits, behavioural signals (impossible travel, failed-login ratios), proof-of-work or CAPTCHA challenges after suspicion, device and token binding, WAF bot scoring at the edge, and anomaly detection on aggregate traffic shape; accept that perfect prevention is impossible and aim to raise attacker cost.

8. “Rate limiting vs load shedding vs autoscaling: how do they fit together?” Rate limiting enforces fairness and plan limits per caller. Load shedding protects the system as a whole from overload by dropping low-priority work. Autoscaling adds capacity but takes minutes, so you still need the other two in the meantime. A healthy stack uses all three plus timeouts and circuit breakers.

Quiz#

1. A limit of 100/min with a fixed window: what is the worst-case burst?

200 requests within about a second: 100 just before a window ends and 100 just after the next begins.

2. Token bucket with capacity 10 and refill 2 tokens/s. How many requests can a caller make in the first second after being idle, and in a sustained minute?

Idle with a full bucket: 10 immediately plus about 2 more from refill during the second (≈12). Sustained over a minute: about 10 + 2 × 60 = 130, so the average converges to 2/s.

3. Which algorithm shapes output perfectly smoothly?

The leaky bucket (a queue drained at a constant rate).

4. Why must the check-and-decrement be atomic?

Two concurrent requests could both read the same remaining count and both pass, exceeding the limit. Use a Lua script, INCR, or compare-and-set.

5. 429 or 503 when your CPU is at 95% and a free-tier user calls an endpoint within their quota?

503 (with Retry-After) because the server is overloaded, not the user over limit; ideally shed free-tier and batch traffic first.

6. What does a client do if there is no Retry-After header?

Exponential backoff with full jitter, capped, with a maximum number of attempts and a retry budget.

7. Fail-open or fail-closed when the limiter store is unavailable?

Fail-open for general API traffic to preserve availability (with a local fallback limit); fail-closed for security-critical limits such as login, OTP and password reset.

8. Why are rate limits keyed only by IP a bad idea for authenticated APIs?

Many users share one IP (NAT, offices, mobile carriers) causing false positives, and attackers rotate IPs. Prefer API key or user ID once authenticated; keep IP limits for unauthenticated endpoints.

9. When is a concurrency limit better than a rate limit?

When request durations vary widely (reports, uploads, LLM calls): a fixed rate can still allow unbounded requests in flight, whereas a concurrency limit bounds actual resource use.

10. How do you limit expensive GraphQL queries?

Compute a cost per query (depth, number of fields, list sizes), reject above a threshold and charge a cost-weighted token bucket.

11. Name two ways to reduce Redis load from a rate limiter.

Local token leases or per-node buckets with periodic sync, and batching/pipelining; also sharding hot keys into sub-buckets.

12. Why add jitter to Retry-After values and client backoff?

Without it, clients throttled at the same time return at the same instant and create a synchronized spike (thundering herd).

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes