When the agent writes back: idempotency keys, dedupe and an undo path

Most agent tutorials stop at the read. Pull the placements, bucket the end dates, build the list. That part is safe: if the sync is wrong, you rerun it and nobody notices.

Writes are different. The first time an agent puts something into the ATS — a note on a candidate, an activity record, a task for a recruiter, a status change on a submission — your automation has entered the system of record that your recruiters, your invoices and, eventually, a client dispute all depend on. A retry loop that logged 2,400 duplicate notes over a long weekend is not a story anybody tells twice.

This is the pattern we build before an agent is allowed to write anything, on Loxo, Crelate, JobAdder, Vincere or Recruiterflow alike.

The failure you are actually defending against

It is not the agent deciding something stupid. Human-in-the-loop handles that: the agent drafts, a person approves, the same boundary described in our approval queue walkthrough.

It is plumbing. Three shapes, in rough order of how often they bite:

  1. The ambiguous timeout. You POST a note. The ATS gets it, commits it, and the response dies on the way back. Your HTTP client retries. Two notes.
  2. The replayed batch. A run crashes at item 180 of 300. Somebody reruns it from the top. Items 1 to 179 happen again.
  3. The clobber. The agent updates a candidate's availability field using a record it read forty minutes ago. In between, a recruiter typed something better. The agent wins, and nobody can see what was lost.

All three are solved with boring mechanics, not better prompts.

Step one: give every intended write a key

An idempotency key is a string your code computes from the meaning of the write, before any API call. Same intent, same key, forever.

import hashlib

def write_key(kind, entity_id, run_scope, payload_fingerprint):
    raw = f"{kind}|{entity_id}|{run_scope}|{payload_fingerprint}"
    return hashlib.sha256(raw.encode()).hexdigest()[:32]

# "log the redeployment outreach note for candidate 88112,
#  for the week starting 2026-09-21"
key = write_key("redeploy_note", 88112, "2026-W39", "outreach_v3")

Note what is not in the key: a timestamp, a UUID, the model's output text. Those change on every run and would hand you back the duplicates you are trying to prevent. run_scope is the unit of intended repetition — a week, a pay period, an assignment id. It says plainly: this note is meant to happen once per candidate per week.

Some ATS APIs accept an Idempotency-Key header. Use it when it exists, but do not depend on it. Enforce the key on your side, where you control the semantics.

Step two: a write log that is also the lock

One table. It is your dedupe check, your audit record and your undo source.

create table agent_writes (
  write_key      text primary key,
  run_id         uuid not null,
  system         text not null,          -- 'jobadder', 'timesheets'
  entity_type    text not null,          -- 'candidate', 'placement'
  entity_id      text not null,
  action         text not null,          -- 'create_note', 'update_field'
  status         text not null,          -- intent|sent|confirmed|failed|reverted
  before_value   jsonb,
  request_body   jsonb not null,
  remote_id      text,
  actor          text not null,          -- approving human, or 'agent:redeploy'
  created_at     timestamptz not null default now(),
  confirmed_at   timestamptz
);

The sequence is always: insert the row as intent first, then call the API, then update to confirmed with the remote_id. Because write_key is the primary key, a replayed batch fails the insert and skips — the database does your dedupe, not an if statement racing another worker.

Two fields earn their keep later. before_value is what the field held immediately before you touched it; without it there is no undo. actor is the person who approved, not the agent, because when a client asks in November who changed a submission status, "the automation" is not an answer.

Step three: a dedupe window for the things keys cannot catch

Keys stop exact repeats. They do not stop an agent sending a second, differently-worded nudge to a contractor who was already chased yesterday, because the payload genuinely differs.

So add a rule check before send, in the same spirit as the chase rules in our Timesheet and Compliance Chaser:

select count(*) from agent_writes
where entity_type = 'candidate'
  and entity_id = :candidate_id
  and action in ('create_note', 'send_outreach')
  and status in ('sent', 'confirmed')
  and created_at > now() - interval '72 hours';

Non-zero means hold, and route it to the daily exceptions list instead. Pick the window from how the work actually runs — a timesheet chase on a weekly cycle wants a different number from a credential expiry at 90, 30 and 7 days out.

Step four: reconcile, because failed usually means maybe

Any row sitting in intent or failed after a run is a question, not a conclusion. The write may have landed. Before the next run, read back from the ATS and check: does a record matching this key's intent exist for that entity in that window?

If yes, mark it confirmed and attach the remote_id. If no, it is genuinely eligible to retry. Agents that skip this step are the ones that duplicate on Tuesday what they half-wrote on Monday.

Step five: the undo path

Assume you will need it, and build it before go-live rather than during the incident. The requirement is narrow and achievable: given a run_id, reverse every confirmed write from that run.

  • Created records (notes, activities, tasks): delete by remote_id if the API allows it; otherwise append a clearly worded correction and flag the originals for a human. Decide which, in writing, before the first run.
  • Updated fields: restore before_value, but only if the field still holds what the agent wrote. If it does not, a person has edited it since — leave it alone and list it for review.
  • Anything that left the building — an email, an SMS, a submission to a client — is not undoable. Those get a correction and a phone call. Which is the argument for keeping sends behind approval in the first place.

One command, runnable by an operations lead at 7am: undo-run <run_id> --dry-run, then the same without the flag. If reversing a bad batch requires an engineer with database access, you do not have an undo path, you have a hope.

What this costs

Maybe a day of build on the first agent, less on the ones after, because the table and the helpers are reused. Set against it: the one weekend an API change turns every write into a timeout-and-retry, and the difference between a line in the exceptions report and a recruiter cleaning 2,400 notes out of the ATS by hand.

We do not let an agent write to a client's system of record without it. If you are scoping a build and want the write path drawn properly, tell us your ATS and what you want written.