Idempotency Keys in Distributed Agent Operations
Stable per-step keys and tool-level enforcement stop agent retries from duplicating writes.

Idempotency keys in distributed agent operations must identify the actions a workflow is meant to take as well as the requests it sends. Agents use planning, tool retries, and queue redelivery in ways that can repeat external writes even when one API call is protected. Safe execution therefore needs infrastructure to provide stable per-step keys, durable records, and enforcement at tool boundaries.
Why agents have made idempotency a first-class infrastructure problem
Agent frameworks add another source of retries on top of systems that already expect repeated delivery. Their tool wrappers can retry operations on their own, while the tools may have been written for humans who rarely press the same button many times in a row. LangChain’s 2024 telemetry showed that tool calls grew from a tiny share of agent traces in 2023 to nearly a quarter by 2024, a rise of roughly 44×. Volume magnifies the exposure. Composition can turn those repetitions into duplicate effects.
Stripe retries undelivered webhooks for up to three days, AWS SQS standard queues document duplicate delivery as part of their contract, and HTTP retries are normal behavior. Agents inherit these conditions. Roy Fielding formalized idempotency for HTTP methods in RFC 2616 in 1999, which he co-authored, before his 2000 REST dissertation. RFC 7231 §4.2.2 restated the concept. Engineers now have to keep that property across autonomous workflows whose actions pass through several layers that each retry on their own.
How the agent retry surface stacks across layers
A planner may decide to send a follow-up email twice after losing intermediate state. A tool wrapper may retry on a 5xx response or timeout, while a queue consumer may rerun the operation after its visibility timeout expires. These retries do not share a single trigger. If the operation ID does not stay the same throughout the chain, one logical intent can lead to several external writes.
If the wrapper repeats a request with the same key, the downstream service can deduplicate it. If the planner instead reconstructs the whole step with a new key, that service sees a separate operation. The model introduces another source of variation because it can produce a subtly different tool call while pursuing the same intent. At millions of calls per day, even infrequent variation exposes non-idempotent operations downstream.
The diagnostic distinction is between decision quality and execution safety. A post-mortem that concludes “the agent acted weirdly” can miss a framework that instructed the agent to retry against a tool never designed for repetition. The failure is architectural. Better reasoning cannot give an operation a durable identity it lacks or make retry layers that act on their own agree on which work has already succeeded.
Why tools, not agents, must own idempotency
The agent’s non-determinism is useful for reasoning but unsuitable for enforcing whether an external action has already happened. An agent that reasons “I think I already charged this customer” offers a weaker guarantee than a record showing that a particular key returned success at a specific timestamp. Records replace inference at this boundary. The architectural rule is to keep enforcement outside the reasoning loop, where state machines can distinguish completed work from a new request.
That separation requires three cooperating layers. The agent runtime generates and maintains per-step keys from durable workflow state, using the workflow run ID, step index, and action type. On resume, it recovers the same identity. The tool execution layer checks the deduplication store, passes the key downstream, and caches results for as long as they are needed. The tool interface accepts the key and enforces deduplication itself, passes it to an external API, or uses it as a unique constraint for internal writes.
A double subscription charge incident illustrates why this structure is necessary. Stripe’s idempotency layer worked correctly, but the agent framework retried the whole sequence at the agent step, above the tool step where the key lived. The protected call was not the complete operation. The same separation fails if a key includes datetime.now(), because each retry acquires a fresh identity and bypasses the deduplication store. Correct enforcement at one boundary cannot compensate for changing identities above it.
Generating stable, deterministic idempotency keys at the workflow level
A replay-safe key is deterministic, derived from durable workflow state, and established before the first attempt. The workflow run ID, step index, and action type provide inputs that survive retries and process restarts. The runtime stores that identity before execution. Reconstructing the same key from unchanged durable inputs is safe, while creating a fresh key during a retry defeats deduplication. This distinction separates recovery of an operation’s identity from allocation of a new operation.
The two-phase reservation pattern enforces that identity under concurrent execution. First, an atomic insert-if-not-exists reserves the key as IN_PROGRESS, with the PRIMARY KEY constraint preventing another execution from proceeding under the same key. After processing, the record becomes COMPLETED and holds the response payload for future replays. For internal writes without native support, a dedicated deduplication table contains the key, run ID, step index, action type, cached result, and expiry. The constraint does the enforcement work.
External APIs with native idempotency support, including Stripe and PayPal, receive the deterministic key directly and return the original response when it is repeated. This protects the execute-then-log crash window, in which a worker receives success but dies before recording completion. The orchestration engine then sees unfinished work and replays it. Attempt B must use attempt A’s key. Local completion records alone cannot close this gap around an external effect.
PostHog’s October 2026 implementation provides a concrete reservation model. Its shared IdempotencyKeys store for CDP workflows holds caller-supplied keys in a dedicated Valkey instance, scoped by route and team. A route reserves its key before queueing work and receives one of five states. The reserved state permits queueing, while replayed returns the run already queued. The in_flight state means the first request has not finished queueing and the caller should retry. The conflict state identifies a key used for a different request, while unavailable leaves the route to decide whether to fail open or closed. A short reservation window precedes a longer period during which the key holds the run ID.
Extending idempotency across multi-step workflows with the saga pattern
A multi-step workflow may need retries after some steps have already succeeded. Reserving inventory, charging payment, and sending confirmation cannot be treated as one protected tool call when each step changes a different system. Distributed transactions take more coordination than production agent workflows can afford. Sagas instead use explicit compensation to reach eventual consistency. Each step therefore needs its own stable idempotency key and a compensating action to go with it.
The saga context supplies the identity for each action. An inventory reservation key combines the step name, order identifier, and product identifier, while a payment key combines the step name, order identifier, and attempt number. These are step-scoped keys. A retry must preserve the identity of the step being repeated. Otherwise, the saga orchestrator’s recovery behavior can create duplicate reservations, charges, or confirmations.
An inventory reservation is paired with releasing that reservation, a payment with issuing a refund, and a confirmation with sending a cancellation notice. If confirmation fails permanently, the executor compensates the completed steps in reverse order, refunding payment and then releasing inventory. Durable execution engines help manage how work is saved and retried. They do not replace per-step idempotency at the tool boundary, because replaying a correctly remembered step can still repeat an external effect.
TTL mismatches and other silent failure modes in production
Deduplication records cannot be retained forever, but their TTL must outlast the longest retry horizon of every delivery substrate in the chain. A queue redelivery after expiry reaches a store that no longer remembers the original operation. Deduplication has become a delay. Records for operations that trigger billing must be kept even longer.
Mutable context creates a less obvious version of the timestamp failure. A key may look deterministic within one attempt yet change between attempts because one of its inputs changed. The audit trail is what makes this failure diagnosable. It must show that the key was used, which attempt it resolved, and what cached response it returned. Without those records, incident response cannot reliably reconstruct whether repeated requests produced duplicate effects.
A workflow can record every key correctly and still leave customers in inconsistent states if it lacks compensation for permanent failure after partial success. Event consumption forms a separate boundary. Webhook replays and queue redelivery can reopen closed work unless handlers store processed event IDs. Write-layer idempotency does not automatically establish that the event initiating the write has already been consumed.
What idempotency requires from the software factory's infrastructure layer
Workflow-wide protection requires shared capabilities that individual tool implementations cannot establish alone. The platform must expose stable operation IDs, deduplication stores, and audit records as named, discoverable parts of its contract. An AI-ready internal developer platform describes idempotency at the same level as input and output schemas, authentication, authorization, error codes, operation status, and documentation. It is not an undocumented convention. Tool authors need a defined capability they can implement and callers can rely on.
An agent-initiated deployment shows how this contract intersects with authority. A deployment plan can contain the image, target, config diff, rollout method, and idempotency key, but the initiating agent also needs an identity and constrained permissions. Repetition safety is not permission safety. Without those constraints, prompt injection or credential failure at the agent layer can expose production infrastructure to unrestricted writes. The platform contract must cover both whether an action is allowed and whether a retry repeats its effect.
An agentic merge queue makes the operation identity concrete. When handling CI failures, merge conflicts, and queue management, it must treat each queue operation as an idempotent, auditable step. Re-queueing a PR on retry requires the original enqueue operation ID. IaC and GitOps apply a related principle through declarative, idempotent, version-controlled configuration, with reconciliation continuously enforcing the declared state. Repeated application is safe by design. A composable platform exposes the deduplication store, key schema, and audit log as components engineers can inspect and instrument.
Designing idempotency in at the loop-specification stage
Idempotency decisions belong in the loop specification because retry behavior determines the meaning of every state-changing step. The tool contract states whether the tool accepts keys natively, requires a deduplication table, or is naturally idempotent. That declaration belongs beside the input schema and authentication requirements. Retry bounds are likewise defined per step. The planner, wrapper, and queue substrate each need explicit limits that account for the other layers rather than silently inheriting unrelated framework defaults.
Duplicate charges, ghost orders, and fourteen-email onboarding escaped testing because those environments did not reproduce the network timeouts, worker restarts, and queue redelivery that expose unsafe repetition at scale. The strongest counterargument is that durable execution engines already handle much of the persistence and retry coordination. They do reduce the per-team burden. They also reduce the cases requiring keys, but the remaining cases include payments, state mutations, and external writes, where repeated effects have direct consequences.
The practical test belongs before production access is granted. For every tool call that mutates external state, can the step be replayed safely using the same idempotency key? The answer must come from a durable record. If it requires checking the agent’s reasoning about what happened earlier, the design is not production-ready.


