agent_signal

Guide

LangGraph long-running tool runs twice: why it repeats after a few minutes, and how to stop it

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

Short answer

A LangGraph tool that runs for minutes can run twice when the server decides the run looks stuck and starts it again from the last checkpoint while the first copy is still working. Issue #7417 reports this on LangGraph Cloud for tool calls over about 3 minutes; both copies finish, so the work, the cost and any charge happen twice. There is no fix released and the issue is open. Protect the tool itself: send an idempotency key built from thread_id plus the tool call id with every side effect, and claim the call in your own table before the long work starts, so a second copy waits for the first one's result instead of doing everything again.

Your tool takes a few minutes. Somewhere in the middle, a second copy of it starts, and both finish. The report gets built twice, the sub-agent burns tokens twice, and if the tool ends with a charge, the customer pays twice. This guide shows why that happens and gives you a fix you can paste in, so one tool call does its work once even if it gets started twice. Everything below was run on langgraph 1.2.18 and 1.2.16 with langchain 1.4.7 (Python 3.13.5), Oct 30, 2026.

Why the long tool runs twice

This was reported in issue #7417, "Long tool calls (~180s+) silently re-executed from checkpoint on LangGraph Cloud". It was opened on Apr 5, 2026 and is still open, with 88 comments from 40 different people as of Oct 30, 2026. The reporter describes it like this:

  1. A tool call starts and keeps running. In their case it was a deepagents task() call that runs a sub-agent for 3 to 10 minutes.
  2. At around 180 seconds, the server starts the same tool call again from the last checkpoint, while the first one is still running. The copy has the same arguments and a tools step with no model step before it, so no new model decision caused it.
  3. Both copies finish. That is 2 to 3 times the work and the cost, and any side effect inside the tool happens again.

The reporter tried BG_JOB_SHUTDOWN_GRACE_PERIOD_SECS=900 (still repeated at about 180s), BG_JOB_ISOLATED_LOOPS=true (no change) and wrapping the call in asyncio.to_thread() (the gap doubled to about 360s, but it still repeated). From reading the server code, they believe the run gets swept as stale, goes back to pending, and is picked up again.

What we checked ourselves: in langgraph-api 0.17.0, BG_JOB_HEARTBEAT = 120 is set in the code, not read from an environment variable, so you can't tune it. And the local dev server (langgraph dev, which uses langgraph-runtime-inmem 0.37.0) has a sweep that does nothing, so you will not see this on your laptop. That is why this kind of bug tends to show up only after you deploy.

Since no setting stops it, the fix lives in your tool: make a second start of the same tool call harmless. This is the same idea as LangGraph tool retry runs twice, where a failed node runs again on resume.

Reproduce it, then fix it

We can't run LangGraph Cloud's scheduler locally, so we do what a re-dispatch does. One process starts the run and enters a long tool call. Two seconds later, a second process runs the same thread again from its last checkpoint with graph.invoke(None, config). SqliteSaver holds the checkpoints, and a second SQLite file plays your database and a payment API, so both processes see the same data. No model and no network: the model node plays the LLM.

# long_tool.py  (pip install langgraph==1.2.18 langchain==1.4.7 langgraph-checkpoint-sqlite==3.1.2)
# python long_tool.py first|redispatch   with TOOL=naive|keyed|guarded
import os, sqlite3, sys, time
from langchain.tools import tool, ToolRuntime
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition

WORK_SECS, LEASE_SECS = 6, 3   # the "long" tool and how long a silent worker keeps its claim
app = sqlite3.connect("app.db", isolation_level=None, timeout=30, check_same_thread=False)  # your DB + a fake payment API
app.executescript("""
CREATE TABLE IF NOT EXISTS charges(id INTEGER PRIMARY KEY, amount INT, idem_key TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS work_log(pid INT);
CREATE TABLE IF NOT EXISTS ledger(key TEXT PRIMARY KEY, status TEXT, result TEXT, beat REAL);
""")

def charge(amount, idempotency_key=None):
    """Stands in for a payment API. With a key it returns the first charge instead of charging again."""
    if idempotency_key:
        row = app.execute("SELECT id FROM charges WHERE idem_key=?", (idempotency_key,)).fetchone()
        if row:
            return f"ch_{row[0]}"
    return f"ch_{app.execute('INSERT INTO charges(amount, idem_key) VALUES (?,?)', (amount, idempotency_key)).lastrowid}"

