AI API Retry Budgets: Retry-After, Attempts and Deadlines
An application policy for 429 and 503 responses: parse Retry-After, bound attempts and deadlines, and reconcile uncertain outcomes before replay.

Retry an AI API request after a 429 only when you have evidence that the previous attempt was rejected, repeating the operation is safe, and the remaining deadline can cover the required wait, another call and response validation. Count the original request as attempt one. Otherwise stop or defer the job with an explicit recovery state.
The controls and offline example below belong in your application. Your executor owns transport, scheduling and durable job state; follow API429’s published endpoint contract. Start with the API429 documentation and API reference to check the actual client contract. Use the model catalog for published model information; vendor documentation alone does not establish availability through another service.
Read the signal before choosing an action
A status code is evidence about a response, not a complete history of the operation. Preserve any request identifier and classify the job's observed state before scheduling another generation. A capacity response with a known rejection differs from a connection that vanished after submission. The latter could have completed work even though your caller received nothing.
| Signal | Application action | Evidence needed before another call |
|---|---|---|
| 429, rejected operation, safe replay | Consider bounded retry | A credible wait and remaining attempt/deadline allowance |
| 503, rejected operation, safe replay | Consider the same bounded policy | Temporary failure classification and confirmed rejection |
| 429 associated with an exhausted allowance | Stop or defer pending corrective action | Recovery condition from the applicable service contract |
| Missing Retry-After | Use capped exponential delay with jitter | A locally chosen cap and safe replay evidence |
| Invalid Retry-After | Stop automatic scheduling | Operator review or a corrected trustworthy signal |
| Accepted job, unknown timeout or partial stream | Reconcile existing work | Recorded completion, status lookup where documented, or human review |
| 403 or invalid request | Fix access or input | A corrected configuration; repeated waiting does not fix it |
HTTP 429 is defined in RFC 6585 section 4; Retry-After is optional. Google's troubleshooting guide distinguishes resource exhaustion and temporary unavailability, but a retry recommendation still needs your job's safety and timing checks. Read Google rate limits for the applicable limit dimensions. Avoid guessing that every capacity failure clears after the same interval.
Parse Retry-After seconds and HTTP dates
RFC 9110 section 10.2.3 permits an integer delay in seconds or an HTTP date. Parse both. For a date, compare against a timezone-aware current UTC value and convert the difference to a nonnegative delay. A valid past date produces zero waiting time; it does not bypass replay safety, attempt limits or deadline checks. Keep your clocks synchronized when interpreting date headers. The example validates the complete HTTP-date grammar for IMF-fixdate, obsolete RFC850 dates and asctime dates under RFC 9110 section 5.6.7. It treats all three as UTC, applies the rolling fifty-year rule for two-digit RFC850 years, and rejects control characters, trailing junk and non-HTTP timezones. Unsupported leap-second values stop automatic scheduling for review.
Treat the server delay as a minimum. If it exceeds your application's permitted wait, defer or stop; never shorten it to the local cap and retry early. Reject malformed, negative, fractional or unbounded numeric input explicitly. A header that cannot be interpreted safely should produce a visible policy failure rather than silently becoming a missing header.
Without a header, use a capped exponential delay plus bounded jitter chosen by the application. Jitter spreads wakeups; it does not create quota or prove the next call will succeed. The downloadable example adds jitter only to its locally chosen delay, while preserving server-provided waits exactly. A scheduler may add further delay, but must recheck the deadline before execution.
Count attempts and spend one total deadline
Define maximum attempts inclusively: the original call is one, and each subsequent submission consumes another. A limit called “retries” can easily be misread by separate teams, so log both the current attempt and maximum total attempts. Count validation repair and alternate-model generation in your broader task allowance even if they use separate failure classifications.
Use a monotonic clock for the live task deadline so wall-clock adjustments do not extend a job. Reserve enough remaining time for the next network call and for validation, persistence and delivery after it returns. The scheduling condition is:
required wait + next call allowance + validation reserve <= remaining deadline
A response arriving at the very edge is useful only if the reserve covers the remaining work. The example allows equality and defers when the required sum exceeds the available time. In an actual executor, enforce the call allowance with the transport's documented timeout controls and recheck after scheduler delays. A policy decision does not itself enforce network cancellation or establish whether remote work stopped.
Queue wait is part of the task's age. Keep an explicit expiry, bounded queue length and admission policy in the application scheduler. If live completion is no longer useful, return a clear deferred state only when the product permits background completion. Record a durable job identifier and next eligible time, and limit later recovery attempts too. Moving work to a queue must not reset its lifetime or make an infinite retry loop appear bounded.
Reconcile uncertain outcomes and deduplicate downstream writes
A timeout indicates that the caller stopped waiting. It does not prove rejection. Likewise, an accepted asynchronous job or partially received stream must not automatically cause another paid generation. Preserve the original job record, received output and documented request identifier. Look up the existing operation only where the service documents that capability; otherwise send the case to a controlled reconciliation workflow.
Downstream deduplication is a separate application responsibility. Before writing a ticket, invoice or CRM update, bind the validated result to a durable business operation identifier and use the destination's documented uniqueness or transaction mechanism. Persist the successful write outcome so a restarted worker can resume without writing twice. Merely adding an arbitrary Idempotency-Key header does not establish generation idempotency support in API429 or any other endpoint.
An alternative model also represents another submission. Approve its input, output schema, tools and quality requirements before allowing it into recovery. Changing models cannot establish that the original operation failed, and an alternate response can create the same duplicate business action. Keep uncertain jobs out of automatic replay until their state is resolved.
Use the application idempotency ledger guide to preserve operation identity during recovery, and the request coalescing guide to bound callers sharing an authorized in-flight result. Keep an uncertain operation attached to its original identity while you reconcile evidence.
Before deciding whether another attempt is appropriate, separate catalog selection evidence from a scoped workload health observation. A listed model or an earlier complete result does not resolve the outcome of a timed-out paid operation; reconcile that operation before replay.
Audit SDK retries before adding an outer loop
Inspect the SDK version and retry configuration actually deployed. Some clients retry automatically; defaults and supported configuration vary. An application loop around an SDK loop can multiply submissions, waits and cost while the outer counter reports only a few attempts. Choose a single retry owner where possible, or include every SDK submission in the same accounting and deadline.
Record status, outcome classification, attempt count, selected delay, remaining deadline and final decision with sanitized job identifiers. Do not log secret keys or sensitive prompts. Compare submitted attempts with completed business tasks to detect amplification. For spending allowances and reconciliation, continue to the AI API cost guardrails guide; this page supplies no current price or workload benchmark.
Download and run the offline policy example
Download the complete Python policy. It uses only the standard library, accepts injectable clocks and jitter, and returns a decision without network access, sleeping or keys. Run it with python3 api429-retry-policy.py. Its synthetic demonstration returns a retry plan; that is a policy test, not a successful API generation or proof of a native feature. The caller must supply truthful rejection and replay-safety evidence.
"""Offline application policy only: no network, waiting, or API feature claims."""
from datetime import datetime, timezone
import json
import math
import re
def finite(value, minimum=0):
return (type(value) in (int, float) and math.isfinite(value)
and minimum <= value <= 1_000_000_000_000)
def http_date(header, utc):
"""Strict HTTP-date formats; UTC, including RFC850's rolling year rule.
Leap seconds are rejected for reconciliation instead of scheduled early.
"""
short = r'(Mon|Tue|Wed|Thu|Fri|Sat|Sun)'
long = r'(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)'
month = r'(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'
clock = r'([0-9]{2}):([0-9]{2}):([0-9]{2})'
imf = re.fullmatch(short + r', ([0-9]{2}) ' + month + r' ([0-9]{4}) ' + clock + r' GMT', header)
old = re.fullmatch(long + r', ([0-9]{2})-' + month + r'-([0-9]{2}) ' + clock + r' GMT', header)
asc = re.fullmatch(short + r' ' + month + r' ( [1-9]|[0-9]{2}) ' + clock + r' ([0-9]{4})', header)
if imf or old:
weekday, day, mon, year, hour, minute, second = (imf or old).groups()
elif asc:
weekday, mon, day, hour, minute, second, year = asc.groups()
else:
raise ValueError('not a complete HTTP-date')
year, day, hour, minute, second = map(int, (year, day, hour, minute, second))
mon = ('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split().index(mon) + 1)
if old:
year = utc.year + ((year - utc.year % 100) % 100)
if (year, mon, day, hour, minute, second) > (utc.year + 50, utc.month, utc.day, utc.hour, utc.minute, utc.second):
year -= 100
date = datetime(year, mon, day, hour, minute, second, tzinfo=timezone.utc)
if weekday[:3] != ('Mon Tue Wed Thu Fri Sat Sun'.split()[date.weekday()]):
raise ValueError('weekday does not match date')
return date
def decide(*, status, outcome, replay_safe, attempt, max_attempts, deadline,
monotonic, utc_now, retry_after=None, call_allowance=5, reserve=1,
max_wait=10, base_delay=1, jitter=lambda: 0):
"""Return a plan; caller owns scheduling, transport and durable job state.
attempt includes the original call (1). outcome='rejected' is evidence
supplied by the caller, never inferred solely from an HTTP status.
"""
def result(action, reason, wait=0):
return {'action': action, 'reason': reason, 'wait': wait}
try:
now = monotonic()
utc = utc_now()
noise = jitter()
if (type(attempt) is not int or type(max_attempts) is not int
or not 1 <= attempt <= max_attempts <= 1000
or type(status) is not int or not 100 <= status <= 599
or type(replay_safe) is not bool
or not all(finite(v) for v in (now, deadline, reserve, max_wait))
or not finite(call_allowance, 0.000001)
or not finite(base_delay, 0.000001)
or not finite(noise) or noise > 1
or not isinstance(utc, datetime) or utc.utcoffset() is None):
return result('stop', 'invalid_input')
if outcome != 'rejected' or not replay_safe:
return result('reconcile', 'outcome_or_replay_uncertain')
if status not in (429, 503):
return result('stop', 'nonretryable_status')
if attempt >= max_attempts:
return result('stop', 'attempt_limit')
if retry_after is None:
# Compare to the cap before exponentiation to avoid overflow.
if base_delay >= max_wait or attempt - 1 >= math.log2(max_wait / base_delay):
delay = max_wait
else:
delay = base_delay * (2 ** (attempt - 1))
wait = min(max_wait, delay + delay * noise)
else:
try:
if not isinstance(retry_after, str) or not 1 <= len(retry_after) <= 128:
raise ValueError('invalid header length or type')
if any(ord(char) < 32 or ord(char) == 127 for char in retry_after):
raise ValueError('control character in header')
header = retry_after.strip(' ')
if header.isascii() and header.isdecimal():
wait = int(header)
else:
date = http_date(header, utc.astimezone(timezone.utc))
wait = max(0, (date - utc).total_seconds())
if not finite(wait):
raise ValueError('unbounded delay')
except (ValueError, TypeError, OverflowError):
return result('stop', 'invalid_retry_after')
if wait > max_wait:
return result('defer', 'wait_exceeds_cap', wait)
if wait + call_allowance + reserve > deadline - now:
return result('defer', 'deadline', wait)
return result('retry', 'within_budget', wait)
except (ValueError, TypeError, OverflowError):
return result('stop', 'invalid_input')
def demo():
"""Synthetic clocks and response: success means a decision, not generation."""
return decide(status=429, outcome='rejected', replay_safe=True, attempt=1,
max_attempts=3, deadline=120, monotonic=lambda: 100,
utc_now=lambda: datetime(2026, 10, 24, tzinfo=timezone.utc),
retry_after='2', jitter=lambda: 0.5)
if __name__ == '__main__':
print(json.dumps(demo(), sort_keys=True))
FAQ
Should every 429 or 503 be retried?
No. Retry only a safely repeatable operation with a known rejected state and enough attempts and time remaining. A hard allowance failure needs corrective action. An unknown state requires reconciliation even when the observed response is associated with a normally transient status.
What happens when Retry-After is longer than my deadline?
End the live retry path. Defer only if your product supports background work with durable state, a new explicit recovery policy and a bounded expiry. Do not shorten the header value or reset the same job's budget silently.
Can a request timeout make duplicate generation safe?
No. A client timeout does not certify that remote execution stopped. Keep the job's outcome uncertain until evidence resolves it. Partial output should remain attached to the original operation rather than being mistaken for a rejection.
Where should an API429 user check access failures?
For an earlier OpenRouter refusal, consult the OpenRouter 403 diagnosis. For API429 access questions, use the public FAQ and the current documentation for the endpoint you call. Access failures and invalid payloads require correction; exponential waiting alone cannot repair them.
Does this example provide API429 queueing or idempotency?
It provides application scheduling decisions only. Your executor, persistent job store and downstream destination implement the required controls. Verify each supported endpoint and response contract in the API reference before connecting this example to real work.
Sources & further reading
Put the next step into practice.
Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

