Idempotent Side Effects
Build a local ticket service that honours an Idempotency-Key header, give the agent's create_ticket tool a key that stays the same across retries and restarts, watch a lost reply create a duplicate without it, and reconcile by lookup, or report an unknown outcome, when a service offers no key at all.
Contentsand lesson path
On this page
- The problem
- Step 1: A ticket service that remembers keys
- Step 2: A key that names the action, not the attempt
- Step 3: Lose a reply and retry
- Step 4: A key reused for something else
- Step 5: No key support? Reconcile, or say "unknown"
- 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
- Make side-effecting tools idempotent with idempotency keys so that retried steps never repeat an action.
Prerequisites: Agent Loops & ReAct
01. The problem
In the last two lessons, every recovery re-ran the step that was interrupted. That is not a flaw of one tool: any system that records progress after a step finishes has a moment where the step's effect exists but the record does not. Retries add a second source of repeats. When a request times out, you cannot tell whether the service did the work and the reply was lost, or never got the request.
An operation is idempotent if doing it twice has the same effect as doing it once. Reading a record is naturally idempotent; so is "set the ticket status to closed". "Create a ticket" and "charge £40" are not. The standard fix is an idempotency key: a value the client sends with the request that names the logical action, not the attempt. The service stores the key with its result. When the same key arrives again, it returns the stored result instead of acting again.
In this worked example you will build a small ticket service that supports keys, connect the agent's create_ticket tool to it, lose a reply on purpose, and then handle a service that has no keys at all. Everything runs on Python 3.10 or newer with only the standard library. Create a folder called idem-lab, save each file below into it, and use two terminals in that folder.
02. Step 1: A ticket service that remembers keys
The service stores tickets in SQLite. For a request with an Idempotency-Key header it also stores the key, a hash of the request body and the reply, all in the same transaction as the ticket. That detail matters: if the ticket and the saved reply were written separately, a crash between the two writes would leave a ticket with no key, and the next retry would create a second one.
Three more behaviours copy what real services such as Stripe do. A repeat with the same key and the same body gets the saved reply, marked with an Idempotent-Replayed header. A repeat with the same key but a different body is refused, because a key reused for another action is a bug in the client: Stripe returns an error, and this service uses 422. The IETF draft that standardises the Idempotency-Key header (still an Internet-Draft, not an RFC) recommends the same 422, and 409 for a repeat that arrives while the first request is still being processed; this small service handles one write at a time, so it never needs 409. And POST /admin/faults lets you make the next create succeed and then drop the connection before the reply, which is exactly the lost-reply case.
"""A local ticket service with Idempotency-Key support (stdlib only)."""
import hashlib
import json
import os
import sqlite3
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
db = sqlite3.connect("tickets.sqlite", check_same_thread=False)
db.executescript("""
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY, ref TEXT, title TEXT, queue TEXT); -- ref: not unique
CREATE TABLE IF NOT EXISTS idem (key TEXT PRIMARY KEY, req_hash TEXT, body TEXT);
""")
lock = threading.Lock()
faults = {"drop_next": 0, "lookup_down": False} # set via POST /admin/faults
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args): # keep the terminal quiet
pass
def reply(self, status, body, replayed=False):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
if replayed:
self.send_header("Idempotent-Replayed", "true")
self.end_headers()
self.wfile.write(data)
def do_GET(self):
url = urlsplit(self.path)
ref = parse_qs(url.query).get("ref", [None])[0]
if ref and faults["lookup_down"]:
return self.reply(503, {"error": "lookup unavailable"})
sql, args = "SELECT id, ref, title, queue FROM tickets", ()
if ref:
sql, args = sql + " WHERE ref = ?", (ref,)
rows = db.execute(sql + " ORDER BY id", args).fetchall()
keys = ("id", "ref", "title", "queue")
self.reply(200, [dict(zip(keys, r)) for r in rows])
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if self.path == "/admin/faults":
faults.update(body)
return self.reply(200, faults)
key = self.headers.get("Idempotency-Key")
req_hash = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
with lock, db: # one transaction: ticket row and saved reply together
if key:
saved = db.execute(
"SELECT req_hash, body FROM idem WHERE key = ?", (key,)).fetchone()
if saved and saved[0] != req_hash:
return self.reply(422, {"error": "key reused with other params"})
if saved:
return self.reply(201, json.loads(saved[1]), replayed=True)
cur = db.execute(
"INSERT INTO tickets (ref, title, queue) VALUES (?, ?, ?)",
(body.get("ref"), body["title"], body["queue"]))
ticket = {"id": cur.lastrowid, **body}
if key:
db.execute("INSERT INTO idem VALUES (?, ?, ?)",
(key, req_hash, json.dumps(ticket)))
if faults["drop_next"]: # committed, but the reply never arrives
faults["drop_next"] -= 1
self.close_connection = True
return
self.reply(201, ticket)
if __name__ == "__main__":
port = int(os.environ.get("TICKET_API_PORT", "8765"))
print(f"ticket API on http://127.0.0.1:{port}", flush=True)
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()rm -f tickets.sqlite
python3 ticket_api.pyticket API on http://127.0.0.1:876503. Step 2: A key that names the action, not the attempt
The tool below retries up to three times on errors that may be temporary: a dropped connection, a timeout, a 5xx or a 429. A 4xx such as 422 is raised at once, because sending the same bad request again will fail the same way.
The important line is step_key. It derives the key from the run ID and the step ID, so it is the same on attempt 1 and attempt 3, and also after a crash and resume, as long as the resumed run keeps its run ID. Hashing keeps the key short and avoids putting names or emails in it. The fresh_key_each_try flag exists only to show the common mistake of creating a new random key inside the retry loop.
"""The agent's create_ticket tool: a stable key plus bounded retries."""
import hashlib
import http.client
import json
import os
import time
import uuid
from urllib import error, request
API = os.environ.get("TICKET_API_URL", "http://127.0.0.1:8765")
# Network trouble, a lost reply or an HTTP error (HTTPError is a URLError).
RETRYABLE = (error.URLError, http.client.RemoteDisconnected, TimeoutError)
def call(method, path, body=None, key=None):
req = request.Request(API + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
if key:
req.add_header("Idempotency-Key", key)
with request.urlopen(req, timeout=2) as resp:
return resp.status, resp.headers.get("Idempotent-Replayed"), json.load(resp)
def step_key(run_id: str, step_id: str) -> str:
"""Same logical action -> same key, on every attempt and after a restart."""
return hashlib.sha256(f"{run_id}/{step_id}".encode()).hexdigest()[:32]
def create_ticket(run_id, step_id, title, queue, fresh_key_each_try=False):
for attempt in range(1, 4):
key = str(uuid.uuid4()) if fresh_key_each_try else step_key(run_id, step_id)
try:
status, replayed, ticket = call("POST", "/tickets",
{"title": title, "queue": queue}, key)
note = " (replayed)" if replayed else ""
print(f" attempt {attempt}: {status}{note} -> ticket {ticket['id']}")
return ticket
except error.HTTPError as exc:
if exc.code < 500 and exc.code != 429:
raise # a 4xx will fail the same way again: do not retry
print(f" attempt {attempt}: HTTP {exc.code}, retrying")
except RETRYABLE as exc:
print(f" attempt {attempt}: {type(exc).__name__}, retrying")
time.sleep(0.2 * 2 ** (attempt - 1))
raise RuntimeError("create_ticket failed after 3 attempts")04. Step 3: Lose a reply and retry
The demo turns on one dropped reply, calls the tool with the stable key, then does the same with a fresh key per attempt, and finally lists every ticket.
"""Lose one reply, retry, then count tickets: stable key versus fresh key."""
from tool import call, create_ticket
call("POST", "/admin/faults", {"drop_next": 1})
print("stable key, reply lost once:")
create_ticket("run-7", "step-3", "Refund not received", "billing")
call("POST", "/admin/faults", {"drop_next": 1})
print("fresh key on every attempt, reply lost once:")
create_ticket("run-8", "step-3", "Refund not received", "billing",
fresh_key_each_try=True)
_, _, tickets = call("GET", "/tickets")
print("tickets now:")
for t in tickets:
print(f" {t['id']}: {t['title']}")python3 demo_retry.pystable key, reply lost once:
attempt 1: RemoteDisconnected, retrying
attempt 2: 201 (replayed) -> ticket 1
fresh key on every attempt, reply lost once:
attempt 1: RemoteDisconnected, retrying
attempt 2: 201 -> ticket 3
tickets now:
1: Refund not received
2: Refund not received
3: Refund not receivedWith the stable key, attempt 1 created ticket 1 and lost the reply; attempt 2 carried the same key, so the service returned the saved reply for ticket 1 and created nothing. The agent got its ticket ID and the customer got one ticket. With a fresh key, attempt 1 created ticket 2 and lost the reply, and attempt 2 looked like a brand-new request, so it created ticket 3. Two tickets for one action, and no error anywhere to tell you.
Notice that the tool could not tell the two situations apart: both first attempts ended in RemoteDisconnected. Only the key let the service recognise the repeat.
05. Step 4: A key reused for something else
A key that is too coarse is as dangerous as one that changes too often. If a key were derived only from the run ID, every step of the run would share it, and the second action would get the first action's reply. This service compares the body hash and refuses the mismatch.
"""Reuse a key for a different request: the service refuses it."""
from urllib import error
from tool import call, step_key
key = step_key("run-7", "step-3") # the key already used for ticket 1
try:
call("POST", "/tickets", {"title": "Change my address", "queue": "account"}, key)
except error.HTTPError as exc:
print(exc.code, exc.read().decode())python3 demo_mismatch.py422 {"error": "key reused with other params"}So the rule is one key per logical action: one key per run and step, and if a step creates several things, one key per item, for example run-7/step-3/line-2. Keys also expire. Stripe's v1 API, for example, may remove a key once it is at least 24 hours old, after which the same key makes a new request. If your runs can be resumed days later, a stored key alone is not enough; you also need the lookup in the next step.
06. Step 5: No key support? Reconcile, or say "unknown"
Many APIs take no idempotency key. You can still avoid blind repeats if the API lets you store your own reference on the object and search by it. After a lost reply, you reconcile: you look up your reference to find out what really happened. If the object exists, you use it. If the search says it does not exist, a retry is safe only under two conditions: the lookup reads committed data (not a lagging index or replica), and the first request can no longer be running, for example because the server gives up on requests sooner than you wait. This lab's service meets both, since it commits before it drops the reply and answers lookups from the same database. If you cannot find out, because the search itself fails, the honest result is unknown: record it for a person or a later job to check, and do not guess. Retrying could create a duplicate, and reporting failure could hide a ticket that exists.
The ticket service stores ref but does not enforce that it is unique, like many real APIs, so the lookup is the only protection here.
"""No idempotency key? Look the action up by our own reference before retrying."""
import json
from urllib import error
from tool import RETRYABLE, call
REVIEW_QUEUE = "needs_review.jsonl"
def find_by_ref(ref):
_, _, rows = call("GET", f"/tickets?ref={ref}")
return rows[0] if rows else None
def create_or_reconcile(ref, title, queue, tries=3):
"""Returns (outcome, ticket). Outcomes: created, found, unknown, failed."""
try:
_, _, ticket = call("POST", "/tickets",
{"ref": ref, "title": title, "queue": queue})
return "created", ticket
except error.HTTPError as exc:
if exc.code < 500:
raise # rejected outright, so nothing was created
except RETRYABLE:
pass # the reply is lost: the ticket may or may not exist
try:
ticket = find_by_ref(ref)
except RETRYABLE:
with open(REVIEW_QUEUE, "a") as f: # do not guess: park it for a human
f.write(json.dumps({"ref": ref, "action": "create_ticket"}) + "\n")
return "unknown", None
if ticket:
return "found", ticket
if tries > 1: # confirmed absent by a consistent lookup
return create_or_reconcile(ref, title, queue, tries - 1)
return "failed", None # confirmed absent, out of retries
if __name__ == "__main__":
call("POST", "/admin/faults", {"drop_next": 1})
outcome, ticket = create_or_reconcile("run-9/step-3", "Card declined", "billing")
print(outcome, ticket and ticket["id"])
call("POST", "/admin/faults", {"drop_next": 1, "lookup_down": True})
outcome, ticket = create_or_reconcile("run-10/step-3", "Card declined", "billing")
print(outcome, ticket and ticket["id"])
print("review queue:", open(REVIEW_QUEUE).read().strip())python3 reconcile.pyfound 4
unknown None
review queue: {"ref": "run-10/step-3", "action": "create_ticket"}In the first call the reply was lost, the lookup found ticket 4, and the agent carried on with it. In the second call the reply was lost and the lookup was down, so the request went to needs_review.jsonl. Ticket 5 does exist; a person checking the queue would find it and close the item. In an agent, "unknown" should stop or pause the run at this step and show the item to an operator, rather than letting the model decide whether to try again. Stop the service with Ctrl+C in terminal 1 when you are done.
When an effect cannot be made idempotent or checked, the remaining tool is compensation: a second action that undoes the first, such as cancelling a duplicate ticket or refunding a double charge. Compensation is a business action with its own failure cases, so treat it as a last resort, not a replacement for keys.
07. Check your understanding
08. Apply it
Take the side-effect list from lesson 1 for your practice agent. For each external call, write down which of these three it supports: an idempotency key (and for how long the service keeps it), a lookup by your own reference, or neither. Give every call a key derived from run and step IDs, add a reconciliation path for calls with only a lookup, and make calls with neither stop the run with an "unknown outcome" item for review. Lesson 5 will crash your agent at each of these points to prove it.
09. Review prompt
Without looking, explain what the service stores for each key and why it stores it in the same transaction as the ticket. Describe what happened to tickets 1, 2 and 3 in the demo. Then state the decision you make after a lost reply in three cases: the API takes keys, the API only supports lookup, and the lookup is unavailable.
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.