Skip to content
← Notebook

Agent Engineering

Durable Execution in AI Agents: Checkpointing, Idempotency and Asynchronous Approval (HITL) in Production

Why 85% of multi-step agents fail when they run in volatile memory and how to design a Durable Harness with deterministic replay, idempotency keys and asynchronous human approval gates.

Date
Oct 16, 2026
Reading time
9 min
Result
0 Duplicate Side Effects • 100% Token Savings on Retries • 0% CPU While Waiting for HITL • Replay < 3ms

Translated from the Spanish original. The code, data and READMEs on GitHub are in Spanish.

The wave of open-source releases in October 2026 (from meta-harnesses such as Ruflo, AWS Strands Harness and Pizza Bot to the mass adoption of durable execution engines such as Inngest, Hatchet and LangGraph Checkpointers) has left an unquestionable architectural lesson in the trenches: an AI agent in production isn’t a model, it’s a model plus its harness (Agent = Model + Harness).

The model provides stochastic reasoning; the harness provides state durability, tool isolation, idempotency guarantees and human approval gates (Human-in-the-Loop).

Yet 85% of developers are still deploying long-running agents inside a simple while loop in RAM or tied to a synchronous HTTP request. In this technical notebook from YesWeLab (@Yeswelab_OU) we break down why that architecture collapses in the real world and how to build indestructible agents under our Dual Track philosophy.


1. Death at Step 9: The Disaster of Volatile Agents

Imagine an autonomous agent for financial operations or sales onboarding that runs a 10-step workflow: it researches a company, queries the ERP, generates a PDF contract, issues an invoice in Stripe, sends an email to the customer and updates the CRM.

In a naive architecture based on volatile memory (a Python script or a workflow with no intermediate checkpoints), this is what happens when the network blips or the LLM provider returns an HTTP 529 Overloaded error at step 9:

[ VOLATILE EXECUTION IN RAM: THE BLIND RETRY DISASTER ]

Step 1: Agent researches tax details (LLM + web)        ──► ✅ OK ($0.04)
Step 2: Agent validates the tax ID in the database      ──► ✅ OK
Step 3: Agent drafts the contract (LLM)                 ──► ✅ OK ($0.08)
Step 4: Tool call -> stripe.create_invoice(€490)        ──► ✅ OK [REAL SIDE EFFECT]
Step 5: Tool call -> smtp.send_email(customer)          ──► ✅ OK [REAL SIDE EFFECT]
...
Step 9: LLM summarises for the CRM                      ──► 💥 ERROR 529 / NETWORK TIMEOUT

[ AUTOMATIC WORKER RETRY FROM STEP 1 ]
├──► Burns the tokens for steps 1 to 8 again (cost x2)
├──► Runs stripe.create_invoice(€490) A SECOND TIME (customer charged twice)
└──► Sends a second, duplicate email to the customer

When state lives only in the process’s local variables:

  1. Any Docker container restart or network outage destroys progress.
  2. Retrying the whole task fires tools with irreversible side effects again (payments, sent messages, created records).
  3. The token bill doubles or triples by regenerating reasoning that had already succeeded.

2. Anatomy of a Durable Agent Harness: Checkpointing and Deterministic Replay

Durable Execution turns the agent loop into a state machine backed by a persistent event log (Append-Only Step Journal).

                ┌──────────────────────────────────────────┐
                │       AGENT TURN / TOOL CALL             │
                └────────────────────┬─────────────────────┘
                                     │
                     Does (run_id, step_id, args_hash) exist
                           in the Step Journal (WAL)?
                                     │
                 ┌───────────────────┴───────────────────┐
                 │ YES (replay after a crash)            │ NO (first run)
                 ▼                                       ▼
   ┌───────────────────────────┐           ┌───────────────────────────┐
   │   INSTANT HYDRATION       │           │   REAL EXECUTION + LOCK   │
   │ • Reads output from SQLite│           │ • Calls the LLM or MCP    │
   │ • Latency: < 2ms          │           │ • Persists output in WAL  │
   │ • Cost: $0.00 in tokens   │           │ • Advances graph pointer  │
   │ • 0 duplicate effects     │           └───────────────────────────┘
   └───────────────────────────┘

The 3 engineering pillars of the durable harness

Technical Pillar What problem it solves in the trenches Implementation mechanism
1. Step Checkpointing Avoids losing context and partial results if the container dies halfway through a 15-minute job. Serialising the graph state to SQLite WAL / Postgres at the end of each node.
2. Idempotency Keys Stops an external tool (Stripe, CRM, email) from executing the same mutation twice during a retry. A deterministic hash SHA256(run_id + tool_name + canonical_json(args)) checked before calling the API.
3. Async HITL (Suspend/Resume) Eliminates processes blocked for hours waiting for human approval. The agent saves the checkpoint, sends a signed webhook to Telegram/Slack and ends the process (0% RAM/CPU).

3. Implementation in Code: A Durable Step Runner + Idempotency in SQLite WAL

You don’t need heavy infrastructure to give your Python agents durability and idempotency. With SQLite in WAL mode you can implement a Durable Harness that guarantees exactly-once execution over your MCP tools:

import sqlite3
import hashlib
import json
from typing import Callable, Any

