← Back to Blog
ARCHITECTURE

What Is Distributed Locking? Managing Resources Across Servers

F. Çağrı BilgehanJanuary 22, 202610 min read
distributed lockingredisdistributed systemsconcurrency

What Is Distributed Locking? Managing Resources Across Servers

Multiple servers accessing the same resource simultaneously? Two instances decrementing stock at once? Distributed locking provides safe, serialized access in distributed environments.

The Problem

Single-server mutexes don't work across multiple instances. Without distributed locks, concurrent operations cause data inconsistencies.

Redis Distributed Lock

// Acquire: SET key value NX PX ttl
const acquired = await redis.set(`lock:${resource}`, token, 'NX', 'PX', 10000);

// Release: Lua script (atomic, only owner can release)
const script = `
  if redis.call("get", KEYS[1]) == ARGV[1] then
    return redis.call("del", KEYS[1])
  end
`;

Redlock Algorithm

Uses 5+ independent Redis instances. Lock acquired when majority (3/5) agree. Survives single instance failure.

Fencing Tokens

Prevent stale lock holders from executing operations after TTL expires using monotonically increasing tokens.

Tools

| Tool | Mechanism | Best For | |------|-----------|----------| | Redis | SET NX PX | Fast, simple | | Redlock | Multi-Redis | More reliable | | ZooKeeper | Ephemeral nodes | Strong guarantees | | etcd | Leases | Kubernetes-native |

Best Practices

  1. TTL required — Prevent deadlocks
  2. Atomic release — Only the owner can release
  3. Retry with backoff — Exponential backoff on failure
  4. Fencing tokens — Block stale operations
  5. Minimize lock duration
  6. Monitor — Lock wait times and timeouts

Conclusion

Distributed locking prevents resource conflicts in distributed systems. Use Redis for simple cases, Redlock or ZooKeeper for critical systems. Always use TTL and fencing tokens.

Learn distributed locking on LabLudus.

Related Posts

What Is a Message Queue? Async Communication with RabbitMQ & Kafka

Message queues explained: RabbitMQ, Apache Kafka, async architecture, pub/sub patterns, and event-driven design for scalable systems.

What Is Software Architecture? A Comprehensive Guide

What is software architecture, why does it matter, and how do you learn it? A deep dive into architectural patterns, quality attributes, and the architect's career path.