SproutStackSproutStack home

Design a Rate Limiter

13 min readBeginner-friendlyFree to read

Before this, it helps to know: Failures, Retries & Rate Limits, Caching Basics.

Read a little, play a little. No scary maths, and no rush.

Share:

The problem

A misconfigured script retrying in a tight loop can send thousands of requests a second at your login endpoint. Without a limit, that script (or an attacker doing it on purpose) overloads the database and takes every honest user down with it. A rate limiter caps how many requests one client can make in a period of time and turns the rest away politely.

This lesson builds one the way an interview answer would. The basics come first; the Going deeper parts cover the races, clocks and failure modes that experienced engineers get asked about.

Step 1: Requirements

Try it first: what would you put on each list?

Functional:

  • Limit requests per client: per user ID or API key when signed in, per IP address otherwise.
  • Different limits per endpoint and per plan: login is strict, product search is generous, paid plans get more.
  • Rejected requests get a clear answer: 429 Too Many Requests and when to retry.

Non-functional:

  • Low latency: the check runs on every request, so it should add about a millisecond, not tens.
  • Shared across servers: the limit is per user, not per user per gateway machine.
  • Fault-tolerant: if the limiter breaks, the product should keep working.
  • Accurate enough: letting a few extra requests through is fine; letting 2× through is not.

Clarify one more thing: is this protecting your servers (a safety limit) or enforcing a paid quota (billing)? A safety limit can be approximate. A billing quota needs exact counts and an audit trail, which is a different and slower design.

Step 2: Estimates

  • 10 million users, 50,000 requests per second at peak through the gateways.
  • Each request does one limiter check, so 50,000 checks per second.
  • State per user is small: a token count and a timestamp, roughly 100 bytes with overhead. 10 million users ≈ 1 GB, which fits in memory on one machine.

So this is a small-data, high-throughput problem. Memory is cheap; what matters is that each check is fast and correct when many servers do it at once.

Step 3: Where the limiter lives

Put the check in the API gateway (or a middleware every service shares), before requests reach the backends. Never in the browser: anyone abusing your API is not running your JavaScript.

The gateways are many machines behind a load balancer, so they need one shared count per user. Redis is the usual choice: it is in memory, fast, and has atomic operations.

cachedcheckcheckallowedClientsGateway Alimit checkGateway Blimit checkRedisone key per userRuleslimits per planBackend services
Every gateway checks the same Redis key for a user, so the limit holds no matter which gateway a request lands on.

Load the rules (which endpoint, which plan, what limit) into each gateway's memory and refresh them every minute or so. Reading the rules on every request would double the work for no benefit.

Step 4: Deep dive — choosing an algorithm

Bad: fixed window. Count requests per calendar minute and reset on the minute. Simple, one counter per user. The flaw is the boundary: 100 requests at 0:59 and 100 more at 1:00 means 200 requests in two seconds, both windows "within the limit."

Good: sliding window log. Store the timestamp of every request (a Redis sorted set works) and count those in the last 60 seconds. Exact, no boundary problem. The cost is memory: a user making 1,000 requests a minute stores 1,000 timestamps.

Great: token bucket or sliding window counter. Both are cheap and accurate enough for almost every case.

  • Token bucket: each user has a bucket that holds, say, 100 tokens and refills at 10 per second. A request takes one token; an empty bucket means reject. It allows short bursts (a full bucket) while enforcing a steady average. Stripe has written about using token buckets for its API limits. You store just two numbers per user: tokens left and the time of the last refill.
  • Sliding window counter: keep this minute's count and last minute's count, and estimate the rolling total as current + previous × (fraction of the previous window still inside the last 60 seconds). Two counters per user, and close to exact: Cloudflare reported that only a tiny fraction of requests were misjudged across real traffic.

Pick token bucket when bursts are fine (most APIs), and a sliding window when you want "no more than N in any 60 seconds" to be closer to literally true.

Step 5: Deep dive — making the check atomic

This is where most first designs break. The obvious version reads, decides, then writes:

tokens = GET rate:user:123      # gateway A reads 1, gateway B also reads 1
if tokens > 0:
    DECR rate:user:123          # both decrement
    allow                       # both allow: the limit is broken

Between the read and the write, another gateway can do the same. Both see one token; both let a request through.

Good: decrement first, then check. DECR is atomic and returns the new value. If it is below zero, reject (and optionally add the token back). No gap between reading and writing.

Great: do the whole check in one Lua script. Redis runs a script atomically: no other command runs in the middle. That lets you implement the full token bucket (refill based on elapsed time, cap at the bucket size, take a token, set an expiry) as one step:

-- KEYS[1] = bucket key; ARGV = capacity, refill per second
local capacity = tonumber(ARGV[1])
local rate     = tonumber(ARGV[2])
local t        = redis.call('TIME')                 -- the Redis server's clock
local now      = tonumber(t[1]) + tonumber(t[2]) / 1e6
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) * rate)
local allowed = tokens >= 1
if allowed then tokens = tokens - 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
return allowed and 1 or 0

Load it once with SCRIPT LOAD and call it with EVALSHA, so each check sends only a short hash, not the whole script.

Going deeper: clocks, expiry and the fixed-window trap

Whose clock? Refill depends on elapsed time. If each gateway passes in its own now, one gateway with a clock running fast refills buckets too generously. Reading TIME inside the script means every check uses the same clock. (Recent Redis versions replicate a script's effects, not the script itself, which is why a script can safely read the time.)

Keys that never expire. A common fixed-window bug: INCR key, then EXPIRE key 60 as a second command. If the process dies between the two, the key never expires and that user is blocked for good. Set the expiry in the same atomic step (inside the script, or SET key 0 EX 60 NX before the INCR).

Inactive users. Every bucket gets an expiry, so the 9 million users who are not active right now cost no memory.

Step 6: Deep dive — what clients see

A rejected request gets a proper answer, so honest clients can slow down instead of retrying blindly:

HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0

429 is defined in RFC 6585 and Retry-After is a standard HTTP header. The X-RateLimit-* headers are a widespread convention rather than a standard (an IETF draft proposes standard RateLimit headers). Pair this with exponential backoff with jitter in your own clients, so thousands of them do not retry at the same instant.

Step 7: Failure modes and scale

If Redis is down, the limiter must decide without it. Fail closed (reject everything) turns a cache outage into a full outage. Fail open (allow everything) keeps the product up but drops protection. Many teams fail open with a coarse local limit in each gateway's memory as a safety net: not shared, so not exact, but abuse stays bounded. Put a short timeout on the Redis call (a few milliseconds) so a slow Redis does not slow every request.

If one Redis is not enough, use Redis Cluster. Each user's key lives in one slot, so each check still touches one node, and users spread evenly across nodes. There are no cross-key transactions to worry about because each check uses one key.

Going deeper: hot keys and multiple regions

One very busy key. A single API key sending 30,000 requests a second puts all of that on one Redis node. Options: give each gateway a small local allowance it spends before asking Redis (accurate to within the allowance), or limit very high-volume keys with local token buckets that are reconciled every second. Both trade a little accuracy for a lot less shared work.

Several regions. A Redis round trip across an ocean adds ~100 ms to every request, which breaks the latency requirement. Usually each region enforces its own limit (for example, half the global limit each, or a share based on traffic), and you accept that the global total is approximate. Exact global limits across regions are rarely worth what they cost.

What interviewers expect at each level

  • Early career: explains why a limiter is needed, puts it in the gateway, picks token bucket or fixed window, and returns 429. Needs prompting on multiple servers.
  • Mid-level (2–5 years): compares algorithms with their trade-offs, uses a shared store, makes the check atomic and can explain the race it prevents, and designs sensible keys and limits per endpoint.
  • Senior: owns the failure modes: fail open versus closed with a reason, Redis timeouts, clock skew, keys that never expire, hot keys, and multi-region limits. Separates safety limits from billing quotas, and says how they would roll out a new limit safely (log what would be rejected first, then enforce).

Remember this

  • Limit per user or API key, not globally: one abuser should not punish everyone.
  • Read-then-write is a race. Make the check one atomic step: decrement-and-check or a Lua script.
  • Token bucket allows bursts and enforces an average; a sliding window counter is the cheap, near-exact alternative.
  • Decide in advance what happens when the limiter's store is down. "Fail open with a local backstop" is a common answer.

Check your understanding

5 questions · first-try answers earn the most XP

1. A limit allows 100 requests per minute using a fixed window that resets on the minute. What can a client do that the limit was meant to prevent?
2. Two gateway servers run `GET tokens`, see 1, then each run `DECR tokens`. What goes wrong?
3. Your token bucket script takes `now` from each gateway's clock. One gateway's clock runs 30 seconds fast. What happens?
4. Redis is down for 30 seconds. What does failing open mean, and why do many teams choose it?
5. Signed-in users are limited by user ID. What should anonymous traffic be limited by, and what is the catch?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Practice this in an incident

Related chapters

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.