Coding-Agent Idempotency: Stop Paying Twice for the Same Change
By Eric Bush · August 27, 2026 · 7 min read
Unattended coding agents fail in ordinary ways: a scheduler retries after a timeout, a worker restarts after a push, or the network hides a successful API response. Without idempotency, the same task can generate a second article batch, open duplicate changes, rewrite analytics, or send repeated notifications. Every duplicate carries compute and cleanup cost.
Assign a stable task key from job type, target, intended period or version, and relevant parameters. The key must survive process restarts but change when the desired result changes. Store task state outside transient model context: planned, executing, side effect pending, verified, failed safely, or requires investigation.
Check Authoritative State First
Before generation, inspect the actual repository, branch, files, database rows, deployment, or external resource. Do not trust only a scheduler flag. Verify that today's content, last week's analytics row, or the requested dependency version is absent. When the desired state already exists and passes checks, mark the task complete without producing a second mutation.
Make the precondition exact. “No recent article” is ambiguous; “no twelve-post batch dated YYYY-MM-DD imported in the index” is testable. “Pricing was checked” should include a verification date and table integrity, not just a log line. Precise checks lower both duplicates and false skips.
Separate Attempt From Effect
Record an attempt before costly work, but do not call it successful until the effect is read back. For commits, capture SHA and remote branch state. For deployments, match the exact commit. For an API write, preserve request identifier and resulting resource version. For notifications, use a provider idempotency key if supported.
A timeout creates unknown state, not failure. Query the target using the task key or expected result before retrying. If state cannot be determined, stop consequential retries and request investigation. Blindly repeating a write because the response was lost is one of the most expensive retry patterns.
Design Safe Repository Retries
Require a clean worktree and known branch. Fetch and compare local and remote history. Permit only a fast-forward when authorized. If the local branch is unexpectedly ahead, remote is divergent, or unrelated files changed, stop without stash, reset, rebase, or overwrite. Preserving evidence is more valuable than forcing a scheduled run to appear green.
After writing, run deterministic gates and review the diff. Commit only nonempty intended changes, then push once. If push output is ambiguous, fetch and check whether the exact SHA is on the remote before retrying. A rejected push is not permission to rewrite history.
Make Data Appends Unique
Give periodic records a natural unique key such as week start, timezone, environment, and source scope. Validate complete periods and all required metrics before append. Refuse duplicates and partial rows in code. A rerun should report the existing record and trend, not update an immutable historical snapshot silently.
For generated files, uniqueness should include slug, title, cover asset, and import binding. Check the whole corpus, not just the current directory listing. Duplicate semantic topics require human-quality review because a new slug can still repeat old work.
Measure Duplicate Avoidance
Track retries, tasks safely skipped, unknown-state stops, duplicate attempts caught, and cleanup avoided. Estimate avoided model tokens, CI minutes, deployment time, reviewer labor, and external side effects. Also measure false skips, because an overly broad task key can suppress legitimate work.
Idempotency is an end-to-end property: stable identity, authoritative preconditions, durable attempt state, read-back verification, and bounded retries. It reduces cost precisely when systems are unreliable. The best unattended task can run again after any interruption and either finish the missing work or prove that the intended result already exists.
Run Interruption Drills
Inject termination before generation, during file writes, after commit, during push, after deployment creation, and after an external notification succeeds but before its response is stored. Restart with the same task key. Verify that the job resumes missing work, recognizes completed effects, or stops on unknown consequential state.
Inspect artifacts after every drill: worktree, local and remote SHA, database uniqueness, deployment metadata, and provider request identifiers. Count extra tokens and elapsed time. Fix the earliest ambiguous boundary rather than adding broad retries at the end, because late retries multiply every preceding cost.
Repeat drills after changing schedulers, storage, git workflows, or external APIs. Idempotency assumptions decay when infrastructure changes. A short quarterly exercise is cheaper than discovering during a production interruption that the task ledger and the real side effect can no longer be reconciled.
Expose task keys and effect status in operator tooling. When a run stalls, an operator should see the exact last verified boundary without reading a model transcript. Manual recovery must use the same checks as automatic recovery and record any override. A hidden one-off fix can restore today's task while breaking the next retry, so make recovery actions part of durable state.
Want to calculate exact costs for your project?
Frequently Asked Questions
What makes a good idempotency key?
Combine job type, exact target, intended period or version, and parameters that change the desired result.
How should a timeout be handled?
Treat it as unknown state, query the authoritative target, and retry only after proving the effect did not occur.
Should an agent clean a dirty worktree automatically?
No. Stop and preserve the user's changes rather than stashing, resetting, rebasing, or overwriting them.
How is idempotency value measured?
Track duplicate work and side effects avoided, while monitoring false skips of legitimate tasks.
Related Articles
Coding-Agent Branch Fan-Out Cost: Price Parallel Work Through Reconciliation
Parallel agents can shorten elapsed time while multiplying context, conflicts, tests, and review. Measure net value at the integrated accepted change.
Coding-Agent Kill-Switch Drills: Price the Shutdown Path Before an Incident
Test session cancellation, credential revocation, network isolation, and artifact quarantine while measuring the real operational cost of agent shutdown.
Coding-Agent Source Verification Cost: Budget Facts Before Implementation
Price first-party research, claim extraction, cross-checks, recency, and failed verification against the rework caused by unsupported coding decisions.