# How to test a LangGraph agent for double charges after resume or a restart

By Agent Signal · Published 2026-11-28 · Updated 2026-11-28

> **Short answer:** Your normal tests run a graph start to finish in one process, so they never see a side effect run twice. To test for it, pause the graph at interrupt() with a persistent checkpointer such as SqliteSaver, end that process, resume the same thread_id with Command(resume=...) in a new process, and count the side effects in your own store. One approval must mean one charge. Add a second case that kills the process right after the charge, before LangGraph saves the node, because moving the charge below interrupt() does not cover that case; only an idempotency key does. The free agentsignal-check CLI runs these crash cases on your graph and prints PASS or FAIL.


You already know the bug: a LangGraph node with `interrupt()` runs again on resume, and a charge or an email above the interrupt goes out twice. If not, start with [why a LangGraph interrupt resumes twice](/guides/langgraph-interrupt-resume-twice/). This guide is about the next question: **how do you prove your graph doesn't do it, and keep it that way?** You get a pytest test that restarts the process between pause and approval, a second test that crashes right after the charge, and the free crash test that runs these cases for you. Everything below ran on **langgraph 1.2.24, langgraph-checkpoint 4.3.2, langgraph-checkpoint-sqlite 3.1.3, pytest 9.2.0, Python 3.13.5, Nov 28, 2026**.

## Why your current tests pass anyway

A normal test calls `graph.invoke(...)`, answers the interrupt in the same process and checks the final state. Three things hide the double charge:

