Sub topic 9
Telling clients: 429, 503, and Retry-After
This chapter assumes you know basic HTTP status codes, how request latency is measured, and how to read short Python examples. It also assumes you have read the chapters on load shedding and bounded queues.
Shedding load protects the server. It does not help the caller unless the caller can tell what happened and what to do next. A bare dropped connection or a slow timeout looks like a network fault, and clients usually answer a fault by retrying at once. A clear overload signal lets well-behaved clients slow down, wait, or try another server.
Why the signal matters
When a server rejects work, the client has to decide between three actions:
- Retry immediately.
- Wait and retry later.
- Give up and report an error.
The server knows which of these is best. The response is the only channel it has to say so. If the signal is missing or wrong, clients pick the worst option for an overloaded service, which is an immediate retry. The chapter on retries covers how that multiplies load. Here the goal is to send signals that avoid it.
A good overload response has three properties:
- It is fast. Rejecting should cost far less than serving. Check the limit before parsing bodies, querying databases, or doing authentication that needs a network call.
- It is specific. The status code says whose problem this is: the client's rate or the server's capacity.
- It carries guidance. A
Retry-Afterheader says when to come back.
429 versus 503
Two status codes cover most overload cases. They answer different questions.
| Code | Name | Meaning | Typical cause |
|---|---|---|---|
| 429 | Too Many Requests | This client sent too many requests in a time window. | Per-client rate limit, such as a token bucket per API key |
| 503 | Service Unavailable | The server cannot handle the request right now. | Full queue, in-flight limit reached, dependency down, shutting down |
The distinction is about who should change behavior. A 429 says "you in particular are going too fast." The fix is for that client to slow down, and other clients are unaffected. A 503 says "the service as a whole is saturated." Every client is affected, and the right response is for all of them to back off.
This has practical consequences:
- Use 429 when you can identify the caller (API key, user ID, IP address) and that caller exceeded its own quota.
- Use 503 when the limit is global, such as the in-flight limit from the earlier chapter, or a bounded queue that is full.
- Do not use 500 for shedding. A 500 means "something broke," and many clients, monitors, and alerting rules treat it as a bug to investigate. Shedding is intended behavior and should be easy to tell apart from failures.
- Be careful with 502 and 504. These usually come from a proxy or gateway and mean a bad or missing upstream response. A gateway may legitimately return 503 itself when it sheds.
Some services return 503 for everything and some return 429 for everything. Either is workable if the documentation says so. The important point is that clients can tell shedding from errors.
The Retry-After header
Retry-After tells the client how long to wait before the next attempt. HTTP defines two formats:
- A number of seconds:
Retry-After: 5 - An HTTP date:
Retry-After: Thu, 26 Nov 2026 10:30:00 GMT
The seconds form is simpler and does not depend on clock agreement between server and client, so prefer it. The header is defined for 503 and for 3xx redirects. RFC 6585 allows it on 429 responses as well, and most clients honor it there.
Choosing the value is a design decision, not a formality. Some approaches:
- Per-client rate limit (429): compute the time until the client's bucket has enough tokens for one request. For a token bucket with rate
rtokens per second and a deficitdtokens, the wait isd / rseconds, rounded up. - Global saturation (503): estimate how long the queue takes to drain. By Little's law, a queue of
Litems served at rateμper second drains in aboutL / μseconds. - Unknown recovery time: use a short, slightly randomized value so clients do not all return at the same second.
The third case matters. If every rejected client receives Retry-After: 1, they all come back one second later as a synchronized wave. Adding jitter on the server side spreads them out.
Here is a small handler that combines the in-flight limit with an honest 503 and a jittered hint:
import random
MAX_IN_FLIGHT = 50
in_flight = 0
def retry_after_seconds() -> int:
# Base hint of 1 second plus up to 2 seconds of random spread.
return 1 + random.randint(0, 2)
async def handle(request, process):
global in_flight
if in_flight >= MAX_IN_FLIGHT:
headers = {"Retry-After": str(retry_after_seconds())}
return 503, headers, b"overloaded"
in_flight += 1
try:
return 200, {}, await process(request)
finally:
in_flight -= 1The check and the increment have no await between them, so this is safe inside one asyncio event loop. With threads you would need a lock or an atomic counter.
For a per-client limit, the TokenBucket class from the admission control chapter can supply the wait time. Extend it with a method that reports the delay:
import math
import time
class TokenBucket:
def __init__(self, rate: float, capacity: float) -> None:
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.updated = time.monotonic()
def _refill(self) -> None:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
def allow(self, cost: float = 1.0) -> bool:
self._refill()
if self.tokens >= cost:
self.tokens -= cost
return True
return False
def seconds_until(self, cost: float = 1.0) -> int:
"""Whole seconds until `cost` tokens are available."""
self._refill()
deficit = max(0.0, cost - self.tokens)
return math.ceil(deficit / self.rate)
buckets: dict[str, TokenBucket] = {}
def check_rate_limit(api_key: str):
bucket = buckets.setdefault(api_key, TokenBucket(rate=5, capacity=10))
if bucket.allow():
return None
wait = max(1, bucket.seconds_until())
return 429, {"Retry-After": str(wait)}, b"rate limit exceeded"The max(1, ...) guards against a computed wait of zero, which would tell the client to retry immediately.
What the client should do
A signal only helps if clients act on it. A well-behaved client follows these rules:
- On 429 or 503, do not retry before the
Retry-Aftertime has passed. - If the header is absent, fall back to exponential backoff with jitter.
- If both exist, wait for whichever is longer. The server's hint is a minimum, not a suggestion to ignore when the local backoff is shorter.
- Stop after a bounded number of attempts or when the request's own deadline runs out.
- Do not retry status codes that will not change, such as 400 or 404.
Server authors cannot enforce any of this. Some clients ignore the header. That is one reason the server must still protect itself with limits that do not depend on client cooperation.
Gotchas
- Hiding overload behind 200. Returning a 200 with an error body defeats load balancers, monitors, and client libraries that key off status codes. Shed with a real status.
- Expensive rejections. If building the 503 takes a database call or a template render, shedding itself consumes the capacity you are trying to save. Keep the response small and static.
- Retry-After that lies. A value of 1 second when the queue needs 30 seconds to drain produces repeated rejections. Each rejected retry still costs CPU.
- Connection reuse. A 503 on a keep-alive connection lets the client reuse it. Closing the connection forces a new TCP and TLS handshake, which costs more under load. Keep connections open unless you are overwhelmed at the socket level.
- Proxies rewriting codes. A load balancer or gateway may replace your 503 with its own page or strip headers. Test the response as the client actually receives it.
- Mixing meanings. If the same code means "you are over quota" in one endpoint and "we are down" in another, clients cannot react correctly. Pick one convention per service.
The flow of a shed request
Choosing between the signals
Exercises
Exercise
A public API gives each API key 10 requests per second using a token bucket. One key exceeds that rate while the rest of the service is idle. Which status code should the server return, and how should it choose the Retry-After value?
Show answer
Return 429, because the problem is one caller's rate and not the service's capacity. Set Retry-After to the time until that key's bucket holds one token again, which is the token deficit divided by the refill rate, rounded up to at least 1 second.
Exercise
Your service sheds load by returning 503 with "Retry-After: 2" to every rejected request. Latency spikes every two seconds even though average traffic is steady. What is happening, and what are two ways to fix it?
Show answer
Rejected clients all retry at the same moment, so they return as a synchronized wave every two seconds. Fix it by adding random spread to the server's Retry-After value, and by having clients apply jitter to their own backoff, so retries are spread over time.