def long_work(beat=lambda: None):
    """Minutes of model calls or sub-agent work in real life. Here: 6 seconds."""
    app.execute("INSERT INTO work_log VALUES (?)", (os.getpid(),))
    for _ in range(WORK_SECS):
        time.sleep(1); beat()

def key_for(runtime):
    return f"{runtime.config['configurable']['thread_id']}:{runtime.tool_call_id}"

@tool
def bill_naive(amount: int, runtime: ToolRuntime) -> str:
    """Do the long job, then charge."""
    long_work(); return charge(amount)

@tool
def bill_keyed(amount: int, runtime: ToolRuntime) -> str:
    """Do the long job, then charge with an idempotency key."""
    long_work(); return charge(amount, idempotency_key=key_for(runtime))

def claim(key):
    """Return None if this worker owns the call, or the saved result if another worker finished it."""
    while True:
        now = time.time()
        if app.execute("INSERT OR IGNORE INTO ledger VALUES (?, 'running', NULL, ?)", (key, now)).rowcount:
            return None                                   # first worker: go
        status, result, beat = app.execute("SELECT status, result, beat FROM ledger WHERE key=?", (key,)).fetchone()
        if status == "done":
            return result                                 # someone already did it: reuse the result
        if now - beat > LEASE_SECS and app.execute(
                "UPDATE ledger SET beat=? WHERE key=? AND status='running' AND beat=?", (now, key, beat)).rowcount:
            return None                                   # the owner went silent: take over
        time.sleep(0.5)                                   # the owner is alive: wait for its result

@tool
def bill_guarded(amount: int, runtime: ToolRuntime) -> str:
    """Do the long job once per tool call, then charge with an idempotency key."""
    key = key_for(runtime)
    if (done := claim(key)) is not None:
        return done
    long_work(beat=lambda: app.execute("UPDATE ledger SET beat=? WHERE key=?", (time.time(), key)))
    result = charge(amount, idempotency_key=key)
    app.execute("UPDATE ledger SET status='done', result=? WHERE key=?", (result, key))
    return result

TOOL = {"naive": bill_naive, "keyed": bill_keyed, "guarded": bill_guarded}[os.environ.get("TOOL", "naive")]

def model(state):  # plays the LLM: one tool call, then a final answer
    if isinstance(state["messages"][-1], ToolMessage):
        return {"messages": [AIMessage(f"Done: {state['messages'][-1].content}")]}
    return {"messages": [AIMessage("", tool_calls=[{"name": TOOL.name, "args": {"amount": 79}, "id": "call_1"}])]}

g = StateGraph(MessagesState)
g.add_node("model", model)
g.add_node("tools", ToolNode([TOOL]))
g.add_edge(START, "model")
g.add_conditional_edges("model", tools_condition)
g.add_edge("tools", "model")

with SqliteSaver.from_conn_string("checkpoints.db") as saver:
    graph, config = g.compile(checkpointer=saver), {"configurable": {"thread_id": "order-42"}}
    if sys.argv[1] == "first":       # the run that starts the long tool call
        out = graph.invoke({"messages": [HumanMessage("bill order 42")]}, config)
    else:                            # what a re-dispatch does: run the thread again from its last checkpoint
        print("redispatch starts at:", graph.get_state(config).next)
        out = graph.invoke(None, config)
    print(f"{sys.argv[1]:<10} -> {out['messages'][-1].content}")
#!/usr/bin/env bash
# Starts the long tool call, then 2 seconds later re-dispatches the same thread from its checkpoint,
# the way a worker that looks stale gets re-run. KILL=1 kills the first worker mid-job instead.
for t in naive keyed guarded; do
  rm -f app.db checkpoints.db*; echo "== $t"
  TOOL=$t python long_tool.py first & first=$!
  sleep 2
  [ "$KILL" = 1 ] && kill -9 $first && echo "first worker killed"
  TOOL=$t python long_tool.py redispatch
  wait $first 2>/dev/null
  python -c "import sqlite3; d=sqlite3.connect('app.db'); q=lambda t: d.execute(f'SELECT count(*) FROM {t}').fetchone()[0]; print(f'charges: {q(\"charges\")}, times the long job ran: {q(\"work_log\")}')"
done

Actual output on 1.2.18:

== naive
first      -> Done: ch_1
redispatch starts at: ('tools',)
redispatch -> Done: ch_2
charges: 2, times the long job ran: 2
== keyed
first      -> Done: ch_1
redispatch starts at: ('tools',)
redispatch -> Done: ch_1
charges: 1, times the long job ran: 2
== guarded
first      -> Done: ch_1
redispatch starts at: ('tools',)
redispatch -> Done: ch_1
charges: 1, times the long job ran: 1

