LPOP and RPOP
Players who press "Find a match" in Wordcraft wait in line. The matchmaker should always pair the player who has waited longest, and each player must be taken exactly once. Pushing at one end of a list and popping at the other gives you that line for free.
The rule
Opposite ends make a queue; the same end makes a stack.
LPOP key removes the item at the head and returns it; RPOP key does the same at the tail. Popping a missing or empty list replies (nil), and when the last item is popped the key is deleted.
127.0.0.1:6379> RPUSH queue:match asha ravi meera
(integer) 3
127.0.0.1:6379> LPOP queue:match
"asha"
127.0.0.1:6379> LPOP queue:match
"ravi"
127.0.0.1:6379> RPUSH queue:match tom
(integer) 2
127.0.0.1:6379> LPOP queue:match
"meera"
127.0.0.1:6379> LPOP queue:match
"tom"
127.0.0.1:6379> LPOP queue:match
(nil)Queue (first in, first out). Push at one end and pop at the other: RPUSH + LPOP (or LPUSH + RPOP). The oldest item leaves first. This is the fair match queue above.
Stack (last in, first out). Push and pop at the same end: LPUSH + LPOP. The newest item leaves first, like an undo history.
Popping several. Since Redis 6.2, LPOP key count removes up to count items and returns them as a list: LPOP queue:match 2 takes two players at once.
Waiting instead of polling. A matchmaker that calls LPOP in a loop wastes effort while the queue is empty. BLPOP queue:match 5 blocks until an item arrives or 5 seconds pass, then replies with the key name and the item, or (nil) on timeout. BRPOP is the tail version.
The shortcut
Say where things go in and where they come out. Different ends means queue: the oldest comes out. Same end means stack: the newest comes out.
What must come out first?
Undo reverses the most recent change, so the newest item leaves first.
A plain list queue has one weakness: once a worker pops an item, Redis forgets it. If the worker crashes before finishing, the item is lost. The last lesson of this section shows how LMOVE closes that gap by moving the item into a "working" list in the same step.
Drills
Answer fast — trust the rule.
After RPUSH jobs j1 j2 j3, what does RPOP jobs return?
Which pair gives a first-in, first-out queue?
queue:match holds only tom. You run LPOP queue:match. What does EXISTS queue:match reply afterwards?
queue:match holds asha, ravi, meera. What does LPOP queue:match 2 return?
Remember
- Opposite ends make a queue; the same end makes a stack.
- Say where items go in and come out, and the order follows.
- An empty list disappears; BLPOP waits for work instead of polling.
