Skip to content

Lesson 11 of 38Building blocks

Rate Limiting

Protect APIs with fixed window, sliding window, token bucket, and leaky bucket limits, enforced at the gateway with Redis.

24 min read0/6 questions

Without a limit, one buggy script in a retry loop, one scraper, or one attacker guessing passwords can use up all your capacity and take the service down for everyone else. Rate limiting caps how many requests a client can make in a period of time. It shows up in every public API, it is a classic interview question in its own right ("design a rate limiter"), and it is a building block in most other designs.

Why rate limit

  • Abuse and security: slow down credential stuffing on /login, scraping, and denial-of-service floods.
  • Fairness: one heavy customer should not starve the others sharing the same servers.
  • Cost: every request costs compute, and some cost real money downstream (SMS messages, AI model calls, paid third-party APIs).
  • Stability: shed excess load early and cheaply instead of letting it overload the database.

A limit has three parts: who is limited (the key: API key, user id, IP address, or a combination), how much (100 requests per minute, 5 login attempts per 15 minutes), and what happens when they go over (usually reject with 429 Too Many Requests).

Where to enforce it

Client-side limits are polite but anyone can bypass them. The real enforcement belongs on the server, as early as possible: at the API gateway or edge, before the request costs you anything. Because there are many gateway instances, they share counters in a fast central store, almost always Redis.

Rate limiting at the gateway with Redis
Normal clientNormal clientRunaway scriptRunaway scriptGateway 1: rate limiterGateway 1rate limiterGateway 2: rate limiterGateway 2rate limiterRedis: shared countersRedisshared countersAPI serversAPI serversGET /orders500 req/sINCRINCR

A request arrives. The gateway increments the client's counter in Redis: INCR rl:key_abc:1728000060 returns 12. The limit is 100 per minute, so it is allowed.

1/4
Quick check
You run 6 gateway instances. Each one keeps its own in-memory counter and allows 100 requests per minute per API key. What limit does a client actually get?
Need a nudge? A hint rules out a wrong answer.

The algorithms

There are four classic algorithms (one with two variants). Step through each with a limit of 3 requests per second.

Fixed window counter: split time into fixed windows (each whole second, each minute) and count requests in the current one. One counter per client per window; it resets when the window changes. It is the simplest to build, and the flaw shows up at the edges of windows.

Fixed window: the boundary burst
0.7s
0
0.8s
1
0.9s
2
1.0s
3
1.1s
4
1.2s
5
window = 0 to 1 scount = 3

Three requests late in the first window (0 to 1 s). Count hits 3, the limit.

1/3
Predict the outputPython

Sliding window counter: previous window had 8 requests, current has 3, we are 25% into the current window. What is the estimate?

print(8 * 0.75 + 3)
Need a nudge? Hints walk you through it.
AlgorithmMemory per clientBurstsAccuracyNotes
Fixed window1 counterUp to 2x at window edgesRoughSimplest; INCR + EXPIRE
Sliding window logEvery timestampNoneExactExpensive at high limits
Sliding window counter2 countersSmoothedClose to exactGood default
Token bucketTokens + timestampAllowed up to capacityExact average rateMost popular for APIs
Leaky bucketA queueQueued, output smoothExact output rateShapes traffic to a fixed rate
Match the pairs0/4 matched

Pick the algorithm for each requirement.

Choose an item, then its match on the other side.

Token bucket in code

You never need a background timer. Each time a request arrives, compute how many tokens dripped in since the last request, add them (capped at capacity), then try to spend one.

Pythontoken_bucket.py
class TokenBucket: def __init__(self, capacity: float, rate: float): self.capacity = capacity # max burst self.rate = rate # tokens added per second self.tokens = capacity # start full self.last = 0.0 def allow(self, now: float) -> bool: self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate) self.last = now if self.tokens >= 1: self.tokens -= 1 return True return False bucket = TokenBucket(capacity=5, rate=2) # burst of 5, then 2 per second # A burst of 8 requests at t=0, then one every 0.25 s.times = [0.0] * 8 + [0.25, 0.5, 0.75, 1.0, 1.25, 1.5]for t in times: verdict = "200" if bucket.allow(t) else "429" print(f"t={t:4.2f}s {verdict} tokens left {bucket.tokens:.1f}")
Output
Press Run (⌘ Enter) to see what happens.

