Idempotency Key With Redis Store
Ensure operation idempotency using Redis-stored keys with TTL for safe retry of side-effecting operations.
Code
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);}}How it works
Idempotency Key With Redis Store keeps everything in the functions idempotent and idempotentSafe.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Instead of silently continuing, the code raises Error at the guard.
What to watch for
- External dependency:
ioredis— install it before running the snippet. - The guard
existingshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
idempotent is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
FAQ
- What happens on invalid input?
- Validation comes first — `Error` marks the failure at `existing`, before any partial work happens.
- Which packages must be installed first?
- Yes. The imports resolve to `ioredis`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.