Concepts · Concept
Redis: Distributed Lock, Sorted Set, Set
**
**
Atomic command : SET key value NX EX 600
NX = “only set if this key does not already exist”
EX 600 = TTL of 600 seconds (10 min)
Distributed Lock (via Redis) — how to describe it:
“A distributed lock lets multiple processes/servers coordinate exclusive access to a shared resource, using Redis as the shared coordination point. The core primitive is SET key value NX EX ttl — NX means ‘only set if the key doesn’t already exist,’ making the check-and-set atomic in one step, so two concurrent requests can never both acquire the lock. EX sets a TTL, so the lock auto-releases if the holder crashes or forgets to release it, rather than deadlocking forever.”
Where you already used this, concretely:
- Ticketmaster — SET lock:ticket:{ticketId} {userId} NX EX 600 to reserve a seat for 10 minutes during checkout, with the value (userId, not just true) letting you verify the confirming user is the one who holds the reservation
Redis Sorted Set (ZSET) — how to describe it:
“A Redis Sorted Set stores unique members, each associated with a numeric score, kept automatically in score order. You can query by score range extremely efficiently — get everything with a score between X and Y — which is the killer feature.”
Where you already used this, concretely:
- Ticketmaster — event:{eventId}:reserved, scored by expiry timestamp, so ZRANGEBYSCORE … now +inf instantly returns only currently-active reservations; expired ones fall out of range automatically, no cleanup job needed
- Ticketmaster’s waiting queue — ordered by join time/priority, same range-query mechanism
When to reach for it: anything with a natural ordering by a number — timestamps (expiry, recency), scores (leaderboards), priorities (queues) — where you need both membership and efficient range queries by that number.
Redis Set — how to describe it:
“A Redis Set stores unique members with no ordering and no score — just fast membership checks (SISMEMBER) and set operations (union, intersection, difference).”
Where you already used this, concretely:
- Ticketmaster’s waiting queue — the “admitted” set (SADD admitted:{eventId} {userId}), where you only needed “is this user allowed through” — a yes/no membership check, no ordering needed at that stage
When to reach for it: pure membership checks where you don’t care about order or an associated value — “has this happened,” “is this user in this group” — simpler and slightly cheaper than a Sorted Set or Hash when you don’t need the extra structure.
NotE:
thoughtful statement like “We’d implement Redis with AOF persistence and Sentinel for failover to handle node failures with minimal data loss” demonstrates you’ve considered potential failure modes and aren’t treating Redis as a magical black box.