Event-Driven AI Agents: Queues, Delivery Semantics, and Recovery
Build event-driven AI agents with durable acceptance, duplicate handling, transactional outboxes, lease recovery, and safe poison-message redrive policies.
Abhishek Raj · · 7 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
An event-driven AI agent starts or resumes work when something happens: a document arrives, a customer replies, a tool finishes, or an approval is recorded. The queue decouples that occurrence from the worker that handles it. Reliability comes from the surrounding state transitions, especially when a message is repeated or a worker disappears halfway through an action.
This guide develops an illustrative document-review workflow. The proposed schemas and policies are design examples, not a tested implementation or a claim about production performance.
Separate events, jobs, and agent decisions
An event describes an occurrence. A job assigns work in response. An agent decision proposes a next step within that job. Keeping these concepts separate prevents a queue redelivery from becoming a brand-new interpretation of the same business event.
CloudEvents standardizes an event envelope and requires a unique combination of source and id for distinct events. A repeated event can retain that identity. It defines interoperable event metadata, not the business outcome or authorization policy of your agent. CloudEvents 1.0.2 specification.
For the hypothetical reviewer, an event says that document version 12 became available. The corresponding job asks the agent to extract specified fields from that version. The model may propose another retrieval step, but it cannot change the event identity or silently replace version 12 with a newer file.
A useful application record might contain:
{
"event_source": "https://example.com/document-service",
"event_id": "evt_842",
"event_type": "com.example.document.available.v1",
"document_ref": "doc_91@12",
"workflow_id": "review_203",
"policy_version": "review-policy-4"
}
These are illustrative fields. Validate their formats and resolve document access using authenticated service context. An identifier inside a message is a lookup hint, not proof that its publisher can authorize access.
Choose the acknowledgement boundary deliberately
Amazon SQS standard queues can deliver a message more than once; AWS explicitly recommends idempotent consumers. Receiving a message therefore cannot be treated as acquiring permanent ownership of the business operation. SQS at-least-once delivery.
There are two useful application contracts:
| Contract | Acknowledge after | Recovery responsibility |
|---|---|---|
| Queue owns the complete short task | Durable completion of that task | Queue redelivery plus task deduplication |
| Queue delivers a trigger to a workflow engine | Durable acceptance into recoverable workflow storage | Workflow scheduler and checkpoint recovery |
For a long-running reviewer, the second contract can simplify operation. In one local database transaction, record the accepted event and create the runnable workflow. Acknowledge the queue only after that commit. The scheduler must independently discover runnable workflows; otherwise a process crash after acknowledgement can strand work.
Deduplication must inspect status. A completed record can reuse its result. An accepted workflow can return its existing identifier. A transient worker claim without durable, recoverable work is insufficient: acknowledging that duplicate could discard the only remaining trigger.
Make business updates and emitted events atomic locally
Suppose extraction finishes and the application must both save the result and announce document.reviewed. Writing the database and publishing directly to a broker creates a gap: either operation can succeed while the other fails.
The transactional outbox pattern writes business state and an event record in the same database transaction. A separate relay publishes committed records. AWS describes this as a solution to the dual-write problem and notes that consumers still need to handle duplicate notifications. AWS transactional outbox pattern.
In this proposed reviewer, the completion transaction would:
- Confirm that the workflow revision still matches the worker's expected revision.
- Save the extracted result and its source document version.
- Mark the workflow completed.
- Insert an outbox event with a stable event identifier.
If the transaction rolls back, none of these changes becomes authoritative. If the relay publishes and crashes before marking the row published, it may publish again. That is acceptable only because consumers recognize the stable identity.
The outbox does not include a remote payment, email, or model request in the same transaction. Those operations need their own recorded intent and reconciliation contract. See idempotency for agent actions for the remote-effect boundary.
Treat visibility as a renewable lease
In SQS, receipt temporarily hides a message; failure to delete it before the visibility timeout allows redelivery. Visibility can be extended, but AWS documents that standard queues can still deliver duplicates during this period. It is not a correctness lock. SQS visibility timeout.
For a worker processing a short queue-owned task, choose a visibility period based on observed processing time and renew it while making progress. Separately maintain an application claim with a revision or fencing token. Before persisting results, verify the worker still owns the current claim.
For the trigger-to-workflow design, visibility only needs to cover validation and durable acceptance. Do not hold a queue receipt open during a human approval that might take hours. Persist a waiting state and resume on a later approval event instead.
If a lease expires while an external call is running, two workers may overlap. Conditional database writes prevent a stale worker from replacing newer state, but cannot undo an email it already sent. Fence writes at the destination where possible, or use a stable action key and query its status after an ambiguous timeout.
Walk through a crash without losing the task
Consider this hypothetical sequence:
- The ingress consumer receives event
evt_842. - Its acceptance transaction inserts an inbox record and workflow
review_203. - The process crashes before acknowledging the queue.
- Another consumer receives the event and finds the existing accepted workflow.
- It acknowledges the duplicate after confirming the workflow remains recoverable.
- A workflow worker claims the runnable record and begins extraction.
The first model response is recorded against a specific step. If a worker crashes after storing the result, recovery reads that record rather than issuing another model call automatically. If it crashes before storing a response, a repeated call may be necessary and may produce a different answer. This is a cost and reproducibility boundary, even without external business effects.
Suppose the document later advances to version 13. The old job should either finish explicitly against version 12 or become superseded according to policy. It should not mix evidence from both versions. The event that announces version 13 has a different identity and may create a separate job.
For workflows with several resumable steps, use durable agent workflow principles rather than growing a single queue callback into an implicit workflow engine.
Quarantine poison messages with useful evidence
Not every failure deserves another model attempt. A malformed payload, unsupported event version, revoked document access, and temporary dependency outage need different handling.
SQS dead-letter queues isolate repeatedly unsuccessful messages using a configured receive threshold. Its documentation also warns that moving a message to a dead-letter queue can disrupt workflows requiring exact FIFO ordering. SQS dead-letter queues.
An application policy can distinguish:
- Invalid envelope: quarantine with a schema error and publisher identity.
- Temporary dependency failure: schedule bounded retries with increasing delay and jitter.
- Unknown remote outcome: reconcile the existing action before retrying.
- Unsupported event version: hold for migration or route to a compatible consumer.
- Budget exhausted: stop the workflow with an explicit operational outcome.
Preserve the original event identity during redrive. Fixing code and replaying a failed delivery should not manufacture a new business occurrence. Record a separate recovery-attempt identifier for diagnosis.
Also record whether any effects already occurred. A dead-letter message does not prove that nothing happened. Blindly redriving an event after partial completion can repeat actions unless the workflow resumes from its ledger.
Validate failure sequences, not just handlers
A useful test harness controls broker delivery, worker crashes, database commits, and tool responses. Verify invariants after each sequence:
- Repeated delivery creates one logical workflow for the chosen deduplication scope.
- Acknowledged triggers have durable, discoverable work or a durable terminal rejection.
- A stale claim cannot overwrite a newer result.
- Every published completion event corresponds to committed completion state.
- Redrive preserves business identity and does not erase prior effects.
Measure acceptance delay, runnable-workflow age, oldest outbox age, duplicate rate, repeated attempts, and quarantine age. A healthy broker queue can coexist with a stuck workflow scheduler, so inspect both layers.
Run a failure exercise where the relay crashes after publishing, another where a worker loses its lease, and another where model output cannot satisfy semantic validation. The expected outcome should be a recoverable state or an explicit stop, never a silent success label.
Frequently asked questions
Does a FIFO queue make the whole agent exactly once?
Do not infer a whole-system guarantee from broker behavior. A worker can still crash around a database commit or remote effect. State the guarantee at each boundary and design recovery for ambiguous outcomes.
Should every agent thought become an event?
Persist decisions needed for recovery, auditing, or coordination. Turning every transient model token into a business event adds volume and exposes unnecessary content. Keep operational traces distinct from authoritative workflow transitions.
When is a queue unnecessary?
A short synchronous request may be simpler when it fits the request deadline and needs no durable waiting. Introduce asynchronous delivery when independent scaling, burst absorption, or recoverable long-running work justifies its operational cost.
Source reference list
Related reading
- Idempotency for AI Agent Actions: Preventing Duplicate Side Effects
Prevent duplicate AI agent actions with stable intent identities, immutable request fingerprints, durable ledgers, and recovery for uncertain outcomes.
- Durable AI Agent Workflows: Checkpoints, Replay, and Recovery
Design durable AI agent workflows with checkpoints, recorded decisions, safe retries, and recovery paths that handle crashes without duplicating actions.
- AI Agent Retries and Timeouts: Deadlines, Jitter, and Retry Budgets
Design AI agent retries around end-to-end deadlines, classified failures, jitter, shared budgets, and cancellation without multiplying unsafe side effects.