PREP WITH PROOF
Menu
APIS & RELIABILITY / PRACTICAL GUIDE

HTTP Retries: Backoff, Retry-After, and Idempotency

Design bounded HTTP retries with deadlines, jitter, Retry-After, and idempotency keys. Includes a tested Python retry-planning example and failure scenarios.

THE QUICK ANSWER

Retry only when the operation is safe to repeat, the failure is eligible under the API contract, and another attempt fits the remaining deadline. Use bounded backoff with jitter, respect an applicable Retry-After delay, and reuse the same idempotency key for the same supported operation. A timeout means the outcome may be unknown; it does not prove the server did nothing.

The request can succeed while the response disappears

Consider a client that asks an API to create a shipping order. The server saves the order, but the connection drops before the client receives the response. The client sees a timeout. Sending another create request may produce a second order unless the API can recognize the repeat. Waiting longer might reduce uncertainty, but it does not by itself establish what happened.

This is a hypothetical failure scenario, not a reported incident or a test against a shipping provider. It exposes the first design question: can you distinguish a logical operation from the individual network attempts used to perform it? If the client generates a fresh identity for every attempt, the server may correctly interpret each as a new request.

Write down the possible outcomes before writing a retry loop: the server rejected the request before execution, the operation completed but the reply was lost, or the operation is still in progress. An API’s status lookup or reconciliation workflow may resolve uncertainty more appropriately than another write. Your response to a timeout should follow that contract.

Separate repeatable effects from identical responses

HTTP idempotency concerns the intended server effect of repeating an identical request, not a promise that every response will be identical. HTTP defines PUT, DELETE, and safe methods as idempotent. A second DELETE can therefore produce a different response without changing the intended final effect. Non-idempotent methods should not be automatically retried without additional knowledge that makes repetition safe or establishes that the first request was not applied.

Do not infer repeatability only from a method name in application code. Verify the endpoint’s documented behavior, request identity, and any preconditions. Repeating a request to set a resource to a particular state is a different operation from asking the server to increment a counter. A client wrapper that treats both as “JSON over HTTP” loses that important distinction.

For a write whose outcome is unknown, decide whether the provider supports an idempotency mechanism and what guarantees it provides. Sending an invented Idempotency-Key header to an endpoint that does not implement it adds no protection. If safe repetition cannot be established, surface the uncertainty or reconcile it rather than turning on retries for every exception.

Source: RFC 9110: HTTP idempotent methods and Retry-After ↗

Choose an error policy for the endpoint

A 429 response signals rate limiting and can include Retry-After. That is a request to reduce pressure, not a reason to send a tight loop of new attempts. For other failures, a status code alone is often insufficient to decide whether the intended operation can be repeated safely. Use the provider’s error and retry documentation as part of the policy.

The following table is a review aid, not a universal list of retryable statuses. Authentication failures, malformed payloads, and failed preconditions usually need a different action before resubmission. Similarly, do not classify every transport exception as transient: a certificate validation failure is not the same diagnosis as a temporary connection disruption.

Keep the initial failure classification separate from scheduling. First decide whether the failure and operation are eligible for a repeat. Then decide whether there is time and capacity for it. This makes it possible to explain why the same 503 response might be retried for a supported idempotent operation but returned immediately for a write with unknown repeatability.

ObservationDecision to establish before retrying
429 with an applicable Retry-AfterWhether repetition is safe and the requested wait fits the deadline.
502, 503, or 504Whether the endpoint contract permits another attempt despite an uncertain outcome.
Timeout without a usable responseWhether the operation may have committed and how its identity is preserved.
Validation or authentication errorWhat must change; repeating the same invalid request is not a repair.
Success responseStop retrying and process the successful result.

Source: RFC 6585: 429 Too Many Requests ↗

Budget the whole operation, not just each socket call

A retry policy needs an overall deadline in addition to a timeout for an individual attempt. Otherwise, several individually bounded calls plus their waiting periods can outlive the caller’s useful response window. Include the request path’s connection establishment, processing, and response handling as appropriate for the client library; a setting called “timeout” may not cover every phase.

For an illustrative four-second operation budget, suppose the first attempt consumed one second. Three seconds remain. A proposed two-second wait followed by a request that needs a two-second allocation no longer fits. The correct planning result is to stop, shorten the permitted attempt only if that is meaningful, or defer through a supported workflow—not to ignore the deadline.

Use a monotonic clock for elapsed-time accounting. Recompute the remaining budget after each attempt and wait, and check cancellation before sending again. Wall-clock timestamps are useful for interpreting an HTTP-date header, but clock adjustments should not silently extend an elapsed-time deadline. The small function later in this guide receives an already-calculated remaining budget rather than reading a clock itself.

Source: Amazon Builders’ Library: timeouts, retries, and backoff with jitter ↗

Combine Retry-After with backoff without retrying early

Retry-After can express a nonnegative delay in seconds or an HTTP-date. A client adapter must interpret the applicable form, handle malformed values deliberately, and account for clock differences when converting a date to a wait. The example function below expects an already-validated number of seconds; it is not an HTTP header parser.

A useful policy is to choose a randomized local backoff, then wait at least the applicable server-directed minimum. Do not reduce a ten-second Retry-After to your two-second local backoff cap and call that compliance. If the wait cannot fit the remaining operation budget, return a stopped or deferred outcome instead of retrying early.

For a fleet of clients receiving the same server delay, consider additional bounded jitter after that minimum when the contract permits it. Using only the same minimum for every caller can synchronize their next attempts. The planner below uses the larger of the minimum and local jitter for simplicity; that choice does not guarantee a dispersed fleet when the server minimum dominates.

