AlgoViz

Design a rate limiter

medium 45 min

Protect services against overload, abuse and surprise bills.

Practise it on the whiteboardGuided steps, draw your design, and get AI feedback on the drawing and your answers.

Video lesson · Chapter 1 of 5

Admit one request and spend one token

0:00 / 3:58

Token bucket rate limiter

1:17Reel

Design a rate limiter in one picture
Design a rate limiter in one picture

Theory

Read or listen first. About 1 min.

What it is

A rate limiter decides whether a request may go ahead, based on how many the same caller has made recently. Over the limit, it refuses politely or makes the caller wait.

The rule has three parts: who is counted (a user, a key, an address), how many are allowed, and over what time.

As a design problem the algorithm is the easy part. The hard part is that twenty gateways must agree on one count, within a millisecond or two, even while parts of the system fail.

Why it exists

Without limits, one broken script or one attacker can use up a service that thousands share. Limits keep it fair, protect the systems behind it and control cost.

A limiter also has to be fast, because it runs on every request, and correct when many servers count at once.

A short history

  1. 1980s

    Network engineers shape traffic with leaky bucket and token bucket schemes, still the basis of many limiters.

  2. 1997

    HTTP/1.1 (RFC 2068) includes the Retry-After header, which tells a client when to come back.

  3. 2000s

    Public web APIs publish limits per key, and limits become part of API design.

  4. 2012

    RFC 6585 adds status code 429 Too Many Requests.

Words to know

Token bucket
Tokens drip in; each request takes one. Allows short bursts.
Leaky bucket
Requests leave at a steady rate.
Fixed window
A counter for each minute, with a weak point at the boundary.
Sliding window
Counts the last 60 seconds, not the current minute.
429
The status that says too many requests.
Fail open
If the limiter breaks, let requests through.
Fail closed
If the limiter breaks, refuse.
Atomic
Read, decide and write as one step that nothing can interrupt.
Hot key
One caller whose counter gets far more traffic than others.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3NumbersWork out a number when the answer changes what you build.
  4. 4API and dataThe contract first, then the data that serves it.
  5. 5DesignStart with the smallest system that works. Change it only when something breaks.
  6. 6Deep divesCompare the options before you open them, then say which you would pick.
  7. 7Explain your choicesAnswer first. Then compare your reasoning.
  8. 8By levelThe same question is judged differently for mid, senior and staff.
  9. 9MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Intercept. An API gateway or middleware inspects the request and extracts the client identifier.

Understand it

Start here

One ticket, many doors

A school has a group ticket for ten pupils. The stadium has several doors, and the pupils may use any of them.

Turnstiles that share one tally
Door 110 of 10stop

The tally is the design problem. The turnstile is easy.

A rate limiter caps the number of requests an entity can make within a specified time window. It prevents backend exhaustion from rogue clients, stabilizes shared resources against noisy neighbours, and helps defend against brute-force attacks.

Four pages, four views

Step 1

Core algorithms compared

Four common rate-limiting algorithms

  1. 1

    Token bucket

    A bucket holds up to N tokens. Tokens replenish at a constant rate. Each incoming request consumes one token. If tokens remain, the request passes; otherwise, it is dropped. Allows short bursts up to bucket capacity and requires O(1) memory.

  2. 2

    Leaky bucket

    Requests enter a FIFO queue of fixed capacity and drain out at a strictly uniform rate. If the queue overflows, new requests drop. This shapes traffic into a perfectly steady output but adds latency to queued requests.

  3. 3

    Fixed window counter

    Time is divided into fixed intervals like 60-second windows. A single counter increments on every call. It is cheap to store, but traffic concentrated right at window boundaries can deliver twice the allowed limit within a brief span.

  4. 4

    Sliding window counter

    A hybrid approach that estimates request density using a weighted sum of the previous and current window counts. It all but removes the boundary spike while using only O(1) memory per client.

Step 2

High-level architecture

One request through the limiter

A client sends a request with an API key to the gateway, which finds the rule and runs one atomic script on a Redis counter. Allowed requests go to the backend; others get a 429.
The gateway reads the API key or token, finds the route rule, and one atomic Lua script counts the request in Redis.

Place rate limiting in an API gateway or reverse proxy rather than embedding it deep within individual business services. This stops excess traffic at the perimeter before it consumes application threads, database connections, or compute instances.

The parts

PartDoes
Limiter in the gatewayReads the caller, finds the rules, asks the store, passes or refuses, adds headers
RedisHolds the counts, runs the atomic script, forgets idle callers by expiry
RulesWhich limit for which caller and route, changed while running
MonitoringShare refused per rule, errors, extra time, health of the store, patterns of abuse

Step 3

Atomic sliding window with Redis

Distributed rate limiters rely on a shared store such as Redis. Checking the count and updating it in two separate network calls introduces a race condition where concurrent requests both read an outdated counter and pass through.

The race

Lua
local key = KEYS[1]local now = tonumber(ARGV[1])local window = tonumber(ARGV[2])local limit = tonumber(ARGV[3])-- Drop timestamps older than current windowredis.call('ZREMRANGEBYSCORE', key, 0, now - window)local current = redis.call('ZCARD', key)if current < limit then  redis.call('ZADD', key, now, now .. '-' .. ARGV[4])  redis.call('PEXPIRE', key, window)  return {1, limit - current - 1}else  return {0, 0}end
Sliding window log using a Redis sorted set inside an atomic Lua script. ARGV[4] is a unique request id, so that two calls in one millisecond do not overwrite each other.

