Skip to content

Design a Distributed Rate Limiter

Intermediate 76 min read Part 17 of 18

Design a 1M req/s rate limiter: algorithm choice, gateway placement, atomic Redis Lua counters, rule config, fail-open vs fail-closed and multi-region limits.

The Problem#

A rate limiter decides, for every incoming request, whether the caller is still within their allowance. The allowance is something like "100 requests per minute per user" or "10 searches per second per API key". Requests within the limit pass through. Requests over the limit are rejected straight away with HTTP 429 "Too Many Requests", plus headers that say how long to wait.

We will design the limiter for a large social media API. It sees about 1 million requests per second from 100 million daily users, spread across many gateway machines and several regions. The limiter has to give one consistent answer even though no single machine sees all of a user's traffic. It must add only a millisecond or two to each request. It must also keep working, or fail in a controlled way, when its own storage breaks.

This question comes up a lot in interviews because it is small enough to finish and deep enough to separate levels. A mid-level answer picks an algorithm and puts Redis behind it. A senior answer finds the race condition in the naive Redis code and fixes it with an atomic script, then shards the counters. A staff answer covers what happens when Redis is down, when traffic arrives in three regions at once, when an operator needs to cut a limit in the middle of an attack, and when the limiter itself becomes the bottleneck.

The underlying concepts (the algorithms, their maths, and where limits sit in a system) are covered in Rate Limiting and Throttling. This page applies them to one concrete system and makes every decision explicit.

Clarifying Questions#

QuestionAssumed answerWhy it matters
Are we limiting HTTP requests, or business actions such as "posts per day"?HTTP requests per endpoint. Business quotas are a later extension.Request-level limits must be checked on the hot path in about a millisecond. Business quotas can be slower and must be durable.
Who is the client: user, IP address, API key, or a mix?A mix. Signed-in traffic uses the user ID, developer traffic uses the API key, and anonymous traffic uses the IP.The identity becomes the counter key. It decides the shard, the fairness, and how easy the limit is to dodge.
What scale?1M requests/s at peak, 100M daily active users, about 20 gateway clusters across 3 regions.One Redis node handles about 100k simple operations per second, so 1M checks per second forces sharding.
How much latency may the check add?Under 2 ms at p99 within a region. The hard ceiling is 10 ms, after which we stop waiting.This rules out a remote service in another region and pushes us toward co-located state and strict timeouts.
How exact must the limit be?Approximately right is fine. Letting through 1-5% extra for a few seconds is acceptable. Never letting through 10 times the limit.Approximate limits let us use eventual consistency across regions and local fallbacks. Exact global limits would need coordination on every request.
Do limits differ by plan or endpoint?Yes. Free, pro and enterprise tiers, plus tighter limits on expensive endpoints such as search and upload.We need a rule engine with matching and priorities, not one hard-coded number.
Must rule changes take effect quickly?Normal changes within a minute. Emergency cuts during an attack within about 5 seconds.This decides poll-based versus push-based configuration delivery.
What happens when the limiter's storage is down?Decide per endpoint. Most endpoints degrade to local limits, and sensitive ones such as login fail closed.This is the fail-open versus fail-closed decision, and it changes the availability of the whole API.
Should excess requests be queued or rejected?Rejected with 429 for interactive traffic. Queuing is only for internal batch work.Queues hide overload, use up memory and make latency unpredictable.
Is there a global limit to protect the backend as a whole?Yes. Each service has a fleet-wide capacity limit in addition to the per-client limits.Per-client limits do not stop a million well-behaved clients from overloading the system together.
Do we need analytics on who was throttled?Basic metrics and sampled logs only. Deep analytics are out of scope.Throttle decisions should be emitted asynchronously so that logging never slows the check.

Requirements#

Functional#

  1. Identify the client of each request by user ID, API key or IP address, and find which rules apply to it.
  2. Enforce configurable rules, such as "free users get 100 requests per minute on the timeline endpoint", across every gateway and region.
  3. Reject over-limit requests with HTTP 429 and headers that state the limit, the remaining allowance and the reset time, so clients can back off politely.
  4. Change rules at runtime without a deploy, including emergency changes that apply within seconds.

Out of scope: long-term storage of counters, rich analytics over throttling data, billing-grade quotas (monthly API call allowances that must never be lost), and full DDoS mitigation. We will show where DDoS defences plug in.

Non-Functional#

  • Low latency. The check adds under 2 ms at p99 in-region and never more than about 10 ms in total. The limiter sits on every request, so 5 ms of extra latency at p99 shows up in every endpoint's p99.
  • High availability. The limiter must not take the API down. A limiter outage should mean somewhat looser or slightly stricter limits, not a dead site. Target: the limit-check path is at least as available as the gateway (99.99%).
  • Scale. Handle 1M checks per second at peak, with tens of millions of active counters. Add capacity by adding shards.
  • Accuracy that is good enough. Within one region, limits are close to exact: at most a few requests over. Across regions they are eventually consistent: excess is bounded and short-lived. Strong global consistency is explicitly out of scope.
  • Fairness and isolation. One abusive client, or one hot key, must not slow down the limiter for everyone else.
  • Operability. Rules can be changed safely: validated, versioned, tried in shadow mode, rolled out gradually, and rolled back fast.

Which of these matter most? Latency and availability come first, because the limiter wraps every single request. Accuracy is deliberately relaxed, because that relaxation is what buys us latency and availability. A limiter that is exact but adds 30 ms, or one that takes the API down when Redis restarts, causes more harm than the abuse it prevents. This trade-off is the CAP Theorem and PACELC in miniature. During a partition we choose availability, so we serve and enforce approximately. With no partition we choose latency over consistency: we use local or regional state rather than a global round trip.

Capacity Estimation#

We only compute the numbers that change the design. See Back-of-the-Envelope Estimation for the method.

Traffic. Assume a peak of 1M requests per second. With a day of about 10^5 seconds and a peak around 2.5 times the average, the average is about 400k requests per second. That is roughly 35 billion requests a day. Every one of them needs a decision.

Checks per request. A request is rarely governed by a single rule. A typical signed-in request matches three: the user's per-endpoint rule, the user's overall rule, and a per-IP rule that catches account farms. Some rules can be checked entirely in memory, for example a global fleet-wide limit that each gateway enforces locally as its share. Say 2 rules per request need shared state. At peak that is about 2M counter updates per second.

What one Redis primary can do. A Redis primary handles around 100k simple commands per second on its single main thread. A token-bucket Lua script does several hash reads and writes plus some arithmetic, so a realistic figure is 50k-80k script runs per second per primary. We want 50% headroom for spikes and for re-sharding, so we plan for 40k per primary. The cluster then needs 2M / 40k = about 50 primaries, each with at least one replica, so roughly 100 Redis processes. This is the number that forces sharding. One Redis node, or even a few, cannot do it.

Memory. State is small. A token bucket is two fields: the token count and the last refill time. Stored as a small Redis hash, it costs about 100-150 bytes including key and overhead. Suppose 30M distinct users are active in a busy hour, with 2 bucket keys each, plus 20M distinct IP keys. That is 80M keys × 150 B ≈ 12 GB in total, or about 240 MB per primary. Memory is not the bottleneck: throughput is. This would change with a sliding-window log. A user allowed 1,000 requests per minute keeps up to 1,000 timestamps, which in a sorted set is about 64-100 KB for that user alone. One million heavy users would then need around 100 GB. That memory cost is the first argument against the log algorithm at this scale.

Network. One script call is about 150-250 bytes in each direction, including key names and arguments. At 2M calls per second that is roughly 0.5-1 GB/s across the cluster, or 10-20 MB/s per primary. That is well within a 10-25 Gbit NIC. Connection count matters more than bandwidth. Suppose 2,000 gateway processes each keep 4 connections to each of 50 primaries. That gives every primary 8,000 client connections, which is manageable, but it is why we use multiplexed or pooled clients and not one connection per request.

Latency budget. In the same data centre, a network round trip is about 0.5 ms. The script itself runs in 10-50 µs. Client-side work (serialising the call, sitting in the pool queue, parsing the reply) adds another 0.1-0.3 ms. So a check costs about 0.6-1 ms at p50 and 1.5-2 ms at p99 when the Redis shard is healthy and in the same zone. A cross-zone hop adds 1-2 ms. A cross-region hop adds 80-200 ms, which is completely outside the budget. This one calculation explains most of the design: state must live in the same region, ideally the same zone, as the gateway that asks.

Rule set size. Even a large platform has thousands of rules, not millions: per-endpoint and per-tier rules plus a few thousand per-customer overrides. In memory that is under 10 MB, so every gateway can hold the whole rule set. Matching a request against it is a hash lookup, not a database query.

What these numbers imply:

  • 2M updates per second means sharded Redis, using Redis Cluster or client-side consistent hashing, with about 50 primaries.
  • 12 GB of state means the data fits in memory easily. We are buying throughput, not capacity.
  • A sub-2 ms budget means one round trip per check, atomic logic on the server side, and state in the same region.
  • Thousands of rules means rules are cached in every gateway and pushed or polled. They are never looked up per request.

Core Entities#

  • Rule: a policy such as "tier = free, endpoint = POST /tweets, 300 per 3 hours, token bucket, burst 50". It has a match condition, a client dimension (user, key or IP), an algorithm with its parameters, a priority, and an action on breach.
  • Client: the thing being limited, identified by a user ID, an API key, an IP address or prefix, or a combination such as user plus endpoint. Each client has one counter per applicable rule.
  • Counter (bucket state): the live state for one rule and one client. For a token bucket that is the token count and the last refill time. It lives in Redis with a TTL and is safe to lose.
  • Request context: what the gateway knows about a request: verified identity, tier from the token claims, method and route, source IP, region, and timestamp.
  • Decision: allow or deny, plus the remaining allowance, the reset time and the rule that decided. The decision becomes response headers and a sampled log event.
  • Rule set version: an immutable, versioned snapshot of all rules. Gateways load one, and operators promote, canary and roll back versions.

API Design#

The limiter has two interfaces: the internal check that gateways call, and the control-plane API operators use to manage rules. Clients never call the limiter directly. They only see its effects in response headers.

# Data plane: internal check (in-process library call or local sidecar; never a cross-region RPC)
check(ctx: { clientKeys: {user?, apiKey?, ip}, route, method, tier, cost = 1 })
  -> { allowed: bool, limit, remaining, resetAt, retryAfterSec?, ruleId }
 
