Lists, Queues and Streams
Ordered data, and the two ways to do messaging.
A list keeps insertion order and is cheap at both ends, so it is the first thing people reach for as a queue. This chapter is when that is right.
Pushing and reading
RPUSH adds at the right, LPUSH at the left, and both return the new length:
RPUSH q a b c
LRANGE q 0 -1
LPUSH q first
LRANGE q 0 -1LRANGE q 0 -1 is the whole list: inclusive indexes, negative from the end. LINDEX reads
one position:
RPUSH l a b c
LINDEX l 0
LINDEX l -1
LINDEX l 99Popping
Both ends again, and a count pops several at once:
RPUSH q a b c d e
LPOP q
RPOP q
LPOP q 2
LRANGE q 0 -1
LPOP emptyPopping the last element removes the key, as with hashes in chapter 4:
RPUSH q only
LPOP q
EXISTS q
TYPE qA list as a queue
Push one end, pop the other, and you have FIFO:
RPUSH q first second third
LPOP q
LPOP qBLPOP
LPOP on an empty list returns immediately, so a worker would have to poll. BLPOP waits
instead:
RPUSH jobs job1
BLPOP jobs 0LMOVE
The gap in 5.3 was that a popped job exists nowhere. LMOVE pops and pushes as one step:
RPUSH pending a b
LMOVE pending processing LEFT RIGHT
LRANGE pending 0 -1
LRANGE processing 0 -1The job is in processing before work starts, so a sweeper can return it if the worker dies.
Source and destination may match, rotating a list:
RPUSH ring a b c
LMOVE ring ring LEFT RIGHT
LRANGE ring 0 -1LTRIM
It keeps a range and discards the rest, which caps a list in place:
RPUSH feed a b c d e
LTRIM feed 0 2
LRANGE feed 0 -1
LLEN feedPub/Sub
PUBLISH sends to a channel and returns how many clients received it:
PUBLISH news helloWith a subscriber connected, the same command returns 1 and the subscriber prints the
message. It needs a second connection, because SUBSCRIBE blocks:
redis-cli SUBSCRIBE newsStreams
A stream is an append-only log with ids. XADD with * generates one from the clock:
redis-cli XADD events '*' action loginMilliseconds, a dash, then a sequence number. Explicit ids make the rest easier to see, and
XRANGE - + reads everything:
XADD events 1-1 action login
XADD events 2-1 action logout
XLEN events
XRANGE events - +Ids must increase, which is what makes the log append-only:
XADD s 5-1 f v
XADD s 3-1 f vConsumer groups
A group tracks what each consumer has taken and whether it finished. XREADGROUP with >
means “entries nobody has yet”:
XADD tasks 1-1 job a
XADD tasks 2-1 job b
XGROUP CREATE tasks workers 0
XREADGROUP GROUP workers alice COUNT 1 STREAMS tasks >That entry is now pending — delivered, not confirmed:
XPENDING tasks workersXACK confirms it, and the pending list empties:
XACK tasks workers 1-1
XPENDING tasks workersChoosing between the three
| Stored? | Survives a dead worker? | Several readers? | |
|---|---|---|---|
| Pub/Sub | no | no | every subscriber gets a copy |
| List | yes | only with LMOVE |
one pops each item |
| Stream + group | yes | yes, pending until acked | split, or copy per group |