Courses / System Design Interview / Chapter 18
Module 4 · Building Blocks III: Limits, Storage and Search · Chapter 18 of 49
Rate Limiters
Builds on Building Blocks: The Parts Every Design Reuses. Next up: Blob Stores.
Part 1 · Why limit requests, and where
What a rate limiter does
A public API with no limit lets one noisy client slow everyone else, and a login page with no limit lets a script try ten lakh passwords. A rate limiter is the part that says no, early and cheaply.
For each incoming request, a rate limiter decides whether to serve it now or to reject it because the caller has used up its share of some period. The share is the limit, for example 100 requests per minute for each API key. The caller is identified by a key, such as an API key, a user id or an IP address, and every key has its own count. A request over the limit gets an error answer at once, before it reaches the database or any other costly part.
Four reasons to limit come up again and again.
- Fairness. One heavy client must not starve the rest.
- Protection. A client bug that retries in a tight loop, or a deliberate attack, can overload a service that is otherwise healthy.
- Cost. A call to a paid downstream service, or to a language model, costs money every time.
- Abuse. Password guessing, scraping, and sending an OTP to the same stranger's phone again and again.
Rate limiting is easy to confuse with load shedding. A load shedder drops traffic because the whole service is overloaded, whoever sent it. A rate limiter drops traffic because one caller went past its own allowance, even when the service is idle. Stripe's engineering post on its limiters describes both in one system: a request rate limiter for each user, a limiter on concurrent requests, and two load shedders that refuse lower-priority traffic when the fleet is busy.
Throttling is used loosely. In this chapter, to throttle means to slow a caller down, and to reject means to refuse the request. Most limiters reject.
Where the limiter runs
A limiter can sit in three places, and large systems usually use more than one.
| Place | What it can see | Good for | Weak at |
|---|---|---|---|
| In the client | Its own calls only | Being polite, avoiding wasted calls | Cannot be trusted: a hostile client ignores it |
| At the gateway | Every request, before any work is done | One rule for all services, cheap rejection | Knows only the URL, headers and key, not how costly the work is |
| Inside a service | The operation and the tenant | Limits by cost, such as expensive searches | The request has already reached the process |
What it can seeIts own calls only
Good forBeing polite, avoiding wasted calls
Weak atCannot be trusted: a hostile client ignores it
What it can seeEvery request, before any work is done
Good forOne rule for all services, cheap rejection
Weak atKnows only the URL, headers and key, not how costly the work is
What to count
The key decides who shares a limit. Each choice has a cost.
| Key | Strength | Problem |
|---|---|---|
| API key or user id | Matches who is paying or who is responsible | Needs the caller to be identified first |
| IP address | Works before login, for example on a sign-up page | Many phones behind one mobile carrier can share a public address, so one noisy user can block many innocent ones |
| Tenant or account | Protects a shared plan limit | One user inside the tenant can use up everyone's share |
| Endpoint plus key | Lets a cheap read and a costly export have different limits | More keys to store |
Counting requests treats a lookup and a heavy report as equal. A cost-based limiter charges more for expensive calls: a search might take 10 units from the allowance and a lookup 1. The algorithms in the next lessons all support this, because they track an allowance that a request can spend in different amounts.
The answer to a refused request matters as much as the refusal. The standard answer is HTTP status 429, with headers that say when to try again. The last lesson of this chapter builds one.
| Term | Meaning |
|---|---|
| Limit | How many requests a key may make in a period |
| Key | What the count is kept for: user, API key, IP address, tenant |
Part 2 · The token bucket
A bucket of tokens
The token bucket is the most widely used limiting algorithm. Stripe's engineering post says the company uses the token bucket algorithm for its rate limiting and builds its limiters on Redis. The idea fits in three sentences.
Each key has a bucket that holds up to capacity tokens. Tokens are added at a steady rate, for example one per second, until the bucket is full. Every request must take one token, and when the bucket is empty the request is rejected.
The two numbers have separate jobs. The rate is the long-run average the caller may sustain. The capacity is the burst: how many requests may arrive at once after a quiet period. A bucket with rate 1 and capacity 5 allows five requests together, then one a second.
Nobody needs a timer that drops tokens into every bucket. A bucket stores two values, the token count and the time it was last updated. When a request arrives, the limiter works out how many tokens should have been added since then, caps the total at the capacity, and then tries to take one. This lazy refill costs a few arithmetic operations per request and no background work, which is why a single machine can keep many lakhs of buckets.
Watch for the token count on the gateway falling with each request
Read it as steps
The algorithm in code
The class below keeps the token count and the time of the last update. The caller passes in the current time, which keeps the logic easy to test: a trace of timestamps always gives the same answer.
class TokenBucket: def __init__(self, rate, capacity): self.rate, self.capacity = rate, capacity self.tokens, self.last = capacity, 0.0 def allow(self, now): elapsed = now - self.last refill = elapsed * self.rate self.tokens = min(self.capacity, self.tokens + refill) self.last = now if self.tokens >= 1: self.tokens -= 1 return True return False
bucket.py: a token bucket with lazy refill
The first run replays the scene. At time 0 there are eight requests, one second later two, and at four seconds four more. A Y is an allowed request and an n a rejected one. It was run with Python 3.12.10.
import sys from bucket import TokenBucket print(sys.version.split()[0]) b = TokenBucket(rate=1, capacity=5) # 5 tokens, +1 per second for t, n in [(0.0, 8), (1.0, 2), (4.0, 4)]: marks = "".join("Y" if b.allow(t) else "n" for _ in range(n)) print(f"t={t:.1f}s {n} requests {marks:8} " f"tokens left {b.tokens:.1f}")
l2_run.py: replay the burst of the scene
3.12.10 t=0.0s 8 requests YYYYYnnn tokens left 0.0 t=1.0s 2 requests Yn tokens left 0.0 t=4.0s 4 requests YYYn tokens left 0.0
The first line is the burst: five tokens, so five Y and three n. A second later exactly one token has come back, so the pair is Yn. Three seconds after that, three tokens have accumulated, so three of the four requests pass. The token count printed is the count after the whole batch, and it is zero each time because every token was used.
Rate against burst, and the quiz
The second run shows what the two numbers mean over a longer time. The caller sends ten requests a second for twenty seconds, against a bucket with rate 5 and capacity 10.
from bucket import TokenBucket b = TokenBucket(rate=5, capacity=10) # long-run average: 5 a second allowed = 0 for i in range(200): # 10 requests a second for 20 s allowed += b.allow(i * 0.1) print(f"sent 200 in 20 s, allowed {allowed}") print(f"average allowed rate: {allowed / 20:.1f} a second")
l2b_run.py: steady overload against rate 5, capacity 10
sent 200 in 20 s, allowed 109 average allowed rate: 5.5 a second
Of 200 requests, 109 were allowed. Ten came from the full bucket at the start, and the refill supplied about five a second after that: 99 more over the 19.9 seconds before the last request. The average of 5.5 a second is the rate plus the initial burst spread over the period. In a longer run it settles toward 5.
Choosing the numbers is a product decision. A larger capacity is kind to clients that send a page of requests together, but it lets a client spend a lot of backend capacity in one instant. A smaller capacity smooths traffic and may reject honest clients that happen to be bursty. Because all of a bucket's state is two numbers, the bucket is also cheap to keep in a shared store, which the fifth lesson uses.
A bucket has rate 2 a second and capacity 20, and has been idle for an hour. How many requests can arrive at once and be accepted?
- Twenty, because the bucket is full and the capacity is the burst.
- After that, two a second.
Why does the code compute the refill when a request arrives instead of adding tokens on a timer?
- A timer for every key would cost background work for lakhs of idle buckets.
- Computing the refill from the elapsed time gives the same answer with two stored numbers.
In the run, 200 requests were sent in 20 seconds at rate 5 and capacity 10, and 109 were allowed. Where do the 109 come from?
Part 3 · Leaky bucket and fixed window
The leaky bucket
The leaky bucket looks like the token bucket turned around. Requests pour into a bucket and leak out at a fixed rate. If a request arrives when the bucket is full, it overflows and is rejected.
There are two ways to use that picture, and people mix them up. In the queue version the bucket really is a first-in, first-out queue. Requests wait in it and a worker takes one out at the leak rate, so the backend sees a perfectly smooth stream. Full queue means reject. In the meter version nothing waits. The bucket is only a number, the level, that rises by one for each accepted request and falls at the leak rate, and a request is accepted if the level has room.
The nginx documentation for limit_req says the module uses the leaky bucket method. Its rate is the leak rate in requests per second. Its burst is the size of the bucket: excess requests wait until their number goes past burst, and then they are rejected. With nodelay, requests inside the burst are served at once instead of waiting, but they still count against it. The module's default status for a rejected request is 503, and it can be changed with limit_req_status.
The two algorithms differ mainly in what they promise. A token bucket allows a burst and then the average rate. A leaky bucket in its queue form promises that the output never exceeds the rate, so it suits protecting a backend that cannot take bursts, at the cost of delaying requests.
The meter version, written on the next page, is the same arithmetic as the token bucket with the count reversed: tokens left equals capacity minus level. Which name to use is a matter of how you describe the behaviour.
Fixed window counter
The simplest limiter of all is the fixed window counter. Cut time into windows of equal length, for example ten seconds. Keep one counter for each key and window. Add one for every request, reject when the counter reaches the limit, and start from zero in the next window.
It needs one integer per key, and it is easy to build in a shared store: a key made from the user and the window number, incremented on every request and set to expire when the window ends. The Redis documentation for INCR describes this pattern: one counter per client and per second, given an expiry. It also warns that its single-counter variant has a race, a counter left without an expiry if the client fails between the increment and the expiry. The fifth lesson looks at a related race, in a check made before the increment.
It has a well-known flaw at the window edges. The limit is enforced per window, not per any ten seconds. A client that sends its whole allowance at the end of one window and again at the start of the next gets twice the limit through in a very short time.
class LeakyBucket: """The bucket as a meter: it drains at a fixed rate""" def __init__(self, rate, capacity): self.rate, self.capacity = rate, capacity self.level, self.last = 0.0, 0.0 def allow(self, now): drained = (now - self.last) * self.rate self.level = max(0.0, self.level - drained) self.last = now if self.level + 1 <= self.capacity: self.level += 1 return True return False class FixedWindow: def __init__(self, limit, window): self.limit, self.window = limit, window self.count, self.start = 0, 0.0 def allow(self, now): start = now - now % self.window if start != self.start: self.start, self.count = start, 0 if self.count < self.limit: self.count += 1 return True return False
windows.py: the leaky bucket (meter) and the fixed window
Both classes take the time as an argument, like the token bucket. The next lesson adds two more classes to the same file.
The boundary burst, and the quiz
The run below uses a limit of 10 requests per 10 seconds. The client sends 10 requests at time 9.5 and 10 more at time 10.5, one second apart and on either side of the window boundary at 10.
from windows import FixedWindow, LeakyBucket # limit: 10 requests per 10 s; 10 sent at t=9.5 and 10 at t=10.5 trace = [9.5] * 10 + [10.5] * 10 fw = FixedWindow(limit=10, window=10) print("fixed window, burst across the boundary:", sum(fw.allow(t) for t in trace), "of", len(trace), "allowed") lb = LeakyBucket(rate=1, capacity=10) # drains 1 per second print("leaky bucket, same trace:", sum(lb.allow(t) for t in trace), "of", len(trace), "allowed")
l3_run.py: the same trace against two limiters
fixed window, burst across the boundary: 20 of 20 allowed leaky bucket, same trace: 11 of 20 allowed
The fixed window let all 20 through, 20 requests in one second under a limit of ten per ten seconds. The leaky bucket, draining at one per second, accepted the first ten, then only one more after one second of leaking, so 11 in total. The difference is that the bucket remembers recent traffic, while the window forgets everything at the boundary.
The fixed window lets through: 2x the limit (20 requests in a second, from the run)
Read it as steps
Ten requests at the end of one window and ten at the start of the next.
Fixed windows are still a fine choice where the limit is generous and a 2x burst for a moment does no harm, for example a daily quota. When the burst matters, use one of the algorithms of the next lesson.
Part 4 · Sliding windows
Sliding window log
A sliding window limits the number of requests in the last N seconds counted back from now, not in a fixed calendar slot. That removes the boundary burst, because the window moves with each request.
The exact version is the sliding window log. Keep a log of the timestamps of the accepted requests for each key. When a request arrives, remove timestamps older than the window, count what is left, and accept the request only if the count is below the limit. If accepted, add its timestamp.
It is exact, and it has a cost. Memory per key grows with the limit, since the log holds up to one timestamp per allowed request. A key allowed 10 lakh requests per hour would need 10 lakh timestamps. For small limits, such as ten login attempts per hour, this is fine. A rejected request is not recorded, so a client that keeps hammering does not enlarge the log.
class SlidingLog: def __init__(self, limit, window): self.limit, self.window = limit, window self.log = deque() def allow(self, now): while self.log and self.log[0] <= now - self.window: self.log.popleft() if len(self.log) < self.limit: self.log.append(now) return True return False def size(self): return len(self.log)
windows.py: the SlidingLog class (the file imports deque)
Expiry happens from the left of a deque, so each timestamp is added once and removed once, which keeps the work for one request small on average.
Sliding window counter
The sliding window counter is an approximation that keeps only two counters per key: the count in the current fixed window and the count in the previous one. It estimates the sliding window by weighting the previous window by how much of it still overlaps.
Suppose the window is ten seconds, the previous window had 8 requests, and the current window has 3 requests and is 2.5 seconds old. The sliding window reaches back 10 seconds from now, which includes the last 75 percent of the previous window. The estimate is 8 x 0.75 + 3 = 9 requests. A new request is accepted if the estimate plus one stays within the limit.
class SlidingCounter: def __init__(self, limit, window): self.limit, self.window = limit, window self.prev, self.cur, self.start = 0, 0, 0.0 def allow(self, now): start = now - now % self.window if start != self.start: gap = round((start - self.start) / self.window) self.prev = self.cur if gap == 1 else 0 self.cur, self.start = 0, start share = 1 - (now - start) / self.window if self.prev * share + self.cur + 1 <= self.limit: self.cur += 1 return True return False
windows.py: the SlidingCounter class
The estimate assumes the earlier window's requests were spread evenly across it. When they were not, for example when all 8 came in the last second, the estimate undercounts for a short moment. The error is bounded, and the memory is fixed at two numbers per key, which is why this variant is popular for large systems.
Comparing the two, and the quiz
The first check is the boundary trace from the previous lesson. The second replays 300 seconds of random arrivals, about three requests a second on average, against a limit of 20 per 10 seconds. The arrival times come from a fixed random seed, so the run can be repeated.
import random from windows import SlidingLog, SlidingCounter boundary = [9.5] * 10 + [10.5] * 10 for cls in (SlidingLog, SlidingCounter): lim = cls(limit=10, window=10) n = sum(lim.allow(t) for t in boundary) print(f"{cls.__name__:15} boundary burst: {n} of 20 allowed") random.seed(7) t, trace = 0.0, [] while t < 300: t += random.expovariate(3.0) # about 3 requests a second trace.append(t) log, cnt = SlidingLog(20, 10), SlidingCounter(20, 10) peak = diff = na = nb = 0 for t in trace: a, b = log.allow(t), cnt.allow(t) na += a nb += b peak = max(peak, log.size()) diff += a != b print(f"{len(trace)} requests, limit 20 per 10 s") print(f"allowed: log {na}, counter {nb}") print(f"disagreements between log and counter: {diff}") print(f"log kept at most {peak} timestamps; counter keeps 2 numbers")
l4_run.py: both sliding limiters on the same traces
SlidingLog boundary burst: 10 of 20 allowed SlidingCounter boundary burst: 10 of 20 allowed 922 requests, limit 20 per 10 s allowed: log 563, counter 559 disagreements between log and counter: 288 log kept at most 20 timestamps; counter keeps 2 numbers
Both limiters admit exactly 10 of the 20 boundary requests, the correct answer for ten per ten seconds. The fixed window admitted all 20.
On the long trace the two disagree on 288 of 922 individual decisions, but they admitted almost the same total: 563 for the log and 559 for the counter. The number of disagreements looks large because one different decision changes the state that every later decision depends on, so the two paths drift apart. The total is the better measure of accuracy. The log kept at most 20 timestamps here because the limit is 20, while the counter holds two numbers however high the limit goes.
| Algorithm | Memory per key | Accuracy | Allows bursts |
|---|---|---|---|
Part 5 · Limiting across many servers
Why a shared limit is hard
A single process can keep its buckets in memory. A real service runs on many servers behind a load balancer, and a caller's requests land on all of them. If every server keeps its own count, a limit of 100 per minute becomes 100 per minute on each server, so a caller can send 100 times the number of servers in total each minute.
There are three ways out, and each trades accuracy against cost.
- Sticky routing. Send all requests of one key to the same server, for example by hashing the key. The count stays local, but one hot key loads one server, and a server failure loses its counts.
- A shared store. Every server asks a fast central store, such as Redis or a database, for the count. The count is exact and every request pays a network round trip.
- Local counts, synchronised in batches. Each server takes a slice of the allowance, spends it locally, and tops up from the shared store. It is fast and slightly loose: the global limit can be passed by about one slice for each server.
Most designs start with the shared store, since the extra round trip is usually small next to the request itself. The next page is about what goes wrong when many servers use it at once.
The race in check-then-act
The natural way to write a limiter on a shared store is: read the count, compare it with the limit, and if it is below, add one. Those are separate steps. Between the read and the write another server can do the same, and both believe there is room for one more.
The Redis documentation for INCR shows a related hazard in a variant of its rate limiter pattern: the increment and the expiry are separate commands, so a failure between them leaves a counter that never expires. The fix it gives is to make the two one atomic action with a Lua script. An atomic operation runs as a single step that nobody else can interleave with.
The program uses SQLite as the shared store, with eight threads and a connection each. Every thread sends 50 requests, 400 in all, against a limit of 100. One version reads then updates. The other uses a single UPDATE ... RETURNING statement that raises the count only if it is below the limit, and returns the new count only when it did. A returned row means the request was allowed.
import os, sqlite3, sys, threading, time print(sys.version.split()[0], "sqlite", sqlite3.sqlite_version) DB, LIMIT, THREADS, EACH = "l5.db", 100, 8, 50 def connect(): return sqlite3.connect(DB, timeout=30, isolation_level=None) def check_then_act(con): (n,) = con.execute("SELECT n FROM quota WHERE k='u1'").fetchone() if n < LIMIT: time.sleep(0) # let another thread run con.execute("UPDATE quota SET n = n + 1 WHERE k='u1'") return True return False def atomic(con): row = con.execute( "UPDATE quota SET n = n + 1 WHERE k='u1' AND n < ? RETURNING n", (LIMIT,)).fetchone() return row is not None
l5_run.py, part 1: the two ways to count
def trial(fn): if os.path.exists(DB): os.remove(DB) c = connect() c.execute("CREATE TABLE quota (k TEXT PRIMARY KEY, n INTEGER)") c.execute("INSERT INTO quota VALUES ('u1', 0)") allowed = [] def worker(): con, ok = connect(), 0 for _ in range(EACH): ok += fn(con) con.close() allowed.append(ok) ts = [threading.Thread(target=worker) for _ in range(THREADS)] for t in ts: t.start() for t in ts: t.join() c.close() return sum(allowed) for fn in (check_then_act, atomic): print(f"{fn.__name__:14} limit {LIMIT}, " f"allowed {trial(fn)} of {THREADS * EACH}") os.remove(DB)
l5_run.py, part 2: the trial harness
The result, and the quiz
3.12.10 sqlite 3.49.1 check_then_act limit 100, allowed 106 of 400 atomic limit 100, allowed 100 of 400
Python 3.12.10 and SQLite 3.49.1; RETURNING needs SQLite 3.35 or newer.
The check-then-act version admitted 106 of the 400 requests, six over the limit. The atomic version admitted exactly 100. The exact number for the first version depends on how the threads interleave and can change between runs and machines; it was 106 in the run shown and between 105 and 107 in other runs here. What does not change is that it can go over, and the atomic version cannot.
The fix has one shape everywhere. Put the check and the update into one operation that the store executes atomically: a conditional UPDATE in a database, a Lua script or a counter command in Redis, or a transaction with a compare-and-set. The same applies to a token bucket, whose read-refill-take sequence must be one atomic step.
Two more problems remain in a shared limiter. The first is expiry: a counter for a user who never returns must disappear, so set an expiry whenever the count is created. The second is the store itself, which is now a dependency on every request. Decide whether it fails open or closed, as the first lesson said, and keep its latency low by placing it close to the servers.
Two servers read a count of 99 against a limit of 100 at the same moment. What can happen with check-then-act?
- Both see room, both add one, and the count ends at 101.
- The check and the update were separate steps.
How does the UPDATE ... WHERE n < ? RETURNING n statement avoid the race?
- The database applies the condition and the increment as one operation.
- A returned row means the request got a slot, and no row means the limit was reached.
Why is a per-server local count with no sharing a poor limiter for a service with 20 servers?
- Each server allows the full limit, so the caller can send up to 20 times the limit overall.
Part 6 · Telling the client: 429 and rate-limit headers
The status code and Retry-After
A refusal should tell the caller two things: that it was a limit and not a fault, and when to come back. HTTP has a status for this. RFC 6585 defines 429 Too Many Requests, and says the response may include a Retry-After header that tells the client how long to wait before making a new request.
The same RFC leaves some choices open. It does not define how the server identifies the user, nor how it counts requests. A server may count per resource, across the whole server or across a group of servers, and may identify users by credentials or by a cookie. That is why the earlier lessons are about design choices and not about a protocol.
Compare the other common answer. As noted before, nginx's limit_req rejects with 503 by default, which says the server is unavailable. A 429 is more useful to a client library, because it can tell a limit from an outage and can read the wait time. The Retry-After header carries either a number of seconds or an HTTP date, as RFC 9110 defines it. That RFC describes it for 503 and redirect responses, and RFC 6585 allows it on a 429.
A well-behaved client treats 429 as a signal to stop, wait for at least the time given, and then retry with some random delay added so that many clients do not return at the same instant.
A refused request should also be cheap to produce. The point of the limiter is to protect the work behind it, so the 429 is built from the count alone, without opening a database connection or touching the request body.
Rate-limit headers
Clients cannot adapt to a limit they cannot see. Many APIs therefore send headers on every response that say what the limit is and how much is left. There is no final standard. The IETF HTTP API working group has an Internet-Draft, draft-ietf-httpapi-ratelimit-headers, which was at revision 12, dated 20 November 2026, when this lesson was written. It defines three fields.
RateLimit-Policyannounces the quotas the server applies, with a quotaqand an optional windowwin seconds.RateLimitreports the quota still available asa, with an optional windoww.RateLimit-Partitiondeclares the dimensions, such as the user or the method, that the quota is partitioned by.
Because it is a draft, names and parameters have changed between revisions, and older services send X-RateLimit-Limit style headers instead. Treat the draft as a direction, and check the current text before relying on a detail. The draft also says that when Retry-After and RateLimit appear together, Retry-After takes precedence.
The server below sends these headers. It is a standard-library HTTP server on port 55482 with one token bucket for each value of an X-Client header, using the TokenBucket class from earlier: capacity 5, one new token a second, the same bucket as the scene.
import math, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from bucket import TokenBucket CAPACITY, RATE = 5, 1.0 # 5 tokens, one new token each second W = int(CAPACITY / RATE) # seconds to refill the whole bucket POLICY = f'"bucket";q={CAPACITY};w={W}' buckets, t0 = {}, time.monotonic() class Handler(BaseHTTPRequestHandler): def do_GET(self): key = self.headers.get("X-Client", self.client_address[0]) b = buckets.setdefault(key, TokenBucket(RATE, CAPACITY)) ok = b.allow(time.monotonic() - t0) self.send_response(200 if ok else 429) left = int(b.tokens) self.send_header("RateLimit-Policy", POLICY) self.send_header("RateLimit", f'"bucket";a={left};w={W}') if not ok: wait = math.ceil((1 - b.tokens) / RATE) self.send_header("Retry-After", str(wait)) body = b"ok\n" if ok else b"slow down\n" self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass ThreadingHTTPServer(("127.0.0.1", 55482), Handler).serve_forever()
l6_server.py: a token bucket behind HTTP, 429 on refusal
A run with curl, and the quiz
The first command sends seven requests as the client ravi and prints only the status code of each. The second shows the full response to the next request, and the third waits a little over a second and sends one more. It was run with curl 8.21.0, and the Date and Server headers were removed from the output below.
request 1: 200 request 2: 200 request 3: 200 request 4: 200 request 5: 200 request 6: 429 request 7: 429
HTTP/1.0 429 Too Many Requests RateLimit-Policy: "bucket";q=5;w=5 RateLimit: "bucket";a=0;w=5 Retry-After: 1 Content-Length: 10 slow down
The eighth request, refused
HTTP/1.0 200 OK RateLimit-Policy: "bucket";q=5;w=5 RateLimit: "bucket";a=0;w=5 Content-Length: 3 ok
After waiting 1.2 seconds
The first five requests pass, the sixth and seventh are refused, and the eighth shows the 429 with its headers. a=0 in the RateLimit field says no quota remains, and Retry-After: 1 says to wait one second. After 1.2 seconds one token has returned, so the next request gets 200, and a=0 again because that request used it. The Retry-After value is rounded up to a whole second, because the header carries whole seconds here.
A second client, meena, would not have been affected by any of this, because each value of the key has its own bucket.
What does a client learn from a 429 that it would not learn from a 503?
- That the cause is its own request rate and not a server fault.
- With Retry-After it also learns how long to wait.
In the response, RateLimit: "bucket";a=0;w=5 and Retry-After: 1 appear together. Which tells the client when to retry?
- Retry-After. The draft says it takes precedence over the RateLimit window.
Why should the 429 be produced before any database work?
- The limiter exists to protect that work, so refusing must cost almost nothing.