# What the client sees on success
HTTP/1.1 200 OK
RateLimit-Policy: "timeline";q=900;w=900
RateLimit: "timeline";r=412;t=37
X-RateLimit-Limit: 900   X-RateLimit-Remaining: 412   X-RateLimit-Reset: 1767225600
 
# What the client sees when over the limit
HTTP/1.1 429 Too Many Requests
Retry-After: 37
X-RateLimit-Limit: 900   X-RateLimit-Remaining: 0   X-RateLimit-Reset: 1767225600
{ "error": "rate_limited", "rule": "timeline-free", "retry_after": 37 }
 
# Control plane: operators only, authenticated, audited
POST   /v1/rules                     { match, dimension, algorithm, params, action }  -> { ruleId, version }
PUT    /v1/rules/{ruleId}            { ...changes, mode: "shadow" | "enforce" }        -> { version }
DELETE /v1/rules/{ruleId}                                                              -> 204
POST   /v1/rulesets/{version}/promote  { canaryPercent }                               -> 202
POST   /v1/rulesets/rollback         { toVersion }                                     -> 202
GET    /v1/clients/{key}/usage                                                         -> { rules: [...] }
POST   /v1/blocks                    { key, reason, ttlSec }                           -> 201

A few notes on this API. cost lets expensive calls, such as a bulk export, use up several tokens instead of one. The X-RateLimit-* headers are a widely used convention that is not formally standardised. The IETF HTTP API working group has a draft that defines RateLimit and RateLimit-Policy headers, and many APIs send both styles during the transition. Control-plane writes are idempotent by version: promoting the same version twice changes nothing. They are audited, because a bad rule can take down an API just as surely as a bad deploy.

High-Level Design#

We build the design one functional requirement at a time, starting with the simplest thing that could work and adding a component only when a requirement forces it.

1) The system identifies the client and finds the applicable rules#

Two decisions come first, and they depend on each other: where the limiter runs and which identity it keys on. Where it runs decides what it can see. A gateway sees headers, the path and the IP. An application server also sees the database view of the user. What it can see decides which identities are practical.

Where it sits. There are three classic placements, compared fully in Deep Dive 2:

  • In-process in each application server. This is very fast because counters are in local memory, but each server only sees its share of traffic. With 5 servers behind a round-robin load balancer, a user allowed 100 requests per minute can really make 500, because each server counts only the 100 it saw. The limits end up off by a factor equal to the number of servers, and they shift whenever the load balancer rebalances.
  • A dedicated rate-limit service that application servers call before doing work. It holds global state and can take rich business context ("this user is in a promotion"). The cost is an extra network hop on every request, plus a new critical dependency with its own failure modes.
  • At the edge, in the API gateway or load balancer. The check happens before any application code runs, so blocked requests never use backend resources. It is like a bouncer at the door rather than a security guard who throws people out after they have been inside for an hour. The cost is that the gateway only knows what is in the request.

We put enforcement in the API gateway (see API Gateway and Backend-for-Frontend), which already terminates TLS, authenticates requests and routes them. The gateway holds the rule set in memory and keeps the counters in a shared, sharded Redis in the same region. That keeps the gateway's main advantage, rejecting early, and it fixes the in-process problem because every gateway reads and writes the same counters.

Identifying the client. The gateway builds the counter key only from information it can trust:

  • User ID comes from the verified JWT or session after authentication. It is the best key for signed-in traffic, because it follows the person across devices and IPs. Plan tier and other entitlements travel as signed claims in the token. The gateway can then apply "pro users get 10 times more" without a database lookup. (See Authentication and Authorization.)
  • API key comes from the Authorization or X-API-Key header. It is the natural key for developer APIs, because limits are a contract with the key holder. The gateway looks up the key's plan in a local cache that is refreshed from the key store.
  • IP address is used for anonymous traffic and as a second line of defence for everyone. It must be the real client IP. Behind a CDN or load balancer, that is the right-most X-Forwarded-For entry added by a proxy we trust, never the left-most value, which the client can forge. IP limits must be generous, because thousands of real users can share one corporate NAT or mobile carrier gateway. For IPv6 we key on the /64 prefix, since one subscriber usually controls a whole /64.

Real systems apply several rules per request and enforce the most restrictive one. Alice might have used 50 of her 1,000 hourly requests, but if her IP has hit its limit of 100 per minute, she is blocked. The order in which rules are checked matters for correctness, and we return to that in Deep Dive 10.

2) The system enforces configurable rules across all gateways#

Now the core: an algorithm and a place to keep its state.

Algorithm. The four standard choices are fixed window counter, sliding window log, sliding window counter and token bucket. There is also leaky bucket, which is closely related to token bucket. Deep Dive 1 compares them in detail. For a public API we choose the token bucket for most rules. Each client has a bucket holding up to B tokens, refilled at r tokens per second, and every request takes one token out. It allows short bursts up to B, enforces a long-run rate of r, and needs only two numbers of state per client. Stripe documents using token buckets for its API limits, and Amazon API Gateway describes its throttling in the same terms.

State. Bucket state must be shared, or we are back to the in-process problem. If Alice sends 50 requests to gateway A and 50 to gateway B, each gateway thinks she has sent only 50. We keep the state in Redis, an in-memory key-value store that all gateways can reach in under a millisecond. Redis suits this job for several reasons:

  • Its operations are fast.
  • It can expire keys, so idle buckets clean themselves up.
  • Its single-threaded execution makes a server-side script atomic.
  • It is easy to replicate and shard.

See Redis in Practice.

The obvious way to code it has a race. Here is the naive version:

  1. Read the bucket with HMGET.
  2. Compute the refill in the gateway.
  3. Write the result back with MULTI / HSET / EXPIRE / EXEC.

The write is atomic, but the read is not part of it. Two requests for the same user can arrive at two gateways at the same moment. Both read "1 token left", both allow their request, and both write "0 tokens". Two requests went through on one token. Under load this happens all the time, and it turns any limit into a loose suggestion.

The fix is to make the whole read-compute-write cycle a single atomic operation: a Lua script run inside Redis with EVALSHA. Redis runs a script to completion before it serves any other command, so no other request can sneak in between the read and the write. The script reads the bucket, adds the tokens earned since the last refill, takes a token if one is available, writes the new state, sets the TTL and returns the decision, all in one round trip. Deep Dive 3 shows the script and the remaining subtleties: clocks, multiple keys, and what atomic does and does not mean in Redis. This is the general Pattern: Dealing with Contention: when concurrent read-modify-write cycles race, widen the atomic boundary until it covers the whole cycle.

3) Over-limit requests get 429 and helpful headers#

When the script says "deny", the gateway stops processing straight away. It does not queue the request. Queued requests hold memory and connections. Clients that do not see an answer retry, which adds even more load. And response times become unpredictable, which is worse for a user than a clear "try again in 30 seconds". Queuing or "shaping" has a place for internal batch work and outbound traffic to a fragile partner API (Deep Dive 12), but not for interactive public requests.

The rejection is HTTP 429, which the HTTP standard defines for exactly this case. It carries the limit, the remaining allowance (0), the reset time, and Retry-After in seconds. Successful responses also carry the limit, the remaining allowance and the reset time, so a well-written client can slow down before it ever sees a 429. Official SDKs read these headers and back off with jitter. Without them, rejected clients tend to retry on fixed timers, all at the same moment. Status codes are a contract: use 429 for "you, specifically, are over your limit", and 503 for "the service is overloaded or unavailable for everyone". Clients and CDNs treat the two differently.

4) Operators change rules at runtime#

Rules live in a rule store, a small relational table owned by a rule service, which is the control plane. A rule edit creates a new immutable version of the rule set. Gateways must pick it up without a deploy. They poll every 30 seconds for routine changes and also subscribe to a push channel for urgent ones. The channel is a watch on a coordination store such as etcd or ZooKeeper, or a pub/sub topic. Each gateway validates a new version, swaps it in atomically, and reports which version it is running, so operators can see when a change has fully rolled out. Deep Dive 7 covers shadow mode, canaries and rollback.

The full high-level design#

The design has a data plane, which handles every request and must be fast, and a control plane, which handles rules and must be safe. We draw them separately so that each diagram stays readable.

The data plane in one region:

The control plane, shared by all regions:

Each component in one line:

  • CDN and DDoS edge. This layer absorbs volumetric attacks and applies very coarse per-IP limits before traffic reaches our data centres. Examples are Cloudflare, AWS Shield and Google Cloud Armor. See Content Delivery Networks (CDN).
  • Regional load balancer. It spreads connections over the gateway fleet. The limiter does not depend on which gateway gets which request, because the state is shared. See Load Balancing.
  • API gateway with the limiter library. It authenticates the request, extracts the identity keys, matches rules from its in-memory rule set, and runs one atomic script per shard touched. It then forwards the request or returns 429.
  • Redis Cluster. This is the shared counter state, sharded by client key over 16,384 hash slots, with a replica per primary and automatic failover. Data is short-lived, with a TTL on every key.
  • Fallback limiter. These are per-gateway in-memory buckets sized to that gateway's share of each limit. They are used when Redis is slow or unreachable, so the system degrades to approximate limits instead of none, or none at all for every request.
  • Backend services. They have their own last line of defence: limits on concurrent requests and load shedding by priority. Per-client limits cannot protect against the sum of many legitimate clients.
  • Rule service and store. These are the source of truth for rules. They validate, version and audit changes, and they support shadow mode, canaries and rollback.
  • Config distribution. This pushes new rule-set versions to every gateway within seconds. Polling remains as a backup, and a snapshot in object storage lets cold gateways start even when the rule service is down.
  • Abuse detection. It watches throttle events and anomaly signals, then adds temporary blocks so that abusive keys are rejected in memory without touching Redis.
  • Observability. It covers decisions per rule, check latency, Redis health, fallback-mode activations and the rule version running on each gateway. See Observability: Logs, Metrics and Traces.

Key Flows#

