Retries happen constantly in distributed systems. A webhook times out at 5 seconds, an HTTP client retries, or an AI agent calls the same tool twice in a loop. Without an idempotency key, your server processes the side effect twice.

The standard fix is hashing the request payload with SHA-256 and caching the result. The trap is calling JSON.stringify(payload) directly before hashing.

Why Naive JSON.stringify Fails

JavaScript preserves insertion order for object keys, and different clients or microservices rarely insert keys in the exact same order.

Consider two identical payloads:

const clientA = { to: "alex@example.com", meta: { retry: 1, traceId: "abc" } }; const clientB = { meta: { traceId: "abc", retry: 1 }, to: "alex@example.com" }; 

To your business logic, clientA and clientB are the same request. To JSON.stringify, they produce completely different strings, which means two different SHA-256 hashes and a bypassed idempotency check.

Canonicalizing Objects Recursively

To guarantee identical digests across runtimes, sort object keys recursively while keeping array order intact (since array element order is semantically meaningful).

type JsonValue = | string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; export function canonicalizeJson(value: JsonValue): JsonValue { if (Array.isArray(value)) { return value.map(canonicalizeJson); } if (value !== null && typeof value === "object") { const sorted: { [key: string]: JsonValue } = {}; for (const key of Object.keys(value).sort()) { const entry = value[key]; if (entry !== undefined) { sorted[key] = canonicalizeJson(entry); } } return sorted; } return value; } 

A subtle detail here is skipping undefined values. JSON.stringify omits undefined properties during serialization, so filtering them explicitly keeps your canonical structure aligned with the serialized output.

Computing the SHA-256 Digest

Using the Web Crypto API (available natively in Bun, Node 20+, Deno, and Cloudflare Workers), you can hash the canonical string with zero external dependencies:

export async function buildIdempotencyKey(payload: JsonValue): Promise<string> { const canonical = JSON.stringify(canonicalizeJson(payload)); const bytes = new TextEncoder().encode(canonical); const hashBuffer = await crypto.subtle.digest("SHA-256", bytes); return Array.from(new Uint8Array(hashBuffer)) .map((byte) => byte.toString(16).padStart(2, "0")) .join(""); } 

Pairing Hashes With Scoped Locks

Even a deterministic key has a race condition if two identical requests arrive within the same millisecond before either writes to your cache. Always combine the digest with an atomic SET key NX EX 86400 in Redis (or a UNIQUE constraint insert in SQLite/Postgres) so the second caller receives a 409 Conflict or replays the cached response instead of executing in parallel.

💡 Developer Infrastructure Note: If your AI agent or background worker dispatches transactional emails over HTTP or MCP, idempotency gates only hold up when the delivery layer enforces velocity caps and recipient allowlists too. SadaSend pairs an active Port 25 bounce gate with spend guards built for automated workflows.