Implementing Distributed Locks in Distributed Systems with Redis (Redlock)

Mastering distributed locking mechanisms in microservices and Node.js by exploring the Redlock algorithm, lock safety properties, lease times, and failure handling in Redis.

In modern distributed systems and microservices architectures, multiple independent service instances frequently compete to access shared resources, execute background cron jobs, or process payment transactions concurrently. Without proper synchronization, race conditions can lead to duplicate database entries, inventory overselling, or corrupted state.

While traditional locking mechanisms like database row locks or in-memory mutexes work well within a single monolith, they fail across distributed clusters. To solve this, developers use Distributed Locks backed by high-performance data stores like Redis. This comprehensive guide explores how to implement robust distributed locks using Redis, the theory behind the Redlock algorithm, lock safety properties, lease times, and failure handling.

Why Single-Instance Locks Fail in Microservices

When scaling an application horizontally across multiple containerized instances or Kubernetes pods, standard JavaScript async/mutex locks only lock execution within a single Node.js runtime process.

If two pods attempt to process a financial transaction for the same user simultaneously, both will execute independently unless a centralized coordination service—such as Redis—enforces mutual exclusion across the entire cluster.

Basic Locking with SET NX EX

The fundamental building block of a Redis distributed lock is the SET command with the NX (Not Exists) and EX (Expire) parameters.

TypeScript
Implementing basic atomic Redis lock acquisition and release in Node.js.
import { createClient } from 'redis';
import { randomBytes } from 'crypto';

const client = createClient();
await client.connect();

async function acquireLock(resourceKey: string, ttlSeconds: number): Promise<string | null> {
  const lockIdentifier = randomBytes(16).toString('hex');
  
  // SET resourceKey lockIdentifier NX EX ttlSeconds
  const result = await client.set(resourceKey, lockIdentifier, {
    NX: true,
    EX: ttlSeconds,
  });

  return result === 'OK' ? lockIdentifier : null;
}

async function releaseLock(resourceKey: string, lockIdentifier: string): Promise<boolean> {
  // Using a Lua script to ensure safe, atomic check-and-delete
  const luaScript = `
    if redis.call("get", KEYS[1]) == ARGV[1] then
      return redis.call("del", KEYS[1])
    else
      return 0
    end
  `;
  
  const result = await client.eval(luaScript, {
    keys: [resourceKey],
    arguments: [lockIdentifier],
  });

  return result === 1;
}

Achieving Fault Tolerance with Redlock

Relying on a single Redis master instance introduces a single point of failure. If the master crashes and fails over to a replica before the lock replication syncs, another client could acquire the same lock, violating safety guarantees.

• Multi-Node Coordination: The Redlock algorithm solves this by running Redis across N independent master nodes (typically 5). To acquire a lock, the client attempts to acquire the lock on all nodes sequentially using the same random token and timeout.

• Quorum Requirement: The lock is only considered successfully acquired if the client successfully acquires the lock on a majority of the nodes ($N/2 + 1$) within a specified time drift window.

Summary

Implementing distributed locks in Redis ensures safe concurrency control and mutual exclusion across distributed microservices.

By utilizing atomic SET NX EX commands, safe Lua script release mechanisms, and the Redlock algorithm for multi-node fault tolerance, engineering teams can build resilient distributed applications.