Redis Hard coding 1 views 1 min read

How do you implement a distributed lock with Redis?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Redis conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

A common implementation is SET key value NX PX ttl. NX sets the key only if it does not exist, and PX gives the lock an expiry so a crashed holder cannot deadlock the system. The value should be a unique token so only the owner releases the lock.

token = str(uuid.uuid4())
if redis.set("lock:order:42", token, nx=True, px=10000):
    try:
        process_order(42)
    finally:
        redis.eval(
            "if redis.call('get', KEYS[1]) == ARGV[1] then "
            "return redis.call('del', KEYS[1]) else return 0 end",
            1, "lock:order:42", token)

The Lua script makes check-and-delete atomic, preventing one client from deleting another's lock. For failover safety use Redlock across independent nodes, but note it is contested and cannot give strict fencing guarantees. Long tasks should renew the TTL and pass fencing tokens downstream.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?