When multiple instances of a microservice attempt to modify a shared resource simultaneously, a simple local mutex won't work. You need a distributed lock to ensure only one node executes the critical section.
Module 1: The Basics of Redis Distributed Locks
A naive distributed lock in Redis uses SETNX (Set if Not eXists). However, this is prone to failure if the Redis instance crashes or the client holds the lock forever due to a failure.
Requirements for a Safe Lock
- Mutual Exclusion: At any given moment, only one client can hold a lock.
- Deadlock Free: Eventually, it is always possible to acquire a lock, even if the client that locked a resource crashes (TTL).
- Fault Tolerance: The lock service itself must be highly available.
Module 2: The Redlock Algorithm
To solve the single-point-of-failure problem of a single Redis node, Redlock uses a consensus mechanism across 5 independent Redis instances. A lock is acquired only if a majority (3/5) of the nodes grant the lock.
Module 3: Strongly Consistent Locks (etcd / ZooKeeper)
For mission-critical data (like financial transactions), AP systems like Redis are generally avoided for locking. Instead, CP systems like etcd or ZooKeeper are used because they rely on the Raft or Zab consensus algorithms, ensuring strict serializability.