Checking a request against its limits#

  1. The gateway authenticates the request first. The identity used as the limit key must be verified, or attackers can pick whichever key has the most tokens left. Tier and user ID come from signed token claims, so no database is touched.
  2. Rule matching happens entirely in memory, typically in tens of microseconds. The result is a short list of (rule, key) pairs: for example the user's timeline rule, the user's global rule and the IP rule.
  3. One EVALSHA per shard runs the token-bucket logic atomically inside Redis. Keys for the same client share a hash tag, so they land on one shard and one script call handles them all. The reply carries everything the response headers need.
  4. Allowed requests are forwarded. Denied requests are answered with 429 at this point, and the backend never sees them. The response headers are written in both cases.
  5. The decision event is sent asynchronously, fire-and-forget, to the metrics pipeline. It is sampled for allowed requests and recorded at a higher rate for denials. Logging must never add latency or become a failure path.

Pushing an emergency rule change#

  1. Emergency changes go through the same validated pipeline as routine changes. A bad rule pushed in panic can cause an outage just as easily as an attack can. Validation checks the schema, rejects rules that would match all traffic unless explicitly confirmed, and estimates how much traffic the rule would affect.
  2. The rule store is the source of truth. The watch key only says which version is current, so the coordination store holds a few bytes, not the whole rule set.
  3. Gateways fetch the version, verify its checksum, compile it into their matching structures off the hot path, and swap a pointer. Requests in flight finish under the old rules, and new requests use the new ones.
  4. Every gateway reports the version it is running. The operator sees how far the rollout has reached instead of hoping. A gateway that misses the push picks up the change on its next 30-second poll.

Data Model#

The limiter keeps two kinds of data with very different needs. Rules are small, valuable, rarely written and read by every gateway, so they belong in a relational database with versioning and an audit trail. Counters are huge in number, written millions of times a second and safe to lose, so they belong in Redis with TTLs. The entity diagram covers the control-plane data. The counters are described as key layouts below it.

Database choice. The rules use a relational database such as PostgreSQL or MySQL. The data is small, a few thousand rows, but it needs transactions: publishing a version and its rules together. It needs constraints, such as one active version, and it needs joins for audit queries. It is read rarely, by the rule service, never on the hot path, so its latency does not matter. The counters use Redis Cluster because the workload is about 2M atomic read-modify-write operations per second on tiny, short-lived values. That is the opposite profile, and a durable database would be a poor fit. See Choosing a Database: A Decision Guide.

Counter key layout. Keys are built so that all of one client's counters share a hash tag. The part inside braces decides the hash slot, so every key for a client lands on the same shard, and one script can update them atomically:

  • Token bucket: rl:{u:12345}:timeline is a hash with fields tk (tokens, a float) and ts (last refill, in milliseconds). Its TTL is the time to refill completely plus some slack.
  • Same user, another rule: rl:{u:12345}:global sits in the same slot as the key above.
  • Fixed window: rl:{k:ak_9f3}:search:29458321 is an integer counter. The suffix is the window number, floor(now / 60). The TTL is the window length plus a little.
  • Sliding log: rl:{ip:203.0.113.7}:login is a sorted set with score = timestamp in ms and member = a unique request ID. Its TTL is the window length.
  • Blocklist: bl:{k:ak_9f3} is a string holding the reason, with a TTL equal to the block length. It is also cached in gateway memory.

Keys and sharding. The shard key is the client identity: user ID, API key or IP prefix. That puts every rule for one client in one place and spreads different clients evenly. It does not spread one very hot client. Deep Dive 9 deals with that. IP-keyed counters and user-keyed counters for the same request will usually live on different shards. That is fine: the gateway issues two script calls in parallel, so the latency cost is the slower of the two, not their sum.

Indexes. In the rule store: a unique index on (version, rule_id); an index on (match_route, match_tier) for the rule service's conflict checks; and an index on RULE_OVERRIDE.client_key for support tooling ("why is this customer throttled?"). Redis needs no secondary indexes, because every access is by exact key.

Retention. Counters disappear through their TTLs. Nothing is kept long term, and losing them only resets someone's allowance, which is always safe for availability. Rule versions are kept forever, because they are tiny and essential for audit and rollback. Sampled decision logs go to the observability stack with its normal retention, for example 14-30 days.

Deep Dives#

1) Which rate-limiting algorithm should we use, and for which rules?#

An interviewer wants to hear that you know the main options, can say how each behaves at window edges, in memory and under bursts, and can choose on purpose. You do not have to implement all of them. A real platform uses more than one: different rules have different needs.

Basic: fixed window counter. Divide time into fixed windows, for example minutes starting at :00. Keep one integer per client per window. Each request runs INCR on the key for the current window, and the request is rejected if the result is above the limit. In Redis it is two commands: INCR rl:{u:1}:post:29458321, then EXPIRE of 60 seconds, but only when INCR returned 1, meaning this is the first request of the window. That detail matters. Calling EXPIRE on every request pushes the expiry forward each time, so a client with steady traffic never gets a fresh window and stays throttled forever. Also, if the gateway crashes between INCR and EXPIRE, the key never expires. Both problems go away if the pair runs as one Lua script, or as one SET with NX EX followed by INCR.

The fixed window is the cheapest option there is: one small integer per client, one round trip, trivial to explain. Its flaw is the boundary burst. With a limit of 100 per minute, a client can send 100 requests at 12:00:59 and another 100 at 12:01:00, which is 200 requests in two seconds, double the intended rate. In general, a fixed window allows up to 2N in any period of length W that straddles a boundary. The second flaw is starvation within a window. A client that uses up its allowance at 12:00:05 is locked out for 55 seconds, even if the average rate over the last minute was fine. Fixed windows are still the right choice for coarse quotas where the edge effect does not matter, such as "10,000 requests per day". They are also right when you need a number people can reason about easily, such as "you have 3 password resets per hour".

Basic, exact: sliding window log. Keep a sorted set of the timestamps of each client's recent requests. On each request:

  1. Remove entries older than now minus W, using ZREMRANGEBYSCORE.
  2. Count what is left, using ZCARD.
  3. If the count is under N, add the current timestamp with ZADD and allow the request. Otherwise reject it.

All three steps run in one Lua script. This is exact: at every instant it counts precisely the requests in the last W seconds, so there is no boundary burst at all. The cost is memory and CPU in proportion to the limit. A client allowed 1,000 per minute stores up to 1,000 entries, and each sorted-set entry costs tens of bytes. The trim step also costs time proportional to the number of expired entries. A subtle point: should a rejected request be recorded in the log? If it is, a client that keeps hammering stays blocked forever, which punishes retries harshly. If it is not, the limit counts only allowed requests, which is the usual meaning. Choose deliberately. The log is the right tool for low limits on high-value actions, where exactness matters and N is small: login attempts (5 per 15 minutes), OTP sends, password resets, payment attempts.

Better: sliding window counter. Keep the fixed-window counters, but estimate a true sliding window by weighting the previous window. If we are a fraction p of the way into the current window, the estimate is:

estimate = current_count + previous_count × (1 − p)

The request is rejected if the estimate reaches N. For example, 30% of the way into the current minute, we count 70% of last minute's requests plus all of this minute's. The state is two integers per client, which is as cheap as the fixed window. The worst-case burst at a boundary almost disappears, because the old window's weight fades smoothly instead of dropping to zero. The approximation assumes the previous window's requests were evenly spread. If they were all at its end, the estimate under-counts. If they were all at its start, it over-counts. Cloudflare has described using this approach for its rate limiting product across many customer domains, and reported that the error was very small in practice. That matches intuition: across many clients, uneven traffic within a window averages out. This is a good default for plain "N per window" rules where you want window semantics without the edge burst.

Best for most API rules: token bucket. Each client has a bucket of capacity B that gains r tokens per second, never going above B. A request costing c is allowed if at least c tokens are present, and then c tokens are removed. You never need a background timer to refill buckets. The refill is computed lazily when the next request arrives:

tokens = min(B, tokens + (now − last) × r)

The state is two numbers. The behaviour is easy to describe: a long-run rate of r and a burst of up to B. Two knobs is exactly what API traffic needs. A mobile app opening sends 15 requests at once and then goes quiet. A fixed window either rejects that burst or must allow 15 per second forever. A token bucket with r = 1 per second and B = 20 allows the burst and still caps the sustained rate. Costs fit naturally: a search costs 5 tokens, a profile read costs 1. The weaknesses:

  • Tuning. You must choose two numbers per rule, not one.
  • Cold start. A new or idle client starts with a full bucket, so a fleet of fresh bots each gets B free requests at once. The fix is to start new buckets partly full for anonymous dimensions.
  • Explaining the headers. "Remaining" is the current token count, and "reset" is the time until the bucket is full again. That is a little less intuitive than a window.

A close relative: leaky bucket and GCRA. The leaky bucket appears in two forms. As a queue, requests enter a FIFO queue that drains at a constant rate, which smooths output perfectly. NGINX's limit_req works this way, with a burst queue and an optional nodelay. This is the right model when you are shaping outbound traffic to a fragile dependency, but it adds queueing delay. As a meter, it is mathematically the same as a token bucket with the sign flipped: the bucket fills with requests and leaks at rate r. The Generic Cell Rate Algorithm (GCRA), from ATM networking, is a neat way to implement the meter. It stores a single number per client, the "theoretical arrival time" (TAT):

  1. On each request, compute new_tat = max(TAT, now) + T, where T = 1/r is the emission interval.
  2. Allow the request if new_tat − now ≤ τ + T, where τ is the burst tolerance, and store new_tat. Otherwise reject it.

GCRA needs one stored value instead of two, and it computes "retry after" exactly: new_tat − now − τ − T. Libraries such as redis-cell implement it, and it is a good thing to mention as a staff-level refinement.

Choosing per rule:

Rule kindAlgorithmWhy
General API traffic per user or keyToken bucket or GCRAAllows natural bursts, enforces sustained rate, tiny state
"N per window" quotas shown to customersSliding window counterWindow meaning without edge bursts, two integers
Daily or monthly coarse quotasFixed windowCheapest; edge effect irrelevant at day scale
Login, OTP, password reset, paymentsSliding window logExact, low N, high-stakes
Outbound calls to a fragile partnerLeaky bucket as a queueSmooth constant output; delay is acceptable
Protect a service's capacityConcurrency limit (in-flight count)Rate limits ignore how long requests take

