Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 42 ยท Core Data Types

Lists

Redis lists: LPUSH and RPUSH, LPOP and RPOP, LRANGE, LTRIM, LINSERT, blocking BLPOP, LMOVE, capped lists for recent items and the O(N) pitfalls.

A Redis list is an ordered sequence of strings. You add and remove items at either end, read slices by position and keep the order you inserted. That makes lists a natural fit for queues, stacks, activity feeds and "last N items" views. Adding or removing at the head or the tail takes constant time no matter how long the list is, which is the property to remember when you design with them.

This lesson covers pushing and popping, reading ranges, trimming, editing the middle, blocking pops for work queues and LMOVE for moving items safely between lists. Real syntax shows in read-only blocks. The runnable examples use the JavaScript MiniRedis emulator from What Is Redis?, extended with list commands and a small model of blocked clients. It follows real Redis's command semantics but not its network or performance.

Pushing and popping

LPUSH adds to the head (left) and RPUSH to the tail (right). Both accept several values and return the new length. LPOP and RPOP remove and return an item from the matching end, or nil when the list is empty or missing. Since Redis 6.2 they also take a count and then return an array.

TEXT
127.0.0.1:6379> RPUSH queue job-1 job-2 job-3
(integer) 3
127.0.0.1:6379> LPUSH queue job-0
(integer) 4
127.0.0.1:6379> LPOP queue
"job-0"
127.0.0.1:6379> RPOP queue 2
1) "job-3"
2) "job-2"

A subtle detail: LPUSH stack a b c pushes a, then b, then c to the head, so the list reads c b a. The values appear in reverse order of the arguments. A stack uses LPUSH with LPOP; a queue uses RPUSH with LPOP (or the mirror image).

Redis also deletes a list key as soon as it becomes empty. There is no such thing as an empty list stored under a key, so EXISTS returns 0 after the last LPOP.

Both ends are cheap

LPUSH / LPOP Add or remove at the head.
RPUSH / RPOP Add or remove at the tail.

Constant time, whatever the list length.

1 / 3

Reading and editing

  • LLEN key returns the length (0 for a missing key).
  • LRANGE key start stop returns a slice. Both ends are inclusive, 0 is the head, and negative numbers count from the tail, so LRANGE key 0 -1 means the whole list.
  • LINDEX key index returns one element by position, with negatives from the tail, or nil.
  • LSET key index value replaces an element; it errors if the key is missing or the index is out of range.
  • LINSERT key BEFORE|AFTER pivot value inserts next to the first element equal to pivot. It returns the new length, -1 if the pivot is missing and 0 if the key is missing.
  • LREM key count value removes occurrences of a value: count > 0 from the head, count < 0 from the tail, 0 all of them.
  • LPOS key element returns the position of a matching element (Redis 6.0 and later).

Try it: a list tour

JS Pushing, popping and editing a list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the results against the rules above: LINSERT with a pivot that does not exist answers -1, LREM stack 2 a removed two a values, and once the list was emptied by LPOP stack 10 the key no longer existed. Pushing onto a key that holds a string fails with WRONGTYPE.

Capped lists: the latest N items

A very common pattern keeps only the most recent items, such as the last 100 page views or the last 10 notifications. Push the new item and then trim:

TEXT
127.0.0.1:6379> LPUSH recent:user:42 "viewed /pricing"
(integer) 1
127.0.0.1:6379> LTRIM recent:user:42 0 99
OK

LTRIM key start stop keeps only the range you name and discards the rest, so the list never grows beyond 100. Because the two commands are separate, a client that crashes between them leaves one extra item, which is harmless; if you need both to happen together, run them in a transaction. To read the feed, LRANGE recent:user:42 0 9 returns the ten newest items.

Moving items safely with LMOVE

LMOVE source destination LEFT|RIGHT LEFT|RIGHT removes an item from one end of the source and pushes it onto one end of the destination, atomically, returning the item. It is how you build a reliable queue: a worker takes a job off jobs and puts it on its own processing list in one step. If the worker crashes, the job is still on processing and can be recovered. When it finishes, it removes the job with LREM. (RPOPLPUSH is the older command that does the same thing in one direction.) Full queue designs appear in Queues, locks and leaderboards.

Blocking pops for work queues

Polling an empty queue in a loop wastes CPU and adds delay. BLPOP key [key ...] timeout and BRPOP solve this: if one of the lists has an item, the pop works like LPOP and returns [key, value]. If all are empty, the client waits (is blocked) until another client pushes, or until the timeout in seconds passes, in which case the reply is nil. A timeout of 0 waits forever.

TEXT
127.0.0.1:6379> BLPOP inbox 5
(nil)
(5.03s)

Details worth knowing:

  • Several clients can wait on the same key. The longest-waiting client is served first.
  • With several keys, Redis checks them in order and takes from the first non-empty one.
  • Blocking commands only block your connection, not the server, so each worker needs its own connection.
  • BLMOVE is the blocking version of LMOVE (Redis 6.2).
  • Inside a transaction, blocking commands never wait.

