agent_signal
← All templates

Free template · Postgres + Python

Side-effect ledger

This is the pattern most teams hand-roll after their first double charge: a table of committed side effects, checked before the tool runs again. Here it is, tested, free to copy.

Tested on PostgreSQL 17 · psycopg 3 · MIT · no signup · last tested 2026-10-18

Checkpoints save state, not side effects

A checkpointer saves your agent’s state between steps. It does not record that a charge, an email or a delete already happened. When a LangGraph run resumes after interrupt(), the paused node runs again from the top. When any run is resumed twice or retried after a crash, the tool runs again. Either way, so does the side effect inside it. The ledger records each committed effect under a key derived from stable run data, so the second call returns the stored result instead of running the effect again. It runs once per key; if a worker crashes mid-call, the effect can run again after the lease expires, so also pass the same key to the provider (e.g. Stripe Idempotency-Key).

The table

schema.sql
-- side-effect ledger (tested on PostgreSQL 17). MIT. https://tryagentsignal.com/templates/side-effect-ledger/
-- Safe to re-run. One row per (effect, idempotency_key). Reserve, then commit:
--   pending   = reserved, the effect may be running. now() < lease_until -> EffectInFlight;
--               lease expired -> treated as a crashed call, reclaimed, the effect runs again with the same key
--   committed = the effect ran; result holds its return value (returned, the effect is not called again)
--   failed    = the effect raised (error holds it); the next call with the same key and args runs it again
-- args_hash = sha256 of the canonical JSON of the call's args; same key + different args -> IdempotencyKeyMismatch
create table if not exists side_effects (
  run_id          text not null,
  effect          text not null,
  idempotency_key text not null,
  args_hash       text not null,
  status          text not null check (status in ('pending','committed','failed')),
  result          jsonb,
  error           text,
  created_at      timestamptz not null default now(),
  lease_until     timestamptz,
  committed_at    timestamptz,
  primary key (effect, idempotency_key)
);
create index if not exists side_effects_pending_lease_idx on side_effects (lease_until) where status = 'pending';
  1. 1.Reserve. insert ... on conflict do nothing returning status claims the key with status pending before the effect runs.
  2. 2.Already committed. The stored result is returned and the effect is not called.
  3. 3.Still pending. The effect started but has not committed: another worker is mid-call, or one crashed. Inside the lease (default 5 minutes) the decorator raises EffectInFlight and the caller retries later.
  4. 4.Lease expired or failed. A pending row older than the lease, or a row marked failed because the effect raised, is reclaimed and the next call with the same key runs the effect again.

The decorator

ledger.py
"""Side-effect ledger: run a side effect once per key, with a lease for crashed calls (psycopg 3, sync + async).
MIT. Needs the side_effects table from schema.sql. https://tryagentsignal.com/templates/side-effect-ledger/

    @side_effect_ledger(conn=lambda: psycopg.connect(DSN), key=lambda amount, order_id, **_: f"{order_id}:charge")
    def charge(amount, order_id, idempotency_key):      # idempotency_key is filled in for you
        return stripe.PaymentIntent.create(amount=amount, currency="usd", idempotency_key=idempotency_key).id

The key MUST come from stable run data (order_id, thread_id, tool_call_id): a resumed or retried run has
to compute the same key. str(uuid4()) is wrong: every retry gets a new key, so nothing is deduped.
Runs once per key; if a worker crashes mid-call, the effect can run again after the lease expires, so also
pass the same key to the provider (e.g. Stripe Idempotency-Key).
  committed            -> stored result returned, the effect is not called
  pending, in lease    -> EffectInFlight (another worker is mid-call, or one crashed: retry later)
  pending, lease over  -> treated as a crashed call: reclaimed atomically, the effect runs again, same key
  failed (it raised)   -> the effect runs again, same key
  same key, other args -> IdempotencyKeyMismatch, the effect is not called
A crash, kill or cancellation leaves the row pending. Results are stored as JSON (non-JSON via str()).
"""
import asyncio, functools, hashlib, inspect, json, logging, os
import psycopg
from psycopg.types.json import Jsonb

