Lab: Background Runs with Retries and Cancellation
Build a small runs service with the standard library: a 202 Accepted endpoint, a SQLite run store, a worker with per-attempt timeouts, capped exponential backoff with jitter that honours Retry-After, cooperative cancellation at safe points, and a Server-Sent Events progress stream that a client can reconnect to.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A run store that outlives requests
- Step 2: A fake agent that fails on cue
- Step 3: The worker
- Step 4: The API and the progress stream
- Step 5: A client, and a run that succeeds
- Step 6: A rate limit and a hung call
- Step 7: A dependency that stays broken
- Step 8: Cancel a run in the middle
- Step 9: Reconnect and poll
- Check your understanding
- Apply it
- Review prompt
Lessons of Durable Agent Execution
- What Breaks in Long-Running Agents Concept · 15 min
- Checkpointers Versus Workflow Engines Concept · 15 min
- Idempotent Side Effects Worked example · 20 min
- Lab: Background Runs with Retries and Cancellation Lab · 25 min
- Crash, Resume, Compare Lab · 25 min
- Check: Failure and Recovery Scenarios Knowledge check · 8 questions
What you will learn
- Run agent tasks as background jobs with timeouts, retries with backoff, cancellation and progress reporting to clients.
Prerequisites: Agent Loops & ReAct
01. Goal and setup
An agent run that takes minutes should not live inside the HTTP request that starts it. A proxy will cut the request, a browser tab will close, a deploy will restart the server. The usual design is a background job: the API stores the run, answers 202 Accepted with the run ID straight away, and a separate worker does the work. The client then follows the run by ID, either by polling its status or by reading a stream of progress events.
In this lab you build that design end to end and break it on purpose. A fake agent with four steps stands in for the model and tools, and each run has a scenario that scripts a failure: a rate limit, a hung call, a broken dependency, or a slow run that you cancel. Because the failures are scripted and the random numbers are seeded, every output below repeats exactly on your machine.
You need: Python 3.10 or newer (tested with 3.12) and nothing else; every module is in the standard library. Create a folder bg-lab, save the files below into it, and run every command from that folder.
bg-lab/
├── store.py step 1: runs and progress events in SQLite
├── agent.py step 2: a fake four-step agent with scripted failures
├── worker.py step 3: timeouts, retries with backoff, cancellation
├── server.py step 4: the HTTP API and the event stream
└── client.py step 5: starts a run and prints its events02. Step 1: A run store that outlives requests
Two tables hold everything a client may ask about. runs has one row per run with its status (queued, running, then one of four end states) and a cancel_requested flag. events is an append-only list of progress events, numbered per run by seq. Numbered events are what make a reconnecting client possible later: it says "I have seen up to 5" and gets the rest.
next_queued() claims a run by switching it to running inside the same transaction that found it, so two worker threads cannot pick the same run. requeue_interrupted() is for start-up: a run left in running belongs to a process that died, so it goes back to the queue. That restart is at-least-once: the run begins again from its first step. Resuming from the last finished step is the subject of the next lab.
"""Runs and their progress events, in SQLite, so they outlive any one request."""
import json
import sqlite3
import threading
db = sqlite3.connect("runs.sqlite", check_same_thread=False)
db.executescript("""
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY, scenario TEXT, status TEXT DEFAULT 'queued',
cancel_requested INTEGER DEFAULT 0, result TEXT);
CREATE TABLE IF NOT EXISTS events (
run_id INTEGER, seq INTEGER, kind TEXT, data TEXT, PRIMARY KEY (run_id, seq));
""")
lock = threading.Lock() # one shared connection: every use goes through the lock
TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"}
def create_run(scenario: str) -> int:
with lock, db:
return db.execute("INSERT INTO runs (scenario) VALUES (?)",
(scenario,)).lastrowid
def get_run(run_id: int):
with lock:
row = db.execute("SELECT id, scenario, status, cancel_requested, result "
"FROM runs WHERE id = ?", (run_id,)).fetchone()
keys = ("id", "scenario", "status", "cancel_requested", "result")
return dict(zip(keys, row)) if row else None
def update(run_id: int, **fields) -> None:
cols = ", ".join(f"{k} = ?" for k in fields)
with lock, db:
db.execute(f"UPDATE runs SET {cols} WHERE id = ?", (*fields.values(), run_id))
def emit(run_id: int, kind: str, **data) -> None:
with lock, db:
(seq,) = db.execute("SELECT COALESCE(MAX(seq), 0) + 1 FROM events "
"WHERE run_id = ?", (run_id,)).fetchone()
db.execute("INSERT INTO events VALUES (?, ?, ?, ?)",
(run_id, seq, kind, json.dumps(data)))
def events_after(run_id: int, seq: int):
with lock:
return db.execute("SELECT seq, kind, data FROM events WHERE run_id = ? "
"AND seq > ? ORDER BY seq", (run_id, seq)).fetchall()
def next_queued():
with lock, db:
row = db.execute("SELECT id FROM runs WHERE status = 'queued' "
"ORDER BY id LIMIT 1").fetchone()
if row:
db.execute("UPDATE runs SET status = 'running' WHERE id = ?", row)
return row[0] if row else None
def requeue_interrupted() -> int:
"""At start-up: runs left 'running' by a crash go back to the queue."""
with lock, db:
return db.execute("UPDATE runs SET status = 'queued' "
"WHERE status = 'running'").rowcountpython3 -m py_compile store.py && echo "store.py compiles"store.py compiles03. Step 2: A fake agent that fails on cue
run_step plays the part of one model or tool call. The rate_limited scenario answers the first two attempts at search_docs with HTTP 429 and a Retry-After of 0.3 seconds. A real Retry-After header carries whole seconds or an HTTP date; the lab shortens the wait to 0.3 seconds so that it runs quickly. hang makes the first summarise attempt sit for 3 seconds, like a call that never answers. broken fails search_docs with 503 every time. slow makes each step take 0.4 seconds, which gives you time to cancel. A real agent would raise Transient from its model client when it sees 429, 500, 503 or a connection error.
"""A fake agent: four steps whose failures are scripted by the run's scenario."""
import time
STEPS = ["plan", "search_docs", "summarise", "file_report"]
STEP_SECONDS = {"slow": 0.4} # how long one step takes; default 0.05 s
class Transient(Exception):
"""A failure worth retrying, such as HTTP 429 or 503 from a model API."""
def __init__(self, status: int, retry_after: float | None = None):
super().__init__(f"HTTP {status}")
self.retry_after = retry_after
def run_step(scenario: str, step: str, attempt: int) -> str:
if scenario == "rate_limited" and step == "search_docs" and attempt <= 2:
raise Transient(429, retry_after=0.3)
if scenario == "hang" and step == "summarise" and attempt == 1:
time.sleep(3) # stuck call: the step timeout must stop waiting for it
if scenario == "broken" and step == "search_docs":
raise Transient(503)
time.sleep(STEP_SECONDS.get(scenario, 0.05))
return f"{step} ok"python3 -m py_compile agent.py && echo "agent.py compiles"agent.py compiles04. Step 3: The worker
The worker applies four rules, each with a reason.
- Every attempt has a timeout.
future.result(timeout=STEP_TIMEOUT)stops waiting after one second. It does not stop the call: a Python thread cannot be killed from outside, so the stuck attempt keeps running in the pool until it returns on its own. That is acceptable for a read, but for a side effect it means the old attempt and the retry can both land, which is one more reason tools need the idempotency keys from Idempotent Side Effects. Workflow engines handle this with activity timeouts and heartbeats; you can also run risky calls in a subprocess that you are able to kill. - Only some errors are retried, and only a few times. A transient error or a timeout is retried up to
MAX_ATTEMPTS; anything else fails the run at once. The whole run also has a deadline. - Retries wait longer each time, by a random amount. The ceiling doubles per attempt (0.1 s, 0.2 s, 0.4 s, at most 2 s) and the actual wait is a random value between zero and the ceiling, a scheme called full jitter. Doubling gives an overloaded service room to recover; randomness stops hundreds of workers from retrying in the same instant. If the server sent
Retry-After, the worker never waits less than that. - Cancellation is cooperative. A cancel request only sets a flag. The worker checks it at safe points: before each step and during each backoff wait. A step that is running is allowed to finish, so nothing is left half done, and the run records which steps it skipped.
"""The worker: step timeouts, retries with backoff and jitter, cooperative cancel."""
import random
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as StepTimeout
import agent
import store
STEP_TIMEOUT = 1.0 # seconds one attempt may take
MAX_ATTEMPTS = 4
BASE, CAP = 0.1, 2.0 # backoff ceiling: 0.1 s, 0.2 s, 0.4 s ... at most 2 s
RUN_DEADLINE = 30.0 # seconds for the whole run
pool = ThreadPoolExecutor(max_workers=8) # runs the step attempts
class Stop(Exception):
def __init__(self, status: str, **detail):
super().__init__(status)
self.status, self.detail = status, detail
def cancel_point(run_id: int, skipped: list[str]) -> None:
if store.get_run(run_id)["cancel_requested"]:
raise Stop("cancelled", skipped=skipped)
def backoff(rng: random.Random, attempt: int, retry_after: float | None) -> float:
ceiling = min(CAP, BASE * 2 ** (attempt - 1))
delay = rng.uniform(0, ceiling) # "full jitter": spreads retries out
return max(delay, retry_after or 0) # never sooner than the server asked
def execute(run_id: int) -> str:
scenario = store.get_run(run_id)["scenario"]
rng = random.Random(run_id) # seeded, so the lab output repeats
deadline = time.monotonic() + RUN_DEADLINE
for i, step in enumerate(agent.STEPS):
cancel_point(run_id, agent.STEPS[i:]) # safe point: between steps
store.emit(run_id, "step_started", step=step, n=f"{i + 1}/{len(agent.STEPS)}")
for attempt in range(1, MAX_ATTEMPTS + 1):
if time.monotonic() > deadline:
raise Stop("timed_out", step=step)
future = pool.submit(agent.run_step, scenario, step, attempt)
try:
output = future.result(timeout=STEP_TIMEOUT)
break
except StepTimeout: # the stuck thread may still finish later!
error, retry_after = "step timeout", None
except agent.Transient as exc:
error, retry_after = str(exc), exc.retry_after
if attempt == MAX_ATTEMPTS:
raise Stop("failed", step=step, error=error)
wait = backoff(rng, attempt, retry_after)
store.emit(run_id, "retry", step=step, attempt=attempt, error=error,
wait=round(wait, 3))
end = time.monotonic() + wait
while time.monotonic() < end: # wait, but notice a cancel request
cancel_point(run_id, agent.STEPS[i:])
time.sleep(0.02)
store.emit(run_id, "step_done", step=step, output=output)
return "report filed"
def worker_loop() -> None:
while True:
run_id = store.next_queued()
if run_id is None:
time.sleep(0.05)
continue
try:
result = execute(run_id)
status, detail = "succeeded", {"result": result}
except Stop as stop:
status, detail = stop.status, stop.detail
store.emit(run_id, status, **detail) # last event first, then the status
store.update(run_id, status=status, result=str(detail))python3 -m py_compile worker.py && echo "worker.py compiles"worker.py compiles05. Step 4: The API and the progress stream
POST /runs stores a run and replies 202 with the run ID and the events URL; it does no agent work itself. GET /runs/{id} returns the current row for clients that prefer to poll. GET /runs/{id}/events is a Server-Sent Events (SSE) stream: one long HTTP response of text/event-stream, in which each event is a few field: value lines followed by a blank line. Each event carries an id; a client that reconnects sends the last one it saw in a Last-Event-ID header and receives only newer events. The stream closes once the run has ended and every event has been sent.
A dropped stream does not cancel the run here: the run belongs to the worker, not to the connection. Cancelling is an explicit POST /runs/{id}/cancel. MCP makes the opposite choice for ordinary requests over Streamable HTTP, where closing the stream cancels the request, which is one reason long-running MCP tools return a task handle instead.
"""HTTP API: start a run (202), read it, stream its progress (SSE), cancel it."""
import json
import re
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import store
import worker
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def send_json(self, status: int, body: dict) -> None:
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_POST(self):
size = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(size) or b"{}")
if self.path == "/runs":
run_id = store.create_run(body.get("scenario", "happy"))
return self.send_json(202, {"id": run_id, "status": "queued",
"events": f"/runs/{run_id}/events"})
match = re.fullmatch(r"/runs/(\d+)/cancel", self.path)
if match and store.get_run(int(match[1])):
store.update(int(match[1]), cancel_requested=1)
return self.send_json(202, {"id": int(match[1]), "cancel": "requested"})
self.send_json(404, {"error": "not found"})
def do_GET(self):
match = re.fullmatch(r"/runs/(\d+)(/events)?", self.path)
run = store.get_run(int(match[1])) if match else None
if run is None:
return self.send_json(404, {"error": "not found"})
if not match[2]:
return self.send_json(200, run)
self.send_response(200) # Server-Sent Events: one long response
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.end_headers()
seq = int(self.headers.get("Last-Event-ID", 0)) # resume after a drop
while True:
rows = store.events_after(run["id"], seq)
for seq, kind, data in rows:
self.wfile.write(f"id: {seq}\nevent: {kind}\ndata: {data}\n\n".encode())
self.wfile.flush()
if not rows and store.get_run(run["id"])["status"] in store.TERMINAL:
return # everything sent and the run is over: close the stream
time.sleep(0.05)
if __name__ == "__main__":
print("requeued after restart:", store.requeue_interrupted(), flush=True)
threading.Thread(target=worker.worker_loop, daemon=True).start()
print("runs API on http://127.0.0.1:8766", flush=True)
ThreadingHTTPServer(("127.0.0.1", 8766), Handler).serve_forever()python3 -m py_compile server.py && echo "server.py compiles"server.py compiles06. Step 5: A client, and a run that succeeds
The client starts a run, reads the stream line by line, and prints each event. It can also send a cancel when it sees a given event, reconnect from an event ID, or just read the status.
"""Start a run, print its event stream, optionally cancel after one event."""
import json
import sys
from urllib import request
API = "http://127.0.0.1:8766"
def call(method: str, path: str, body: dict | None = None) -> dict:
data = None if body is None else json.dumps(body).encode()
req = request.Request(API + path, data=data, method=method,
headers={"Content-Type": "application/json"})
with request.urlopen(req, timeout=5) as resp:
return json.load(resp)
def follow(run_id: int, cancel_after: str | None, last_id: int = 0) -> None:
req = request.Request(f"{API}/runs/{run_id}/events",
headers={"Last-Event-ID": str(last_id)})
with request.urlopen(req, timeout=30) as resp:
event: dict[str, str] = {}
for raw in resp: # an SSE event is "field: value" lines, then a blank line
line = raw.decode().rstrip("\n")
if line:
field, _, value = line.partition(": ")
event[field] = value
continue
data = json.loads(event["data"])
fields = ", ".join(f"{k}={v}" for k, v in data.items())
print(f"{event['id']:>2} {event['event']:<12} {fields}")
if cancel_after == f"{event['event']}:{data.get('step')}":
reply = call("POST", f"/runs/{run_id}/cancel")
print(" -> client sends cancel:", reply)
event = {}
if __name__ == "__main__":
if sys.argv[1] == "follow": # reconnect: python client.py follow RUN LAST_ID
follow(int(sys.argv[2]), None, int(sys.argv[3]))
sys.exit()
if sys.argv[1] == "status": # poll instead: python client.py status RUN
run = call("GET", f"/runs/{sys.argv[2]}")
print(run["status"], run["result"])
sys.exit()
scenario = sys.argv[1]
cancel_after = sys.argv[2] if len(sys.argv) > 2 else None
run = call("POST", "/runs", {"scenario": scenario})
print("202 Accepted:", run)
follow(run["id"], cancel_after)
print("final status:", call("GET", f"/runs/{run['id']}")["status"])rm -f runs.sqlite
python3 server.pyrequeued after restart: 0
runs API on http://127.0.0.1:8766python3 client.py happy202 Accepted: {'id': 1, 'status': 'queued', 'events': '/runs/1/events'}
1 step_started step=plan, n=1/4
2 step_done step=plan, output=plan ok
3 step_started step=search_docs, n=2/4
4 step_done step=search_docs, output=search_docs ok
5 step_started step=summarise, n=3/4
6 step_done step=summarise, output=summarise ok
7 step_started step=file_report, n=4/4
8 step_done step=file_report, output=file_report ok
9 succeeded result=report filed
final status: succeeded07. Step 6: A rate limit and a hung call
python3 client.py rate_limited
python3 client.py hang202 Accepted: {'id': 2, 'status': 'queued', 'events': '/runs/2/events'}
1 step_started step=plan, n=1/4
2 step_done step=plan, output=plan ok
3 step_started step=search_docs, n=2/4
4 retry step=search_docs, attempt=1, error=HTTP 429, wait=0.3
5 retry step=search_docs, attempt=2, error=HTTP 429, wait=0.3
6 step_done step=search_docs, output=search_docs ok
7 step_started step=summarise, n=3/4
8 step_done step=summarise, output=summarise ok
9 step_started step=file_report, n=4/4
10 step_done step=file_report, output=file_report ok
11 succeeded result=report filed
final status: succeeded
202 Accepted: {'id': 3, 'status': 'queued', 'events': '/runs/3/events'}
1 step_started step=plan, n=1/4
2 step_done step=plan, output=plan ok
3 step_started step=search_docs, n=2/4
4 step_done step=search_docs, output=search_docs ok
5 step_started step=summarise, n=3/4
6 retry step=summarise, attempt=1, error=step timeout, wait=0.024
7 step_done step=summarise, output=summarise ok
8 step_started step=file_report, n=4/4
9 step_done step=file_report, output=file_report ok
10 succeeded result=report filed
final status: succeededRun 2 waited 0.3 seconds before both retries. The jittered delay was smaller than that, but the server had asked for 0.3 seconds, and backoff() takes the larger value. Run 3 shows the timeout: the first summarise attempt gave no answer within a second, the worker waited a short random time and tried again, and the second attempt succeeded. The first attempt's thread was still asleep in the pool at that moment; its late result is simply ignored.
08. Step 7: A dependency that stays broken
python3 client.py broken202 Accepted: {'id': 4, 'status': 'queued', 'events': '/runs/4/events'}
1 step_started step=plan, n=1/4
2 step_done step=plan, output=plan ok
3 step_started step=search_docs, n=2/4
4 retry step=search_docs, attempt=1, error=HTTP 503, wait=0.024
5 retry step=search_docs, attempt=2, error=HTTP 503, wait=0.021
6 retry step=search_docs, attempt=3, error=HTTP 503, wait=0.158
7 failed step=search_docs, error=HTTP 503
final status: failedFour attempts, three waits, then the run stops with failed and says which step and which error. Look at the waits: 0.024, 0.021, 0.158. Each is random below its ceiling (0.1, 0.2, 0.4), so a second wait can be shorter than the first. The numbers repeat only because the generator is seeded with the run ID; in production you would not seed it, and many workers would spread out instead of retrying together.
09. Step 8: Cancel a run in the middle
The slow scenario takes 0.4 seconds per step. The client sends a cancel as soon as it sees search_docs start.
python3 client.py slow step_started:search_docs202 Accepted: {'id': 5, 'status': 'queued', 'events': '/runs/5/events'}
1 step_started step=plan, n=1/4
2 step_done step=plan, output=plan ok
3 step_started step=search_docs, n=2/4
-> client sends cancel: {'id': 5, 'cancel': 'requested'}
4 step_done step=search_docs, output=search_docs ok
5 cancelled skipped=['summarise', 'file_report']
final status: cancelledThe cancel arrived while search_docs was running. The worker let that step finish (event 4), reached the next safe point, and stopped with a record of the two steps it skipped. Nothing ran after the cancel was seen, and nothing was cut off half way.
10. Step 9: Reconnect and poll
A client that lost its connection after event 5 of run 4 can pick up where it stopped. A client that cannot read streams can poll the status instead.
python3 client.py follow 4 5
python3 client.py status 4 6 retry step=search_docs, attempt=3, error=HTTP 503, wait=0.158
7 failed step=search_docs, error=HTTP 503
failed {'step': 'search_docs', 'error': 'HTTP 503'}11. Check your understanding
12. Apply it
Move your practice agent into this shape: an endpoint that returns 202 and a run ID, a worker, a progress stream, and a cancel endpoint. Map your model client's real errors to retry or fail (429, 500, 503, connection errors and timeouts usually retry; 400, 401 and 403 do not), read Retry-After when the API sends it, and add a run deadline. Then try one thing the lab did not show: stop server.py with Ctrl+C while a slow run is in progress, start it again, and look at what requeued after restart prints and what the run's events show. Write down which steps ran twice, and keep that note for the next lab.
13. Review prompt
Without looking, describe the life of one run from POST /runs to its last event. Explain why the API answers 202 instead of doing the work, what a per-attempt timeout does and does not stop, how the wait before each retry is chosen, where the worker checks for cancellation and why it does not stop a step half way, and how a client resumes a dropped event stream.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.