Skip to main content

Idempotent LLM function calling: each tool call at most once

9 min read
LLM
AI Engineering
Idempotency
PostgreSQL
Reliability
Backend
SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus

Short answer. Give every tool call the model plans a row of its own, keyed by its position in the plan, and run the tool inside the same database transaction that marks that row done. A process that crashes mid-run then resumes from the rows instead of re-asking the model, and a tool that already committed is reused rather than re-run. The one tool whose effect lives outside the database (sending a message) can't join that transaction, so the loop records that it started and never retries it on its own.

The rest of this post is how I got there in KhataGO, a WhatsApp bookkeeping app where the "tool" is a ledger write and a duplicate means a shopkeeper's books are wrong.

What broke

A user sends "sold 500 to Ram, cash". The message goes to Gemini with ten function-calling tools. The model asks for create_transaction, the tool writes a row, the result goes back, the model replies. Up to five such turns per message.

Inbound messages are already exactly-once at the message level: one row per message with a unique waMessageId (the webhook post covers that layer). A worker claims a message with a conditional UPDATE, and a claim older than ten minutes (AI_CLAIM_STALE_MS, lib/whatsappClaim.ts) can be taken over by another worker.

The loop that ran inside that claim was a while in agent.ts. Five turns of model decisions and ledger writes, all in a stack frame. If the process died between turn one and turn two, the stack frame was gone but the create_transaction from turn one had already committed. Ten minutes later the claim went stale, another worker picked the message up and ran the whole thing again from turn zero. Same message, same model, usually the same plan: a second sale to Ram.

The comment I left on the schema (prisma/schema.prisma, above model AgentRun) says it in one line:

/// The dedup on `waMessageId` makes the message exactly-once; nothing made
/// the tools inside it exactly-once.

Two true statements, one bad sum

"A stale claim is re-run" and "a tool call writes the ledger" were both true, and together they said the ledger could be written twice. The fix landed on 2026-09-05 as one pull request (85323bd). The migration adds two tables and drops nothing.

Why not re-ask the model on resume?

My first instinct was to persist only tool results and let a resumed run ask the model again. That doesn't work, because a model isn't deterministic. Ask it again for a turn whose tools half-ran and it might order the calls differently, and a stored result keyed by position would go to the wrong call. So the unit of durability is the model's decision for a turn. Two tables:

  • AgentRun, one row per message: the state, how many turns have been planned, the final reply.
  • AgentStep, one row per planned tool call: tool name, args, a hash of the args, the result, and a status.

The step's unique key is the idempotency key:

model AgentStep {
  runId    String
  turn     Int
  seq      Int      /// Position within the turn's plan.
  tool     String
  argsHash String
  args     Json
  result   Json?
  status   String   @default("PLANNED")  /// PLANNED → (STARTED) → DONE
  @@unique([runId, turn, seq])
}

I keyed on position, not on tool name, on purpose. "Sold 500 to Ram and bought 200 from Shyam" is one turn with two create_transaction calls, and a name-keyed row would collapse them into one. The name and the args hash are stored so a resume can check it's replaying the call it thinks it is (lib/ai/loop.test.ts, "position, not name, is identity").

Persisting the plan is one write: planTurn inserts the steps, bumps the turn counter and moves PLANNING → TOOL_CALL in a single transaction. A crash will eventually land in any gap you leave between those.

Where does the at-most-once guarantee actually live?

In one method. The tool runs with the transaction client, and the step's move to DONE is a conditional update in the same transaction. This is PrismaRunStore.completeStep in lib/ai/runStore.ts, trimmed:

async completeStep<T>(step: StepRecord, work: (db: ToolDb) => Promise<T>) {
  if (step.status === "DONE") {
    return { result: step.result as T, executed: false };
  }
  try {
    return await this.prisma.$transaction(async tx => {
      const result = await work(tx);
      const r = await tx.agentStep.updateMany({
        where: { id: step.id, status: { in: ["PLANNED", "STARTED"] } },
        data: { status: "DONE", result: toJson(result), finishedAt: new Date() },
      });
      if (r.count === 0) throw new StepAlreadyCompleted();
      return { result, executed: true };
    });
  } catch (error) {
    if (error instanceof StepAlreadyCompleted) {
      const fresh = await this.prisma.agentStep.findUniqueOrThrow({ where: { id: step.id } });
      return { result: fresh.result as T, executed: false };
    }
    throw error;
  }
}

