AI API Duplicate Jobs: Idempotency Keys and Durable Recovery
Design an application operation ledger for duplicate AI jobs, exact payload conflicts and uncertain outcomes; distinguish in-flight coalescing and caching.

AI API duplicate jobs need a durable application operation identity before recovery starts. Record the user action, claim it atomically, bind it to exact request inputs and preserve uncertain outcomes. An arbitrary idempotency header cannot establish an endpoint contract, and a caller timeout cannot prove that generation stopped. In-flight sharing is a separate control: use it only when callers are authorized to receive the same result.
Separate three controls
HTTP idempotence describes method semantics. RFC 9110 defines an idempotent method by the intended effect of repeating an identical request; safe methods, PUT and DELETE have that property. It does not make every POST generation request idempotent. A generation endpoint needs its own documented agreement about keys, parameter conflicts, retention, concurrent requests and recoverable results before you can rely on remote deduplication.
Stripe illustrates why the endpoint contract matters. Its API v1 documentation describes storing the first status and body after execution begins, including a 500 response; validation and concurrent-execution conflicts have different treatment. That is a Stripe-specific example, not behavior established for an AI endpoint. Do not infer support in API429 from a familiar header name. Read the API429 documentation and public API reference for the exact endpoint and request shape. An omitted feature in a public reference is not proof of universal absence; a documented contract is required for the behavior you rely on.
| Control | Application purpose | Boundary to remember |
|---|---|---|
| Durable operation ledger | Recognize one business action across attempts and restarts | Local records alone cannot prove remote execution happened once |
| In-flight coalescing | Let authorized callers share one active execution | A memory map disappears on restart and is not distributed idempotency |
| Completed-result cache | Reuse a finished result when reuse is permitted | Freshness, authorization and retention still require explicit policy |
The request coalescing guide develops the second control. Keep these boundaries visible in your design: a cache miss is not permission to repeat an unknown operation, and an empty in-flight map is not evidence that an earlier process never dispatched work.
Define one business operation
Choose an operation boundary users can understand: produce the extraction for document revision seven, prepare one reply for a support action, or create one requested image. The same prompt can belong to different business operations. A deliberate regeneration needs a new operation identifier even when every input byte matches, because the person asked for another result. Conversely, a browser refresh during the original action should carry its existing identity.
Generate an opaque high-entropy identifier when the application accepts the action, then persist it before dispatch. Scope it to the tenant and authorization boundary; do not trust a caller-supplied tenant label without checking authenticated authority. Bind the record to the endpoint, exact model identifier, prompt bytes, schema and tool definitions, immutable file contents or snapshot identifiers, retrieval snapshot and every generation parameter. Include output format, output limits and any explicit randomness settings. Compare a stable representation of those exact values, with a versioned encoding, rather than an informal concatenation of strings.
Do not strip prompt whitespace, collapse model aliases, round randomness settings or discard defaults merely to make requests match. Those transformations can change the work or erase a meaningful difference. If the application intentionally preprocesses text, preserve that transformation as part of its own input contract and record the resulting exact submitted input. A model alias that resolves differently later cannot silently become the identity of an earlier request.
Keep personal information, prompts, credentials and request bodies out of operation identifiers and routine logs. A payload hash is sensitive correlation data, not anonymization: recognizable or guessable inputs can remain linkable. Restrict access to fingerprints and diagnostic events. Store result references behind application authorization, encrypt retained results where appropriate, and apply documented retention limits. A cached result must pass current access checks before anyone receives it.
Claim and recover with a durable ledger
Create a unique constraint over the application scope and operation identifier. In a transaction, insert or claim that record and compare its stored payload identity. Concurrent callers must see one durable decision. The winning owner alone may dispatch; a same-key, different-payload submission becomes a conflict and must not execute the changed work. A duplicate with the same payload may observe state, or join only when the application explicitly permits shared authorized semantics.
| State | Meaning in this application design | Recovery action |
|---|---|---|
| new | Recorded intent without a dispatch claim | Atomically claim before dispatch |
| claimed | One worker owns the next decision | Check durable dispatch evidence; a crash may require reconciliation |
| in-flight | Dispatch started; completion is unconfirmed | Observe the existing operation; avoid blind replay |
| completed | Validated result and outcome are durable | Return the authorized retained result or reference |
| unknown | Acceptance or completion cannot be established | Reconcile evidence; require a controlled decision before new paid work |
| conflict | Identifier was presented with different inputs | Reject the mismatch; obtain a deliberate new operation if appropriate |
| expired | Retention or recovery eligibility ended | Review explicitly; do not silently treat the old key as new work |
This is a proposed application state model, not an API429 response schema. Use a transactional transition and ownership version for each write. A lease may help coordinate workers, and a fencing token or compare-and-set version can reject stale application writes. These controls protect records where your application enforces them. They do not cancel a remote request or fence a service that does not recognize the token.
There is an unavoidable uncertain interval between updating your database and sending a request to another system. A worker can crash immediately before dispatch, immediately after acceptance, or after receiving output but before saving it. A local “dispatch intended” record cannot distinguish all these cases. Lease expiry never proves that remote execution is absent. Without a suitable remote contract or a reconcilable receipt, recovering the lease must not automatically authorize another generation. Do not advertise exactly-once execution from a local unique constraint.
A caller's response deadline and the operation's execution state are separate. Return a bounded response when the caller can no longer wait, while preserving the operation as in-flight or unknown as evidence requires. Cancellation detaches that caller; it does not certify remote cancellation. If multiple permitted observers wait, bound their number and memory usage and track individual deadlines. One observer leaving must not erase durable evidence needed by the others.
Reconcile uncertainty before retry or fallback
A partially received stream, an accepted job or a lost final response belongs to the original operation. Preserve available output and documented identifiers under access control. Poll, resume or retrieve results only where the endpoint actually documents those capabilities. Do not invent a status route, assume a stream can replay from an offset, or interpret a disconnect as a rejected request.
Use the retry budget guide for 429 and 503 classification, Retry-After parsing, total deadlines and attempt limits. Those scheduling controls do not resolve an unknown acceptance state. An alternative model is another potential generation, and its output can produce the same downstream effect. Check the exact model and supported parameters in the model catalog; changing the model does not establish that the first operation failed.
Keep completed and unknown deduplication tombstones for the full supported replay window, including delayed queue delivery and client retries. A tombstone can preserve minimal identity and outcome evidence after the result itself is deleted, subject to privacy and retention rules. When a key expires, route its reuse to explicit review or a deliberate new operation; never delete the record on a short TTL and silently replay old work. Describe what users can recover after result retention ends.
Downstream effects need their own controls. Writing a CRM record, sending email or taking payment requires a destination-supported unique operation key, transaction or another documented duplicate-protection mechanism. An application outbox can durably connect a local result to delivery intent, but an ambiguous delivery still needs destination reconciliation. No local transaction automatically spans the model request and a third-party business system. The cost guardrails guide covers application accounting boundaries; distinguish model attempts from successful business actions. Consult the public FAQ for customer-facing service questions.
Synthetic failure walkthrough
Consider a fictional document extraction operation with opaque identifier op-example-7, tenant scope A and immutable document revision seven. Two workers receive the same queue event. The unique claim gives worker one ownership; worker two observes the matching record without submitting another request. This example describes application design, not an API429 trial.
Worker one saves dispatch intent and sends the request, then crashes before recording the response. Worker two later sees the lease expire. It marks the case for reconciliation rather than submitting again: the remote service might still be generating, might have finished, or might never have received the request. The request's absence from worker two's memory proves nothing. If a documented remote receipt later resolves completion, the application validates and stores the authorized result using its current ownership version.
Suppose the original worker returns late with a stale version. Its direct write must fail the version guard; a reconciliation path can evaluate its evidence without overwriting a newer decision. If no supported lookup or trustworthy completion evidence exists, an operator or explicit product workflow decides whether to create a new operation after communicating the uncertainty. A second generation remains possible; the design has not manufactured proof of exactly-once execution.
Finally, a successful extraction queues a CRM update through an outbox. A delivery timeout leaves that downstream action uncertain too. Reconcile using the CRM's supported identifier or uniqueness mechanism before resending. The generation's completed state alone cannot prove whether the CRM accepted the update.
Proposed application acceptance checks
These are proposed tests for your implementation, not measured API429 behavior. Make their assertions about durable records, dispatch decisions and authorized observations, rather than matching a library's internal function calls.
| Scenario | Application acceptance condition |
|---|---|
| Concurrent identical claims | One owner obtains dispatch permission; matching observers see the same operation |
| Same key, changed payload | A conflict is returned before another dispatch |
| Restart before or after dispatch | Durable evidence survives; ambiguous acceptance becomes unknown |
| Lease expiry and late completion | Expiry cannot authorize blind replay; stale writes fail version checks |
| Accepted job or partial stream | Recovery preserves identity and output; no automatic paid resubmission |
| Caller cancellation | The observer detaches without asserting remote cancellation |
| Cross-tenant access | Neither fingerprints nor result references expose another tenant's output |
| Intentional regeneration | A new operation is recorded even with identical prompt bytes |
| Retention expiry | Old-key reuse requires review; tombstones prevent silent replay |
| Downstream delivery uncertainty | Destination reconciliation precedes another business effect |
FAQ
Does sending Idempotency-Key make an AI API request safe to replay?
Only a documented endpoint contract can establish remote handling of that key. Your durable ledger still has to reject payload conflicts and preserve uncertain states. A header alone is not evidence of acceptance, deduplication or result retention.
Can two identical prompts share one operation?
Only when they represent the same business action. Independent creative variations, separate audit results and a user's intentional regeneration need separate identities. Authorized in-flight sharing is an additional opt-in decision, not something inferred from textual similarity.
Should a timeout or expired lease create a new request automatically?
No. Both concern local observation or ownership; neither establishes what the remote service executed. Reconcile first, and make any new generation an explicit operation decision when uncertainty remains.
Is a completed-result cache enough?
A cache can serve authorized reusable output, but it cannot close the crash interval before a result was saved. Keep operation identity and unknown-state evidence in durable storage independently of cache eviction.
Runnable offline Python 3.10+ ledger state-machine verification
The following self-contained Python 3.10+ standard-library module tests an application idempotency ledger across reserved, in_flight, unknown_timeout and completed states, rejecting same-key payload conflicts and fencing stale worker writes after an uncertain POST /v1/chat/completions timeout:
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
from typing import Literal
LedgerState = Literal["reserved", "in_flight", "completed", "unknown_timeout", "conflict"]
def fingerprint_operation_payload(
tenant_id: str,
endpoint: str,
model_id: str,
prompt_bytes: str,
schema_version: str,
snapshot_id: str,
) -> str:
canonical = json.dumps(
{
"v": 1,
"tenant_id": tenant_id,
"endpoint": endpoint,
"model_id": model_id,
"prompt_bytes": prompt_bytes,
"schema_version": schema_version,
"snapshot_id": snapshot_id,
},
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
@dataclass
class LedgerRecord:
tenant_id: str
operation_id: str
payload_hash: str
state: LedgerState
owner_worker: str
version: int = 1
result_ref: str | None = None
class DurableOperationLedger:
def __init__(self) -> None:
self._records: dict[tuple[str, str], LedgerRecord] = {}
def claim_or_inspect(
self,
tenant_id: str,
operation_id: str,
payload_hash: str,
worker_id: str,
) -> tuple[LedgerState, int]:
key = (tenant_id, operation_id)
existing = self._records.get(key)
if existing is None:
record = LedgerRecord(
tenant_id=tenant_id,
operation_id=operation_id,
payload_hash=payload_hash,
state="reserved",
owner_worker=worker_id,
version=1,
)
self._records[key] = record
return ("reserved", record.version)
if existing.payload_hash != payload_hash:
return ("conflict", existing.version)
return (existing.state, existing.version)
def mark_in_flight(self, tenant_id: str, operation_id: str, expected_version: int) -> LedgerRecord:
rec = self._records[(tenant_id, operation_id)]
if rec.version != expected_version or rec.state != "reserved":
raise RuntimeError("Fencing check failed on transition to in_flight")
rec.state = "in_flight"
rec.version += 1
return rec
def record_disconnect_uncertainty(
self, tenant_id: str, operation_id: str, expected_version: int
) -> LedgerRecord:
rec = self._records[(tenant_id, operation_id)]
if rec.version != expected_version or rec.state != "in_flight":
raise RuntimeError("Fencing check failed on transition to unknown_timeout")
rec.state = "unknown_timeout"
rec.version += 1
return rec
def reconcile_completed(
self,
tenant_id: str,
operation_id: str,
expected_version: int,
new_owner: str,
result_ref: str,
) -> LedgerRecord:
rec = self._records[(tenant_id, operation_id)]
if rec.version != expected_version or rec.state not in ("in_flight", "unknown_timeout"):
raise RuntimeError("Stale version or invalid state for reconciliation")
rec.owner_worker = new_owner
rec.state = "completed"
rec.result_ref = result_ref
rec.version += 1
return rec
if __name__ == "__main__":
ledger = DurableOperationLedger()
fp_rev7 = fingerprint_operation_payload(
tenant_id="tenant-a",
endpoint="POST /v1/chat/completions",
model_id="gemini-3.8-flash",
prompt_bytes="Extract clauses from contract revision 7",
schema_version="clauses-v1",
snapshot_id="doc-rev-7",
)
# Worker 1 claims operation op-example-7 in state 'reserved'
state_w1, ver_w1 = ledger.claim_or_inspect("tenant-a", "op-example-7", fp_rev7, "worker-1")
assert state_w1 == "reserved" and ver_w1 == 1
# Same key with different payload bytes is rejected as a conflict
fp_modified = fingerprint_operation_payload(
tenant_id="tenant-a",
endpoint="POST /v1/chat/completions",
model_id="gemini-3.8-flash",
prompt_bytes="Extract clauses from contract revision 8",
schema_version="clauses-v1",
snapshot_id="doc-rev-8",
)
conflict_state, _ = ledger.claim_or_inspect("tenant-a", "op-example-7", fp_modified, "worker-2")
assert conflict_state == "conflict"
# Worker 1 marks the operation 'in_flight', then experiences a network timeout
rec = ledger.mark_in_flight("tenant-a", "op-example-7", expected_version=1)
assert rec.state == "in_flight" and rec.version == 2
rec = ledger.record_disconnect_uncertainty("tenant-a", "op-example-7", expected_version=2)
assert rec.state == "unknown_timeout" and rec.version == 3
# Worker 2 inspects the operation after lease expiry: it sees 'unknown_timeout', not permission to replay
observed_state, observed_ver = ledger.claim_or_inspect("tenant-a", "op-example-7", fp_rev7, "worker-2")
assert observed_state == "unknown_timeout" and observed_ver == 3
# After reconciling completion evidence, Worker 2 advances the record to 'completed'
completed = ledger.reconcile_completed(
"tenant-a", "op-example-7", expected_version=3, new_owner="worker-2", result_ref="enc://results/op-example-7"
)
assert completed.state == "completed" and completed.version == 4
# A late stale write from Worker 1 using old version 2 is fenced and rejected
try:
ledger.reconcile_completed(
"tenant-a", "op-example-7", expected_version=2, new_owner="worker-1", result_ref="enc://stale"
)
raise AssertionError("Stale write should have failed version fencing")
except RuntimeError:
pass
print(json.dumps({"operation_id": "op-example-7", "final_state": completed.state, "version": completed.version}))
Sources & further reading
Put the next step into practice.
Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.