This script is exact, and stores one entry for each passed call. Use it for small limits. For large ones, keep a token bucket in the same kind of script: see Deep dives under Interviews.

Step 4

HTTP headers and client feedback

When rejecting traffic, return HTTP status 429 Too Many Requests. Include explicit headers so well-behaved clients can throttle their own retry cycles instead of hammering the endpoint.

HTTP
HTTP/1.1 429 Too Many RequestsContent-Type: application/jsonRetry-After: 30RateLimit-Policy: "default";q=100;w=60RateLimit: "default";a=0;w=30{  "error": "rate_limit_exceeded",  "message": "Rate limit exceeded. Try again in 30 seconds."}
Retry-After is the standard. RateLimit and RateLimit-Policy are from an unfinished IETF draft, whose syntax changes between versions (in version 12, a is what is left and w the window in seconds). Many APIs still send X-RateLimit-Limit, -Remaining and -Reset.

Step 5

Resilience and distributed trade-offs

Centralized Redis Cluster

  • Exact counts across all gateways of a region.
  • Simple policy enforcement without local node synchronization.
  • Native TTL support cleans up idle client keys automatically.

Pure Local In-Memory Counters

  • Traffic imbalances across nodes can lead to unpredictable limits.
  • Each caller may get the limit once per gateway.
  • Requires state sharing protocols like gossip to stay consistent.

Why local counts are not enough

40+35+30=105>100worst case: 20 gateways×100=2,00040 + 35 + 30 = 105 > 100 \qquad \text{worst case: } 20\ \text{gateways} \times 100 = 2{,}000
Three servers with 40, 35 and 30 each believe they are far below 100.

Ways to share a count

WayExtra timeExactnessUse
Central Redis in the regionabout 1 msExact while it is healthyDefault
Gossip between gatewaysnoneLate by the exchange intervalVery high volume, rough limits
Same caller to the same gatewaynoneExact until gateways changeWhen the balancer can hash by key
Leased tokens from Redisnone for most callsNever over, sometimes refuses earlyHot callers

Step 6

Rules engine and identification keys

Rate limits must not be applied uniformly. Structure rules to match different dimensions: client identity, client tier, and requested endpoint.

Key generation dimensions

  1. 1

    By IP address

    Useful for unauthenticated endpoints. However, multiple users behind a corporate NAT share an IP, and malicious actors can rotate IP addresses easily.

  2. 2

    By user or API key

    The preferred choice for authenticated systems. Ensures users receive their contracted tier limits regardless of which network or device they connect from.

  3. 3

    By endpoint cost

    Resource-intensive operations like report generation or checkout should have stricter limits than lightweight cache reads.

JSON
{  "id": "api-free-tier",  "name": "Free Tier API Limit",  "priority": 10,  "match": {    "path": "/api/*",    "methods": ["GET", "POST"],    "userTiers": ["free"],    "headers": { "x-api-version": "v1" }  },  "subject": "account",  "limit": 60,  "window": "1m",  "onStoreFailure": "local",  "action": "reject",  "response": { "status": 429, "message": "Upgrade to Pro for higher limits" }}
One rule as data.

Rules by priority, example numbers

PriorityRuleLimit a minuteIf the store fails
100POST /api/login, per address and per account name5Strict local limit
50POST, PUT and DELETE, per account100Local limit
10Plan: free, pro, enterprise60; 1,000; by contract, 10,000 and moreLocal limit
1Everything else, per address300Local limit
First match wins, so the order matters. If several limits should hold together, collect all matches and check all in one script.

Finding the rule

Step 7

One request, start to end

The whole path

And when Redis is slow

Step 8

Before it goes live

Checklist

  • Redis shards with replicas
  • One script for check and count
  • Local fallback for each rule
  • Headers, and Retry-After on 429
  • Metrics and alerts
  • Rules changed while running
  • Timeout and circuit breaker to Redis
  • Refusals logged with the rule
  • Limits by plan
  • Connection pool

Common mistakes

  • No expiry: memory grows for ever
  • GET then SET
  • Blocking everything when Redis is down
  • One limit for all endpoints
  • Only by address
  • No headers for clients
  • Redis as the only defence

Summary

The whole topic in one minute.

A rate limiter keeps one caller from using more than a fair share.

Token bucket suits bursts; a sliding window is smoother than a fixed one. Count in one shared place with an atomic step, tell the client when to retry, and decide in advance what happens when the limiter itself fails.

Grow it step by step: one gateway, one shared Redis, rules as data, shards and replicas, a local memory of refused callers, then a share of the limit for each region.

  • Token bucket allows short bursts; a sliding window counter is smooth with O(1) memory.
  • Use atomic Redis operations with Lua scripts to eliminate race conditions.
  • Always return HTTP 429 alongside Retry-After, and show limits on every answer.
  • Place rate limiting at the gateway to drop excess load early.
  • Fail open with a local limit for standard traffic; stay strict for logins and money.
  • Remember refused callers locally, and give each region its share.

Sources