· 7 min read · 1320 words

Building Deterministic LangGraph Workflows: StateGraph, interrupt() Gates, and Durable Jobs

How to build LangGraph StateGraph approval gates that hold across two-day waits, weird client payloads, and killed Kubernetes pods: top-of-node interrupt replay, fail-closed resume parsing, separating checkpoints from durable job records, and abandoned-run reconcilers.

Part 2 of Deterministic Workflows vs Autonomous AI Agents in LangGraph.

Building Deterministic LangGraph Workflows: StateGraph, interrupt() Gates, and Durable Jobs

Turning an unreliable prompt-orchestrated agent into a deterministic LangGraph StateGraph is the easy afternoon part. The hard part is everything that happens once real users run it in production: when a human ignores an approval prompt for forty-eight hours, sends back a weird payload shape, closes their browser tab, or triggers a rolling cluster deploy that kills the pod mid-run.

Part 1 covered how to decide when a process belongs in a workflow instead of an autonomous loop. This chapter is the real implementation guide: wiring a StateGraph onto an existing agent harness, building fail-closed interrupt() human gates, separating checkpoints from durable job records, and making sure a killed pod never strands a job "in progress" forever.


Register the workflow as an ordinary agent

On our platform, conversational agents and deterministic workflows live in the exact same registry. Our agent base class exposes a create_graph() hook that builds a Deep Agent by default; a workflow agent overrides it and returns a compiled StateGraph using the exact same Postgres checkpointer, store, tracing, and durable run lifecycle:

# Simplified from the workflow agent class
class UpgradeWorkflow(AbstractGraphAgent):
    async def create_graph(self) -> AgentGraph:
        resources = await resource_provider.get_agent_resources(...)
        tools = index_tools(resources.tools)
        workers = await self._build_impact_worker()
        discovery = await self._build_discovery_subgraph()
        graph = self._build_workflow(workers, tools, discovery).compile(
            name=self.name,
            store=resources.store,
            checkpointer=resources.checkpointer,
        )
        return graph.with_config(self._runtime_config)

Before we even touched human gates, four StateGraph rules bit someone on the team and are now pinned by unit tests:

  1. Restrict callers to messages only. LangGraph silently drops input keys outside input_schema. Declare a narrow UpgradeInput(TypedDict) containing only messages, let node 1 parse the request and seed internal channels itself, and write a test asserting set(graph.get_input_jsonschema()["properties"]) == {"messages"}. Keep messages even when the graph has no model turn: nodes append short human notes ("Scope approved", "Two services skipped") that stream straight to the UI.
  2. Checkpoint round trips turn Pydantic models into plain dicts. With a JSON checkpointer, typed Pydantic rows stored in state come back as raw dict objects after pause/resume. Every node reading a list channel passes it through small _ensure_* re-validation helpers.
  3. Call MCP tools in tool-call form, not plain dicts. Our workflow nodes invoke tools directly by name without a model. Our first version called tool.ainvoke(args_dict), which returned raw content; our AG-UI streaming adapter only emits live UI progress events for ToolMessage or Command objects, so every job update vanished and the web UI fell back to polling the entire job every two seconds. Switching to tool-call form ({"name", "args", "id", "type": "tool_call"}) fixed streaming immediately.
  4. Return tool failures as values, and retry only annotated read-only/idempotent tools. Our try_tool helper catches transient failures and retries once, strictly when the tool's own MCP annotations mark it read-only or idempotent (never on rate limits, and never on a hard-coded list of write tools). Equally important: failed audit writes to the job store log and continue rather than throwing away an estate's worth of finished worker compute.

Anatomy of a fail-closed interrupt() approval gate

Our workflow pauses at up to three human gates: scope approval before any service is analyzed, a conditional database confirmation if schema changes appear, and publication approval before export.

In LangGraph, a gate is a node calling interrupt() followed by a separate router function. When interrupt() runs, LangGraph checkpoints state and exits the run segment; when the user responds, the client invokes the same thread with Command(resume=answer), and LangGraph re-executes the gate node from its very first line, this time returning answer from interrupt():

# Simplified from the workflow gates module
async def publication_gate_node(tools, state, config):
    decision = decision_of(interrupt(publication_payload(state)))
    errors = await job_record_gate(
        tools, config, job_id=state.get("job_id"), kind="publication", decision=decision
    )
    update = {"publication_decision": decision, "errors": errors}
    if not approved(decision):
        update["halt_reason"] = "Publication was not approved, so no plan was exported."
    return update

def route_after_publication(state) -> str:
    """Export is structurally unreachable until publication approval clears."""
    return "export" if approved(state.get("publication_decision")) else "close_job"

