When an API returns a 429, a 529 or a 503, the correct response is a backoff: the service is busy, not broken. When it returns an invalid request error, retries will loop forever, because the request itself is wrong. The two cases look similar in a crash trace and behave very differently, so the code must tell them apart before it decides.
Before you start
An agent that calls an external API, and a way to read the response status and the retry-after header.
Read the status and the retry header
When a call fails, read the HTTP status first: 429, 529 and 503 mean back off and retry, while 400 and 401 mean the request or the credentials are wrong and retrying will not help.
Read the retry-after header when the API sends one, and wait at least that long. If there is no header, wait a growing interval, such as 2, then 4, then 8 seconds.
Wait, then retry the same call once
Wait the backoff interval, then retry the identical call once. If it succeeds, log the retry and continue: the run is saved and the cost is one extra call.
If it fails again with a 429, wait longer and retry once more, up to three retries in total. After that, stop and escalate: the service is down, not busy.
Slow the run down if limits keep hitting
If 429s keep coming, the run is calling too fast: add a delay between calls, reduce the batch size, or spread the work over more time. A run that hammers a rate-limited API will be limited again.
Check the usage dashboard for the real limit: the limit may be per minute, per day, or per key, and the fix depends on which one you are hitting.
Practice check: fictional Maple Corner agent, 20 API calls, 3 hit 429
The table below is fictional practice material, worked out by hand from the stated retries. It is the expected result for the practice calls, not a run of any API.
| Call | Status | Wait | Retry result | Verdict |
|---|---|---|---|---|
| 7 | 429 | 2 s | Success | Pass |
| 12 | 429 | 4 s | Success | Pass |
| 15 | 429 | 8 s | Success on 3rd try | Pass |
| 18 | 400 | None | Not retried | Pass – correct, no retry |
Three 429s all succeed after backoff retries, and the 400 is correctly not retried. The run finishes all 20 calls with 3 extra retries and no failures.
Expected result. UNTESTED: the calls in the practice table are worked out by hand, not measured by running an API. Read the status on your own next failed call, back off and retry a 429 up to three times, and never retry a 400.
Limits
- A 429 means wait, a 400 means fix the request: retrying the wrong one wastes calls or loops forever.
- The retry-after header is the service telling you how long to wait: use it when it is there.
