Sub topic 11
Telling clients about limits: HTTP 429 and Retry-After
This chapter assumes you know basic HTTP request and response concepts, can read Python, and have seen a limiter that returns allow or deny. A limiter that rejects requests silently is hard to live with. Clients cannot tell a limit from an outage, so they retry at once and make the overload worse. This chapter covers how to report a rejection so well-behaved clients slow down on their own.
The 429 status code
HTTP 429 Too Many Requests is defined in RFC 6585. It means the client sent too many requests in a given time. It is a 4xx code, so it says the client should change its behavior. Choose it over these alternatives:
| Status | Meaning | Use for rate limiting? |
|---|---|---|
| 429 Too Many Requests | The client exceeded its allowed rate | Yes. This is the standard choice. |
| 503 Service Unavailable | The server is overloaded or down | Only for global load shedding, not per-client limits |
| 403 Forbidden | The client is not allowed | No. It hides the fact that waiting would help. |
| 200 with an error body | Transport succeeded, application failed | No. Clients and proxies cannot detect it. |
The difference between 429 and 503 matters. A 429 says "you in particular are going too fast." A 503 says "the service cannot serve anyone right now." Monitoring, retry libraries, and caches treat them differently, so do not mix them.
The Retry-After header
A 429 response may include a Retry-After header that tells the client how long to wait. The header has two legal forms:
- A number of seconds, such as
Retry-After: 30. - An HTTP date, such as
Retry-After: Thu, 26 Nov 2026 10:41:15 GMT.
Prefer the seconds form. It is a relative value, so it does not depend on the client's clock matching yours. The clock-skew problem is covered in a later chapter. Use whole numbers and round up. If you round down, the client retries too early and is rejected again.
How you compute the wait depends on the algorithm.
- Fixed window: the time until the current window ends, which is
window - (now % window). - Token bucket: the time until enough tokens exist, which is
(cost - tokens) / refill_rate. - Sliding window log: the time until the oldest entry in the window expires.
- Sliding window counter: an estimate. The simplest safe answer is the time until the current window ends.
Returning the wait from the limiter
The token bucket from earlier in this tutorial returns only True or False. To build a good response, the limiter needs to report how long the caller should wait. The class below extends it with a decision object.
import math
import time
from dataclasses import dataclass
@dataclass
class Decision:
allowed: bool
limit: int
remaining: int
retry_after: int # whole seconds; 0 when allowed
class TokenBucket:
"""Single-process token bucket. Not thread-safe."""
def __init__(self, capacity, refill_rate, clock=time.monotonic):
self.capacity = capacity
self.refill_rate = refill_rate
self.clock = clock
self.tokens = float(capacity)
self.last = clock()
def check(self, cost=1):
now = self.clock()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
if self.tokens >= cost:
self.tokens -= cost
return Decision(True, self.capacity, int(self.tokens), 0)
wait = (cost - self.tokens) / self.refill_rate
return Decision(False, self.capacity, int(self.tokens), math.ceil(wait))
bucket = TokenBucket(capacity=2, refill_rate=0.5)
for _ in range(3):
print(bucket.check())The third call prints a decision with allowed=False and retry_after=2. The bucket is empty and refills at 0.5 tokens per second, so one token takes two seconds.
Building the response
A good 429 response has three parts: the status line, headers that describe the limit, and a body that a human or a program can read. The next example is a standalone HTTP handler built on the Python standard library.
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
LIMIT = 3
WINDOW = 10
counts = {} # (client, window_index) -> count
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
client = self.client_address[0]
now = time.time()
index = int(now // WINDOW)
count = counts.get((client, index), 0)
reset_in = int(WINDOW - (now % WINDOW)) + 1
if count >= LIMIT:
body = json.dumps({
"error": "rate_limited",
"message": "Too many requests. Retry after %d seconds." % reset_in,
"retry_after": reset_in,
}).encode()
self.send_response(429)
self.send_header("Retry-After", str(reset_in))
self.send_header("RateLimit-Limit", str(LIMIT))
self.send_header("RateLimit-Remaining", "0")
self.send_header("RateLimit-Reset", str(reset_in))
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
counts[(client, index)] = count + 1
body = b'{"ok": true}'
self.send_response(200)
self.send_header("RateLimit-Limit", str(LIMIT))
self.send_header("RateLimit-Remaining", str(LIMIT - count - 1))
self.send_header("RateLimit-Reset", str(reset_in))
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()Run it and call curl -i http://127.0.0.1:8080/ four times in a row. The fourth response is a 429 with a Retry-After value of at most 11. The counts dictionary grows without bound in this demo. A real limiter must expire old windows.
Informational rate limit headers
Telling clients their remaining budget on successful responses lets them slow down before they are rejected. Two families of headers exist.
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset: widely used by public APIs for years. Their exact meaning is not standardized. For example,Resetis a Unix timestamp on some services and a number of seconds on others.RateLimit-Limit,RateLimit-Remaining,RateLimit-Reset: the names proposed in an IETF draft for standardization. The draft has changed between revisions, so check its current state before depending on details.
Whichever names you choose, document them. Say whether Reset is seconds or a timestamp, and state which window or bucket the numbers describe. The example above uses seconds, which avoids clock dependence.
How clients should react
The server's message only helps if the client honors it. A well-behaved client does the following:
- On a 429, read
Retry-Afterand wait at least that long. - If the header is missing, back off exponentially, such as 1, 2, 4, 8 seconds.
- Add random jitter to every wait, so many clients do not retry at the same instant.
- Cap the number of retries and give up with a clear error.
Jitter deserves emphasis. If a thousand clients were all rejected in the same second and all told Retry-After: 5, they will all return together in the same second. Randomizing the wait spreads the load. Servers can help by adding a small random amount to the value they send.
import random
import time
import urllib.error
import urllib.request
def get_with_retry(url, max_attempts=5):
delay = 1.0
for attempt in range(1, max_attempts + 1):
try:
with urllib.request.urlopen(url) as resp:
return resp.read()
except urllib.error.HTTPError as err:
if err.code != 429 or attempt == max_attempts:
raise
header = err.headers.get("Retry-After")
if header is not None and header.isdigit():
wait = int(header)
else:
wait = delay
delay *= 2
time.sleep(wait + random.uniform(0, 0.5 * wait))This client handles only the seconds form of Retry-After. A production client should also parse the date form.
Edge cases and common mistakes
- Returning 429 without
Retry-After. Clients guess, and guesses tend to be too aggressive. - Rounding the wait down. A client told to wait 1 second when 1.4 are needed is rejected again. Always round up.
- Counting rejected requests. If a rejected request still consumes budget, a client that retries blindly never recovers. Decide deliberately, and in most designs rejected requests should cost nothing.
- Leaking internals. Error bodies should not reveal other users' limits, internal key names, or store details.
- Mixing up limit scopes. If a request is rejected by a per-IP limit while the client holds a per-user quota, the headers must describe the limit that rejected it. Otherwise
Remainingsays 50 while the response is a 429. - Caching. A 429 response is not normally cacheable. Do not let a shared cache serve one client's rejection to others. Setting
Cache-Control: no-storeon the response guards against that. - Mismatched hints. The
Retry-Afterheader, the body field, and theRateLimit-Resetvalue should agree. Generate all of them from one computed number.
The sequence below shows a client being rejected, waiting, and succeeding.
Exercise
A token bucket has capacity 10 and a refill rate of 2 tokens per second. A request costs 4 tokens, and the bucket currently holds 1.5 tokens. What should the Retry-After value be, and why that number?
Show answer
The shortfall is 4 - 1.5 = 2.5 tokens. At 2 tokens per second that takes 1.25 seconds. Round up to a whole number of seconds, so Retry-After: 2. Rounding down to 1 would make the client retry before enough tokens exist and be rejected again.
Exercise
Your API returns 429 with no Retry-After header. A thousand clients are rejected in the same second and all retry with a fixed 1-second delay. What goes wrong, and what two changes fix it?
Show answer
All clients retry together every second, so the server sees a repeated synchronized spike and stays overloaded. Fix it by sending an accurate Retry-After so clients wait the right amount, and by having clients add random jitter (and exponential backoff when the header is absent) so their retries spread out over time.