Idempotency Key With Redis Store

Ensure operation idempotency using Redis-stored keys with TTL for safe retry of side-effecting operations.

TypescriptResilience

Code

snippet
import Redis from'ioredis';export async function idempotent<T>(redis:Redis,key:string,fn:()=>Promise<T>,{ttl=86400000}={}):Promise<T>{const existing=await redis.get('idem:'+key);if(existing)return JSON.parse(existing)as T;const result=await fn();await redis.set('idem:'+key,JSON.stringify(result),'PX',ttl);return result;}export async function idempotentSafe<T>(redis:Redis,key:string,fn:()=>Promise<T>,{ttl=86400000}={}):Promise<T>{const lock=await redis.set('idem:lock:'+key,'1','NX','PX',10000);if(!lock)throw new Error('operation in progress');try{const existing=await redis.get('idem:'+key);if(existing)return JSON.parse(existing)as T;const result=await fn();await redis.set('idem:'+key,JSON.stringify(result),'PX',ttl);return result;}finally{await redis.del('idem:lock:'+key);}}