class DurableAgentHarness:
    def __init__(self, db_path: str = "/Users/mortadelo/yeswelab/data/lab.db"):
        self.conn = sqlite3.connect(db_path)
        self.conn.execute("PRAGMA journal_mode=WAL;")
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS agent_step_journal (
                idempotency_key TEXT PRIMARY KEY,
                run_id TEXT NOT NULL,
                step_name TEXT NOT NULL,
                result_json TEXT NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)
        self.conn.commit()

    @staticmethod
    def _compute_key(run_id: str, step_name: str, payload: dict) -> str:
        canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False)
        raw = f"{run_id}:{step_name}:{canonical}"
        return hashlib.sha256(raw.encode("utf-8")).hexdigest()

    def step_run(self, run_id: str, step_name: str, payload: dict, fn: Callable[..., Any]) -> Any:
        key = self._compute_key(run_id, step_name, payload)
        cur = self.conn.cursor()

        # 1. Check whether the step already ran successfully (deterministic replay)
        cur.execute(
            "SELECT result_json FROM agent_step_journal WHERE idempotency_key = ?",
            (key,)
        )
        row = cur.fetchone()
        if row is not None:
            print(f"[REPLAY] Step '{step_name}' hydrated from disk (0 tokens / 0 side-effects)")
            return json.loads(row[0])

        # 2. Run the tool or the LLM turn for the first time
        result = fn(**payload)

        # 3. Persist atomically before moving on to the next step
        cur.execute(
            """
            INSERT INTO agent_step_journal (idempotency_key, run_id, step_name, result_json)
            VALUES (?, ?, ?, ?)
            """,
            (key, run_id, step_name, json.dumps(result, ensure_ascii=False))
        )
        self.conn.commit()
        return result

If the process dies at step 9 and the supervisor (launchd, systemd or Docker) brings it back up with the same run_id:

  • Steps 1 to 8 print [REPLAY] in under 2 milliseconds, returning exactly the same JSON objects without touching the network or charging the customer twice.
  • Step 9 runs cleanly from where it left off.

4. Asynchronous Human-in-the-Loop: The “Inbox & Webhook Resume” Pattern

The second big anti-pattern in AI agents is assuming the user is watching a chat window waiting for the agent to finish. When an agent needs authorisation for a critical action (e.g. posting on social media, issuing a refund or deploying code):

  1. Never keep a sleep() or an open connection in memory: If the human takes 3 hours to reply from their phone, any server restart will kill the wait.
  2. Suspend to disk (Dehydrate): The agent writes its full state to the database with status = 'waiting_approval', generates a signed resume_token and sends an interactive card to Telegram or Slack.
  3. Release all resources: The worker finishes its execution. RAM and CPU usage during the 3 hours of waiting is exactly zero.
  4. Event-driven resume (Rehydrate): When the user taps “Authorise” (or the scheduled timeout expires with an auto-approve / auto-reject policy), the webhook wakes a worker, loads the checkpoint by its run_id and runs only the final step.

5. The Dual Track Strategy at YesWeLab

At YesWeLab we apply this architecture at two levels depending on the project’s volume and infrastructure:

Track A: Open Source in the Trenches / DIY ($0 Cost and Local Control)

  • LangGraph + SqliteSaver (WAL Mode): Every node transition in the agent’s graph is automatically saved to a local SQLite file with a deterministic thread_id, letting you use interrupt_before=["critical_tool"] to pause and resume workflows without losing state.
  • Self-Hosted n8n with the Wait Node (Webhook Resume): In hybrid n8n workflows in Docker, the Wait node configured in On Webhook Call mode automatically dumps the execution state to n8n’s SQLite/Postgres database, freeing the container’s memory until the Telegram or email button calls the unique $execution.resumeUrl.
  • An Idempotency Journal in SQLite: A local agent_step_journal table with a SHA-256 primary key to shield destructive MCP tools at zero cost.

Track B: Fast-Track SaaS and Distributed Scaling

  • Inngest (step.run and step.waitForEvent): Serverless agent orchestration where each step is a durable function with automatic exponential retries and event waits of up to 30 days without paying for idle compute.
  • Temporal / Hatchet + n8n Cloud HITL: For enterprise fleets with dozens of concurrent agents, guaranteeing queues with adaptive backpressure, dead-letter queues and full SOC 2 / GDPR audit traceability.

6. A Checklist from the Trenches: Auditing Agentic Durability

Before connecting an agent to tools with a real impact on your business, check these 5 points:

  • Chaos Test (Kill -9 Test): If you kill the agent’s container at step 4 of 6 and relaunch it with the same run_id, does it resume at step 4 without repeating steps 1 to 3?
  • Mandatory Idempotency Keys: Every MCP tool that writes data, sends messages or moves money requires a deterministic idempotency_key derived from the run_id.
  • Zero Waits in RAM: No human approval workflow keeps a process alive with sleep() or hanging HTTP connections; all HITL serialises state to disk.
  • Timeouts with an Explicit Policy: Approval gates have a defined SLA (e.g. auto-publish at 11:00 if it’s scheduled content, or auto-abort if it’s a financial transaction).
  • Separate Transient from Terminal Errors: 429/529 errors apply exponential backoff on the current step; 400 Bad Schema errors break the loop immediately without burning budget.
#LangGraph SQLiteSaver#n8n Wait Webhook#Inngest#Ruflo Harness#SQLite WAL#Docker#Python