Practical technical guides / Agent-era architecture: idempotency by business key

A Re-Planning Agent Opens the Same Return Twice: Deduplicate on a Business Key, Not a Request ID

Request keys stop retries, not re-plans. A restarted agent opened a second return for one damaged book; a partial unique index on the business key returns the open one.

By Sandeep Belgavi · Published 2026-11-09

Request keys stop retries, not re-plans. A restarted agent opened a second return for one damaged book; a partial unique index on the business key returns the open one.

Two returns for one damaged book

An agent at Belgavi's Book Store handles return requests. Jenya reported that a copy in order ORD-1042 arrived damaged. Run 1 of the agent opened a return. Its next step, a call to the warehouse, timed out, and the orchestration restarted the run from its last checkpoint. The restarted run re-read the conversation, re-planned and opened a return again. Later that afternoon Geetha, working the help desk, saw the case and opened a third one by hand.

All three calls used idempotency keys, and the keys worked as designed. Each key was unique to one request, and no request was processed twice. The duplicates came from three different requests that described the same fact: one item in one order needs a return.

This is the gap between request idempotency and business idempotency. Agents widen it, because re-planning, restarts and parallel runs produce new requests for old intentions far more often than a person clicking a button twice. This guide shows how to close it with a business key enforced by the database, and how to decide what is allowed to repeat.

Two keys, two different duplicates

A request key (often called an idempotency key) identifies one attempt to do something. The client generates it, sends it with the request and reuses it on retries. The server remembers the key and the result, and returns the stored result for a repeat. It protects against network-level duplicates: a timeout after the server acted, a client retry, a message delivered twice.

A business key identifies the thing being created in domain terms. For a return it is the order and the item. For a refund it might be the return. For a callback request it might be the customer and the day. It protects against duplicates that arrive as genuinely new requests.

An agent run that restarts and re-plans almost always produces a new request key, because the key was generated inside the step that was lost. Deriving the request key from the run identifier and step number helps with plain retries, but a re-plan can renumber steps, and a second run or a person has a different identifier anyway. The business key does not depend on who asked or how many times.

Enforce the business key where the data lives

The rule "at most one open return per order item" belongs in the database, because only the database sees every writer: agent runs, the help-desk screen, the batch job that imports returns from the website. In SQLite and PostgreSQL a partial unique index states it exactly:

create unique index one_open_return_per_item
    on returns(order_id, isbn13)
    where status in ('requested', 'approved');

The where clause matters. Once a return is refunded or rejected, it is no longer open, so a second, genuinely new return for the same item (the replacement copy was also damaged) is allowed. A plain unique index on (order_id, isbn13) would forbid that forever.

Find or create, and say which happened

The creating code inserts and, if the index rejects the row, reads the existing open return and returns it. It also records the request key, so a retry of the same request gets the same answer:

def create_return(db, request_id, order_id, isbn, reason, created_by):
    key_isbn = isbn13(isbn)                      # normalise before it becomes part of a key
    db.execute("begin immediate")
    row = db.execute("select return_id from requests where request_id=?", (request_id,)).fetchone()
    if row:
        db.execute("commit")
        return row[0], "replayed"                # same request, retried
    try:
        rid = db.execute("insert into returns(order_id, isbn13, reason, status, created_by) values (?,?,?,?,?)",
                         (order_id, key_isbn, reason, "requested", created_by)).lastrowid
        outcome = "created"
    except sqlite3.IntegrityError:               # another request already opened it
        rid = db.execute("select id from returns where order_id=? and isbn13=? and status in ('requested','approved')",
                         (order_id, key_isbn)).fetchone()[0]
        outcome = "existing"
    db.execute("insert into requests(request_id, return_id) values (?,?)", (request_id, rid))
    db.execute("commit")
    return rid, outcome

The three outcomes, created, replayed and existing, go back to the agent as part of the tool result. "A return for this item is already open (RET-1, opened by run 1)" is useful information: the agent can attach to that return instead of telling the customer a new one was started. Returning only an identifier hides the fact that nothing new happened.