The last row is easy to forget and impresses interviewers. A rate limit counts request arrivals. A service is overwhelmed by requests in flight, which is the arrival rate times the latency (Little's Law: L = λ × W). If latency jumps from 50 ms to 2 s during an incident, the same 1,000 requests per second means 2,000 requests in flight instead of 50, and a rate limiter does not notice anything wrong. A concurrency limiter caps requests in flight, per client or per service, and catches that case. Stripe has written about running exactly this combination: a request-rate limiter, a concurrent-request limiter, and load shedders that reserve capacity for critical traffic.

Our choice: token bucket (stored as two fields, or GCRA as one) for the per-user, per-key and per-endpoint API rules. Sliding log for authentication-sensitive endpoints. Sliding window counter for customer-visible "per minute" quotas. Concurrency limits and load shedding inside the services. The limiter library implements all of these as separate Lua scripts behind one check() interface, and each rule names its algorithm. The full mathematical comparison is in Rate Limiting and Throttling. The burst bounds are worked out in the first deep-dive block at the end of this page.

2) Where should the rate limiter sit: in the app, as a service, or at the gateway?#

Where the limiter runs decides what it can see, what it protects, and what it costs in latency and failure modes.

Basic: in-process in each application server. Every server keeps its own in-memory buckets. A check costs about 1 µs and has no dependencies. But every server enforces the limit on its own share of the traffic. With 5 servers and round-robin balancing, the effective limit is 5 times what was configured. With uneven balancing it is unpredictable. The usual "fix" is to configure limit / N on each server. That only works while the balancer spreads each client evenly, which a round-robin balancer does in aggregate but not for a single client over a short period. It also breaks every time the fleet scales up or down. In-process limiting is still valuable for two jobs. One is protecting the server itself: concurrency caps and queue-length limits, where a local view is exactly right. The other is acting as a fallback when shared state is unavailable.

Better: a dedicated rate-limit service. Application servers call isAllowed(client, rule) on a central service before doing the work. The service holds global state, and callers can pass rich context such as subscription tier, account age, a fraud score, or "this endpoint is in its launch week". One team owns the logic for everyone. Envoy's global rate-limit model works like this: the proxy calls a separate gRPC service, often Lyft's open-source ratelimit, which is backed by Redis, with descriptors describing the request. The costs:

  • One extra network hop per request, about 0.5-1 ms in the same data centre, and more if the service is far away or overloaded.
  • A new critical dependency with its own capacity, deploys and outages.
  • A fail-open or fail-closed decision at every caller.
  • Requests have already crossed the edge and used a connection to an application server before being rejected, so abusive traffic still costs something.

Better still: in the API gateway or load balancer. The check runs where requests enter, before any application code. Blocked requests cost almost nothing downstream. The limitation is context: the gateway knows only what is in the request. That is why identity and tier should travel as signed claims in the token, not as database lookups. The gateway still needs shared state, so we add Redis, and "at the gateway" really means "gateway logic plus a nearby state store".

Best: layered limits, each enforcing what it can see best. Production systems use all of the layers above, each for a different purpose:

  1. Edge or CDN. Very coarse per-IP and per-ASN limits, bot scores and blocklists. This absorbs floods before they reach the data centre, works without login identity, and is cheap per request.
  2. API gateway. Per-user, per-key and per-endpoint token buckets against shared Redis state. This is the core of this design: it enforces the contract with each client.
  3. Service. Concurrency limits, adaptive load shedding and priority queues. These protect the service from the sum of legitimate traffic and from slow downstream dependencies, which per-client limits cannot do. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
  4. Business rules in the application. "5 posts per minute for accounts less than one day old" is a product rule that needs database context. It is checked where that context lives. Often it is the same limiter library pointed at the same Redis, just called from the application.

The common mistake is to treat these as alternatives and pick one. They protect against different failures. A gateway limiter does not stop a backend from collapsing under legitimate peak load, and a service load shedder cannot enforce "free tier means 100 per minute". The interview answer is: "The gateway is the main enforcement point for client limits, with an edge layer in front and concurrency limits behind."

A note on sidecars and service meshes. In a microservice setup, a sidecar proxy such as Envoy can apply limits on each service-to-service call. Local limits, enforced per sidecar, protect a callee from one noisy caller. Global limits use a rate-limit service. This is the same layering idea applied to internal traffic. See Microservices Infrastructure Patterns.

3) How do we make the Redis counter update atomic and correct?#

We saw why the naive "HMGET, compute, then MULTI/EXEC" approach races. The read happens outside the transaction, so two gateways can both spend the same last token. There are three ways to fix it.

Basic: optimistic concurrency with WATCH. The gateway runs WATCH on the key, reads it, computes the new state, and then runs MULTI / HSET / EXEC. If another client changed the key after the WATCH, EXEC aborts and the gateway retries. This is correct. But under contention, which is exactly the hot-client case we care about, it degrades into retry storms. Every attempt also costs at least two round trips: read, then transaction. And in Redis Cluster all watched keys must share a slot.

Better: server-side Lua script. Send the whole algorithm to Redis as a script and call it with EVALSHA using the script's SHA-1 hash. Load the script once, and retry with EVAL if the server answers NOSCRIPT. Redis runs a script atomically: no other command runs on that node until the script returns. So the read, the refill, the spend and the write cannot interleave with another request. The check takes one round trip. Here is a token bucket that supports a cost and returns everything the headers need:

-- KEYS[1] = bucket key; ARGV: capacity, refill_per_ms, cost, ttl_ms
local cap  = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local ttl  = tonumber(ARGV[4])
local t    = redis.call('TIME')                 -- server clock: one clock for all gateways
local now  = t[1] * 1000 + math.floor(t[2] / 1000)
local s    = redis.call('HMGET', KEYS[1], 'tk', 'ts')
local tk   = tonumber(s[1]) or cap              -- new bucket starts full
local ts   = tonumber(s[2]) or now
tk = math.min(cap, tk + math.max(0, now - ts) * rate)
local allowed = 0
if tk >= cost then tk = tk - cost; allowed = 1 end
redis.call('HSET', KEYS[1], 'tk', tk, 'ts', now)
redis.call('PEXPIRE', KEYS[1], ttl)
local wait = 0
if allowed == 0 then wait = math.ceil((cost - tk) / rate) end
return { allowed, math.floor(tk), wait }

Several details here matter in production:

  • Whose clock? If each gateway sends its own now, then clock skew between gateways shows up directly in the refill. A gateway whose clock runs 2 seconds fast hands out 2 seconds of extra tokens. A gateway whose clock is behind produces negative elapsed time, which the max(0, ...) guards against. Reading TIME inside the script gives every gateway for that key the same clock: the shard's clock. Since Redis 5, scripts are replicated by their effects rather than re-run on replicas, so non-deterministic commands like TIME are safe. Redis 7 always replicates effects. See Time, Clocks and Ordering.
  • TTL. Set the TTL to about the time it takes an empty bucket to fill, cap / rate, plus some slack. A key that expires is the same as a full bucket, so expiry is correct, not just a way to save memory.
  • Keep the script short. A script blocks the shard while it runs. Token-bucket scripts take microseconds. Never loop over unbounded data inside a script. A sliding-log trim is bounded by the window's size, which is another reason to use the log only for small N.
  • Multiple rules in one call. Pass all of a client's keys in one script call, which only works if they share a hash tag and therefore a slot. The script checks every rule first and spends tokens only if all of them pass. Otherwise a request rejected by rule 3 would already have spent tokens from rules 1 and 2. This "check all, then commit all" order is the multi-rule correctness point from Deep Dive 10.
  • Floats. Store tokens as a float, or as integer "milli-tokens", so that slow rates such as 0.1 tokens per second do not round down to zero.

Best: the script, plus a precise picture of what "atomic" means. The Lua script is the standard answer. The senior detail is knowing its limits:

  • Atomic is not durable. Replication is asynchronous. If a primary fails just after granting a token, the promoted replica may not have that write. The client gets a few extra requests during failover. For rate limiting, that is fine, and it is why we never use this design for money.
  • Atomic is per shard. A script cannot touch keys in different slots. The user key and the IP key for one request are checked by two scripts on two shards, so a request can spend a user token and then be rejected by the IP rule. To avoid that, either check the cheap-to-fail rule first, or accept a small leak. Usually it is worth accepting. The alternative, cross-shard two-phase commit, is far too heavy for a rate limiter.
  • Long scripts hurt everyone. A slow script blocks every other client on that shard. Alert when script time goes past about 1 ms, and set busy-reply-threshold (called lua-time-limit before Redis 7) so that runaway scripts are reported rather than silently stalling the node.
  • Redis Functions. Redis 7 adds Functions: named, persistent server-side code loaded with FUNCTION LOAD. They avoid the NOSCRIPT reload dance and are versioned with the deploy. The semantics are the same.

The same "widen the atomic boundary" reasoning appears in Concurrency Control and Database Locking. In-memory stores make it cheap.

4) How do we scale to 1M requests per second?#

The capacity estimate says about 2M script calls per second at peak. One Redis primary is good for roughly 50k-80k token-bucket scripts per second. So we must spread the counters over many nodes, and every request for a given client must find the same node. Otherwise that client's state splits in two and the limit stops working.

Basic: one big Redis primary, plus replicas. Replicas do not help here. Every check is a write, and writes all go to the primary. Vertical scaling also hits a wall early: Redis runs commands on one main thread, so a bigger machine adds memory, not script throughput. Redis 6 added I/O threads, which help with network reads and writes, but scripts still run one at a time. This works up to roughly 50k checks per second.

Better: client-side sharding with consistent hashing. The gateway hashes the client key, such as u:12345, onto a ring of N Redis primaries and sends the script to the owner. Because the hashing is consistent, adding a shard moves only about 1/N of the keys (see Consistent Hashing). Moved keys simply start with a full bucket on their new shard. That is a brief, bounded loosening of the limit, and it is acceptable. The downside is that every gateway must agree on the ring. Membership changes need a coordination mechanism, and a gateway with an outdated ring sends keys to the wrong shard.

