Idempotency Keys: The One API Pattern That Prevents Duplicate Payments (and Worse)
You hit "Submit Order" and nothing happens. The spinner just spins. Is it processing? Did the request get lost? You click again. If the API on the other end does not implement idempotency, you just placed two orders. Maybe two charges to your card. This is a solved problem — and the solution is simpler than you think. What Is Idempotency? An operation is idempotent if doing it multiple times produces the same result as doing it once. GET requests are naturally idempotent — fetching a resource does not change it. DELETE is also idempotent in practice. The trouble is POST and PATCH : create an order twice, and you get two orders. An idempotency key is a client-generated unique identifier (usually a UUID) that you send with a mutating request. The server stores this key with the result. If the same key arrives again — whether due to a retry, a network blip, or an impatient user — the server returns the cached result instead of executing the operation again. Implementing Idempotency on the Server Here is a minimal Express implementation backed by Redis: const express = require ( " express " ); const redis = require ( " ioredis " ); const { v4 : uuidv4 } = require ( " uuid " ); const app = express (); const cache = new redis (); app . use ( express . json ()); // TTL for idempotency records: 24 hours const IDEMPOTENCY_TTL = 86400 ; async function idempotencyMiddleware ( req , res , next ) { const key = req . headers [ " idempotency-key " ]; if ( ! key ) return next (); // optional on GET/DELETE const cached = await cache . get ( `idem: ${ key } ` ); if ( cached ) { const { status , body } = JSON . parse ( cached ); return res . status ( status ). json ( body ); } // Intercept the response to cache it const originalJson = res . json . bind ( res ); res . json = async ( body ) => { if ( res . statusCode < 500 ) { await cache . setex ( `idem: ${ key } ` , IDEMPOTENCY_TTL , JSON . stringify ({ status : res . statusCode , body }) ); } return originalJson ( body ); }; next ();