Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Idempotency Matters More Once an LLM Can Cause Side Effects

A timeout does not prove a tool write failed. This article designs idempotency keys, durable operation records, request hashing, and unknown-outcome recovery so retries cannot accidentally repeat real-world side effects.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#idempotency#retries#distributed-systems#postgresql#tool-calling#typescript#python
On this page

The dangerous retry is the one that follows an ambiguous success.

An agent calls send_invoice. The downstream service creates the invoice, but the response is lost during a network timeout. The agent sees an error and tries again.

Now the customer has two invoices.

This is not an LLM-specific failure. Distributed systems have always had the problem that a caller can lose the response after a server commits a write. Agents make it easier to trigger because retries can happen at several layers: HTTP client retries, tool wrapper retries, workflow replay, model self-correction, or a user pressing “try again.”

Once an LLM can trigger side effects, I want idempotency to be a property of the tool contract rather than a suggestion in the prompt.

The example here is an invoicing assistant that can create and send customer invoices. The same design applies to email, refunds, CRM updates, provisioning, deployment actions, and most writes where “do it twice” is meaningfully different from “do it once.”

Define the logical action before the request attempt

An idempotency key should identify one *business action*, not one HTTP request.

If the workflow decides “create the April invoice for account A-91,” retries of that same decision reuse the same key.

TypeScript
type CreateInvoiceCommand = {  accountId: string;  billingPeriod: string;  lineItems: Array<{    sku: string;    quantity: number;    unitPriceCents: number;  }>;};​type IdempotentCommand<T> = {  idempotencyKey: string;  payload: T;};

The key can be generated when the workflow creates the action node:

TypeScript
import { randomUUID } from "node:crypto";​const command: IdempotentCommand<CreateInvoiceCommand> = {  idempotencyKey: randomUUID(),  payload: {    accountId: "A-91",    billingPeriod: "2026-04",    lineItems,  },};

Do not generate a new key inside every retry loop. That defeats the mechanism.

Store idempotency before performing the side effect

A simple operation table is enough to explain the design:

SQL
CREATE TABLE idempotent_operations (  tenant_id TEXT NOT NULL,  idempotency_key TEXT NOT NULL,  request_hash TEXT NOT NULL,  status TEXT NOT NULL CHECK (status IN ('started', 'completed', 'failed')),  result_json JSONB,  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),  PRIMARY KEY (tenant_id, idempotency_key));

The first caller claims the key. Later callers either wait, return the completed result, or detect that the key was reused incorrectly.

The request_hash is important. Without it, a buggy agent can reuse the same key for different arguments and receive the result of an unrelated operation.

Canonicalize and hash the request

The hash needs stable serialization.

