How do you implement idempotency keys on LLM-triggered webhook actions so retries never duplicate side effects? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you implement idempotency keys on LLM-triggered webhook actions so retries never duplicate side effects?

message-square
0

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 as sha256(tenantId + ":" + workflowOrRunId + ":" + stepOrTurnIndex + ":" + toolName + ":" + canonicalJson(args))—or reuse the model’s tool_call.id when retrying within the same assistant turn.
  • Atomic SET NX claim 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 while IN_PROGRESS, wait briefly or return a retryable conflict; if already COMPLETED, 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-Key HTTP 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

  1. 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.
  2. 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.
  3. Execute the outbound webhook with Idempotency-Key header and timeout: Send the HTTP request with the deterministic key in headers, then atomically persist the COMPLETED status and serialized result with a longer retention TTL (e.g., 24 hours).
  4. Release or mark FAILED cleanly 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 the IN_PROGRESS lock (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 leaseTtlMs to your outbound webhook HTTP timeout: Set the Redis IN_PROGRESS lease slightly longer than your outbound fetch AbortSignal.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" for orderId: "ORD-99"), scope the key to tenantId + toolName + orderId rather than turnId so duplicate actions across turns are also blocked.