In PostgreSQL the same logic can be written with insert ... on conflict (order_id, isbn13) where status in ('requested','approved') do nothing returning id, followed by a select when no row comes back. Either way, the index makes the race safe: when six agent runs called the function at the same moment in the companion example, exactly one return was created and five received existing.

The story, replayed

The companion example runs the afternoon twice: once with only the request key, once with the business key as well.

RequestWhat happenedRequest key onlyWith business key
run-1/step-3agent opens a returnRET-1 createdRET-1 created
run-1/step-3same call retried after a timeoutRET-1 replayedRET-1 replayed
run-2/step-2run restarts and re-plansRET-2 createdRET-1 existing
desk/geetha-1Geetha opens one, ISBN typed with hyphensRET-3 createdRET-1 existing
run-7/step-1after RET-1 is refunded, a new return for the same itemRET-4 createdRET-2 created

With only the request key, three returns were open at once for one damaged book. With the business key, one was open, and the legitimate later return was still allowed because the first had been closed.

Normalise before you compare

The help-desk screen accepted 978-0-306-40615-7; the agent sent 9780306406157. Run without normalisation, the business key treated them as different items and Geetha's return was created as a duplicate. The fix is to normalise in one place before the value becomes part of a key: strip separators, check the length and the ISBN-13 check digit, and reject anything that does not pass. The same applies to email addresses, phone numbers, postcodes and anything else people type. A business key is only as good as the canonical form of its parts.

Choosing the business key

The hard part is not the index, it is deciding what "the same thing" means. Some questions that settle it:

  • What does the customer think happened? If Jenya would say "I asked for one return", the key is order and item. If a second damaged copy in the same order is possible, quantity or line number belongs in the key.
  • What may legitimately repeat? A second reminder email is allowed; a second refund for the same return is not. Repeats that are allowed but limited are budgets, not keys.
  • When does the fact end? The partial index encodes the lifetime. A return is open until it is refunded or rejected. A callback request might be open until the end of the day.
  • Who else creates these records? Every writer must go through the same constraint. If an import job writes directly to the table without the index, the agent's duplicates come back through the side door.

Migration steps

  1. Measure the duplicates you already have. Group existing open records by the candidate key and count groups larger than one. If they exist before agents, they will multiply after.
  2. Clean up, then add the index. A unique index cannot be created over existing duplicates. Close or merge them first; in PostgreSQL use create unique index concurrently on a large table so writes continue.
  3. Change create endpoints to find or create. Return the outcome, not just an identifier. Keep request keys for retries.
  4. Teach the agent what existing means. Add the outcome to the tool description and to evaluation cases: a re-planned run that receives existing should continue with that record, not apologise and create another.
  5. Alert on existing rates. A sudden rise usually means a loop or a restart storm, which is worth knowing even when no duplicate was written.

Failure modes

  • Key too narrow. Order alone as the key blocks a second return for a different item in the same order.
  • Key too wide. Including the free-text reason in the key lets "damaged" and "arrived damaged" create two returns.
  • Constraint only in application code. A check-then-insert in the service has the same race as any read-then-write; the index is what makes concurrent creators safe.
  • Silent merge. Returning the existing record without telling the caller hides a planning error that should show up in traces.
  • Closing to get around the key. If an agent can close a return, it can close one and open another. Closing should be a separate, reviewed action with its own rules.

When this is unnecessary

If records are naturally unique, for example one profile per account, the constraint already exists. If duplicates are harmless and cheap to merge later, such as draft notes, a nightly deduplication job may be simpler. The business key matters when a duplicate causes a second physical or financial effect: a second courier pickup, a second refund, a second message to a customer.

Verification

  • Concurrency test: N concurrent creates with different request keys produce one record and N - 1 existing outcomes.
  • Lifetime test: after closing, a new record for the same key is created.
  • Normalisation test: hyphenated and plain ISBNs map to the same key; an invalid check digit is rejected.
  • Agent evaluation: a restarted run that receives existing attaches to the open return in its reply.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/business_key_dedup. Views are my own and do not represent any employer, past or present.