Sub topic 11
Telling clients about limits: HTTP 429 and Retry-After
This chapter assumes you know basic HTTP status codes and headers, and that you have a limiter that returns allow or deny, such as the token bucket from earlier chapters. Here we cover what the server sends back when it denies a request.
Why the response matters
A bare rejection makes clients guess. They retry immediately, which adds load and gets them rejected again. A good response says that the limit caused the failure and when to try again. It also gives well-behaved clients enough information to slow down before they are rejected.
Status code and Retry-After
Use 429 Too Many Requests (defined in RFC 6585). Do not use 503 Service Unavailable for per-client limits. A 503 says the server is unhealthy, and clients and monitoring tools treat it that way.
Add a Retry-After header (RFC 9110). It takes either a whole number of seconds or an HTTP date. Seconds are simpler and avoid clock disagreement between server and client.
How you compute the wait depends on the algorithm:
| Algorithm | Wait until the next request can succeed |
|---|---|
| Fixed window | Time left in the current window |
| Sliding window counter | An estimate, or time left in the current window |
| Token bucket | `(cost - tokens) / refill_rate`, rounded up |
Round up. A rounded-down value sends the client back too early and causes a second rejection.
Informational headers
Sending limit state on every response, including successful ones, lets clients pace themselves. Two conventions exist. Many APIs use X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. An IETF draft proposes RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset, where reset is in seconds. The draft may change, so pick one scheme, document it, and keep the meaning of each header stable.
Building the response
This function turns a token bucket's state into a status, headers and body.
import math
def build_response(allowed, limit, tokens, refill_rate, cost=1):
"""Return (status, headers, body) for a token bucket decision.
`tokens` is the bucket level after the decision.
"""
headers = {
"RateLimit-Limit": str(limit),
"RateLimit-Remaining": str(int(tokens)),
"RateLimit-Reset": str(math.ceil((limit - tokens) / refill_rate)),
}
if allowed:
return 200, headers, {"ok": True}
wait = max(1, math.ceil((cost - tokens) / refill_rate))
headers["Retry-After"] = str(wait)
body = {"error": "rate_limited", "retry_after_seconds": wait}
return 429, headers, body
print(build_response(True, 5, 3.0, 1))
print(build_response(False, 5, 0.0, 0.5))The second call prints status 429 with Retry-After: 2, because an empty bucket refilling at 0.5 tokens per second needs 2 seconds to hold one token.
Common mistakes
- Returning 429 with no
Retry-After, so clients retry in a tight loop. - Giving every client the same
Retry-Aftervalue. Clients that were rejected together then return together. Ask clients to add random jitter, and consider adding some to the value you send. - Leaking internals in the body, such as the Redis key or other clients' limits.
- Sending a limit header that disagrees with what the algorithm enforces.
Exercise
A token bucket has capacity 10, refill rate 2 tokens per second, and 0.5 tokens left. A request costs 1 token. What status and Retry-After value should the server return?
Show answer
Status 429. The bucket is short by 0.5 tokens, and 0.5 / 2 = 0.25 seconds. Rounding up gives Retry-After: 1.