"Design a rate limiter" is the most common warm-up question in system design interviews, and one of the most commonly failed. Not because it is hard, but because it is easy to answer badly at length.
Most candidates hear "rate limiter" and start listing algorithms: fixed window, sliding window log, sliding window counter, token bucket, leaky bucket. Fifteen minutes later they have compared five algorithms carefully, and they still have not said where the limiter runs. They have not said what happens when Redis, which holds the counters, goes down. They have not said what breaks when one customer sends a hundred times more traffic than everyone else put together.
The algorithms are the least interesting part of this problem. Each one is about twenty lines of code and well documented, and in a real system the choice between them changes almost nothing. The design is decided by something else: one decision you make in the first three minutes, usually without noticing.
A rate limiter is a protection mechanism, not an accounting system. Its job is to keep your service up, not to produce a correct number. Once you accept that, every hard question here gets easier, because you can give up some exactness to get speed, uptime and a lower cost. Candidates who miss this spend the rest of the interview defending a consensus protocol that nobody asked for.
This walkthrough follows a 45 minute interview, with a suggested time for each section. If you remember one thing from it, remember the sentence in bold.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
A rate limiter sits in front of your API. For every request that arrives, it decides whether to let the request through or reject it. A rule looks like "this API key may make 1,000 write requests per minute." Requests past that get an HTTP 429 and never reach your application code.
Before you design anything, work out what you are protecting against. People use the name "rate limiting" for four different problems, and each one needs a different answer.
- Abuse. Scrapers, people trying stolen passwords on your login endpoint, or someone stepping through your
/users/{id}route to collect data. This traffic is deliberate, and the person behind it changes tactics when you block them. - Accidental overload. A customer ships a retry loop with no backoff and sends you 40,000 requests per second by mistake. This is far more common than abuse, and much easier to handle.
- Fairness between customers. One noisy customer uses up capacity that other customers paid for. Nobody is doing anything wrong, but you have to stop one customer from slowing down the others.
- Plan quotas and billing. "Your plan includes 5 million API calls per month."
The first three are rate limiting. The fourth is not, and if you treat it as rate limiting, you end up building a billing system inside your rate limiter. A monthly quota is a billing number. It has to be exactly right, it can run minutes behind, and it gets checked against invoices. A rate limit only has to be roughly right, it must answer in a few milliseconds, and its count is thrown away seconds later. Those are two different systems. We design the rate limiter here, and come back to this split in deep dive 7.
Functional requirements
Core:
- For every request, decide allow or reject against the configured rules, before the request reaches application code.
- Support rules for different identities (API key, logged-in user, IP address, customer account) and different targets (the whole API, a group of routes, a single endpoint). Each rule has its own limit and window.
- Let operators change rules while the system is running, without a deploy.
- Reject with a response the client can do something with, so a well-behaved client can correct itself.
Out of scope, deliberately:
- Authentication. We assume someone upstream has already worked out who the caller is.
- Monthly plan quotas and billing, for the reasons above.
- Bot detection, firewall rules, and absorbing a flood of traffic during a DDoS. Those belong to a different layer.
- Limits on how many requests run at once, and shedding load when servers are overloaded. These are related and useful, but they are a separate mechanism.
Non-functional requirements
- Low latency. The limiter adds under 5 ms at p99, which means 99 of every 100 checks take less than that. It runs on every request, so its slowest responses become your API's slowest responses.
- More available than the service it protects. The limiter must never be able to take down the thing it is defending. That is a stronger promise than "it should be highly available."
- Scale. Peak traffic is 1 million requests per second, from roughly 100 million daily active users (DAU), with tens of millions of live limit keys.
- Approximately correct is correct. Going five percent over a limit is fine. Letting ten times the limit through is not. Blocking traffic that is under the limit is worse than either.
- Keep customers apart. One client's traffic volume must not affect decisions made for any other client.
Requirement 4 is the one everything else rests on. Write it down in exactly those words, because a version that says "must be accurate" will cost you the interview.
The set up
Core entities
The design has four entities.
- Principal. The caller being limited, written with its type in front:
api_key:ak_9f2c,user:u_881,ip:203.0.113.7,tenant:acme. The type matters, because "1,000 per minute" means something very different for an API key than for an IP address. - Rule. The policy. It has a matcher that says which requests it applies to, plus a limit, a window, an algorithm, and what to do on a reject.
- Bucket. The counter for one principal under one rule. It is the only thing in the system that changes on every request. Most of the design is about where the bucket lives, who updates it, and when.
- Decision. The answer: allow or reject, plus which rule fired, how much allowance is left, and when it resets.
System interface
There are two interfaces. The data plane answers one question a million times a second: allow or reject this request? The control plane changes the rules a few times a week. The two have different traffic, different accuracy needs, different behaviour when they break, and different expectations for whoever is on call. So we design them separately.
Data plane:
POST /v1/check
{
"descriptors": [
{ "key": "api_key", "value": "ak_9f2c" },
{ "key": "endpoint", "value": "POST /v1/messages" }
],
"cost": 1
}
200 OK
{
"decision": "ALLOW",
"matched_rule": "rl_write_per_key",
"limit": 1000,
"remaining": 417,
"reset_after_ms": 22400,
"retry_after_ms": 0
}
Three things to note in that payload.
The descriptors are a list, and one call checks all of them. A descriptor is one thing the request should be counted against. A single request usually falls under several rules at once: a limit per API key, a limit per endpoint, and an overall limit for the whole customer account. If the interface checks one rule per call, every request makes three network round trips, one after another, and that uses up the latency budget. So one call checks every matching rule, and the request is rejected if any of them rejects. The rate limit service for Envoy, a widely used proxy, works this way.
cost exists because not all requests are equal. A bulk export puts far more load on the system than a health check. If the caller can declare a weight, one mechanism covers both "1,000 requests per minute" and "1,000 units of work per minute", and you do not need a second system.
remaining and reset_after_ms come back on allowed requests too, not just on rejections. This costs almost nothing, it helps a lot, and most implementations skip it. A client that can see it has 12 of its 1,000 calls left will slow down on its own. A client that only finds out when it is rejected can only retry and hope.
The control plane is ordinary create, read, update and delete (CRUD) over rules. Every rule is versioned, and there is a record of who changed what. The interface is plain on purpose, but deep dive 6 shows why rule changes still need a deploy pipeline and not just a form.
High-level design
We will work through the functional requirements in order. Each one forces a decision.
1. Where should the limiter run?
Choose a place before you choose an algorithm. The place changes the design more than the algorithm does.
In-process counters in each service
Every service instance keeps its own counters in memory. There is no shared state, no network call and no dependency.
It also does not work. With a limit of 1,000 per minute and 200 instances behind a load balancer, the real limit is anywhere between 1,000 and 200,000, depending on how requests spread. Pinning each client to one instance does not fix it, because instances come and go as you scale, and the mapping keeps changing. Counters kept on one instance cannot enforce a limit across all of them.
It is still useful as a second layer, behind the shared one. Deep dive 5 uses it that way, as the fallback when Redis is down.
A dedicated rate limit service, backed by a shared data store
The gateway calls a rate limiter service over the network. The service owns the counters, which live in a shared data store such as Redis. Every instance sees the same numbers, so the limit is enforced as written.
This is the standard answer, and it is correct. Lyft's ratelimit service, which Envoy calls, works this way, and most companies run something like it. You get one place to deploy the limiter logic, one owner for Redis, and a clean interface.
The cost is one extra network hop plus one Redis round trip on every request, and a new hard dependency in front of every service.
Decide in the gateway, with quota leased from a central authority
This design removes the extra hop. The limiter runs in the gateway, as middleware inside the gateway process or as a sidecar process next to it. The gateway already handles every request and already knows the principal. The limiter keeps a small block of allowance in local memory, and tops up that block from Redis every so often instead of on every request.
Most requests make no network call at all, and Redis sees only a fraction of the traffic. The gateway also keeps making decisions when Redis is unreachable, just less precisely.
The cost is that each decision uses slightly stale information. The total across the fleet can go over the limit by the amount of allowance the gateways are holding. That is acceptable, because requirement 4 says approximately correct is correct. You give up accuracy that the requirements said you could give up, and you get the latency and uptime that they said you must have.
For the rest of this walkthrough, the gateway enforces the limit, with shared state in Redis behind it. This keeps both the per-request path and the failure story simple.
2. Identify who is being limited
Use a lasting identity when you have one, and fall back to a network one. For traffic you can authenticate, count against the API key or the user ID. These are stable, they belong to a real customer, and an attacker cannot get a new one cheaply.
For traffic you cannot authenticate, you only have the IP address, and it fails in both directions. Mobile carriers put thousands of unrelated users behind one address. A per-IP limit is then either so loose that it protects nothing, or so tight that it blocks many innocent users at once. Meanwhile an attacker can rent a few thousand addresses for very little money and get past the limit easily.
But the endpoints you cannot authenticate are the ones that need the most protection: login, signup, password reset, and anything that sends an email or an SMS. So use two layers. Limit each address, and add a looser limit on a wider group. That group can be the surrounding /24 block, the 256 addresses that share the first three numbers, or the whole network the traffic came from. An attacker who rotates through addresses in a rented range then resets the first counter but not the second. Neither layer is good enough on its own. Together they make abuse expensive.
Next, work out how many distinct keys you can end up with, because the key format decides that. If the client controls part of the key, it can create as many keys as it likes, each with a fresh allowance, and then there is no limit. The common case is counting against the raw path. /users/12345/messages and /users/12346/messages become separate keys, and the limit stops working. Normalise the path to the route template, /users/{id}/messages, before you build the key.
Here is a key format that works:
rl:v1:{ak_9f2c}:write_per_key
│ │ └── rule id, so different rules never collide
│ └── principal, in hash-tag braces so all of one
│ principal's rules land on the same shard
└── schema version, so you can change the format later
The braces are Redis Cluster hash tags. Redis Cluster splits keys across shards, each a separate Redis node, and normally picks the shard by hashing the whole key. When part of the key is wrapped in braces, it hashes only that part, so every key for one principal lands on the same shard. That lets a single script check all of that principal's rules in one round trip. It is a small piece of syntax with a large effect on the design, and knowing it shows you have built this before.
3. Which algorithm decides?
Now we can choose an algorithm. Four are worth knowing, and the useful way to compare them is by what they cost, not by how they work. Simple arithmetic rules out two of them.
Fixed window counter
Split time into fixed windows that line up with the clock, for example one minute each: 11:00:00 to 11:01:00, then 11:01:00 to 11:02:00. The state is one number per window: how many requests have arrived in it so far. It is stored under a key that names the window, such as rl:{rule_id}:{principal}:{window_start}.
Every request runs Redis's INCR on that key. INCR adds one and returns the new count in the same call. If the count is over the limit, the request is rejected. On the first increment in a window, the limiter also sets an EXPIRE for the window's length. The key then deletes itself when the window ends, and nobody has to reset it. The whole cost is one INCR per request, one EXPIRE per window, and a single integer of state. No algorithm here is cheaper.
It also has a flaw, and ordinary traffic triggers it.
A client can send its whole allowance at the end of one window, and its whole allowance again at the start of the next. That puts twice the limit through in a couple of seconds. It does not take an attacker. Any client with a cron job that runs on the minute does it by accident, and so does every other client with a job on the minute, at the same moment. The result is a spike across your whole customer base every sixty seconds.
Sliding window log
Store each request's timestamp in a Redis sorted set, with the time as its score. On each check, the limiter drops entries older than the window with ZREMRANGEBYSCORE, adds the new timestamp with ZADD, and counts what is left with ZCARD. If the count is over the limit, the request is rejected. It is exact, it has no boundary problem, and it is the simplest idea on the list.
It also cannot work at our scale, and one calculation shows why.
A client limited to 1,000 requests per minute holds 1,000 sorted-set members. Each member costs roughly 100 bytes once you include the member string, the score, and skiplist overhead. per key 1,000 × 100 B ≈ 100 KB 10M keys 10,000,000 × 100 KB ≈ 1 TB Compare a token bucket, which stores two numbers: per key ~200 B with Redis overhead 10M keys ≈ 2 GB Roughly 500× the memory, and every check is an O(log N + M) write (N = current set size, M = expired entries dropped) instead of a counter increment.
That is a terabyte of memory, spent on exactness that requirement 4 says you do not need. Say that out loud and move on. The calculation is enough to rule it out.
There is a second problem. Redis runs all the commands for a shard on a single thread. While one script walks through ten thousand sorted-set members, every other command on that shard waits. This does more damage to your slowest responses than the memory does to your bill.
Sliding window counter
This is the approximate version, and the right default when the limit is stated as a window. It keeps two counters, as two separate Redis keys: one for the current window and one for the previous window. To estimate the recent rate, it counts the current window in full. It counts the previous window in proportion to how much of it still falls inside the last sixty seconds.
estimate = current_count + previous_count × overlap_fraction
at 11:01:15 with a 60s window:
25% into the current window, so 75% of the previous window
is still inside the trailing 60 seconds
estimate = 30 + (90 × 0.75) = 97.5 → under 100, allow
This assumes traffic in the previous window was spread evenly, and real traffic is not. Cloudflare measured how much error that assumption causes. Across 400 million requests from 270,000 distinct sources, 0.003 percent of requests were wrongly allowed or wrongly blocked. On average, the estimate was about six percent away from the real rate. No source under the threshold was blocked, and the few sources that got through wrongly were less than fifteen percent over.
So the error is three thousandths of one percent, and it costs two counters instead of a terabyte. Quote that measurement in the interview. It is much stronger than saying the error is "small."
Token bucket
A bucket holds up to capacity tokens and refills at rate tokens per second. Each request takes one token, or cost tokens. If the bucket is empty, reject.
No background timer adds tokens. The bucket refills when it is read. When a request arrives, the limiter works out how many tokens have built up since the bucket was last touched, caps the total at capacity, and then decides. The state is two numbers: the token count and the time of the last refill.
The reason to prefer it is not accuracy. It has two knobs instead of one. Real requirements almost always come in two parts: "1,000 requests per minute sustained, but allow a burst of 100." The burst part exists so that a page load firing several calls at once is not rejected. A token bucket sets both parts directly: capacity=100, rate=16.7/s. Window-based algorithms have one knob, so you have to choose between allowing bursts and holding a sustained rate. Stripe's public writeup describes this exact setup, with a token bucket per user in Redis. The read, the arithmetic and the write all run inside one Lua script, a small program that Redis runs on the server, so no other command can run in between.
Leaky bucket needs only a short mention. Instead of saying yes or no straight away, it puts requests in a queue and lets them out one at a time at a fixed rate, so the output is perfectly smooth. The cost is that requests wait in line instead of getting an instant answer. That is bad when the client is waiting with a timeout. Know that it exists, and do not use it here.
Choosing
| memory / key | ops per check | bursts | boundary problem | knobs | |
|---|---|---|---|---|---|
| Fixed window | ~150 B | 1 atomic incr | allows 2× at boundaries | yes, severe | 1 |
| Sliding log | ~100 KB | O(log N + M) write | exact | none | 1 |
| Sliding counter | ~250 B | 1 script | bounded, ~6% error | negligible | 1 |
| Token bucket | ~200 B | 1 script | bounded by capacity | none | 2 |
Default to the token bucket. Its two knobs, burst size and sustained rate, match the way limits are usually described. It costs about the same as the sliding window counter, one script per check, and far less than the sliding window log.
Use a fixed window counter only for cheap, rough limits where the boundary burst does not matter. An example is a very high ceiling per customer whose only job is to catch a runaway retry loop. It is one INCR, which is cheaper than running a script.
Use the sliding window counter when the requirement is stated as a trailing window, like "1000 requests in any rolling 60 seconds."
Never use the sliding window log in production.
4. What stops two requests reading the same counter?
This question shows whether you have built a rate limiter or only read about one. Everything above assumed that checking a counter and updating it happen as one step, with nothing in between. By default they do not, and the error is large.
GET the counter, decide, SET it back
This takes two round trips, which doubles the latency the limiter adds. The bigger problem is the gap between the read and the write. During that gap, every other instance can read the same old value.
For example, a client is at 999 of 1,000 and sends 200 requests at once across your gateway fleet. All 200 read 999, all 200 see room for one more, and all 200 are allowed. You have admitted 1,199 requests against a limit of 1,000, and the same thing happens on the next burst. The error grows with the number of requests in flight at once, so it gets worse as your traffic grows.
Atomic primitives, or a Lua script for anything more complex
For a fixed window, INCR returns the new value and cannot be interrupted. One command updates the counter and returns the value the decision needs, and nothing more is required.
The token bucket and the sliding window counter have to read state, do arithmetic, and write back, so they use a Lua script. Redis runs the script on the shard that owns the key, with no other command in between, and the whole check is one round trip.
The script does four things. It reads the bucket's tokens and last refill time, and works out how many tokens have refilled since then. It checks whether there are enough for this request. If there are, it spends them and saves the new state. Here it is in Lua:
-- KEYS[1] = the bucket's key
-- ARGV[1] = now_ms, ARGV[2] = capacity, ARGV[3] = refill_per_sec, ARGV[4] = cost
local now_ms = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local refill_per_sec = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
-- 1. Read what's stored. If this bucket has never been touched before,
-- treat it as full, refilled just now.
local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local last = tonumber(state[2]) or now_ms
-- 2. Work out how many tokens should have refilled since last time,
-- capped at capacity so it can't overfill.
local elapsed = math.max(0, now_ms - last) / 1000
local filled = math.min(capacity, tokens + elapsed * refill_per_sec)
-- 3. Not enough tokens: deny, and report what's left.
if filled < cost then
return { 0, math.floor(filled) }
end
-- 4. Enough tokens: spend `cost` of them, save the new state, and let
-- the key expire on its own if this principal goes quiet.
redis.call('HSET', KEYS[1], 'tokens', filled - cost, 'ts', now_ms)
redis.call('PEXPIRE', KEYS[1], 120000)
return { 1, math.floor(filled - cost) }
Say two things about this script without being asked. First, the caller passes in now, and the script does not read the clock itself, so the same inputs always give the same result. Second, every key a script touches has to live on the same shard. That is why the principal sits inside hash-tag braces in the key. It lets one script handle all of a principal's rules together, instead of one call per rule.
Avoid WATCH, MULTI and EXEC here. Together they make an optimistic transaction: if another writer changes the key in between, the transaction fails and you retry. Collisions are most likely on your busiest keys, and those are the keys where you can least afford retries.
Stop doing it per request
Ask a different question: why does every request need a Redis operation at all?
Each gateway instance asks the shared bucket in Redis for a block of tokens, say 50, in one atomic call. This is a lease. The call takes up to 50 tokens off the shared bucket and tells the instance how many it got. It gets fewer if the bucket was running low. The instance spends those tokens from its own memory, one request at a time, without calling Redis. When they run out, it asks for another block. Redis operations drop by a factor of the block size.
Leasing has two costs, and you should name both.
First, a lease takes tokens off the shared count the moment it is granted. But the instance can spend them whenever it likes, even after the window that granted them has ended. So unspent tokens can leak across a window boundary. Whatever is left in an instance's memory when a new window starts gets spent on top of the new window's fresh allowance, and the new window never counts it. The most that can leak is instances × block_size. With 200 instances and a block of 50, that is up to 10,000 extra requests. For a limit of 1,000 that is unacceptable, and for a limit of 10 million it does not matter. A short lease expiry limits how long a block can survive, and so how much can leak across a boundary. It shrinks the leak, but it does not remove it.
Second, if an instance goes quiet or crashes while it holds unspent tokens, those tokens are lost. Nobody else can use them, and the customer gets that allowance back only as the bucket refills. So keys with little traffic need a smaller block, and then less is lost at once.
So the block size is set per rule, not as one default for everything. Size it in proportion to the key's traffic, and keep it small enough that the worst case above stays inside your five percent tolerance.
This is the same trade as before: some accuracy for speed. This time you make it on purpose, with a number behind it instead of a guess.
Which data store, and why persistence is actively wrong
By now there are two storage decisions: where the counters live, and where the rules live. They end up in different data stores for opposite reasons. The counters are the surprising one, because for them durability costs a lot and gives nothing back.
A durable database for the counters
This is the first thing most people reach for. A counter looks like ordinary data, so it feels natural to store it like everything else. You put it in Postgres or DynamoDB, and read the value, update it and write it back inside one transaction. The result is correct and easy to inspect.
Now compare it with the requirement. Every request waits for a durable write on the hot path, the code every request runs through. That write is a write-ahead log flush, replication to a follower, and a transaction commit. All of it has to fit inside a 5 ms budget, for a check that is supposed to be nearly free. And you pay for durability on data that is only useful for one window.
An in-memory store, replicated for availability
Counters live in memory, in a data store like Redis. Reads and writes take microseconds, the atomic increment is a single operation, and the 5 ms budget is no longer tight.
Each node replicates to a replica asynchronously, so a node failure does not lose every counter at once. Most candidates reach this answer, and it is correct enough to pass.
In memory, and turn persistence off on purpose
Go one step further and say something that sounds wrong: do not persist the counters at all, and do not replicate them synchronously.
A counter is only useful for one window, usually a second to a minute. If a node dies and its counters are lost, the principals on it start again from zero. Each gets at most one extra window's allowance, and then the system is correct again. The error has a known size, and it fixes itself.
Compare that with what persistence gives you. A user would never notice the difference, and persistence has two costs. Every request pays for a durable write. And when you recover from a crash, the state you replay is already out of date by the time it is restored. Requirement 4 says approximately correct is correct, and this is the third place the design relies on it.
| data store | what goes in it | the requirement that forces it |
|---|---|---|
| in-memory, sharded, no persistence | counters and token buckets | a 5 ms budget on every request, and state whose value expires within one window |
| the config data store, read through a local cache | rules: limits per principal, per route | read on every request but changed rarely, so it is replicated to every gateway and read from memory |
| an analytics data store, append-only | rejection events, for tuning limits | write-only on the hot path, queried offline, and never read by the limiter itself |
| nothing | history of allowed requests | already in your access logs, and duplicating it buys nothing |
All of this is safe because the data is worthless within seconds. That fact lets you skip persistence, skip synchronous replication, and reshard without worrying about it (deep dive 3). A candidate who says "Redis" has named a product. A candidate who says "this state expires in one second, so durability buys nothing a user would notice" has explained the choice. That answer also explains why any in-memory data store would do, and why the expensive options are no better.
The state, and why it is barely a schema
There are no tables on the hot path. Here is all the state there is:
# The counter. One key per (principal, rule, window).
# key rl:{rule_id}:{principal}:{window_start}
# value integer
# ttl 2 x window (long enough for the sliding
# window counter to read the
# previous window, no longer)
# The token bucket. Two fields, written together.
# key tb:{rule_id}:{principal}
# value { tokens: float, last_refill_ms: int64 }
# ttl idle timeout, so silent principals evict themselves
# The rules. Small, relational, replicated to every gateway.
rules (
rule_id bigint primary key,
scope smallint, -- api_key | user | ip | route
match text, -- which principals it applies to
limit_count int not null,
window_ms int not null,
burst int, -- token bucket only
version bigint not null, -- for safe rollout
updated_at timestamptz
)
Three things to note.
The key includes the window, so expiry does the cleanup. With window_start in the key, each new window gets a new key. Old keys are removed by their TTL (time to live), not by explicit deletes. There is no sweeper job and no delete rate to worry about.
The token bucket stores a timestamp, not a schedule. Tokens are refilled lazily: the limiter works them out from the elapsed time when it reads the bucket. So no background job updates every bucket. A bucket nobody touches costs nothing, and that matters because most principals are idle most of the time.
Rules carry a version, so you can tell when a rollout has finished. If a rule change reaches half your gateways and then something goes wrong, two different sets of rules are running at once. That is worse than not pushing the change at all. So each gateway reports which version it is running. The rollout is complete only when every gateway has confirmed it moved past the old version.
The operations that carry the product
Only one operation matters here, and it runs on every request. It is the sliding window counter check from earlier, as a single atomic Lua script:
-- KEYS[1] = current window's key, KEYS[2] = previous window's key
-- ARGV[1] = window_ttl_ms, ARGV[2] = overlap_fraction, ARGV[3] = limit
local window_ttl_ms = tonumber(ARGV[1])
local overlap_fraction = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
-- 1. Increment the current window's count. If this is the first
-- request in the window, make it expire once the window ends.
local cur = redis.call('INCR', KEYS[1])
if cur == 1 then redis.call('PEXPIRE', KEYS[1], window_ttl_ms) end
-- 2. Read the previous window's count. 0 if it's already expired.
local prev = tonumber(redis.call('GET', KEYS[2]) or 0)
-- 3. Estimate the rate: this window in full, plus however much of
-- the previous window is still inside the trailing period.
local est = cur + prev * overlap_fraction
-- 4. Allow if that estimate is under the limit. Report it either way.
return { est <= limit and 1 or 0, est }
-- Runs on rule change, not per request. Gateways poll or
-- subscribe, then serve every decision from local memory.
SELECT rule_id, scope, match, limit_count, window_ms, burst, version
FROM rules WHERE version > $1;
The script runs hundreds of thousands of times a second and must be a single round trip, so it is one script and not three separate calls. The query runs a handful of times a day.
That ratio sums up the storage design. One operation matters, and it runs in memory. Everything else is configuration. If you find yourself designing indexes or joins for a rate limiter, you have added a data store the problem did not need.
5. What should a rejection actually say?
A rejection is an API response, and it needs the same care as a successful one. If you treat it as an afterthought, blocked clients often retry harder and send you more traffic than before.
Use 429, and keep it distinct from 503. A 429 means "you went over your allowance." A 503 means "we are unhealthy." The client should react differently to each, and they belong on different dashboards. If you mix them, you cannot tell a customer's runaway script from your own outage.
Always send Retry-After. This header tells the client how long to wait, and it changes how clients behave. Without it, the client can only guess. In practice it guesses by retrying straight away, and your limiter ends up handling more traffic than your API did before you installed it. A rejection without a retry hint makes a load problem bigger.
Vary the retry hint per client. If you tell 10,000 blocked clients to come back in exactly 30 seconds, you create a spike 30 seconds from now. Add a small random amount, called jitter, to the value for each client. Do not count on clients to do this themselves. Some will, but most will not.
Send the limit state on successful responses too. The common headers are X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, and GitHub and most large APIs send them. A client that can see it has 12 calls left will slow itself down. A client that slows itself down is worth more to you than any limit you enforce at the edge.
Do not queue rejected requests. If you hold a request until allowance frees up, you add delay for a caller who has probably timed out already. You also turn a cheap rejection into a connection and memory you have to hold. Reject the request and let the client come back.
Log denials with the rule that caused them. Without the rule, nobody can answer the support ticket "why is my integration getting throttled", and you will get that ticket. Log a sample rather than every denial, but always include the rule ID.
Deep dives
The deep dives you get depend on the interviewer and on the level you are interviewing at. The first three come up far more often than the rest.
1. How big does Redis need to be?
Here the design gets real numbers. Do this arithmetic in the interview. It takes ninety seconds, and it changes the answer.
Active keys
1M req/s peak, average active principal makes ~10 req/min
→ 1,000,000 × 60 / 10 ≈ 6M active principals per minute
× 3 rules each ≈ 18M live keys
Memory
token bucket entry, with key string and Redis overhead ≈ 200 B
18M × 200 B ≈ 3.6 GB
→ comfortably one node
Throughput
1M checks/s, one atomic script each
a Redis shard handles ~100k simple ops/s with headroom for p99
1,000,000 / 100,000 = 10 shards minimum
plus headroom for failover and peak
≈ 20 shards
Memory says one node. Throughput says twenty.State the gap plainly: this cluster is sized by operations per second, not by how much data it holds. Most data stores are the other way round, so the habit of sharding because the data is big will mislead you here. You are sharding for CPU.
Now go back to leased quota with a block size of 50, and run the throughput line again. You get 20,000 operations per second instead of a million, and that fits on a single primary with a replica. Batching does more than reduce load on the cluster. It removes the need for a cluster. Twenty nodes become two, with far less that can break and nothing that spans shards. The numbers show that the staff answer from earlier holds up.
But the 20,000 figure assumes every rule can be leased, and that is not true. Small limits cannot be leased at all, so they still go to Redis once per request. Deep dive 3 works out how much of the traffic can realistically be leased. The conclusion still holds, but only because of that traffic split. State the split as an assumption, because batching alone does not guarantee the result.
Three more settings to note.
- Replication: asynchronous, and never wait for it. A counter increment lost during a failover costs you a handful of extra allowed requests. Waiting for replication adds latency to 100 percent of requests. The first cost is far smaller.
- Persistence: off, or as close to off as your operations team allows. This data is worthless within seconds, so a disk write on the hot path buys nothing. After a cold restart every key starts empty, which briefly gives everyone a fresh window. If that matters, warm up from a replica rather than from disk.
- Eviction: let idle keys expire. Every write to a counter also sets an expiry a little longer than the key is needed. For a fixed window that is the window itself, so the expiry might be 65 seconds for a 60-second window. A sliding window counter also reads the previous window, so its keys need two windows, as the state block above shows. The extra 5 seconds is a safety margin against ordinary timing differences, such as network delay and command processing time. It does not need to be exact. Without a TTL, a key never disappears on its own. Every principal who ever made one request keeps a key in Redis forever, including someone who used your API once a year ago and never came back. Your key count then keeps growing toward everyone you have ever seen. It should stay near the number of principals active right now, because that is the number you sized the data store for.
maxmemory-policy = allkeys-lruis the backstop for when your TTL logic has a bug anyway. When memory runs out, Redis deletes the least recently used (LRU) keys to make room, instead of refusing writes or crashing. In the worst case, a rarely used principal's counter resets a little early and gets a slightly larger allowance than it should. That is a small accuracy cost you can live with. Without the backstop, the same bug fills memory and takes the whole node down. Then you lose the whole rate limiter, not just some of its accuracy.
2. Where does the 5 ms go?
The limiter runs on every request, so its slow responses become your API's slow responses. If the limiter takes 50 ms one time in a thousand, your API's p999, the slowest one request in a thousand, rises to about 50 ms. That shows up in your public latency graphs.
same-AZ Redis round trip 0.4 to 1.0 ms cross-AZ round trip 1.0 to 2.0 ms Lua script execution 0.02 to 0.1 ms serialization + connection checkout 0.1 to 0.5 ms ───────────────────────────────────────────────── one round trip, same AZ ~1.5 ms typical two round trips, cross-AZ ~5 ms, budget gone
Five rules follow from this.
One round trip per request, never several. Check every matching rule in a single script, over keys that live on the same shard. That is why the keys use hash tags and why the API takes a list of descriptors.
Open your connections in advance, and size the pool for peak. Opening a connection per request is an obvious mistake. A less obvious one is a pool that is big enough for typical load (p50) but turns into a queue at p99. Time spent waiting for a connection never appears in your Redis metrics, so these slow responses are hard to trace. Measure the wait on the client side.
Set a tight timeout, and treat a timeout as allow. Use five to ten milliseconds. The version that goes badly wrong has no timeout at all. Redis gets slow, every gateway thread waits on it, and the thread pool fills up. A short Redis slowdown becomes a full outage, in a service that had fail-open logic the whole time. Failing open means allowing the request when the limiter cannot answer. The logic was right, but the deadline was missing.
Remember the shard is single-threaded. One expensive command delays every other command on that shard. Cap the work any script can do, and never let a script loop over a collection with no size limit, such as the sliding window log's sorted set. Keep the KEYS command out of production completely. It scans the whole keyspace and blocks everything else while it runs. On a database with millions of keys, it can stall a shard for seconds. This is not the KEYS[1] in the Lua scripts above, which is just how a script receives its key arguments. The standalone KEYS command is the dangerous one.
Cross-AZ writes cannot be avoided in the obvious layout. An availability zone (AZ) is a separate data centre within a region. Writes go to a primary, and the primary sits in one AZ. So two thirds of a gateway fleet spread over three AZs pay a cross-AZ hop on every request. You can pin shards per AZ, but then each count covers only one AZ, and the global limit is no longer real. The other option is to call Redis less often, which is leasing again: one call per 50 requests instead of one per request. Fewer calls also means fewer cross-AZ hops. So the fix that solved throughput and cluster size solves this too. When one mechanism solves three problems, it is usually the right one.
3. How many gateway instances, and what does the fleet size break?
Interviewers rarely ask "how many servers" directly. The question comes inside other questions: how a gateway finds the limiter service, what happens when the fleet scales up in the middle of an incident, and what breaks when you add a shard. Each of those depends on a number the design has assumed without stating, so work it out first.
Step 1: how many gateway instances are there? 1M req/s peak, one gateway handles ~5,000 req/s comfortably 1,000,000 / 5,000 = 200 instances Step 2: how much can leasing overshoot the limit, worst case? every instance could be sitting on a full unspent block at once: worst case overshoot = instances × block_size Step 3: how big can a block be and stay under the 5% overshoot allowed by requirement 4? block_size ≤ 0.05 × limit / 200 instances limit 1,000/min → max block 0.25 cannot lease at all limit 10,000/min → max block 2.5 limit 100,000/min → max block 25 limit 10,000,000/min → max block 2,500 Step 4: at what limit does the max block size finally reach 1 token? 200 instances / 0.05 tolerance = 4,000 per minute below that, no block size satisfies the 5% tolerance at all
A limit below roughly 4,000 per minute cannot be leased at all on a fleet this size. The block would have to be smaller than one token. State this bound whenever you propose leasing. It follows from one multiplication.
So leasing is decided per rule, not for the whole system. Rules with large limits lease generous blocks. Rules with small limits go to Redis on every request, which is what the senior answer already did. The staff answer does not replace the senior one. It adds leasing on top, for the rules where the arithmetic allows it.
This means the throughput figure from deep dive 1 needs another look, because it assumed every rule could be leased.
Assume 90% of your total traffic falls under large limits, the enterprise API keys and per-tenant ceilings, and the remaining 10% falls under small limits (a strict per-IP limit, a tight per-user limit) too small to lease at all, per the previous section. These are aggregate req/s across however many principals fall into each bucket, not a single rule's own limit. Validate this split with the interviewer, because it is doing a lot of work here. leasable traffic 900,000 req/s / 50 (block) = 18,000 ops/s unleasable traffic 100,000 req/s × 1 = 100,000 ops/s ────────────────────────────────────────────────────────────── total ≈ 118,000 ops/s vs 1,000,000 with no leasing at all → 8.5× reduction shards at ~100k ops/s each → 1.2, call it 2 If the split is 80/20 instead, the total is 216,000 ops/s and you need three shards rather than the two above.
Twenty shards still come down to two or three, so the earlier conclusion holds. But it holds because of a traffic assumption, not because of batching alone, so state the assumption when you make the claim. Traffic under small limits sets the minimum load on Redis, and batching cannot reduce it.
Leasing also brings two new problems, and both need coordination that the design did not need before.
First, the fleet size now affects correctness. If autoscaling takes you from 200 instances to 400 during a spike, every block size you chose for 200 instances can now overshoot by twice as much. So each instance needs to know roughly how many instances there are. You do not need a gossip protocol for this, where instances keep telling each other who is alive. The control plane already pushes rules to every gateway, so it can push the current count of healthy instances on the same channel. Each gateway then calculates its block size from that count. The count can be a few seconds stale, because the bound changes slowly. Erring on the safe side costs a few extra Redis calls, not correctness.
Second, a shrinking fleet is the dangerous direction. Scaling down, or a routine rolling deploy, stops instances that still hold unspent leases. Those tokens are lost, and the customer gets them back only as the bucket refills. So during a deploy, the customer's real limit drops below what they are paying for. The fix is to have each instance hand back its unspent tokens when it shuts down cleanly. That removes the dip during deploys, and it is one line in your shutdown hook. Keep the lease expiry short as well, ten to thirty seconds. Expiry does not give tokens back, but it limits how long a quiet instance can keep spending old ones.
How a gateway finds the limiter service only matters in the senior design, where the limiter is a separate process. Use the service discovery your platform already has, such as Kubernetes Endpoints or Consul. Register a new limiter instance when it is ready, not when it starts. A new instance has not yet opened its Redis connections or loaded its Lua scripts. If it takes traffic straight away, its first requests are slower or fail. So the load balancer should send it traffic only once it is ready. Also keep discovery off the request path. Look up the endpoints in the background, cache the result, and keep using the last good set when discovery is unavailable. The rule cache in deep dive 6 works the same way, for the same reason: stale data is better than no data.
Resharding Redis while it is live is risky for almost any other kind of data store, but here it costs almost nothing. Redis Cluster divides keys into hash slots, and resharding moves slots between nodes. While a slot moves, the counters in it can be lost or briefly split across two nodes. On most systems that is a real incident. Here it costs a handful of extra allowed requests during the move, because the data is worthless within seconds anyway. In a data store of record, such as a database holding user data, losing or splitting records during a move would be a real loss.
The same property that let you skip persistence, skip synchronous replication, and fail open now makes resharding harmless too. Say that out loud. One requirement, approximately correct is correct, makes all four of these safe.
When the limiter itself is the bottleneck, shed load rather than queue it. A circuit breaker is a switch in the client that stops calling Redis once calls keep failing. If Redis is saturated and the timeout keeps firing, the breaker should switch the gateways to their local buckets and keep the fleet serving. Never let requests pile up waiting for a limiter decision. That is the same mistake as a Redis call with no timeout: nothing limits how long you wait, so a slow dependency turns into a full outage.
4. Hot keys and contention
Traffic is never even. Suppose one enterprise customer, or one attacker with a valid key, sends 200,000 requests per second under a single principal. That principal's key hashes to exactly one shard.
Two things break. The shard is over capacity, and it also serves thousands of other customers. So requirement 5, keeping customers apart, no longer holds: one client's traffic now slows down everyone who shares that shard.
Add more shards
This does not help. Adding shards spreads keys across more nodes, but it does not split a single key. Under any scheme that hashes keys to shards, one key belongs to one partition. So a single hot key cannot be divided, however large the cluster gets. If you add a hundred nodes, the key still lands on one of them.
Split the counter into sub-buckets
Replace one key with N keys, rl:...:0 through rl:...:N-1, each with a limit of limit / N, and send each request to one of them at random. The sub-bucket number has to go inside the hash-tag braces, as in {ak_9f2c:3}, or every sub-key still hashes to the same shard. The sub-keys then spread across shards, and the load on any one shard drops by roughly N.
The cost is some unfairness near the limit. Random routing fills the sub-buckets unevenly, so a request can be rejected by an empty sub-bucket while another one still has room. With a small N, 8 to 16, the error is a few percent and well inside tolerance. With a large N the error grows quickly, so do not raise N without a reason.
Split per key, not everywhere. Most principals never need splitting, and splitting all of them multiplies your key count and memory for nothing. Detect the hot keys and split only those.
Batch, then stop asking about hopeless keys
The staff answer makes two moves. The first is leased quota again, and here the hotter the key, the better batching works. A key at 200,000 requests per second with a block size of 50 makes 4,000 Redis operations per second. You can also raise the block size for that one key, because its traffic uses up even a large block in milliseconds. Batching works best exactly where the problem is.
The second move is for abuse. If a principal has been fully blocked for the last several seconds, asking Redis again tells you nothing new. The gateway remembers the denial locally for one second and stops calling Redis for that principal. An attacker sending 200,000 requests per second now costs one Redis operation per second per instance, instead of 200,000, and their requests are still rejected.
The cost is that when the client's allowance frees up, the gateway can take up to a second to notice. For a client that has been over its limit the whole time, that second does not matter.
5. What happens when Redis goes down?
Start from requirement 2: the limiter must never be able to take down the service it protects. If the limiter is a hard dependency of the gateway, the service's availability is the two availabilities multiplied together. Adding the protection has then made the service less available.
Fail closed: reject everything when Redis is unreachable
This turns a cache outage into a total outage. Whatever risk you were guarding against was smaller than being completely down.
A worse version is also common: the call to Redis has no timeout. Every request waits until the network gives up, the gateway's thread or connection pool fills with waiting requests, and the service stops serving. This happens even when the fallback says fail open, because the code never reaches the fallback. The bug is the missing deadline, not the policy.
Fail open, with a tight timeout and a circuit breaker
On a timeout or an error, the limiter allows the request. The timeout is 5 to 10 ms. A circuit breaker sits in front of Redis. Once Redis is clearly down, the breaker opens, and requests stop waiting for the timeout and fail open straight away.
This is correct, and enough for most interviews. Name the remaining risk yourself. Redis is often unhealthy because the system is under stress. So failing open removes your protection at the moment you need it most. The staff answer fixes this.
Fail open to a local limit, not to unlimited
Every gateway instance keeps a small token bucket per key in its own memory, sized at roughly the global limit divided by the number of instances, plus some slack. In normal operation it never rejects anything, because the central limiter is stricter and rejects first.
When Redis becomes unavailable, the local bucket becomes the limiter. The limit changes from "1,000 per minute, coordinated globally" to "somewhere between 1,000 and 2,000 per minute, rough and uncoordinated." That is acceptable for the length of an incident. The damage now has a bound, and you no longer have to choose between no protection and no service.
This is the in-process approach from the first decision, used as a second layer instead of the main one. It also covers a case teams rarely plan for, where Redis is up but slow. The local layer keeps limiting while the circuit breaker waits for Redis to recover.
This local fallback also protects you from your own mistakes. Suppose someone ships a broken deploy of the limiter, or pushes a bad rule that removes a limit by accident. The local layer still enforces its own rough cap, so the mistake cannot let all traffic through unchecked. This matters more for your own mistakes than for Redis failures, because your team is more likely to break something than Redis is.
6. How does a rule change reach the fleet without causing an outage?
Few candidates bring up the control plane, and some of the worst outages in this system start there.
Matching and precedence. A request can match several rules. The limiter checks all of them and rejects if any rejects, as Envoy does. When two rules cover the same requests, the more specific one wins. When rules load, build the matchers into a structure that is fast to look up, such as a hash map keyed by route template plus a sorted list for the general rules. Then the limiter does not have to compare every rule against every request.
Distribution: push, with polling as a backup. Gateways hold rules in memory, so no request ever waits for config. Pushing changes over pub/sub gets them out in under a second, which you need when you are trying to stop an incident. Polling every 10 to 30 seconds limits how stale a gateway can get. You need it because a pub/sub message can be missed, and without polling, an instance could run stale rules forever without anyone noticing. Push gives you speed, and polling makes sure every gateway catches up eventually.
A config failure must be safe. If the rule service is unreachable, each gateway keeps serving the last rules it knew were good, for as long as it takes. The two other options are both wrong: falling back to "no rules" means no limit, and falling back to "deny" means an outage. Stale rules are the right answer here, and a rule set fifteen minutes old is fine.
Fast propagation also spreads mistakes fast. A rule change reaches all of your traffic. Someone types 100 where they meant 100000, and within a second an enterprise customer's whole integration starts getting 429s, because the push is fast. A mistake that spreads fast causes a bigger outage than one that spreads slowly.
So ship rule changes the way you ship code, with four safeguards.
- Shadow mode. Every new or changed rule first runs with a "shadow" flag set. The limiter evaluates it on every request and logs what it would have decided, but the flag stops it from rejecting anything. You then check the log. If the rule would have blocked your largest customer, you fix it before it ships. Once the log shows the rule is safe, you remove the flag. Nothing else in the control plane gives as much value, and it costs almost nothing to build.
- Staged rollout. Enforce on one percent of gateway instances, then ten, then all.
- Versioning with instant rollback. Rules are immutable versions, and rolling back means selecting the previous version, not editing fields under pressure.
- A record of changes. Who changed what, when, and why. The first question in an incident review is always "what changed."
7. Can the limit be exact across regions?
Sooner or later someone asks for a limit that is exact across regions. The answer has two parts.
First, you cannot have it cheaply. A round trip between regions takes 60 to 150 ms, so you cannot put one on every request. It would also make each region's request path depend on another region's health, and avoiding that is the reason you run several regions in the first place.
There are three practical options, from least to most work.
- Per-region limits, documented as such. Nothing is split or coordinated, and customers are told the limit applies per region. Many large APIs do this. It is a fair answer as long as you say it out loud, and do not imply a global limit you do not enforce.
- Static allocation. Divide the global limit across regions in proportion to how much traffic each one normally gets. It is simple, needs no coordination, and works while traffic stays where you expect. It breaks during a regional failover. One region suddenly takes all the traffic and starts rejecting it, while another region's share sits unused.
- Allocation with background rebalancing. A controller checks demand in each region every few seconds and moves quota between regions. The coordination happens off the request path, so the latency budget is untouched, and the split adjusts within seconds. You build this if the limits are part of a contract.
Second, go back to the split from the first section. If the requirement is exact global counting, month over month, checked against an invoice, then it is not a rate limiter. It is a metering pipeline. Each request emits a usage event, and a background job adds the events up. Enforcement lags by seconds to minutes, and billing checks the totals on a slower path. A metering pipeline has a different accuracy requirement, a different latency budget, different failure behaviour, and a different team on call.
Say this in the interview, because this is the trap the question is built around. Candidates who accept "it must be exact and global" as a requirement then spend twenty minutes designing consensus for a component whose whole job was to be cheap and fast.
8. How do you know it is working?
This deep dive is short, but include it. Experience of running a limiter shows here more clearly than anywhere else.
You need to answer four questions quickly: how much traffic is being rejected right now, which rule is rejecting it, which customers are affected, and whether a proposed rule change would have rejected anything.
- Metrics: decisions by rule and outcome, limiter latency as a histogram rather than an average, Redis error rate, and circuit breaker state. Also count how many decisions were served from local state rather than from Redis.
- Deny rate is a product metric, not just an ops metric. A sudden rise means either an attack or a customer integration that broke five minutes ago, and those need very different responses. Alert on a sudden change rather than on a fixed threshold. A fixed deny-rate threshold means nothing when customers differ this much.
- Watch how many distinct label values you create. A metric like
decisions_total{rule, outcome}is cheap: a few dozen rules times two outcomes is a few dozen time series. If you addprincipalas a label instead, you get one time series per API key per rule per outcome. That is tens of millions of series, and it overloads your metrics backend. It tends to happen during an incident, when many new keys appear at once. Keep per-principal detail in sampled logs and a top-N summary instead of in metric labels.
Final design
The path of one request:
- The request arrives at the edge and reaches a gateway instance, which has already worked out the principal from the API key or session and normalised the route to a template.
- Rate limiter middleware looks up the matching rules in its in-memory cache, which was filled by a push and is kept fresh by polling.
- If the instance still holds unspent leased allowance for those rules, it decides locally and the request continues. No network call.
- Otherwise it makes one script call to the shard that owns that principal's keys, checking every matching rule together, and takes out a block of allowance sized to how much traffic that key gets.
- If any rule rejects, the gateway returns 429 with
Retry-After, varied per client, and the rule ID goes to the sampled denial log. If every rule allows, the request proceeds and the response carries the remaining allowance so the client can pace itself. - If Redis times out or the breaker is open, the instance's own local bucket decides instead. Coarser, still bounded, never blocking.
- Every decision emits a metric labelled by rule and outcome, never by principal.
These numbers justify the shape. Peak traffic is a million requests per second, with roughly 18 million live keys at about 200 bytes each. If every rule can be leased, leasing cuts Redis load to roughly 20,000 operations per second, which one primary with a replica serves comfortably. With the 90/10 traffic split from deep dive 3, it is about 118,000, or two shards. A request that reaches Redis costs about 1.5 ms in the same AZ. A request served from a lease costs almost nothing.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
Breadth matters more than depth here, and it is fine if the interviewer leads you through the structure.
You should get the requirements right, and pick one algorithm with a real reason for it. You should see that per-instance counters cannot enforce a global limit, and put the state in a shared data store. You should know what a 429 is, and that a retry hint goes with it.
Expect the interviewer to drive the deep dives. You do not have to raise atomicity, hot keys or the control plane yourself, but you should be able to reason about them once the interviewer raises them.
Senior
You should drive the structure without prompting, and raise three things yourself.
Atomicity. If you describe a read, then a decision, then a write, and never say they must be one operation, that usually ends a senior loop. Reach for INCR or a Lua script and say why.
Real numbers. Size the data store. Interviewers expect you to notice the gap between what memory needs and what throughput needs. If you get to "this is sharded for operations per second, not for data size", you are answering at senior level.
A coherent failure story. Fail open, with a tight timeout and a circuit breaker, and say plainly that failing closed turns a dependency outage into a total outage. Getting this wrong is disqualifying more often than any algorithm mistake.
When asked about uneven traffic, you should get to splitting a counter into sub-buckets, and understand why adding shards does not help a single hot key.
Staff+
A correct design is still the bar. A staff+ answer also decides what not to build.
State the accuracy trade as a requirements decision, early, and use it to cut scope. This is what the whole question is built to test.
Question whether the data store belongs on the request path at all, and get to local enforcement with leased quota. Then put a bound on it. The overshoot is the fleet size times the block, so the block size has to come from the limit and the instance count, not from a round number. If you notice that small limits cannot be leased at all, you show that you have sized the technique, not just heard of it.
Separate rate limiting from quota metering, and say plainly that exact global counting is a different system with a different accuracy requirement.
Treat rule changes as a question of how much damage they can do. Bring up shadow mode, staged rollout and versioned rollback. Nothing else in this question shows operating experience as clearly.
Be able to say what you would not build: coordination between regions on every request, exact counting, a queue for rejected requests, and persistence on the counter data store. A team could spend a quarter on any one of these. Naming them as deliberate omissions is worth more than adding another box to the diagram.
Sources
This article takes inspiration from these pieces, and they're worth reading in full!
- Cloudflare, How we built rate limiting capable of scaling to millions of domains. The origin of the sliding window counter error analysis: 400 million requests, 270,000 sources, 0.003 percent misclassified.
- Stripe, Scaling your API with rate limiters. Token bucket in Redis with Lua for atomicity, and the argument for running several distinct limiters rather than one.
- Lyft, Announcing Ratelimit and the envoyproxy/ratelimit source. Where the descriptor model and the reject-if-any-rejects behaviour come from.
- IETF httpapi working group, RateLimit header fields for HTTP. It is still a draft after many revisions, which shows the standard is not settled yet.