Agent Retries Turn One Write Into Two: Why It Happens and How to Make the Write Path Idempotent
Why a retry can commit one agent write twice, how to derive a stable idempotency key, what lakehouse MERGE deduplicates, and how to test it.
A courier carries a signed order form to a warehouse. The form arrives, the order is picked and packed, and the acknowledgement never makes it back to the sender. The sender, holding no proof of delivery and no reason to assume the parcel was filled, re-sends the form. The warehouse, which has no way to tell a re-send from a new order, fills it again.
That is the shape of the duplicate-write problem in agent systems. A retry is not the bug, and the duplicate is not the retry's fault. It is what any at-least-once delivery model produces when the write path has no way to recognise a repeat of the same business operation. The agent runtime sends a tool call, the call commits a side effect, the response is lost, and the retry policy does exactly what it was configured to do.
The stakes are concrete: a ledger entry posted twice, an inventory decrement applied twice, a row duplicated in a table an analyst then trusts. The rest of this article works through the mechanism, how to derive an idempotency key from the business operation, what a lakehouse commit does and does not deduplicate, when a single transaction stops being enough, the misconceptions that keep duplicates in production, the tests that catch them, and the criteria for signing off a write path.
The two-call failure: commit succeeds, acknowledgement is lost
A single request involves three distinct events, and only two of them live on the connection: the request is sent, the side effect is committed, and the response is returned. The commit happens in the target system, outside the caller's view. When the connection drops after the commit and before the response, the caller observes a timeout — and a timeout is indistinguishable from a request that never arrived.
This is the mechanism the Kafka delivery-semantics documentation describes for producers: if a producer expects but fails to receive a response indicating that a message was committed, it resends, and the message may be written to the log again if the original request had succeeded. Nothing about the caller's world separates a lost request from a lost response, so retrying is the rational choice and duplicating is the default outcome.
A retry can land in one of four windows relative to the commit:
Window | State at retry | Result |
|---|---|---|
Before commit | No side effect yet | Correct — the retry does the work |
During commit | Commit in flight | Depends on the target's concurrency control |
After commit, before acknowledgement | Side effect already durable | Duplicate |
After acknowledgement | Caller already has the result | No retry should occur |
The third window is the one that produces the duplicate, and it is the one no client-side timeout policy can detect.
The second failure mode is concurrent dispatch: two workers pick up the same task, or an orchestrator re-issues a subtask while the first attempt is still running. Neither attempt is a retry in the temporal sense, but both carry the same logical operation, and both commit. The mechanism is the same — two executions of one business operation with nothing to tell them apart.
This is a property of the request/response boundary, not of any one vendor's queue or database. Any system that retries without an operation identity will exhibit it.
What "exactly once" actually promises — and to whom
Delivery guarantees are agreements between named parties — broker and producer, broker and consumer, service and caller — and they frequently exclude the actor standing outside the system. The Confluent documentation makes this caveat directly: many systems claim exactly-once delivery, but these systems may not account for cases where a consumer or producer outside the system has failed. Read that scope literally. A guarantee that covers the broker and the producer says nothing about the business effect recorded in a downstream table.
The three semantics are tradeoffs between latency and durability:
At most once — messages are delivered once; on failure they may be lost and are not redelivered.
At least once — messages are never lost, but may be delivered more than once.
Exactly once — each message is delivered once and only once, even if part of the system fails.
Kafka's default is at-least-once. Since version 0.11.0.0 the producer offers an idempotent option: the broker assigns each producer an ID and deduplicates using a sequence number sent with every message, so resending does not create duplicate entries in the log. Transactional delivery, also from 0.11.0.0, extends this to exactly-once semantics for Kafka-to-Kafka transfers, and requires consumers to be configured appropriately — the isolation_level setting determines whether messages from aborted transactions are visible.
Both mechanisms operate inside the log. The idempotent producer removes the duplicate message; it does not remove the duplicate business effect that a consumer produces when it processes a message twice and writes to an external system. The documentation notes that coordinating consumed data with an external system's state is the hard part, which is why the next section lives at the application layer.
The practical shift: stop asking whether the platform is exactly-once and start asking where the operation's identity is defined.
Deriving an idempotency key from the business operation, not the model response
The key must be computed before the first attempt, from the inputs of the business operation — "apply credit X to invoice Y for period Z" — and carried unchanged through every retry. AWS's agentic-AI guidance states that idempotency key generation is where most teams go wrong: non-deterministic keys such as timestamps and UUIDs generated at retry time defeat the mechanism, because the retry computes a different key from the original attempt. Hash the workflow ID, task type, and request body, and the same logical operation always produces the same key.
The agent-specific failure is a key minted from something the model produced — its response text, a fresh identifier it invented, or a timestamp taken at call time. Any of these is non-deterministic by construction.
Key source | Deterministic across attempts? | Survives a retry | Verdict |
|---|---|---|---|
Hash of workflow ID + task type + request body | Yes | Yes | Use this |
UUID generated at retry time | No | No | Defeats the mechanism |
Timestamp of the attempt | No | No | Defeats the mechanism |
Model-generated response text | No | No | Defeats the mechanism |
UUID generated once, before the first attempt, and stored with the operation | Yes, in effect | Yes | Acceptable if persisted |
Once the key is stable, the pre-execution check is straightforward: query the idempotency store for an existing result under the same key and return the cached result if the operation already succeeded. Conditional writes make this safe under concurrency — two parallel retries cannot both create a record — and TTL-based expiry keeps the store bounded while preserving the guarantee inside the expected retry window.
Stripe's idempotent request documentation supplies the spec-level requirements worth copying. Keys are client-generated and up to 255 characters; sensitive data such as email addresses or personal identifiers should not be used as keys; the idempotency layer compares incoming parameters against the original request and errors if they differ. Note the scope: Stripe describes automatic pruning of keys at least 24 hours old, and saving results only after endpoint execution begins, for API v1 specifically. Confirm the retention and replay semantics of your own gateway rather than assuming them.
The Idempotency-Key HTTP header draft gives the wire-level contract. A resource should define an expiration policy and publish it in its documentation; it should reply with HTTP 422 when a key is reused with a different request payload; and it may compute a fingerprint of the payload to detect that reuse. Requests carrying different keys are distinct requests and are each processed, even if their fingerprints match. Two residual risks remain: a duplicate can arrive after the key's TTL but before any observable effect, and a key reused after pruning is treated as a new request. And the honest limit — a deterministic, well-propagated key prevents duplicates only where the executing system actually consults the key.
Where the key must survive: retries, replays, and delegation
Trace the key's path: agent runtime → orchestrator → tool call → external API → lakehouse commit. It is commonly dropped at three seams. A retry wrapper that rebuilds the request body can regenerate the key along with it. An orchestrator that re-authorises a delegated subtask under a new workflow ID hands downstream steps a different key. An SDK layer that accepts an idempotency option the caller never sets silently sends none.
The AWS guidance is explicit that propagation extends the guarantee: when an orchestrator delegates a subtask, include the parent workflow's key or a deterministic derivative, and pass the agent's key to external systems that support built-in idempotency. The same source notes that retries returning cached results are the signal the mechanism is working, which makes cache-hit rate the operational indicator to track — a retried operation that returns a cached result is a duplicate that was correctly suppressed.
The commit itself: MERGE/upsert and concurrency in a lakehouse
Three questions get conflated here: does the commit deduplicate, does it conflict, and does it maintain isolation. They have different answers, and only the first is about idempotency.
Isolation and atomicity. Iceberg's reliability documentation describes commits that replace the path of the current table metadata file using an atomic operation, so all updates to table data and metadata are atomic and all table changes occur in a linear history. Readers always use a consistent snapshot without holding a lock. Concurrent writes use optimistic concurrency: each writer assumes no other writers are operating, writes new metadata, and attempts the atomic swap; if the swap fails because another writer committed, the failed writer retries against the new current table state. Commits are structured as assumptions and actions, and after a conflict the writer checks that the assumptions still hold before re-applying — a compaction that rewrote two files is safe to commit only if both source files are still present.
Conflicts. Delta Lake's concurrency control documentation describes the same read–write–validate-and-commit shape and publishes the conflict matrix: INSERT against INSERT cannot conflict; MERGE, UPDATE and DELETE can conflict with each other and with compaction. The resulting exceptions include ConcurrentAppendException, ConcurrentDeleteReadException, ConcurrentDeleteDeleteException, MetadataChangedException, ConcurrentTransactionException and ProtocolChangedException. Whether two operations actually conflict depends on whether they touch the same set of files, which is why partitioning by the columns used in the operation conditions makes the sets disjoint. The documentation's own example is a MERGE on user_id, date and country against a table partitioned by date and country: the condition is not explicit enough to stay inside a partition, so it can scan the whole table and conflict with concurrent writes to any partition. Adding the specific date and country to the merge condition makes it safe to run concurrently.
Deduplication. This is the caveat that matters most. MERGE matches on the condition you give it. A merge keyed on the derived idempotency key converges repeated writes; a merge keyed on a generated surrogate ID produces two rows. The format does not enforce the uniqueness for you — the Iceberg table spec defines two rows as the same when their identifier fields are equal, then states that uniqueness of rows by this identifier is not guaranteed or required by Iceberg and is the responsibility of processing engines or data providers.
So: idempotent key plus an upsert keyed on it gives convergence. The key is the operation's identity; the merge condition is where that identity reaches the table.
Agent write paths that commit into an open-format lakehouse inherit exactly this question. Singdata's platform positions agent interfaces against the same table semantics and permissions as human users, so an agent's MERGE is subject to the same commit and conflict behaviour described above (platform overview).
When a single transaction is not enough: the saga boundary
A multi-step agent action needs a saga only when it crosses a boundary no single commit can cover. The Saga pattern documentation frames the trigger precisely: a unit of work spanning services that each hold a dedicated database, where traditional ACID guarantees are not directly applicable across independently managed stores, and where a failed step must be compensated rather than rolled back.
The moving parts are worth naming exactly. A saga breaks the work into local transactions, each completing atomically within one service, updating that service's database, and triggering the next step via an event or message. Compensable transactions can be undone by an opposite effect. The pivot transaction is the point of no return: after it succeeds, compensable transactions are no longer relevant and all subsequent actions must complete. Retryable transactions follow the pivot and are idempotent, which is what lets the saga reach a consistent final state through transient failures.
The practical consequence for an agent write path: a saga reachable only through compensating transactions cannot be made idempotent by an idempotency key alone. The key deduplicates a repeat of a step; it does not reverse a partial sequence.
Situation | Single transaction | Saga | Not a saga |
|---|---|---|---|
One store, one atomic commit | ✓ | ||
Multiple services, each with its own database | ✓ | ||
An external, irreversible step mid-sequence | ✓ | ||
Tightly coupled transactions | ✓ | ||
Cyclic dependencies between participants | ✓ | ||
Compensation required at earlier participants | ✓ |
Choreography has services exchange events with no central controller — good for simple workflows, harder to trace as steps are added, and prone to cyclic dependencies. Orchestration puts a central controller in charge of the flow — better for complex workflows, at the cost of a single point of failure.
Because each service manages its own data, there is no built-in isolation across participants, and the documentation names the resulting anomalies: lost updates, dirty reads, and fuzzy or nonrepeatable reads. Its countermeasures form the design menu for an agent that re-plans mid-task — semantic locks, commutative updates, reordering so updates land in retryable transactions, rereading values before updating, and version files that log operations in sequence.
Common misconceptions that keep duplicates in production
"Our broker is exactly-once, so we are safe." The guarantee covers the parties it names. The Confluent documentation warns that systems claiming exactly-once may not account for a consumer or producer outside the system failing. If your business effect is written by an actor outside that boundary, the guarantee does not reach it.
"Our keys are random UUIDs, so they cannot collide." Collision resistance is not the property that matters. Determinism across attempts is. A UUID generated at retry time is unique by design and therefore useless as an idempotency key — the retry computes a different one from the original attempt, which is exactly the anti-pattern AWS names.
"MERGE makes the table idempotent." The match condition does, not the operation. A merge keyed on a surrogate ID inserts a second row. The Iceberg spec states plainly that uniqueness by identifier is not guaranteed or required by the format and is the responsibility of processing engines or data providers.
"The model hallucinated a second call." Usually the model called once and the retry layer called twice. Check whether the key differs between the two recorded attempts — a non-deterministic key is the discriminator that separates a retry-layer duplicate from a genuine second decision.
"The idempotency record is permanent." Retention and pruning are part of the contract. Stripe prunes keys at least 24 hours old for API v1 and generates a new request if a pruned key is reused, and the header draft asks resources to publish an expiration policy. The window must exceed the longest plausible retry.
"A cached response proves no second side effect occurred." It proves the response was reused. That is only meaningful if the store was written in the same scope as the effect — which is why the pre-execution lookup and the result write must share one atomic boundary.
What to test before rollout: lost acknowledgement, concurrent duplicate, worker crash
Three scenarios cover the failure modes above. Each needs a fault-injection seam, an observable, and a pass condition. These are designed scenarios, not observed production statistics.
Lost acknowledgement. Terminate the response path after the commit is durable and before the caller receives it, then let the retry policy run. Observable: row count in the target table and the payload returned to the caller. Pass: the table holds one row and the retry returns the original result. This is the only test that exercises the window where duplicates are actually born.
Concurrent duplicate. Dispatch the same logical operation twice in parallel with the same derived key. Observable: the number of committed effects and the status returned to the loser. Pass: exactly one effect, and a well-formed conflict for the loser — a 409 for an outstanding key, per the header draft, or a conditional-write rejection at the store.
Worker crash. Kill the process mid-sequence, restart the orchestrator, and verify resumption from the recorded position rather than from step one. For multi-step actions this is where the saga's pivot transaction and retryable steps get exercised, and where a non-idempotent step surfaces as a duplicate.
Boundary cases worth adding to the same harness:
Key reuse with a changed payload — expect a rejection, per the draft's 422 guidance.
Retry after key expiry — expect a new request, and confirm that is acceptable for the operation.
Idempotency store unavailable at check time — fail closed, not open.
Merge-condition drift after a repartition — the condition may no longer stay inside a partition.
A concurrent compaction or
dataChange = falserewrite colliding with the agent's MERGE — use the Delta conflict matrix to predict which pairs can conflict.
Run the lost-acknowledgement and crash cases against real commit boundaries rather than mocked ones; a mocked commit cannot reproduce the window you are testing.
Acceptance criteria for signing off an agent write path
Each criterion below is checkable by someone who did not build the system.
Every side-effectful operation has a deterministic key derived from operation inputs, and the derivation is written down.
The key is propagated unchanged through every retry, delegation, and external call that supports idempotency.
The pre-execution lookup and the result write share one atomic scope, enforced by a conditional write rather than a read-then-write.
Retention exceeds the worst-case retry window, and the expiry policy is documented for callers.
The merge or upsert matches on the derived key, and partitioning makes concurrent file sets disjoint where the workload allows.
Multi-step actions declare which steps are compensable, which is the pivot, and which are retryable.
The three fault-injection scenarios pass in a pre-production environment, with the lost-acknowledgement and crash cases executed against real commit boundaries.
Conflict exceptions are classified, and retried only when the operation's assumptions still hold.
Duplicate detection is observable, so a cache hit on a retried operation can be distinguished from a first execution.
The first and third criteria carry the most weight. A deterministic key without a shared atomic scope leaves a race between two parallel retries; a shared scope without a deterministic key has nothing to key on. Everything else in the list depends on those two.
FAQ
Is a random UUID ever acceptable as an idempotency key? Yes, if it is generated once, before the first attempt, and stored with the operation so every retry reuses it. The failure is generation at retry time, not randomness itself.
Does a unique constraint on the target table replace the idempotency key? Partly. It enforces convergence on whatever the writer supplies, but the caller still needs a stable key to reuse across attempts, and not every target enforces uniqueness — the Iceberg spec explicitly leaves that to processing engines and data providers.
What happens if the idempotency store is down? The check and the effect must fail closed together. Failing open means executing without knowing whether the operation already ran; failing closed means the request is rejected and retried later. Which posture you choose is an availability decision, but it must be a decision rather than an accident.
Can an agent safely retry a step that calls an external system without idempotency support? Only by making the step compensable, or by moving it after the saga's pivot transaction so it is never repeated.
How long should keys be retained? At least the longest plausible retry window plus clock skew, published as policy — the header draft asks resources to define and publish an expiration policy. Derive the number from your own retry configuration.
This publication builds data infrastructure for agent workloads and therefore has a commercial interest in agent write-path reliability.
Putting it into practice
The retry is not the defect. The missing operation identity is. Every duplicate described in this article traces back to a write path that could not tell a repeat from a new request, and every fix — deterministic keys, shared atomic scope, keyed upserts, saga boundaries — restores that identity at a different layer.
Start with one agent workflow, not the whole platform. List its side-effectful operations, and for each one write down the exact inputs a derived key would hash: the workflow ID, the task type, and the request body, following the AWS deterministic-key guidance. If two operations in that list produce the same key from different business intents, or the same intent produces different keys across attempts, you have found your duplicate before it reaches production. That inventory is the first artifact a design review can actually check.