Safe API Retries: Timeouts, Idempotency and Duplicate Work

A timeout tells you that a caller stopped waiting. It does not tell you whether the remote service accepted the request, committed a write, or started downstream work.

That distinction matters whenever an API creates something: an order, a payment instruction, a shipment, or a provisioning job. Retrying can recover from a temporary failure. It can also repeat work that already succeeded.

Safe API retries require more than a retry library. They need an explicit agreement about request identity, concurrent execution, stored outcomes, and what happens when certainty is unavailable.

A fictional walkthrough: the order exists, but the response is missing

Consider a fictional storefront submitting an order to an order service. The intended business invariant is simple: one checkout submission should create one order, even if transport failures cause repeated requests.

The sequence looks like this:

  1. The storefront sends POST /orders for checkout checkout-demo-A.
  2. The order service validates the request and commits the order.
  3. The response is delayed or lost before the storefront receives it.
  4. The storefront reaches its timeout and offers a retry.

The storefront now has an uncertain outcome. Reporting definite failure would be misleading. Sending a new, unrelated create request could produce a duplicate.

Instead, the storefront should retry the same logical operation using the same idempotency key. If the original request completed, the service can return its stored outcome rather than create another order.

The key is not merely a duplicate detector. It identifies the caller’s intent across multiple delivery attempts.

Give each logical operation a stable, scoped identity

Generate the key before the first attempt and persist it with the checkout submission. A browser refresh, worker restart, or queue redelivery must not silently generate a replacement key for that same operation.

Scope the key to an authenticated account or tenant and a defined operation. For example, the server might identify a request using:

(tenant_id, operation_name, idempotency_key)

This prevents unrelated tenants or operations from sharing one deduplication namespace. A key is not authorization: every retry still needs normal authentication and access checks.

Do not derive request identity solely from the payload. Two intentional orders can contain identical items and addresses. Conversely, the same key with a changed delivery address is not necessarily the same intent.

The AWS Builders’ Library guidance on safe retries with idempotent APIs explains why caller-provided request identifiers help distinguish repeated delivery from separate intent. The implementation still needs a clear lifecycle for those identifiers.

Detect changed payloads before accepting a retry

Store a fingerprint of the meaningful request fields alongside the key. On a repeated request, compare that fingerprint before returning a previous outcome or starting work.

For the fictional checkout, meaningful fields might include the customer reference, item identifiers, quantities, currency, and delivery address. Exclude transport details that legitimately change between attempts, such as a tracing identifier.

Define normalization deliberately. Object field ordering should not cause false conflicts, but normalization must not erase a meaningful difference. Store enough information to apply that comparison consistently across deployments.

If a caller reuses the key with a different meaningful payload, reject it with a documented conflict response. Do not overwrite the original association or silently replay an unrelated result.

The client should resolve that conflict explicitly, not automatically mint a fresh key. Otherwise, a protective rejection becomes a path to duplicate work.

Make reservation and business writes atomic

A common implementation mistake is checking whether a key exists, creating the order, and then recording the key. Concurrent requests can both pass the initial check. A crash after order creation can also leave no durable record of the association.

Where the order and idempotency record share a transactional database, use a uniqueness constraint on the scoped key and one transaction to bind that key, its fingerprint, and the created order. Persist the outcome needed for replay in the same transaction where practical.

Concurrent attempts must not both become owners of the operation. The losing attempt should follow the stored state: replay a completed result or receive a documented pending response. It must not start another order creation path.

If the design commits an in-progress reservation before performing work, define crash recovery too. A stale reservation needs investigation and controlled ownership transfer, not blind deletion. Lease expiry alone does not prove that the original worker stopped.

Atomicity also has a boundary. A database transaction does not automatically include a payment provider or warehouse API. A transactional outbox can durably record downstream work with the order, but delivery may repeat. Consumers need their own deduplication or reconciliation strategy.

Bound retries and give uncertainty somewhere to go

An idempotency key does not make every failure retryable. Follow the provider’s documented error semantics. Validation failures usually require a corrected request; throttling or temporary unavailability may permit another attempt.

For retryable failures:

  • Set both an attempt limit and an overall elapsed-time budget.
  • Use capped exponential backoff with jitter to spread attempts.
  • Honor documented server retry guidance, including Retry-After where applicable.
  • Coordinate retry ownership so nested clients and workers do not multiply attempts.

When the budget expires, preserve the operation identity and mark the outcome as unresolved. Use a documented status lookup or reconciliation process to establish whether the order exists before allowing another logical submission.

If the provider has no idempotency contract or reliable lookup, retries on writes may require manual review. A correlation field helps investigation, but does not itself prevent duplicates.

Define retention, replay, and downstream limits

Idempotency records cannot always live forever. Document how long they remain valid and align that window with client retries, delayed jobs, and operational recovery. Once a record expires, the same key may no longer protect against duplicate creation.

Define what replay returns: the original creation result, a stable resource reference, or another documented representation. Also define which failure outcomes are retained and which allow another attempt. Clients should not have to infer these rules from status codes.

This is not an exactly-once guarantee. It is a bounded contract that suppresses repeated effects within stated limits. Order creation, payment processing, and fulfillment each need an appropriate business invariant and recovery path.

A reusable review checklist

Before enabling automatic retries on a write, confirm:

  • Identity: Does one logical operation retain one key across restarts and redelivery?
  • Scope: Are tenant, authorization, and operation boundaries enforced?
  • Intent: Does key reuse with changed content produce an explicit conflict?
  • Atomicity: Can concurrency or a crash separate the business write from its durable identity?
  • Recovery: Can pending operations be investigated without starting duplicate work?
  • Policy: Are retryable failures, backoff, budgets, and retention documented?
  • Downstream effects: Can repeated delivery duplicate payment, fulfillment, or notifications?

A useful next step is a controlled test: commit a test order, interrupt its response, then retry with the original key. Check both the returned result and downstream business records. A successful HTTP response alone does not establish that duplicate work was avoided.

For related investigation practices, browse the related DOAAS engineering guidance. GhostImpact helps understand API changes, map producer-to-consumer dependencies, and investigate potential downstream impact; those dependencies can help identify which consumers need retry-contract checks.

Explore GhostImpact.