Best: Redis Cluster, keyed on hash tags, with pipelined and parallel calls. Redis Cluster divides the keyspace into 16,384 hash slots, spreads the slots across primaries, and tells smart clients the slot map. When slots move, a client that sends a key to the wrong node gets a MOVED reply and updates its map. During a migration it gets ASK and follows it. Replicas and automatic failover are built in. We get sharding without inventing it. The design points that make it work at 1M requests per second are:

  • Hash tags put a client's keys in one slot. Everything for user 12345 is rl:{u:12345}:..., so one script call covers all of that user's rules atomically.
  • One script call per shard per request. A request usually touches two shards: the user's and the IP's. The gateway sends both calls in parallel, so the latency is the slower of the two, not their sum.
  • Pipelining and connection multiplexing. Clients such as Lettuce or ioredis multiplex many in-flight commands over a few connections per node. This keeps the connection count per shard manageable with thousands of gateway processes, and it batches network writes.
  • Size for 50% headroom. That is about 50 primaries at 40k scripts per second each. Monitor CPU per shard, not just the cluster average. A single hot shard pinned at 100% CPU while the cluster average is 40% is the usual failure.
  • Scale by moving slots. To add primaries, migrate slots online. Keys in flight move with MIGRATE. Because the data is short-lived, you can even skip migration: empty the slot and accept full buckets for its clients.

Reducing the number of calls. Each avoided call saves a round trip and leaves shard capacity for other work. Several techniques help, and you can combine them:

  • Check in memory first. If a key is on the local blocklist, or its last reply said "0 remaining, retry in 30 s", the gateway rejects locally until that time without calling Redis. This alone removes most of the load from abusive clients, who are exactly the ones sending the most requests.
  • Local token leasing. For very high-limit clients, for example an enterprise key allowed 50k requests per second, the gateway takes a batch of tokens, say 100, from the shared bucket in one call and spends them locally. That cuts Redis calls by 100 times for that client. The limit can then be exceeded by at most the unspent leases across all gateways, so keep lease sizes small relative to the limit and give leases a short expiry. Doorman, a system YouTube built and open-sourced, takes this idea further: clients request capacity from a central server and are granted shares that they enforce themselves.
  • Local limits for global rules. A rule like "this endpoint may receive 50k requests per second in total" does not need per-request coordination. Each of G gateways enforces 50k / G locally. A background process adjusts the shares every few seconds based on each gateway's observed traffic.

5) How do we keep the check inside the latency budget?#

The budget is under 2 ms at p99 added in-region, and a hard 10 ms ceiling after which we stop waiting. Here is where the time goes and how to protect each part:

StepTypicalWhat can blow it upProtection
Rule match in gateway memory10-50 µsRegex-heavy rules, huge rule listsCompile rules into hash maps and tries keyed by route and tier
Key build and script call serializationabout 20 µsAllocations, large argsShort keys, preloaded script SHA
Connection pool wait0-100 µsPool too small, head-of-line blockingMultiplexed clients, pool sized to concurrency
Network to Redis, same zone0.2-0.5 msCross-zone or cross-region placementZone-aware placement, never cross region
Script execution10-50 µsLong scripts, big sorted setsBounded scripts, log only for small N
Shard queueing0-1 msHot shard, CPU saturationHeadroom, hot-key handling, local deny cache

The protections, roughly in order of payoff:

  1. Persistent, pooled connections. A fresh TCP connection per check would add a handshake of 0.5 ms or more within the data centre, plus TLS if it is enabled. Over long distances that becomes tens of milliseconds. Every serious Redis client keeps connections open. You tune the pool or multiplexing to the concurrency.
  2. Place state next to the gateway. Gateways and their Redis shards share a region and, where possible, an availability zone. A same-zone round trip is about 0.3 ms, while cross-zone adds 1-2 ms. If shards are spread across zones for availability, accept the cross-zone hop for some calls and keep the p99 target in mind. A cross-region call (80-200 ms) is never acceptable on this path.
  3. A strict timeout with a defined fallback. Give the check a time budget of about 5 ms. When it runs out, the gateway does not wait. It uses the local fallback bucket (Deep Dive 6). A slow limiter must never turn into a slow API: the timeout limits how much latency the limiter can ever add, regardless of what Redis is doing.
  4. One round trip. The Lua script does the read, compute and write in one call. Calls to different shards run in parallel.
  5. Skip Redis when possible. Use the local deny cache, the blocklist and token leases for high-volume clients.
  6. Hedged requests? No. Sending the same check to two nodes would double-spend tokens. Hedging fits idempotent reads, not counters. This is worth saying in an interview, because hedging is a common answer to tail latency.

Measure the limiter's own latency separately from the request latency: a histogram of check duration per shard, plus a counter for fallback decisions. That makes "the limiter made the API slow" quick to rule in or out during an incident.

6) What happens when Redis is slow or down: fail open or fail closed?#

Once state is sharded, each shard is a dependency of every request for its clients. A shard can be down because of a primary crash, a network partition, a failover in progress, or a CPU-saturated node that times out. The gateway then has to decide something without its data.

Good, but risky: fail closed. If we cannot check, we reject, returning 503 or 429. Nothing unverified gets through. This makes sense where letting traffic through unchecked is worse than being down. Examples are payment authorisation, login and OTP endpoints (where an attacker who can turn off the limiter gets unlimited password guesses), and high-security admin APIs. The cost is severe: a limiter outage becomes an API outage, even though every backend is healthy. Rejected clients also retry, often in sync, which is the classic retry storm. When the shard comes back, it faces a thundering herd of clients that are all retrying at once.

Good, but risky: fail open. If we cannot check, we allow. The API stays up and users notice nothing. This makes sense for low-risk read endpoints whose backends have their own protection. The danger is that limiter failures are correlated with load. Redis often falls over because traffic is spiking, for example during a viral event or an attack. Failing open then sends all of that traffic to the backends at the worst possible moment, and an outage of the limiter becomes an outage of the whole platform.

Both are reasonable answers for some endpoints, and that is the point. The best answer does not pick one globally.

Best: degrade to local limits, choose the failure mode per rule, and fix availability at the root.

  1. Degrade, do not drop. Each gateway keeps in-memory fallback buckets for every rule, with capacity = rule limit / number of gateways, rounded up and padded about 1.5 times for uneven balancing. While a shard is unreachable, keys on that shard are checked against the local buckets. Limits become approximate, often looser, sometimes stricter for one unlucky client, but they still exist. An abusive client sending 10,000 requests per second still gets throttled to about (limit / G) × G × 1.5. It does not get unlimited access. This is the same "approximate is fine" relaxation we accepted in the requirements.
  2. Failure mode per rule. Every rule carries on_unavailable: local | open | closed. Most API rules use local. Login, OTP and payment rules use closed, so the endpoint serves 503 with Retry-After while the shard is unreachable. Cheap health checks may use open.
  3. Circuit breaker on the shard. If the error rate or timeouts on a shard cross a threshold, the gateway stops calling it for a cool-down period and goes straight to fallback. It does not pay a 5 ms timeout on every request. Probe requests decide when to close the breaker again. This keeps a slow shard from turning into a slow API. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
  4. Make it rare. Every primary has a replica in another zone. Redis Cluster detects a failed primary through gossip among the nodes and promotes a replica, typically within seconds to tens of seconds depending on cluster-node-timeout. During failover the counters on that shard may lose their most recent writes. Clients get slightly more tokens, which is harmless. Watch out for split brain: if a partitioned old primary keeps accepting writes for a few seconds, those writes are discarded when it rejoins. That is again acceptable for counters. See Designing for High Availability and Heartbeats, Failure Detection and Gossip.
  5. Alert on fallback mode. Fallback is invisible to users by design, so it must be loud for operators. Alert on the percentage of decisions made in fallback, on shards with open breakers, and on time spent in closed mode for each rule.

The diagram shows only the forward path. A failed probe returns the gateway to LocalFallback and restarts the cool-down. Suspect can return to Shared if the errors were a short blip. A shard is handled independently: one bad shard puts only its slots' keys in fallback. Other clients keep exact limits.

Why did the hi-hurry breakdown choose fail-closed for a social platform? Its argument was correlation: failing open during a viral spike could flood the databases. The local fallback answers the same worry without turning the API off. It keeps the protection, roughly, while staying available. Make the trade-off out loud in an interview: "Global fail-closed takes us down whenever Redis has an outage. Global fail-open removes protection exactly when load is highest. So I degrade to per-gateway local limits for most rules, and I fail closed only on security-critical rules."

7) How are rules configured, distributed and changed safely at runtime?#

Rules change all the time. Product launches raise limits, enterprise deals add overrides, abuse teams add blocks, and incident responders cut limits on a struggling endpoint. A change must reach every gateway quickly, and a bad change must not become an outage.

Basic: rules in code or a config file shipped with the gateway. This is simple and version-controlled. But every change needs a deploy that takes tens of minutes, which is far too slow during an attack. It also mixes rule changes with code changes, so a limit tweak carries the risk of a binary deploy.

Better: rules in a database, polled by gateways. The rule service stores rules in a table: dimension, route pattern, tier, algorithm, parameters and priority. Gateways poll for the current version every 30 seconds and cache the whole rule set in memory. This is simple and robust: if the rule service is down, gateways keep their last good copy. The cost is propagation delay, up to one poll interval, plus jitter, before every gateway has a change. That is fine for routine edits and too slow for emergencies. You cannot poll every second from thousands of gateways without turning the rule service into a hotspot itself.

Best: versioned rule sets, pushed by watch, polled as backup, with validation, shadow mode and staged rollout.

  • Immutable versions. Each change creates a new numbered rule set with a checksum. Gateways run exactly one version at a time, which makes "which rules are live?" a one-number answer. Rollback means pointing back to the previous version.
  • Push plus pull. The active version number lives in a coordination store with watches, such as etcd or ZooKeeper (see ZooKeeper and etcd), or on a pub/sub channel. Gateways react to a change within a second or two. Polling at 30-60 seconds stays on as a backstop for gateways that missed a notification. Pushing only a version pointer, not the rule body, keeps the coordination store tiny and makes watch storms cheap. A snapshot of the latest rule set in object storage lets a newly started gateway boot even if the rule service is down.
  • Validation before publish. Check the schema and parameter ranges, reject rules that conflict at the same priority, and flag rules that would match all traffic. Estimate the impact by replaying recent sampled traffic against the new rule ("this would have rejected 34% of POST /tweets in the last hour"). Require a second approver for broad rules.
  • Shadow mode. A new rule first runs with mode: shadow. It evaluates and counts, emitting "would have rejected" metrics, but it does not reject. This finds the rule that accidentally throttles an important partner before it does.
  • Canary rollout. Deliver the new version to 1%, then 10%, then 100% of gateways, watching 429 rates and error budgets at each step. Emergency changes may skip the canary but never validation. See CI/CD and Deployment Strategies.
  • Overrides and expiry. Per-customer overrides and temporary blocks carry an expires_at, so a hot-fix raise for one customer does not become permanent by accident.
  • Matching performance. Gateways compile the rule set into lookup structures: route templates in a trie and tiers in hash maps, with priorities resolved at compile time. Matching then takes microseconds no matter how many overrides exist.