log = logging.getLogger("side_effect_ledger")
class EffectInFlight(RuntimeError): """Same effect + key is pending inside its lease. Retry later."""
class MissingIdempotencyKey(ValueError): """No key, or an empty one. Keys must come from stable run data."""
class IdempotencyKeyMismatch(ValueError): """The key was already used with different arguments."""

RESERVE = ("insert into side_effects (run_id, effect, idempotency_key, args_hash, status, lease_until) "
           "values (%s, %s, %s, %s, 'pending', now() + make_interval(secs => %s)) on conflict do nothing returning status")
READ = ("select status, result, args_hash, lease_until > now() from side_effects "
        "where effect = %s and idempotency_key = %s")
RECLAIM = ("update side_effects set status = 'pending', run_id = %s, error = null, "
           "lease_until = now() + make_interval(secs => %s) where effect = %s and idempotency_key = %s "
           "and (status = 'failed' or (status = 'pending' and lease_until < now())) returning status")
COMMIT = ("update side_effects set status = 'committed', result = %s, committed_at = now(), lease_until = null "
          "where effect = %s and idempotency_key = %s")
FAIL = ("update side_effects set status = 'failed', error = %s, lease_until = null "
        "where effect = %s and idempotency_key = %s")

def _plain(o):  # args that aren't JSON: dates/decimals/uuids by value, other objects by type only (reprs hold addresses)
    return str(o) if type(o).__module__ in ("datetime", "decimal", "uuid") else f"<{type(o).__qualname__}>"

def _decide(effect, key, args_hash, row):
    """None -> reserve again; ('hit', result); ('reclaim', status) -> try to take the row over."""
    if row is None: return None
    status, result, stored_hash, in_lease = row
    if stored_hash != args_hash:
        raise IdempotencyKeyMismatch(f"{effect}: key {key!r} was already used with different arguments")
    if status == "committed": return ("hit", result)
    if status == "pending" and in_lease: raise EffectInFlight(f"{effect}: key {key!r} is pending (lease not expired)")
    return ("reclaim", status)

def side_effect_ledger(*, conn, key, lease_seconds=300, effect=None, run_id=None):
    """conn: callable returning a psycopg connection (sync or async), a pool's .connection, or an autocommit connection."""
    if not callable(key): raise MissingIdempotencyKey("side_effect_ledger needs key=callable(*args, **kwargs) -> str")
    if conn is None: raise TypeError("side_effect_ledger needs conn=")
    def deco(fn):
        name, sig = effect or f"{fn.__module__}.{fn.__qualname__}", inspect.signature(fn)
        inject = "idempotency_key" in sig.parameters
        def prep(a, kw):
            k = key(*a, **kw)
            if k is None or str(k).strip() == "":
                raise MissingIdempotencyKey(f"{name}: key() returned {k!r}; derive it from stable run data")
            b = sig.bind_partial(*a, **kw); b.apply_defaults(); b.arguments.pop("idempotency_key", None)
            h = hashlib.sha256(json.dumps(b.arguments, sort_keys=True, default=_plain, separators=(",", ":")).encode()).hexdigest()
            lease = float(os.environ.get("AGENTSIGNAL_LEDGER_LEASE_S", lease_seconds))
            return str(k), str(run_id(*a, **kw) if run_id else k), h, lease
        def call(a, kw, k): return fn(*a, **kw, **({"idempotency_key": k} if inject else {}))
        def jsonb(v): return Jsonb(v, dumps=functools.partial(json.dumps, default=str))
        def warn(k, why): log.warning("re-running %s key %r (%s); same key passed again", name, k, why)

        @functools.wraps(fn)
        async def awrapper(*a, **kw):
            k, rid, h, lease = prep(a, kw)
            async with _aconnect(conn) as c:
                async def q(sql, p):
                    if isinstance(c, psycopg.AsyncConnection): return await (await c.execute(sql, p)).fetchone()
                    return await asyncio.to_thread(lambda: c.execute(sql, p).fetchone())
                for _ in range(5):
                    if await q(RESERVE, (rid, name, k, h, lease)): break
                    d = _decide(name, k, h, await q(READ, (name, k)))
                    if d and d[0] == "hit": return d[1]
                    if d and await q(RECLAIM, (rid, lease, name, k)): warn(k, d[1]); break
                else: raise EffectInFlight(f"{name}: key {k!r} is contended")
                try: res = await call(a, kw, k)
                except Exception as e:  # crash/cancel (BaseException) leaves it pending -> lease
                    await q(FAIL + " returning 1", (repr(e), name, k)); raise
                await q(COMMIT + " returning 1", (jsonb(res), name, k)); return res

        @functools.wraps(fn)
        def wrapper(*a, **kw):
            k, rid, h, lease = prep(a, kw)
            with _connect(conn) as c:
                for _ in range(5):
                    if c.execute(RESERVE, (rid, name, k, h, lease)).fetchone(): break
                    d = _decide(name, k, h, c.execute(READ, (name, k)).fetchone())
                    if d and d[0] == "hit": return d[1]
                    if d and c.execute(RECLAIM, (rid, lease, name, k)).fetchone(): warn(k, d[1]); break
                else: raise EffectInFlight(f"{name}: key {k!r} is contended")
                try: res = call(a, kw, k)
                except Exception as e:  # crash/cancel (BaseException) leaves it pending -> lease
                    c.execute(FAIL, (repr(e), name, k)); raise
                c.execute(COMMIT, (jsonb(res), name, k)); return res
        return awrapper if inspect.iscoroutinefunction(fn) else wrapper
    return deco

