DEV Community

Quinn Li
Quinn Li

Posted on

Idempotency Keys in Agent Loops: Where They Leak

An expense tool receives two identical requests for lunch. Are they two new reports, or two attempts to file the same report after the first reply was lost? The amount, employee and description cannot answer that question. The submitting application knows which action the user authorized.

Follow one action through a re-plan

Allocate an operation identifier when the application accepts the submission. Persist the submission, its tenant, the intended effect and a versioned representation of the effect-bearing fields before invoking the expense service. Carry the identifier through queue messages and planner checkpoints. A model's turn number, a new worker's request identifier or a freshly generated timestamp belongs in the attempt history. None should change the identity of an already submitted expense.

When a caller reuses the identifier, compare the effect-bearing fields with the stored version. A change of currency, amount or payee is a conflict to resolve explicitly. Formatting differences may be normalized if the API defines them as equivalent. A legitimately new lunch gets a new submission identifier even if every field is identical to yesterday's. Keep tenant and operation kind in the uniqueness scope.

Test the distinction

Build three synthetic fixtures: the same submission after a worker restart, a different submission with identical fields, and an existing submission with a changed currency. Expect one logical operation, two logical operations and an input conflict, respectively. Test two workers racing on the first case with a database uniqueness constraint so only one can own the first dispatch. A separate read followed by an unconditional write allows both workers to believe they won.

A stable local identifier lets the caller recognize intent. For a missing reply, upstream deduplication or authoritative reconciliation is also necessary. Check the endpoint's documented key scope and retention before sending again.

PostgreSQL INSERT · HTTP semantics, §9.2.2

This article was created with AI assistance.

Top comments (0)