LangGraph.js
Make a LangGraph.js graph wait for a person's approval with interrupt(), a Postgres checkpoint and a webhook that resumes it with Command.
In LangGraph.js, interrupt() stops a graph and keeps its state in a checkpoint until new Command({ resume }) wakes it. VariantGate supplies the person who decides: 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. The code below was run against @langchain/langgraph 1.7 with an approval, a denial, a lowered amount and a resume in a second process. The Python version is on the LangGraph page.
If a decision takes seconds and nothing needs to survive a restart, you don’t need a graph for it: ask inside the tool with guard, as the Vercel AI SDK page shows. This page is for waits that outlast a request or a worker.
1. Install
npm install @langchain/langgraph @langchain/core
npm install https://variantgate.com/sdk/variantgate-agent-latest.tgzMake an agent key under Agents and put it in VARIANTGATE_KEY. Then, in approvals.ts:
import { ApprovalClient } from "@variantgate/agent";
export const approvals = new ApprovalClient({
agent: "refund-graph",
apiUrl: "https://api.variantgate.com",
key: process.env.VARIANTGATE_KEY ?? "",
});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 {
Annotation,
Command,
END,
interrupt,
type LangGraphRunnableConfig,
MemorySaver,
START,
StateGraph,
} from "@langchain/langgraph";
import { approvals } from "./approvals";
import { shop } from "./shop"; // your own refund code
/** Request id to thread id. A table in production. */
export const waiting = new Map<string, string>();
const Refund = Annotation.Root({
orderId: Annotation<string>,
amountEur: Annotation<string>,
approvalId: Annotation<string>,
result: Annotation<string>,
});
type State = typeof Refund.State;
/** Ask once. The id lands in the checkpoint, so a resume never asks again. */
async function ask(state: State, config: LangGraphRunnableConfig) {
const asked = await approvals.ask({
action: "payment.refund",
summary: `Refund €${state.amountEur} for order ${state.orderId}`,
amount: state.amountEur,
currency: "EUR",
details: { order: state.orderId },
ttlSeconds: 24 * 3600,
});
waiting.set(asked.id, config.configurable?.thread_id);
return { approvalId: asked.id };
}
/** Record how it went. Best effort: the graph must end even if this fails. */
async function record(id: string, outcome: "succeeded" | "failed", note: string) {
try {
await approvals.reportOutcome(id, outcome, note);
} catch (error) {
console.error("outcome not recorded", id, error);
}
}
/** End without a refund. The request is settled, so stop watching it. */
async function stop(id: string, result: string, failure?: string) {
if (failure) {
await record(id, "failed", failure);
}
waiting.delete(id);
return new Command({ goto: END, update: { result } });
}
/** Pause until the request is settled, then route on the answer. */
async function waitForPerson(state: State) {
const decision = await approvals.check(state.approvalId);
const onHold = decision.status === "approved" && decision.paused;
if (decision.status === "pending" || onHold) {
interrupt({ approvalId: state.approvalId });
return new Command({ goto: "waitForPerson" }); // resumed: read the answer again
}
if (!decision.allowed) {
return stop(decision.id, `Not refunded: ${decision.status}.`);
}
if (decision.approved_summary !== decision.summary) {
const why = "approved with other wording";
return stop(decision.id, `Not refunded: ${why}.`, why);
}
if (decision.approved_amount === null) {
// It was asked with an amount, so an approval carries one. Never guess it.
const why = "approved without an amount";
return stop(decision.id, `Not refunded: ${why}.`, why);
}
// A person may approve less than was asked: refund what was approved.
return new Command({ goto: "refund", update: { amountEur: decision.approved_amount } });
}
async function refund(state: State) {
const refundId = await shop.refund(state.orderId, state.amountEur);
// The money moved: never fail the node over the record, or a retry refunds twice.
await record(state.approvalId, "succeeded", `refund ${refundId}`);
waiting.delete(state.approvalId); // settled: only now stop watching it
return { result: `Refunded €${state.amountEur} for order ${state.orderId}.` };
}
export const graph = new StateGraph(Refund)
.addNode("ask", ask)
.addNode("waitForPerson", waitForPerson, { ends: ["refund", "waitForPerson", END] })
.addNode("refund", refund)
.addEdge(START, "ask")
.addEdge("ask", "waitForPerson")
.addEdge("refund", END)
.compile({ checkpointer: new MemorySaver() }) // a durable checkpointer in production
// Save each step before the next starts: a crash during the refund then
// never rolls the graph back to its interrupt, where a resume would refund again.
.withConfig({ durability: "sync" });- The graph acts only when
allowedis true. Denied, expired and withdrawn end it without a refund. An approval that arrives while the workspace or this agent is paused keeps the graph waiting until the pause is lifted. - The value passed to
resumeis ignored on purpose. Whoever wakes the graph cannot grant anything; the node reads the answer from VariantGate. - 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
waitinguntil its graph has finished, so a crash before the refund leaves it where the sweep can find it.durability: "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. Such a graph has no interrupt, soresumeleaves it alone, and after ten minutes the sweep below moves it toneedsPerson. Check with your payment provider, then finish it withgraph.invoke(null, config)if no refund went out. - Resuming early is harmless: the node reads the request again and pauses once more if nobody has decided yet.
ttlSecondssets 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. Wait in the same process
For waits of minutes, the process that started the graph can wait for the answer and resume it. check with a wait holds the call open for up to 30 seconds and returns as soon as someone decides:
import { Command, isInterrupted } from "@langchain/langgraph";
import { approvals } from "./approvals";
import { graph } from "./graph";
const config = { configurable: { thread_id: "refund-1182" } };
let state = await graph.invoke({ orderId: "1182", amountEur: "49.00" }, config);
while (isInterrupted(state)) {
await approvals.check(state.approvalId, 30); // returns once someone decides, or after 30 s
state = await graph.invoke(new Command({ resume: true }), config);
}
console.log(state.result);It prints Refunded €49.00 for order 1182. after an approval, Refunded €10.00 for order 1182. when the person lowers the amount to €10, and Not refunded: denied. after a denial.
4. Wake the graph when a person decides
For waits of hours, let the process go. 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 { Command } from "@langchain/langgraph";
import { verifyWebhook, WebhookVerificationError } from "@variantgate/agent/webhook";
import { approvals } from "./approvals";
import { graph, waiting } from "./graph";
const DECIDED = new Set(["request.approved", "request.denied", "request.expired"]);
const resuming = new Set<string>(); // threads this process is resuming now
/** Wake a graph paused at its interrupt. A graph still running reads the answer itself. */
export async function resume(thread: string) {
if (resuming.has(thread)) {
return; // two resumes at once would both refund
}
resuming.add(thread);
try {
const config = { configurable: { thread_id: thread } };
const snapshot = await graph.getState(config);
if (snapshot.tasks.some((task) => task.interrupts.length > 0)) {
await graph.invoke(new Command({ resume: true }), config);
}
} finally {
resuming.delete(thread);
}
}
/** POST /variantgate, as a route handler (Next.js, Hono, Bun and others). */
export async function POST(request: Request) {
const secret = process.env.VARIANTGATE_WEBHOOK_SECRET ?? "";
let event;
try {
event = await verifyWebhook(secret, request.headers, await request.text());
} catch (error) {
if (error instanceof WebhookVerificationError) {
return new Response(null, { status: 400 });
}
throw error;
}
const thread = "request_id" in event.data ? waiting.get(event.data.request_id) : undefined;
if (DECIDED.has(event.type) && thread) {
await resume(thread); // only a wake-up: the graph reads the answer itself
}
return new Response(null, { status: 204 });
}Without the resuming set, two copies of the same webhook arriving together both see the interrupt and both resume; we tried it, and the order was 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:
const STUCK_AFTER_MS = 10 * 60 * 1000; // far longer than a refund takes
export const needsPerson = new Set<string>(); // a table in production
/** Run every few minutes. Wakes what a webhook missed, flags what a crash stopped. */
export async function sweep() {
for (const [requestId, thread] of [...waiting]) {
if ((await approvals.check(requestId)).status === "pending") {
continue;
}
await resume(thread);
const snapshot = await graph.getState({ configurable: { thread_id: thread } });
const age = Date.now() - Date.parse(snapshot.createdAt ?? "");
if (snapshot.next.includes("refund") && age > STUCK_AFTER_MS) {
// A crash stopped the refund. The money may have moved: a person checks.
waiting.delete(requestId);
needsPerson.add(thread);
}
}
}Before it runs for real
- Use a durable checkpointer, such as
@langchain/langgraph-checkpoint-postgres, so a waiting graph survives a restart and another process can resume it:import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres"; const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL ?? ""); await checkpointer.setup(); // creates its tables once // .compile({ checkpointer }) in place of new MemorySaver() - Keep
waitingin a table next to it. The thread id is all the webhook needs to find the right graph. - The
resumingset only guards one process. With several, resume each thread from one worker at a time, for example with a queue keyed by thread id. Passing the request id to your payment provider as an idempotency key, which Stripe accepts, stops a second refund even then. - Write a rule such as “always allow
payment.refundup to €20”. Small refunds are then approved at once, and only the larger ones wait for a person. - 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. Every client method is on the TypeScript client page.