When you run a Node.js application on multiple servers or containers, it’s common for multiple processes to try modifying the same resource at the same time.
For example:
-
Two instances might both try to update the same database row.
-
Multiple workers might try to process the same background job.
This can lead to race conditions — inconsistent or duplicated data updates.
To prevent that, we use a distributed lock.
What Is a Distributed Lock?
A distributed lock ensures that only one process at a time can perform a specific operation, even across multiple machines.
It’s like putting a “do not disturb” sign on a shared resource — until the sign is removed, no one else can use it
Why Use Redis?
Redis is a fast, in-memory data store often used for caching, queues, and synchronization.
It’s ideal for distributed locking because it supports atomic operations — meaning no two commands can interfere mid-execution.
With one simple command, Redis can:
-
Set a lock only if it doesn’t exist (
NXoption) -
Automatically expire the lock after a set time (
PXoption)
This prevents deadlocks — even if a process crashes, the lock eventually disappears.
How It Works (Conceptually)
-
When your Node.js app wants to do something exclusive (e.g., update shared data), it tries to acquire a lock in Redis.
-
If the lock doesn’t exist, Redis creates it and gives access to the process.
-
While the lock is active, no other instance can acquire it.
-
After the process finishes, it releases the lock (or it expires automatically).
This mechanism keeps your operations safe and consistent.
Minimal Example
Here’s what the core logic looks like conceptually (simplified for clarity):
SET resource_lock unique_value NX PX 5000
That line means:
“Set the key
resource_lockonly if it doesn’t already exist, and expire it in 5 seconds.”
If it succeeds, you have the lock.
If not, someone else has it — try again later.
When you’re done, you delete the key (but only if you still own it).
Practical Use Cases
-
Preventing duplicate background jobs in worker queues
-
Ensuring single writes to a shared record
-
Avoiding conflicts in payment or order processing
-
Managing critical sections in microservices
Production-Ready Option: Redlock
While a single Redis instance works fine for small projects, it can become a single point of failure.
For distributed and fault-tolerant systems, use the Redlock algorithm — a safe, well-tested locking mechanism designed by Redis’s creator.
You can implement it easily with the npm redlock library, which handles retries, timeouts, and multi-Redis consensus for you.