1. **The state looks right.** The checkpointer saves graph state, not what your code did to the outside world. A second charge leaves no trace in the state.
2. **The node re-run is by design.** The LangGraph docs say that on resume "the runtime restarts the entire node from the beginning", so "any code that ran before the `interrupt` will execute again" ([LangGraph interrupts](https://docs.langchain.com/oss/python/langgraph/interrupts)). A test that only checks the output can't tell one run from two.
3. **`InMemorySaver` hides restarts.** The docs note that `InMemorySaver` keeps checkpoints in RAM, so "when the process restarts, all checkpoints are lost" ([LangGraph persistence](https://docs.langchain.com/oss/python/langgraph/persistence)). A real restart test needs a persistent checkpointer, such as `SqliteSaver`, and a second process.

So the test has to do what production does: pause, end the process, resume in a new one with the same `thread_id`, and then **count the side effects where they land**, not in the graph state.

## The graph under test

`payments.py` stands in for a payment API. It writes each charge to a SQLite table and, when it gets a key it has seen, returns the first charge instead of making a new one. That is how a provider idempotency key behaves. `CRASH_AFTER_CHARGE=1` kills the process right after a charge, before LangGraph can save the node.

```python
import os, sqlite3
DB = os.environ.get("PAYMENTS_DB", "payments.db")

def _db():
    c = sqlite3.connect(DB)
    c.execute("CREATE TABLE IF NOT EXISTS charges (id INTEGER PRIMARY KEY, amount INTEGER, key TEXT UNIQUE)")
    return c

def charge(amount, key=None):
    """Stands in for a payment API. With a key, a repeat call returns the first charge."""
    c = _db()
    if key:
        row = c.execute("SELECT id FROM charges WHERE key=?", (key,)).fetchone()
        if row:
            return f"ch_{row[0]}"
    cur = c.execute("INSERT INTO charges (amount, key) VALUES (?, ?)", (amount, key))
    c.commit()
    if os.environ.get("CRASH_AFTER_CHARGE") == "1":
        os._exit(1)  # the process dies after the charge, before LangGraph saves the node
    return f"ch_{cur.lastrowid}"

def count():
    return _db().execute("SELECT COUNT(*) FROM charges").fetchone()[0]
```

`app.py` has the buggy graph (charge above `interrupt()`) and the fixed one: approval in its own node, then a charge node that sends a key built from the `thread_id` plus the tool call id. The tool call id is in the state here to keep the example small. In a real agent, take it from the saved AI message, so every resume sees the same id.

```python
from typing import TypedDict
from langgraph.graph import START, END, StateGraph
from langgraph.types import interrupt
from langgraph.config import get_config
import payments

class State(TypedDict, total=False):
    amount: int
    tool_call_id: str
    approved: bool
    charge_id: str

def charge(amount, key=None):          # the side effect the test watches
    return payments.charge(amount, key)

# BUG: charge above interrupt(), so it runs again when the node restarts on resume
def approve_and_charge(state: State):
    charge_id = charge(state["amount"])
    approved = interrupt({"question": f"Charge ${state['amount']}?"})
    return {"approved": approved, "charge_id": charge_id}

def build_buggy(checkpointer):
    b = StateGraph(State)
    b.add_node("approve_and_charge", approve_and_charge)
    b.add_edge(START, "approve_and_charge"); b.add_edge("approve_and_charge", END)
    return b.compile(checkpointer=checkpointer)

# FIX: approval in its own node; the charge comes after it and carries a key
def approval(state: State):
    return {"approved": interrupt({"question": f"Charge ${state['amount']}?"})}

def do_charge(state: State):
    if not state.get("approved"):
        return {}
    thread_id = get_config()["configurable"]["thread_id"]
    key = f"{thread_id}:{state.get('tool_call_id', 'charge')}"
    return {"charge_id": charge(state["amount"], key=key)}

def build_fixed(checkpointer):
    b = StateGraph(State)
    b.add_node("approval", approval); b.add_node("do_charge", do_charge)
    b.add_edge(START, "approval"); b.add_edge("approval", "do_charge"); b.add_edge("do_charge", END)
    return b.compile(checkpointer=checkpointer)
```

`step.py` runs one step per process, so the pause and the approval happen in different processes, like a deploy or a crash in between.

```python
# One process = one step. Run "start" and "resume" as separate processes, like a deploy in between.
import sys, sqlite3, app
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command
which, step, thread = sys.argv[1], sys.argv[2], sys.argv[3]
saver = SqliteSaver(sqlite3.connect("checkpoints.db", check_same_thread=False))
graph = {"buggy": app.build_buggy, "fixed": app.build_fixed}[which](saver)
config = {"configurable": {"thread_id": thread}}
if step == "start":
    out = graph.invoke({"amount": 500, "tool_call_id": "call_1"}, config)
    print("paused:", bool(out.get("__interrupt__")))
else:
    out = graph.invoke(Command(resume=True), config)
    print("done:", out.get("charge_id"))
```

## Test 1: restart between pause and approval

`test_restart.py` copies the files into a temporary folder, runs the start and the resume as two separate processes, and counts rows in the charges table. One approval must mean one charge.

```python
# pytest: approve once across a real process restart, then count charges.
import os, subprocess, sys, pytest
import payments

def run(which, step, thread, env=None, cwd=None):
    e = {**os.environ, **(env or {})}
    return subprocess.run([sys.executable, "step.py", which, step, thread], env=e, cwd=cwd, capture_output=True, text=True)

@pytest.fixture(autouse=True)
def fresh(tmp_path, monkeypatch):
    for f in ("app.py", "payments.py", "step.py"):
        (tmp_path / f).write_text(open(f).read())
    monkeypatch.chdir(tmp_path)
    monkeypatch.setenv("PAYMENTS_DB", str(tmp_path / "payments.db"))
    yield

@pytest.mark.parametrize("which", ["buggy", "fixed"])
def test_restart_between_pause_and_approval(which):
    assert run(which, "start", "order-42").returncode == 0      # process 1 pauses, then exits
    assert run(which, "resume", "order-42").returncode == 0     # process 2 approves once
    assert payments.count() == 1, f"{which}: {payments.count()} charges for one approval"

@pytest.mark.parametrize("which", ["fixed"])
def test_crash_after_charge_before_checkpoint(which):
    assert run(which, "start", "order-43").returncode == 0
    crashed = run(which, "resume", "order-43", {"CRASH_AFTER_CHARGE": "1"})
    assert crashed.returncode != 0                               # died right after charging
    assert run(which, "resume", "order-43").returncode == 0      # a new worker resumes
    assert payments.count() == 1, f"{which}: {payments.count()} charges after a crash"
```

Run it with `python -m pytest -q test_restart.py`. Our result:

```text
E       AssertionError: buggy: 2 charges for one approval
FAILED test_restart.py::test_restart_between_pause_and_approval[buggy] - Asse...
1 failed, 2 passed in 4.35s
```

The buggy graph charged twice for one approval: once on the first run, and again when the node restarted on resume. The fixed graph charged once in both tests. (The crash test in the same file is the next section.)

## Test 2: crash right after the charge

Test 1 passes for any graph that moves the charge below `interrupt()`. It doesn't cover the worst case: the process dies after the charge goes out but before LangGraph saves the charge node. On the next resume, LangGraph runs that node again, because as far as it knows, the node never finished. `test_crash_after_charge_before_checkpoint` does exactly that, then resumes in a fresh worker.

With the key, the fixed graph passed: one charge. As a control, we ran the same test on the fixed graph with the key removed (`charge(state["amount"])` instead of `charge(state["amount"], key=key)`):

```text
E       AssertionError: no key: 2 charges after a crash
```

So the node split fixes the ordinary resume, but only the idempotency key fixes the crash. The LangGraph docs say the same: "If a node fails after committing a side effect but before completing, retrying the node can repeat the effect. Use idempotent operations or deduplicate writes in the external system" ([LangGraph interrupts](https://docs.langchain.com/oss/python/langgraph/interrupts)). If your provider has no idempotency keys, keep your own table with a UNIQUE key, as in `payments.py`.

## Let the crash test run the cases for you

Writing a kill point for every side effect gets tedious. Our free crash test, [agentsignal-check](/crash-test/?k=seo-test-langgraph-resume-duplicate-side-effects), does it for you. It's free, needs no signup and runs on your laptop. It stops your graph mid-approval, starts it again, counts the calls to the side effect you name and prints PASS or FAIL. Point `--graph` at a factory that takes a checkpointer and `--effect` at the function that charges or sends:

```bash
pip install "agentsignal-check[langgraph] @ git+https://github.com/agentsignal/agentsignal-check@v0.4.0"
agentsignal check --graph app:build_buggy --effect app:charge --input '{"amount": 500, "tool_call_id": "call_1"}' --resume true
```

On the buggy graph from this guide, it printed:

```text
agentsignal check: app:build_buggy
Approval flow: 1/5 crash tests survived
Double-charge risk: HIGH  Lost-approval risk: LOW
LangGraph 1.2.24 · checkpoint 4.3.2 · Python 3.13.5 · agentsignal-check 0.4.0 · 2026-11-28T15:40:24Z
[FAIL] baseline: 2 effect call(s) in a clean run; duplicates {'app:charge(500,)[]': 2}
    fix: https://tryagentsignal.com/guides/langgraph-interrupt-resume-twice/
[FAIL] double_execution.kill_resume: crash after effect #1 -> re-executed {'app:charge(500,)[]': 3}; crash after effect #2 -> re-executed {'app:charge(500,)[]': 3}
    fix: https://tryagentsignal.com/guides/langgraph-interrupt-resume-twice/
[FAIL] double_execution.kill_before_checkpoint: crash before checkpoint #2 -> re-executed {'app:charge(500,)[]': 3}; crash before checkpoint #3 -> re-executed {'app:charge(500,)[]': 2}
    fix: https://tryagentsignal.com/guides/langgraph-interrupt-resume-twice/
[PASS] approval.lost_on_restart: pending interrupt visible from a fresh process
[FAIL] approval.replay: same approval delivered twice -> duplicates {'app:charge(500,)[]': 3}
    fix: https://tryagentsignal.com/templates/langgraph-approval-ui/
```

On the fixed graph:

```text
agentsignal check: app:build_fixed
Approval flow: 5/5 crash tests survived
Double-charge risk: LOW  Lost-approval risk: LOW
LangGraph 1.2.24 · checkpoint 4.3.2 · Python 3.13.5 · agentsignal-check 0.4.0 · 2026-11-28T15:40:31Z
[PASS] baseline: 1 effect call(s) in a clean run
[PASS] double_execution.kill_resume: no duplicates across 1 crash point(s)
[PASS] double_execution.kill_before_checkpoint: no duplicates across 4 checkpoint write(s)
[PASS] approval.lost_on_restart: pending interrupt visible from a fresh process
[PASS] approval.replay: second resume caused no duplicate effects
```

The buggy run exits with code 1 and the fixed run with 0, so you can use it as a CI step. The [crash test page](/crash-test/?k=seo-test-langgraph-resume-duplicate-side-effects) has the GitHub Action that runs it on every pull request.

## Which guide covers your case

These tests catch the double charge. These guides explain each cause and its fix:

- Code above `interrupt()` runs again on resume: [LangGraph interrupt resumes twice](/guides/langgraph-interrupt-resume-twice/).
- Several interrupts in one node replay earlier answers: [LangGraph multiple interrupts](/guides/langgraph-multiple-interrupts-resume/).
- A subgraph, or code before a subgraph call, runs again: [LangGraph subgraph interrupt resume reruns](/guides/langgraph-subgraph-interrupt-resume-reruns/).
- A failing node retries and repeats the call: [LangGraph tool retry runs twice](/guides/langgraph-tool-retry-runs-twice/).
- A tool that runs for minutes gets started a second time: [LangGraph long-running tool runs twice](/guides/langgraph-long-running-tool-runs-twice/).
- OpenAI Agents SDK instead of LangGraph: [duplicate tool calls after resume](/guides/duplicate-tool-calls-after-resume/) and [approved tool runs again after a crash](/guides/openai-agents-approved-tool-runs-again-after-crash/).

A separate case, approving parallel tool calls one at a time with `HumanInTheLoopMiddleware` and `durability="exit"`, can ask for an already approved call again and run it twice: [LangGraph parallel tool approval asked again and runs twice](/guides/langgraph-parallel-tool-approval-runs-twice/?k=int-test-langgraph-resume-duplicate-side-effects).

## Checklist for your own graph

- Use the same persistent checkpointer type you run in production, or at least `SqliteSaver`, never `InMemorySaver`, for restart tests.
- Run the pause and the resume in separate processes, with the same `thread_id`.
- Count side effects in the system they land in (a table, a fake provider, a mock that records calls), not in the graph state.
- Add one crash case per side effect: kill the process right after it, then resume.
- Send every side effect an idempotency key that is the same on every resume, such as `thread_id` plus the saved tool call id.

[Run the free crash test on your graph](/crash-test/?k=seo-test-langgraph-resume-duplicate-side-effects)
