This guide was prepared with AI assistance using the linked documentation. Code examples are illustrative; verify them against your environment and current API documentation before use.
An agent asks a service to create a support ticket. The request reaches the service, the ticket is saved, and the response disappears on the way back. From the agent’s point of view, the call timed out. If it creates the ticket again with a new identity, the customer may receive two tickets and two notifications.
The fix is not “retry everything.” The application needs to distinguish a known failure from an unknown outcome, identify one intended action across attempts, and reconcile with the system that actually performed it. Only then can a retry policy make a workflow more reliable without multiplying side effects.
This guide follows a ticket-creation workflow through durable operation records, provider idempotency, bounded backoff, worker crashes, and operator recovery. The same ideas apply to payments, bookings, emails, and account updates, but each provider has different contracts. Code examples are illustrative and call out where storage, credentials, and provider behavior must be supplied by your application.
The short answer
For every side-effecting agent action, create a stable operation ID on the server before making the external call. Store the intended action and its current state durably. Reuse the same operation ID for retries when the downstream provider supports that behavior, and check the provider’s documented retention and lookup rules. If the result is uncertain and no safe lookup or idempotency mechanism exists, stop automatic execution and send the case for reconciliation.
Use exponential backoff with jitter only for failures that are both likely to be transient and safe to retry. Set a maximum number of attempts and a total deadline. A timeout tells you the caller stopped waiting; it does not prove that the remote system stopped working.
Follow one request through the failure
Suppose a customer says, “Open a ticket for the printer that stopped working.” The model proposes create_ticket with a title and description. The application validates the request, assigns operation ID op_91, records the intended action, and calls the ticket provider using that identifier as an idempotency key if the provider supports one.
Now the connection drops. There are several plausible outcomes:
- The request never reached the provider.
- The provider received the request but rejected it before creating a ticket.
- The provider created the ticket, but the response was lost.
- The provider is still processing the request.
The caller cannot infer which outcome occurred from a timeout alone. A second request with a new operation ID may create a duplicate in the third or fourth case. Repeating the same request with the same key can be safe only if the provider’s idempotency contract covers the operation and the key is still within its retention window.
The user interface should reflect that uncertainty. “We’re checking whether the ticket was created” is honest. “Ticket created” is premature, while “creation failed” may prompt the user to submit a second request. Once reconciliation confirms the provider’s result, show the ticket identifier or an actionable failure.
Separate the user’s intent from individual attempts
One user intent may require several network attempts. The durable operation represents the intent: create one ticket with a particular payload for a particular account. An attempt records one interaction with the provider. Keeping these concepts separate makes it possible to see that three HTTP calls were attempts to complete one action, not three independent tickets.
A useful operation record contains an opaque operation ID, tenant and actor IDs from authenticated context, action type, normalized request hash or versioned payload reference, state, timestamps, provider reference when known, and a retry or reconciliation deadline. Attempt records can contain a sequence number, start and finish times, status class, and a sanitized error category. Avoid recording access tokens or full sensitive ticket contents in a broad operational log.
Generate the operation ID on a trusted server. Do not let the model invent a new identifier each time it wants to repeat an action. If the user deliberately creates a second, distinct ticket, allocate a new operation ID and make that distinction visible in the product. A retry after a lost response should keep the original ID.
Operation identity does not authorize an action. The server still checks the user’s permission, the target account, and any review requirements. A key prevents certain duplicates only within the boundaries the application and provider actually enforce.
Classify failures before scheduling a retry
Not all errors have the same meaning. A malformed request will usually fail again until the payload changes. A permission denial needs an access decision or credential repair, not an infinite loop. A temporary rate limit may be retryable after a delay, provided the operation itself is safe to repeat. A network timeout during a write may be ambiguous.
| Observation | Likely next step | What to verify |
|---|---|---|
| Invalid input reported before processing | Stop and correct the request | The provider’s validation guarantees |
| Authentication or permission denied | Stop and investigate access | Whether the same credentials can ever succeed |
| Rate limit or temporary capacity error | Retry only if safe, after the provider’s delay | Retry-After, attempt budget, and idempotency |
| Connection fails before send is known to begin | Retry if your client can establish no request was sent | How the client exposes connection failures |
| Timeout after a write may have been sent | Mark outcome unknown and reconcile | Provider lookup and idempotency contract |
| Provider confirms success | Persist result and stop | Provider identifier and operation match |
| Provider confirms permanent business failure | Stop and report the result | Whether any partial effect occurred |
The table is a design starting point, not a universal mapping from status code to policy. A 500 might be returned before or after a provider begins execution. A 429 does not magically make an unprotected write safe to repeat. Read the provider’s documentation and test the exact operation.
Google Cloud’s retry guidance distinguishes retryable responses from idempotency conditions and warns against retrying permanent errors or non-idempotent operations unconditionally. That guidance describes Cloud Storage; use your own provider’s rules for the final decision.
Persist the operation before the side effect
An in-memory variable disappears if a process restarts. Store the operation before dispatching the external request so another worker can determine what was intended and whether it has already been claimed. Use a unique constraint on the operation identity, scoped appropriately for your tenants and action types.
The following PostgreSQL sketch illustrates the shape of the data. It is not a complete migration: production code needs foreign keys, access controls, retention, and an application-specific payload design. It deliberately stores an opaque payload reference instead of assuming sensitive ticket text belongs in a general-purpose operations table.
CREATE TABLE agent_operation (
operation_id uuid PRIMARY KEY,
tenant_id uuid NOT NULL,
actor_id uuid NOT NULL,
action_type text NOT NULL,
payload_hash text NOT NULL,
payload_ref text NOT NULL,
state text NOT NULL CHECK (state IN (
'pending', 'executing', 'succeeded', 'failed', 'unknown'
)),
provider_ref text,
attempt_count integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);The hash must be computed from a stable, canonical representation of the intended parameters. Naively hashing JSON text can produce different hashes for equivalent objects with different key ordering. Define normalization, character encoding, and versioning explicitly. If the payload changes materially, reject reuse of the existing operation ID and create a separately authorized operation when appropriate.
Keep the payload available for the period needed to retry or investigate, subject to your retention policy. A hash alone cannot reconstruct a request. Conversely, storing the complete payload indefinitely may expose information you no longer need. The right design depends on privacy requirements and the provider’s recovery window.
Model uncertainty as a state
The operation should not jump directly from “request sent” to “success.” A compact state model can make recovery decisions explicit:
Loading diagram…
pending means the application has a durable intent but has not confirmed dispatch. executing means a worker has claimed the operation; it does not prove the provider received anything. succeeded requires evidence from the provider or a reliable reconciliation query. failed means the service has enough evidence that the intended effect did not occur and will not occur under that request. unknown covers ambiguous results. manual_review is appropriate when automation cannot establish the outcome safely.
State names alone do not enforce correctness. Define allowed transitions in code, store the reason for each transition, and use transactions or conditional updates to prevent concurrent workers from taking incompatible actions. Decide who can move an operation out of unknown, what evidence they must record, and whether the user needs an update.
A worker that dies while holding executing needs a recovery path. A lease can identify work that has not been renewed, but an expired lease does not mean the remote action failed. The replacement worker must reconcile the original operation or safely retry with the same provider-supported key. Lease expiry is a scheduling signal, not a verdict about the external side effect.
Understand what an idempotency key promises
An idempotency key lets a provider recognize repeated requests as the same intended operation, within the provider’s documented scope and retention period. Providers differ in which endpoints support keys, how they compare parameters, whether they cache errors, and how long they retain records. Some support a lookup by client reference; others do not.
Stripe’s idempotent request reference is a useful concrete example, not a universal specification. For its API v1, Stripe describes storing the first response after endpoint execution begins, returning the stored result for later requests with the same key, comparing parameters, and permitting keys to be pruned after they are at least 24 hours old. Its API v2 behavior is described separately. Recheck the current documentation for the endpoint and API version you use.
That retention detail matters. If your worker wakes after a provider has forgotten the key, blindly resending may create a new operation. Reconcile by a durable provider reference or other documented lookup before retrying. If you cannot determine the result, require a person to resolve it. Keep the original payload and operation ID available long enough to perform that investigation.
Do not put customer email addresses, order numbers, or other sensitive values directly in keys when an opaque random ID will work. Do not reuse a key with different parameters. The application should reject that conflict even if a downstream provider also checks it. Conversely, a deliberately new action needs a new key; suppressing every similar request forever would block legitimate work.
Create and claim work atomically
Two workers can pick up the same pending operation at nearly the same time. If both send a write before either records success, a local “check then act” sequence is insufficient. Use the database’s concurrency controls to claim the operation atomically, and use provider-side idempotency as a separate layer where available.
This PostgreSQL example demonstrates a conditional claim. The application must check whether a row was returned. It omits leases and recovery metadata for clarity; a real worker needs both, along with transaction boundaries and appropriate indexes.
UPDATE agent_operation
SET state = 'executing',
attempt_count = attempt_count + 1,
updated_at = now()
WHERE operation_id = $1
AND state = 'pending'
RETURNING operation_id, tenant_id, action_type, payload_ref, attempt_count;If the update returns no row, do not dispatch the write from that worker. Another worker may have claimed it, or the operation may already be complete. Query its state through an authorized service if the caller needs an update.
The atomic claim does not create a transaction with a remote ticket provider. A process can crash after the provider accepts the request but before the local database records success. That gap is why idempotency and reconciliation remain necessary. Do not describe a local database transaction as an exactly-once guarantee across independent systems.
Use an outbox when a database change must trigger a message
Consider an application that saves an operation and publishes a queue message. If the database commit succeeds but publishing fails, the worker never sees the task. If publishing succeeds but the database transaction rolls back, the worker may act on an operation that does not exist. This is the dual-write problem.
A transactional outbox writes the business record and an event record in the same database transaction. A separate dispatcher reads committed outbox rows and publishes them. The consumer must still handle duplicate messages because the dispatcher can crash after publishing but before marking an event as sent. AWS describes the pattern and its duplicate-message implications in its transactional outbox guidance.
For the ticket workflow, the event might contain only an operation ID and event ID. The worker loads the authorized payload from the application’s store. It records processed event IDs or uses the operation’s conditional claim to prevent redundant processing, while still following the provider’s rules for a repeated external call.
An outbox is not necessary for every application. A small service may use a database-backed worker that directly polls pending operations. Choose the simplest mechanism that provides durable work, bounded concurrency, and observable recovery for your deployment. Whichever mechanism you choose, test a crash at each boundary between storage, queueing, and the external provider.
Design the retry budget before writing a loop
A retry budget has at least four parts: which errors qualify, how many total attempts are allowed, how long the whole operation may take, and how long to wait between attempts. Clarify whether a configuration value counts total attempts or only retries. An initial request plus three retries is four attempts.
Check the SDK’s own retry behavior. If your HTTP library makes three attempts, your worker retries the whole call three times, and the queue delivers the job twice, the provider may see up to eighteen attempts. The exact count depends on the configuration, but the multiplication is real. Prefer one clearly owned retry layer or coordinate budgets across layers.
Set an overall deadline that reflects the user experience and the downstream operation. A user waiting for a search result may need a quick failure. A background reconciliation job can wait longer, provided the UI shows pending status and the operation remains within the provider’s idempotency window. Never let an agent keep retrying a permanent authorization error until its token budget or timeout happens to run out.
Add exponential backoff and jitter
Exponential backoff increases the delay between eligible attempts, up to a cap. Jitter adds randomness so many workers do not retry at the same instant after an outage. This can reduce a retry surge, but it does not make an unsafe write safe. First establish the operation’s retry eligibility and idempotency behavior.
Here is a small full-jitter delay function. It returns a delay between zero and a capped exponential ceiling. The example is deterministic when a test supplies a fixed random function; it does not send requests or choose which errors are retryable.
export function retryDelayMs(
retryIndex: number,
baseMs = 250,
capMs = 5_000,
random = Math.random
): number {
if (!Number.isInteger(retryIndex) || retryIndex < 0) {
throw new Error("retryIndex must be a non-negative integer");
}
if (baseMs <= 0 || capMs <= 0) throw new Error("delays must be positive");
const ceiling = Math.min(capMs, baseMs * 2 ** Math.min(retryIndex, 30));
return Math.floor(random() * ceiling);
}With a base of 250 milliseconds, the first retry has a ceiling of 250 milliseconds, the second 500, and the third 1,000, until the configured cap applies. The actual value varies. Use a bounded attempt count and deadline in the calling code. Treat a provider-supplied Retry-After according to that provider’s documentation and your deadline; do not retry sooner than instructed merely because a random delay was shorter.
The AWS Builders’ Library discussion of timeouts, retries, and backoff explains why synchronized retries can add load during an incident. Many SDKs already implement a suitable strategy. Review and configure the built-in behavior before adding another loop around it.
Keep reads and writes on different paths
A read-only lookup can often be retried without creating a duplicate external action, but it can still be expensive, rate-limited, or sensitive. A repeated search may also return different data if the source changes. Decide whether the user needs a consistent snapshot or simply the latest answer, and avoid displaying stale results as current without context.
A write needs a stronger contract. Creating a ticket, sending an email, changing a booking, or issuing a refund may have consequences outside your database. Some writes are naturally conditional: for example, “set status to closed if version is 7.” Others are not: “send another email” remains a new side effect even when the message body is identical. Classify each operation by what the downstream service actually guarantees.
For a multi-step workflow, track each side effect separately. If an agent creates a ticket and then sends an email, a retry of the entire workflow must not create a second ticket merely because the email failed. Store the successful ticket reference, resume from the failed step when safe, and use a distinct operation identity for the email. Do not assume every provider supports deduplication for every action.
Reconcile an unknown outcome
Reconciliation asks the system of record what happened to the original operation. The best mechanism depends on the provider: a lookup by idempotency key, a client reference attached to the created resource, an operation-status endpoint, a webhook, or a search with documented consistency guarantees. Record which method you use and what evidence is sufficient to mark the operation complete.
Start with the strongest available identifier. Searching for “a ticket with the same title created today” can produce false matches, particularly when two customers report the same problem. If the provider’s search is eventually consistent, absence immediately after a timeout does not prove the operation failed. Wait and retry the lookup within a bounded window, following the provider’s documented consistency behavior.
If the provider returns a matching ticket, store its provider ID and transition the operation to succeeded. If it confirms that the original request definitively failed without side effects, transition to failed or retry according to policy. If it cannot answer, preserve unknown and route the case to an operator. A manual investigation may involve the provider’s dashboard or support team, but it should not require guessing from the model’s narrative.
Webhooks can help resolve an uncertain state, but they may be delayed, duplicated, or delivered out of order. Verify signatures according to the provider’s instructions, deduplicate event IDs, and compare the event against the operation it claims to describe. Protect against a late webhook incorrectly overwriting a newer confirmed state.
Keep the user informed without making promises
Expose meaningful states in the interface: pending, checking, completed, failed, and action needed. A user should not need to interpret an HTTP status code. When a ticket is confirmed, show its identifier and link if available. If an operation needs review, explain what will happen next and avoid encouraging the user to repeat the same action blindly.
For a long-running operation, a status endpoint or notification can update the user when the result is known. Ensure the endpoint authorizes access to the operation’s tenant and actor. An opaque operation ID is useful, but possession of an ID alone should not grant access to private ticket details.
The assistant’s final text must derive its status from the application record, not from its own expectation. If the tool returns unknown, the model may explain that the application is checking. It must not invent a ticket number. If an operation succeeds after the conversation has ended, the application can provide a later update through a channel the user has authorized.
Test the boundaries where failures happen
Happy-path tests prove that a ticket can be created when all systems respond. Reliability tests ask what happens when the response is lost, a worker stops, or the same message arrives twice. Use synthetic accounts and a fake provider that can pause at controlled points. Record the number of external side effects and the final operation state.
| Test | Injected condition | Expected result |
|---|---|---|
| Response lost | Provider creates ticket, then connection drops | Operation becomes unknown and resolves to one ticket |
| Duplicate job | Queue delivers the same operation twice | One worker claims it; provider sees no unsafe duplicate |
| Process crash | Worker stops after provider acceptance | Recovery reconciles the original operation |
| Parameter mismatch | Same operation ID arrives with changed payload | Request is rejected for review |
| Expired provider key | Retry occurs after documented retention | No blind resend; reconcile or request manual review |
| Permanent denial | Provider rejects credentials | Stop retries and surface an actionable error |
| Throttling | Provider returns a retry delay | Respect delay and remaining budget |
| Duplicate webhook | Same signed event arrives twice | One durable state transition |
| Late webhook | Old failure arrives after confirmed success | Do not overwrite newer verified state |
| User repeats submit | Browser resends the original intent | Reuse the known operation when the client contract identifies it |
Test a legitimate second request too. A deduplication rule that blocks all tickets with the same title can silently lose real work. The operation ID should represent the user’s intent, not a broad guess that similar text must be a duplicate.
A runnable check for the delay helper
The following assertions exercise the pure delay function using fixed random values. They do not test a real timer or a provider. Add them to your project’s TypeScript test runner and adjust the import path to match your module configuration.
import assert from "node:assert/strict";
import { retryDelayMs } from "./retry-delay.js";
assert.equal(retryDelayMs(0, 250, 5_000, () => 0), 0);
assert.equal(retryDelayMs(1, 250, 5_000, () => 0.5), 250);
assert.equal(retryDelayMs(8, 250, 5_000, () => 0.5), 2_500);
assert.throws(() => retryDelayMs(-1));For integration tests, fake time where your test framework supports it and inject the provider client. Assert that permanent errors do not schedule another attempt and that the total deadline stops a retry even if the nominal attempt count has not been reached. Verify that the same idempotency key and normalized parameters are used for every retry of one operation.
Include a test for cancellation. A user closing a browser tab may stop the UI from waiting, but it does not necessarily cancel a dispatched external write. The server must maintain the operation’s durable state and reconcile any uncertain result. If your product supports cancellation, define the point after which cancellation becomes a separate compensating action rather than pretending the original call never happened.
Observe the operation, not just the model conversation
Track counts and age of pending and unknown operations, attempts per operation, provider error categories, reconciliation outcomes, queue depth, and time from intent to confirmed result. Break down metrics by operation type and provider so a noisy search endpoint does not hide a failure in ticket creation. Avoid including customer content or personal identifiers in metric labels.
Alerts need an owner and a threshold that matches the workflow. A handful of unknown operations that are seconds old may be normal during a brief network interruption. Unknown operations that exceed the reconciliation window need investigation. A growing queue can indicate an outage, a stuck worker, or a retry storm; the dashboard should make those paths distinguishable.
Keep a protected audit trail with operation ID, actor, action type, transitions, provider reference, and reviewer or operator decisions where applicable. Record enough information to correlate an incident without storing credentials. Decide how long records are retained and who may inspect them. If a user-visible support reference is provided, make it an opaque identifier rather than a secret or raw customer data.
Plan for degraded providers
When a provider is unhealthy, unlimited retries can increase pressure on it and consume your own capacity. Pause or reduce new writes, apply concurrency limits, and use a circuit breaker or queue controls where appropriate. Keep the pending operation durable so work can resume after recovery without losing its original identity.
Separate automatic retries from manual replay. An operator should see the payload version, last attempt, provider reference, current state, and reason the previous result was uncertain. A replay button that silently creates a fresh operation ID can cause the very duplicate you are trying to prevent. Require a documented decision when the provider cannot establish whether the original action occurred.
Set an escalation route before launch. The on-call person needs to know where to inspect provider status, how to pause the worker, which records to preserve, and who owns the customer communication. If the provider’s idempotency retention is shorter than your outage window, the runbook must say what happens after that window expires.
Handle multi-step recovery deliberately
Some workflows have several systems: create a ticket, reserve a time slot, and send a confirmation. A database transaction cannot atomically cover all three external services. Treat the workflow as a sequence of separately tracked operations with explicit dependencies and recovery steps.
If ticket creation succeeds and slot reservation fails, the ticket may remain open for manual scheduling. If a slot is reserved but the confirmation email fails, retry the email only if its provider supports safe deduplication or the application can otherwise establish delivery state. A compensating action, such as cancelling a reservation, is itself another operation that can fail and may have policy consequences.
Do not promise a universal rollback. Decide which partial outcomes are acceptable, which need a human, and how the user will see them. This is the practical work behind a saga-style workflow: each step has an owner, a durable state, and a defined response to failure. A compensating action does not erase an email already read or guarantee that a customer never saw a provisional booking.
Common mistakes to avoid
Retrying every exception. Validation errors, permission denials, and permanent business failures are not fixed by repeated calls. Classify the error and account for the side effect before scheduling another attempt.
Creating a new key for every attempt. This tells an idempotent provider that each retry is a new operation. Keep the server-created key stable for the same intent and parameters, within the provider’s supported window.
Assuming a database lock covers a remote API. A local claim prevents two local workers from dispatching concurrently, but it cannot roll back an external action after a crash. Use provider support and reconciliation to bridge that gap.
Using a ticket title as the deduplication key. Two legitimate customers can report the same problem. Tie identity to an explicit operation, not to a loose similarity test on content.
Treating key retention as unlimited. Providers can remove old idempotency records. Store the retention deadline and switch to reconciliation or manual review when safe retry is no longer supported.
Ignoring nested retries. An SDK, worker, and queue can each retry independently. Document the combined attempt budget and test the number of calls the provider actually receives.
Marking a timeout as a definite failure. A response can be lost after success. Preserve the unknown state until the provider or an operator supplies evidence.
Frequently asked questions
Is an HTTP POST safe to retry?
It depends on the endpoint and the provider’s contract. Some POST operations support idempotency keys; others do not. A safe retry requires both a retryable failure and a guarantee that repeating the same intended operation will not create an unacceptable duplicate. Check the provider’s documentation and retention window.
Can the model choose the idempotency key?
The application should generate and persist the key from trusted server-side state. A model can propose an action, but its output may vary across retries and should not determine whether two external calls represent one authorized intent.
What if the provider has no idempotency support?
Look for a documented operation-status endpoint, a client reference, or another reliable way to establish the result. If there is no safe way to distinguish success from failure after a timeout, do not blindly repeat the write. Keep the operation unknown and send it for manual reconciliation.
Does exponential backoff prevent duplicate actions?
No. Backoff changes when retries happen. Idempotency and reconciliation address whether a repeated request can create an additional effect. You usually need both a safe retry contract and a bounded delay strategy.
Is an outbox an exactly-once delivery system?
An outbox makes the local business update and event record atomic in the same database transaction. The event may still be published or consumed more than once. Make the consumer and downstream operation resilient to duplicates and test the crash between publishing and marking the event sent.
How long should retries continue?
Choose a deadline based on the user experience, provider limits, cost, and documented idempotency retention. Short interactive reads and background reconciliation have different needs. Stop when the deadline or attempt budget is exhausted and expose a clear pending or action-needed state.
Launch checklist
- A server-generated operation ID represents one authorized intent.
- The intended parameters and current state are stored durably before dispatch.
- Reuse of an operation ID with different parameters is rejected.
- Concurrent workers claim work atomically and have a crash-recovery path.
- Retryable errors are defined per operation and provider.
- Attempt count, total deadline, backoff, jitter, and provider retry delays are documented.
- SDK, worker, and queue retry settings have one coordinated budget.
- Provider idempotency scope, parameter rules, and retention are recorded.
- Ambiguous outcomes enter an unknown state and have a reconciliation owner.
- Duplicate jobs, lost responses, expired keys, and delayed webhooks are tested.
- User-visible status comes from confirmed application state.
- Operators can pause execution, inspect evidence, and recover without generating a new intent accidentally.
For the related permission and approval boundary, see Secure AI Agent Function Calls. For a broader launch review, use the agent launch checklist with your application’s own policies.
Sources and further reading
- Stripe: Idempotent requests — endpoint-specific key behavior, parameter checks, and retention.
- Google Cloud: Retry strategy — retryable conditions, idempotency, backoff, and common anti-patterns for Cloud Storage.
- Amazon Builders’ Library: Timeouts, retries, and backoff with jitter — timeout selection and retry load.
- AWS Prescriptive Guidance: Transactional outbox pattern — durable event publication and duplicate handling.
- Amazon SQS: At-least-once delivery — why consumers of standard queues should handle duplicate messages.