def _ready(c):
    if not c.autocommit:
        if c.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
            raise ValueError("side_effect_ledger needs a connection outside a transaction (use autocommit=True)")
        c.autocommit = True  # the reservation must be committed before the effect runs
    return c

class _connect:
    """Shared connection object: used as-is. Callable: called per use; a connection is closed after, a context
    manager (pool.connection) is entered and exited."""
    def __init__(self, conn): self.conn, self.cm, self.own = conn, None, False
    def __enter__(self):
        if isinstance(self.conn, psycopg.Connection): return _ready(self.conn)
        r = self.conn()
        if isinstance(r, psycopg.Connection): self.cm, self.own = r, True; return _ready(r)
        self.cm = r; return _ready(r.__enter__())
    def __exit__(self, *e):
        if self.own: self.cm.close()
        elif self.cm is not None: self.cm.__exit__(*e)

class _aconnect:
    def __init__(self, conn): self.conn, self.cm, self.own, self.c = conn, None, False, None
    async def __aenter__(self):
        if isinstance(self.conn, (psycopg.Connection, psycopg.AsyncConnection)): self.c = self.conn
        else:
            r = self.conn()
            if inspect.isawaitable(r): r = await r
            if isinstance(r, (psycopg.Connection, psycopg.AsyncConnection)): self.c, self.own = r, True
            else: self.cm = r; self.c = await r.__aenter__() if hasattr(r, "__aenter__") else r.__enter__()
        if isinstance(self.c, psycopg.AsyncConnection) and not self.c.autocommit:
            if self.c.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
                raise ValueError("side_effect_ledger needs a connection outside a transaction (use autocommit=True)")
            await self.c.set_autocommit(True)
        elif isinstance(self.c, psycopg.Connection): _ready(self.c)
        return self.c
    async def __aexit__(self, *e):
        if self.own: r = self.c.close(); await r if inspect.isawaitable(r) else None
        elif self.cm is not None: await self.cm.__aexit__(*e) if hasattr(self.cm, "__aexit__") else self.cm.__exit__(*e)

In your framework

LangGraph: node after interrupt()

