Turn invoice events into tasks that run once, however often they arrive
An event-driven agent receives duplicates, events out of order and events its own actions caused. Admit each invoice event through a deduplication record, an actor filter and a per-invoice task key, and claim work under a lease that expires, so every invoice is processed exactly once in effect.
18 MIN
By AIAgentInterviews · Updated
TL;DR: Do not let raw events drive the agent. Put an intake step in front of it that records every event id it has seen, ignores events the agent itself caused, collapses events about the same invoice into one task keyed by the invoice, and hands tasks to workers under a lease that expires. The agent then works on tasks, and duplicates, reorderings and its own echoes never reach it.
Where you are. The first lesson. Wrenfield Supplies' accounts-payable agent exists as a loop that can match one invoice. Now it has to wake up on its own.
The inbox that never stops
Wrenfield's invoices arrive through three channels: a supplier portal, an email parser and the purchasing system. Each publishes an event when an invoice appears or changes. In the first week of running the agent directly on those events, three things went wrong, none of them the model's fault.
The same invoice arrived from the portal and from email within a minute, so two runs matched it and one of them queued a second payment proposal. The portal re-sent an event after a timeout, so a third run started. And when the agent wrote a note on an invoice ("matched to PO-4471"), the purchasing system published "invoice updated", and the agent woke up and matched it again.
In plain language. An event is a notification that something happened, delivered at least once and possibly more. A task is the agent's unit of work, created once per invoice. A lease is a time-limited claim on a task by one worker; if the worker dies, the lease runs out and another worker may take the task. An actor is whoever caused a change, recorded on the change itself.
Separate events from tasks
The fix is a small intake step between the event stream and the agent. It answers four questions for every event, in this order:
- Have I seen this event id? If so, drop it. Brokers redeliver.
- Did the agent cause it? If the event's actor is the agent, drop it. That breaks the echo.
- Which invoice is it about? Normalise to the invoice key: supplier id plus invoice number, not the channel's own id, because two channels describe the same invoice with different ids.
- Is there already an open task for that invoice? If so, attach the event to it as new evidence. If not, create one.
Only tasks reach workers, and workers claim them under a lease.
Event
portal, email, purchasing
Seen before?
event id record
Caused by us?
actor filter
Which invoice?
supplier + number
Task
one per invoice, leased
A worked case: one invoice, five events
Here is the intake on the five events Wrenfield's logs showed for invoice 9188 from the supplier Calloway Paper. The figures are synthetic.
def invoice_key(event):
return f"{event['supplier'].lower()}:{event['invoice_no'].strip().upper()}"
class Intake:
def __init__(self, agent_id):
self.agent_id, self.seen, self.tasks = agent_id, set(), {}
def admit(self, event):
if event["id"] in self.seen:
return "duplicate"
self.seen.add(event["id"])
if event["actor"] == self.agent_id:
return "own change"
key = invoice_key(event)
if key in self.tasks:
self.tasks[key]["evidence"].append(event["id"])
return f"evidence for {key}"
self.tasks[key] = {"evidence": [event["id"]], "state": "queued"}
return f"new task {key}"
intake = Intake("agent:ap")
events = [
{"id": "p-1", "supplier": "Calloway", "invoice_no": "9188", "actor": "portal"},
{"id": "m-7", "supplier": "calloway", "invoice_no": " 9188", "actor": "email"},
{"id": "p-1", "supplier": "Calloway", "invoice_no": "9188", "actor": "portal"},
{"id": "u-3", "supplier": "Calloway", "invoice_no": "9188", "actor": "agent:ap"},
{"id": "u-4", "supplier": "Calloway", "invoice_no": "9188", "actor": "clerk:maya"},
]
print([intake.admit(e) for e in events])
print(len(intake.tasks), intake.tasks["calloway:9188"]["evidence"])
# => 1 ['p-1', 'm-7', 'u-4']
Five events became one task with three pieces of evidence. The portal's redelivery was dropped by id; the agent's own note was dropped by actor; the email copy and the clerk's later edit were attached to the existing task, because they might matter. The clerk's edit is a good example: it is not a duplicate, and the agent should see it before acting.
Two design choices in that code carry weight. The key normalises case and whitespace, because two channels format the same invoice number differently. And attaching new events to an open task, rather than starting a second run, is what stops two runs competing over the same invoice.
Leases, not locks forever
A worker claims a queued task with a lease of, say, five minutes, and renews it while working. If it crashes, the lease lapses and another worker takes the task, starting from whatever the task's state recorded. Two rules keep leases honest:
- Renew while working, release while waiting. When the agent needs a controller's approval, it moves the task to a waiting state and releases the lease. Holding a lease for hours blocks a worker and hides crashes.
- Check the lease before every side effect. A worker that was paused by a long garbage collection may wake with an expired lease while another worker has taken over. Before writing anything, it confirms it still holds the claim, or it stops.
Side effects themselves still need idempotency keys tied to the business action (the payment for invoice 9188, not "this run's payment"), because leases reduce duplicate work but cannot make a crash between a write and its record impossible. Lesson five builds that for payments.
What intake does not decide
Intake decides whether there is work. It does not decide whether the invoice is genuine, whether it matches, or whether to pay. Those are the agent's and the policy's jobs, with the evidence the intake collected. Keep intake boring and deterministic; it should never call a model.
What if · interview follow-ups
Change one condition
Wrenfield's intake admits events for invoice 9188 into a single task.
Start here
The supplier sends a corrected invoice with the same number but a new total. New task or evidence?
Is it the same invoice, and is the open task safe to continue?
Attach it as evidence to the open task and move the task back to matching, so the agent re-evaluates with the new total before any payment. If the task already paid, open a follow-up task for the correction rather than reopening a finished one.
Weak answerCreating a second task, so two runs decide about one invoice.
Constraint changes
A worker's lease expires mid-match because the matching tool hung. Another worker takes the task. What must the first worker do if it wakes up?
Who owns the task now?
Check its lease before any write, find it no longer holds the task, and stop without writing. The second worker continues from recorded state.
Weak answerFinishing the write because it had already decided.
Constraint changes
Finance asks the agent to add a tag to every invoice it processed. How does that interact with the actor filter?
Who is the actor of the tag?
The tags are the agent's changes, so their update events are dropped by the actor filter. If another system rewrites the invoice in response to the tag, that event has a different actor and will arrive; decide whether it is evidence or noise by its type.
Weak answerDisabling the actor filter for tags and waking the agent on every one.
Do this before moving on
Build Wrenfield's intake for your own synthetic stream: at least twenty events covering duplicates by id, the same invoice from two channels with different formatting, events caused by the agent, a later human edit and a corrected invoice. Add leases with expiry and a check before writes.
Review your result. Show the task table after the stream: one task per invoice, the evidence attached to each, and the dropped events with the reason for each drop. Then kill a worker mid-task and show another completing it without a second write.
Go deeper
- Event-driven and background agents: the four rules this intake implements, with the inbox people use to supervise.
- Idempotent side effects: keys tied to the business action, which leases alone cannot replace.
- Side effects that survive retries: what to record so a crash between a write and its journal entry is recoverable.
- An agent that triggers itself: the interview version of the echo problem, with the defences scored.
Key takeaways
- Events arrive at least once, out of order and sometimes caused by the agent itself; tasks should not.
- Dedupe by event id, drop the agent's own changes, and key tasks by the business object, normalised.
- Attach new events to an open task as evidence instead of starting a competing run.
- Leases expire on crashes; release them while waiting and re-check them before every write.
Check yourself
Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.
1Why key tasks by supplier and invoice number rather than by the channel's event id?
2What should a worker do before writing anything after a long pause?
3Why should the intake step never call a model?
Sign in to track which lessons you have finished.