TypeScript
import { createHash } from "node:crypto";​function canonicalJson(value: unknown): string {  if (Array.isArray(value)) {    return `[${value.map(canonicalJson).join(",")}]`;  }​  if (value && typeof value === "object") {    const entries = Object.entries(value as Record<string, unknown>)      .sort(([a], [b]) => a.localeCompare(b))      .map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`);​    return `{${entries.join(",")}}`;  }​  return JSON.stringify(value);}​function requestHash(value: unknown): string {  return createHash("sha256")    .update(canonicalJson(value))    .digest("hex");}

For production code I would use a well-tested canonicalization format/library where interoperability matters rather than casually inventing one. The point is that semantically identical request objects should not hash differently because object keys arrived in another order.

Claim the key atomically

The race to avoid is two workers checking “does this key exist?”, both seeing no row, and both creating the invoice.

Use a unique constraint and atomic insert.

TypeScript
async function claimOperation(input: {  tenantId: string;  key: string;  hash: string;}): Promise<"claimed" | "existing"> {  const inserted = await db.query(    `INSERT INTO idempotent_operations       (tenant_id, idempotency_key, request_hash, status)     VALUES ($1, $2, $3, 'started')     ON CONFLICT DO NOTHING     RETURNING idempotency_key`,    [input.tenantId, input.key, input.hash],  );​  return inserted.rowCount === 1 ? "claimed" : "existing";}

If the row already exists, load it and compare the hash.

TypeScript
if (existing.requestHash !== hash) {  throw new Error("Idempotency key was reused with different arguments");}​if (existing.status === "completed") {  return existing.result;}

The started state needs more thought because it may represent a currently running request or a crashed worker.

Keep the actual write behind the same operation record

For a database-local side effect, you can often make the idempotency record and domain write part of one transaction.

TypeScript
async function createInvoiceIdempotently(  tenantId: string,  command: IdempotentCommand<CreateInvoiceCommand>,): Promise<Invoice> {  const hash = requestHash(command.payload);​  return db.transaction(async (tx) => {    const operation = await tx.lockIdempotentOperation(      tenantId,      command.idempotencyKey,      hash,    );​    if (operation.status === "completed") {      return InvoiceSchema.parse(operation.resultJson);    }​    const invoice = await tx.invoice.create({      tenantId,      ...command.payload,    });​    await tx.completeIdempotentOperation(      tenantId,      command.idempotencyKey,      invoice,    );​    return invoice;  });}

This prevents a database commit where the invoice exists but the operation record does not.

External APIs are harder because there is no shared transaction.

Pass idempotency downstream when the provider supports it

If a payment, email, or provisioning API supports idempotency keys, pass the logical key through.

TypeScript
await paymentClient.refund({  paymentId,  amountCents,  idempotencyKey: command.idempotencyKey,});

Now both your workflow and the downstream service understand that retries refer to the same logical action.

If the downstream service does not support idempotency, your local dedupe record can prevent *your* system from deliberately submitting twice, but it cannot fully solve the “remote committed, response lost” ambiguity.

In that case, look for a queryable operation ID, unique business key, or post-write reconciliation API.

Model unknown outcomes explicitly

After a timeout, do not immediately mark the operation failed if the remote side may have committed it.

Use a state that tells the workflow what it actually knows.

TypeScript
type OperationState<T> =  | { status: "not-started" }  | { status: "in-progress" }  | { status: "completed"; result: T }  | { status: "failed"; error: string }  | { status: "unknown"; externalOperationId?: string };

An unknown state should trigger reconciliation before retry.

For an email provider, search by your message/reference ID. For a deployment, inspect the deployment operation. For an invoice, query by a unique invoice request key.

“Timeout” describes the caller's observation. It does not describe the server's state.

Python service pattern

Python
from dataclasses import dataclassfrom enum import Enum​class OperationStatus(str, Enum):    STARTED = "started"    COMPLETED = "completed"    FAILED = "failed"    UNKNOWN = "unknown"​@dataclass(frozen=True)class IdempotentCommand:    key: str    payload: dict[str, object]​async def execute_idempotently(    *,    tenant_id: str,    command: IdempotentCommand,    repository,    perform,):    payload_hash = hash_payload(command.payload)    operation = await repository.claim_or_get(        tenant_id=tenant_id,        key=command.key,        payload_hash=payload_hash,    )​    if operation.payload_hash != payload_hash:        raise ValueError("Idempotency key reused with different payload")​    if operation.status is OperationStatus.COMPLETED:        return operation.result​    if operation.status in {OperationStatus.STARTED, OperationStatus.UNKNOWN}:        reconciled = await repository.try_reconcile(operation)        if reconciled is not None:            return reconciled​    result = await perform(command)    await repository.complete(tenant_id, command.key, result)    return result

The unresolved pieces—hash_payload, repository behavior, reconciliation—are dependencies because their correct implementation depends on the database and side effect. The business flow is still explicit and testable.

Use deterministic keys when the business action is naturally unique

Random UUIDs work when the workflow persists and reuses them correctly.

Sometimes the domain gives you a better key.

For example:

Text
invoice:{tenantId}:{accountId}:{billingPeriod}

If the business rule says there must only ever be one monthly invoice of this type, a deterministic key prevents duplicate logical actions even if two separate agent runs independently decide to create it.

Be careful: deterministic keys encode business uniqueness. Do not use them when two legitimate actions can share the same fields.

Idempotency is scoped

An idempotency key such as abc123 should not collide across every customer in a multi-tenant system.

I usually scope uniqueness by tenant and often by tool/action:

Text
(tenant_id, action_name, idempotency_key)

That also makes authorization easier to reason about because a result from one tenant can never satisfy a request in another.

Keep approval separate from the key

A human-approved write should preserve the exact arguments that were approved.

One useful record is:

TypeScript
type ApprovedAction = {  approvalId: string;  idempotencyKey: string;  requestHash: string;  approvedBy: string;  approvedAt: string;};

At execution time, recalculate the request hash. If the agent changed the amount, recipient, or other relevant arguments after approval, the approval no longer matches.

The idempotency key prevents duplicate execution. The request hash binds execution to the approved action.

Replay needs the same key

Durable workflows frequently resume from checkpoints after a worker crash.

If the checkpoint says “next step: send invoice,” but the process crashed immediately after sending and before writing the next checkpoint, replay may attempt the step again.

The only safe design is for the step itself to be idempotent and to reuse the same persisted key during replay.

Checkpointing without idempotent side effects can make recovery *more* dangerous because it creates deliberate re-execution.

A retry policy should know whether a tool is idempotent

I classify tool writes:

TypeScript
type SideEffectPolicy =  | { kind: "read-only" }  | { kind: "idempotent-write"; requiresKey: true }  | { kind: "non-idempotent-write"; retryAutomatically: false };

A generic retry wrapper can then refuse to automatically retry a non-idempotent write.

The model should not decide this dynamically based on whether retry “seems safe.” The tool contract already knows its semantics.

Test the lost-response case

The most important idempotency test is not “send the same request twice after success.”

It is:

  1. tool receives request with key K;
  2. side effect commits;
  3. test drops the response or crashes the worker before completion is observed;
  4. workflow retries with K;
  5. exactly one side effect exists;
  6. the recovered result is returned.

Also test concurrent duplicate requests racing on the same key and key reuse with a different payload.

Those are the cases that expose whether the uniqueness and transaction boundaries are real.

When idempotency is unnecessary

Pure reads do not need idempotency keys. Deterministic calculations do not need a dedupe table. Some updates are naturally idempotent: “set feature flag to false” can often be repeated safely, although audit/events around it may still need care.

The machinery belongs around side effects where duplicate execution matters and retries/replay are plausible.

Agents increase both conditions.

Once a model can make writes, the tool layer needs to answer a distributed-systems question before the first retry happens: if we are unsure whether the previous attempt committed, how do we know that trying again will not do it twice?

A prompt cannot provide that guarantee. A durable idempotency boundary can.

KEEP READING

Related engineering notes