Skip to content

Chapter 3 of 7

Lists and Hashes

The Redis List is an ordered collection of strings, ordered by insertion. Small lists are stored in a compact structure called a listpack, which replaced the older ziplist representation. Insertion at the head with LPUSH is constant time, \(O(1)\), making lists well suited to use as queues or stacks. Blocking variants exist for consumer-style workloads: BLPOP and BRPOP block the client until an element becomes available or a timeout elapses, which makes it possible to coordinate producers and consumers without busy-waiting. The direction of insertion is chosen with LPUSH (insert at the head, or left end) versus RPUSH (insert at the tail, or right end).

Several commands shape lists in place. LTRIM removes all elements outside a specified index range, leaving only the requested window. LLEN reports the current length. The classic producer/consumer pattern uses LPUSH to enqueue and BRPOP to dequeue, giving a simple message queue in just two commands. A second pattern, the recent-activity feed, is built by LPUSH-ing new items and then calling LTRIM to keep only the most recent N, so the list automatically stays bounded in size. LMOVE, the modern replacement for RPOPLPUSH, atomically pops an element from one list and pushes it to another, with the direction configurable.

A Hash maps field-value pairs within a single key, which is a natural fit for objects such as users, products, or sessions. Reading a single field with HGET is constant time, \(O(1)\). To inspect an entire hash, HGETALL returns all fields and values as a flat list, while HVALS returns only the values. Numeric updates on a field can be done atomically with HINCRBY, which increments the integer value of a field. HDEL removes one or more fields, and from Redis 7.4 onward, HEXPIRE can attach a TTL to an individual hash field. Choosing a hash to represent an object instead of many separate string keys typically uses less memory and allows partial-field reads and writes, which is far more efficient than fetching and rewriting the entire object.

All chapters
  1. 1Redis Fundamentals and the String Type
  2. 2Sets and Sorted Sets
  3. 3Lists and Hashes
  4. 4Streams, Pub/Sub, and Messaging
  5. 5Specialized Data Structures
  6. 6Memory Management and Persistence
  7. 7Replication, Clustering, Transactions, and Operations

Drill it

Reading is not remembering. These come from the Redis Data Structures And Use Cases deck:

Q

What does the acronym Redis stand for?

REmote DIctionary Server

Q

In which language is Redis written?

C

Q

What is the default port number for Redis?

6379

Q

How is Redis primarily classified architecturally?

An in-memory key-value data store used as a database, cache, and message broker