08A.13 Background and Long-Running Agents
Most agents in tutorials answer a person who is waiting. Many agents in production do not. A schedule fires at 7 a.m. and an agent writes the daily digest. A payment webhook arrives and an agent triages the failure. A queue holds ten thousand tickets and agents work through them overnight. Nobody is watching, so the engineering is different: the work must survive crashes, never run twice by accident, stay inside a budget, and tell a human when it needs one. In this lesson you build a small but complete background agent runner in plain Python: triggers, a job table with a state machine, leases and heartbeats, retries with backoff, a dead-letter queue, notifications, a budget guard and a kill switch. It builds on the trigger table in 08A.14 section 7.5 and the approval gate from 08A.12, and it ends where durable execution begins (08C.3).
What you'll learn
- The three ways an unattended agent starts: event or webhook, schedule (cron) and queue, and what each one demands of your code
- The job state machine: queued, running, succeeded, dead, stopped, awaiting approval
- Idempotent job handling: dedupe keys at the trigger and idempotent effects inside the job
- Leases and heartbeats: how a crashed worker's job gets picked up by another, and how a "zombie" worker is stopped from overwriting the new owner
- Retries, backoff with jitter, poison messages and the dead-letter queue
- Notifying the user: when to speak and when to stay quiet
- Budgets and a kill switch for runs nobody is watching
- Why unattended agents need tighter autonomy than interactive ones
- What to observe, and what the providers' own background features do and do not give you
What you don't need
- API keys. The runner uses a scripted agent and runs offline with real output. Part 11 says where the providers' background features fit and links to the lessons that cover them; it runs no provider call.
- Docker, Redis, Celery, Kafka or any server. The "queue" is an in-memory SQLite table (
sqlite3is in the Python standard library) and workers are threads. - A framework. Durable-execution engines such as Temporal and AWS Step Functions come up only as the next step after the toy in Part 12.
Setup
Python 3.11 or newer and the standard library only. As of 1 December 2026 there is nothing to install. Save each block under the file name in its first comment line, in one folder, and run python3 demo_jobs.py <scenario>.
What you must be able to do after this lesson#
- Build a job runner that models each agent run as a job with a written state machine and moves it only along allowed transitions
- Deduplicate triggers on the logical job (event id for webhooks, job name plus time slot for cron, message id for queues) so a repeat creates one job
- Reclaim a crashed worker's job with leases and heartbeats, and fence writes so a stale worker cannot overwrite the new owner
- Retry transient failures with backoff and jitter, and move poison jobs to a dead-letter state that notifies a human
- Stop unattended runs with per-job budgets and a kill switch, and park risky calls as propose-and-notify instead of running them
- Choose what to notify on, and monitor job state, queue age and silence
- Test a runner with invariant checks for duplicates, crashes, budgets and the kill switch
Why this matters for an AI engineer#
A chat agent has a person to catch its mistakes. A background agent has a log file. The same bugs that cost a user a moment of confusion (a repeated step, a retry that sends twice, a loop that never ends) cost money, send emails to customers, or quietly stop working for a week. Almost every serious agent deployment grows a background mode, and that is where the "boring" engineering (idempotency, leases, budgets) decides whether you sleep.
| You'll hear... | You'll understand it after... |
|---|---|
| "It runs on a cron job and posts a digest." | Part 3: Triggers |
| "The webhook fired twice and we got two refunds." | 3.1 Webhooks |
| "A worker died mid-job; who picks it up?" | Part 5: Leases and heartbeats |
| "Retry three times, then dead-letter it." | Part 6: Retries and the dead-letter queue |
| "Don't page me for every retry." | Part 7: Notifying the user |
| "It ran all weekend and spent how much?" | Part 8: Budgets and the kill switch |
| "Why can't it just send the email by itself?" | Part 9: Tighter autonomy when unattended |
| "OpenAI has a background mode, and Anthropic has batches." | Part 11: Provider background features |
Part 1: Three kinds of unattended agent#
1.1 What "background" means#
A background agent is an agent run that is started and finished without a person waiting on the other end of a request. A long-running agent is one whose run takes longer than a request can reasonably stay open: minutes, hours or days. They overlap but are not the same. A scheduled digest is background and short. A research task that runs for three hours while the user is in a meeting is background and long.
Interactive versus background changes four things at once:
| Interactive | Background | |
|---|---|---|
| Who starts it | A user request | A trigger: event, timer or queue message |
| Who can answer a question | The user, now | Nobody, now |
| What a crash looks like | A visible error | Silence, unless you built detection |
| What stops a runaway | The user closes the tab | Only what you built: budgets, kill switch |
08A.14 section 7.5 tabulates the trigger models and the risks that sit before the loop starts. This lesson turns that table into running code. 11C.1 section 5.11 compares sync and async serving shapes for the same work; here we go inside the async worker. The loop inside each job is the loop from 08A.2 and its budgets are 08A.3; here we build everything around it.
1.2 What the running example does#
The jobs below belong to the support assistant: a daily digest of open tickets, a ticket-triage run per webhook event, a flaky call to an upstream API, and an outreach job that wants to send an email. The agent inside each job is a script of tool steps (like the scripted model in 08A.2 section 3.5), so every run is deterministic and costs nothing. What you are testing is the runner, not the model.
Part 2: The job table and its state machine#
11C.1, section 2.9 builds an in-process accept-and-poll job layer, and section 5.5 names the queue-and-worker systems. This part builds the agent-specific job table: states, leases and fenced writes.
2.1 States#
Every job is a row with a state. A state machine is a fixed list of states and the allowed moves between them. Writing it down prevents the worst background bug: a job in a state nobody knows how to leave.
stateDiagram-v2
[*] --> queued: enqueue (deduped)
queued --> running: claim (lease granted)
running --> succeeded: finish
running --> queued: retry with backoff
running --> queued: lease expired (worker crashed)
running --> dead: attempts used up
running --> stopped: budget or kill switch
running --> awaiting_approval: needs a human
awaiting_approval --> queued: approved (08A.12)
succeeded --> [*]
dead --> [*]
stopped --> [*]| State | Meaning | Who moves it on |
|---|---|---|
queued |
Waiting for a worker, possibly until a retry time | A worker claiming it |
running |
A worker holds a lease on it | The worker, or the lease expiring |
succeeded |
Finished; result stored | Terminal |
dead |
Gave up after the allowed attempts: the dead-letter state | A human, who reads it and may re-queue |
stopped |
Ended on purpose by a budget or the kill switch | A human decides |
awaiting_approval |
Parked: the agent proposed something that needs a person | The approval flow of 08A.12 |
2.2 The store#
Here is the whole queue, about 100 lines. Read the comments: each method exists to remove one specific failure from this lesson.
# jobs.py (part: store)
from __future__ import annotations
import hashlib
import hmac
import json
import random
import sqlite3
import threading
class Clock:
"""Fake time, so leases and backoff are testable without sleeping."""
def __init__(self, t: float = 0.0):
self.t = t
def now(self) -> float:
return self.t
def advance(self, s: float) -> None:
self.t += s
class JobStore:
"""States: queued -> running -> succeeded | dead | stopped | awaiting_approval.
sqlite3 stands in for your real database. A real one would claim with
SELECT ... FOR UPDATE SKIP LOCKED or UPDATE ... RETURNING; here a lock does the job."""
def __init__(self, clock: Clock, lease_s: float = 30, max_attempts: int = 3, seed: int = 7):
self.clock, self.lease_s, self.max_attempts = clock, lease_s, max_attempts
self.seed = seed
self.kill = threading.Event() # the kill switch
self.lock = threading.Lock()
self.db = sqlite3.connect(":memory:", check_same_thread=False)
self.db.row_factory = sqlite3.Row
self.db.executescript("""
CREATE TABLE jobs (
id INTEGER PRIMARY KEY, dedupe_key TEXT UNIQUE NOT NULL,
kind TEXT, payload TEXT, state TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
lease_owner TEXT, lease_expires REAL, next_run_at REAL NOT NULL,
last_error TEXT, result TEXT, cost REAL NOT NULL DEFAULT 0);
CREATE TABLE events (job_id INTEGER, t REAL, kind TEXT, detail TEXT);
""")
def _event(self, job_id, kind, detail=""):
self.db.execute("INSERT INTO events VALUES (?,?,?,?)", (job_id, self.clock.now(), kind, detail))
def enqueue(self, dedupe_key: str, kind: str, payload: dict) -> tuple[int, bool]:
"""Idempotent: the same dedupe_key never creates a second job."""
with self.lock:
cur = self.db.execute(
"INSERT OR IGNORE INTO jobs (dedupe_key, kind, payload, state, next_run_at) VALUES (?,?,?,?,?)",
(dedupe_key, kind, json.dumps(payload), "queued", self.clock.now()))
row = self.db.execute("SELECT id FROM jobs WHERE dedupe_key=?", (dedupe_key,)).fetchone()
if cur.rowcount:
self._event(row["id"], "enqueued", dedupe_key)
return row["id"], bool(cur.rowcount)
def claim(self, worker: str) -> dict | None:
"""Take one runnable job and lease it. An expired lease makes a running job claimable again."""
if self.kill.is_set():
return None # kill switch: nothing new starts
with self.lock:
now = self.clock.now()
while True:
row = self.db.execute(
"""SELECT * FROM jobs WHERE (state='queued' AND next_run_at<=?)
OR (state='running' AND lease_expires<?) ORDER BY id LIMIT 1""", (now, now)).fetchone()
if row is None:
return None
if row["state"] == "running":
self._event(row["id"], "lease_expired", f"was held by {row['lease_owner']}")
if row["attempts"] >= self.max_attempts:
self.db.execute("UPDATE jobs SET state='dead', last_error='lease expired too many times' WHERE id=?",
(row["id"],))
self._event(row["id"], "dead", "lease expired too many times")
continue
attempt = row["attempts"] + 1
self.db.execute("UPDATE jobs SET state='running', attempts=?, lease_owner=?, lease_expires=? WHERE id=?",
(attempt, worker, now + self.lease_s, row["id"]))
self._event(row["id"], "claimed", f"{worker} attempt {attempt}")
return {**dict(row), "attempt": attempt, "payload": json.loads(row["payload"]), "worker": worker}
def heartbeat(self, job: dict) -> bool:
"""Extend the lease, but only if we still own this exact attempt."""
with self.lock:
cur = self.db.execute(
"UPDATE jobs SET lease_expires=? WHERE id=? AND lease_owner=? AND attempts=? AND state='running'",
(self.clock.now() + self.lease_s, job["id"], job["worker"], job["attempt"]))
return cur.rowcount == 1
def finish(self, job: dict, state: str, result: dict | None = None, error: str | None = None,
cost: float = 0.0) -> bool:
"""Fenced write: a stale worker (old attempt, expired lease) cannot overwrite the new owner."""
with self.lock:
cur = self.db.execute(
"""UPDATE jobs SET state=?, result=?, last_error=?, cost=cost+?, lease_owner=NULL
WHERE id=? AND lease_owner=? AND attempts=? AND state='running'""",
(state, json.dumps(result) if result is not None else None, error, cost,
job["id"], job["worker"], job["attempt"]))
ok = cur.rowcount == 1
self._event(job["id"], state if ok else "finish_rejected", error or "")
return ok
def retry_or_dead(self, job: dict, error: str, cost: float = 0.0) -> str:
with self.lock:
if job["attempt"] >= self.max_attempts:
state, wait = "dead", 0.0
else: # exponential backoff with full jitter
state = "queued"
rng = random.Random(f"{self.seed}-{job['id']}-{job['attempt']}") # per-job, so thread order cannot change it
wait = rng.uniform(0, min(300, 5 * 2 ** job["attempt"]))
cur = self.db.execute(
"""UPDATE jobs SET state=?, last_error=?, next_run_at=?, lease_owner=NULL, cost=cost+?
WHERE id=? AND lease_owner=? AND attempts=? AND state='running'""",
(state, error, self.clock.now() + wait, cost, job["id"], job["worker"], job["attempt"]))
if cur.rowcount == 1:
self._event(job["id"], "retry_scheduled" if state == "queued" else "dead",
f"{error}; next in {wait:.1f}s" if state == "queued" else error)
return state
def rows(self):
return self.db.execute("SELECT * FROM jobs ORDER BY id").fetchall()
def events(self, job_id):
return self.db.execute("SELECT * FROM events WHERE job_id=? ORDER BY rowid", (job_id,)).fetchall()Three design points to keep in mind while you read.
Dedupe key. dedupe_key TEXT UNIQUE plus INSERT OR IGNORE means enqueueing the same logical job twice creates one row. That one line is what makes retried webhooks and double-firing schedulers harmless (Part 3).
Claim as one atomic step. A worker must find a job and mark it as its own without another worker doing the same. Here a Python lock plays the role; in a real database you use a single atomic statement, such as UPDATE ... RETURNING or SELECT ... FOR UPDATE SKIP LOCKED. The lesson is the shape, not the lock.
Fenced writes. finish and retry_or_dead only change a row if the caller still owns this attempt (lease_owner and attempts match). A worker whose lease expired cannot overwrite the new owner's result. Part 5 shows it working.
Part 3: Triggers: webhook, cron and queue#
This part turns the trigger rows of 08A.14, section 7.5 into code. 03.9, section 13.7 covers verifying each provider's own webhook signatures in detail.
3.1 Webhooks: verify, then dedupe#
A webhook is an HTTP request another system sends you when something happens. Two things go wrong before your agent runs a single step.
- Anyone can call your endpoint. An unauthenticated webhook is a free "run an agent" button for attackers. Providers sign the body with a shared secret (an HMAC, a keyed hash). You recompute it and compare in constant time.
- Providers retry. If your endpoint answers slowly, the same event arrives again. Key the job on the provider's event id so the second delivery creates nothing.
Also answer fast: the endpoint's job is to verify, enqueue and return. Never run the agent inside the HTTP request.
3.2 Cron: the slot is the key#
A schedule (cron) fires at fixed times. Two replicas of your scheduler, or a restart at the wrong moment, will fire the same slot twice. Make the dedupe key the job name plus the slot number (time divided by the period), and double fires collapse into one job.
3.3 Queue: at-least-once means "assume duplicates"#
A queue consumer pulls messages. The message id (or a business id inside it) is the dedupe key, and handling must be idempotent because the queue will redeliver after a crash. That is Part 4.
# jobs.py (part: triggers)
def sign(secret: bytes, body: bytes) -> str:
return hmac.new(secret, body, hashlib.sha256).hexdigest()
def handle_webhook(store: JobStore, secret: bytes, body: bytes, signature: str) -> str:
"""Verify the sender, then enqueue keyed by the provider's event id."""
if not hmac.compare_digest(sign(secret, body), signature):
return "rejected: bad signature"
event = json.loads(body)
_, created = store.enqueue(f"webhook:{event['id']}", "ticket_triage", {"ticket": event["ticket"], **event.get("job", {})})
return "enqueued" if created else "duplicate ignored"
def scheduler_tick(store: JobStore, job_name: str, now_epoch: int, period_s: int, payload: dict) -> str:
"""A cron-like tick. The slot number is the dedupe key, so a double-firing scheduler
(two replicas, a restart at the wrong moment) still creates one job per period."""
slot = now_epoch // period_s
_, created = store.enqueue(f"cron:{job_name}:{slot}", job_name, payload)
return f"slot {slot}: " + ("enqueued" if created else "already enqueued")# demo_jobs.py (excerpt)
def triggers():
store = JobStore(Clock())
secret = b"demo-shared-secret"
body = json.dumps({"id": "evt_1001", "ticket": "T-77"}).encode()
good = sign(secret, body)
print("webhook, first delivery :", handle_webhook(store, secret, body, good))
print("webhook, provider retries :", handle_webhook(store, secret, body, good))
print("webhook, forged signature :", handle_webhook(store, secret, body, "0" * 64))
for t in (1_700_000_000, 1_700_000_030, 1_700_003_600): # hourly job; second tick is a duplicate fire
print("cron tick", t, "->", scheduler_tick(store, "daily_digest", t, 3600, {"steps": steps("read_tickets")}))
print("jobs in the queue:", [(r["id"], r["dedupe_key"]) for r in store.rows()])webhook, first delivery : enqueued
webhook, provider retries : duplicate ignored
webhook, forged signature : rejected: bad signature
cron tick 1700000000 -> slot 472222: enqueued
cron tick 1700000030 -> slot 472222: already enqueued
cron tick 1700003600 -> slot 472223: enqueued
jobs in the queue: [(1, 'webhook:evt_1001'), (2, 'cron:daily_digest:472222'), (3, 'cron:daily_digest:472223')]The provider's retry and the second cron tick created no extra jobs, and the forged request was rejected before anything was queued. Slot 472222 and slot 472223 are the two hours the ticks fall in, so the third tick correctly creates a new job.
Part 4: Running the agent inside a job#
4.1 The agent: a loop with guards#
The next block is the job body. For each scripted step it checks, in order: the kill switch, the budget, the autonomy rule (Part 9), a simulated transient failure, and the lease heartbeat, and only then calls the tool. Tools are idempotent: the key is the job id, the tool and the arguments, so replaying a step returns the stored result without repeating the effect. This is the same idea as 08A.2 section 6.3, and 08A.7 goes deeper on it.
# jobs.py (part: agent)
class Transient(Exception): ...
class BudgetExceeded(Exception): ...
class Killed(Exception): ...
class NeedsApproval(Exception): ...
class SimulatedCrash(BaseException): ... # the process dies; nothing after it runs
TIER = {"read_tickets": "read", "write_note": "reversible_write", "post_channel": "reversible_write",
"flaky_api": "read", "send_email": "approval_write"}
UNATTENDED_OK = {"read", "reversible_write"} # tighter than interactive: no human is watching
class Tools:
"""Idempotent tools: the dedupe key is (job id, tool, args), so replaying a step is harmless."""
def __init__(self):
self.seen: dict[str, dict] = {}
self.channel: list[str] = []
self.lock = threading.Lock()
def call(self, job_id, tool, args):
key = hashlib.sha256(f"{job_id}|{tool}|{json.dumps(args, sort_keys=True)}".encode()).hexdigest()[:8]
with self.lock:
if key in self.seen:
return {**self.seen[key], "replayed": True}
if tool == "post_channel":
self.channel.append(args["text"])
self.seen[key] = {"ok": True, "tool": tool}
return self.seen[key]
def run_job(store: JobStore, tools: Tools, job: dict, crash_after_step: int | None = None) -> dict:
p = job["payload"]
spent = 0.0
for i, step in enumerate(p["steps"]):
if store.kill.is_set():
raise Killed(f"kill switch set before step {i}")
if spent + step["cost"] > p.get("max_cost", 1.0) or i >= p.get("max_steps", 20):
raise BudgetExceeded(f"step {i} would pass the budget (spent {spent:.2f} of {p.get('max_cost', 1.0):.2f})")
if TIER[step["tool"]] not in UNATTENDED_OK:
raise NeedsApproval(json.dumps({"step": i, "tool": step["tool"], "args": step["args"]}))
if step["tool"] == "flaky_api" and job["attempt"] <= p.get("fail_times", 0):
raise Transient("503 from upstream")
if not store.heartbeat(job):
raise Transient("lost the lease") # someone else owns this job now: stop touching it
tools.call(job["id"], step["tool"], step["args"])
spent += step["cost"]
job["spent"] = spent # money already spent counts, even if the run stops later
if crash_after_step == i:
raise SimulatedCrash()
return {"steps_done": len(p["steps"]), "spent": round(spent, 2)}Notice what a retry is here: the job restarts from step 0. The earlier steps run again, and idempotent tools make that safe. That is the honest limit of this toy. A job that does an hour of work cannot afford to start over, which is the motivation for checkpointing in 08C.3.
4.2 The worker#
# jobs.py (part: worker)
class Notifier:
"""Stand-in for email or Slack. Only terminal or human-needed states notify, never every retry."""
def __init__(self):
self.outbox: list[str] = []
self.lock = threading.Lock()
def send(self, msg):
with self.lock:
self.outbox.append(msg)
def process_one(store: JobStore, tools: Tools, notifier: Notifier, worker: str,
crash_after_step: int | None = None) -> str | None:
job = store.claim(worker)
if job is None:
return None
jid = job["id"]
try:
result = run_job(store, tools, job, crash_after_step)
store.finish(job, "succeeded", result=result, cost=result["spent"])
notifier.send(f"job {jid} done: {result['steps_done']} steps, ${result['spent']}")
return "succeeded"
except SimulatedCrash:
return "crashed" # no finish(), no retry call: only the lease expiring can recover this job
except BudgetExceeded as e:
store.finish(job, "stopped", error=f"budget: {e}", cost=job.get("spent", 0.0))
notifier.send(f"job {jid} STOPPED by budget: {e}")
return "stopped"
except Killed as e:
store.finish(job, "stopped", error=f"kill switch: {e}", cost=job.get("spent", 0.0))
notifier.send(f"job {jid} STOPPED by kill switch")
return "stopped"
except NeedsApproval as e:
store.finish(job, "awaiting_approval", error=str(e), cost=job.get("spent", 0.0))
notifier.send(f"job {jid} needs a human: {e}")
return "awaiting_approval"
except Exception as e: # transient or unexpected: retry with backoff, then dead-letter
state = store.retry_or_dead(job, f"{type(e).__name__}: {e}", cost=job.get("spent", 0.0))
if state == "dead":
notifier.send(f"job {jid} DEAD after {job['attempt']} attempts: {e}")
return stateprocess_one is where the state machine meets reality. Every way a job can end maps to a store call and, where a human should know, a notification. SimulatedCrash is a BaseException subclass that deliberately skips every handler: a real crash does not run your except blocks either.
4.3 Many jobs, many workers#
Here is the whole machine on six jobs and three worker threads: two healthy jobs, one that fails twice then works, one that always fails (poison), one that wants to send an email, and one that is too expensive. The drain helper starts three threads and, when only backoff timers remain, advances the fake clock so the demo needs no sleeping.
# demo_jobs.py (excerpt)
def drain(store, tools, notifier, n_workers=3):
"""Run n worker threads until nothing is runnable now; if jobs are only waiting on a
backoff timer, advance the fake clock to the next one and go again."""
while True:
def work(name):
while process_one(store, tools, notifier, name):
pass
threads = [threading.Thread(target=work, args=(f"w{i}",)) for i in range(n_workers)]
[t.start() for t in threads]
[t.join() for t in threads]
waiting = store.db.execute("SELECT MIN(next_run_at) m FROM jobs WHERE state='queued'").fetchone()["m"]
if waiting is None:
return
store.clock.advance(max(0, waiting - store.clock.now()))# demo_jobs.py (excerpt)
def fleet():
store, tools, notifier = JobStore(Clock()), Tools(), Notifier()
store.enqueue("a", "digest", {"steps": steps("read_tickets", "post_channel", label="a:")})
store.enqueue("b", "digest", {"steps": steps("read_tickets", "write_note")})
store.enqueue("c", "flaky", {"steps": steps("flaky_api", "post_channel", label="c:"), "fail_times": 2})
store.enqueue("d", "poison", {"steps": steps("flaky_api"), "fail_times": 99})
store.enqueue("e", "outreach", {"steps": steps("read_tickets", "send_email")})
store.enqueue("f", "expensive", {"steps": steps("read_tickets", "read_tickets", "read_tickets", cost=0.4), "max_cost": 1.0})
drain(store, tools, notifier)
table(store)
print("\nnotifications:")
for m in sorted(notifier.outbox):
print(" -", m)
print("\nevents for job 3 (the flaky one):")
for e in store.events(3):
detail = e["detail"].split(" ", 1)[-1] if e["kind"] == "claimed" else e["detail"] # hide which thread won
print(f" t={e['t']:>6.1f} {e['kind']:<16} {detail}")
print("\nchannel posts:", sorted(tools.channel))Output (real, python3 demo_jobs.py fleet; thread timing does not change this output, which I confirmed by running it three times):
id kind state attempts cost last_error
1 digest succeeded 1 0.04
2 digest succeeded 1 0.04
3 flaky succeeded 3 0.04
4 poison dead 3 0.0 Transient: 503 from upstream
5 outreach awaiting_approval 1 0.02 {"step": 1, "tool": "send_email", "args": {"te
6 expensive stopped 1 0.8 budget: step 2 would pass the budget (spent 0.
notifications:
- job 1 done: 2 steps, $0.04
- job 2 done: 2 steps, $0.04
- job 3 done: 2 steps, $0.04
- job 4 DEAD after 3 attempts: 503 from upstream
- job 5 needs a human: {"step": 1, "tool": "send_email", "args": {"text": "send_email-1"}}
- job 6 STOPPED by budget: step 2 would pass the budget (spent 0.80 of 1.00)
events for job 3 (the flaky one):
t= 0.0 enqueued c
t= 0.0 claimed attempt 1
t= 0.0 retry_scheduled Transient: 503 from upstream; next in 0.3s
t= 0.3 claimed attempt 2
t= 0.3 retry_scheduled Transient: 503 from upstream; next in 3.4s
t= 3.7 claimed attempt 3
t= 3.7 succeeded
channel posts: ['a:post_channel-1', 'c:post_channel-1']Read the table row by row. Jobs 1 and 2 succeeded on the first attempt. Job 3 needed three attempts: the events show two backoffs (0.3 s, then 3.4 s) before it worked, and its post happened once. Job 4 hit the attempt limit and is dead. Job 5 was parked as awaiting_approval after spending 0.02 on its read step. Job 6 spent 0.80 on two steps and was stopped before the third would pass the 1.00 budget. Notice that every notification is about an outcome that needs attention or confirms completion; there is no message for each retry.
Part 5: Leases, heartbeats and zombie workers#
5.1 The problem: a worker disappears#
A worker can die (out of memory, a deploy, the machine rebooting) halfway through a job. The row says running forever and no other worker will touch it. The usual fix is a lease: a claim that expires. A worker that claims a job gets, say, 30 seconds. If it does not finish or renew in time, the job becomes claimable again.
5.2 Heartbeats#
A heartbeat is the worker saying "still alive" by renewing its lease, here before every step. A long step needs a heartbeat inside it, or a timer thread that renews while the step runs. If the worker hangs or dies, the heartbeats stop and the lease expires. The lease length is a trade: short leases recover quickly but risk duplicate work when a healthy worker is just slow; long leases are the opposite.
# demo_jobs.py (excerpt)
def heartbeat():
store, tools = JobStore(Clock(), lease_s=30), Tools()
store.enqueue("slow", "digest", {"steps": steps("read_tickets", "write_note")})
job = store.claim("A")
for t in (20, 20, 20): # a long step; the worker heartbeats every 20 seconds
store.clock.advance(t)
print(f"t={store.clock.now():>4.0f} heartbeat ok: {store.heartbeat(job)} | B can claim: {store.claim('B') is not None}")
store.clock.advance(31) # now the worker stops heartbeating (hung)
print(f"t={store.clock.now():>4.0f} no heartbeat for 31s | B can claim: {store.claim('B') is not None}")t= 20 heartbeat ok: True | B can claim: False
t= 40 heartbeat ok: True | B can claim: False
t= 60 heartbeat ok: True | B can claim: False
t= 91 no heartbeat for 31s | B can claim: TrueWhile worker A kept renewing every 20 seconds, worker B could never take the job even after 60 seconds. Once the heartbeats stopped for 31 seconds, the lease expired and B could claim it.
5.3 Crash, reclaim and the zombie#
Now the crash. Worker A runs a three-step job and "dies" after step 1, which had already posted a message. We check B cannot take the job early, advance past the lease, and let B finish. Then a zombie appears: A was only paused (a long garbage collection, a network partition), wakes up, and tries to report its result.
# demo_jobs.py (excerpt)
def lease():
store, tools, notifier = JobStore(Clock(), lease_s=30), Tools(), Notifier()
store.enqueue("long", "digest", {"steps": steps("read_tickets", "post_channel", "write_note")})
# worker A runs the job and its process dies right after step 1 (the post already happened)
print("A:", process_one(store, tools, notifier, "A", crash_after_step=1))
print("channel after A's crash:", tools.channel)
store.clock.advance(10)
print("B tries at t=10 (lease valid until t=30):", process_one(store, tools, notifier, "B"))
store.clock.advance(21)
print("B tries at t=31 (lease expired):", process_one(store, tools, notifier, "B"))
print("channel after B finishes:", tools.channel, "(posted once, B replayed the step)")
for e in store.events(1):
print(f" t={e['t']:>5.1f} {e['kind']:<14} {e['detail']}")
# a zombie: A was only paused, not dead. It wakes up and tries to report its result.
stale = {"id": 1, "worker": "A", "attempt": 1}
print("zombie A calls finish():", store.finish(stale, "succeeded", result={"x": 1}))
table(store)A: crashed
channel after A's crash: ['post_channel-1']
B tries at t=10 (lease valid until t=30): None
B tries at t=31 (lease expired): succeeded
channel after B finishes: ['post_channel-1'] (posted once, B replayed the step)
t= 0.0 enqueued long
t= 0.0 claimed A attempt 1
t= 31.0 lease_expired was held by A
t= 31.0 claimed B attempt 2
t= 31.0 succeeded
zombie A calls finish(): False
id kind state attempts cost last_error
1 digest succeeded 2 0.06Three things worth stating plainly. The message was posted once, because B replayed step 1 through an idempotent tool and the tool recognised it. The attempt counter went to 2. The cost column shows 0.06, which is only B's three steps: A crashed, so it never got to record what it had spent. That is a real gap in this toy (spend from a crashed attempt is lost), and one more reason to write cost to storage at every step in a real system. And the zombie's finish returned False: the fenced write checks the owner and the attempt, so A could not overwrite B's result. A fencing token (here the attempt number) is how distributed systems keep a stale owner from doing damage.
Part 6: Retries, backoff and the dead-letter queue#
03.8 owns retries for single model calls. This part applies the same rules to whole agent jobs and adds the dead-letter state.
6.1 What to retry#
Not every failure deserves a retry.
| Failure | Retry? | Why |
|---|---|---|
| Upstream 503, timeout, connection reset | Yes, with backoff | Likely to pass |
| Provider rate limit (429) | Yes, after the wait the provider asks for | 03.8 owns the details |
| Bad input, a validation error, a refused action | No | It will fail the same way |
| Budget exceeded | No | The budget is the answer; retrying spends more |
| Kill switch | No | A person decided |
| Needs approval | No (park it) | A human must act |
In the code, Transient and unexpected errors take the retry path; budget, kill and approval each end the job in their own state.
6.2 Exponential backoff with jitter#
Exponential backoff waits longer after each failure (5 s, 10 s, 20 s...), and jitter randomises the wait so retries spread out instead of hammering a struggling service at the same instant (03.8 covers both for model calls). The store uses "full jitter": a random wait between zero and the exponential cap. In the output above the waits were 0.3 s and 3.4 s, both inside their caps (10 s, then 20 s). The random generator is seeded per job and attempt so the tests are repeatable; in production, do not seed.
6.3 Poison messages and the dead-letter queue#
A poison message is a job that fails every time no matter how often you retry it: a malformed payload, a bug triggered by one ticket. Without a limit it loops forever. After max_attempts, the job moves to dead. That state is the dead-letter queue (DLQ), a holding area for jobs that need a human. A DLQ is only useful if:
- Someone is told. Job 4 above sent a "DEAD after 3 attempts" notification.
- The failure is inspectable. The row keeps
last_error, the attempts, the cost and the event history. - Re-queueing is deliberate. A human fixes the cause, then re-enqueues with a new dedupe key or resets the row. Auto-redrive without a fix recreates the loop.
6.4 Retries and cost#
Every retry of an agent job can spend model tokens again. In retry_or_dead the cost of the failed attempt is added to the row, so total spend per job is honest. Retry limits for jobs should be lower than for cheap HTTP calls (three attempts is a common default), and the budget in Part 8 should cap total spend across attempts, not just per attempt.
Part 7: Notifying the user#
Deep-dive
A background agent that finishes silently is a background agent nobody trusts. A background agent that sends a message for every step teaches people to ignore it. The rule that works: notify on outcomes and on needs, not on progress.
| Event | Notify? | To whom | Content |
|---|---|---|---|
| Succeeded | Yes (or a digest, if frequent) | The job owner | What was done, link to the result, cost |
| Retry scheduled | No | Nobody; it is in the log | |
| Dead (DLQ) | Yes | On-call or the owner | Job id, error, attempts, link to the trace |
| Stopped by budget | Yes | The owner | What it had done, what it spent, how to raise the budget |
| Kill switch | Yes | The owner | Which jobs were stopped and by whom |
| Awaiting approval | Yes | The approver (08A.12) | The exact proposed action, with approve and deny links |
| Nothing happened (a scheduled run found nothing to do) | Usually no | Or a weekly "all quiet" heartbeat |
Three practical notes. Use deduplicated, grouped notifications: ten dead jobs from one bug should be one message with ten ids, not ten pages. Put the next action in the message, not only the failure. And notify through a channel the person actually reads; an email to an unmonitored mailbox is the same as silence. In the code the Notifier is a list; in production it is Slack, email or a pager, with its own rate limits.
Part 8: Budgets and the kill switch#
08A.14, section 7.2 introduces kill switches as an operating control. This part builds the job-level version and shows it stopping a fleet.
8.1 Budgets for runs nobody watches#
The per-run limits inside the loop (steps, tokens, money and time) are 08A.3's subject. In the background they are the only brake. This lesson adds the job-level guard and the layer above it:
- Per-job limits as in
run_job(max_cost,max_steps): the guard checks before each step whether the step would pass the limit, so a job stops at 0.80 of 1.00, not at 1.20. Money already spent is recorded even when the job is stopped. - Per-period and per-tenant limits across all jobs, such as "this schedule may spend 5 dollars a day". Those belong to cost governance (11B.6). The point here is that a stuck schedule can burn a week of spend if only per-job limits exist.
8.2 The kill switch#
A kill switch is a control that stops agent activity quickly, without a deploy. Two properties matter: it must stop new work (the store refuses all claims while it is set), and it must stop running work at the next safe point (every step checks it). It is a flag, not a process kill, because a process kill can land between a tool call and its bookkeeping. 11B.7 covers kill switches at organisation scale (per tenant, per tool, per model); this is the job-level version.
# demo_jobs.py (excerpt)
def kill_switch():
store, tools, notifier = JobStore(Clock()), Tools(), Notifier()
for i in range(4):
store.enqueue(f"j{i}", "digest", {"steps": steps("read_tickets", "write_note", "post_channel")})
running = store.claim("w0") # one job is already mid-run
store.kill.set()
print("kill switch set. new claims:", store.claim("w1"))
from jobs import run_job, Killed
try:
run_job(store, tools, running)
except Killed as e:
store.finish(running, "stopped", error=f"kill switch: {e}")
notifier.send(f"job {running['id']} STOPPED by kill switch")
table(store)
store.kill.clear()
drain(store, tools, notifier)
print("after clearing the switch and draining:")
table(store)kill switch set. new claims: None
id kind state attempts cost last_error
1 digest stopped 1 0.0 kill switch: kill switch set before step 0
2 digest queued 0 0.0
3 digest queued 0 0.0
4 digest queued 0 0.0
after clearing the switch and draining:
id kind state attempts cost last_error
1 digest stopped 1 0.0 kill switch: kill switch set before step 0
2 digest succeeded 1 0.06
3 digest succeeded 1 0.06
4 digest succeeded 1 0.06With the switch set, no new claim succeeded and the job that was already running stopped at its next check. Clearing the switch let the queue drain. The stopped job stays stopped and does not silently restart: a person decided, so a person decides again.
Part 9: Why unattended agents get tighter autonomy#
The closing rule of 08A.14, section 7.5 says a non-interactive run cannot ask for approval at 3 a.m. This part makes that rule run on the job table.
In 08A.12 a risky call pauses for a human who is around. In the background nobody is. Two designs are safe:
- Pre-authorise a narrow scope. The job may use only read tools and reversible writes. In the code,
UNATTENDED_OK = {"read", "reversible_write"}; anything else stops the run. - Propose and notify. When the agent reaches an
approval_writecall (send an email, issue a refund), the job moves toawaiting_approvalwith the exact proposed call stored, and a human is told. The pause is durable because the job row is the saved state. When a person approves through the queue of 08A.12, the job is re-queued with that one decision applied.
The worked example is job 5 in the fleet run: the read_tickets step ran, the send_email step did not, the row holds {"step": 1, "tool": "send_email", ...}, and a notification went out. The agent was never able to send that email by itself.
The reasons to be stricter than interactive are all about missing feedback:
- No one is watching to say "stop". Mistakes compound for hours.
- Triggers are untrusted input. A webhook payload or a ticket body may carry an attacker's text. The more your agent can do unattended, the more an injected instruction can do. 08A.5 covers prompt injection and least privilege; the rule here is that unattended jobs get the smallest toolset that does the job.
- Failures repeat. An interactive bug annoys one user; a scheduled bug runs every day.
The practical policy: start every background job as read-only plus propose-and-notify. Widen it one tool at a time, with an eval (Part 13) and a budget, and only after the proposals have been right for long enough that the approvals feel like rubber stamps. Then the policy-approved path from 08A.12 applies, with its audit trail.
Part 10: Observability for background runs#
Deep-dive
You cannot attend a background run, so its record is everything. Tracing in depth is the subject of 11A.1 (OpenTelemetry GenAI conventions and trace structure) and the lighter 03.12; 11A.3 covers audit logs, dashboards and SLOs. Here is what is specific to background work.
Per job, always: the job id, the dedupe key and its trigger source, the attempt number, the worker, the state transitions with times (the events table in this lesson is the minimum), cost per attempt, and a trace id linking to the model and tool spans. The trace id is what turns "job 4 is dead" into a readable trajectory.
Per fleet, as metrics:
| Metric | What it tells you | Typical alert |
|---|---|---|
| Queue depth and age of the oldest queued job | Workers are behind or stuck | Age over your latency target |
| Success, retry and dead rates per job kind | A bug or an upstream outage | Dead rate above a small threshold |
| Lease expiries per hour | Workers dying or leases too short | Any sustained rise |
| Attempts per job (distribution) | Hidden flakiness | A shift in the upper percentiles |
| Cost per job and per day, by schedule | Runaway spend | Above the per-period budget |
| Time from trigger to notification | The user's experience | Above target |
Jobs in awaiting_approval and their age |
Approvers are the bottleneck | Age over the approval deadline |
Also watch for silence. A scheduled job that did not run produces no error. Alert on "expected a succeeded daily_digest in the last 26 hours and found none". This kind of check is often called a dead-man's switch or a heartbeat monitor, and it catches the scheduler itself dying.
Part 11: Provider background features#
Reference
Both primary providers have features with "background" or "batch" in the name. They solve narrower problems than the runner above, so it helps to be exact. 03.9 owns the details and the runnable samples; this part only says where they fit. Limits and behaviour change, so confirm on the pages linked in 03.9 and in Further resources before relying on a number.
11.1 OpenAI Responses background mode#
Setting background=True on a Responses request makes the API return at once with a response id while the model runs on OpenAI's side. You poll it, cancel it, or resume its stream after a dropped connection (03.9, section 13.2 covers polling, cancelling and the storage rules, and 03.3, Part 9 covers resumable streams). The storage rules matter for governance, which 14A.7 covers. What this gives you: one long model response without holding an HTTP connection. What it does not give you: a retry policy, dedupe, budgets across calls, approvals, or any control over your own tools. A multi-step agent loop is still your code, and each step is still a request.
11.2 Anthropic Message Batches#
The Message Batches API processes many Messages requests asynchronously at a discount (03.9, Part 8 has the limits, statuses and a full lifecycle). Batches are for many independent single requests: summarise 10,000 tickets overnight, run an eval set. Each batch item is one model request, so an agent loop that needs the tool result before the next call does not fit directly: you would submit one batch per step. Use batches for fan-out work and for the cost of running evals (11B.8), not as an agent runtime.
11.3 What the providers do not replace#
Neither feature gives you triggers, dedupe, leases, retries across steps, a dead-letter queue, notification, an autonomy policy or a kill switch. Think of them as ways to make one expensive model call cheaper or longer-lived. The runner you built is the layer that makes the whole agent run reliable.
Part 12: Where this toy ends and durable execution begins#
Reference
The runner above restarts a crashed job from step 0 and relies on idempotent tools to make that safe. That is fine for jobs of seconds or a few steps. It breaks down when:
- a job takes hours and starting over wastes real money or breaks time-sensitive state;
- a job must wait for days (for an approval, a payment, a reply) without holding a worker;
- you need to know exactly which step completed, replay history, or resume after a deploy;
- steps are many and branching.
The answer is durable execution: the framework records the result of every completed step, and after a crash it replays from the log and continues, instead of starting again. Temporal and AWS Step Functions are the two systems 08C.3 introduces, and LangGraph checkpointers do a version of it (08F.11 part 4; 08A.9 part 6). Notice that nearly every concept in this lesson carries over: dedupe keys, idempotent activities, retries with backoff, heartbeats for long steps, dead-letter handling, budgets and kill switches. Learn them once here and you will recognise them in every engine.
Part 13: Evaluate it#
An unattended agent has two things to test: the runner (does it keep its promises under duplicates, crashes and failures?) and the agent (does it get the task right, run after run?). Test them separately.
13.1 What to measure#
| Measure | Applies to | Pass rule |
|---|---|---|
| Duplicate triggers create one job | Runner | Always |
| An effect happens exactly once across crash and reclaim | Runner | Always |
| Transient failures recover within the attempt limit; poison jobs reach the DLQ and notify | Runner | Always |
| A job never passes its budget by more than a step's cost | Runner | Always |
| After the kill switch, nothing new starts and running jobs stop at the next check | Runner | Always |
| An unattended job never runs a tool outside its allowed tiers | Runner and policy | Always |
| Task success rate over repeated runs | Agent | Your target, measured with enough runs to trust it |
| Cost per successful run | Agent | Within the schedule's budget |
| Time from trigger to notification | System | Within target |
The runner checks are deterministic and belong in CI. The agent checks are statistical, because scheduled agents run many times and a single success proves little. The concept home for reliability across repeated runs (pass rates, confidence intervals, pass^k) and for cost per successful task is 10A.7 Parts 4 and 5.
13.2 A tiny eval design for the runner#
Inputs: six scenarios (three deliveries of one event, a crash after a side effect, a flaky job and a poison job, an over-budget job, the kill switch, an unattended email). Metric: the job rows, the tool effects and the notifications. Pass rule: every invariant holds.
# eval_jobs.py -- invariant checks for a background-agent runner (stdlib only)
import json
from demo_jobs import drain, steps
from jobs import Clock, JobStore, Notifier, Tools, handle_webhook, process_one, sign
def fresh():
return JobStore(Clock()), Tools(), Notifier()
def check_duplicates():
store, _, _ = fresh()
body, secret = json.dumps({"id": "evt_9", "ticket": "T-1"}).encode(), b"k"
for _ in range(3):
handle_webhook(store, secret, body, sign(secret, body))
return len(store.rows()) == 1, "3 deliveries of one event -> 1 job"
def check_crash_replay():
store, tools, n = fresh()
store.enqueue("x", "digest", {"steps": steps("read_tickets", "post_channel", "write_note")})
process_one(store, tools, n, "A", crash_after_step=1)
store.clock.advance(31)
process_one(store, tools, n, "B")
return tools.channel.count("post_channel-1") == 1 and store.rows()[0]["state"] == "succeeded", \
"crash after a side effect, reclaim -> effect happened once, job succeeded"
def check_retry_budget():
store, tools, n = fresh()
store.enqueue("f", "flaky", {"steps": steps("flaky_api"), "fail_times": 2})
store.enqueue("p", "poison", {"steps": steps("flaky_api"), "fail_times": 99})
drain(store, tools, n)
states = [r["state"] for r in store.rows()]
return states == ["succeeded", "dead"] and any("DEAD" in m for m in n.outbox), \
"flaky job recovers within 3 attempts; poison job dead-lettered AND a human was told"
def check_budget():
store, tools, n = fresh()
store.enqueue("b", "expensive", {"steps": steps("read_tickets", "read_tickets", "read_tickets", cost=0.4), "max_cost": 1.0})
drain(store, tools, n)
row = store.rows()[0]
return row["state"] == "stopped" and row["cost"] <= 1.0, "job stops before passing max_cost; spend recorded"
def check_kill():
store, tools, n = fresh()
for i in range(3):
store.enqueue(f"k{i}", "digest", {"steps": steps("read_tickets")})
store.kill.set()
started = process_one(store, tools, n, "w")
return started is None and all(r["state"] == "queued" for r in store.rows()), "kill switch set -> nothing new starts"
def check_unattended_write():
store, tools, n = fresh()
store.enqueue("e", "outreach", {"steps": steps("read_tickets", "send_email")})
drain(store, tools, n)
return store.rows()[0]["state"] == "awaiting_approval" and not tools.channel, "unattended approval_write is parked, not run"
results = [f() for f in (check_duplicates, check_crash_replay, check_retry_budget, check_budget, check_kill, check_unattended_write)]
for ok, label in results:
print(("PASS" if ok else "FAIL"), "-", label)
print("overall:", "PASS" if all(ok for ok, _ in results) else "FAIL", f"({sum(ok for ok, _ in results)}/{len(results)})")PASS - 3 deliveries of one event -> 1 job
PASS - crash after a side effect, reclaim -> effect happened once, job succeeded
PASS - flaky job recovers within 3 attempts; poison job dead-lettered AND a human was told
PASS - job stops before passing max_cost; spend recorded
PASS - kill switch set -> nothing new starts
PASS - unattended approval_write is parked, not run
overall: PASS (6/6)This is a bespoke harness, kept small on purpose. Mutate the runner to see it work: remove the UNIQUE constraint on dedupe_key, delete the lease_owner check in finish, or drop the UNATTENDED_OK test, and the matching line turns to FAIL.
13.3 The Module 10A and 10B toolkit#
Concept lessons first, then the tools.
- 10A.7 Evaluating agents: reliability across runs, cost per successful task, and Part 8 on long-running tasks.
- 10A.11 Evaluating agent memory and context: for jobs that carry state from one scheduled run to the next.
- 10A.12 Evaluating multi-agent systems: when several workers or agents share a queue.
- DeepEval track (required): 10B.2 fundamentals, 10B.3 judges and custom metrics, 10B.4 built-in metrics, 10B.5 tracing and agent evaluation (Part 9 scores each run's task completion and efficiency), 10B.6 datasets, and 10B.7 red teaming and CI (run the agent checks nightly and fail the build on regression).
- Inspect track (optional): 10B.15 Part 7, limits (optional) for budgets as part of an eval's design, 10B.15 Part 8, approval (optional) and 10B.15 Part 9, tool result review (optional). Note that "checkpointing" in 10B.15 means resuming an interrupted eval run, which is a different thing from durable execution of an agent (08C.3).
Common misconceptions#
- "A cron job plus a script is a background agent." It is until the second time it fires, the first time it crashes, or the first time it runs long. Add dedupe, leases, budgets and a way to know it did not run.
- "Retries make the system reliable." Retries make failures repeat. Without idempotency, a retry doubles an effect; without a limit, it loops; without backoff, it hammers a struggling service.
- "The queue guarantees exactly-once." Almost no queue does. You get at-least-once delivery and make handling idempotent.
- "A lease means only one worker runs the job." It means only one worker owns the job. A slow or paused worker can still be running, which is why writes are fenced and effects are idempotent.
- "The dead-letter queue is where failures go to be forgotten." It is where failures wait for a human. Without a notification and a runbook it is a graveyard.
- "Unattended just means interactive without the UI." It means no feedback, untrusted triggers and repeating failures, so autonomy must be narrower.
- "OpenAI background mode or Anthropic batches are my agent runtime." They make one model call asynchronous or cheaper. The rest of the runtime is yours.
- "Notify on everything so nothing is missed." People mute channels that cry wolf. Notify on outcomes and needs.
Key takeaways#
- Unattended agents start from webhooks, schedules or queues. Verify the sender, then dedupe on the logical job: event id for webhooks, job name plus slot for cron, message id for queues.
- Model a job as a state machine (queued, running, succeeded, dead, stopped, awaiting approval) with every transition written down.
- Make handling idempotent: the same job twice must not repeat its effects. Tool dedupe keys are built from the job id, the tool and the arguments.
- Use leases and heartbeats so a crashed worker's job is reclaimed, and fence writes by owner and attempt so a zombie cannot overwrite the new owner.
- Retry transient failures with exponential backoff and jitter; never retry budget stops, kill switches or approvals; dead-letter poison jobs and tell a human.
- Notify on outcomes and needs, grouped and with the next action; do not notify on every retry.
- Give unattended runs per-job budgets, per-period budgets and a kill switch that stops new and running work. Record money spent even when a run stops.
- Run unattended agents with tighter autonomy: read and reversible tools only, and propose and notify for anything that needs approval (08A.12).
- Observe job state, attempts, cost and queue age, and alert on silence as well as errors.
- OpenAI's background mode and Anthropic's Message Batches make single model calls asynchronous or cheaper. They are not agent runtimes. When jobs get long or must wait for days, move to durable execution (08C.3).
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Background agent | An agent run started and finished without a person waiting on a request |
| Long-running agent | A run that outlasts a normal request: minutes to days |
| Trigger | What starts a run: an event or webhook, a schedule, or a queue message |
| Webhook | An HTTP request a provider sends when something happens; verify its signature and dedupe its event id |
| HMAC signature | A keyed hash of the request body that proves the sender knows the shared secret |
| Job state machine | The fixed set of job states and the allowed moves between them |
| Dedupe key | A key for the logical job; enqueueing the same key twice creates one job |
| At-least-once delivery | A queue guarantee that a message may arrive more than once, never zero times |
| Idempotent job handling | Processing a job twice has the same effect as processing it once |
| Lease | A time-limited claim on a job that expires if the worker does not finish or renew it |
| Heartbeat | A worker renewing its lease to show it is alive |
| Zombie worker | A worker that lost its lease but is still running and may try to write results |
| Fencing token | A value (here the attempt number) checked on writes so a stale owner is rejected |
| Exponential backoff with jitter | Waiting longer after each failure, with a random component so retries spread out |
| Poison message | A job that fails every time however often it is retried |
| Dead-letter queue (DLQ) | The holding state for jobs that exhausted their attempts, waiting for a human |
| Propose and notify | An unattended agent records the exact action it wants and tells a human instead of doing it |
| Kill switch | A flag that stops new work immediately and running work at its next check |
| Dead-man's switch | An alert that fires when an expected event (a scheduled run) did not happen |
| Durable execution | Recording each completed step so a crashed run resumes instead of restarting |
Exercises#
- A second trigger. Add a queue-consumer trigger: a function
handle_message(store, msg)that enqueues onmsg["id"]and returns "duplicate ignored" for redeliveries. Show five deliveries of three distinct ids create three jobs. Hint: reusestore.enqueuewithf"queue:{msg['id']}"; assertlen(store.rows()) == 3. - Longer jobs, shorter leases. Make a job with a step that takes 45 seconds of fake time while the lease is 30. Show another worker steals it, then add a heartbeat inside the step to fix it. Hint: advance the clock inside the step in two 20-second halves and call
store.heartbeat(job)between them. - Redrive the DLQ. Write
redrive(store, job_id)that moves adeadjob back toqueuedwith attempts reset, logs an event naming who did it, and refuses jobs that are notdead. Hint: UPDATE withWHERE state='dead'and checkrowcount. - Digest notifications. Change
Notifierso that dead-job messages within the same minute are grouped into one message listing all job ids. Hint: buffer by(kind, int(clock.now() // 60))and flush when the minute changes. - A per-day budget. Add a
budget_ledgerthat sumscostby job kind per day and refuses to start a job of that kind once the day's total passes a limit, parking it asstoppedwith a clear reason. Hint: querySUM(cost)for the kind insideclaimor at the top ofprocess_one. - Dead-man's switch. Write
check_expected(store, kind, within_s)that returns an alert string if nosucceededjob of that kind exists in the lastwithin_sseconds. Show it firing when the scheduler is stopped. Hint: recordfinished_aton success; compare withclock.now().
Check yourself#
- Name the three kinds of trigger for an unattended agent and the dedupe key you would use for each.Webhook: the provider's event id. Cron: job name plus the time slot (time divided by period). Queue: the message id or a business id inside it.
- Why must a webhook endpoint verify a signature before enqueueing?Without it, anyone who finds the URL can start agent runs, which means spending money and possibly triggering actions with attacker-chosen content.
- A queue gives at-least-once delivery. What two things do you add to get effectively-once results?Dedupe keys at the trigger (so duplicates create one job) and idempotent handling inside the job (so replayed steps do not repeat effects).
- What problem does a lease solve, and what does a heartbeat add?A lease lets a crashed worker's job be claimed by another worker after a timeout. A heartbeat renews the lease while a healthy worker is still working, so slow jobs are not stolen.
- What is a zombie worker, and how does the fenced
finishstop it from doing damage?A zombie lost its lease (it was paused or partitioned) but wakes up and tries to report. The fenced write only succeeds if the caller still owns this attempt, so the stale worker'sfinishreturns false and the new owner's result stands. - Which failures should be retried, and which should not? Give two of each.Retry: upstream 503 or timeout; a rate limit after the stated wait. Do not retry: a validation error or refused action; a budget stop (also acceptable: kill switch or needs-approval).
- What is jitter for, and what happens to a struggling service without it?Jitter randomises retry times so many failed jobs do not all retry at the same instant. Without it, synchronised retries can hammer a struggling service and keep it down.
- When should a background job notify a human, and when should it stay quiet?Notify on outcomes (done, dead, stopped by budget or kill switch) and on needs (an approval). Stay quiet on retries and routine progress, and group related alerts.
- Why should a scheduled, unattended job start read-only with propose-and-notify, instead of getting the same tools as the chat agent?Nobody is watching to stop mistakes, trigger content is untrusted and may carry injected instructions, and a bug repeats every run. A smaller toolset limits damage; proposing and notifying keeps a human decision on risky actions.
- OpenAI's background mode and Anthropic's Message Batches both mention "asynchronous". What do they not give you that the runner in this lesson does?They do not give triggers, dedupe, retries across steps, leases, a dead-letter path, notifications, an autonomy policy, budgets across calls or a kill switch. They make one model call asynchronous or cheaper; the runner makes the whole agent run reliable.
Further resources#
- 08A.14 — Reliable and Safe Agents, section 7.5: the trigger-model table this lesson implements.
- 08A.2 — The Tool Loop: the loop inside each job, budgets and idempotency.
- 08A.9 — Workflows vs Agents, Part 6: durable and long-running workflows.
- 08F.11 — Persistence and Memory in LangGraph: checkpointing as durable execution.
- 03.8 — Errors and Retries and 03.9 — Async, Concurrency and Batch: model-call retries and bounded concurrency.
- 11A.1 — Tracing and Observability and 11B.1 — Cost and Latency Optimization: the production lessons this one feeds.
- OpenAI — Background mode:
background, polling, cancel,starting_after(checked 1 December 2026). - Anthropic — Batch processing: Message Batches limits, discount, result retention (checked 1 December 2026).
← 08A.12 — Human-in-the-Loop and Approval Gates as a Pattern | Module 08A overview | 08A.14 — Reliable, Safe and Observable Agents →