How Idempotency Keys Prevent Duplicate Side Effects on LLM-Triggered Webhooks
When an LLM invokes a tool or triggers an outbound webhook action (such as creating a refund, sending an email, charging a card, or updating a CRM record), network timeouts, worker crashes, or upstream LLM retries can cause the exact same tool call to execute more than once. Binding every side-effecting tool execution to a deterministic idempotency key ensures that retries return the original stored outcome instead of re-executing the external mutation.
- Deterministic key derivation vs. random UUIDs: A random
crypto.randomUUID()generated inside the tool wrapper creates a new key on every retry and fails to deduplicate. Instead, derive the idempotency key deterministically from stable business and turn coordinates—such assha256(tenantId + ":" + workflowOrRunId + ":" + stepOrTurnIndex + ":" + toolName + ":" + canonicalJson(args))—or reuse the model’stool_call.idwhen retrying within the same assistant turn. - Atomic
SET NXclaim state machine (IN_PROGRESS->COMPLETED/FAILED): Before firing the webhook, atomically claim the key in Redis (or a unique DB constraint) with a short lease TTL (IN_PROGRESS). If a concurrent duplicate arrives whileIN_PROGRESS, wait briefly or return a retryable conflict; if alreadyCOMPLETED, return the cached response payload immediately without hitting the downstream webhook. - Forward the idempotency key to downstream APIs too: Pass the derived key in an
Idempotency-KeyHTTP header on the outbound webhook request so even if your worker crashes after the downstream server committed the action but before your local cache updated, the downstream receiver also deduplicates it.
Steps to Implement Idempotent LLM Webhook Actions
- Canonicalize tool arguments and derive a deterministic idempotency key: Sort object keys recursively so
{ a: 1, b: 2 }and{ b: 2, a: 1 }hash identically, and combine tenant/user scope, workflow/message ID, tool name, and canonical args into a SHA-256 idempotency key. - Claim the key atomically in Redis before sending the webhook: Use
SET key value NX PX <leaseTtlMs>to acquire exclusive execution rights. Inspect any existing record first so completed keys return the cached result immediately. - Execute the outbound webhook with
Idempotency-Keyheader and timeout: Send the HTTP request with the deterministic key in headers, then atomically persist theCOMPLETEDstatus and serialized result with a longer retention TTL (e.g., 24 hours). - Release or mark
FAILEDcleanly on transient errors: If the outbound call fails with a transient error (e.g.,502/503/timeout) and you want retries to re-attempt, delete theIN_PROGRESSlock (or store a short-lived failure state) so a subsequent retry can safely re-acquire and execute.
TypeScript Example: Atomic Redis-Backed Idempotent Tool / Webhook Executor
import crypto from "node:crypto";
import type { Redis } from "ioredis";
export interface IdempotentContext {
tenantId: string;
conversationId: string;
turnId: string;
toolName: string;
}
type StoredIdempotencyRecord<T> =
| { state: "IN_PROGRESS"; ownerId: string; startedAtMs: number }
| { state: "COMPLETED"; result: T; completedAtMs: number };
/**
* Recursively sorts object keys so semantically identical tool argument payloads
* always produce the exact same canonical JSON string and SHA-256 hash.
*/
function canonicalizeJson(value: unknown): string {
if (value === null || typeof value !== "object") {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return `[${value.map((item) => canonicalizeJson(item)).join(",")}]`; } const obj = value as Record<string, unknown>; const sortedKeys = Object.keys(obj).sort(); const entries = sortedKeys .filter((k) => obj[k] !== undefined) .map((k) => `${JSON.stringify(k)}:${canonicalizeJson(obj[k])}`); return `{${entries.join(",")}}`;
}
export function deriveToolIdempotencyKey(
ctx: IdempotentContext,
args: unknown
): string {
const canonicalPayload = [
ctx.tenantId,
ctx.conversationId,
ctx.turnId,
ctx.toolName,
canonicalizeJson(args),
].join(":");
const digest = crypto.createHash("sha256").update(canonicalPayload).digest("hex");
return `idem:llm-webhook:${ctx.tenantId}:${digest}`;
}
export class IdempotentWebhookExecutor {
constructor(
private readonly redis: Redis,
private readonly leaseTtlMs = 30_000,
private readonly resultTtlSeconds = 86_400
) {}
async execute<TArgs, TResult>(
ctx: IdempotentContext,
args: TArgs,
dispatchWebhook: (idempotencyKey: string, payload: TArgs) => Promise<TResult>
): Promise<{ deduplicated: boolean; idempotencyKey: string; result: TResult }> {
const redisKey = deriveToolIdempotencyKey(ctx, args);
const ownerId = crypto.randomUUID();
const inProgressRecord: StoredIdempotencyRecord<TResult> = {
state: "IN_PROGRESS",
ownerId,
startedAtMs: Date.now(),
};
// 1. Attempt atomic claim via SET NX PX
const claimed = await this.redis.set(
redisKey,
JSON.stringify(inProgressRecord),
"PX",
this.leaseTtlMs,
"NX"
);
if (claimed !== "OK") {
const existingRaw = await this.redis.get(redisKey);
if (existingRaw) {
const existing = JSON.parse(existingRaw) as StoredIdempotencyRecord<TResult>;
if (existing.state === "COMPLETED") {
return {
deduplicated: true,
idempotencyKey: redisKey,
result: existing.result,
};
}
}
throw new Error(`Webhook action already in progress for key \${redisKey}; retry shortly.`);
}
try {
// 2. Dispatch external webhook forwarding the deterministic key
const result = await dispatchWebhook(redisKey, args);
// 3. Persist COMPLETED outcome atomically
const completedRecord: StoredIdempotencyRecord<TResult> = {
state: "COMPLETED",
result,
completedAtMs: Date.now(),
};
await this.redis.set(
redisKey,
JSON.stringify(completedRecord),
"EX",
this.resultTtlSeconds
);
return {
deduplicated: false,
idempotencyKey: redisKey,
result,
};
} catch (err) {
// Release lock only if still owned by this worker so retries can re-attempt
const releaseIfOwnerLua = `
local val = redis.call("GET", KEYS[1])
if not val then return 0 end
local decoded = cjson.decode(val)
if decoded.state == "IN_PROGRESS" and decoded.ownerId == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
`;
await this.redis.eval(releaseIfOwnerLua, 1, redisKey, ownerId);
throw err;
}
}
}
Helpful Tips for Production LLM Webhook Idempotency
- Never include volatile timestamps or request IDs inside the hashed payload: If you hash
Date.now()or an HTTP trace ID into the key, every retry generates a different hash and bypasses deduplication completely. - Match
leaseTtlMsto your outbound webhook HTTP timeout: Set the RedisIN_PROGRESSlease slightly longer than your outboundfetchAbortSignal.timeout(...)so a slow webhook cannot overlap with an early retry while still expiring cleanly if a Node.js pod crashes mid-request. - Include semantic business identifiers when cross-turn deduplication matters: If an LLM might re-issue the exact same tool call on a later turn (e.g.,
"refund_order"fororderId: "ORD-99"), scope the key totenantId + toolName + orderIdrather thanturnIdso duplicate actions across turns are also blocked.
You must log in or register to comment.
