# When an AI Agent's API Call Times Out, Duplicate Orders Happen: How to Build Idempotency and the Saga Pattern Into ERP Integrations

> Network timeouts cause AI agents to create duplicate ERP orders. Learn how Idempotency-Key headers and the Saga pattern keep multi-step transactions safe.

- Published: 2026-10-19
- Author: Master Mind
- Canonical: https://aimaster.fi/en/artikkelit/kun-ai-agentin-api-kutsu-patkii-syntyy-tuplatilaus-idempotenssi-ja-saga-malli

A single three-second network timeout can turn a helpful AI agent into a machine that books duplicate orders and locks up warehouse inventory. Implementing idempotency and the Saga pattern in AI agent integrations is an architectural prerequisite the moment your growth company moves agents from read-only assistants to executing write operations across ERP, WMS, and billing systems. According to the Internet Engineering Task Force specification (IETF, 2025, draft-ietf-httpapi-idempotency-key-header-07), standard HTTP POST and PATCH requests are not inherently idempotent: if a connection drops before the response arrives and the client retries, the target server executes the transaction a second time.

Most growth companies only discover this gap after their first production incident. While [structured outputs and JSON schema in AI integrations](https://aimaster.fi/en/artikkelit/structured-outputs-ja-json-skeema-tekoalyintegraatiossa-estavat-rikkinaiset-erp-kutsut) guarantee that an agent's payload matches the ERP's field definitions, schema validation says nothing about whether that exact request has already been executed five seconds earlier.

## Why does a retrying AI agent create duplicate orders in your ERP?

An AI agent creates duplicate orders because a language model cannot distinguish between a failed execution and a lost network response. When an ERP endpoint takes longer than expected and hits a timeout, the agent's tool-calling loop assumes the action failed and issues a new POST request, creating a second order or invoice in the database.

In Brandur Leach's engineering analysis of distributed API failures (Stripe Engineering, 2017, Designing robust and predictable APIs with idempotency), every network call between two systems can fail in three distinct ways: the initial connection fails before reaching the server, the operation fails midway on the server, or the server completes the write successfully but the connection drops before the confirmation reaches the client. In the third scenario, the ERP has already created the sales order, but the AI agent only sees a timeout error.

Without transaction state tracking, the agent tries to be helpful and runs the tool call again. If the agent is simultaneously hammered by rate limits or temporary slowdowns, uncoordinated retries also trigger a thundering herd effect unless requests are spaced out with exponential backoff and random jitter (Stripe Engineering, 2017). PowerPoint architectures rarely mention network timeouts, because on a slide every arrow reaches its box on the first try.

## How do idempotency keys prevent duplicate executions in AI agent integrations?

Idempotency keys prevent duplicate executions by attaching a deterministic, unique identifier (`Idempotency-Key`) to every state-changing tool call before it leaves the orchestration layer. If the AI agent retries the same step after a timeout, the receiving gateway recognizes the key, blocks the duplicate database write, and returns the cached result of the original transaction.

A critical architectural rule is that the language model itself must never invent the idempotency key. If the model generates a random string inside its tool arguments, a retry after a context reset will produce a brand-new key. Instead, the orchestration layer computes the key deterministically—for example, by hashing the customer order ID, the workflow run ID, and the specific tool name (`order_84920_run_12_create_erp_order`).

- First attempt: The orchestration gateway writes the idempotency key to a fast state table with an `IN_PROGRESS` lock before forwarding the POST request to the ERP.
- Completed execution: Once the ERP returns the new order number, the gateway updates the key record to `COMPLETED` and caches the exact response payload.
- Retry after timeout: When the AI agent retries the tool call with the same key, the gateway immediately returns the cached order number without touching the ERP a second time.
- Payload mismatch protection: Following the IETF specification (IETF, 2025), if a retry reuses an existing key with modified parameters, the gateway rejects the call with an error to prevent silent data corruption.

## How does the Saga pattern clean up a multi-step transaction when Step 3 fails?

The Saga pattern cleans up failed multi-step workflows by pairing every forward write action with a reverse compensating action that undoes the state change if a subsequent step fails. When an AI agent reserves inventory in the WMS and creates an order in the ERP, but the credit check or freight booking fails, the Saga orchestrator executes the compensations in reverse order.

Unlike traditional single-database applications, an AI agent operating across cloud CRM, WMS, and ERP platforms cannot lock all systems inside a single atomic database transaction (two-phase commit). As Emily Fortuna details in Temporal's engineering guide on distributed workflows (Temporal, 2023, Saga compensating actions design pattern & Saga design pattern explained), the Saga pattern replaces cross-system locks with local transactions and an explicit stack of compensating actions executed in Last-In, First-Out (LIFO) order.

Crucially, Fortuna highlights a subtle production trap: the compensating action (`addCompensation`) must be registered in the workflow state *before* the forward tool call is executed (Temporal, 2023). If the agent's inventory reservation call times out right after the WMS deducts the stock, registering the compensation beforehand ensures the rollback routine still runs `releaseInventoryIfPresent` and frees the locked units. Furthermore, every compensating action must itself be idempotent so that a network glitch during cleanup never leaves orphaned reservations behind.

|  |
|  |

## How do you build transaction-safe AI agents on top of Master OS?

Transaction-safe AI agents are built by separating business reasoning from state management: the agent decides what action is needed, while the underlying integration platform enforces idempotency keys, retry policies, and Saga compensations. At AIMASTER, this transaction layer is built into our core architecture and delivered in 3-day sprints without months of specification slides.

**Master Plan** is an AI strategy sprint that maps where AI generates the most value for your company — measured in euros. During this phase, we also identify every write-enabled process—from order entry to warehouse allocations and invoicing—where a partial failure would cause direct financial loss or manual cleanup work.

**[Master OS](https://aimaster.fi/tuotteet/master-layer)** is the company's AI Operating System: a platform that securely connects the company's existing systems (CRM, ERP, documents), data, and agents for AI use. In Master OS, tool calls do not hit legacy ERP endpoints raw; the platform attaches deterministic idempotency keys and maintains the Saga compensation log automatically. **Master Mind** is a suite of AI agents that operates on top of Master OS and handles business processes autonomously. **Custom AI solutions** are delivered using an agile sprint model: one sprint is 3 development days.

When we built the Aini AI assistant for Jaajo Linnonmaa and automated digital marketing workflows for Tagomo, reliability in production came down to strict boundaries between reasoning and execution. An agent can draft, analyze, and propose freely, but the moment it mutates state in a production system, deterministic engineering rules take over.

Want to see which of your company's order, inventory, or billing workflows are ready for autonomous AI agents—and how to protect them from duplicate transactions before going live? Book a [Free Master Mind Analysis](https://aimaster.fi/analyysi), and we will map your highest-value agent workflows and their integration architecture in euros.

## Frequently asked questions

### Are structured outputs and JSON schemas enough to prevent duplicate orders?

No. Structured outputs only ensure that the agent's JSON payload matches the target API schema and will not crash the parser. If the HTTP response drops due to a network timeout and the agent retries the call, a perfectly formatted JSON request will still create a duplicate order unless it is protected by an idempotency key.

### Who generates the idempotency key—the language model or the integration platform?

The idempotency key must be generated deterministically in the orchestration layer before the tool call is executed—typically by combining the business object identifier, the workflow execution ID, and the step name. If the AI model generates a new random identifier on every retry, the target API will treat the retry as a brand-new order.

### Can idempotency and the Saga pattern be added to a legacy ERP without changing its source code?

You do not need to modify the legacy ERP itself. You place a lightweight integration gateway in front of the ERP that stores idempotency keys in a fast state store and exposes clear compensating endpoints—such as canceling a reservation or crediting a draft order—for the Saga orchestrator.

### How does the Saga pattern differ from a traditional database transaction?

Two-phase commit (2PC) locks database rows across all participating systems simultaneously, which slows operations down and is rarely supported across modern cloud APIs. The Saga pattern commits each step locally and undoes completed steps via reverse compensating actions if a later step fails.
