In high-concurrency scenarios, distributed locks are essential for ensuring data consistency. However, many developers’ understanding of Redis distributed locks stops at “SETNX”, leading to frequent production incidents.
This article comprehensively covers the correct usage of Redis distributed locks from principles, implementation, common misuse cases to production-grade solutions.
Why Do We Need Distributed Locks?
In single-node applications, we use synchronized or ReentrantLock to solve concurrency issues. But in distributed systems:
- Multiple service instances access shared resources simultaneously
- Database transactions cannot cover cross-service business logic
- Cache-database consistency requires coordination
At this point, distributed locks are needed to ensure that only one thread/process can execute critical code sections at the same time.
Basic Implementation: SETNX + EXPIRE
The simplest implementation:
# Acquire lock
SETNX lock_key 1
EXPIRE lock_key 30
# Release lock
DEL lock_key
Problems:
- Atomicity issue: SETNX and EXPIRE are not atomic operations
- Deadlock risk: If the service crashes after acquiring the lock, the lock will never be released
- Misdeletion risk: Releasing the lock might delete another client’s lock
Improved Solution: SET NX PX + Lua Script
# Acquire lock (atomic operation)
SET lock_key client_id NX PX 30000
# Release lock (Lua script ensures atomicity)
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
Advantages:
- SET command’s NX and PX parameters ensure atomicity
- Lua script guarantees atomic release of lock
- client_id prevents misdeletion of other clients’ locks
Production-Grade Solutions
Solution 1: Redisson (Recommended)
Redisson provides mature distributed lock implementation:
RLock lock = redisson.getLock("myLock");
lock.lock(); // Automatic renewal
try {
// Business logic
} finally {
lock.unlock();
}
Features:
- Automatic renewal (Watchdog mechanism)
- Reentrant locks
- Fair/non-fair locks
- Timeout auto-release
Solution 2: Redisson + Spring Boot
# application.yml
redisson:
config: |
singleServerConfig:
address: "redis://127.0.0.1:6379"
connectionMinimumIdleSize: 10
connectionPoolSize: 64
database: 0
idleConnectionTimeout: 10000
pingTimeout: 1000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
Common Misuse Cases
Case 1: Unreasonable Lock Expiration Time
- Problem: Setting too short expiration time
- Consequence: Business logic not completed before lock expires
- Solution: Set based on maximum business execution time + safety margin
Case 2: Ignoring Lock Renewal
- Problem: Long-running tasks where lock expires
- Consequence: Other clients acquire lock and modify data
- Solution: Use automatic renewal mechanism or manual renewal
Case 3: Ignoring Network Partition Issues
- Problem: Network jitter causes client to think lock acquisition succeeded
- Consequence: Split-brain problem, multiple clients think they hold the lock
- Solution: Use Redlock algorithm or strong consistency storage
Best Practice Checklist
- Must set timeout: Prevent deadlocks
- Use unique identifier: Avoid misdeleting other clients’ locks
- Atomic operations: Both lock acquisition and release must be atomic
- Consider auto-renewal: For long-running tasks
- Monitoring & alerts: Lock acquisition failure rate, waiting time, etc.
- Fallback strategy: Backup strategy when lock service is unavailable
Performance Comparison Test
| Solution | Lock Acquisition Time | Lock Release Time | Reliability | Use Case |
|---|---|---|---|---|
| Native SETNX | 0.5ms | 0.3ms | Low | Test environment |
| SET NX PX | 0.6ms | 0.4ms | Medium | Simple business |
| Redisson | 1.2ms | 0.8ms | High | Production environment |
| Redlock | 2.5ms | 1.5ms | Very High | Financial-grade systems |
Conclusion
Redis distributed locks are not just simple “lock-acquire-lock-release” operations, but a complete concurrency control solution. Choosing the appropriate implementation method and combining it with business scenario characteristics is key to truly leveraging the value of distributed locks.
Remember: Locks are just means, consistency is the goal.
This article is compiled from actual production experience. Feel free to share your distributed lock practical experience in the comments.