Patterns
35 items
35 items
Mutual exclusion across distributed nodes
Distributed locking provides mutual exclusion across multiple processes or servers, ensuring only one client can access a resource at a time. Unlike local locks, distributed locks must handle network partitions, process crashes, and clock skew. Implementations include Redis (Redlock), ZooKeeper, etcd, and database-based locks. Key challenges are: ensuring lock release on failure (TTL/leases), preventing stale lock holders from operating (fencing tokens), and handling split-brain. Essential for coordinating access to shared resources in distributed systems.
If lock holder crashes, lock must eventually release. Use TTL or lease-based expiration. But TTL creates timing issues - holder might still be working when lock expires.
After lock expires, old holder might still send operations. Include monotonically increasing token with all operations. Storage rejects operations with old tokens.
Redis Redlock attempts fault-tolerant locking across N Redis instances. Requires majority. Criticized for clock dependency. Use with caution for critical sections.
Scenario: Two processes try to withdraw $100 from account with $150 balance.
Without locking: 1. Process A reads balance: $150 2. Process B reads balance: $150 3. Process A: $150 - $100 = $50, writes $50 4. Process B: $150 - $100 = $50, writes $50 5. Result: $50 balance, but $200 withdrawn!
With distributed lock: 1. Process A acquires lock 2. Process A reads $150, withdraws $100, writes $50 3. Process A releases lock 4. Process B acquires lock 5. Process B reads $50, insufficient funds!