Coderhouse goes global

🌍

Read more

What Is Idempotency? How AI Engineers Make Agent Tool Calls Safe to Retry

AI Engineering

Build and ship real applications with LLMs, agents and automation.

8 weeks · Live online · View course →

Data Analytics

Go from zero to job-ready analyst with SQL, Python and BI tools.

10 weeks · Live online · View course →

Dan Patiño

AI Strategy & Innovation at Coderhouse

Artificial Intelligence

What Is Idempotency? How AI Engineers Make Agent Tool Calls Safe to Retry

What Is Idempotency? How AI Engineers Make Agent Tool Calls Safe to Retry

Idempotency is the property of an operation that produces the same result whether it runs once or many times. In AI engineering, an idempotent tool call or API request can be safely retried after a timeout, a crash or a duplicate event without charging a customer twice, sending the same email twice or creating two tickets for one problem.

It matters because AI agents retry a lot. Models call tools in loops, networks drop connections, LLM providers return rate-limit errors and webhook senders deliver the same event more than once. If the actions behind those calls are not idempotent, every retry becomes a potential duplicate side effect in a real business system.

Idempotent vs safe vs non-idempotent operations

HTTP gives a useful vocabulary. The HTTP Semantics specification (RFC 9110) defines GET, HEAD, PUT and DELETE as idempotent methods, while POST is not idempotent by default.

  • Safe operations only read data, such as looking up an order status. Repeating them changes nothing.

  • Idempotent operations may change data, but repeating them leaves the same final state. "Set ticket status to closed" is idempotent: closing a closed ticket keeps it closed.

  • Non-idempotent operations change state every time. "Create a refund", "append a note" or "send a message" produce a new side effect on each call.

Most valuable agent tools fall into the third group, which is exactly why AI engineers have to design idempotency in rather than hope for it.

Why AI agents make idempotency urgent

A traditional web form is submitted by one person who clicks once (or twice, by accident). An agent is a program that can repeat itself in ways you did not plan for:

  • Client retries: your orchestration code retries a tool call after a timeout, but the first call actually succeeded on the server.

  • Model retries: the model does not see a clear success message and decides to call the same tool again.

  • Rate limits and outages: backoff-and-retry logic around LLM API rate limits can replay a whole step, including the tool calls inside it.

  • Duplicate events: webhook providers typically deliver events "at least once", so an agent triggered by a webhook may start twice for the same order.

  • Resumed workflows: a long-running agent that crashes and resumes from a checkpoint may re-run the last step.

How idempotency keys work

The most common pattern is the idempotency key: a unique value the client sends with a request so the server can recognize repeats. Stripe's API documentation describes the classic version: the server saves the result of the first request made with a given key and returns that same result for later requests with the same key, instead of performing the action again. The IETF is also standardizing an Idempotency-Key HTTP header for this purpose.

The flow looks like this:

  1. The agent (or your code around it) generates a key for one logical action, for example refund:order-4821:attempt-1 or a random UUID stored with the task.

  2. The tool server checks a store (a database table or cache) for that key.

  3. If the key is new, it performs the action, saves the response with the key and returns it.

  4. If the key already exists, it skips the action and returns the saved response.

  5. If the same key arrives with different parameters, it rejects the request, because that signals a bug.

The crucial design choice is who creates the key. Do not let the model invent a fresh key on each attempt, or every retry looks new. Generate the key deterministically in your code from the business action (task ID plus tool name plus target record), so a replay of the same step always reuses it.

Design patterns for idempotent agent tools

1. Prefer "set" over "add"

Where possible, expose tools that declare a final state instead of an increment. set_subscription_plan(customer, "pro") is naturally idempotent; upgrade_plan(customer) is not.

2. Use natural unique keys

Many actions have a business identifier you can enforce with a unique constraint: one invoice per order, one onboarding email per signup, one ticket per incident ID. A database constraint is a simple, reliable guard against duplicates.

3. Deduplicate incoming events

Store the event ID of every webhook or queue message you process and ignore repeats. This stops a duplicate delivery before the agent even starts reasoning.

4. Return clear, structured results

Models retry when results are ambiguous. Return explicit outcomes, such as {"status": "already_processed", "refund_id": "re_123"}, so the model understands the action is done. This pairs well with function calling schemas that define tool outputs precisely.

5. Make multi-step work resumable

For workflows with several side effects, record which steps finished. On resume, skip completed steps instead of replaying the whole chain.

A quick example: an AI support agent issuing refunds

A customer asks for a refund. The agent verifies the order and calls issue_refund(order_id=4821, amount=40). The payment provider processes it, but the response times out. The orchestrator retries.

  • Without idempotency: the second call creates another refund. The customer gets 80 instead of 40, and finance finds it a week later.

  • With idempotency: the tool sends the key refund:4821. The provider recognizes it, returns the original refund and the agent tells the customer the refund is confirmed.

Same model, same prompt, very different business outcome. That is why idempotency is a production concern, not an academic one.

Common mistakes

  • Random keys per retry: generating a new UUID inside the retry loop defeats the purpose.

  • Keys that expire too soon: if keys are deleted before retries stop, late duplicates slip through.

  • Checking then acting without a lock: two parallel calls can both see "key not found". Use an atomic insert or unique constraint.

  • Ignoring the model layer: even with perfect APIs, a prompt that encourages "try again if unsure" can create duplicate intents. Pair idempotent tools with clear tool results.

  • Treating reads as free: safe reads are retry-friendly, but repeated expensive reads still cost money and rate-limit budget.

FAQ

Is idempotency the same as "exactly once" delivery?

No. Distributed systems usually guarantee at-least-once delivery. Idempotency is how you get exactly-once effects on top of at-least-once delivery.

Do I need idempotency for read-only tools?

Read-only tools are already safe to repeat. Focus first on tools that write, pay, send or delete.

Where should the idempotency logic live: in the agent or in the API?

Both help, but the server side is the real guarantee. The agent layer should generate stable keys and dedupe events; the tool or API should enforce them.

Keep learning with Coderhouse

Shipping agents that act safely on real systems is core forward-deployed work. Explore the path that fits your goals:

Dan Patiño

I'm Dan Patiño, head of AI Strategy & Innovation at Coderhouse. My day-to-day work involves merging the tactical management of e-commerce (CRO, Email Marketing and SEO) with the development of disruptive solutions. I specialize in building internal AI-powered apps to automate tasks and boost innovation within the team. I firmly believe that technology is strategy's best ally. To dive deeper into my professional journey, I'll be waiting for you on my LinkedIn profile.