How to Build Deterministic SHA-256 Idempotency Keys in TypeScript (With Recursive JSON Sorting)
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 : "a***@example.com" , meta : { retry : 1 , traceId : "abc" } } ;
const clientB = { meta : { traceId : "abc" , retry : 1 } , to : "a***@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.
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: "a***@example.com", meta: { retry: 1, traceId: "abc" } };
const clientB = { meta: { traceId: "abc", retry: 1 }, to: "a***@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 {
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.
Top comments (1)
The recursive sort is the right core, and the undefined-skip detail is the one most people miss. One gap I would close before shipping this: the key hashes only the payload, so two different endpoints receiving the same JSON body produce the same key. If the key space is shared across routes - and it usually is, once a second service adopts the helper - a charge and a refund with identical bodies would collide. I would fold the method and route into the canonical string, e.g. hash POST:/payments plus the canonical payload, so the key names the operation, not just the bytes. Two questions: you set the lock TTL to 86400 - what happens to a retry that lands on day two, after the key expired but the original effect is still in the books? And on the number edge, how does your canonicalizer treat -0, NaN and Infinity, since JSON.stringify turns the last two into null?
Comments
No comments yet. Start the discussion.