The naive tool did the long job twice and charged twice. The keyed tool also did the long job twice, but the payment API saw the same key and returned the first charge, ch_1. The guarded tool did the job once: the second copy found the claim, waited, and returned the first copy's result, so both runs ended with ch_1.

We ran each case 20 times on each version, every time with fresh processes and fresh databases. "Killed" means the first worker got kill -9 two seconds into the job, before it charged (KILL=1 ./run.sh):

Tool Second run starts while the first is still working First worker killed mid-job
bill_naive 2 charges, job ran twice, in 20 of 20 runs 1 charge, job started twice, 20 of 20
bill_keyed 1 charge, job ran twice, 20 of 20 1 charge, job started twice, 20 of 20
bill_guarded 1 charge, job ran once, 20 of 20 1 charge, job started twice, 20 of 20

langgraph 1.2.18 and 1.2.16 gave identical results. In the killed case every tool has to start the job again, because the first copy never finished. The guarded tool waits until the dead worker's 3 second lease runs out, then takes over, so a crash doesn't leave the call stuck.

The key was order-42:call_1 in both processes. The second run started at the tools step, so it read the same saved AI message and got the same tool call id.

The fix in 3 steps

  1. Send an idempotency key with every side effect. Build it from thread_id plus the tool call id. ToolRuntime gives a tool both (runtime.config and runtime.tool_call_id). Pass it to a provider that rejects repeats, such as Stripe's Idempotency-Key. Stripe keys can be up to 255 characters. On Stripe's v1 API a key may be removed once it is 24 hours old, and the same key then makes a new request (Stripe idempotent requests). This stops the double charge, but not the double work.
  2. Claim the tool call before the long work starts. Insert the key into a table with a UNIQUE constraint and refresh a heartbeat while you work. A second copy that finds a live claim waits for the result instead of starting over. It only takes over when the heartbeat stops, which means the first worker really died. That saves the repeated work and cost, which is what the people in #7417 are paying for. Our free side-effect ledger is that table with a lease, tested on Postgres.
  3. Don't keep a tool call open for minutes. If a job takes minutes, start it in the background and return a job id, then check on it. For deepagents, the docs offer async subagents, which "launch background tasks that return immediately" and are meant for tasks that are "long-running". We did not test async subagents. Keep steps 1 and 2 either way, because a background job can be started twice too.

FAQ

Does upgrading LangGraph fix it? Not as of Oct 30, 2026. Issue #7417 is open and has no maintainer reply. We could not test LangGraph Cloud, and the local dev server never re-dispatches, so check your own traces for a tools step with no model step before it.

Can I raise the heartbeat or a timeout? Not the heartbeat: it is fixed at 120 seconds in langgraph-api 0.17.0. The reporter's grace period and isolated loop settings didn't stop it, and asyncio.to_thread() only pushed it later.

Is the tool call id the same in the second copy? In our test, yes: order-42:call_1 in both. The issue describes the copy starting at the tools step with the same arguments, which means it reads the same saved AI message. If your traces show the model running again before the copy, the ids can change. Then build the key from something your app sets, such as the order id.

Why not just use the idempotency key? It stops the second charge. It does not stop the second run of the job itself, so you still pay for the model calls, sub-agents or API calls twice. The claim in step 2 stops both.

What if the first worker really crashed? Then its heartbeat stops. In our test with the first worker killed mid-job (KILL=1 ./run.sh), the guarded tool waited until the 3 second lease ran out, took over, and charged once. Use a lease longer than the longest gap between heartbeats in your tool.

What we did not test

No LangGraph Cloud, real model, payment API or production database. We started the second run by hand with graph.invoke(None, config) on one machine, with SQLite. We did not test the async API, Postgres, deepagents, async subagents or LangGraph.js.

Get the template

Check your own agent in 2 minutes

Want to see a repeated side effect happen, then stop? Run the free 2-minute crash test. It kills a LangGraph agent right after an approved charge, resumes it, and counts how many times the charge runs. It doesn't recreate a Cloud re-dispatch, but the fix it checks is the same: one key per tool call.

Free starter pack

The approval-flow starter pack

Tested human-in-the-loop approval starters for LangGraph, OpenAI Agents SDK, Vercel AI SDK and Google ADK, plus the Agent Signal newsletter. Free.

Get the Agent Signal newsletter