Choosing the Right Distributed Lock: A Guide for Architects

Distributed locks are essential for coordinating access to shared resources across multiple machines; this article compares common solutions—Redis locks, database optimistic and logical locks, DB row locks, and Zookeeper locks—detailing their principles, pros, cons, implementation details, and best‑fit scenarios.

Java Baker
Java Baker
Java Baker
Choosing the Right Distributed Lock: A Guide for Architects

Qualified Distributed Lock Requirements

Mutual exclusion – only one client holds the lock at any time.

Dead‑lock protection – the lock is released automatically if the holder crashes.

Re‑entrancy – the same client can acquire the lock multiple times without blocking itself.

Performance – low overhead for lock and unlock, high throughput.

Pessimistic vs. Optimistic Locks

Pessimistic Lock

Assumes a high probability of conflict; acquires an exclusive lock before operating on the resource.

Typical implementations: DB row lock ( SELECT ... FOR UPDATE), DB logical lock (status field), Redis SET NX PX command.

Advantages: strict mutual exclusion, no repeated retries.

Disadvantages: other threads must wait, risk of dead‑lock, throughput limited by lock granularity and hold time.

Suitable for write‑heavy workloads with frequent conflicts.

Optimistic Lock

Assumes conflicts are rare; reads data first and checks a version field during update.

Typical implementations: version column, CAS (compare‑and‑set).

Advantages: lock‑free, lower overhead.

Disadvantages: many retries under high contention; possible ABA problem unless a monotonically increasing version is used.

Suitable for read‑heavy, write‑light workloads such as inventory or balance deduction.

Solution Candidates

1. DB Row Lock (Pessimistic, Not Recommended)

Principle: use InnoDB exclusive lock via SELECT ... FOR UPDATE inside a transaction.

Implementation notes:

Must run inside a transaction; otherwise the lock is released immediately.

WHERE clause should hit a primary key or unique index to avoid table‑level or gap locks.

Avoid time‑consuming operations (e.g., external RPC) inside the transaction.

Set a reasonable innodb_lock_wait_timeout to prevent indefinite blocking.

Best fit: low concurrency, strong consistency, existing DB without adding middleware (e.g., internal scheduled tasks).

2. DB Optimistic Lock

Principle: add a version column to the business table and use it for CAS‑style updates.

Implementation steps:

Query the current version (v1).

Update with UPDATE ... WHERE biz_id=? AND version=?.

Check affected rows: >0 means success; 0 means another thread modified the row, so retry.

Best fit: medium concurrency, read‑many/write‑few scenarios such as inventory or balance deduction.

3. DB Logical Lock (Pessimistic)

Principle: add a lock_status field; acquire lock with a conditional UPDATE that sets the status to 1 only when it is 0 or expired.

Lock acquisition:

Unlock with owner verification:

Periodic task clears expired locks to avoid dead‑lock when the holder crashes.

Best fit: medium concurrency where lock state must be persisted (e.g., multi‑step business flows).

4. Redis Lock (Pessimistic)

Principle: use the atomic SET key value NX PX timeout command; success means the lock is acquired, and the key expires automatically.

Implementation notes:

Value must be a unique identifier (e.g., UUID); unlocking requires a compare‑and‑delete, usually via a Lua script.

Lock renewal (watchdog) is needed for long‑running tasks; Redisson provides this out of the box.

Re‑entrancy can be achieved with a hash storing owner and re‑entry count.

Best fit: high‑concurrency write scenarios that can tolerate brief weak consistency (e.g., flash‑sale deduplication, idempotent message processing).

5. Multi‑node RedLock (Not Recommended)

RedLock attempts to acquire the lock on a majority of independent Redis nodes. The article notes added complexity, performance overhead, and edge cases under GC pauses or network latency, so it is not recommended.

6. Zookeeper Lock (Not Recommended)

Principle: create an ephemeral sequential node under /lock; the client with the smallest sequence number owns the lock.

If not the smallest, watch the predecessor node; when it disappears, re‑evaluate.

Unlocking is simply deleting the node; ZK automatically removes the node if the session expires.

Best fit: scenarios demanding strong consistency where performance and operational cost are acceptable (e.g., leader election in Hadoop/Kafka clusters), not typical business logic.

Comparison Summary

DB Row Lock – Strong consistency, low performance, simple implementation, requires lock timeout configuration, suitable for low‑concurrency internal tasks.

DB Optimistic Lock – Strong consistency, medium‑high performance, low implementation complexity, no dead‑lock, suitable for moderate concurrency with read‑heavy workloads.

DB Logical Lock – Strong consistency, medium performance, moderate implementation complexity, dead‑lock avoided via expiration, suitable for medium concurrency where lock state must be persisted.

Redis Lock – Weak consistency, high performance, moderate implementation complexity (Lua script or Redisson), dead‑lock avoided via TTL and renewal, suitable for high‑concurrency write scenarios that can accept occasional stale locks.

Zookeeper Lock – Strong consistency, low performance, high implementation complexity, automatic dead‑lock protection, suitable only for cluster coordination, not for typical business logic.

Recommendation Order

Prefer DB optimistic lock, DB logical lock, or Redis lock.

Avoid DB row lock and Zookeeper lock for most application‑level use cases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaConcurrencyRedisZookeeperdistributed lockoptimistic lock
Java Baker
Written by

Java Baker

Java architect and Raspberry Pi enthusiast, dedicated to writing high-quality technical articles; the same name is used across major platforms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.