A typical rule, as an operator would write it:

- id: timeline-free
  match: { route: "GET /v1/timeline", tier: free }
  dimension: user
  algorithm: token_bucket
  capacity: 60          # burst
  refill_per_sec: 1     # 60 per minute sustained
  on_unavailable: local
  mode: enforce
  priority: 100
- id: login-ip
  match: { route: "POST /v1/login" }
  dimension: ip
  algorithm: sliding_log
  limit: 10
  window_sec: 900
  on_unavailable: closed

8) How do limits stay consistent across multiple regions?#

We run in three regions: US-East, EU-West and Asia-Pacific. A user's requests usually go to the nearest region, but not always. A traveller switches regions, GeoDNS sends people somewhere else during a failover, and a developer's API key can be used from servers on three continents at once. A limit of "1,000 per hour per key" is a promise about the key's total usage, so the question is how to enforce a global number when the counters live in regional Redis clusters 80-200 ms apart.

Basic: independent regional limits. Each region enforces the full limit on its own counters. This is simple and fast. Most users are only ever in one region, so for them it is exact. But a client that spreads traffic over R regions gets up to R times the limit. A scraper that knows this will deliberately route through all three regions. A common fix is to give each region limit / R. That is fine for a client spread evenly, but a client who is entirely in one region gets only a third of their allowance there. That is a visible bug for the most common, legitimate case.

Basic, other extreme: one global counter store. All regions call one primary Redis in one region. The limit is exact, but every request from Europe or Asia pays a 100-200 ms round trip, which is fifty times the budget. It also ties every region's availability to one region. Synchronous cross-region consensus, such as a Raft group spanning regions, is exact and survives failures, but it adds the same latency on every check. That is a non-starter on the hot path. See Consensus: Raft and Paxos.

Better: home region per client. Each user or key is assigned a home region, based on where their data lives or where their traffic usually comes from. The home region's Redis is authoritative. Requests that land in the home region are checked locally, which is the common case. Requests elsewhere either make a cross-region call, which is slow but rare, or use a small local allowance. This is exact for the common case and correct for the rare case, at the price of latency for travelling clients. It works best when the platform already uses data homing (see Multi-Region and Global Data).

Best: local enforcement with asynchronous global reconciliation (eventual consistency, bounded overshoot). Every region enforces locally against a global estimate, and regions exchange counts asynchronously:

  1. Each region counts its own usage per client in its local Redis, as before.
  2. Every second or so, each region publishes per-client usage deltas for its active clients over a cross-region stream, such as a Kafka topic replicated across regions or a purpose-built sync service. Only clients with recent traffic are sent, so the stream stays proportional to active clients, not to all clients.
  3. Each region keeps a "remote usage" value per client: the sum of the other regions' recent counts. The local decision uses local_count + remote_count against the global limit.
  4. Counts from different regions merge as per-region counters that are summed, which is a grow-only counter CRDT. Merging is commutative and idempotent, so duplicated or reordered sync messages cause no harm. See Conflict Resolution, OT and CRDTs.

How much can a client overshoot? In the sync delay d, each region can admit up to the remaining allowance without seeing the others. The worst case is roughly (R − 1) × (limit rate × d) above the limit, for a client sending at full rate to all regions at once. With a 1-second sync and a limit of 100 per second, a three-region attacker gets at most about 200 extra requests per second, and only until the next sync tells every region the truth. That is bounded and short-lived, exactly what the requirements allowed.

Two refinements are worth naming:

  • Adaptive quota split. Instead of comparing a merged count to one global limit, a coordinator gives each region a share of each active client's limit in proportion to recent demand, for example 90% to US-East and 5% to each of the others. Regions enforce their share locally and give unused share back on the next tick. Overshoot is then close to zero. The cost is a coordinator, which may itself be per-client, homed on the client's home region.
  • Only sync what is global. Most rules are per-region by nature: "per IP per endpoint" is effectively regional, because an IP is in one place. Only rules that are contracts, such as per-API-key plan limits and enterprise quotas, need global reconciliation. That cuts sync traffic by orders of magnitude.

During a network partition between regions, sync stops. Each region falls back to its local counts plus the last known remote counts, which slowly age out. Overshoot grows with the length of the partition, but it never exceeds R times the limit, and every region stays available. That is the A choice in CAP, made deliberately. Billing-grade quotas, where an overshoot costs money, should instead live in a strongly consistent store and be checked off the hot path, for example per batch of usage records. They are a different product from rate limiting, and saying so is a staff-level signal.

9) How do we handle hot keys and abusive clients?#

A hot key in a rate limiter is a single client whose checks overload one shard. One attacking IP sending 200k requests per second would need about 200k scripts per second on its shard, which is more than one primary can handle. That shard's other clients would then see timeouts and fall back too. Hot keys come from abuse (scrapers, credential stuffing, botnets behind one key) and from legitimate heavy clients (an analytics pipeline, a partner integration, a mobile app bug that refreshes in a tight loop).

Basic: more replicas or a bigger node. Neither helps much. Every check is a write and goes to the primary, and the main thread is the limit. See the hot-key discussion in Redis in Practice.

Better: stop calling Redis for clients you already know the answer for.

  • Local deny cache. When a script returns "denied, retry in 30 s", the gateway remembers that for the key, in memory and with a TTL equal to the retry time. Later requests from the key are rejected locally until then. An attacker sending 200k requests per second now costs Redis about one call per gateway per retry period, instead of 200k calls per second.
  • Automatic blocking. If a key exceeds its limit repeatedly, say 10 times in a minute, the abuse system adds it to the blocklist for a growing period: 1 minute, then 10, then an hour. Blocklist entries are pushed to gateways and checked in memory first. Redis keeps the authoritative copy with a TTL.
  • Edge defence. Volumetric attacks belong at the CDN and DDoS layer, which can absorb millions of requests per second per IP and per ASN before they cost us anything. Our limiter is not a DDoS mitigation system. Its job is fairness and contract enforcement.

Best: also design legitimate heavy clients so they never become hot keys.

  • Lease tokens in batches for high-limit keys (Deep Dive 4). An enterprise key allowed 50k per second costs Redis 500 calls per second with leases of 100, not 50,000.
  • Split one logical bucket into several sub-buckets. Split a very high limit into k sub-buckets, rl:{k:ent1#0} to rl:{k:ent1#7}, each holding limit / k and placed on a different shard. The gateway picks a sub-bucket at random for each request. The total limit is kept on average, and the load spreads over k shards. The risk is unfairness between sub-buckets, which shows up as early rejections when the client's load is uneven across them. That is acceptable for a client sending tens of thousands of requests per second.
  • Shape well-behaved clients. Official SDKs implement client-side rate limiting. They read RateLimit headers and pace requests, and they retry with exponential backoff and jitter. Client-side limiting is never a security control, since clients can ignore it. But it smooths the honest majority, and that lowers infrastructure cost.
  • Batch endpoints. Offer bulk APIs so that one request carries 100 operations, with a cost of 100 tokens. That gives one check instead of 100, and the client still pays the same allowance.
  • Plan for shared IPs. IP rules must be generous enough for a university or mobile carrier NAT, where thousands of people can share one address. Signed-in limits should carry most of the enforcement. Treat a very hot IP that has many distinct signed-in users behind it as a NAT, not an attacker.

10) How do we evaluate several rules on one request correctly?#

A single request may match a per-endpoint rule, a per-user global rule, a per-IP rule, a per-tenant rule and a fleet-wide limit. All of them must pass, and the response headers should describe the most restrictive one.

Basic: check rules one after another, spending a token each time. If the third rule rejects, tokens for the first two have already been spent on a request that never ran. A client hitting their IP limit then also drains their user and endpoint buckets. After the IP window resets, they are rejected again by buckets they never really used. Over time this gives far stricter limits than configured, and that is hard to debug.

Better: check all, then commit all, inside one script. When the keys share a hash tag, one Lua script reads every bucket, decides, and spends from all of them only if every rule passes. This is exact and costs one round trip. It covers every rule keyed on the same identity, such as all of a user's rules.

Best: group rules by shard, order the groups, and accept a bounded leak between groups.

  • Group the matched (rule, key) pairs by identity. In practice there are two or three groups: the user, the IP and the tenant. Each group is one atomic script on one shard.
  • Check the most likely rejecter first. If a request fails the IP group, which is cheap and often the one rejecting during attacks, skip the user group entirely. When latency matters more than saving a few tokens, run the groups in parallel and refund. If group A spent tokens but group B rejected, send A a small async "refund" script that adds the tokens back, capped at capacity. That keeps both latency and accuracy.
  • Enforce fleet-wide limits locally in each gateway as a share, never as a Redis key. A key that every request touches is the ultimate hot key.
  • Headers report the rule with the least remaining allowance relative to its limit, so the client backs off for the right reason. The response body names the rule ID for debugging.

The refund trick is a small instance of compensation: undo a side effect instead of coordinating up front. Cross-shard atomicity through two-phase commit would cost far more than the occasional lost token.

11) How do we identify clients reliably and fairly?#

The limit key is a security boundary. If an attacker can choose their own key, the limiter is decoration.

Basic: use whatever identifies the request. Trust the X-Forwarded-For header as the IP and the user_id the client sends. Both are trivially forged. An attacker sets a random X-Forwarded-For on each request, or claims to be a different user each time, and gets a fresh bucket for every request.

Better: derive identity only from verified sources.

  • IP. Use the TCP peer address when there is no proxy in front. Behind trusted proxies, walk X-Forwarded-For from the right and skip only the addresses of our own proxies and CDN. The first untrusted address is the client. Many CDNs also send a verified client-IP header. Trust it only on connections that come from the CDN's address ranges.
  • User. Take the user from a verified JWT signature or a session lookup. Take the tier from signed claims, not from a query parameter.
  • API key. Hash the key and look up its plan in a local cache. Reject unknown keys before spending a bucket, otherwise invalid keys create unlimited new buckets and fill memory.