The burst of 5 passes, the next 3 are rejected, and after that exactly 2 requests per second get through.

Distributed rate limiting with Redis

With many gateway instances, the bucket or counter lives in Redis. A fixed window is two commands:

INCR  rl:{api_key}:{current_minute}     -> returns the new count
EXPIRE rl:{api_key}:{current_minute} 60  (only when the count is 1)

For a token bucket, reading the tokens, refilling, and spending must happen atomically, or two gateways can both read "1 token left" and both allow a request. The standard way is a small Lua script that Redis runs as one atomic operation (or a library like redis-cell that does it for you).

Two practical decisions:

  • Fail open or closed? If Redis is unreachable, most APIs fail open (allow requests) so a cache outage does not become a full outage. Login and payment endpoints may fail closed.
  • Latency: one Redis round trip (about 0.5 ms in the same region) per request is usually fine. At extreme scale, gateways keep local counters and sync to Redis every few hundred milliseconds, accepting slightly fuzzy limits.

Telling clients: 429 and Retry-After

A rejected request gets 429 Too Many Requests, and good APIs say when to try again and how much quota is left, so well-behaved clients can slow down instead of hammering you.

Hitting a rate limit
ClientAPIGET /v1/search?q=boots200 OK, RateLimit-Remaining: 0, RateLimit-Reset: 20GET /v1/search?q=sandals429 Too Many Requests, Retry-After: 20(waits 20 s + jitter) GET /v1/search?q=sandals200 OK

GET /v1/search?q=boots

1/6
Put it in order4 steps

Put a gateway's rate limit check in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Design a rate limiter service: a 10-minute walkthrough

"Design a rate limiter" is often a full interview, or the deep dive inside a bigger one. You already have the algorithms. What the interviewer is testing now is whether you can turn them into a service that many teams use, that adds almost no latency, and that does something sensible when it breaks. Here is how to spend ten minutes on it.

Minutes 0 to 2: pin down the requirements

Ask before you draw. The answers change the design.

  • What is limited, by what key? Per API key on a public API, per user on an app, per IP on login, per tenant for fairness. Often several at once.
  • Hard or soft limits? A limit protecting a fragile database must be close to exact. A limit on a free tier can be off by a few percent and nobody cares.
  • Scale. For example: 500,000 requests per second across 40 gateway instances in 3 regions, 20 million active keys.
  • Latency budget. The limiter sits on every request, so it gets a tiny budget: well under a millisecond at p99 in the common case.
  • What happens on failure? Ask it now, because the answer shapes everything below.

Say the numbers out loud: 20 million keys at roughly 100 bytes each (key name, two counters, an expiry) is about 2 GB, which fits in a small Redis cluster. 500,000 checks per second is too many for a single Redis node to handle comfortably with headroom, so the counters will be sharded.

Minutes 2 to 4: rules as configuration, not code

Teams should be able to add or change limits without a deploy. Limits live in a config file or a small rules store, the limiter reloads them on change, and each rule matches on descriptors (attributes of the request: route, plan, API key, IP). This is the shape Envoy's open source global rate limit service uses:

ratelimit-rules.yaml
domain: public_api
descriptors:
  # Every API key on the free plan: 100 requests per minute
  - key: plan
    value: free
    descriptors:
      - key: api_key
        rate_limit: { unit: minute, requests_per_unit: 100 }
 
  # Paid plan: 2,000 per minute
  - key: plan
    value: pro
    descriptors:
      - key: api_key
        rate_limit: { unit: minute, requests_per_unit: 2000 }
 
  # Login, per IP, regardless of plan: 5 per minute
  - key: route
    value: login
    descriptors:
      - key: remote_ip
        rate_limit: { unit: minute, requests_per_unit: 5 }

