Video in progress

Strong Middle ⚡ Redis and caching

How is a small hash or sorted set stored inside Redis, and how does that affect memory?

Small collections are stored in a compact listpack (ziplist before Redis 7), in consecutive bytes. When the element count or size goes over a threshold, it converts to a real hash table or skiplist, and memory use goes up several times.

📖 Answer

Within a single logical type, Redis has several "encodings":

Type When small When large
Hash listpack hashtable
Sorted set listpack skiplist + hashtable
Set intset (numbers only) / listpack hashtable
List listpack quicklist

Checking:

HSET user:1 name Ali city Toshkent
OBJECT ENCODING user:1      -> "listpack"

The thresholds are configurable:

hash-max-listpack-entries 128
hash-max-listpack-value 64
zset-max-listpack-entries 128

Why does a large sorted set use two structures? The skiplist gives ordering by score and ZRANGE/ZRANK in O(log N), while the hash table gives ZSCORE in O(1). The cost is that every element is referenced from two places.

A practical trick: instead of making millions of tiny objects into separate string keys, group them into small hashes. For example, instead of user:1234567, a field 67 inside the hash user:12345. As long as each hash stays under 100 elements, it stays in listpack and the per-key overhead (about 50+ bytes per key) goes away. But then you can't put a separate TTL on each field (Redis 7.4 added HEXPIRE; a small hash with expiring fields stays in the listpackex encoding, but each field's expiry takes extra space).

Lookup in a listpack is linear, so setting the threshold too high hurts CPU.