Idempotency for AI Agent Actions: Preventing Duplicate Side Effects
Prevent duplicate AI agent actions with stable intent identities, immutable request fingerprints, durable ledgers, and recovery for uncertain outcomes.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
Idempotency for AI agent actions means that repeating the same logical operation does not create additional intended effects. It matters because agents can retry a tool, resume a checkpoint, receive a duplicate event, or regenerate a plan after losing a response. Each of those paths can repeat an operation even when the model never explicitly decides to duplicate it.
The application needs a durable way to recognize the original intent. A prompt saying “do not create duplicates” cannot establish whether an external service already acted. This guide develops a hypothetical replacement-shipment workflow; its ledger, state names, and policies are proposed engineering designs rather than a tested reference implementation.
Separate logical intent from execution attempts
An execution attempt is a particular network request. A logical action is the business operation that those requests are trying to accomplish. One replacement shipment may require several attempts, but those attempts must retain the same action identity.
HTTP idempotence concerns the intended server effect of repeated requests. RFC 9110 identifies PUT, DELETE, and safe methods as idempotent, while cautioning against automatic retries of non-idempotent operations without additional knowledge. HTTP method selection alone does not establish the semantics of an agent's entire workflow. RFC 9110, section 9.2.2.
For our proposed support workflow, the application creates an action record after the replacement request has been validated and authorized. Its identity survives worker restarts, model changes, and tool retries. A run identifier can be attached for tracing, but a new run must not automatically create a new business action.
Do not deduplicate purely by payload. Two customers can legitimately request identical products, and one customer can legitimately receive two separate shipments. Equal arguments do not prove equal intent. Conversely, two model outputs with slightly different explanations can describe the same action. Identify intent in the business workflow, then validate the action's arguments against that identity.
Bind an action key to an immutable request
A proposed action envelope might contain:
{
"action_id": "act_example_724",
"action_type": "create_replacement_shipment",
"business_request_id": "replacement_example_19",
"schema_version": 2,
"payload": {
"order_id": "order_example_91",
"item_id": "item_example_6",
"quantity": 1,
"destination_version": 4
}
}
The executor obtains tenant and actor identity from trusted server context. The model does not choose those authority boundaries or manufacture a new action identifier whenever a call fails.
Calculate a fingerprint from a canonical representation of the validated action type, schema version, and effect-relevant payload. Define canonicalization explicitly: field order, missing versus null values, normalized identifiers, and numeric representation should not vary accidentally across workers. Exclude attempt timestamps and tracing identifiers, which legitimately change between retries.
Store both the fingerprint and enough protected request data to investigate mismatches. A hash is a comparison aid, not authorization and not a guarantee that sensitive inputs have become anonymous. Reject reuse of a key with different effect-relevant arguments. If the destination changes, require an explicit revised business decision instead of silently mutating the existing request.
AWS's idempotent API discussion describes caller-provided identifiers and rejecting parameter changes under an existing identifier. Its design also emphasizes the relationship between token recording and mutation atomicity. The envelope and fingerprint choices above are our illustrative application policy. Making retries safe with idempotent APIs.
Make the ledger authoritative under concurrency
A read-then-write check is insufficient. Two workers can both see no record and both dispatch the shipment request. Reserve the action using a storage operation that enforces uniqueness across concurrent writers.
For a PostgreSQL implementation, a composite primary key over tenant and action identity is one possible foundation:
-- Illustrative schema fragment; not a complete migration.
CREATE TABLE action_ledger (
tenant_id text NOT NULL,
action_id text NOT NULL,
request_hash text NOT NULL,
status text NOT NULL,
PRIMARY KEY (tenant_id, action_id)
);
PostgreSQL documents that composite uniqueness applies to the combination of columns; a primary key also requires non-null values. These properties can enforce one local action record. They do not make a remote shipping API part of the database transaction. PostgreSQL constraints.
In the proposed ledger, distinguish these outcomes:
| State | Known fact | Permitted handling |
|---|---|---|
| RESERVED | The action identity and immutable payload exist | One eligible executor may dispatch |
| IN_PROGRESS | Dispatch has started; completion is unresolved | Reconcile or wait; do not create another action |
| SUCCEEDED | Authoritative result is recorded | Return the recorded outcome to authorized callers |
| REJECTED | The operation was definitively refused without its intended effect | Report the refusal under the defined retry contract |
| OUTCOME_UNKNOWN | The service may have acted | Query external evidence or escalate |
Transitions need conditional writes or equivalent serialization. A lease may assign responsibility for investigating an action, but lease expiry is not proof that its remote effect never happened. A replacement worker inherits the uncertainty along with the action identity.
Put deduplication where the effect occurs
A local ledger cannot close every crash window around a remote API. Suppose the shipping service creates a shipment, then the worker crashes before storing the returned identifier. Another worker now sees an unfinished local record. Repeating the call without downstream protection can create another shipment.
Where supported, pass the same stable action key to the downstream service and preserve its contract. Otherwise use a service-specific lookup by durable business reference, or redesign the downstream operation to expose a verifiable identity. If neither is available, retain an unknown outcome and require reconciliation. A workflow that stops honestly is preferable to one that claims certainty it does not possess.
Provider contracts differ. Stripe's API v1 documentation says that once execution begins, the saved response for a key can include an error response; it also describes parameter comparison and key pruning. Its API v2 behavior differs. This is a useful warning to read the exact API and version contract rather than generalize one vendor's retry rules to every tool. Stripe idempotent requests.
Check whether a provider's key scope includes the account, endpoint, region, or another boundary. Record that scope alongside the action. Also distinguish an accepted job from a completed shipment: deduplicating job creation does not prove the job's later processing succeeded exactly once.
Walk through a response lost after shipment creation
Imagine a customer requests one replacement for a damaged item. The application authenticates the actor, verifies eligibility, binds the destination version, and creates act_example_724. The executor sends the replacement request using that identity.
The provider creates shipment S, but its response is lost. The tool returns an unknown-outcome classification rather than “failed.” The agent can explain that confirmation is pending, but cannot promise another shipment or declare that none exists.
A recovery worker reads the ledger and checks the provider using the original key or business reference. If the provider confirms S, the worker records S and returns the existing result. If a safe repeat is supported within the provider's contract, the worker repeats the same logical request with the same key. It never generates a fresh key merely to get past an error.
If the provider cannot establish the outcome, route the action for review with its original arguments, attempt history, and available evidence. Retry timing and deadlines remain separate controls; see agent retries and timeouts. Creating a second shipment and later canceling one is a compensating workflow with different risks, covered in compensating transactions.
Define retention and authorization together
Deduplication lasts only as long as the enforcing system remembers the operation. Set the application's maximum recovery horizon against the downstream retention contract. A locally remembered action does not make a pruned downstream key safe to reuse. After that boundary, reconcile by another authoritative identifier or stop for review.
Retain a minimal tombstone when appropriate: identity, fingerprint, final disposition, and a protected result reference may be sufficient after detailed payload data expires. Specify how delayed queue messages and restored backups interact with that tombstone. A deletion job must not silently turn an old retry into a new shipment.
Recheck authorization on duplicate requests. A cached success response might contain private information, and a caller whose access was revoked should not retrieve it merely by presenting a known key. Separate permission to observe a historical result from permission to initiate an effect. Deduplication prevents repetition; it does not grant authority.
Verify the crash windows and business invariant
Write the invariant first: one authorized replacement request produces no more than one intended shipment under the supported retry and retention contract. Then test sequences rather than only calling the endpoint twice.
- Deliver the same request concurrently to two workers and inspect external shipment count.
- Crash after reservation, after dispatch, after provider commit, and after local result recording.
- Reuse a key with changed quantity or destination and require an explicit mismatch.
- Retry after local or downstream retention expiry and verify the prescribed reconciliation path.
- Repeat with a different tenant, a revoked actor, or a stale worker lease.
- Return a provider error after an ambiguous effect and ensure the system does not mint a replacement identity.
Assert the external effects, ledger history, and user-facing statement together. A plausible final answer is not evidence that duplicate effects were prevented. Document unsupported failure modes explicitly rather than advertising an unqualified “exactly once” guarantee across systems you do not control.
Frequently asked questions
Can the model generate the idempotency key?
It can propose data, but the application should establish and persist the logical action identity. A model-generated value recreated after a retry can accidentally describe a new action. Keep identity creation in the trusted workflow.
Is a request-body hash enough?
No. Identical payloads can represent distinct legitimate intentions. Use a stable action identifier for deduplication and a payload fingerprint to detect inconsistent reuse of that identifier.
Does idempotency remove the need for compensation?
No. It limits repetition of one operation. A workflow can still complete one legitimate step and fail another, requiring a business-specific recovery or compensating action.
Source reference list
Related reading
- AI Agent Retries and Timeouts: Deadlines, Jitter, and Retry Budgets
Design AI agent retries around end-to-end deadlines, classified failures, jitter, shared budgets, and cancellation without multiplying unsafe side effects.
- Compensating Transactions for AI Agent Workflows
Design compensating transactions for AI agent workflows with recovery ledgers, explicit business reversals, uncertain outcomes, and irreversible boundaries.
- AI Agent Audit Logs: Provenance, Privacy, and Action Accountability
Design AI agent audit logs with trustworthy event producers, action provenance, durable delivery, tamper evidence, privacy controls, and investigation checks.