Best: identity hierarchy, aggregation and pre-authentication limits.

  • Limit before authentication too. Authentication is itself expensive and a target: checking a password hash costs about 50-100 ms of CPU by design. Login endpoints get an IP-based limit and a per-account-name limit before any password check. That stops both brute force against one account and credential stuffing across many accounts.
  • Aggregate where attackers have many addresses. For IPv6, key on the /64 or /56 prefix: one customer often has 2^64 addresses. Add a coarser per-ASN or per-subnet limit to catch botnets that rotate through many IPs in one hosting provider.
  • Layer the dimensions. Use user plus endpoint for fairness, tenant for B2B contracts, and IP or ASN for abuse. Each catches what the others miss. A shared NAT gets a generous IP limit, and the user limits do the precise work.
  • Mind cardinality. Every new identity is a new key. An attacker spraying random API keys or IPv6 addresses can create keys faster than TTLs remove them. Validate identities before creating state, aggregate prefixes, and cap memory per shard with maxmemory plus a volatile-ttl or allkeys-lru eviction policy. Evicting a bucket only resets a limit.

See Security Fundamentals for System Design for the wider threat model.

12) What should happen to over-limit traffic: reject, queue, delay or degrade?#

Basic: always reject with 429. This is right for most interactive APIs. It is fast, cheap and honest. On its own it is crude: every over-limit request is treated the same, whether it is a bot, a well-paying customer at a brief peak, or a critical internal job.

Better: reject well. Include Retry-After and the limit headers, and make retry behaviour part of the contract:

  • Jitter the retry hint. Return Retry-After with a small random spread, so that clients rejected in the same second do not all come back in the same second. Synchronised retries create a new spike at exactly the reset time.
  • Distinguish the causes. Use 429 for a client over its own limit and 503 for service-wide shedding, so the client knows whether slowing down will help.
  • Keep rejections cheap. A 429 must cost much less than a served request: no backend calls and a tiny body. Otherwise attackers can overload the service with requests that are "only" rejected.

Best: match the response to the traffic.

  • Interactive public API: reject immediately. Queuing only hides overload and adds latency.
  • Internal batch and async work: delay instead of reject. Workers pull from a queue at the allowed rate, a leaky bucket used as a queue. Requests wait, nothing is lost, and the dependency sees a smooth rate. See Pattern: Managing Long-Running Tasks.
  • Outbound calls to a partner with strict limits: shape on our side with a leaky bucket, so we never send the partner's limiter a 429-worthy burst.
  • Graceful degradation: for some endpoints, over-limit clients get a cheaper answer instead of an error. Examples are a cached timeline instead of a freshly ranked one, or lower-resolution images.
  • Priority under overload: when the service itself is shedding load, drop low-priority traffic first, such as prefetches, analytics beacons and background sync. Keep checkout and login. That needs a priority field on each request, set at the gateway from the route and client.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Redis primary crashChecks for that shard's slots time out until failover; counters lose their latest writesReplica in another zone with automatic failover; local fallback buckets; circuit breaker so gateways stop waiting
Hot client key (attack or heavy partner)One shard saturates; its other clients time out and fall backLocal deny cache, blocklist, token leasing, sub-bucket splitting, edge DDoS layer
Slow shard from a long script or big sorted setTail latency for all keys on the shardBounded scripts, sliding log only for small N, slow-script alerts, busy-reply-threshold
Naive read-then-write updateConcurrent requests double-spend tokens; limits become looseSingle atomic Lua script per shard; check all rules, then commit all
Clock skew across gatewaysExtra or missing tokens on refillUse the Redis server clock (TIME) inside the script; clamp negative elapsed time
Bad rule pushed (matches all traffic)Mass 429s; an outage caused by the limiterValidation, impact replay, shadow mode, canary rollout, one-click version rollback
Rule service or config store downNew changes cannot shipGateways keep the last good version; snapshot in object storage; 30-60 s polling as backstop
Cross-region partitionGlobal limits can be exceeded by up to R times while sync is stoppedLocal enforcement with last known remote counts; only contract rules synced globally
Synchronised client retries at resetSpike exactly at window boundaries or after an outageJittered Retry-After, SDK backoff with jitter, token bucket instead of fixed windows
Forged identity (spoofed XFF, random keys)Attackers get unlimited fresh buckets; memory fillsTrusted-proxy IP parsing, verified JWTs, validate keys before creating state, prefix aggregation, maxmemory with eviction
Shared NAT or carrier IPLegitimate users throttled togetherGenerous IP limits, prefer user and key limits, NAT detection from many distinct users per IP
Limiter itself becomes a latency sourceEvery API endpoint gets slower5 ms check timeout with fallback, same-zone placement, pooled multiplexed connections, per-shard latency SLOs

What Interviewers Expect#

Mid-level#

  • Gather requirements and choose the client identity (user, key or IP), and mention 429 with Retry-After and limit headers.
  • Explain one algorithm well, usually token bucket, including bursts versus sustained rate. Name at least one alternative and its flaw, such as the fixed-window boundary burst.
  • Place the limiter sensibly, at the API gateway, and explain why it needs shared state such as Redis rather than per-server memory.
  • When asked about scale, say that Redis needs to be sharded by client key, with a rough idea of how routing works.

Senior#

  • Move quickly through the algorithms, then compare them on accuracy, memory and burst behaviour, and choose different ones for different rules (for example sliding log for login).
  • Find the read-modify-write race in naive Redis code without prompting. Fix it with a Lua script, and explain what atomic does and does not cover: per shard only, not durable across failover.
  • Size the cluster from the QPS and per-shard throughput. Use Redis Cluster hash slots and hash tags so a client's rules share a shard. Mention connection pooling and the latency budget.
  • Discuss fail-open versus fail-closed with real reasoning, including that limiter failures happen alongside load spikes. Bring up hot keys, the local deny cache and blocklists, and poll versus push for rule updates.

