Redis Distributed Lock with Three Checks: Why Small Projects Should Rethink Its Use
The article analyzes Redis distributed locks—its three‑step verification, the limited guarantees it provides, and why small‑to‑medium projects should often prefer database constraints, idempotency keys, or state machines over adding a lock that introduces extra complexity and maintenance overhead.
Many projects instinctively add a Redis distributed lock for order deduplication, inventory decrement, or scheduled‑task acquisition, assuming it makes the system safer. The author first asks whether the goal is to prevent two actors from executing simultaneously or to ensure that a particular operation can only take effect once.
What the "three checks" actually verify
Lock acquisition : SET lockKey token NX PX leaseTime – creates the lock only if it does not exist and attaches a lease.
Unlock : a Lua script compares the stored token and deletes the key only when they match, preventing accidental removal of another instance’s lock.
Renewal : before extending the lease, the client again checks the token to confirm the lock is still owned.
This pattern solves two classic pitfalls: a lock that expires and is then mistakenly deleted, and a business operation that runs longer than the initial lease.
Limitations of the lock
The lock only guarantees cross‑instance mutual exclusion, not full business correctness. After a lease expires, a thread may be paused by GC, network jitter, or a stalled machine and later resume while another instance has already acquired the lock, potentially writing to the database. The token can stop the old thread from unlocking, but it cannot undo SQL, RPC, or message actions already performed.
Redis primary‑replica failover also creates a window: if the primary confirms the lock before replicating it and then crashes, the new primary may not have the lock, allowing another client to enter the critical section.
Lock is not a panacea
Therefore, a lock merely reduces the probability of concurrent execution; the business logic must still be able to detect duplicate or expired operations.
Do not conflate five problems with “locking”
Mutual exclusion : only one executor at a time, e.g., a single instance runs a full‑reconciliation job.
Idempotency : repeated requests produce the same effect once, such as payment callbacks.
State flow : enforce valid transitions, e.g., an order moves from “pending” to “paid” but not back.
Data consistency : prevent negative inventory, ensure order and deduction records commit together.
Fault recovery : decide who compensates or retries after a crash mid‑process.
Redis locks mainly address the first item; the other four are often better solved by database constraints, state machines, or idempotency keys.
Concrete alternative: unique index + local transaction
Assign a request_id to each order request and create a unique index on (user_id, request_id):
CREATE UNIQUE INDEX uk_order_request ON orders(user_id, request_id);
INSERT INTO orders(user_id, request_id, amount, status) VALUES (?, ?, ?, 'CREATED');If two requests arrive simultaneously, the database allows only one insert; the other catches the unique‑key violation and can query the existing order by request_id. This approach remains correct even if the lock expires, the service restarts, or the client retries.
Inventory decrement via conditional update
When stock must not go below zero, a conditional update expresses the rule directly:
UPDATE sku SET stock = stock - 1 WHERE id = ? AND stock > 0;Returned affected‑row count of 1 means success; 0 means insufficient stock. Combining the stock update and a reservation record in the same local transaction keeps the constraint at the data layer.
Choosing the right solution
Unique index + local transaction : solves duplicate writes and guarantees data constraints; handle conflict by transaction rollback; suited for order creation and consumption records.
Conditional update + state machine : prevents illegal state transitions and controls inventory boundaries; requires explicit state handling and retry logic; suited for inventory, order status, approval flows.
Message deduplication : handles at‑least‑once delivery; store message IDs atomically with business writes; suited for payment callbacks, async notifications, MQ consumption.
Redis distributed lock : provides short‑term cross‑instance mutual exclusion; must manage lease, renewal, loss, retry, and monitoring; suited for scheduled‑task抢占 and other cross‑node exclusive operations.
Hidden maintenance cost of a Redis lock
Beyond tryLock() and unlock(), you must define the maximum critical‑section duration, decide what to do when renewal fails, choose whether lock acquisition failure means skipping or queuing, prevent retry storms, monitor wait and hold times, and handle primary‑replica switches that could cause double execution.
If the critical section calls third‑party services, you also need to ensure those services support an idempotency key; otherwise the lock cannot guarantee a single call.
When to actually adopt a Redis lock
If the operation can be performed inside a single database transaction, prefer unique indexes, conditional updates, or state checks. If requests, callbacks, or messages may be duplicated, use idempotency keys or message deduplication. Only when you truly need cross‑instance mutual exclusion, the cost of duplicate execution is high, the database cannot serialize the operation, and you have defined clear recovery and compensation strategies should you lose the lock, consider a Redis distributed lock.
The decisive questions are: can the critical section be repeated safely? Can final data be reconciled if duplicates occur? Is the potential loss from a fault higher than the operational cost of maintaining the lock?
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
