Redlock Distributed Lock Redis
Acquire distributed locks across multiple Redis instances using the Redlock algorithm with quorum and TTL.
Code
import Redis from'ioredis';export async function redlock(clients,resource,{ttl=10000,retries=3,delay=200}={}){const quorum=Math.floor(clients.length/2)+1;const token=Math.random().toString(36).slice(2);for(let attempt=0;attempt<retries;attempt++){const acquired=await Promise.all(clients.map(c=>c.set(resource,token,'NX','PX',ttl).then(r=>r==='OK')));if(acquired.filter(Boolean).length>=quorum)return{token,unlock:()=>unlock(clients,resource,token)};await new Promise(r=>setTimeout(r,delay));}throw new Error('lock failed');}async function unlock(clients,resource,token){const script='if redis.call("get",KEYS[1])==ARGV[1] then return redis.call("del",KEYS[1]) end';await Promise.all(clients.map(c=>c.eval(script,1,resource,token)));}How the snippet works
The working surface is the functions redlock and unlock — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Error is not tied to any input check: it fires whenever execution reaches that line.
The result comes back as an object carrying token, clients, resource.
What to watch for
- Dependency check:
ioredis— not built-in, must be present in the project.
Using it
The primary signature is export async function redlock(clients,resource,{ttl=10000,retries=3,delay=200}={})
redlock is what another module would consume; nothing else here is load-bearing for callers.
The call returns token, clients, resource — destructure what you need at the call site.
Interactive Tools for This Topic
FAQ
- Does the code guard against bad input?
- The snippet does not validate input. `Error` is thrown unconditionally at its throw site — nothing guards it.
- What does this need from the package registry?
- These are real dependencies: `ioredis`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.