LangGraph

Make a LangGraph graph wait hours for a person's approval with interrupt, a durable checkpoint and a webhook that resumes it.

LangGraph’s interrupt stops a graph and keeps its state in a checkpoint until someone resumes it. VariantGate supplies the someone: the question goes to an inbox that a teammate can answer from a phone, an email link or Slack, rules can answer the routine ones, and every answer is kept on the record. Together, a graph can wait hours for a decision without holding a process open.

If a decision takes seconds or minutes, you don’t need any of this: ask inside the tool, as the LangChain page shows. This page is for waits that outlast a request or a worker.

1. Install the client

pip install https://variantgate.com/sdk/variantgate-latest.tar.gz

It has no dependencies beyond the standard library and works on Python 3.9 or newer. Make an agent key under Agents in your workspace and put it in VARIANTGATE_KEY. The client reads it from there.

2. Ask in one node, wait in the next

The graph below refunds an order only after a person approves. The split into two nodes matters: LangGraph runs a node again from its first line when it resumes, so the node that asks must finish before the one that waits. The request id is then in the checkpoint, and resuming reads that request instead of asking a second time.

import contextlib
from typing import TypedDict

from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
from variantgate import ApprovalClient, VariantGateError, is_allowed

approvals = ApprovalClient("refund-graph")  # reads VARIANTGATE_KEY
waiting: dict[str, str] = {}  # request id -> thread id; a table in production


class Refund(TypedDict, total=False):
    order_id: str
    amount_eur: str
    approval_id: str
    result: str


def ask(state: Refund, config: RunnableConfig) -> Refund:
    """Ask once. The id lands in the checkpoint, so a resume never asks again."""
    asked = approvals.ask(
        "payment.refund",
        f"Refund €{state['amount_eur']} for order {state['order_id']}",
        amount=state["amount_eur"],
        currency="EUR",
        details={"order": state["order_id"]},
        ttl_seconds=24 * 3600,
    )
    waiting[asked["id"]] = config["configurable"]["thread_id"]
    return {"approval_id": asked["id"]}


def record(request_id: str, outcome: str, note: str) -> None:
    """Record how it went. Best effort: the graph must end even if this fails."""
    with contextlib.suppress(VariantGateError):
        approvals.report_outcome(request_id, outcome, note)


def stop(request_id: str, result: str, failure: str = "") -> Command:
    """End without a refund. The request is settled, so stop watching it."""
    if failure:
        record(request_id, "failed", failure)
    waiting.pop(request_id, None)
    return Command(goto=END, update={"result": result})


def wait_for_person(state: Refund) -> Command:
    """Pause the graph until the request is settled, then route on the answer."""
    decision = approvals.check(state["approval_id"])
    on_hold = decision["status"] == "approved" and decision["paused"]
    if decision["status"] == "pending" or on_hold:
        interrupt({"approval_id": state["approval_id"]})
        return Command(goto="wait_for_person")  # resumed: read the answer again
    if not is_allowed(decision):
        return stop(decision["id"], f"Not refunded: {decision['status']}.")
    if decision["approved_summary"] != decision["summary"]:
        why = "approved with other wording"
        return stop(decision["id"], f"Not refunded: {why}.", why)
    if decision["approved_amount"] is None:
        # It was asked with an amount, so an approval carries one. Never guess it.
        why = "approved without an amount"
        return stop(decision["id"], f"Not refunded: {why}.", why)
    # A person may approve less than was asked: refund what was approved.
    return Command(goto="refund", update={"amount_eur": decision["approved_amount"]})


def refund(state: Refund) -> Refund:
    refund_id = shop.refund(state["order_id"], state["amount_eur"])
    # The money moved: never fail the node over the record, or a retry refunds twice.
    record(state["approval_id"], "succeeded", f"refund {refund_id}")
    waiting.pop(state["approval_id"], None)  # settled: only now stop watching it
    return {"result": f"Refunded €{state['amount_eur']} for order {state['order_id']}."}


builder = StateGraph(Refund)
builder.add_node(ask)
builder.add_node(wait_for_person, destinations=("refund", "wait_for_person", END))
builder.add_node(refund)
builder.add_edge(START, "ask")
builder.add_edge("ask", "wait_for_person")
builder.add_edge("refund", END)
graph = builder.compile(checkpointer=InMemorySaver())  # a durable checkpointer in production



def run(graph_input: Refund | Command | None, thread: str) -> dict:
    """Start, resume or finish a thread. Every invoke goes through here: "sync" saves
    each step before the next starts, so a crash during the refund never rolls the
    graph back to its interrupt, where a resume would refund again."""
    return graph.invoke(graph_input, {"configurable": {"thread_id": thread}}, durability="sync")