Staff+#

  • Treat accuracy as a deliberate relaxation: state the overshoot bounds for failover, multi-region sync and token leasing, and tie them to the requirements.
  • Design multi-region enforcement: home regions or asynchronous G-counter reconciliation with bounded overshoot. Separate rate limiting from billing-grade quotas, which need strong consistency off the hot path.
  • Make the limiter safe to operate: versioned rule sets, validation, shadow mode, canaries, rollback, per-rule failure modes, and alerts on fallback mode. A limiter outage caused by a bad rule is the most likely incident, and the design should expect it.
  • Place rate limits inside the overall defence system: edge DDoS protection, gateway contract limits, service concurrency limits and load shedding (Little's Law), and priority-based degradation.
Deep Dive: The mathematics of limits, bursts and tuningShow

Arrival curves: a precise language for "rate plus burst". Network engineers describe a traffic limit as an arrival curve. Let A(t) be the number of requests admitted in any interval of length t. A token bucket with capacity B and refill rate r guarantees A(t) ≤ B + r·t for every interval, however it is placed. That is the whole contract. The bucket can never hold more than B tokens, and in any interval it gains at most r·t new ones. This framing comes from network calculus, which R. L. Cruz set out in "A Calculus for Network Delay" (IEEE Transactions on Information Theory, 1991). It is how router queues and traffic shapers have long been reasoned about. Every algorithm on this page can be stated as an arrival curve, which makes the comparison exact rather than a matter of feel.

Fixed window: why the worst case is 2N. Take a limit of N per window of length W, with windows starting at multiples of W. Look at any interval of length W. It overlaps at most two consecutive windows: the end of one and the start of the next. Each window admits at most N, so the interval admits at most 2N. The bound is tight: N requests just before the boundary and N just after it fit in an interval of length almost zero. So the fixed window's real arrival curve is A(t) ≤ 2N for t ≤ W, about twice the intended rate on short timescales. For limits set to protect capacity, this factor of 2 is the reason to avoid fixed windows. For limits on a daily quota, it does not matter.

Sliding window counter: where the error comes from. The estimate is c_cur + c_prev × (1 − p). It is exact when the previous window's requests were evenly spread, because then the fraction (1 − p) of them really does fall inside the sliding window. In the worst case all of the previous window's requests came at its very end. They all lie inside the true sliding window, but the estimate counts only (1 − p) of them, so it under-counts by p·c_prev. With p close to 1, almost all of them are missed. The worst-case overshoot is therefore about N on very short timescales, but it needs a carefully timed attacker. Across a real population of clients the errors average out, which matches what Cloudflare reported. The opposite skew, everything at the start of the previous window, makes the estimate over-count, so the client is throttled a little early. That errs on the safe side.

Token bucket and GCRA are the same limiter. GCRA stores TAT, the theoretical arrival time. Each admitted request moves TAT forward by T = 1/r, and a request is admitted if TAT − now ≤ τ. Define tokens = (τ + T − (TAT − now)) / T, clamped to the range 0 to B. Then "admit if tokens ≥ 1" is the same as GCRA's test, and moving TAT forward by T is the same as spending one token. As time passes, TAT − now shrinks, which is the same as tokens refilling at rate r. The burst capacity is B = 1 + τ / T. So GCRA is a token bucket stored as one timestamp instead of two numbers. That saves memory, and it gives the exact "retry after" for free.

Worked example: tuning a timeline rule. Product says free users should average no more than 1 timeline refresh per second, but the app sends up to 12 requests at launch (timeline, profile, notifications, ads and so on). The choice is r = 1 per second and B = 15: the launch burst fits with some slack, and sustained scraping is capped at 3,600 per hour. Check it against data. Suppose sampled logs show that the 99.9th percentile of legitimate users peaks at 14 requests in any 10-second window. The arrival curve allows B + r·10 = 25 in 10 seconds, so legitimate users are never throttled. Now a scraper at 50 requests per second: it gets 15, then 1 per second, and the other 49 per second receive 429 from the local deny cache, not from Redis. The Redis cost of the scraper is about one call per gateway per second. The general method is to pick r from the sustained rate you can serve per user, then pick B from a high percentile of legitimate bursts, then check both against replayed traffic in shadow mode.

Little's Law and why concurrency limits are separate. For a stable system, L = λ·W: the average number in flight equals the arrival rate times the average time in the system. A service with 200 worker threads, at 100 ms per request, saturates at λ = 2,000 per second. If a slow dependency doubles W to 200 ms, the same service saturates at 1,000 per second, and no client is over its rate limit. Only a limit on L itself (concurrency) or on total λ (load shedding) protects it. Adaptive concurrency limiters treat the service like a congested network link. They raise the in-flight limit while latency stays flat and cut it when latency rises, much as TCP congestion control does. Netflix's open-source concurrency-limits library takes this approach.

Client-side adaptive throttling. Google's Site Reliability Engineering book (2016), in its chapter on handling overload, describes clients that throttle themselves. Each client tracks, over a recent window, how many requests it sent and how many the backend accepted. It then rejects new requests locally with probability max(0, (requests − K·accepts) / (requests + 1)), with K around 2. When the backend starts rejecting, clients cut their own traffic in proportion, so they stop spending network and server CPU on requests that would be rejected anyway. It complements server-side limits and does not replace them, because only clients we control will run it.

Overshoot budget, stated together. Every relaxation in this design has a bound. Write them down side by side, because interviewers like to see them:

  • Failover loses at most the last replication lag of writes, typically milliseconds of tokens.
  • Re-sharding resets moved buckets to full, which is a one-time burst of at most B per moved client.
  • Token leasing allows at most the sum of unspent leases, gateways × lease size, per client.
  • Multi-region sync adds at most (R − 1) × rate × sync delay.
  • Fallback mode stays within about 1.5 times the limit when traffic is spread evenly.

Each is small and short-lived, and each buys a large gain in latency or availability.

Deep Dive: Rate limiters in production: real systems and their lessonsShow

Stripe. Stripe's engineering blog post "Scaling your API with rate limiters" (2017) describes four layers. The first is a request rate limiter, a token bucket per user. The second is a concurrent requests limiter, which caps in-flight requests per user and targets expensive endpoints. The third is a fleet usage load shedder, which reserves a share of total capacity for critical requests. The fourth is a worker utilisation load shedder, which sheds lower-priority traffic first when workers are busy. Stripe implemented the limits with Redis. The post also advises rolling out limiters carefully: watch which customers would be throttled before enforcing, and give customers clear 429s so their clients can back off. That combination of rate, concurrency and shedding by priority is the layered model from Deep Dive 2, from a company whose API is critical for its users.

GitHub. GitHub's REST API documents a primary limit of 5,000 requests per hour for authenticated users and 60 per hour for unauthenticated requests by IP, with higher limits for some app installations. It reports x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-used and x-ratelimit-reset on every response. It also documents secondary rate limits, for example on concurrent requests and on content-creating endpoints, to catch bursts that the hourly limit would miss. It is a good illustration of a long-window quota plus short-window abuse limits, which is exactly the multi-rule evaluation from Deep Dive 10.

Envoy and Lyft's ratelimit service. Envoy supports local rate limiting, a token bucket inside each proxy, and global rate limiting, where it calls an external gRPC rate-limit service per request with a list of "descriptors" such as the route and a header value. Lyft open-sourced a reference implementation of that service, backed by Redis, with fixed-window counters and per-descriptor configuration in YAML. The design keeps policy, the descriptors to send, in the proxy configuration, and keeps state and limits in the service. The usual production advice is to use local limits for protection and global limits for contracts, with the global call kept fast and set to fail open by default. That default is worth questioning per route, as Deep Dive 6 argued.

NGINX. The limit_req module implements a leaky bucket per key, for example per $binary_remote_addr, with a burst queue. Without nodelay, excess requests in the burst are delayed to the configured rate: that is shaping. With nodelay, they are served at once but still use up burst slots: that is policing. Counters live in a shared memory zone across worker processes but are local to one server. That makes it a good per-node first layer, not a global limiter.

Cloudflare. Cloudflare has written about building its rate limiting on a sliding-window-counter approximation, so it needs only two counters per key at the edge. It accepts a small, measured error instead of storing per-request logs for millions of customer rules. The lesson generalises: at extreme scale the cheapest algorithm with a well-understood error beats an exact algorithm with high memory cost.

Amazon API Gateway and cloud quotas. AWS documents API Gateway throttling as a token bucket, with a steady-state rate and a burst, set at the account, stage and method levels and per API key through usage plans. Most cloud provider APIs work the same way, which is why their SDKs retry 429 and throttling errors with exponential backoff and jitter by default. The broader lesson: once your limiter is public, client libraries and their retry policies become part of your system.

Doorman (YouTube). Doorman is a distributed rate-limiting system open-sourced by YouTube. Clients ask a central server for a share of a global capacity and enforce that share locally, renewing leases regularly. The server allocates capacity with fairness algorithms, so that one client cannot starve the others. It is the token-leasing idea from Deep Dive 4 turned into a whole system. It suits limiting internal clients' use of a shared resource, such as a database's query capacity, where checking every request against shared state would cost too much.

Lessons that keep coming up:

  1. Most limiter incidents are configuration incidents. A rule that matches far more than intended, or a decimal error that sets 10 instead of 1,000. Shadow mode, impact replay and fast rollback prevent more outages than any algorithm choice.
  2. Fallback has to be tested. A fail-open path that has never run may fail closed, or crash, the first time Redis goes down. Practise it in drills by killing a shard in staging and in a production canary.
  3. The 429 path must be cheap. Rejections from attack traffic can outnumber real requests 100 to 1. If a rejection costs a Redis call, a log line and a JSON render, the rejections themselves become the load.
  4. Make limits visible. Customers who can see their usage through headers and dashboards file far fewer tickets and write better clients.
  5. Limits are product decisions. They determine what free users can do and what enterprise customers pay for. Keep them in versioned configuration owned with the product, not as magic numbers in gateway code.
Deep Dive: Building, testing and evolving the limiter from day one to global scaleShow

Stage 1: one region, modest scale (under 50k requests per second). A gateway plugin with a token-bucket Lua script against one Redis primary and its replica. Rules come from a config file reloaded on change, and fail-open is set per rule. This is perfectly reasonable for most companies. Many APIs never need more. Build two things early, because they are cheap now and expensive later: the check() interface that hides the algorithm and storage, and the headers in every response.

Stage 2: growth (50k-500k per second). Move to Redis Cluster with hash-tagged keys. Add the local deny cache and blocklist, because attack traffic grows faster than real traffic. Move rules to a rule service with versions and polling. Add shadow mode the first time a rule causes an incident, or better, before.

Stage 3: large scale (around 1M per second, multiple regions). Regional clusters with local fallback buckets and circuit breakers. Push-based rule distribution. Global sync only for contract rules. Token leasing for the largest customers. Concurrency limits and load shedding inside services. Fleet-wide limits enforced as local shares.

Testing a rate limiter. Correctness tests compare the implementation against a simple model. Run a random sequence of request times and costs through both the Lua script and a straightforward in-memory reference implementation, then assert that they make identical decisions. This is property-based testing, and it is very good at finding refill rounding errors and off-by-one boundaries. Concurrency tests send thousands of parallel requests for one key and assert that exactly B are admitted. Without the atomic script, this test fails right away. Clock tests run the script with gateway clocks skewed by seconds and confirm that the server-time design ignores them. Load tests replay production-shaped traffic, including the skew: a heavy-tailed distribution of requests per key with a few very hot keys, because uniform synthetic load hides hot shards. Chaos tests kill a primary, partition a zone, and add 50 ms of latency to one shard. They assert that the API stays up, that fallback engages within the breaker threshold, and that alerts fire. See Capacity Planning and Load Testing.

What to measure.

  • Decisions. Allowed and denied per rule and per tier, plus shadow "would-deny" counts. A sudden rise in denials on one rule after a deploy is the clearest sign of a bad rule.
  • Check latency. A per-shard histogram, the timeout rate, and the share of decisions made in fallback mode.
  • Redis health. CPU per primary (look for the hottest one, not the average), script latency, memory, evictions, replication lag and failover events.
  • Configuration. The rule-set version running on each gateway and how long a rollout takes to converge.
  • Top keys. The most-throttled keys and the most-active keys, sampled. They feed the abuse team and capacity planning.

Cost. At about 100 Redis processes on memory-optimised instances, the limiter's state tier is a modest line item next to the API fleet it protects. It is usually much smaller than the backend compute that a single unprotected scraping incident would use. The local deny cache and leasing reduce Redis calls and therefore the number of shards. In practice they often halve the cluster size needed during attacks. When debating the cost, compare the limiter with the incidents it prevents, not with zero.

Variants interviewers ask about.

  • Per-tenant fairness in a multi-tenant SaaS. Combine a per-tenant limit with per-user limits inside the tenant, so one tenant's script cannot use up everyone else's capacity. See Multi-Tenant SaaS Architecture.
  • Cost-based limits for expensive operations. Searches cost 5 tokens and exports cost 100. Some APIs charge by measured compute rather than request count. GraphQL APIs often score query complexity before execution and spend that many tokens, because one GraphQL query can do the work of a thousand REST calls.
  • Limits for LLM or AI APIs. Limit both requests per minute and tokens per minute. Since output length is unknown at request time, spend an estimate up front and settle the difference when the response completes. This is the refund idea again.
  • Rate limiting writes to a downstream system such as an email provider or SMS gateway. Use a shaper with a queue (a leaky bucket), not a rejecter, because the work must eventually happen. See Distributed Locks for the related problem of making sure only one worker drains a given queue.

Key Takeaways#

  • Choose the algorithm per rule. Token bucket or GCRA for API traffic (rate plus burst, tiny state). Sliding log for small, high-stakes limits such as login. Sliding window counter for customer-visible windows. Concurrency limits for protecting capacity. Details in Rate Limiting and Throttling.
  • Enforce at the gateway against shared, sharded, same-region state. Do the whole read-compute-write in one atomic Lua script. Key every client's counters with a hash tag so one script covers all of their rules. This is Pattern: Dealing with Contention and Pattern: Scaling Writes applied to counters.
  • Bound the latency. One round trip, pooled connections, same-zone placement and a strict timeout with a defined fallback, so the limiter can never make the API slow.
  • Neither fail-open nor fail-closed globally. Degrade to per-gateway local limits, fail closed only for security-critical rules, and make Redis failures rare with replicas and automatic failover.
  • Use eventual consistency across regions on purpose. Enforce locally, reconcile asynchronously with mergeable counters, and state the overshoot bound. Keep billing-grade quotas separate and strongly consistent.
  • Rules are code. Version them, validate them, run them in shadow mode, roll them out as canaries and roll them back in one step. Bad rules cause more limiter outages than bad Redis nodes.