examples/langgraph_node.py
# LangGraph: approve in one node with interrupt(), charge in the next node through the ledger.
import os, psycopg, stripe
from langgraph.types import interrupt
from ledger import side_effect_ledger

@side_effect_ledger(conn=lambda: psycopg.connect(os.environ["DATABASE_URL"]), effect="charge",
                    key=lambda amount, order_id, **_: f"{order_id}:charge")
def charge(amount, order_id, idempotency_key):
    return stripe.PaymentIntent.create(amount=amount, currency="usd", confirm=True,
                                       idempotency_key=idempotency_key).id

def approve(state): return {"approved": bool(interrupt({"q": f"Charge {state['amount']}?"}))}
def execute(state):  # runs after interrupt(); safe on resume, retry or a replayed approval
    if not state.get("approved"): return {}
    return {"charge_id": charge(state["amount"], order_id=state["order_id"])}

OpenAI Agents SDK: @function_tool(needs_approval=True) body

examples/openai_agents_tool.py
# OpenAI Agents SDK: the approved tool's body goes through the ledger (async path).
import os, psycopg, stripe
from agents import function_tool, RunContextWrapper
from ledger import side_effect_ledger

@side_effect_ledger(conn=lambda: psycopg.AsyncConnection.connect(os.environ["DATABASE_URL"]),
                    effect="charge", key=lambda amount, order_id, **_: f"{order_id}:charge")
async def ledger_charge(amount, order_id, idempotency_key):
    return (await stripe.PaymentIntent.create_async(amount=amount, currency="usd", confirm=True,
                                                    idempotency_key=idempotency_key)).id

@function_tool(needs_approval=True)
async def charge(ctx: RunContextWrapper[dict], amount: int) -> str:
    """Charge the customer for this order."""
    return await ledger_charge(amount, order_id=ctx.context["order_id"])

TypeScript version

ledger.ts
// Side-effect ledger for TypeScript (pg). Same table and semantics as ledger.py. MIT.
// Needs the side_effects table from schema.sql. https://tryagentsignal.com/templates/side-effect-ledger/
//
//   const id = await withLedger("charge", `${orderId}:charge`, (key) =>
//     stripe.paymentIntents.create({ amount, currency: "usd" }, { idempotencyKey: key }).then((p) => p.id),
//     { pool, args: { amount, orderId } });
//
// The key MUST come from stable run data (orderId, threadId, toolCallId). crypto.randomUUID() is wrong:
// every retry gets a new key, so nothing is deduped. Runs once per key; if a worker crashes mid-call, the
// effect can run again after the lease expires, so also pass the same key to the provider (e.g. Stripe
// Idempotency-Key).
//   committed -> stored result, fn not called       pending, in lease -> EffectInFlight (retry later)
//   pending, lease over -> treated as a crashed call: reclaimed atomically, fn runs again with the same key
//   failed (fn threw) -> fn runs again, same key    same key, other args -> IdempotencyKeyMismatch
import { createHash } from "node:crypto";
import type { Pool } from "pg";

export class EffectInFlight extends Error { name = "EffectInFlight"; }
export class MissingIdempotencyKey extends Error { name = "MissingIdempotencyKey"; }
export class IdempotencyKeyMismatch extends Error { name = "IdempotencyKeyMismatch"; }
export type LedgerOptions = {
  pool: Pool;                 // required: no implicit globals
  args?: unknown;             // the effect's arguments; hashed into args_hash (canonical JSON, sorted keys)
  leaseSeconds?: number;      // default 300; env AGENTSIGNAL_LEDGER_LEASE_S overrides
  runId?: string;             // stored for debugging; defaults to the key
  log?: (msg: string) => void;
};

const RESERVE = `insert into side_effects (run_id, effect, idempotency_key, args_hash, status, lease_until)
  values ($1, $2, $3, $4, 'pending', now() + make_interval(secs => $5)) on conflict do nothing returning status`;
const READ = `select status, result, args_hash, lease_until > now() as in_lease from side_effects
  where effect = $1 and idempotency_key = $2`;