The emulator cannot wait in real time, so it models blocking with a list of waiting clients. A blocking pop on an empty list registers the client, and any later push serves waiters in order and prints a line starting with an asterisk. It ignores timeouts.

Try it: capped feeds, reliable moves and blocking

JS LTRIM, LMOVE and blocked workers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first LPUSH onto inbox wakes worker-1, which waited longest. The second push delivers email-2 to worker-2 and leaves email-3 in the list. worker-3 then pops email-3 immediately because data is available, and its next BLPOP blocks because the list is empty again.

SORT: ordering a list (or set) on the fly

Lists keep insertion order, but sometimes you need them ranked: IDs by price, names alphabetically, products by a rating stored elsewhere. SORT reads a list, a set or a sorted set and returns the elements in order without changing the source:

Text
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC | DESC] [ALPHA] [STORE destination]
  • By default SORT treats every element as a number and sorts ascending. A non-numeric element makes it fail with ERR One or more scores can't be converted into double. Add ALPHA to compare as strings.
  • DESC reverses the order, and LIMIT offset count pages through the result.
  • BY pattern sorts by an external key. Each element is substituted for the * in the pattern, and the value found there is used as the sort weight. BY weight_* looks up weight_7 for element 7. A hash field is reached with ->, as in BY product:*->price. BY nosort skips sorting (useful with GET to fetch data in the natural order).
  • GET pattern returns the value of the external key instead of (or in addition to) the element. GET # returns the element itself. Several GET options return several values per element, flattened into one reply.
  • STORE destination saves the result as a new list and returns its length, which is handy for caching a sorted page.
Text
RPUSH products 101 102 103
HSET product:101 name Lamp price 40
HSET product:102 name Desk price 250
HSET product:103 name Chair price 90
SORT products BY product:*->price DESC GET #  GET product:*->name GET product:*->price

Redis 7.0 added SORT_RO, a read-only variant that rejects STORE, so it is allowed on replicas and for read-only ACL users.

SORT has O(N+M*log(M)) cost, so sorting a long list on every request blocks the server for everyone. Sort small collections, cap the work with LIMIT, store the result with STORE and expire it, or keep the data in a sorted set that is always ordered. In a Redis Cluster, BY and GET patterns must resolve to keys in the same hash slot as the sorted key, so they are rarely usable there.

The model below reproduces SORT with BY, GET, ALPHA, DESC, LIMIT and STORE over a small in-memory data set. It is a model of the command, not a Redis server.

JS SORT with BY, GET, ALPHA and STORE

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The ties for 90 (103 and 104) fall back to comparing the elements, which is what Redis does so the output is deterministic. Without ALPHA the names list fails exactly like the real command, and with it uppercase letters sort before lowercase, because the comparison is byte by byte (Apple before fig).

Performance and pitfalls

Lists are stored as a linked list of small compact blocks, which keeps both ends fast and memory use modest. A list can hold more than four billion elements, but that does not mean it should.

  • Positions in the middle are O(N). LINDEX, LINSERT, LSET (except near the ends) and LREM walk the list. On a list with millions of items, a single call can stall the server.
  • LRANGE 0 -1 on a huge list builds an enormous reply. Page through with a range such as 0 99, and cap lists with LTRIM.
  • Need to look things up by value or by score? Use a set, hash or sorted set. A list is a poor index.
  • A list is not durable messaging. Once an item is popped it is gone; use the LMOVE pattern or streams when you must not lose work.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After LPUSH stack a b c, what does LRANGE stack 0 -1 return?

    Each value is pushed to the head in turn, so the last argument ends up first.
  2. 2. What happens to a list key when its last element is popped?

    Redis never stores an empty list. The key is removed as soon as the list becomes empty.
  3. 3. Which pair builds a bounded feed of the 100 most recent items?

    LPUSH adds the newest item at the head and LTRIM 0 99 discards everything beyond the first 100.
  4. 4. What does BLPOP jobs 0 do when the list jobs is empty?

    A timeout of 0 means wait forever. Only the calling connection waits; the server keeps serving others.
  5. 5. Why is LMOVE useful for a reliable queue?

    The job leaves the queue and enters the processing list in one atomic step, so a crashed worker's job can be found and retried.

Summary

  • Lists are ordered strings with O(1) push and pop at both ends; LPUSH a b c reads c b a.
  • LRANGE uses inclusive indexes and negative positions; LTRIM keeps a range and caps lists.
  • LINDEX, LINSERT, LREM and middle LSET are O(N); avoid them on long lists.
  • A list key disappears when it becomes empty.
  • BLPOP/BRPOP block one connection until data arrives, serving the longest-waiting client first.
  • LMOVE moves an item atomically between lists, the basis of reliable queues.

Next, store objects with named fields in Hashes.