Two design points to mention. A single request usually checks several rules (a per-second burst limit, a per-day quota, and a per-IP rule on login), and it is allowed only if it passes all of them. And rules should support a shadow mode that logs "would have rejected" without rejecting, so a new limit can be tested against real traffic before it blocks paying customers.

Minutes 4 to 6: where the limiter runs

There are three placements, and the trade-off is latency against consistency.

PlacementHow it worksGoodBad
In-process libraryEach service imports a library that talks to RedisNo extra hop; simple for one teamEvery language needs a library; every team configures it differently
Sidecar or gateway filterA proxy next to each service (or the API gateway) calls the limiter before forwardingOne implementation for every language; central rulesOne more component on the request path
Central limiter serviceGateways make an RPC to a dedicated rate limit service, which owns RedisSingle place for rules, metrics and storageAn extra network hop on every request; must be as available as the gateway

A common production answer combines the last two: the gateway or sidecar (Envoy, for example) calls a central rate limit service over gRPC, and that service holds the rules and talks to a sharded Redis. Teams get one consistent behavior, and the storage details are hidden behind one API: "may this request with these descriptors proceed?"

A rate limiter service with local caching
ClientsClientsGateway + filter: local counts, deny cacheGateway + filterlocal counts, deny cacheRate limit service: rules, Lua scriptsRate limit servicerules, Lua scriptsRedis Cluster: sharded countersRedis Clustersharded countersRules config: YAML, hot reloadRules configYAML, hot reloadBackend servicesBackend servicesrequestgRPC checkatomic scriptreloadallowed

A request arrives. The gateway extracts descriptors: plan=free, api_key=k_81, route=search.

1/5

Minutes 6 to 8: scaling the counters

Sharding. Spread counters across a Redis Cluster by key. Redis Cluster has 16,384 hash slots, and the key decides the slot, so one client's counters land on one node and the Lua script can run atomically there. If a script touches several keys, they must be on the same slot; a hash tag in braces (rl:{k_81}:minute, rl:{k_81}:day) forces that.

Hot keys. One huge customer, or one IP behind a big corporate NAT, can send a large share of all traffic, and all of it hits one Redis shard. Local counting and a deny cache take most of that pressure off.

Local counts with async sync. Instead of calling Redis on every request, each gateway counts locally, pushes its deltas to Redis every N milliseconds, and pulls back the global total. Latency drops to near zero and Redis load drops by orders of magnitude. The price is overshoot: between syncs, every gateway is working from a slightly old total, so the client can exceed the limit by roughly its request rate times the sync interval. Run it.

Pythonlocal_sync.py
def simulate(gateways: int, limit: int, sync_every: float, rps: int = 200, seconds: int = 60) -> int: """One key, one fixed 60 s window. Requests arrive evenly, round robin across gateways.""" global_count = 0 # the truth, held in Redis known = [0] * gateways # each gateway's last view of the truth unsynced = [0] * gateways # local counts not yet pushed allowed = 0 next_sync = sync_every for i in range(rps * seconds): g = i % gateways if known[g] + unsynced[g] < limit: unsynced[g] += 1 allowed += 1 now = (i + 1) / rps if now >= next_sync: global_count += sum(unsynced) # push deltas unsynced = [0] * gateways known = [global_count] * gateways # pull the new total next_sync += sync_every return allowed LIMIT = 1_050 # per key per minute; the client sends 12,000print(f"{'sync every':>10} {'allowed':>7} {'overshoot':>9}")for interval in [0.0, 0.1, 0.5, 2.0]: if interval == 0.0: allowed = simulate(gateways=1, limit=LIMIT, sync_every=1 / 200) # one shared counter label = "always" else: allowed = simulate(gateways=20, limit=LIMIT, sync_every=interval) label = f"{interval} s" print(f"{label:>10} {allowed:>7} {allowed - LIMIT:>+9}")
Output
Press Run (⌘ Enter) to see what happens.