Read the race through it. Two processes hold the same PLANNED step. Both run the tool, both write a ledger row inside their own transaction. The first one's updateMany matches one row and commits. The second one's matches zero rows, throws, and Prisma rolls back its transaction, taking its ledger row with it. Then it reads the winner's stored result and hands that back, so the model sees one answer whichever process is talking to it.

That turns "a write tool is never re-executed" from a property of control flow, which a crash can interrupt anywhere, into a property of the database, which it can't. The ten-minute staleness window stopped being load-bearing for correctness; it only governs cost now.

The integration test drives this against a real Postgres (tests/integration/agent-run.integration.test.ts): 8 concurrent executors of one planned create_transaction step, with the real tool on the transaction client. All 8 run the tool (there's no lock in front of the transaction), one executed: true comes back, exactly one transaction row exists, and all 8 callers get the same transactionId.

What does a resume do?

It reads the rows, not the state label. resumeEntryState in lib/ai/runState.ts is the whole decision:

export function resumeEntryState(state, facts) {
  if (TERMINAL_STATES.has(state)) return null;
  if (facts.hasReply) return "REPLY";
  if (facts.hasUnfinishedSteps) return "TOOL_CALL";
  return "PLANNING";
}

A stored reply means the model finished; send it, no model call. Unfinished steps mean execute (or reuse) them, then ask the model. Otherwise ask the model. The conversation is rebuilt from the persisted turns' functionCall and functionResponse parts, so the model only sees results it hasn't seen yet, and the five-turn cap counts persisted turns, so a resume at turn three gets two more, not five (lib/ai/loop.cap.test.ts).

Each crash scenario in lib/ai/loop.resume.test.ts runs twice: a hard crash, where the store is restored to the instant of death so nothing written on the way down survives, and a soft one, where the catch block managed to persist FAILED. Both must resume identically. The case I care most about is "crash BEFORE the result is persisted (inside the tool) → resume writes exactly once": the tool throws mid-write on attempt one, attempt two completes, and the execution log reads ["create_transaction", "create_transaction"] while the ledger holds one row. Executed twice, wrote once. That's the honest shape of at-most-once over a crash.

What about a tool that doesn't write to the database?

send_payment_reminder sends a WhatsApp message. A network call can't join a Postgres transaction, so none of the above applies to it. Every tool is classed in lib/ai/toolEffects.ts:

export const TOOL_EFFECTS = {
  create_transaction: "write",
  send_payment_reminder: "external",
  get_recent_transactions: "read",
  // ... the other seven
} as const satisfies Record<string, ToolEffect>;

For an external tool, executeStep in lib/ai/steps.ts flips the step PLANNED → STARTED before the send. A resume that finds a STARTED external step does not re-send, because it can't know whether the first attempt left the building. It records this as the step's result and the model relays it:

This action was interrupted before its outcome was recorded. It was not retried automatically — please check before asking again.

(INTERRUPTED_EXTERNAL_RESULT, lib/ai/loop.ts.) Not re-sending costs one reminder the user can repeat. Re-sending could message a customer twice. I'd rather eat the first.

A test walks every declared tool and fails if one is missing from the table, because a new write tool that defaulted to "read" would be re-executed on every resume.

Wouldn't a framework's checkpointing do this?

I built the same state machine in LangGraph.js behind a flag (lib/ai/graph.langgraph.ts) to find out, and it passes the same crash-and-resume tests. But a checkpoint saves graph state; it can't join the transaction in which create_transaction writes the ledger. In both engines the at-most-once property comes from completeStep and nothing else, so the hand-rolled loop stayed the default.

What I'd tell you to do

  1. Persist the plan, not just the results. Key each call by (run, turn, position).
  2. Tool write and step DONE in one transaction, with a conditional update. Zero rows matched means someone else won; roll back and return their result.
  3. Classify every tool as read, write or external, and make the table a test.
  4. Record STARTED before an external call and never auto-retry a STARTED step. Tell the model what happened in plain words.
  5. Resume from rows, not a state label, and count the turn cap against persisted turns.
  6. Never prune a non-terminal run. My retention cron deletes DONE runs after 90 days and leaves FAILED and DEAD_LETTERED alone; their steps are what makes a later resume exactly-once.

What I'd do differently

Log less, sooner. The agent's trace store held sizes and counts only from the start, no message bodies and no tool arguments, while ten lines above the loop every tool still began with console.log("Executing create_transaction", args) (FINDINGS.md §9). The property I'd designed into the trace store was missing from the log I'd inherited. If you build a loop like this, list every sink a tool argument can reach before you say it never leaves.

SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus