Event-Driven and Background Agents
When nobody is watching a run, the system around the agent has to notice what a person would.
Event-driven agents start when something happens: a message, a file, a schedule or a change in a system. Put events on a durable queue, assume they can arrive twice or out of order, make handling safe to repeat, set aside work that keeps failing, limit intake when you cannot keep up and give every unattended run narrow rights, a budget and a way to reach a person.
What you will learn: event-driven design, event formats, consumers and retries, scheduled jobs, queues, workers and backpressure, and controls for unattended agents.
Prerequisites: Orchestration vs Automation vs Frameworks and Distributed Systems, Networking and Databases.
Event-driven architecture
A producer announces that something happened. A queue or event service holds the announcement. Consumers react. The producer does not wait and need not know who listens.
| Trigger | Example | Mind |
|---|---|---|
| Message | New support email | Content is untrusted |
| Data change | Record updated | Loops when the agent updates it too |
| Webhook | Notice from another service | Verify the sender |
| File arrival | Report uploaded | Partial or hostile files |
| Schedule | Nightly check | Missed and overlapping runs |
| Threshold | Error rate rises | Floods of repeated alerts |
Command messages ask for work; events report facts. Keep the difference clear, since a consumer may ignore a fact but a command expects an outcome.
What an event should carry
Use a consistent envelope. The CloudEvents specification, a common standard, requires an identifier, a source, a specification version and a type for each event. It lets consumers treat events with the same source and identifier as duplicates, and requires producers to keep that pair unique.
| Field | Use |
|---|---|
| Source and identifier | Recognize repeats |
| Type and version | Choose the handler and read the data |
| Time | Judge staleness |
| Subject | Which record it concerns |
| Tenant and actor | Apply permissions |
| Data or reference | What the handler needs |
| Trace identifier | Follow work across services |
Prefer a reference to current data over copying everything, and re-read the record when handling, since it may have changed.
Does this task suit the background?
| Question | Good sign | Warning sign |
|---|---|---|
| Can the result wait? | Minutes or hours are fine | A person is watching a spinner |
| Are inputs complete? | The event identifies everything needed | Frequent clarifying questions |
| Is success checkable? | Rules or records confirm it | Only a person can tell |
| Are mistakes recoverable? | Drafts and reversible changes | Payments, deletions, external messages |
| Is volume predictable? | Bounded with quotas | Outsiders can trigger unlimited runs |
Start with work that produces suggestions for review. Allow direct action only for narrow cases after measured results, with the ability to return to review mode.
Check at the door
Before spending a model call, validate the envelope and data, confirm the sender, check the tenant is active, discard events that are out of scope or too old, and enforce quotas. Simple filters often remove much of the volume cheaply. Count what you discard and why, so that a broken filter cannot silently drop real work.
Consuming safely
"""Consume events safely: deduplicate, retry, set aside what keeps failing."""
from collections import deque
def consume(events, handle, max_attempts=3):
queue = deque((e, 1) for e in events)
done, dead, log = set(), [], []
while queue:
event, attempt = queue.popleft()
key = (event["source"], event["id"])
if key in done:
log.append(f"{event['id']} duplicate, skipped")
continue
try:
handle(event)
except TimeoutError:
if attempt < max_attempts:
queue.append((event, attempt + 1))
log.append(f"{event['id']} attempt {attempt} timed out")
else:
dead.append((event["id"], "timeouts"))
except ValueError as error:
dead.append((event["id"], str(error))) # retrying cannot help
else:
done.add(key)
log.append(f"{event['id']} handled on attempt {attempt}")
return log, dead
calls = {}
def handle(event):
calls[event["id"]] = calls.get(event["id"], 0) + 1
kind = event["kind"]
if kind == "flaky" and calls[event["id"]] == 1:
raise TimeoutError
if kind == "down":
raise TimeoutError
if kind == "bad":
raise ValueError("missing order number")
def event(i, kind="ok"):
return {"source": "shop", "id": i, "kind": kind}
log, dead = consume([event("e1"), event("e2", "flaky"), event("e1"),
event("e3", "bad"), event("e4", "down")], handle)
print(*log, sep="\n")
print("set aside:", dead)
Output:
e1 handled on attempt 1
e2 attempt 1 timed out
e1 duplicate, skipped
e4 attempt 1 timed out
e2 handled on attempt 2
e4 attempt 2 timed out
set aside: [('e3', 'missing order number'), ('e4', 'timeouts')]
The repeated event is skipped, a brief timeout succeeds on retry, an event with missing data is set aside at once because retrying cannot help, and one that keeps timing out is set aside after three attempts. The program keeps its list of handled events in memory and retries immediately. In production, store the identifier durably and atomically with the effect where possible, or pass an operation key to the target service, and delay retries. A timeout can also mean the action happened, so look before repeating it.
Know your queue's promises. Amazon SQS, for example, hides a received message for a visibility timeout, 30 seconds by default, and it reappears if not deleted in time. Agent runs often take longer, so extend the timeout while working or the same message will be processed twice. Its standard queues deliver at least once, while FIFO queues offer exactly-once processing within their rules. Neither makes your calls to other systems unrepeatable by itself.
Dead-letter queues
A dead-letter queue holds messages that exceeded their attempts. It needs an owner, an alert, a view of the error and a safe way to replay after a fix. An ignored one is simply lost work stored neatly.
Scheduling and background jobs
Schedules raise two questions: what happens to runs missed during an outage, and what happens when the previous run is still going.
"""Decide what a scheduled job does after an outage or an overrun."""
from datetime import datetime, timedelta, timezone
def due(last_done, now, every=timedelta(hours=1)):
slot = last_done + every
while slot <= now:
yield slot
slot += every
def plan(last_done, now, policy, running=False):
missed = list(due(last_done, now))
if not missed:
return "nothing due"
if running:
return "skip: previous run still active"
chosen = {"all": missed, "latest": missed[-1:], "none": []}[policy]
runs = ", ".join(f"{s:%H:%M}" for s in chosen) or "wait for next slot"
keys = [f"report:{s:%Y-%m-%dT%H}Z" for s in chosen]
return f"{len(missed)} due; run {runs}" + (
f"; first key {keys[0]}" if keys else "")
last = datetime(2026, 11, 28, 8, tzinfo=timezone.utc)
now = datetime(2026, 11, 28, 12, 20, tzinfo=timezone.utc)
for policy in ("all", "latest", "none"):
print(f"{policy:<7}{plan(last, now, policy)}")
print("busy ", plan(last, now, "all", running=True))
Output:
all 4 due; run 09:00, 10:00, 11:00, 12:00; first key report:2026-11-28T09Z
latest 4 due; run 12:00; first key report:2026-11-28T12Z
none 4 due; run wait for next slot
busy skip: previous run still active
After a gap of several hours, one policy runs every missed slot, another only the latest and a third waits. Reports per hour may need all; a status summary usually needs only the latest. Each run has a key based on its scheduled slot, so a repeat can be recognized. While a run is active, this example skips; other choices are to queue one or replace it. The "busy" flag must come from a claim with expiry, otherwise a crashed run blocks the schedule forever. Store times in a single reference zone and decide explicitly how daylight saving affects local schedules.
| Background job needs | Provide |
|---|---|
| Status | Queued, running, waiting, done, failed, canceled |
| Progress | Last completed step and time |
| Result delivery | Notification and a place to read it |
| Cancellation | A control that workers check |
| Expiry | Give up when the result is no longer useful |
Queues, workers and backpressure
Backpressure means responding when work arrives faster than it can be finished: slow producers, reject, defer, shed low priority or add capacity.
"""A queue under a burst: what limits and extra workers change."""
ARRIVALS = [4, 4, 20, 20, 20, 4, 4, 4, 4, 4] # events per minute
def simulate(workers, per_worker=3, limit=None, max_workers=None):
waiting = rejected = peak = 0
for arriving in ARRIVALS:
if max_workers: # scale with the backlog
need = -(-(waiting + arriving) // per_worker)
count = max(workers, min(max_workers, need))
else:
count = workers
waiting += arriving
if limit is not None and waiting > limit:
rejected += waiting - limit
waiting = limit
peak = max(peak, waiting)
waiting -= min(waiting, count * per_worker)
return peak, waiting, rejected
print("design peak left rejected")
for name, options in [("3 workers", {"workers": 3}),
("3 workers, cap 30", {"workers": 3, "limit": 30}),
("3 to 6 workers", {"workers": 3, "max_workers": 6}),
("3 to 12 workers", {"workers": 3, "max_workers": 12})]:
peak, left, rejected = simulate(**options)
print(f"{name:<22}{peak:>5}{left:>6}{rejected:>10}")
Output:
design peak left rejected
3 workers 42 8 0
3 workers, cap 30 30 0 12
3 to 6 workers 24 0 0
3 to 12 workers 20 0 0
With three workers the backlog peaks at 42 and some work remains at the end. A cap of 30 keeps the queue bounded by rejecting twelve events, which is only acceptable if producers can retry or the work is optional. Extra workers clear the burst. The model assumes workers appear instantly and measures the peak after each minute's arrivals. Real scaling takes time, and model and tool rate limits may stop extra workers from helping at all.
| Control | Protects |
|---|---|
| Concurrency limit | Providers and databases |
| Per-tenant quota | Fairness |
| Priority queues | Urgent work |
| Queue length or age limit | Freshness and storage |
| Spend budget per period | Cost |
| Circuit breaker | A failing dependency |
Watch the age of the oldest message more than queue length alone; it describes what users experience.
Publishing events reliably
A service often needs to save a change and announce it. Doing these separately can leave a saved record with no event, or an event for a change that was rolled back. The transactional outbox pattern writes the record and a pending event in one database transaction; a relay then publishes pending events and marks them sent. The relay may publish twice after a crash, which is another reason consumers must handle repeats.
Agents started without a person watching
An interactive user notices odd behavior. A background agent has no such observer, and its input often comes from outsiders.
- Give it its own identity with the narrowest rights for that event type.
- Treat event contents and fetched documents as data, never as instructions that widen the task.
- Verify webhook signatures and reject stale or replayed requests.
- Require approval for consequential or irreversible actions.
- Cap steps, time and spend per event and per day.
- Record why each run started and what it did.
- Provide a switch that pauses consumption without losing messages.
Securing the entry points
Each trigger is a way into your system. Authenticate publishers and give each only the topics it needs. For webhooks, verify the signature over the raw body using the sender's documented method, compare timestamps to limit replay and remember identifiers you have processed. Limit payload size, scan files and fetch linked content only from allowed destinations. A message that says an action was approved is not an approval: look it up in the system that records approvals. See Prompt Injection Attacks and Defenses.
Stop event loops
If an agent's output creates an event that starts the same agent, it can run indefinitely. Mark the origin of changes, ignore your own where appropriate, carry a hop count and cause identifier, and alert on unusual rates for one subject. Two agents responding to each other need the same protection.
Ordering and staleness
Events may overtake one another. Process by record key when order matters, compare versions and ignore an update older than the current state. Before acting on a delayed event, re-check that the action still makes sense: a reminder for an order canceled yesterday should not be sent.
Estimating capacity
A rough rule: the average number of busy workers equals arrival rate multiplied by average run time. At 30 events per minute and 40 seconds per run, that is 20 busy workers before any allowance for bursts, retries or slow runs. Plan headroom, then check model token limits, tool quotas and database connections at the same concurrency. These figures are invented for the calculation. See Latency, Load Testing and Capacity Planning.
Test the unpleasant cases
- Deliver the same event twice, together and far apart.
- Deliver out of order.
- Kill a worker mid-run.
- Send a malformed and a hostile payload.
- Burst at several times normal volume.
- Take a dependency down and watch retries and the dead-letter queue.
- Replay dead-lettered messages after a fix.
Measure completion, duplicates with effects, oldest message age, cost per event and items waiting for people.
An agent answers incoming email. A customer's automatic out-of-office replies to it, and it replies again. The fix detects automatic-message headers, limits replies per thread per day and alerts when a thread exceeds the limit.
Telling people what happened
Background work is useful only if its results reach someone. Send a short notice with the outcome, what was changed, what is waiting and a link to the detail. Group routine successes into a digest and send failures and decisions promptly to a named queue, not to an inbox nobody reads. Distinguish "nothing to do" from "did not run": a silent job looks the same as a healthy one, so alert when an expected run or heartbeat is missing. Periodically ask whether anyone still uses the output, and retire jobs that only consume money.
Common mistakes
- Assuming each event arrives once and in order.
- Visibility timeouts shorter than agent runs.
- Retrying permanent errors.
- Unwatched dead-letter queues.
- Unlimited queues and workers.
- Schedules with no overlap or catch-up rule.
- Broad rights for agents triggered by outside content.
Checklist
- Events have unique identifiers, types and versions.
- Handling is safe to repeat.
- Retries are delayed and limited.
- Dead-letter items have an owner and alert.
- Missed and overlapping schedules have policies.
- Intake, concurrency and spend are bounded.
- Loops are detected and stopped.
- Unattended agents are narrow, traced and pausable.
Frequently asked questions
Queue or workflow engine?
A queue delivers independent work items. An engine tracks multi-step progress. A queue can start workflows that the engine then runs.
Can I get exactly-once processing?
Some services offer it within defined limits. Design effects to be safe if repeated, because your external calls sit outside those limits.
How many workers should I run?
Enough to meet your message age target without exceeding rate limits or budget. Measure with realistic run times.
How should users follow a background task?
Return an identifier, show status and progress, notify on completion or need for input and let them cancel.
References and further reading
- CloudEvents specification
- Amazon SQS: visibility timeout
- Amazon SQS: dead-letter queues
- Microsoft: queue-based load leveling pattern
Next steps
Workflow Versioning, Testing and Resilience
Retries, versions and tests.
Durable Execution, Checkpoints and Approvals
Resume long runs.
Tool Permissions, Approvals and Abuse Risks
Limit what runs may do.