A shared counter is exact. Syncing every 100 ms lets about 1% extra through; every 2 seconds, about 14%. For a free-tier quota that is a great trade. For "5 login attempts per minute" it is not, so strict, low-volume rules keep checking Redis directly while high-volume, soft rules use local counts. Saying that split out loud is a strong senior signal.

Quick check
Gateways sync local counts to Redis every 500 ms. A client sends 400 requests per second spread across all gateways. Roughly how far past its limit can it get before every gateway sees the true total?
Need a nudge? A hint rules out a wrong answer.

Minutes 8 to 10: failure modes and the edges

Fail open or fail closed, per rule. If Redis or the limiter service is slow or down, the gateway must decide in milliseconds. Set a tight timeout (a few milliseconds) and wrap the call in a circuit breaker, so a sick Redis is skipped quickly instead of adding latency to every request. Most rules fail open, because rejecting all traffic turns a limiter outage into a full outage. Rules that protect against abuse or cost (login attempts, password resets, sending SMS, expensive AI calls) fail closed or fall back to a strict local limit per gateway. Make it a field on the rule, not a global switch.

Multi-region. A single global Redis means cross-region round trips on every check, which breaks the latency budget. The usual answer is per-region counters with the quota split across regions (or a region-local limit plus a looser global reconciliation for daily quotas). Most clients are served from one region anyway, so the error is small.

Time. Fixed windows depend on agreeing what minute it is. Let Redis decide: compute the window inside the Lua script from Redis's own clock, rather than trusting 40 gateway clocks that drift.

Layers. A rate limiter is one layer of defense, not all of it. Volumetric floods are absorbed at the CDN or WAF before they reach you. The gateway enforces per-key limits. Inside each service, a concurrency limit or load shedder protects against the case where traffic is within every quota but the service is still overloaded. Covering all three shows you think about the system, not just the algorithm.

Quick check
Your limiter's Redis cluster becomes unreachable. Which endpoint should fail closed rather than fail open?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

Token bucket rate limiter

Implement a token bucket, the rate limiter behind most API gateways.

  • The bucket holds at most capacity tokens and starts full.
  • Tokens refill continuously at rate tokens per second, never above capacity.
  • allow(now) is called for each request, with now as the time in seconds. If at least one token is available, spend one and return true. Otherwise return false (the API would answer 429 Too Many Requests).

Time is passed in so the limiter is easy to test. now never goes backwards.

b = TokenBucket(capacity=2, rate=1)
b.allow(0)    # True   (2 -> 1 token)
b.allow(0)    # True   (1 -> 0)
b.allow(0)    # False  (empty)
b.allow(1)    # True   (refilled 1 token after 1 second)
class TokenBucket: def __init__(self, capacity: float, rate: float) -> None: pass def allow(self, now: float) -> bool: # Refill based on time passed, then try to spend one token. pass
Key terms
rate limiting
Capping how many requests a client can make per period, to protect capacity, fairness, and cost.
fixed window
Count requests per fixed time slot. Simple, but allows 2x bursts at window edges.
sliding window counter
Weights the previous window's count by its overlap to approximate a true sliding window cheaply.
token bucket
Tokens refill at a steady rate up to a capacity; each request spends one. Allows bursts, caps the average.
leaky bucket
Requests queue and drain at a fixed rate, smoothing traffic. Excess is dropped when the queue is full.
429 + Retry-After
The response for a rate-limited request, telling the client how many seconds to wait.
descriptor
A request attribute (route, plan, API key, IP) that limiter rules match on.
deny cache
A gateway's local memory of keys already over their limit, so repeat offenders are rejected without a Redis call.
fail open / fail closed
Whether requests are allowed or rejected when the limiter itself is unavailable. Chosen per rule.