API Retries Need a Retry Budget
Bound retry amplification across requests, preserve one deadline, and separate safe repetition from the capacity to try again.
A dependency becomes slow, so each caller retries twice. Its caller also retries twice. One user action can now produce nine downstream attempts, exactly when the dependency has the least capacity to handle them. Each retry policy looks modest in isolation. Together they make the incident worse.
A retry budget limits the extra work the system is willing to create. It complements idempotency: an idempotent operation can still overload a service if repeated often enough. Designing retries means choosing which failures qualify, who owns the retry loop, how much time remains, and when the system should stop trying.
Give one layer ownership of retries
Draw the request path through the browser, gateway, application client, and downstream SDK. Identify which layers already retry and which failures they interpret. A transport may retry a connection failure before sending a request; an SDK may retry a throttling response; your application may retry the entire business operation. Those scopes are different.
Choose the layer with enough context to make a useful decision. It should know the overall deadline and whether repeating the operation is acceptable. Let lower layers handle narrowly defined transport recovery only when its interaction with the outer policy is understood. Hidden SDK defaults count toward the attempt budget even if application logs call them one request.
Retries also need an operation identity. A timeout after submission leaves the outcome uncertain. Retrying a mutation requires the destination's idempotency or reconciliation contract; a retry budget alone cannot decide whether the previous attempt committed. Classify uncertain outcomes separately from failures known to have occurred before the effect.
Limit extra work across requests
A per-request attempt cap prevents one request from looping forever. It does not constrain a thousand requests that all fail simultaneously. A shared budget can cap retry amplification for a dependency or traffic class, allowing initial attempts while admitting only a bounded amount of additional work.
One simple design uses credits. Retry attempts consume credits; successful requests replenish them up to a capacity. During a sustained failure, the budget drains and retries stop. During recovery, useful traffic gradually restores the ability to retry. Botocore's retry implementation uses a quota mechanism with acquired and released capacity; the small model below is an illustration, not a reproduction of its complete policy.
Choose the budget scope deliberately. One global pool lets an unhealthy dependency exhaust retries for unrelated services. One pool per request has no aggregate effect. A pool per worker is easier to operate but its aggregate capacity grows with worker count. A shared service-wide policy needs coordination and a defined behavior if that coordinator is unavailable.
A deterministic budget model
This standard-library example separates retry admission from the first attempt. A retry needs a qualifying error, a safe repetition contract, time remaining, a per-request allowance, and a budget credit. The caller supplies a monotonic time value and an overall deadline. Calls to this model are serialized; a concurrent shared implementation must make credit updates atomic. There is no sleeping or real HTTP traffic in this model.
from dataclasses import dataclass
@dataclass
class RetryBudget:
capacity: int
credits: int
def admit(self, *, retryable, safe, attempts, max_attempts,
now, deadline, delay):
if delay < 0 or max_attempts < 1 or attempts < 1:
raise ValueError("invalid retry parameters")
if not retryable or not safe or attempts >= max_attempts:
return False
if now + delay >= deadline or self.credits < 1:
return False
self.credits -= 1
return True
def success(self):
self.credits = min(self.capacity, self.credits + 1)
budget = RetryBudget(capacity=2, credits=2)
request = dict(retryable=True, safe=True, attempts=1,
max_attempts=3, now=0, deadline=10, delay=1)
assert budget.admit(**request)
assert budget.admit(**request)
assert not budget.admit(**request) # shared budget exhausted
budget.success()
assert not budget.admit(**{**request, "safe": False})
assert not budget.admit(**{**request, "now": 9})
assert budget.credits == 1 # rejected retries did not spend capacity
assert budget.admit(**request)Backoff schedules work; deadlines bound it
Exponential backoff reduces retry frequency, and jitter spreads callers that would otherwise retry together. Neither mechanism establishes a total time bound. Carry one request deadline through queue waits, backoff, connection establishment, and response reading. Recalculate remaining time before each attempt rather than restarting the full timeout.
A server's Retry-After response can communicate when another attempt is appropriate. Respect its meaning while applying your own deadline and attempt limits. If the suggested wait exceeds the user's remaining time, return a useful deferred or failure outcome instead of sleeping past the request's useful lifetime. Parsing the header and choosing a clock require care because it can represent either a delay or an HTTP date.
Do not spend a retry credit when merely deciding that an error might be retryable. The example reserves one when the retry is admitted. If admitted work waits in a scheduler, define whether cancellation returns that credit. Keep the rule consistent so repeated scheduling and cancellation cannot accidentally create unlimited retries.
Keep overload controls distinct
A circuit breaker tracks whether a dependency should receive new work at all. A concurrency limit bounds simultaneous in-flight operations. A rate limiter bounds admission over time. A retry budget bounds extra attempts. These controls can cooperate, but substituting one for another leaves gaps.
For example, a small retry budget does not prevent a flood of first attempts. Conversely, a strict concurrency limit can still spend all available slots on retries while new requests starve. Reserve capacity or prioritize traffic according to the service objective. Avoid endlessly queuing work whose deadline will expire before it starts.
Track initial requests, retries admitted, retries suppressed, attempts per logical operation, deadline exhaustion, and dependency outcomes separately. A falling retry count might mean recovery, or it might mean the budget is exhausted. The accompanying success rate and suppression reason make that distinction visible.
Test the incident, not just the successful retry
Test a dependency that fails for every request, one that recovers after a burst, and one that commits but loses the response. Verify that layered policies do not exceed the agreed attempt count. Use injected clocks and deterministic jitter inputs so tests exercise timing boundaries without waiting in real time.
Also test cancellation between admission and execution, malformed Retry-After values, and a retryable response arriving after the overall deadline. These are policy tests; integration tests must still establish the SDK's actual behavior and the destination's idempotency semantics.
The useful outcome is controlled degradation. Some operations will fail while the dependency is unhealthy, but the retry mechanism will not multiply pressure without a bound. When recovery begins, the system has enough remaining capacity to make progress instead of spending it all repeating yesterday's failures.