# Start a refund. It stops at the interrupt and frees the worker.
run({"order_id": "1182", "amount_eur": "49.00"}, "refund-1182")
  • is_allowed is true only for an approval that may be acted on now. Denied, expired and withdrawn end the graph without a refund. An approval that arrives while the workspace or this agent is paused keeps the graph waiting until the pause is lifted.
  • A person may approve a lower amount than was asked, so the refund node uses approved_amount. A reworded approval may mean something the graph cannot do, so it stops and records why. An approval without an amount is never guessed at: the graph stops and records that too. Once the refund has gone through, a failure to record it never fails the node, so a retry cannot refund twice.
  • A thread stays in waiting until its graph has finished, so a crash before the refund leaves it where the sweep can find it. run passes durability="sync" to every invoke, which saves each step before the next starts, so a crash during the refund never rolls the graph back to its interrupt, where a resume would refund again. Python’s with_config ignores this setting, so start, resume and finish threads only through run. A graph stopped during the refund has no interrupt, so resume leaves it alone, and after ten minutes the sweep below moves it to needs_person. Check with your payment provider, then finish it with run(None, thread) if no refund went out.
  • Resuming early is harmless: the node reads the request again and pauses once more if nobody has decided yet.
  • ttl_seconds sets how long the request stays open, from 10 seconds to 7 days. When it runs out, the request is expired, and expired means no.

3. Wake the graph when a person decides

A signed webhook tells your server the moment a request is approved, denied or expired. Its only job is to wake the right thread: it never carries allowed, and the graph reads the answer itself before it acts. resume wakes only a graph that is paused at its interrupt, so a webhook that arrives while the graph is still running, or twice, does nothing. The graph removes its own entry from waiting once the request is settled. Webhooks need the Pro plan or higher.

import os
import threading

from flask import Flask, request
from langgraph.types import Command
from variantgate import WebhookVerificationError, verify_webhook

from refund_graph import approvals, graph, run, waiting

app = Flask(__name__)
DECIDED = {"request.approved", "request.denied", "request.expired"}
resuming: set[str] = set()  # threads this process is resuming now
resuming_lock = threading.Lock()


def resume(thread: str) -> None:
    """Wake a graph paused at its interrupt. A graph still running reads the answer itself."""
    with resuming_lock:
        if thread in resuming:
            return  # two resumes at once would both refund
        resuming.add(thread)
    try:
        if graph.get_state({"configurable": {"thread_id": thread}}).interrupts:
            run(Command(resume=True), thread)
    finally:
        with resuming_lock:
            resuming.discard(thread)


@app.post("/variantgate")
def variantgate_webhook():
    try:
        event = verify_webhook(
            os.environ["VARIANTGATE_WEBHOOK_SECRET"], request.headers, request.get_data()
        )
    except WebhookVerificationError:
        return "", 400
    thread = waiting.get(event["data"].get("request_id", ""))
    if event["type"] in DECIDED and thread:
        resume(thread)  # only a wake-up: the graph reads the answer itself
    return "", 204

Flask answers requests on several threads. Without the resuming set, two copies of the same webhook arriving together both see the interrupt and both resume, and the order is refunded twice. If the rest of the graph is slow, put the resume on a queue and answer the webhook at once. Also run a sweep every few minutes. It catches a decision that lands between the graph’s check and its interrupt, a pause being lifted, and any webhook that never arrived; without webhooks, it does the whole job. It also hands over a graph that a crash stopped during the refund, instead of checking it forever:

from datetime import datetime, timedelta, timezone

STUCK_AFTER = timedelta(minutes=10)  # far longer than a refund takes
needs_person: set[str] = set()  # a table in production


def sweep() -> None:
    """Run every few minutes. Wakes what a webhook missed, flags what a crash stopped."""
    for request_id, thread in list(waiting.items()):
        if approvals.check(request_id)["status"] == "pending":
            continue
        resume(thread)
        snapshot = graph.get_state({"configurable": {"thread_id": thread}})
        if "refund" not in snapshot.next or not snapshot.created_at:
            continue
        if datetime.now(timezone.utc) - datetime.fromisoformat(snapshot.created_at) > STUCK_AFTER:
            # A crash stopped the refund. The money may have moved: a person checks.
            waiting.pop(request_id, None)
            needs_person.add(thread)

Before it runs for real

  1. Use a durable checkpointer, such as LangGraph’s Postgres one, so a waiting graph survives a restart.
  2. Keep waiting in a table next to it. The thread id is all the webhook needs to find the right graph.
  3. The resuming set only guards one process. With several, resume each thread from one worker at a time, for example with a queue keyed by thread id, so a webhook and the sweep never run the same graph at once.
  4. Write a rule such as “always allow payment.refund up to €20”. Small refunds are then approved at once, and only the larger ones wait for a person.
  5. Deny one on purpose and check that the graph stops without refunding.

For how interrupt compares with the approval options in other frameworks, read human-in-the-loop agent frameworks compared.