Redis medium
What is the recommended pattern for acquiring a resilient distributed lock in a single-instance Redis environment?
- A `SET lock_key unique_value NX PX 10000`: Ensures mutual exclusion with an automatic safety timeout.
- B `SET lock_key 1`: Simply sets a flag; relies on the application and users to check it manually.
- C `INCR lock_key`: Increments a counter; the lock is granted to the client that reaches exactly 10.
- D `LPUSH lock_key 1`: Adds a token to a list; the client that pops the token first owns the resource.
Answer: A. `SET lock_key unique_value NX PX 10000`: Ensures mutual exclusion with an automatic safety timeout.
`NX` (Not Exists) prevents overwriting an existing lock. `PX` (Expiration) ensures that if the owner crashes, the lock will 'auto-release' in 10s so other workers aren't blocked forever.
One system design question a day, with spaced repetition so the ones you miss come back.
Get the appRelated questions
- If the Redis memory limit is reached, what specific behavior is exhibited by the `allkeys-lru` eviction policy?
- What is the defining characteristic of a Redis 'Set' data type compared to a standard Redis 'List'?
- In the context of Redis messaging, what is the functional definition of the 'Pub/Sub' feature?
- How does the Redis background snapshotting process (`BGSAVE`) leverage the operating system's `fork()` mechanism to minimize memory overhead?
- Why does Redis proactively disconnect a Pub/Sub client that exhibits high 'output buffer' usage relative to its ingestion rate?
- How does a 'Sorted Set' (ZSET) manage its internal membership and ordering differently from a plain Set?