Four non-obvious details make this hold up in production:

  • Every side effect before interrupt() runs twice. Because resume replays the gate node from line 1, our scope gate writes the job phase ("awaiting scope") before interrupt() using an idempotent update so the job board reflects the wait while parked. Anything non-idempotent goes strictly after interrupt().
  • Put only the question in the interrupt payload. Never copy the full service table or version counts into the interrupt payload; the UI already displays those from the live view, and duplicated state drifts immediately.
  • Bind approvals to a revision. Scope approval stores the revision ID of the discovered estate. If discovery re-runs and produces a new list, the revisions mismatch and the gate re-arms automatically (and because discovery runs in a nested thread, the parent passes its revision counter in so the counter does not reset to zero).
  • Fail closed on resume parsing. Different clients return booleans, strings, or nested dicts. One normalizer handles all of them and rejects everything unknown:
# Simplified from the workflow gates module
_APPROVE_WORDS = frozenset({"approve", "approved", "accept", "accepted", "yes", "confirm", "confirmed", "true"})
_DECISION_KEYS = ("decision", "type", "action", "response", "value", "approved")

def decision_of(resume_value) -> str:
    if isinstance(resume_value, bool):
        return APPROVE if resume_value else REJECT
    if isinstance(resume_value, str):
        return APPROVE if resume_value.strip().lower() in _APPROVE_WORDS else REJECT
    if isinstance(resume_value, Mapping):
        for key in _DECISION_KEYS:
            if key in resume_value:
                return decision_of(resume_value[key])
        logger.warning("gate_decision_unreadable", payload_keys=sorted(map(str, resume_value)))
    return REJECT

Notice the logging detail too: an unreadable payload logs its sorted key names, never its values, because free-text user replies can contain sensitive data. A gate that fails open on an unexpected payload is not a gate.


Keep three stores strictly apart (and survive killed pods)

Early in design review, an engineer warned that stuffing product status into LangGraph state would end up "implementing a product job scheduler inside checkpoint state." They were right. We separated persistence into three distinct stores:

  1. The LangGraph checkpoint (run memory): large, internal, per thread.
  2. A curated state_view() projection (live UI): a small, read-only product summary emitted to the watched thread, never written back. (An early bug read full checkpoints for every agent on every state snapshot, driving pods out of memory on long threads; reading checkpoints only for agents that override state_view() fixed the OOMs.)
  3. A durable Job Record in our workspace service (product memory): cross-thread, auditable, with separate status (monotonic: open, closed, cancelled; never moves backwards) and phase columns so a late phase write can never reopen a cancelled job.

Two-panel diagram showing the interrupt() gate round trip with top-of-node replay and fail-closed decision_of() parsing on the left, and the separation of Checkpoint, Curated state_view(), Durable Job Record, and abandoned-run reconciler on the right.

Left: a gate pauses with zero compute, replays from line 1 on Command(resume), and fails closed on any unreadable answer. Right: keeping checkpoint state, live UI views, and durable job records separate lets an abandoned-run reconciler settle jobs even after a pod kill.

Every in-graph path (rejection, unsupported version refusal, completion) funnels into one close_job node. Yet real runs also die outside the graph: the user clicks cancel, a node throws an unhandled exception, or Kubernetes kills the pod during a rolling deploy.

In September, a cluster redeploy killed a running upgrade; the UI marked the run errored while the job record stayed frozen "in progress" forever because the shutdown never reached close_job.

The lasting fix combined two harness hooks (on_run_parked to stop the job's active-time clock when waiting on a human, and on_run_settled to close the job on cancel/crash) with an abandoned-run reconciler: when a pod dies and its per-thread lease expires, another pod claims the abandoned run, inspects its checkpoint, and invokes on_run_parked or on_run_settled. Even there, code review saved us from a sneaky retry bug where the reconciler's first draft stopped retrying and marked the run finished without ever calling the settle hook.

When it all works together, traces look refreshingly boring. One real development run spanned four segments across almost two days (segment 1 to scope gate: 3% compute; segment 2 after a two-day human wait through fan-out to database gate: 91% compute; segment 3 to publication gate: under 1%; segment 4 export and close: 6%). Total active compute was roughly 0.3% of wall-clock time. Across dev and staging, resuming a paused gate is the normal path, not an edge case.


What I am still going back and forth on

Our architecture record claims every transport reaches a workflow unchanged. In reality, only our web workspace renders interrupts and calls the resume hooks; our IDE integration does not route to the workflow and our HTTP API still lacks a resume path. Building transport-agnostic interrupts on paper is easy; making every client actually resume a paused thread is where the real product work hides.

I also still wish we had listed every off-graph exit (cancel, crash, timeout, rolling deploy) before shipping our first gate. We built happy path first, then cancel, then crash, then pod kill, paying an extra iteration at each step.


Design the exits before you build the gates

A human-in-the-loop gate in LangGraph is more than dropping interrupt() into a node. Make side effects before interrupt() idempotent, fail closed on every unreadable resume value, separate checkpoints from your durable product record, and wire a lease-based reconciler so killed pods still settle cleanly.

Previous: Part 1: When to Use a Deterministic Workflow Instead of an AI Agent. Next: Part 3: Parallel Fan-Out in LangGraph: Send, Bounded Concurrency, Nested Graphs, and Tool-Less Turns.

Related writings