Your AI Agent Called the Same Tool Twice. How Do You Prevent Duplicate Actions in Production?
AI agents are becoming more capable of interacting with real business systems. They can create records, update databases, trigger workflows, manage deployments and execute operations through external APIs.
But there is a problem that developers sometimes overlook.
What happens when an AI agent calls a tool, the backend successfully executes the operation, but the response never reaches the agent?
The agent sees a timeout. It assumes the operation might not have completed and retries the same tool call.
The backend receives another request.
Now imagine that the tool creates a purchase order, transfers money, updates an inventory record or triggers a device operation.
You might end up executing the same business operation twice.
Interestingly, the API might be working exactly as expected. The problem is how the application handles retries and uncertain execution outcomes.
The central idea is simple: AI tool execution should be treated like a production distributed-system operation, not just a function call.
Let's explore how to design this reliably using Python, FastAPI and database-backed idempotency.
1. Why AI Tool Calls Are Different From Ordinary Function Calls
In a traditional application, a function call generally happens within a controlled execution flow.
An AI agent introduces additional uncertainty.
A typical tool-calling workflow looks like this:
- The user submits a request.
- The LLM determines which tool should be called.
- The application validates the generated arguments.
- The backend executes the requested operation.
- The result is returned to the LLM.
- The LLM generates a response for the user.
This looks straightforward until something fails.
Consider this example:
A user asks an enterprise assistant:
"Create a purchase order for 50 units of asset X at ₹1,200 per unit."
The agent generates a tool call:
create_purchase_order(
item="asset-X",
quantity=50,
unit_price=1200
)
The backend successfully creates the purchase order.
However, the network connection times out before the response reaches the agent.
From the agent's perspective, the outcome is unknown.
It might retry the request.
If the backend treats every incoming request as a new operation, another purchase order could be created.
This is an important distinction:
A failed response does not necessarily mean a failed operation.
In distributed systems, the client may not know whether the server completed an operation when communication fails.
The same uncertainty applies to AI agents calling external tools.
2. Introduce Idempotency at the Application Layer
One of the most useful techniques for preventing duplicate operations is idempotency.
An operation is idempotent when repeating the same logical request produces the same intended effect as executing it once.
For example, consider an API that updates a user's preferred language to English.
Executing the same update multiple times should not create additional records or produce additional side effects.
However, creating a purchase order is different.
Every new purchase order represents a new business operation.
Therefore, the backend needs a way to distinguish between:
- A retry of an existing operation.
- A genuinely new operation with identical arguments.
This is where an idempotency key becomes useful.
For example:
idempotency_key = "operation-8f21-unique-id"
The application generates this key for a logical business operation and retains it across retries.
When the same operation is submitted again, the backend recognizes the key and retrieves the existing execution state instead of blindly executing the operation again.
One important implementation detail: do not rely exclusively on the LLM-generated tool-call ID.
A model can generate a different tool-call ID when it retries or reconstructs a request. The application should own the identity of the logical operation.
Also, do not generate idempotency keys solely from request arguments. Two identical purchase orders may represent two legitimate purchases.
3. Build a Durable Tool Execution Ledger
For a production application, storing execution state is just as important as generating an idempotency key.
A durable execution ledger allows the backend to understand what happened to a tool operation, even if the application crashes or the agent retries.
Consider the following database structure:
CREATE TABLE tool_operations (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
tool_name TEXT NOT NULL,
idempotency_key UUID NOT NULL,
request_hash TEXT NOT NULL,
status TEXT NOT NULL,
result JSONB,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE (
user_id,
tool_name,
idempotency_key
)
);
The table stores:
- The user who initiated the operation.
- The tool being executed.
- The logical operation's idempotency key.
- A hash of the validated request.
- The current execution status.
- The previously generated result.
The execution status can follow a lifecycle such as:
REQUESTED
|
v
IN_PROGRESS
|
+------> SUCCEEDED
|
+------> FAILED
|
+------> OUTCOME_UNKNOWN
Why include OUTCOME_UNKNOWN?
Because a timeout does not tell us whether the downstream operation completed.
Suppose the application sends a request to an external purchase-order service. The external service creates the order, but the connection drops before the application receives its response.
Marking the operation as failed would be misleading.
Automatically retrying it without checking the downstream state could create a duplicate.
An explicit unknown state makes this uncertainty visible and allows the application to reconcile the operation.
4. Implementing Idempotent Tool Execution With FastAPI
Let's look at a simplified Python example.
The goal is to ensure that repeated requests with the same logical operation identity do not create multiple business operations.
async def execute_agent_tool(
user_id,
tool_name,
idempotency_key,
request_hash,
arguments,
):
operation = await operation_service.get_or_claim(
user_id=user_id,
tool_name=tool_name,
idempotency_key=idempotency_key,
request_hash=request_hash,
)
if operation.request_hash != request_hash:
raise ValueError(
"Idempotency key reused with different arguments"
)
if operation.status == "SUCCEEDED":
return operation.result
if operation.status in {
"IN_PROGRESS",
"OUTCOME_UNKNOWN",
}:
return {
"status": operation.status,
"operation_id": str(operation.id),
}
result = await purchase_order_service.create(
arguments,
idempotency_key=str(idempotency_key),
)
await operation_service.mark_succeeded(
operation.id,
result,
)
return result
The get_or_claim() operation is particularly important.
It must atomically establish ownership of the operation. A simple database lookup followed by an insert is not enough because two concurrent workers could both observe that the operation does not exist and attempt to execute it.
A database unique constraint, transaction and appropriate conflict-handling strategy help prevent this race.
The example also assumes that the downstream purchase-order service supports idempotency.
If the external service does not support it, the application cannot simply assume that a local database record guarantees exactly-once execution across both systems.
That limitation deserves attention in any production implementation.
5. Handle Retries, Timeouts and Concurrent Execution
Idempotency solves an important part of the problem, but it does not eliminate every failure scenario.
Consider three situations.
Scenario A: The agent retries after a successful operation
The execution ledger already contains a successful result.
The backend returns the stored result instead of creating another purchase order.
Scenario B: Two workers receive the same operation simultaneously
Both workers attempt to process the same idempotency key.
The application must atomically claim the operation so that only one worker becomes the active executor.
The other worker should retrieve the existing operation state rather than execute it independently.
Scenario C: The external operation succeeds, but the application crashes
This is more complicated.
The external system has completed the purchase order, but the local execution ledger still says IN_PROGRESS or OUTCOME_UNKNOWN.
The application needs a recovery mechanism.
Some practical approaches include:
- Passing the same idempotency key to downstream services.
- Querying the downstream service using a business operation reference.
- Using durable execution records.
- Implementing reconciliation workers.
- Applying execution leases with careful recovery rules.
- Using compensating operations when a business action cannot be safely reversed.
A retry should not automatically mean that the business operation must be executed again.
Sometimes the correct action is to check whether it already happened.
This is why distributed systems often require reconciliation rather than relying exclusively on retries.
6. Security and Auditability of AI Tool Execution
There is another important consideration.
An AI agent should never receive unrestricted permission to execute business operations simply because an LLM selected a tool.
Tool execution must remain inside the application's authorization boundaries.
For example, if an operator does not have permission to create purchase orders, the agent should not be able to bypass that restriction by calling a purchase-order tool.
The backend should validate:
- The authenticated user's identity.
- Whether the user can access the requested business resource.
- Whether the requested operation is permitted.
- Whether the tool arguments satisfy business validation rules.
- Whether additional human approval is required.
Sensitive actions may also require explicit confirmation before execution.
For auditability, record useful information such as:
- User ID.
- Tool name.
- Logical operation ID.
- Idempotency key.
- Execution status.
- Timestamp.
- Relevant resource identifier.
- Final operation outcome.
Avoid logging sensitive payloads or secrets unnecessarily.
This creates a traceable connection between the original user request, the agent's tool invocation and the actual backend operation.
It also makes debugging much easier when someone asks:
"Why did the AI assistant create this record twice?"
Conclusion
AI agents introduce a new interaction layer between users and business systems, but the reliability requirements of the backend have not changed.
A tool call can time out. A response can get lost. An agent can retry. Multiple workers can process requests concurrently.
None of these situations should automatically result in duplicate business operations.
For production AI applications, I would treat tool execution as a durable backend workflow with application-owned operation IDs, idempotency keys, execution tracking, authorization and recovery mechanisms.
One distinction is especially important:
Exactly-once business execution is not guaranteed simply because an AI agent calls a tool once or because the API uses an idempotency key.
The application must coordinate its database state with downstream systems and account for uncertain outcomes.
An AI agent may decide what action to request, but the backend must remain responsible for how that action is executed safely.
That is the difference between an AI demo that successfully calls tools and an AI system that can reliably operate in production.
Suggested reading and further exploration:
#AgenticAI #Python #FastAPI #LLM #ToolCalling #Idempotency #DistributedSystems #BackendEngineering #SoftwareArchitecture #ProductionAI
Join the conversation! Your thoughts help the community grow.