Problem
Networks fail, rate limits apply, and services hiccup. Agents that retry blindly cause duplicate orders; agents that never retry abandon tasks unnecessarily.
Context
Use this pattern when:
- Actions may time out without a clear outcome.
- The product applies rate limits or depends on services that fail transiently.
Recommended solution
Accept an idempotency key on every state-changing action and return the original result when a key is reused. Mark errors as retryable or not, provide Retry-After for rate limits and temporary failures, and document the recommended backoff.
- 01Require or accept Idempotency-Key headers on mutations.
- 02Store results by key for a documented window.
- 03Return Retry-After on 429 and 503 responses.
- 04Mark each error code as retryable or not.
Interaction diagram
Example implementation
Illustrative exampleExamples use a fictional store and illustrative field names. Adapt the shape to your stack; the qualities matter more than the exact format.
async function callWithRetry(action: string, input: unknown, key: string) {
for (let attempt = 0; attempt < 4; attempt++) {
const res = await fetch(`/actions/${action}`, {
method: "POST",
headers: { "Idempotency-Key": key, "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (res.ok) return res.json();
const problem = await res.json();
if (!problem.retryable) throw problem;
const wait = Number(res.headers.get("Retry-After") ?? 2 ** attempt);
await new Promise((r) => setTimeout(r, wait * 1000));
}
throw new Error("Retries exhausted");
}Accessibility and security
Accessibility
- When retries are exhausted, report the failure to the person with the last error message, not a generic notice.
Security
- Scope idempotency keys to the caller so one agent cannot replay another's request.
- Rate-limit per grant to contain runaway agents.
Related patterns
FeedbackError ReportingReturn errors with stable codes, precise causes, retry guidance, and suggested next actions.RecoveryRollbackProvide compensating actions so completed steps can be undone when a later step fails.InteractionStructured ActionsDefine each action as a contract with a name, typed input, preconditions, effects, and result.
Applies the principles Predictable Actions and Graceful Failure.