Rate Limiting, Throttling and Quota Management Questions
Protecting API capacity and enforcing fair use: rate-limiting algorithms (token bucket, leaky bucket, fixed/sliding window), per-client, per-tenant and hierarchical quotas, throttling responses (429 semantics, Retry-After, limit headers), and tiered plan enforcement. Covers where to enforce limits (gateway vs. service), distributed counters, concurrency limits, client retry with backoff and jitter, and backpressure, load shedding and graceful degradation under load. Excludes gateway configuration generally, API versioning, authentication mechanics, cache design, and billing and payment pipelines.
Differentiate API throttling (rate limits) from concurrency limits (max simultaneous requests). Describe server-side enforcement techniques for both and client-side strategies to handle limit responses such as exponential backoff, jitter, queueing, and circuit breakers.
Sample Answer
The idea in plain words
A rate limit (throttling) caps how many requests start per unit of time, for example 100 per second. A concurrency limit caps how many requests are in progress at the same instant, for example 20. They look alike but protect different things. A rate limit protects against volume over time. A concurrency limit protects against slowness: a few slow requests can fill every worker even when the rate is low. The link between them is Little's law: the average number in flight equals the arrival rate times the average time each request takes,
L=λ×W
where L is requests in flight, λ is requests per second, W is seconds per request.
Worked example: why a rate limit alone is not enough
Assume a rate limit of λ=100 requests per second.
- Healthy backend, W=0.05 s (50 ms): L=100×0.05=5 requests in flight.
- The database slows, W=2 s: still within the rate limit, but L=100×2=200 in flight. Threads, connections and memory fill up, and the slowness spreads.
Now add a concurrency limit of 20 in flight:
- At 50 ms the ceiling on throughput is 20/0.05=400 requests per second, so the 100 per second rate limit is what binds and nobody notices the concurrency limit.
- At 2 s the ceiling is 20/2=10 requests per second. The server sheds the excess and stays alive instead of collapsing. The concurrency limit adapts to latency automatically; the rate limit does not.
Rule of thumb: a rate limit answers "is this caller asking too often", a concurrency limit answers "can I afford another request right now".
Server-side enforcement
For rate limits: a token bucket (a counter of allowances: capacity B for bursts, refilled at r per second, one spent per request) or a sliding-window counter (a count of requests in the last N seconds, estimated from the previous and current time slots), keyed by API key or user, held in memory on one node or in a shared store like Redis (an in-memory data store that several servers can all read and update) for several nodes. Rejection is HTTP 429 with a Retry-After header.
For concurrency limits:
- A counter or semaphore (a counter that blocks or refuses at a maximum): increment on arrival, refuse if it would exceed the limit, decrement in a
finallyblock (code that runs whether the request succeeded or raised an error) when the request ends, however it ends. - Optionally a short bounded queue for the excess: wait up to a deadline, then reject. An unbounded queue just moves the overload to memory and adds latency to everyone.
- In a distributed setting (several nodes sharing one limit), a distributed counter must survive crashes: a node that dies mid-request never decrements, so each increment needs an expiry (a lease: a claim that disappears on its own after a fixed time unless renewed) or a heartbeat (a periodic "still alive" signal; when it stops, the slot is reclaimed), otherwise the counter leaks until nothing is admitted. Trace with an assumed shared limit of 20: the counter starts at 0, node A admits 5 requests (counter 5) and crashes. Without an expiry the counter stays at 5, so the real limit is now 15. Four such crashes leave 4×5=20, equal to the limit, so every new request is refused although no work is running. If each slot is stored as its own entry that expires after 30 seconds (an assumption, longer than the slowest legitimate request), each stale entry vanishes when its 30 seconds are up, so at most 30 seconds after the crash the 5 stale entries are gone and the counter returns to 0.
- Per-caller concurrency (so one tenant cannot hold every slot) and a global one (so total work is bounded).
Which status to return: 429 when this caller exceeded its share; 503 (Service Unavailable) when the whole server is overloaded regardless of who is asking. Both may carry Retry-After.
Client-side strategies (four)
- Queueing: the client keeps a bounded queue and its own concurrency cap so it never fires a burst the server will reject. Cheap and avoids many 429s.
- Exponential backoff with jitter: after a failure, wait a randomised, growing time before retrying. Backoff means the waits double; jitter means randomising them so a thousand clients that failed together do not retry together. Full jitter: wait random(0,min(cap,base×2attempt)). With base 0.5 s and cap 8 s the ceilings for attempts 0 to 5 are 0.5, 1, 2, 4, 8, 8 seconds (attempt 5 would be 16 but the cap holds it at 8). Their sum is 23.5 s, so the worst case if all six retries fail is 23.5 s of waiting; with full jitter the average is about half that.
- Honour
Retry-After: if the server says 22 seconds, wait at least 22 seconds. The server knows its state; the client's formula does not. - Circuit breaker: after, say, 5 consecutive failures, stop sending for a cool-down (open), then let one probe through (half-open), and close only on success. This keeps a client from adding load to a struggling server.
Backoff with jitter and honouring Retry-After cover what every client meets, a rejected request; queueing, the breaker and the budget are extra layers on top of them.
Also cap retries with a retry budget: retries may be at most about 10% of first attempts (an assumption to tune), so a bad minute does not triple the traffic.
Retry only idempotent requests (safe to repeat with the same result: GET, PUT, DELETE), or POSTs carrying an idempotency key.
Picking the number, and making it adapt
To choose a concurrency limit, start from Little's law with a target rate and the healthy latency. For a target of 100 requests per second at 50 ms, L=100×0.05=5 in flight on average; allow headroom for variation, for example 4 times that, which gives the 20 used above, then raise the limit only while measured latency stays flat and lower it when latency climbs. To make a client's cap adapt, use additive increase and multiplicative decrease (AIMD): add 1 to the cap after each batch of successful calls and halve it after a 429 or a timeout. Illustrative run: cap 20, a 429 arrives and the cap becomes 10; ten clean batches later it is back to 20. The cap therefore follows what the server can currently take instead of a fixed guess.
Common mistakes
Setting only a rate limit and being surprised by a slowdown outage; a concurrency counter with no release on error; retries without jitter, which turn into a synchronised storm; backing off by a formula while ignoring Retry-After.
Design throttling and quota enforcement for different subscription tiers (free, pro, enterprise) so higher tiers get higher throughput and burst capacity while preventing abuse. Discuss where enforcement happens (API gateway vs service), storing counters or tokens, metering, overage handling, and reporting to customers.
Sample Answer
The idea in plain words
Two different limits are needed, and tiers set both. A rate limit caps speed (requests per second) and protects the system from spikes; a quota caps volume over a long period (requests per month) and protects the business model. A burst is how many requests may arrive at once before the rate limit bites. Free, pro and enterprise differ in all three numbers. When a limit is hit, the API answers with HTTP status 429 Too Many Requests (the standard "slow down" status) and usually a Retry-After header, which tells the client how many seconds to wait before trying again. A third dimension, cost, matters when some calls are far more expensive than others (an AI model call versus a metadata read): count the quota in cost units, not in raw requests.
My recommendation: the API gateway (the front door that authenticates and applies policies to every request) enforces the cheap, uniform checks early: identify the key, look up its plan, apply the per-key rate limit and the quota check. The service enforces anything that needs knowledge of the work: per-endpoint cost, concurrency caps for expensive operations and priority shedding. Counters live in a shared low-latency store (Redis-style: an in-memory key-value database), while the authoritative usage record for billing and customer reports lives in a durable metering pipeline (the flow that records every billable request as an event, stores it durably and totals it for invoices and dashboards).
Start with the plan table, the gateway checks and the counters; overage handling, abuse controls, reporting and failure modes build on them.
Plan table (assumed numbers for illustration)
| Free | Pro | Enterprise | |
|---|---|---|---|
| Sustained rate | 5 requests/s | 50 requests/s | 500 requests/s |
| Burst (bucket size) | 10 | 200 | 2,000 |
| Monthly quota | 10,000 | 5,000,000 | 200,000,000 (committed) |
| At quota exhaustion | Hard stop, 429 | Overage billed | Alert people, no automatic cut |
| Priority under overload | Lowest | Middle | Highest |
Units in the table: rates are per second, burst is a count of requests, quotas are per 30-day month, and cost units (below) are a weight per call. "Committed" means the customer has contractually agreed to pay for that volume whether or not they use it. The two limits answer different questions, and the arithmetic shows why you need both. A 30-day month has 30 x 86,400 = 2,592,000 seconds. A Free key running at its full 5 requests/s for the month would make 5 x 2,592,000 = 12,960,000 requests, far above its 10,000 quota; the quota is what binds, and the key reaches it after 10,000 / 5 = 2,000 seconds (about 33 minutes) of flat-out use. Pro reaches 5,000,000 after 5,000,000 / 50 = 100,000 seconds (about 27.8 hours). Enterprise reaches 200,000,000 after 200,000,000 / 500 = 400,000 seconds (about 4.6 days). Without the rate limit, a Pro customer could also send all 5,000,000 in a few minutes, which the system may not survive even though the quota allows it.
Enforcement: where and how
Gateway (every request):
- Authenticate the API key and resolve it to an account and plan (cached for a short time, such as 60 seconds, so plan changes take effect quickly).
- Rate check with a token bucket per key. A token bucket is a counter of tokens that refills at a fixed speed up to a maximum: each request takes one token, an empty bucket means refusal, the maximum (capacity) is the burst and the refill speed is the sustained rate. Here capacity = burst and refill = sustained rate. Free: a key sending 12 requests at the same instant gets the first 10 through and 2 refused; the next token arrives after 1 / 5 = 0.2 seconds, and since
Retry-Aftertakes whole seconds the response saysRetry-After: 1. - Quota check against the period counter.
- Emit a usage event.
Service (where cost is known):
- Weighted cost: a standard call costs 1 unit and an expensive-model call costs 20 (assumed). The monthly quota is counted in these units, so 10,000 Free units allow only 10,000 / 20 = 500 expensive calls, which protects the costly resource from a cheap-looking quota. The gateway bucket in step 2 counts requests, not units, because its job is to shield the gateway from spikes; charging a 20-unit call against a Free bucket of capacity 10 would mean a Free key could never make one. To limit how fast expensive calls arrive, use the concurrency cap below or a second, smaller bucket on that endpoint.
- A concurrency cap per account for expensive operations (requests in flight at once), because rate alone does not bound load when each call is slow.
Counters and storage.
- Rate state: one small record per key, updated by one atomic operation (one step that no other request can interleave with: in Redis, a small Lua script, which Redis runs as a single uninterrupted unit, or a single built-in atomic command) so two gateway nodes never read stale state. Cost: a network round trip per request. To cut it, each node can hold a local bucket for the key and reconcile with the shared store periodically, accepting a small overshoot.
- Quota state: a counter per
(account, period), for example the keyquota:acct42:2025-06, incremented atomically. If each gateway node counts locally and flushes (sends its accumulated count to the shared counter) once per second, the other nodes cannot see that last second of traffic. The rate limit lets a Free key through at most its burst plus one second of refill in any second, 10 + 5 = 15 requests, so the count that is not yet visible to the other nodes is bounded by about 15 requests, which is 0.15 percent of a 10,000 quota and acceptable. A node that crashes before its flush loses at most the same amount. Enterprise commits are billed from the durable record, not from the fast counter. - Quota reset. Put the period in the key (calendar month in UTC, or the account's anniversary day, decided in the contract). A new month is a new key, the old key expires after a few days, and nothing needs a midnight job that could fail. State the reset instant in every response so customers are not surprised.
- Metering. Each request writes an event (
account,key,endpoint,cost,status, time) to a queue and from there to durable storage and analytics. Billing and dashboards read this ledger; the fast counters can be rebuilt from it if Redis loses state.
Overage and abuse
- Free: hard stop with 429 and a quota-specific error type, plus an upgrade link in the body.
- Pro: allow overage and bill it. With an assumed overage price of 2 dollars per 1,000 requests, 5,200,000 requests in a month is 200,000 over, which is 200,000 / 1,000 x 2 = 400 dollars. Offer a spend cap the customer sets themselves, because surprise bills cause disputes.
- Enterprise: alert the account owner at 80 percent and 100 percent of the commit and let a human decide; cutting off a contracted customer automatically is usually a worse failure than the overage.
- Noisy neighbour (one tenant's traffic slowing everyone else down on shared capacity): per-key limits stop one key, but a customer can create many keys, so also apply the limit per account, and keep a per-account concurrency cap. Behind that, protect shared capacity with load shedding (deliberately refusing some work so the rest still succeeds): when the system is overloaded, reject the lowest priority tier first and reserve a floor of capacity for Enterprise, so a Free flood cannot starve it.
- Penalties: a client that keeps hammering after 429s ignores
Retry-After. Escalate: after, say, 10 refused requests within a minute, block the key for 1 minute, then 5, then 15, and log it. Keep the penalty short and automatic to avoid locking out a legitimate integration with a bug. - Account farming (many free signups to get many free quotas): per-IP signup limits, email verification and a per-organisation view.
Reporting to customers
- Headers on every response: the limit, what remains and when it resets (the
X-RateLimit-*convention), so clients can pace themselves. - A usage endpoint and a dashboard showing quota used and remaining, the reset date, requests per endpoint, and the count of 429s, read from the metering ledger (it may lag a few minutes, which the dashboard should say).
- Email alerts at 80 and 100 percent of quota.
- Self-service upgrade: changing the plan updates the account record; the gateway's plan cache expires within its 60-second time to live (TTL: how long a cached entry is kept before it must be looked up again), and the new burst and rate apply on the next bucket refresh. Decide whether to keep the current month's used count (usually yes) and grant the new quota pro-rated or in full.
Failure modes and what would change the design
- The counter store is down. Decide per tier between fail open (when the check cannot run, allow the request) and fail closed (refuse it). Fail open for paid tiers (allow, rely on the ledger for billing) and keep a coarse local limit so a store outage does not become an unlimited-traffic outage; failing closed for everyone would turn a limiter outage into a full API outage.
- Plan lookup is stale. A downgrade can take up to the 60-second cache time to apply, which is acceptable; state it.
- If every call costs about the same and there is one region, a plain gateway bucket plus a monthly counter is enough and the service-level cost layer can be dropped.
- If the product is multi-region, a single global monthly counter becomes a cross-region hot spot (one key that every region updates, so it is slow and contended); allocate each region a share of the quota and rebalance, or count regionally and reconcile in the ledger.
Common mistakes
- Using one number for both rate and quota.
- Counting every request as 1 unit when one endpoint is 20 times the cost.
- Resetting quotas with a cron job that can silently miss.
- Letting each key, not each account, carry the limit.
- Billing from the fast counter instead of the durable ledger.
- Returning a bare 429 without a reason or reset time.
Your API sees very bursty traffic from millions of keys. You are choosing between an exact sliding window log, a weighted two-window counter and a bucket-based limiter. Compare accuracy, burst behaviour and memory per key, and explain how a sliding window can be approximated cheaply in a distributed setting and how large the error is.
Sample Answer
The idea in plain words
All three limiters answer "has this key used up its allowance?", but they remember different amounts about the past. A sliding window log remembers the timestamp of every recent request, so it can answer exactly for any rolling interval. A weighted two-window counter (often called a sliding window counter) remembers only how many requests fell in the current and the previous fixed window and guesses how many of the previous ones still count. A bucket (token bucket) remembers a token count and a last-update time, and enforces a rate with a bounded burst rather than a count in a rolling window. The insight: you are trading memory against exactness of the rolling-window guarantee, and with millions of keys memory decides. For a rolling "L per W seconds" rule, I would use the weighted counter; for a "protect the backend, allow a controlled burst" rule, a token bucket; I would keep the exact log only for tiny limits on high-value keys, such as 5 login attempts per minute. The comparison table and the weighted counter's error bound are the core; the finer-slice variant and the distributed notes extend them.
Compare on three axes
Assume a limit of L = 100 requests per window of W = 60 seconds, 10 million active keys, 8 bytes per timestamp, 8 bytes per counter or token value. These are payload figures only; a real store adds per-key overhead (key string, pointers, expiry), so treat them as lower bounds for comparing the designs.
| Sliding window log | Weighted two-window counter | Token bucket | |
|---|---|---|---|
| State per key | Up to L timestamps | 2 counters + window index | tokens + last-update time |
| Payload per key | 100 x 8 = 800 bytes | about 3 x 8 = 24 bytes | 2 x 8 = 16 bytes |
| For 10M keys | 10,000,000 x 800 = 8,000,000,000 bytes (8 GB) | 10,000,000 x 24 = 240 MB | 10,000,000 x 16 = 160 MB |
| Work per request | Drop old timestamps, count, append: grows with L | Two reads and one increment: constant | Arithmetic on two numbers: constant |
| Accuracy of "L in any W" | Exact | Approximate (see below) | Different guarantee (below) |
| Burst behaviour | A burst of L may go in at once, then nothing until the oldest ages out | Smooths the fixed-window edge, imperfectly | Burst up to capacity C, then the refill rate; tunable independently |
Token bucket guarantee. With capacity C and refill rate r tokens per second, over any interval of T seconds it admits at most C + r x T requests. To mimic 100 per minute, r = 100 / 60 per second. With C = 100 that is up to 100 + 100 = 200 in some 60-second span; with C = 20 it is 20 + 100 = 120. So the bucket does not promise "never more than 100 in a rolling minute"; it promises a long-run rate plus a burst you choose. That is often what a backend wants, but it is a different promise than the other two make.
The weighted counter and how large its error is
Number the windows 0,1,2,… of length W. At time t in window n, let e=t−nW be the seconds elapsed in the current window and f=e/W the fraction elapsed. Let p be the previous window's count and c the current window's count so far. The estimate of requests in the last W seconds is
N^=p⋅(1−f)+cand the request is allowed if N^<L (then c is incremented). The idea: the sliding window (last W seconds) overlaps the previous window by the fraction 1−f, so count that fraction of its requests, assuming they were spread evenly across that window. The error comes entirely from that assumption. The true number of previous-window requests still inside the sliding window is somewhere from 0 to p, while the estimate uses p(1−f). So the error is bounded: the estimate can be too low by at most f⋅p and too high by at most (1−f)⋅p.
Interval notation used below: (15,75] means "after second 15, up to and including second 75" (the round bracket leaves the endpoint out, the square bracket keeps it). A timeline for case 2: window 0 covers seconds 0 to 60 and holds the burst; window 1 covers 60 to 120 and the clock reads 75, which is 15 seconds into it. The true last-60-seconds window looks back only to second 15, so the burst is already outside it, yet the estimate still counts the 75% of window 0 that overlaps.
Three worked cases with L = 100, W = 60:
- Even traffic (1 request per second). At t = 90 (window 1, e = 30, f = 0.5), p = 60 and c = 30: estimate 60 x 0.5 + 30 = 60. The true count in the last 60 seconds is also 60. No error.
- Previous burst early in its window. 100 requests arrive at t = 0 to 5 (p = 100). At t = 75 (e = 15, f = 0.25) the sliding window covers (15, 75], which contains none of them, so the true count is c. The estimate is 100 x 0.75 + c = 75 + c, so the limiter refuses once c reaches 25. It wrongly refuses 75 requests (the true count would allow up to 100). Over-refusal of up to (1−f)p = 75.
- Previous burst late in its window. 100 requests arrive at t = 55 to 59. At t = 110 (e = 50, f = 5/6) the window (50, 110] contains all 100, but the estimate is 100 x (1/6) = 16.67, so 84 more are allowed (each value of c from 0 through 83 gives an estimate below 100, the largest being 16.67 + 83 = 99.67), a total of 100 + 84 = 184 requests inside a 55-second span if the extra requests arrive in one burst after the first 100. The bound f⋅p is 83.3; the count is 84 because c takes the values 0 to 83, and counting starts at 0.
The program below replays cases 2 and 3 with a sliding window log as the exact reference and the weighted counter (exact fractions, so no rounding), each facing 100 attempts at the stated moment.
from fractions import Fraction
L, W = 100, 60 # limit and window length in seconds
def exact_log_allows(times, now, attempts):
"""Sliding window log: count the requests in the interval (now - W, now]."""
live = sum(1 for t in times if now - W < t <= now)
return max(0, min(attempts, L - live))
def weighted_counter_allows(times, now, attempts):
"""Weighted two-window counter: previous window's count weighted by the overlap."""
window = now // W
elapsed = now - window * W
prev = sum(1 for t in times if (window - 1) * W <= t < window * W)
curr = sum(1 for t in times if window * W <= t <= now)
allowed = 0
for _ in range(attempts):
estimate = Fraction(prev * (W - elapsed), W) + curr + allowed
if estimate < L:
allowed += 1
return allowed
case_2 = [i % 6 for i in range(100)] # 100 requests at t = 0..5
case_3 = [55 + i % 5 for i in range(100)] # 100 requests at t = 55..59
for name, times, now in (("case 2, attempts at t=75", case_2, 75),
("case 3, attempts at t=110", case_3, 110)):
log = exact_log_allows(times, now, 100)
counter = weighted_counter_allows(times, now, 100)
print(f"{name}: exact log allows {log}, weighted counter allows {counter}, "
f"difference {counter - log:+d}")
Output:
case 2, attempts at t=75: exact log allows 100, weighted counter allows 25, difference -75
case 3, attempts at t=110: exact log allows 0, weighted counter allows 84, difference +84
Case 2 reproduces the 75 wrongly refused requests and case 3 the 84 wrongly admitted ones.
Tally of allowed requests in cases 2 and 3, assuming 100 further attempts arrive at the moment given. Case 2 at t = 75: an exact log sees an empty window and allows all 100 (200 in total over the two bursts); the counter allows only 25, because the estimate 75 + c reaches 100 at c = 25 (125 in total). Case 3 at t = 110: an exact log sees 100 requests in the window and allows none (100 in total); the counter allows 84 (184 in total). So the worst-case error is on the order of the full limit L, not a few percent, and it appears exactly when traffic inside a window is bunched. For smooth traffic (case 1) the error is near zero. For the very bursty traffic in the question, assume the approximation is loose and decide whether that matters.
Ways to shrink it: use finer slices (for example six 10-second slices, summing them with the oldest slice weighted by its overlap), so only the single edge slice is guessed; the error is then bounded by what one slice holds, at the cost of 6 counters instead of 2 (6 x 8 = 48 bytes payload). Or set the limit lower and add a token bucket for the burst.
Doing it cheaply in a distributed setting
Store one counter per (client, window index), for example rl:{client42}:1234. A script (Redis can run a small Lua program as one uninterrupted step, so no other request can slip in between its reads and writes: that is what "atomically" means) does: read previous and current counts, compute N^, and if allowed increment the current counter and set its expiry (a time after which the store deletes the key by itself) to 2W so old windows disappear. One round trip, no timestamps stored. A shard is one server holding a slice of the keys. In a clustered store, braces in a key name (a "hash tag") tell it to hash only the text inside them: {client42} makes the previous and current keys hash on the client part, so they land on the same shard and one script can touch both. Clock skew (two machines' clocks disagreeing by a little) between nodes shifts window boundaries by the skew, so a request near a boundary can be counted in the neighbouring window; read the time from the store inside the script so every node uses one clock.
Recommendation and failure modes
For millions of keys with bursty traffic, I would run a token bucket at the edge for protection (small state, constant work, explicit burst) and add the weighted counter only where the product must state "L per rolling minute" to customers, accepting and documenting the approximation. I would use the exact log only where the limit is small (5 timestamps = 40 bytes) and exactness matters, such as login attempts. What would flip the choice: a contract that requires a provable maximum in any window (use the log, or a bucket with capacity small enough that C + r x T meets the cap), or memory so abundant that 8 GB is no concern.
Running the code
python window_error.py
Python 3.12, standard library only (fractions); the inputs are fixed, so the output is identical on every run.
Common mistakes: calling the weighted counter "99.x percent accurate" without saying for which traffic shape; comparing log memory per key using the average instead of the limit L; forgetting that the bucket's guarantee is C + r x T, not L per window.
Design a sliding-window rate limiter that can be implemented using Redis. Describe the data structure, required Redis commands (ZADD, ZREMRANGEBYSCORE, ZCOUNT), and a Lua script to make checks atomic. Explain how to bound memory usage, eviction policy, and performance considerations when windows are small or clients are numerous.
Sample Answer
The idea in plain words
A sliding window limiter allows at most L requests in the last W milliseconds, counted back from now, not from a clock boundary. The exact way to do it is a log: remember the timestamp of every allowed request, throw away the ones older than W, and count the rest. Redis fits this because a sorted set (a collection where each member has a numeric score and members are kept ordered by score) can hold the timestamps as scores. The one thing that goes wrong without care is a race: two app servers both read "4 used out of 5", both add a request, and 6 get through. A Lua script runs inside Redis as one uninterrupted step (no other command runs in the middle), which makes check-and-add atomic.
Data structure and commands
The core is one sorted set per client, trimmed, counted and appended to inside one script. The memory-encoding and eviction notes further down are a deeper dive on cost.
- Key: one sorted set per client, for example
rl:client42. - Score: the request time in milliseconds.
- Member: a unique id for the request. It must be unique: sorted-set members are unique, so two requests with the same member in the same millisecond would collapse into one entry and be undercounted. Use a request id or
nowplus a sequence number. ZREMRANGEBYSCORE key -inf (now - W)deletes entries whose score is at or before the window start, which keeps memory bounded.-infand+infmean minus and plus infinity, that is, no lower or no upper bound.ZCOUNT key (now-W +infcounts the entries still inside the window(now - W, now]. The(makes the lower bound exclusive.ZADD key now idrecords an allowed request.PEXPIRE key W(set a time to live, TTL, in milliseconds) makes an idle client's key delete itself W milliseconds after its last allowed request, when every entry in it has aged out.ZRANGE key 0 0 WITHSCORESreads the oldest entry, which tells a denied client when room appears:oldest + W - nowmilliseconds, the value for theRetry-Afterheader after conversion to seconds. That header is sent with the HTTP status 429 Too Many Requests (the standard "slow down" reply) and tells the client how long to wait.
The atomic script
The script returns three numbers: allowed (1 or 0), remaining, and milliseconds until the oldest request leaves the window. Denied requests are not stored, so a client hammering the limiter cannot grow its own set.
-- KEYS[1] = sorted set for one client
-- ARGV[1] = now in ms, ARGV[2] = window in ms, ARGV[3] = limit, ARGV[4] = unique request id
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
-- 1. forget requests at or before the start of the window (now - window, now]
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - window)
-- 2. count what is left
local used = redis.call('ZCOUNT', KEYS[1], '(' .. (now - window), '+inf')
if used < limit then
-- 3a. allowed: record this request and make sure an idle key disappears
redis.call('ZADD', KEYS[1], now, ARGV[4])
redis.call('PEXPIRE', KEYS[1], window)
return {1, limit - used - 1, 0}
end
-- 3b. denied: nothing is stored; the oldest entry decides when room appears
local oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
return {0, 0, tonumber(oldest[2]) + window - now}
The program below is a line-by-line Python translation of the script, run against a small stand-in for a sorted set (it keeps (score, member) pairs in score order and offers only the four operations the script uses; the PEXPIRE step has no counterpart because the stand-in has no clock for key expiry). The Lua itself runs inside Redis; the translation lets you check the logic on its own. It replays a hand-checkable trace (limit 3 per 1000 ms), compares 600 random requests across 3 keys with an independent exact log kept as a plain list of timestamps, and then runs the same comparison on a deliberately wrong variant (used <= limit) to show that the comparison can fail. The time now is supplied as an argument, so the run is deterministic.
import bisect
import random
class SortedSet:
"""Stand-in for the few sorted-set commands the script uses: (score, member) pairs in score order."""
def __init__(self):
self.items = []
def remove_up_to(self, max_score): # ZREMRANGEBYSCORE key -inf max_score
self.items = [e for e in self.items if e[0] > max_score]
def count_above(self, min_exclusive): # ZCOUNT key (min_exclusive +inf
return sum(1 for score, _ in self.items if score > min_exclusive)
def add(self, score, member): # ZADD key score member (a member exists once)
self.items = [e for e in self.items if e[1] != member]
bisect.insort(self.items, (score, member))
def oldest_score(self): # ZRANGE key 0 0 WITHSCORES
return self.items[0][0]
def script(zset, now, window, limit, req_id, off_by_one=False):
"""Step for step the Lua script; returns [allowed, remaining, retry_after_ms]."""
zset.remove_up_to(now - window)
used = zset.count_above(now - window)
if used < limit or (off_by_one and used <= limit):
zset.add(now, req_id)
return [1, limit - used - 1, 0]
return [0, 0, zset.oldest_score() + window - now]
class Reference:
"""Independent exact sliding-window log kept in a plain list of timestamps."""
def __init__(self, window, limit):
self.window, self.limit, self.log = window, limit, []
def check(self, now):
self.log = [t for t in self.log if t > now - self.window]
if len(self.log) < self.limit:
self.log.append(now)
return [1, self.limit - len(self.log), 0]
return [0, 0, self.log[0] + self.window - now]
print("limit 3 per 1000 ms: time, [allowed, remaining, retry_after_ms]")
zset, ref = SortedSet(), Reference(1000, 3)
for i, t in enumerate([0, 100, 200, 300, 999, 1000, 1050, 1100, 1999, 2100]):
got = script(zset, t, 1000, 3, "r%d" % i)
assert got == ref.check(t), (t, got)
print(t, got)
for label, wrong in (("correct script", False), ("used <= limit variant", True)):
rng = random.Random(11)
zsets = {k: SortedSet() for k in "abc"}
refs = {k: Reference(1000, 5) for k in "abc"}
t = mismatches = peak = 0
for i in range(600):
t += rng.choice([0, 0, 10, 50, 200, 400])
k = rng.choice("abc")
mismatches += script(zsets[k], t, 1000, 5, "q%d" % i, wrong) != refs[k].check(t)
peak = max(peak, len(zsets[k].items))
print(f"{label}: 600 requests, 3 keys, mismatches vs reference: {mismatches}, "
f"largest set: {peak} (limit 5)")
Output:
limit 3 per 1000 ms: time, [allowed, remaining, retry_after_ms]
0 [1, 2, 0]
100 [1, 1, 0]
200 [1, 0, 0]
300 [0, 0, 700]
999 [0, 0, 1]
1000 [1, 0, 0]
1050 [0, 0, 50]
1100 [1, 0, 0]
1999 [1, 0, 0]
2100 [1, 1, 0]
correct script: 600 requests, 3 keys, mismatches vs reference: 0, largest set: 5 (limit 5)
used <= limit variant: 600 requests, 3 keys, mismatches vs reference: 113, largest set: 6 (limit 5)
Reading the output
- At t = 300 the three entries at 0, 100 and 200 are inside the window, so the request is denied with 0 + 1000 - 300 = 700 ms to wait, matching the first column of the reply. At t = 999 the oldest entry (0) is 999 ms old, still inside the window
(-1, 999], so the wait is 0 + 1000 - 999 = 1 ms. At t = 1000 the entry at 0 is exactly W old and is removed (the window is(0, 1000]), so the request is allowed. - At t = 1050 the entries are 100, 200 and 1000, three in the window: denied, wait 100 + 1000 - 1050 = 50 ms. At t = 1100 the entry at 100 is removed, so the request is allowed.
- Across 600 random requests on 3 keys the translated script and the reference disagreed 0 times, and no set ever exceeded its limit of 5. The
used <= limitvariant disagreed on 113 of the 600 requests and let a set reach 6 members (at t = 300 in the walk-through it would allow a fourth request), so the comparison does detect a wrong script. This validates one limit and window shape and supplied timestamps; it says nothing about Redis itself, replication, failover, or two clients with different clocks.
Bounding memory and eviction
- Per-key bound: because denied requests are not stored, a set never holds more than L members. Memory per client is therefore at most about L entries, and the total is clients x L x bytes per entry.
- Bytes per entry is not constant. Redis stores a small sorted set in a listpack (one packed array of entries, compact but slow to search when large) and converts it to a skiplist (a layered linked structure plus a hash table, fast for any size but with more bookkeeping per member) when it grows past
zset-max-listpack-entriesor holds a member longer thanzset-max-listpack-value. The Redis documentation gives defaults of 128 entries and 64 bytes from Redis 7.0 (the older names useziplist), and says the compact encodings use up to 10 times less memory, about 5 times on average. Memory is therefore not simply L x a constant: a limit just above the threshold can cost several times more per member. RunOBJECT ENCODING keyandMEMORY USAGE keyon your server version, with your member id length, before sizing. - TTL:
PEXPIREensures idle clients vanish without a cleanup job. - Eviction policy: set a memory ceiling (
maxmemory) and use a policy that only evicts keys with a TTL:volatile-ttlevicts the keys closest to expiring,volatile-lruthe least recently used ones. Here every limiter key has a TTL. Be clear about the cost: if Redis evicts an active client's set, that client's history is gone and it receives a fresh allowance, the same effect as forgetting a bucket that is not full. Size memory so eviction does not happen (a count of evicted keys above 0 is an alert), and decide whether the limiter should fail open (allow requests when it cannot check) or fail closed (refuse them) if memory is exhausted and writes fail.
Performance when windows are small or clients numerous
- Each check costs a round trip plus roughly logarithmic work in the set size, plus the number of entries removed. Removal is amortised (the cost averaged over many calls): each entry is added once and removed once, so the removals cost no more than the adds.
- Small windows with high limits (say 1 second and 1,000 requests) mean large sets, the skiplist encoding, and heavy per-request memory writes. For those, use a counter-based approximation (a weighted two-window counter, or a token bucket with 2 numbers per key) and keep the exact log for small limits where exactness matters, such as login attempts.
- Many clients: the work is per key, so keys spread across a Redis Cluster. This script touches one key, so it is cluster-safe (works on a Redis Cluster, where every key a script touches must live in the same hash slot) without hash tags, the
{...}parts of key names that force related keys together. Avoid one globally shared key, which would put every request on one shard. - Time source: passing
nowfrom the application means two application servers with different clocks disagree about the window. Inside the script, read the time from Redis instead (redis.call('TIME')returns seconds and microseconds; since Redis 5.0 scripts replicate by their effects, so the Redis documentation allows callingTIMEanywhere in a script) so all clients share one clock. - The script trims on every call and then counts with
ZCOUNT. The count would still be right without the trim, becauseZCOUNTonly counts entries inside the window, so trimming less often is possible at the price of larger sets; trimming every call is simplest and bounds memory strictly.
Running the code
python sliding_log_model.py
Python 3.12, standard library only (bisect, random); the trace and the random seed are fixed, so the output is identical on every run.
Common mistakes
- Doing
ZCOUNTthenZADDas two separate commands from the app (a race). - Using the timestamp itself as the member, which collapses same-millisecond requests.
- Storing denied requests too, so a flood inflates the set and keeps extending the block.
- Forgetting
PEXPIRE, leaving a key per client forever. - Treating the memory per request as constant.
Describe the token bucket rate limiting algorithm: explain the key parameters (capacity and refill rate), how it enforces throughput while allowing bursts, and how it differs behaviorally from leaky bucket and fixed-window approaches. Provide a short example of when token bucket is preferable.
Sample Answer
The idea in plain words
Rate limiting means capping how many requests a caller may make over time so one caller cannot starve the others (use up the shared capacity until the rest get little or none of it). A token bucket does this with a simple picture: a bucket holds tokens, every request must take a token out, and tokens drip back in at a fixed speed. If the bucket is empty the request is refused (an HTTP API answers 429 Too Many Requests). The bucket's size allows a burst (many requests at once), and the drip speed fixes the long-run average. That pairing, "short spikes are fine, the average is capped", is why the algorithm is so common.
The two parameters and the formula
- Capacity B: the most tokens the bucket can hold. It is the largest burst a caller can send after being idle.
- Refill rate r: tokens added per second. It is the sustained throughput (steady requests per second the caller can keep up forever).
State per caller is just two numbers: tokens and last (the time of the last update). Nothing runs on a timer. On each request the limiter refills lazily ("lazy refill" means computing the refill when a request arrives instead of adding tokens every tick):
tokens_now = min(B, tokens_before + (now - last) * r)
if tokens_now >= cost: tokens_now = tokens_now - cost, allow
else: deny
last = now
cost is 1 for a plain request and can be larger for expensive calls. Two consequences follow. In any interval of T seconds starting from a full bucket, at most B + r*T tokens can be spent. And an empty bucket needs B / r seconds to refill completely.
Worked trace (assumed numbers: B = 10, r = 2 tokens per second)
- At t = 0 the bucket is full with 10 tokens. Ten requests arrive in the same instant: all ten are allowed, tokens drop to 0. An eleventh at t = 0 is denied.
- At t = 1.5 s the bucket holds 0 + 1.5 * 2 = 3 tokens. Three requests are allowed and a fourth is denied.
- The caller then goes quiet. After 10 idle seconds the formula gives min(10, 0 + 10 * 2) = min(10, 20) = 10: the bucket is back to full, never above B.
- Over any 60 seconds starting from a full bucket the caller can spend at most 10 + 2 * 60 = 130 tokens, and the steady rate is 2 * 60 = 120 per minute. The extra 10 is the burst allowance.
Full refill from empty takes B / r = 10 / 2 = 5 seconds.
How it differs from leaky bucket and fixed window
Take the same limit in all three, an average of 2 requests per second.
| Algorithm | What it does with a burst of 10 arriving at once | Behaviour at a boundary |
|---|---|---|
| Token bucket (B = 10, r = 2) | Serves all 10 immediately, then refuses until tokens return | Cannot exceed B + r*T in any interval |
| Leaky bucket as a queue (holds 10 waiting requests, one leaves every 0.5 s) | Accepts them but releases them at 0.5, 1.0, ..., 5.0 s, so the last waits 5.0 s; extra arrivals while the queue is full are dropped | Output is smooth at 2 per second |
| Fixed window (20 requests per 10 s window, counter resets each window) | Serves them if the window has room | Up to 2x the limit across a window edge |
The fixed-window edge case with numbers: 20 requests at t = 9.9 s fill the first window (counter 20 of 20), then the counter resets at t = 10 s and 20 more at t = 10.1 s are allowed. That is 40 requests in 0.2 s while the stated limit is 20 per 10 s. The token bucket under the same pattern allows at most B + r*T = 10 + 2 * 0.2 = 10.4 tokens in that 0.2 s, so 10 whole requests.
The behavioural summary: token bucket lets bursts through at full speed and caps the average; leaky bucket (queue form) removes bursts by delaying them and adds waiting time; fixed window is the cheapest (one counter) but lets a double burst through at the edge.
Per-tenant quotas and state that expires by itself
Different plans are just different (B, r) pairs, for example a free plan with B = 20, r = 1 per second and a paid plan with B = 200, r = 10 per second (assumed plans). The key is the tenant or API key.
You do not need a central database of every tenant's bucket or a cleanup job. A bucket that has been idle for B / r seconds is full again, and a missing bucket is created full, so deleting an idle bucket changes nothing a caller can observe. So store (tokens, last) under the key with a time-to-live (TTL, an automatic expiry) of about B / r seconds after each update: 20 / 1 = 20 s for the free plan and 200 / 10 = 20 s for the paid one. An in-process map with eviction of full buckets does the same job. This equivalence holds only if new keys start full; if you want new keys to start empty, the TTL trick no longer applies.
When to prefer token bucket
Choose it when clients are naturally bursty but bounded: a browser page that fires 8 parallel API calls on load and then sits idle for a minute is the standard case. With B = 10 and r = 2 the page loads at full speed, and a script hammering the API is held to 2 per second. Fixed window would punish an unlucky page load that lands just after a counter fills; a leaky-bucket queue would make the page wait for its own calls. Prefer a leaky bucket when a fragile downstream (a legacy system that can only take 2 calls per second, with no tolerance for spikes) needs perfectly even input.
Common mistakes
- Confusing capacity with rate: B = 10 does not mean 10 per second, it means 10 stored at most.
- Forgetting the cap
min(B, ...), so a long-idle caller accumulates an unbounded burst. - Using wall-clock time that can jump backwards (when an administrator or time-sync service sets the date) instead of a monotonic clock, which only ever moves forward and is meant for measuring elapsed time.
- Letting a request with cost larger than B wait forever: it can never succeed, so reject it outright.
Unlock Full Question Bank
Get access to all 39 Rate Limiting, Throttling and Quota Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.