const RECLAIM = `update side_effects set status = 'pending', run_id = $1, error = null,
  lease_until = now() + make_interval(secs => $2) where effect = $3 and idempotency_key = $4
  and (status = 'failed' or (status = 'pending' and lease_until < now())) returning status`;
const COMMIT = `update side_effects set status = 'committed', result = $3, committed_at = now(), lease_until = null
  where effect = $1 and idempotency_key = $2`;
const FAIL = `update side_effects set status = 'failed', error = $3, lease_until = null
  where effect = $1 and idempotency_key = $2`;

const canon = (v: unknown): string => Array.isArray(v) ? `[${v.map(canon).join(",")}]`
  : v && typeof v === "object" ? `{${Object.keys(v).sort().filter((k) => (v as any)[k] !== undefined)
      .map((k) => `${JSON.stringify(k)}:${canon((v as any)[k])}`).join(",")}}`
  : JSON.stringify(v ?? null);

export async function withLedger<T>(effect: string, key: string | null | undefined,
                                    fn: (idempotencyKey: string) => Promise<T>, opts: LedgerOptions): Promise<T> {
  if (!opts?.pool) throw new TypeError("withLedger needs opts.pool");
  if (!effect || key == null || String(key).trim() === "")
    throw new MissingIdempotencyKey(`${effect}: key is ${JSON.stringify(key)}; derive it from stable run data`);
  const db = opts.pool, k = String(key), runId = opts.runId ?? k;
  const lease = Number(process.env.AGENTSIGNAL_LEDGER_LEASE_S ?? opts.leaseSeconds ?? 300);
  const hash = createHash("sha256").update(canon(opts.args ?? {})).digest("hex");
  let owned = false;
  for (let i = 0; i < 5 && !owned; i++) {
    if ((await db.query(RESERVE, [runId, effect, k, hash, lease])).rowCount) { owned = true; break; }
    const row = (await db.query(READ, [effect, k])).rows[0];
    if (!row) continue;                                          // deleted meanwhile: reserve again
    if (row.args_hash !== hash) throw new IdempotencyKeyMismatch(`${effect}: key '${k}' was already used with different arguments`);
    if (row.status === "committed") return row.result as T;      // stored result, fn not called
    if (row.status === "pending" && row.in_lease) throw new EffectInFlight(`${effect}: key '${k}' is pending (lease not expired)`);
    if ((await db.query(RECLAIM, [runId, lease, effect, k])).rowCount) {
      owned = true; (opts.log ?? console.warn)(`re-running ${effect} key '${k}' (${row.status}); same key passed again`);
    }
  }
  if (!owned) throw new EffectInFlight(`${effect}: key '${k}' is contended`);
  let res: T;
  try { res = await fn(k); }
  catch (e) { await db.query(FAIL, [effect, k, String(e)]); throw e; }
  await db.query(COMMIT, [effect, k, JSON.stringify(res === undefined ? null : res)]);
  return res;
}

Prove it on your code

Run the free crash test against your LangGraph agent before and after adding the ledger. It kills your agent mid-approval, restarts it and counts how many times the tool ran. With the released agentsignal-check v0.3.2, the after run shows a WARN on kill/resume (no duplicate: the ledger refuses to re-run a call that crashed inside its lease).

Watch both the provider call and your decorated function; watching only the decorated function passes trivially.

agentsignal check
pip install "agentsignal-check[langgraph] @ git+https://github.com/agentsignal/agentsignal-check@v0.3.2"

agentsignal check --graph myapp.graph:build --effect myapp.payments:stripe_charge --effect myapp.payments:charge \
  --input '{"amount":1999}' --report agentsignal-report.md

How the crash test works →

What if the process crashes mid-call?

The ledger marks the key in flight before the charge runs. If the process dies before the result is saved, the charge can run again with the same key once the lease expires. Pass that key to your payment provider so it dedupes the retry.

Download .zipOptional. Everything above is free to copy without signing up.

Want it wired into your agent for you? $79 Fix