Memory Optimization

Difficulty: Advanced

Question

How does Redis optimize memory for small collections internally, and how do you reduce memory usage in a real deployment?

Answer

Redis stores small hashes, sets, sorted sets and lists in compact, contiguous encodings (listpack and intset) instead of full hash tables and skiplists. Once a collection crosses a configured size or element length, Redis converts it to the general-purpose structure. Compact encodings can use several times less memory for small objects, at the cost of O(N) scans inside each object, which is fine when N is small.

Encodings for each type

TypeCompact encodingConverts toThreshold settings (defaults)
Hashlistpackhashtablehash-max-listpack-entries 128, hash-max-listpack-value 64
Sorted setlistpackskiplist + hashtablezset-max-listpack-entries 128, zset-max-listpack-value 64
Set of integersintsethashtableset-max-intset-entries 512
Small set of stringslistpack (7.2+)hashtableset-max-listpack-entries 128, set-max-listpack-value 64
Listlistpack, then quicklist of listpacksquicklistlist-max-listpack-size -2 (8 KB per node)
Stringint, embstr (up to 44 bytes), rawn/an/a

Redis 7.0 replaced the older ziplist with listpack everywhere. Listpack fixes ziplist's cascading-update problem, where growing one entry could force every following entry's header to be rewritten. Old config names like hash-max-ziplist-entries still work as aliases, which is why you will see both in blog posts.

You can check any key with OBJECT ENCODING key. Conversion is one way: once a hash becomes a hashtable it does not shrink back to a listpack if you delete fields.

Why compact encodings save so much

A hashtable needs a bucket array, a separate allocation per entry, and pointers for each field and value. A listpack is one contiguous block of bytes with tiny length prefixes. For a user profile with 10 short fields, that removes dozens of allocations and pointer overhead. Intsets go further by storing integers in the smallest width that fits (16, 32 or 64 bits).

Practical techniques to cut memory

  • Bucket small keys into hashes: instead of 10 million user:12345:lastseen strings, store HSET lastseen:123 45 <ts>, grouping 100 users per hash so each stays a listpack. This is the classic trick that can shrink memory dramatically for tiny values.
  • Keep field values under the -value threshold; one long value converts the whole hash.
  • Use short but readable key names, and avoid storing JSON blobs when a hash would do.
  • Use specialised types: bitmaps for boolean flags, HyperLogLog for unique counts.
  • Always set TTLs on cache keys.
  • Compress large values in the client (gzip, LZ4) when they are rarely partially read.

Fragmentation

Redis uses jemalloc. After lots of deletes and updates, freed memory can be scattered, so the OS-level RSS stays high. Watch mem_fragmentation_ratio (used_memory_rss / used_memory) in INFO memory:

  • Around 1.0 to 1.5 is normal.
  • Well above 1.5 suggests fragmentation; enable activedefrag yes to let Redis defragment online.
  • Below 1.0 means the OS is swapping Redis memory, which is far worse for latency.

MEMORY USAGE key gives the bytes used by a key, and MEMORY DOCTOR gives a human-readable diagnosis.

Gotchas

  • Raising thresholds too high makes operations on those keys O(N) on large N, increasing latency.
  • Converting is triggered by a single large element, so one big field can cost you.
  • redis-cli --bigkeys and --memkeys find the keys worth optimising first.
How a hash changes encoding. A hash stays compact until it crosses a size or value-length threshold.
  1. HSET on new key: Created as a compact listpack.
  2. Up to 128 small fields: Stays listpack, very low overhead.
  3. 129th field or value over 64 bytes: Threshold crossed.
  4. Converted to hashtable: O(1) lookups, more memory per field.
  5. Fields deleted later: Stays a hashtable, no shrink back.

Code examples

Watching encodings change

redis-cli HSET user:1 name Asha city Pune
redis-cli OBJECT ENCODING user:1      # listpack

redis-cli SADD ids 1 2 3
redis-cli OBJECT ENCODING ids         # intset
redis-cli SADD ids hello
redis-cli OBJECT ENCODING ids         # listpack (7.2+), was hashtable before

redis-cli SET counter 100
redis-cli OBJECT ENCODING counter     # int

# Bytes used by a single key
redis-cli MEMORY USAGE user:1

# Fragmentation and totals
redis-cli INFO memory | grep -E 'used_memory_human|mem_fragmentation_ratio'

OBJECT ENCODING reveals which internal representation Redis picked. Exact MEMORY USAGE numbers vary by version and allocator.

Bucketing millions of tiny keys into hashes

// Instead of one string key per user:
//   SET user:1234567:lastseen 1718000000
// group 100 users per hash so each hash stays a listpack.
function bucketKey(userId) {
  const bucket = Math.floor(userId / 100);
  return { key: `lastseen:${bucket}`, field: String(userId % 100) };
}

async function setLastSeen(redis, userId, ts) {
  const { key, field } = bucketKey(userId);
  await redis.hset(key, field, ts);
}

async function getLastSeen(redis, userId) {
  const { key, field } = bucketKey(userId);
  return redis.hget(key, field);
}

Each hash holds at most 100 small fields, below the 128-entry listpack threshold, which avoids per-key overhead for millions of tiny values. The trade-off is that TTLs apply per hash, not per user (unless you use hash field expiry in 7.4+).

Key points

  • Small hashes, sets, sorted sets and lists use compact encodings (listpack, intset).
  • Redis 7.0 replaced ziplist with listpack; old ziplist config names are aliases.
  • Conversion happens on entry count or element size, and is one way.
  • Use OBJECT ENCODING and MEMORY USAGE to inspect keys.
  • mem_fragmentation_ratio well above 1.5 suggests fragmentation; below 1.0 suggests swapping.
  • Bucketing tiny keys into small hashes is a proven memory saver.

Common follow-up questions

  • Why is a sorted set stored as both a skiplist and a hashtable once it grows?
  • What was the cascading update problem in ziplist?
  • How would you find which keys are using the most memory?
  • What does activedefrag do and when would you enable it?
  • What are the trade-offs of raising hash-max-listpack-entries to 1000?

Interview tips

  • Name listpack, not just ziplist; it shows your knowledge is current with Redis 7.
  • Explain the trade-off: compact encodings save memory but make in-object operations O(N).
  • The hash bucketing trick is a great concrete example to bring up.

Concepts covered

Listpack, Intset, Skiplist, OBJECT ENCODING, Memory Fragmentation

More Redis & Caching questions