Summary#
A rate limiter controls how many requests a client may make in a period of time. For example, it might allow 100 requests per minute per user, and reject the excess with HTTP 429 Too Many Requests. Rate limits protect systems from overload, stop abuse such as scraping, brute-force logins and spam, share capacity fairly between customers, control the cost of expensive operations, and enforce the terms of paid plans.
To build one, you decide five things:
- where to enforce limits: client, edge or gateway, service, or outbound calls to dependencies;
- who a "client" is: user ID, IP address, API key, or a combination;
- which algorithm counts requests: token bucket, leaky bucket, fixed window, sliding log, or sliding window counter;
- where the counters live, so that many servers agree. Usually that is Redis, updated atomically with a Lua script;
- how to tell clients they're limited: 429 plus
Retry-Afterand rate-limit headers.
At scale, the hard parts are latency (the check must add only a millisecond or so), sharding the counters, hot keys, the behaviour when the limiter itself fails, and tiered limits by plan, endpoint and cost, as Stripe and others do.
Why It Exists#
Every system has finite capacity, and the clients of every public system include some that are careless, greedy or hostile. Without limits, one client can take far more than its share.
- Overload protection. A buggy client in a tight retry loop, or a viral spike, can send ten times normal traffic. Limits stop one source from exhausting capacity meant for everyone.
- Fairness, or noisy neighbours. In a multi-tenant API, one tenant's batch job shouldn't slow every other tenant's interactive requests. Per-tenant limits give each tenant a predictable share.
- Abuse prevention. Credential stuffing (trying leaked passwords against many accounts), brute-forcing one-time codes, scraping catalogues, creating spam accounts, and scalping tickets all depend on making many requests quickly. Limits per IP, per account and per endpoint make them slow and expensive.
- Cost control. Some requests cost real money: an SMS message, a call to a paid third-party API, a large language model inference, an expensive search query. Limits cap the bill, including the bill from your own bugs.
- Business rules. Paid plans include quotas, such as 10,000 calls a day on the free tier and 1 million on the pro tier. The rate limiter enforces the contract.
- Protecting dependencies. Outbound limits keep your service within a partner's quota. Payment providers, email services and cloud APIs all throttle their callers, and exceeding their limits gets you throttled or blocked.
A few terms are often used loosely, so it helps to separate them.
- Rate limiting rejects requests over a defined allowance per client: N requests per period.
- Throttling is often used as a synonym. More precisely, it means slowing requests (delaying or queuing them) rather than rejecting them. Some APIs say "throttled" for any 429.
- Quotas are long-period allowances: per day, per month, or per billing cycle. They are usually tied to plans and billing.
- Load shedding is the server rejecting work because it is overloaded, regardless of who is asking. Resilience Patterns covers it. A rate limit is about the client's behaviour, and load shedding is about the server's state. Production systems use both.
- Concurrency limits cap the number of requests in flight at once, rather than the number per second. They protect against slow, expensive requests that a rate limit alone would let pile up.
How It Works#
A rate limiter answers one question for each request: "is this client, doing this operation, still within its allowance?" Its interface is small:
isRequestAllowed(clientKey, ruleId) -> { allowed: boolean, remaining: number, resetAt: timestamp }Three kinds of thing are involved.
- Rules define the limits. "Authenticated users: 1,000 requests per hour." "The search endpoint: 10 per minute per IP." "Free plan: 10,000 calls per day."
- Clients are whoever the limits apply to, identified by a key: user ID, API key, IP address, or a combination.
- Requests carry the context used to pick rules: identity, endpoint, method, plan.
For each request, the limiter identifies the client, finds the rules that apply, checks and updates the client's usage for each rule, and allows the request only if every applicable rule allows it. The most restrictive rule wins.
The rest of this section covers each decision in turn: where to enforce, how to identify clients, which algorithm to use, how to keep counters consistent across servers, what to return, and how to model tiered limits.
Where to rate limit: client, gateway or service#
There are three broad places to put the limiter, plus the client.
In-process, in each application server. Each server keeps counters in its own memory. That makes the check very fast, with no network call. The flaw is that each server sees only its share of traffic. With a limit of 100 per minute and 5 servers behind a round-robin load balancer, each server sees about 20 of a user's requests and allows them, while the user actually makes 100, or up to 500 before any server objects. Uneven routing makes the effective limit unpredictable. In-process limits are fine for a single server, for per-instance protection limits ("this instance accepts at most 500 requests a second"), or as a coarse first layer. They don't work for per-client limits across a fleet.
A dedicated rate-limiting service. Application servers call a central service before handling each request: "may user 12345 do this?" The service holds global counters, so limits are exact across the fleet. Because the caller is the application, it can pass rich context: subscription tier, account status, the endpoint, or business rules such as "double limits during the sale". The costs:
- an extra network hop on every request (typically 1–5 ms within a region);
- a new critical dependency, which raises the question of what happens when it is down or slow;
- another service to deploy, scale and monitor.
Lyft's open-source Envoy "ratelimit" service is an example. Envoy proxies call it over gRPC with a set of descriptors, and the service checks counters in Redis.
At the edge: API gateway, load balancer or reverse proxy. Every request passes the gateway anyway, so the limiter runs there and rejects excess requests before they reach any application server. This is the most common placement. It is conceptually simple, it protects everything behind it, and blocked requests cost the backend nothing. The limitation is context. The gateway sees only what is in the request: path, method, headers, IP address, API key, and claims in an authentication token such as a JWT. A rule like "enterprise customers get 10× the limit" is easy only if the plan is in the token, or can be looked up cheaply and cached. The gateway still needs shared state for counters, which is usually Redis. Kong, AWS API Gateway, Apigee, Envoy and NGINX all provide gateway rate limiting. API Gateway and Backend-for-Frontend covers gateways in general.
In the client. Well-behaved clients and SDKs can limit themselves. For example, an SDK can use a local token bucket, or read the server's rate-limit headers and pace itself. This smooths traffic and avoids pointless 429s. It is never a security control, because clients can't be trusted, but it's a valuable complement. Large customers running data pipelines are often the source of hot keys. Client-side pacing keeps them from hammering one counter.
Placement, in depth: layering limits through the stack#
Real systems use several layers, each doing what it is best placed to do.
- Network edge (CDN or WAF): coarse per-IP and per-network limits, bot detection and DDoS filtering, absorbing floods before they reach your infrastructure. Cloudflare, AWS WAF with AWS Shield, Akamai and Fastly all offer rate-limiting rules at the edge.
- API gateway: per-API-key, per-user and per-endpoint limits using shared counters. Plan tiers are applied here when the plan is known from the key or token.
- Service: limits that need business context. "Five password-reset emails per account per hour." "Three failed OTP attempts per code, then invalidate it." "Ten ticket purchase attempts per minute per account during a drop." These belong next to the business logic, because only the service knows what counts. A failed login is one HTTP request, but it's the failure that should count.
- Per-instance protection: a concurrency limit, or a requests-per-second ceiling, on each instance. It works regardless of who is calling, and it's really load shedding.
- Outbound: limits on calls to partners and dependencies, so that you stay inside their quotas. Often this is one shared token bucket per partner, or per partner account, across all your workers.
Each layer fails differently, and they back each other up. If the gateway's Redis cluster is unavailable and the gateway fails open, the per-instance limits still protect each server from collapse.
Choosing between a gateway and a dedicated service is about context and coupling. If most rules depend only on identity and endpoint, the gateway is simpler and faster. If rules depend on business state (plan, account age, fraud score, a sale in progress), either enrich the identity token with that state at login, or call a dedicated service from the application. A common hybrid is to apply coarse limits at the gateway and fine, business-aware limits in services.
The latency budget is tight. A limiter on the critical path of every request should add about 1 ms at p50, and only a few milliseconds at p99. A Redis call within the same availability zone typically takes 0.2–1 ms, plus client overhead. Crossing zones adds about 1–2 ms, and crossing regions adds 50–150 ms, so the counter store must be close to the gateway. Keep persistent, pooled connections. A new TCP connection, and especially a new TLS connection, can cost several milliseconds within a region, or tens of milliseconds across a long distance. Run the check as one round trip: a Lua script, not separate read and write calls. For a single request that matches several rules, pipeline the checks, or combine them into one script.
Identifying clients: per-user, per-IP and per-key limits#
The key a limit is counted against decides who shares an allowance.
- User ID. This suits authenticated APIs. Each user gets their own allowance, wherever they connect from. The ID usually comes from a session or a token (for example the
subclaim of a JWT), which the gateway validates. - API key. This is standard for developer and partner APIs: each key, and so each integration or customer, gets its own allowance, and plans attach to keys. The key usually comes in a header such as
Authorization: Bearer …orX-API-Key. - IP address. This is the only option for anonymous traffic: sign-up pages, login forms, public endpoints. It's also a useful second dimension even for authenticated traffic, against credential stuffing across many accounts from one source. IP addresses are imperfect keys, though.
- Many users can share one address behind a corporate NAT, a mobile carrier's NAT (CGNAT), or a university network, so IP limits must be generous.
- One attacker can use thousands of addresses through botnets or residential proxies.
- An IPv6 user typically controls a whole /64 network, or more, so limit on the /64 prefix rather than the full address.
- Combinations. You can count per user per endpoint ("this user's search calls"), per account per IP, or per tenant. The key is just a string such as
rl:search:user:alice, so you can count against anything you can extract.
Finding the real client IP. Behind load balancers and CDNs, the TCP peer address is the proxy's address. The original client address arrives in a header: X-Forwarded-For, the standard Forwarded header, or provider-specific headers such as CF-Connecting-IP. Any client can send these headers with fake values. Trust only the entries added by your own proxies. In practice that means the address your outermost trusted proxy appended, counting from the right of X-Forwarded-For. Otherwise an attacker rotates fake addresses in the header, and evades every per-IP limit.
Layer rules, and enforce the most restrictive. A request typically matches several rules:
- per user: Alice may make 1,000 requests per hour;
- per IP: this address may make 100 requests per minute;
- per endpoint: search is limited to 10 per minute per user, while profile updates allow 100 per minute;
- global: the whole API accepts 50,000 requests per second, as a final safety ceiling.
If Alice has used 50 of her 1,000 hourly requests, but her IP address has reached its 100 per minute, she is blocked. Check every rule, and reject if any rule rejects. Return the headers of the rule that is most constrained, so the client knows which limit it hit.
Client identification, in depth: rule matching, cost and anonymous traffic#
Rules as data. Store rules as records, not code, so operators can change them without a deploy. For example:
- id: search-per-user
match: { path: "/v1/search", auth: user }
key: "user:${user_id}"
limit: { requests: 10, per: 60s, burst: 20 }
- id: anon-per-ip
match: { auth: none }
key: "ip:${client_ip_prefix}"
limit: { requests: 100, per: 60s }
- id: pro-plan-per-key
match: { plan: pro }
key: "key:${api_key_id}"
limit: { requests: 1000, per: 1s, burst: 2000 }Matching should be fast. Index rules by path or route, plan and authentication state, so each request evaluates a handful of rules, not hundreds.
Not all requests cost the same. A request that fetches one record and a request that exports 10,000 records shouldn't consume the same allowance. Options:
- Weight requests by cost. A token bucket can deduct more than one token per request, for example 1 per read, 5 per write, 50 per export. GitHub's GraphQL API computes a points cost per query from the number of nodes requested, and limits points per hour.
- Separate buckets per class. Stripe separates read and write limits, for example.
- Concurrency limits for long-running requests, so that ten parallel exports can't tie up workers even if they fit the per-minute count.
Anonymous and pre-authentication endpoints need special care, because they are the main targets of abuse. Login, sign-up, password reset and OTP verification should be limited along several dimensions at once:
- per IP (or IP prefix), to slow one source;
- per target account or phone number, to stop distributed attacks on one victim;
- per device fingerprint or session cookie, where available;
- globally per endpoint, to catch large distributed attacks.
They also need escalating responses, not only rejection: CAPTCHAs, increasing delays, and temporary blocks. For OTP codes, the limit is part of the security model. A 6-digit code has 1,000,000 possibilities. Allowing 5 attempts per code gives an attacker a 5 in 1,000,000 chance per code. Allowing unlimited attempts makes the code useless.
Automatic blocklists. A client that keeps hitting its limits, say 10 times in a minute, is probably a misbehaving bot or an attacker. Move it to a temporary blocklist, for 15 minutes for example, checked before the normal counters. A blocklist check can be a local in-memory lookup of a small set, refreshed from Redis. That makes the abusive traffic cheap to reject, and keeps hot keys away from the counter store.
Rate-limiting algorithms compared#
Five algorithms dominate. They differ in how they treat bursts, how accurate they are at window boundaries, and how much memory and work they need per client.
| Algorithm | State per client | Bursts | Accuracy | Typical use |
|---|---|---|---|---|
| Token bucket | 2 numbers (tokens, last refill time) | Allows up to bucket capacity, then the steady rate | Exact for its definition | API rate limits (common at gateways and SDKs); AWS API Gateway throttling; Stripe |
| Leaky bucket (as a queue) | A queue, plus a drain rate | Smooths bursts into a steady output; excess waits or is dropped | Exact output rate | Traffic shaping; NGINX limit_req; smoothing calls to a fragile dependency |
| Fixed window counter | 1 counter per window | Up to 2× the limit around a window boundary | Coarse | Simple quotas (per day or month); low-stakes limits |
| Sliding window log | 1 timestamp per request in the window | No boundary bursts | Exact | Low-volume, high-stakes limits such as logins and OTPs |
| Sliding window counter | 2 counters (current, previous) | Smooths the boundary problem | Approximate (assumes even spread) | High-volume API limits wanting near-sliding accuracy cheaply |
Token bucket#
Picture a bucket that holds at most b tokens (its capacity, or burst size). Tokens drip in at a steady rate r per second, and tokens beyond capacity overflow and are lost. Each request takes one token, or a cost of c tokens. If the bucket has enough tokens, the request is allowed and the tokens are removed. If not, the request is rejected, or it could wait. A client that has been idle can spend its saved-up tokens in a burst of up to b requests, and after that it's held to r per second.
For example, take b = 100 and r = 10 per second. A client idle for a while can send 100 requests at once, then 10 a second after that. Over any interval of length t, the client can never get more than b + r × t requests through. For a 60-second interval that is 100 + 600 = 700. This property makes the bucket easy to reason about.
You don't need a timer that adds tokens. Store two numbers per client, tokens and last_refill, and refill lazily when a request arrives:
function allow(bucket, cost, now):
elapsed = now - bucket.last_refill
bucket.tokens = min(capacity, bucket.tokens + elapsed * rate)
bucket.last_refill = now
if bucket.tokens >= cost:
bucket.tokens -= cost
return ALLOW, remaining = floor(bucket.tokens)
else:
wait = (cost - bucket.tokens) / rate # seconds until enough tokens
return REJECT, retry_after = ceil(wait)New clients start with a full bucket (tokens = capacity). Buckets for idle clients can be deleted after they would have refilled completely, which takes capacity ÷ rate seconds. A deleted bucket behaves exactly like a full one, so expiring keys after that time saves memory, and changes nothing.
Token buckets are popular because they match how real clients behave. A page load fires 20 API calls at once, then nothing for a minute. A strict "1 per 3 seconds" limit would reject most of that page. A bucket with a burst of 30 and a rate of 1 per second allows it, while still capping sustained abuse. Stripe described using token buckets for its request rate limiters, and AWS API Gateway documents its throttling as a token bucket, with a rate and a burst setting.
Token bucket, in depth: parameters, GCRA and the leaky bucket connection#
Choosing r and b. Set r from the sustained rate you want to allow, and b from the legitimate burst you expect. Measure both from real traffic. For example, use the p99 of per-client requests in a 1-second window for b, and the p99 of per-client average rate per minute for r. Then add headroom. A bucket with b = 1 is a strict pacer with no burst. A bucket with a very large b permits long floods after idle periods, so a common guide is b ≈ r × (a few seconds to a minute).
Cold start. Every new client, or every client after a restart that lost the counters, starts with a full bucket. An attacker creating many fresh identities gets a full burst for each, so combine per-key buckets with per-IP or per-account limits on identity creation. If counters are lost during a failover, every client gets a fresh burst at once. Size b so the backend can absorb that.
Fractional tokens and precision. Store tokens as floating-point values, or as integers in milli-tokens, and the time in milliseconds or microseconds. Otherwise low rates, such as 1 request per minute, round incorrectly. Use one clock. In a distributed limiter, use the counter store's clock, such as Redis's TIME command, or tolerate small skews between gateway clocks. A gateway with a clock running fast refills buckets slightly early.
GCRA, the Generic Cell Rate Algorithm. GCRA comes from ATM networking. It is equivalent to a token bucket, but it stores only one number per client: the theoretical arrival time (TAT), which is the time at which the client's next request would be "on schedule".
- Let the emission interval be T = 1 ÷ r, and the burst tolerance be τ = T × (b − 1).
- On a request at time
now, computetat = max(TAT, now). - If tat − now > τ, reject. The client is too far ahead of schedule.
- Otherwise allow the request, and set TAT = tat + T.
One timestamp per key means less memory, and a simpler atomic update. The redis-cell Redis module (command CL.THROTTLE) implements GCRA, and several gateway libraries use it internally.
Leaky bucket, two meanings. The term leaky bucket is used for two different things.
- Leaky bucket as a meter is mathematically the same as a token bucket, viewed from the other side. Requests pour water into a bucket that leaks at rate r. If adding a request would overflow capacity b, the request is non-conforming and is rejected. This is the form GCRA implements.
- Leaky bucket as a queue really holds the requests. Arrivals join a FIFO queue of bounded size, and a worker drains the queue at exactly rate r. Bursts are smoothed into a steady output instead of being passed through. Excess arrivals beyond the queue size are dropped.
The queue form is traffic shaping. It is useful when the downstream system needs a steady pace, as when you call a partner API that allows exactly 10 requests per second, or push writes to a fragile legacy system. It adds latency, because requests wait in the queue. That's why it is a poor fit for interactive APIs, where a fast 429 beats an unpredictable delay.
NGINX's limit_req module is based on the leaky bucket. Its burst parameter sets the queue size. With nodelay, the queued requests are served immediately while their slots still count. That behaves like a token bucket, with the burst as the capacity.
Leaky bucket#
As above, a leaky bucket queue accepts requests into a bounded queue and processes them at a fixed rate, like water dripping from a hole in a bucket at a constant pace, however fast it's poured in. If the bucket is full, new water spills over, so the request is rejected.
- Strength: the output rate is perfectly steady, which protects downstream systems that can't handle bursts, and it enforces a precise pace.
- Weakness: a burst of legitimate requests waits in the queue, or is dropped, even when the system has spare capacity. Queue time adds latency. For example, with a drain rate of 10 per second and a queue of 50, the last request in a full queue waits 5 seconds. A burst of old requests can also delay new ones.
Use it for shaping outbound traffic and for background work. For per-client limits on inbound interactive APIs, prefer a token bucket.
Fixed window counter#
Divide time into fixed windows, such as each calendar minute, and keep a counter per client per window. Each request increments the counter. If the counter exceeds the limit, reject until the next window starts.
key = "rl:" + client + ":" + floor(now / 60) # e.g. rl:alice:28512345
count = INCR(key)
if count == 1: EXPIRE(key, 60) # first request in window sets the expiry
if count > limit: REJECT (retry after the window ends) else ALLOWThis is the cheapest algorithm: one counter, one increment, and the window number baked into the key name. It is ideal for long-period quotas such as "10,000 calls per day", where approximate edges don't matter.
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. Both windows look fine, yet 200 requests arrived within 2 seconds, twice the intended rate. Many clients synchronise on window resets, too, so traffic spikes at the start of every window.
There is also a subtle Redis bug to avoid. Set the expiry only when INCR returns 1, meaning on the first request of the window. If you call EXPIRE on every request, a steady stream of requests keeps pushing the expiry forward, and the window never resets. Do the INCR and EXPIRE in one Lua script. If a crash happened between the two commands, it would leave a counter with no expiry that never resets. (Including the window number in the key also prevents an old counter being reused.)
Sliding window log#
Keep a log of the timestamps of each client's recent requests. On each request, first delete timestamps older than the window, for example those more than 60 seconds old. Then count what is left. If the count is below the limit, add the new timestamp and allow. Otherwise reject. The window truly slides, because every check looks at exactly the last 60 seconds, so there is no boundary burst.
In Redis, a sorted set per client works naturally, with the timestamp as the score:
ZREMRANGEBYSCORE key 0 (now − window)drops old entries;ZCARD keycounts the rest;ZADD key now <unique-id>records the request;EXPIRE key windowcleans up idle clients.
Run the commands as one Lua script so they are atomic. The member must be unique, for example a timestamp plus a random suffix. Otherwise two requests in the same millisecond collapse into one.
The cost is memory and work proportional to the limit. A limit of 1,000 per minute stores up to 1,000 entries per client. A Redis sorted-set entry costs on the order of tens of bytes once you include the skiplist and hash overhead, so call it about 64 bytes. Then 1 million active clients, each near a limit of 1,000, would need 1,000,000 × 1,000 × 64 B ≈ 64 GB, against about 64 MB for a counter-based algorithm. The sliding log suits low limits with high stakes, such as 5 login attempts per 15 minutes, or 3 OTP verifications per code. There, exactness matters, and the logs are tiny.
Sliding window counter#
The sliding window counter approximates a sliding window using two fixed-window counters, for the current window and the previous one. It weights the previous window by how much of it still overlaps the sliding window:
estimate = prev_count × (1 − elapsed_in_current / window) + curr_countSuppose the limit is 100 per minute, the previous minute had 80 requests, the current minute has 30 so far, and we are 25% of the way into the current minute. Then estimate = 80 × 0.75 + 30 = 90. That is under 100, so the request is allowed. Ten seconds later, at 41.7% of the way in, the weight on the previous window has fallen to 0.583, the estimate is 80 × 0.583 + 30 ≈ 76.7, and the client has room for about 23 more.
It needs two counters per client, and gives much smoother behaviour than a fixed window: the boundary burst largely disappears. The approximation assumes the previous window's requests were spread evenly. If they were all at the end of the previous window, the estimate undercounts. If they were all at the start, it overcounts.
How good is the approximation in practice? Cloudflare's engineering blog described using this approach in its rate-limiting product, and reported that in an analysis of about 400 million requests from 270,000 distinct sources, about 0.003% of requests were wrongly allowed or wrongly limited. That is very small for a data structure of two counters.
Algorithms, in depth: choosing, combining and a worked comparison#
A worked comparison. Take a limit of 10 requests per 10 seconds, and a client that sends 10 requests at t = 9 s and 10 more at t = 11 s.
- Fixed window (windows 0–10 s and 10–20 s): all 20 are allowed. That is 20 requests in 2 seconds.
- Sliding log: at t = 11 s, the window covers 1–11 s and already holds 10 requests, so all 10 new ones are rejected. Exact.
- Sliding window counter: at t = 11 s, we are 10% into the window starting at 10 s, so estimate = 10 × 0.9 + 0 = 9. About 1 more request is allowed. Nearly exact.
- Token bucket (b = 10, r = 1 per second): at t = 9 s the bucket is full, and all 10 are allowed. By t = 11 s it has refilled 2 tokens, so 2 are allowed. That is 12 in 2 seconds, consistent with its b + r·t bound.
- Leaky bucket queue (drain rate 1 per second, queue size 10): the first 10 queue up and drain over 10 s. At t = 11 s the queue holds about 8, so roughly 2 more fit and the rest are rejected. Every request that is accepted is delayed, the last by up to 10 s.
Combining algorithms. Large APIs often use two limits on the same key: a short window, which controls bursts, and a long one, which controls volume. For example, a token bucket of 20 per second with a burst of 40, and a fixed-window quota of 100,000 per day. The bucket keeps the traffic shape healthy, and the daily quota enforces the plan. Each limit is cheap, and together they say what the business means.
Memory at scale. For 100 million daily active users with one rule each:
- a token bucket stores two numbers per key, about 100 bytes per key in Redis including key overhead, so ≈ 10 GB;
- GCRA stores one timestamp, so about two-thirds of that;
- a sliding log stores one entry per request, up to the limit per key, and is usually impractical at this scale for high limits.
Only active clients need state. With expiry set as described above, memory tracks the number of clients active in the last refill period, often far below the number of daily users.
Concurrency limiters complement rate limiters. A rate limit counts starts. A concurrency limit counts in-flight requests: increment when a request starts, decrement when it finishes. Ten slow exports a minute can be within any rate limit, but they can still tie up ten workers for minutes each. A per-client concurrency limit, such as 5 in flight per API key, stops that. Distributed concurrency counters need care. If a gateway crashes mid-request, its decrement never happens, so store in-flight entries with timestamps, in a sorted set for example, and expire entries older than the maximum request duration.
Distributed rate limiting with Redis and atomic Lua#
A fleet of gateways needs one shared view of each client's usage. If every gateway keeps its own buckets, the user whose 100 requests are spread over gateways A and B looks like a 50-request user to each. The usual answer is a fast shared store, most often Redis. It keeps data in memory, answers simple commands in well under a millisecond, supports expiring keys, and runs scripts atomically.
The naive version has a race. Here is a natural first attempt.
HMGET alice:bucket tokens last_refillreads the state.- The gateway computes the refill and the decision.
MULTI/HSET/EXPIRE/EXECwrites the new state.
The MULTI/EXEC transaction makes the write atomic, but the read happened outside it. Two gateways handling Alice's requests at the same moment both read "1 token left", both allow their request, and both write "0 tokens". Two requests got through on one token. Under load, with many concurrent requests per hot client, the limit leaks badly. This is the classic lost-update problem of a read-modify-write sequence. Dealing with Contention covers it in general.
The fix is to make the whole read-calculate-write sequence atomic. Redis runs a Lua script as a single atomic operation: no other command runs on that Redis instance while the script runs. The gateway sends the script once (SCRIPT LOAD, or the client library's caching), and then calls it by its hash with EVALSHA. Each check costs one round trip, with no race. Redis 7 also offers FUNCTION LOAD, which registers named functions with the same atomicity. An alternative is optimistic concurrency with WATCH/MULTI/EXEC, which retries if the key changed. That works, but under contention it causes extra round trips, so scripts are the norm.
A token bucket as a Lua script:
-- KEYS[1] = bucket key; ARGV: capacity, refill_per_ms, cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME') -- use Redis clock, not gateway clocks
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or capacity -- new client: full bucket
local ts = tonumber(s[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate) -- lazy refill
local allowed = 0
if tokens >= cost then tokens = tokens - cost; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate)) -- idle bucket = full bucket
local retry_ms = allowed == 1 and 0 or math.ceil((cost - tokens) / rate)
return { allowed, math.floor(tokens), retry_ms }The script reads and writes one key, so it works unchanged on Redis Cluster. (Older Redis versions required redis.replicate_commands() before writing after calling TIME. Redis 5 and later replicate a script's effects rather than the script, so this is no longer needed.) The return value gives the gateway everything it needs for its headers: whether the request is allowed, the tokens remaining, and how long until a retry could succeed.
Why Redis fits:
- sub-millisecond operations;
- automatic cleanup of idle clients through expiry;
- atomic scripts;
- replication and automatic failover (Redis Sentinel, or Redis Cluster);
- broad support in gateways and libraries.
Alternatives include Memcached with atomic incr (fixed windows only, with no scripting), DynamoDB or another database with conditional writes (more latency, but durable), and in-memory limiters inside a proxy synchronised by gossip.
Distributed limiting, in depth: sharding, hot keys, latency and failure#
Throughput and sharding. Suppose the target is 1 million requests per second. One Redis instance handles roughly 100,000–200,000 simple operations per second, and fewer for scripts that do several commands each. So a single instance might manage 50,000–100,000 rate-limit checks per second. Reaching 1 million needs about 10–20 shards, plus headroom. Shard by the rate-limit key, so that all of one client's checks land on the same shard. Otherwise the client's state is split, and the limit is meaningless. Consistent hashing on the key, done by the gateway, works (Consistent Hashing). In practice Redis Cluster does it for you. It divides the key space into 16,384 hash slots, assigns slots to nodes, and routes each key by the CRC16 of the key, modulo 16,384. Gateways use a cluster-aware client. If one check must touch several keys atomically, put them in the same slot with a hash tag, so that rl:{alice}:minute and rl:{alice}:day hash only on alice.
Hot keys. A single key can get more traffic than one shard can handle. That might be one API key used by a huge integration, one IP address behind a big NAT, or an attacker. A shard that handles 100,000 operations a second is overwhelmed by a single client sending 150,000 requests a second. Remedies depend on whether the traffic is legitimate.
- Legitimate high-volume clients:
- client-side rate limiting in the SDK, so the client paces itself;
- batch endpoints, so 100 operations become one request and one check;
- premium tiers with dedicated capacity;
- local token leasing, where a gateway takes a lease of, say, 100 tokens at once from Redis and spends them locally. That divides Redis traffic for the key by 100, at the cost of slight over-admission when the lease isn't fully used.
- Abusive traffic:
- automatic blocklisting: after repeated violations, block the key or IP address for a period, and check a small local blocklist before touching Redis at all;
- DDoS protection at the edge (Cloudflare, AWS Shield, Akamai), which absorbs floods before they reach the gateways.
Approximate, local-first limiting. Exact global counting isn't always worth one Redis call per request. Two common alternatives:
- Local counters with periodic synchronisation. Each gateway counts locally, and every 100 ms to 1 s pushes its increments to a shared store and reads the global total. Decisions use the last known global count plus local increments since. The error is bounded by roughly (number of gateways) × (rate per gateway) × (sync interval), which is often acceptable for limits on the scale of minutes.
- Splitting the limit. With N gateways and sticky-enough routing, give each a share of 1/N of the limit, and adjust shares based on observed traffic.
Envoy supports both a local rate limit filter (per proxy, no external calls) and a global one (calling a rate-limit service). A common arrangement uses the local filter as a cheap first stage, and the global service for exact per-client limits.
Latency. The check sits on every request's critical path, and the budget is often under 10 ms at p99, and ideally about 1 ms.
- Keep Redis in the same region, and ideally the same zone, as the gateways.
- Use persistent, pooled connections. A new TCP and TLS handshake per check would cost several milliseconds, or tens over longer distances.
- Make one round trip per request, combining all matched rules in one script, or pipelining.
- Set a short timeout on the Redis call, such as 5–20 ms, with a defined fallback.
Local caching of "this key is far under its limit" can skip some checks, but it risks over-admission. Use it only for very high limits, where the error is irrelevant.
When the limiter fails: fail open or fail closed? If Redis is unreachable or slow, the gateway must decide.
- Fail open: allow requests unchecked. The API stays up, but rate-limit protection is gone. That is dangerous if the limiter failed because of a traffic surge, because then the surge goes straight to the backends. This is the default choice for many consumer APIs, where availability matters most.
- Fail closed: reject requests that can't be checked. That's safe for the backends, but the API goes down while the limiter is down, often making the outage worse, as clients retry. It suits high-stakes operations: payment authorisation, OTP verification, and login attempts against brute force.
- Degrade to local limits (often the best middle ground). On a limiter failure, fall back to conservative per-gateway in-memory limits: the global limit divided by the number of gateways, or a fixed per-instance ceiling. Protection is approximate, but it never vanishes. Alert whenever a gateway enters the degraded mode.
The best defence is preventing limiter outages. Run Redis with replicas and automatic failover (Redis Cluster or Sentinel), spread across zones. Monitor the latency of the limiter itself. Use circuit breakers, so a slow Redis is treated as a failed Redis quickly. Note that Redis replication is asynchronous. After a failover, the newest counter updates may be lost, so some clients briefly get extra allowance. For rate limiting, that is almost always acceptable. Designing for High Availability discusses fail-open and fail-closed choices more broadly.
Multi-region. With gateways in several regions, a client's traffic usually goes to its nearest region. Options:
- Per-region limits: each region enforces its own counters, and the global limit is split between regions, for example in proportion to traffic. This is simple and fast, and it is accurate as long as a client mostly uses one region.
- Asynchronous global aggregation: regions count locally and exchange counts every second or so. A client spraying requests across regions can exceed the limit by up to the number of regions times the per-region allowance during one sync interval.
- A single global store: exact, but it adds 50–150 ms cross-region latency to each check, which is rarely acceptable.
Per-region enforcement with periodic reconciliation is the usual answer. Rate limits are protective and commercial controls, not accounting, so slight over-admission is tolerable. Billing-grade quotas, such as "1 million calls per month, then charge", can be counted exactly, but asynchronously, from request logs.
429 Too Many Requests and rate-limit headers#
When a client is over its limit, the usual response is to reject immediately with HTTP 429 Too Many Requests, the status code defined for this purpose (RFC 6585, 2012).
Why not queue excess requests and serve them later? For interactive APIs, queuing creates more problems than it solves.
- Queued requests consume memory and connections.
- The client's latency becomes unpredictable.
- Clients that time out while waiting retry, which adds more load.
Fast failure, with clear guidance, lets clients decide what to do. Queuing (throttling in the strict sense) fits only when clients are batch jobs that can afford to wait, or when you shape your own outbound traffic.
Headers tell well-behaved clients how to behave. The widely used de facto set:
X-RateLimit-Limit: the ceiling for this window or rule, for example100;X-RateLimit-Remaining: how many requests remain, for example0;X-RateLimit-Reset: when the allowance resets. This is a Unix timestamp in some APIs, and seconds-until-reset in others, so document which one you use;Retry-After(standard HTTP): how many seconds to wait before retrying, or an HTTP date.
A full rejection looks like this:
HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1767225600
{ "type": "https://api.example.com/errors/rate-limited",
"title": "Rate limit exceeded",
"status": 429,
"detail": "Limit of 100 requests per minute for this API key. Retry in 30 seconds.",
"limit_id": "per-key-minute" }Include the headers on successful responses too, not only on 429s. A client can then slow down before hitting the limit, by watching Remaining fall. GitHub's REST API, for example, returns x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-used, x-ratelimit-reset and x-ratelimit-resource headers on responses.
429 responses, in depth: standards, client behaviour and status-code choices#
The IETF standardisation effort. The IETF HTTPAPI working group has been developing standard RateLimit and RateLimit-Policy header fields to replace the many vendor variants. The draft has changed between versions, from separate RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset fields to structured fields describing named policies. So check the current draft before adopting it, and keep emitting the de facto X-RateLimit-* headers for compatibility.
429 or 503? Use 429 when this client exceeded its allowance, which is the client's own doing. Use 503 Service Unavailable when the server is overloaded for everyone (load shedding), or when the limiter fails closed. Both can carry Retry-After. Some APIs return 403 for quota exhaustion on a billing plan. That is less clear, and it confuses retry logic, because 403 normally means "don't retry".
Make the retry time honest.
- A token bucket can compute it exactly: (cost − tokens) ÷ rate.
- A fixed window returns the time until the window ends.
- A sliding window counter can estimate when the weighted count will fall below the limit.
If every rejected client is told "retry in exactly 60 s" at the window boundary, they all come back at once. Add a little jitter to Retry-After, or rely on clients adding jitter.
Client behaviour. Well-behaved clients:
- honour
Retry-After, and otherwise use exponential backoff with jitter (see Resilience Patterns); - pace themselves when
Remainingis low; - never retry 429s in a tight loop;
- surface persistent limits to operators, because they often mean a misconfiguration or a need for a higher tier.
SDKs should do all of this by default. For example, the AWS SDKs' adaptive retry mode adds client-side rate limiting that responds to throttling errors.
Shadow mode. Before enforcing a new or tightened rule, run it in log-only mode for days: compute the decision, but don't enforce it. Record which clients would have been limited. This catches rules that would break legitimate integrations, such as a partner's nightly sync that bursts to 50 requests a second, before customers see a single 429.
Telling users, not only programs. Interactive applications should turn 429s into a helpful message, like "You're doing that too often, try again in 30 seconds", and preserve the user's input. For abuse-sensitive endpoints, such as logins, deliberately vague messages and escalating friction (a CAPTCHA, then a delay) are better than a precise countdown, which tells an attacker exactly how fast they may go.
Tiered limits (Stripe-style)#
Most commercial APIs apply tiers: limits that vary by plan, by account and by endpoint, sometimes with special handling for test traffic and for critical operations. A typical structure:
| Tier | Sustained rate | Burst | Daily quota | Concurrency |
|---|---|---|---|---|
| Anonymous (per IP) | 1 request/s | 10 | 1,000 | 2 |
| Free (per key) | 10/s | 50 | 10,000 | 5 |
| Pro (per key) | 100/s | 500 | 1,000,000 | 50 |
| Enterprise (per key) | Negotiated, e.g. 1,000/s | 5,000 | Negotiated | 200 |
These numbers are illustrative. Real values come from capacity, cost and pricing.
The plan must be known when the check runs. That means it is encoded in the API key's record, which the gateway caches with a TTL of a minute or so, or in a signed token's claims, so the gateway doesn't query the billing database on every request.
Stripe's published approach is a useful model. In a 2017 engineering blog post, "Scaling your API with rate limiters", Stripe described running four kinds of limiters.
- A request rate limiter: requests per second per user, implemented as a token bucket, with bursts allowed.
- A concurrent requests limiter: a cap on in-flight requests per user, which protects against expensive, slow endpoints.
- A fleet usage load shedder: a portion of fleet capacity is always reserved for critical requests, such as charge creation, and non-critical requests are shed when the remaining capacity is used up.
- A worker utilisation load shedder: when workers are saturated, traffic is shed by priority class, starting with test-mode traffic, then GET requests, then less critical writes.
Stripe described implementing the limiters with token buckets in Redis. It also recommended rolling out limiters gradually, starting in a dark-launch mode that logs without enforcing. Stripe's API documentation has also published separate default limits for live mode and test mode, so that load testing against the test environment can't consume production capacity.
Tiered limits, in depth: designing a fair, monetisable limit system#
Separate the concepts. A clean design keeps four controls apart.
- Rate limits shape short-term traffic: per second, with bursts.
- Quotas cap long-term consumption: per day or month, often billed.
- Concurrency limits cap in-flight work.
- Load shedding protects the system by priority.
Each control has its own counters, error responses and headers. A client hitting a quota needs a different message ("upgrade or wait until the 1st") from one hitting a burst limit ("slow down for a second").
Per-endpoint and per-operation tiers. Not every endpoint deserves the same limit. Reads are cheap, writes cost more, searches and exports are expensive, and notifications (SMS, email) cost money per message. Define per-endpoint multipliers or separate buckets. For example, a pro key might get 100 reads/s, 25 writes/s and 2 exports/minute. Weighted costs in one bucket achieve the same thing with less configuration, but they are harder for customers to reason about.
Fairness inside a tenant. An enterprise tenant with 10,000 users and one shared key can be starved by one runaway script. Offer per-user sub-limits, or encourage per-integration keys, so a tenant's own noisy neighbour is contained. This is a bulkhead applied to limits.
Overrides and exceptions. Support temporary overrides, such as "double this customer's limit for their launch day", with an expiry, an owner and an audit trail. Keep a short emergency path: an operator can drop a limit for an abusive key within seconds.
Dynamic rule configuration. Limits change: launches, attacks, new plans, incidents. Store rules in a configuration store, not in code.
- Poll-based: gateways reload rules from a database or config service every 10–30 s. This is simple and robust, and it suits most changes. The weakness is propagation delay, which during an attack can be the longest 30 seconds of your day.
- Push-based: a coordination service pushes changes to gateways immediately. ZooKeeper and etcd watches notify subscribers when a key changes. Redis pub/sub, or a config service holding streaming connections, can do the same. Changes then propagate within a second or two. In exchange, you must handle missed notifications, gateways that reconnect, and partial rollouts. A common pattern combines the two: push for speed, plus a periodic full poll as a safety net.
Either way, validate rules before they are published (a limit of 0, or one wrong key template, can block everyone), roll out rule changes gradually, and keep the last good configuration cached on every gateway, so the configuration store isn't a critical dependency.
Observability for limits. Track the following:
- 429s by rule, tier and key, so you can spot customers who need an upgrade, and detect attacks;
- limiter latency, p50 and p99;
- the Redis CPU load and the hot shards;
- the rate of fail-open or degraded decisions;
- shadow-mode would-be rejections.
A sudden spike in 429s for many customers at once usually means a bad rule or a limiter bug, not a sudden burst of simultaneous abuse.
When to Use It#
- Any public or partner-facing API. Limits per key and per user, with tiers, are table stakes. Without them, one integration bug can take the API down for everyone.
- Authentication and verification endpoints: login, sign-up, password reset, OTP, CAPTCHA verification. Use multi-dimensional limits (per IP or prefix, per account, per device) with escalating friction. These limits are part of the security design.
- Expensive or costly operations: SMS and email sending, third-party paid APIs, model inference, exports, search. Limits cap cost and protect shared capacity.
- Multi-tenant platforms, to keep one tenant's surge from degrading the others.
- Outbound calls to partners with quotas, to stay under their limits and avoid being blocked. Use a shared bucket per partner account.
- Write-heavy contention points, such as flash sales and ticket drops, to keep bots from monopolising scarce inventory. Limit purchase attempts per account and per payment method.
- Background workers hitting shared resources, such as crawlers hitting websites, where per-domain politeness limits are both courtesy and necessity.
When NOT to Use It#
- As your only overload protection. Per-client limits don't stop overload from many well-behaved clients at once, for example a legitimate surge. You still need load shedding, autoscaling and capacity planning.
- To fix a hot path that should be cached or batched. If legitimate clients routinely hit limits because the API forces 100 calls to do one job, add a batch endpoint or caching, rather than tightening limits.
- With exact global counting where approximate would do. A cross-region, strongly consistent counter on every request costs latency and availability for precision nobody needs. Per-region or approximate limits are usually enough.
- IP-only limits for authenticated traffic. NATs make IP limits unfair, and botnets make them weak. Use identity-based limits whenever identity is known.
- Queuing excess interactive requests instead of rejecting them, except in genuine batch contexts.
- Internal service-to-service calls inside one trust domain, where concurrency limits, back pressure and load shedding are usually better tools. Per-caller quotas still help in large organisations, where one team's job can overwhelm a shared service.
How to Implement It#
- List what you're protecting, and from whom: overload, abuse, cost, fairness, plan enforcement. Each goal suggests a dimension (key, user, IP, endpoint) and a placement (edge, gateway, service, outbound).
- Choose identifiers: user ID for authenticated traffic, API key for developer traffic, IP prefix for anonymous traffic, plus the target account for login-type endpoints. Extract the client IP only from trusted proxy headers.
- Pick algorithms per rule: a token bucket for general API limits; a sliding log for low-volume, high-stakes limits; fixed windows for daily and monthly quotas; a leaky bucket for shaping outbound traffic; concurrency limits for expensive endpoints.
- Store counters in Redis (cluster mode, replicas across zones), in the same region as the gateways. Implement each check as one atomic Lua script, set expiries, and pool connections.
- Define failure behaviour: a short timeout on the limiter call; degrade to local per-instance limits; fail closed only for high-stakes endpoints; alert on degraded mode.
- Return 429s with
Retry-Afterand rate-limit headers, plus a Problem Details body naming the limit. Send the headers on successful responses too. - Manage rules as data, with validation, shadow mode, gradual rollout, overrides with expiry, and push-plus-poll distribution.
- Ship client-side behaviour in SDKs: honour
Retry-After, back off with jitter, pace onRemaining. - Instrument it: 429s by rule and key, limiter latency, Redis shard load, degraded decisions, and shadow-mode results.
A gateway-level example with NGINX's leaky-bucket limit_req, keyed on API key with a per-IP fallback:
# Key: API key if present, otherwise client IP (set via realip from trusted proxies only)
map $http_x_api_key $rl_key {
default $http_x_api_key;
"" $binary_remote_addr;
}
# 10 requests/second per key, 10 MB of shared memory (~160k keys)
limit_req_zone $rl_key zone=api_per_key:10m rate=10r/s;
limit_req_status 429;
server {
location /v1/ {
# Allow bursts of 20 served immediately; beyond that, reject with 429
limit_req zone=api_per_key burst=20 nodelay;
proxy_pass http://api_backend;
}
location /v1/login {
limit_req zone=api_per_key burst=5; # small burst, queued not instant
proxy_pass http://auth_backend;
}
}NGINX's zone lives in each instance's shared memory, so this example limits per NGINX instance. For fleet-wide limits, use a gateway with a shared store, such as Kong with its Redis policy, or Envoy with the global rate-limit service.
| Technology | Fits when |
|---|---|
| Redis + Lua scripts (or Redis Functions) | You build your own gateway or service limiter; need atomic, sub-millisecond shared counters |
| redis-cell module (GCRA) | You want a ready-made token-bucket-equivalent command (CL.THROTTLE) in Redis |
| Envoy local and global rate limit (with Lyft's ratelimit service) | Service mesh or Envoy-based edge; descriptor-based rules; local plus global layering |
| Kong, Apigee, Tyk, AWS API Gateway usage plans | Managed or packaged API gateways with per-key plans, quotas and throttling (AWS uses a token bucket with rate and burst) |
NGINX limit_req / limit_conn | Per-instance request and connection limits at a reverse proxy; simple protection |
| Cloudflare, AWS WAF, Akamai, Fastly rate-limiting rules | Edge limits per IP or signature, bot and DDoS protection before traffic reaches you |
| Bucket4j (Java), Guava RateLimiter, resilience4j RateLimiter | In-process limits in JVM services; Bucket4j can use distributed back ends (Redis, Hazelcast, JCache) |
| golang.org/x/time/rate | Token-bucket limiter in Go services and clients (outbound pacing, per-instance limits) |
| express-rate-limit, rate-limiter-flexible (Node.js) | Node services; rate-limiter-flexible supports Redis and other stores |
| ZooKeeper / etcd watches | Push-based distribution of rate-limit rules to gateways |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Token bucket | Allows realistic bursts; O(1) state; exact bound b + r·t | Two parameters to tune; cold-start bursts | General API limits |
| Leaky bucket queue | Smooth, fixed output rate | Adds latency; bursts wait or drop | Shaping outbound or background traffic |
| Fixed window | Simplest; one counter | 2× boundary bursts; synchronised resets | Daily or monthly quotas; low stakes |
| Sliding window log | Exact | Memory grows with the limit | Low limits, high stakes (login, OTP) |
| Sliding window counter | Near-exact; two counters | Approximation under skewed traffic | High-volume API limits |
| In-process limits | No network call; no dependency | Per-instance only; error up to N servers | Per-instance protection; single server |
| Gateway limits with shared store | Global, protects backends early | Limited business context; Redis dependency | Most API limits |
| Dedicated limiter service | Rich context; reusable | Extra hop; new critical service | Business-aware limits across many services |
| Fail open | API stays available | No protection during limiter outages | Consumer APIs, with local fallback limits |
| Fail closed | Backends always protected | API outage when the limiter fails | Payments, auth and other high-stakes endpoints |
| Exact global counters | Precise | Latency; cross-region cost | Billing-critical limits |
| Approximate local plus sync | Fast, resilient | Over-admission bounded by sync interval | High-volume, multi-region APIs |
Common Pitfalls#
- Read-then-write races. A read outside the transaction, followed by an atomic write, still double-spends tokens. Make the whole check atomic, in one Lua script.
- Calling
EXPIREon every request in a fixed window. The window never resets under steady traffic. Set the expiry only when the counter is created. - Per-instance limits mistaken for global ones. Five instances each enforcing 100 per minute allow 500.
- Trusting
X-Forwarded-Forblindly. Attackers forge the header and rotate addresses. Use only entries added by your trusted proxies. - Tight IP limits on shared networks. Corporate NAT and CGNAT users get blocked together. Prefer identity-based limits, and keep IP limits generous.
- Limiting full IPv6 addresses. Attackers rotate through their /64. Limit by prefix.
- No headers on successful responses. Clients only learn their limits by hitting them.
- Every client told to retry at the same instant. Window resets synchronise retries. Add jitter.
- Forgetting the limiter's own failure mode. A Redis outage either disables protection silently, or takes the API down. Decide in advance, and degrade to local limits.
- Unbounded rule cardinality. A key template that includes the full URL or a query string creates millions of keys. Key on normalised routes.
- Pushing untested rules to production. A mistyped limit blocks every customer. Validate, run in shadow mode, and roll out gradually.
- Counting the wrong thing. For logins, count failures per account, not requests. For exports, count cost or concurrency, not calls.
Real-World Examples#
- Stripe. Stripe's 2017 post "Scaling your API with rate limiters" described a request-rate limiter (a token bucket in Redis), a concurrent-requests limiter, a fleet usage load shedder that reserves capacity for critical requests, and a worker utilisation shedder that sheds traffic by priority. Stripe's documentation lists separate default limits for live and test modes, and its API returns 429 when limits are exceeded.
- GitHub. GitHub's REST API documents a primary rate limit of 5,000 requests per hour for authenticated users (higher for some GitHub App installations), and 60 per hour for unauthenticated requests per IP. It reports usage through
x-ratelimit-*headers. Separate "secondary" limits cover bursts and concurrency. The GraphQL API limits by a computed points cost per query. - Cloudflare. Cloudflare's blog described its rate-limiting implementation using a sliding window counter approximation, with very low measured error, at the scale of millions of domains.
- Lyft and Envoy. Lyft open-sourced its Go-based
ratelimitservice, which Envoy proxies call over gRPC with request descriptors. It stores counters in Redis. Envoy also has a local, per-proxy rate-limit filter. - AWS API Gateway. AWS documents throttling with a token bucket algorithm: steady-state rate and burst settings at the account, stage, method and usage-plan levels, with usage plans tying API keys to rates and quotas.
- X (formerly Twitter) API. X's API has long used per-endpoint limits counted over 15-minute windows, per user or per app.
Case studies that use this pattern#
- Design a Distributed Rate Limiter: the full design, with algorithm choice, gateway placement, Redis sharding, hot keys, fail-open or fail-closed choices, rule configuration and multi-region.
- Design a Web Crawler: per-domain politeness limits, robots.txt crawl delays, and outbound pacing.
- Design a Notification System: per-user notification caps, provider quotas (APNs, FCM, SMS gateways), and outbound shaping.
- Design a Payment System: fail-closed limits on payment attempts, and limits against card-testing fraud.
In the Interview#
Deep Dive: the token bucket bound, and error in distributed countingShow
Why the token bucket admits at most b + r·t in any window of length t. Let A(s, s + t) be the number of requests admitted in the interval [s, s + t], with unit cost. At time s the bucket holds at most b tokens. During the interval, at most r·t more tokens arrive. Each admitted request removes one token, and the count never goes negative. So A(s, s + t) ≤ b + r·t. This is the arrival curve α(t) = b + r·t, the same object network calculus uses to reason about traffic shaping (Cruz, "A Calculus for Network Delay", IEEE Transactions on Information Theory, 1991). The bound is tight. A client that is idle until s, then sends as fast as possible, hits it exactly. So the backend should be provisioned for b + r·t per client over its smallest meaningful window, not just for r.
Sliding window counter error. With a limit L over a window W, suppose the previous window contained P requests, arriving at unknown times, and we are a fraction f into the current window. The true count of requests in the sliding window is between C and C + P (where C is the current window's count), depending on where in the previous window those P requests fell. The estimate C + P·(1 − f) assumes they were uniform. The worst case is P = L, with every request at the very end of the previous window. Then the true count right after the boundary is L + C, but the estimate is close to L·(1 − f) + C. At small f, both are near L + C, so the error is small. It grows linearly with f, up to L·f at the extreme, for an adversary who concentrates traffic at the window's edge. In practice, traffic is far smoother, which is why Cloudflare's measured error was tiny. A determined client can exploit the approximation slightly. When exactness matters against adversaries, use a sliding log, or GCRA.
Distributed over-admission. With G gateways using local counters synced every Δ seconds, each gateway admits requests based on a global count that may be up to Δ old. A client spreading traffic evenly across all G gateways at a rate well above the limit can be over-admitted by up to about G × (r_local × Δ) before the sync catches up. For example, with G = 50 gateways, Δ = 1 s, and a per-gateway local allowance of 2 requests per second, over-admission reaches about 100 requests. That is negligible against a limit of 10,000 per minute, and material against a limit of 10. The general rule: the lower the limit, the more exact the counting must be. High-volume limits can use local or approximate counting. Low limits, such as logins and OTPs, should use exact, central, atomic counting.
Token leasing. A gateway that takes a lease of k tokens at once reduces store traffic by a factor of k, at the cost of up to k × G tokens held by gateways but not yet used. When a client's demand falls, unused leased tokens can be returned or left to expire. Choose k from the per-key rate: about the number of requests the gateway sees for that key in 50–100 ms. Then leases are reused quickly, and the error stays bounded.
Deep Dive: rate limiting against abuse, beyond simple countersShow
Counting requests per key stops careless clients, not determined adversaries. Abuse-focused systems layer more signals.
Distributed attacks need multiple keys. Credential stuffing tries millions of leaked username-password pairs, from thousands of IP addresses (residential proxies), a few attempts each. Per-IP limits barely trigger. Effective defences count along several dimensions at once:
- failed logins per target account (an account under attack gets friction, such as a CAPTCHA, step-up verification or a delay, whatever the source IP);
- failures per IP prefix and per autonomous system (ASN);
- global failure rate for the endpoint, where a sudden jump in failures signals an attack in progress, and raises friction for everyone;
- per device or browser fingerprint, where available.
Escalating responses beat hard blocks. A binary allow-or-429 tells an attacker exactly where the line is. Graduated responses raise the attacker's cost while sparing real users:
- add latency, such as a 1–2 s delay after a few failures, which is cheap for a human and expensive at bot scale;
- require a CAPTCHA or proof-of-work;
- require step-up authentication;
- block temporarily, with exponentially growing block durations for repeat offenders.
Cost asymmetry. For OTP and password-reset flows, model the attacker's success probability. A 6-digit code with 5 attempts per code and 3 codes per hour per account gives at most 15 guesses per hour, which is 15 in 1,000,000 per hour. Without per-account limits, an attacker with 1,000 IP addresses at 5 attempts each gets 5,000 guesses per code. That's a 0.5% chance per code, and it adds up quickly. Limits per target are what make the security argument hold.
Scraping and inventory hoarding. Scrapers spread requests across accounts and addresses, and mimic browsers. Defences include:
- per-account limits tied to account age and reputation (new accounts get lower limits);
- limits on unusual access patterns, such as sequential IDs or very deep pagination;
- requiring authentication for expensive endpoints;
- edge bot management, which uses many signals beyond rate.
For flash sales and ticket drops, combine limits with a virtual waiting room that admits users at a controlled rate, and with per-account and per-payment-method purchase caps.
Shared infrastructure, fairly. Abuse controls must not punish innocent users who share an address. That includes a university network, a mobile carrier's CGNAT pool covering thousands of subscribers, and an enterprise proxy. Favour identity-based limits. Allow-list known shared egress ranges with higher IP limits. Let authenticated users escape IP-level friction.
Deep Dive: fairness, weighted shares and adaptive limitsShow
Fixed per-client limits are simple, but they waste capacity. When the system is quiet, a client capped at 100 requests a second is rejected even though capacity sits idle. When it's busy, the sum of every client's allowance may exceed capacity. Two refinements address this.
Max-min fairness and weighted shares. Treat capacity C as a resource divided between active clients. Max-min fairness gives each client the smaller of its demand and an equal share, then redistributes leftover capacity among the clients that want more. Weighted fair sharing does the same in proportion to weights, such as plan tiers. With C = 10,000 requests/s and three active clients with weights 1, 1 and 8 demanding 500, 5,000 and 20,000, the weighted fair shares are 1,000, 1,000 and 8,000. Client one needs only 500, so the leftover 500 is split 1:8 between the others. Client two ends up near 1,055, and client three near 8,445. Network schedulers implement this through weighted fair queueing and deficit round robin. In request systems, approximations are common: per-tenant queues served round-robin by weight, or limits recomputed every few seconds from observed demand.
Adaptive, capacity-aware limits. Instead of static per-client numbers, compute allowances from the current system health. When the backend is healthy, clients may exceed their nominal limits up to a burst ceiling. When latency or error rates rise, allowances shrink, lowest tiers first. This blends rate limiting with load shedding. Stripe's fleet-usage and worker-utilisation shedders, which reserve capacity for critical traffic and shed by priority, are an example of the shedding half. Google's SRE book describes per-customer quotas enforced alongside criticality-based shedding at the backend.
Global quotas across services. Large organisations often run a central quota service. Each client team or product has a quota per shared backend, and backends enforce it. Google's SRE book describes per-client quotas and client-side throttling for shared services. Doorman, an open-source project from Google, distributes capacity leases to clients using a fair-share algorithm. The design pattern is consistent: a central allocator computes shares from demand and weights, and enforcement points, whether gateways or clients, hold time-limited leases. If the allocator fails, the last lease continues until it expires, which is a built-in fail-safe.
When to bother. Most systems never need these refinements. Static tiers plus load shedding work well. Adaptive and fair-share schemes pay off when expensive shared infrastructure is shared by many internal or external tenants with bursty demand: analytics clusters, model inference fleets, shared storage. There, idle capacity is costly, and fairness disputes are common.
Key Takeaways#
- Rate limiting protects capacity, stops abuse, controls cost, enforces plans, and shares resources fairly. Pair it with load shedding, which protects the server regardless of who is asking.
- Enforce at the gateway for most limits, with edge limits for floods, service limits for business rules such as login failures, and outbound limits for partner quotas. In-process counters alone are wrong across a fleet.
- Identify clients by user ID, API key or IP prefix, often several at once, and enforce the most restrictive rule. Trust forwarded IP headers only from your own proxies.
- Token bucket is the default for API limits (bursts up to b, sustained rate r, at most b + r·t admitted in any window of length t). Fixed windows suit quotas, sliding logs suit low, high-stakes limits, sliding window counters give cheap near-exact limits, and leaky bucket queues shape output.
- Shared counters live in Redis, updated by one atomic Lua script per check. Shard by client key with Redis Cluster, and handle hot keys with client pacing, leasing, blocklists and edge protection.
- Decide the limiter's failure mode in advance. Degrading to local limits usually beats both pure fail-open and pure fail-closed.
- Reject with 429 plus
Retry-Afterand rate-limit headers, and include the headers on successful responses too. - Tiered limits combine per-plan rates, bursts, quotas and concurrency, plus reserved capacity for critical requests. Manage rules as data, with shadow mode and fast push distribution.