Source: RFC 9110: HTTP idempotent methods and Retry-After ↗

A small, testable retry planner in Python

This original function computes a proposed delay or returns None to stop. It does not issue HTTP requests, sleep, parse headers, or make a write safe. The caller supplies safe_to_repeat from the endpoint contract and handles cancellation. A status of None means a transport failure already classified as eligible; it is not shorthand for every exception.

The illustrative policy allows at most three total attempts, including the first, and selects 429, 502, 503, and 504 as status candidates. Those values and the timing constants are example choices, not recommended defaults for every API. attempt is the number of the attempt that just failed: 1 allows planning the second request, 2 allows the third, and 3 stops.

The local full-jitter window begins at 0.25 seconds and doubles, capped at two seconds. Supply a fresh random fraction in normal use; inject a fixed fraction for deterministic tests. request_budget_s reserves time for the next call. Recheck the real deadline after waiting because scheduling delays and other overhead can consume time after this calculation.

from math import isfinite


def plan_retry(*, attempt, status, safe_to_repeat, remaining_s,
               request_budget_s, retry_after_s=0.0,
               jitter_fraction=0.5):
    # Educational policy: three total attempts, not three retries.
    if attempt not in (1, 2) or not safe_to_repeat:
        return None
    # None means an already-classified transient transport failure.
    if status not in (None, 429, 502, 503, 504):
        return None
    values = (remaining_s, request_budget_s,
              retry_after_s, jitter_fraction)
    if not all(isfinite(value) for value in values):
        raise ValueError("Timing inputs must be finite")
    if request_budget_s <= 0 or retry_after_s < 0:
        raise ValueError("Invalid request budget or server delay")
    if not 0 <= jitter_fraction <= 1:
        raise ValueError("Jitter fraction must be between 0 and 1")
    if remaining_s <= 0:
        return None
    window_s = min(2.0, 0.25 * 2 ** (attempt - 1))
    delay_s = max(retry_after_s, window_s * jitter_fraction)
    if delay_s + request_budget_s > remaining_s:
        return None
    return delay_s

Verify the boundary cases before adding network calls

The planner and the result table here were executed locally with Python. They verify scheduling decisions, not network reliability or server-side duplicate prevention. With a fixed jitter fraction of 0.5, the first two failed attempts produce local waits of 0.125 and 0.25 seconds when no server delay overrides them. The third failed attempt stops.

For a safe eligible operation, a three-second server delay produces a three-second proposed wait when enough budget remains. A ten-second minimum with only five seconds remaining stops. An unsafe-to-repeat operation stops even if the response is 503. These checks deliberately separate the permission to repeat from the calculation of a delay.

Also test cancellation in the client that eventually calls this planner, and simulate the server committing a write before its response is lost. Verify the resource count and recorded operation identity after the repeat. A test that merely changes a fake response from 503 to 200 cannot establish protection against duplicate business effects.

Executed planner caseResult
503, safe, attempt 1, four seconds remaining, one-second request budget0.125 seconds
503, safe, attempt 2, otherwise the same0.25 seconds
503, safe, attempt 3Stop
429, safe, minimum three seconds, five seconds remaining3.0 seconds
429, safe, minimum ten seconds, five seconds remainingStop
503, operation not safe to repeatStop
400 or 200 under this example policyStop

Preserve one operation identity across attempts

For an API you control, document how the idempotency key identifies a logical operation, the scope in which it is unique, how long records remain valid, and how concurrent requests behave. Retry the same supported operation with the same key and parameters. A genuinely different operation needs a different identity; changing parameters under an existing key should not silently create ambiguous effects.

The server must coordinate duplicate detection with the business mutation. Recording a key and then performing an unrelated write leaves a crash boundary between them; performing the write first and recording the key later creates the opposite gap. Use an appropriate atomic design for the storage and effects involved, including any external side effects that a database transaction cannot cover alone.

Provider behavior is specific to the contract and API version. For example, Stripe’s current API documentation distinguishes API v1 saved-response replay from API v2 handling of failed or partially completed work. Do not assume that a retry always returns an improved response, or that every provider stores the same outcomes. Read the version-specific contract before deciding what to retry and how to reconcile it.

Source: Amazon Builders’ Library: making retries safe with idempotent APIs ↗

Give retries one owner and measure the real cost

Inspect retries in the SDK, application wrapper, gateway, and job runner before adding another loop. Independent retry layers can multiply downstream attempts. As a simple arithmetic example, two layers that each permit three attempts can produce up to nine downstream attempts for one logical request. A local “only three attempts” limit does not bound the whole path.

Assign a clear owner for retry decisions and set a shared budget where the architecture supports it. Record the logical operation identifier separately from attempt numbers, failure category, requested wait, remaining budget, and final outcome. Avoid putting raw credentials, full sensitive payloads, or unbounded identifiers into metrics labels.

Review successful recovery alongside retry volume and latency. A rising success count can hide excessive extra work, particularly during overload. Start with explicit repeatability and bounded attempts, test uncertain outcomes, and then tune timing from observed behavior. A reliable retry policy should explain when it stops as clearly as when it tries again.

Source: AWS Well-Architected: control and limit retry calls ↗

KEEP THESE THREE THINGS

Your next steps

  1. A timeout leaves the operation’s outcome uncertain; establish repeatability before another write.
  2. Treat the deadline, applicable server wait, local backoff, and total-attempt cap as separate constraints.
  3. Test duplicate effects and retry amplification as well as eventual success.

Sources & official resources

Linked resources checked on 2026-10-23. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →