TExcelTAD
Home › Redis › Redis Memory & Eviction

Redis Memory & Eviction

Memory is Redis's most precious resource. This lesson shows how to see what your data costs, how Redis saves memory with compact encodings, and what happens when the configured limit is reached: the eviction policies.

Measuring memory

MEMORY USAGE key estimates how many bytes a key and its value take, including Redis's own overhead. INFO memory shows the totals for the whole server (used_memory, used_memory_peak, mem_fragmentation_ratio, ...).

redis · try it yourself
SET short "hi"
SET longer "this value is a fair bit longer than the first one, about 80 bytes of text...."
MEMORY USAGE short
MEMORY USAGE longer
STRLEN longer
redis> SET short "hi"
OK
redis> SET longer "this value is a fair bit longer than the first one, about 80 bytes of text...."
OK
redis> MEMORY USAGE short
(integer) 30
redis> MEMORY USAGE longer
(integer) 107
redis> STRLEN longer
(integer) 78

Even a two-byte value costs dozens of bytes, because every key needs a dictionary entry, an object header and the key name itself. Millions of tiny keys add up quickly.

Compact encodings

Small collections are stored in a dense listpack (one contiguous memory block) instead of a hash table or a linked structure. Redis converts them automatically when they grow beyond configurable thresholds:

Type Compact encoding Converted when ... (defaults)
Hash listpack more than 512 fields or a value longer than 64 bytes
Set of integers intset more than 512 members or a non-integer member
Set listpack more than 128 members or a member longer than 64 bytes
Sorted set listpack more than 128 members or a member longer than 64 bytes
List listpack larger lists become a quicklist of listpacks
redis · try it yourself
HSET user:1 name Ada lang python
OBJECT ENCODING user:1
MEMORY USAGE user:1
HSET user:1 bio "A very long biography that is definitely longer than sixty-four bytes in total."
OBJECT ENCODING user:1
MEMORY USAGE user:1
CONFIG GET hash-max-listpack-entries
redis> HSET user:1 name Ada lang python
(integer) 2
redis> OBJECT ENCODING user:1
"listpack"
redis> MEMORY USAGE user:1
(integer) 57
redis> HSET user:1 bio "A very long biography that is definitely longer than sixty-four bytes in total."
(integer) 1
redis> OBJECT ENCODING user:1
"hashtable"
redis> MEMORY USAGE user:1
(integer) 302
redis> CONFIG GET hash-max-listpack-entries
1) "hash-max-listpack-entries"
2) "512"

One value longer than 64 bytes was enough to convert the hash to a real hash table, and its memory usage jumped from 57 to 302 bytes. (The last line shows the field-count threshold, 512 in Redis 8.8.) Keeping values short and collections small pays off.

Memory-saving techniques

Technique Example
Short but readable key names u:1001:sess instead of application:user:1001:session for billions of keys
Group tiny values into hashes HSET counters:100 7 "x" instead of a key per counter
Use the right structure a bitmap or HyperLogLog instead of a set of IDs
Set TTLs data you no longer need disappears on its own
Compress large values in the client gzip or msgpack JSON blobs
Avoid huge single keys split a 10-million-member set into buckets

The "group into hashes" trick works because small hashes are listpacks. Compare a thousand separate keys with the same data spread over ten hashes of a hundred fields:

redis · try it yourself
EVAL "for i = 0, 999 do redis.call('SET', 'item:' .. i, 'v') end" 0
EVAL "for i = 0, 999 do redis.call('HSET', 'bucket:' .. math.floor(i / 100), i % 100, 'v') end" 0
DBSIZE
EVAL "local t = 0 for i = 0, 999 do t = t + redis.call('MEMORY', 'USAGE', 'item:' .. i) end return t" 0
EVAL "local t = 0 for i = 0, 9 do t = t + redis.call('MEMORY', 'USAGE', 'bucket:' .. i) end return t" 0
redis> EVAL "for i = 0, 999 do redis.call('SET', 'item:' .. i, 'v') end" 0
(nil)
redis> EVAL "for i = 0, 999 do redis.call('HSET', 'bucket:' .. math.floor(i / 100), i % 100, 'v') end" 0
(nil)
redis> DBSIZE
(integer) 1010
redis> EVAL "local t = 0 for i = 0, 999 do t = t + redis.call('MEMORY', 'USAGE', 'item:' .. i) end return t" 0
(integer) 31890
redis> EVAL "local t = 0 for i = 0, 9 do t = t + redis.call('MEMORY', 'USAGE', 'bucket:' .. i) end return t" 0
(integer) 5340

The thousand separate keys need 31,890 bytes, while the same values in ten listpack hashes need 5,340: about six times less.

maxmemory and eviction policies

maxmemory sets a limit (for example maxmemory 2gb). When a write would exceed it, Redis applies the maxmemory-policy:

Policy What Redis does at the limit
noeviction (default) refuses writes with an OOM error; reads still work
allkeys-lru evicts the least recently used key, any key
allkeys-lfu evicts the least frequently used key
allkeys-random evicts a random key
volatile-lru / volatile-lfu / volatile-random the same, but only among keys with a TTL
volatile-ttl evicts the key with the nearest expiry
redis · try it yourself
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
CONFIG SET maxmemory 100mb
CONFIG SET maxmemory-policy allkeys-lru
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
redis> CONFIG GET maxmemory
1) "maxmemory"
2) "0"
redis> CONFIG GET maxmemory-policy
1) "maxmemory-policy"
2) "noeviction"
redis> CONFIG SET maxmemory 100mb
OK
redis> CONFIG SET maxmemory-policy allkeys-lru
OK
redis> CONFIG GET maxmemory
1) "maxmemory"
2) "104857600"
redis> CONFIG GET maxmemory-policy
1) "maxmemory-policy"
2) "allkeys-lru"

maxmemory 0 means "no limit". Rules of thumb:

  • A cache: allkeys-lru or allkeys-lfu. Every key is expendable, so evict what is least useful.
  • A primary data store (sessions, queues): noeviction, and alert on memory, because silently losing a queue entry is worse than a failed write.
  • A mix: volatile-lru, giving TTLs only to cache keys. Simpler and safer: use two separate Redis instances.

How approximate LRU works

Redis does not keep a perfect LRU list of all keys (that would cost memory). Each key stores a 24-bit "last access" clock. On eviction Redis samples a few keys (maxmemory-samples, default 5), keeps the best candidates in a small pool, and evicts the oldest. This simulation compares exact LRU with sampled eviction on a tiny dataset:

python · try it yourself
import random

rng = random.Random(7)
keys = [f"k{i}" for i in range(20)]
last_access = {k: i for i, k in enumerate(keys)}   # k0 is the oldest, k19 the newest

def evict_exact():
    return min(last_access, key=last_access.get)

def evict_sampled(samples):
    candidates = rng.sample(sorted(last_access), samples)
    return min(candidates, key=last_access.get)

print("exact LRU evicts:", evict_exact())
for samples in (3, 5, 10):
    picks = [evict_sampled(samples) for _ in range(1000)]
    ages = [last_access[k] for k in picks]
    oldest_share = sum(1 for a in ages if a < 5) / len(ages)
    print(f"samples={samples:>2}: evicts one of the 5 oldest keys {oldest_share:.0%} of the time")
exact LRU evicts: k0
samples= 3: evicts one of the 5 oldest keys 60% of the time
samples= 5: evicts one of the 5 oldest keys 78% of the time
samples=10: evicts one of the 5 oldest keys 99% of the time

More samples get closer to perfect LRU at the cost of a little CPU. LFU works the same way but stores a small, slowly decaying access frequency counter instead of a time.

Test yourself

What happens under the default noeviction policy when memory is full?

  1. The oldest key is deleted
  2. Writes fail with an OOM error
  3. Redis restarts
  4. Keys move to disk

Which policy suits a Redis instance used only as a cache?

  1. noeviction
  2. allkeys-lru
  3. volatile-ttl with no TTLs set
  4. maxmemory 0

Why can grouping many small values into hashes save memory?

  1. Hashes are compressed with gzip
  2. Small hashes use the compact listpack encoding with less per-entry overhead than separate keys
  3. Hashes are stored on disk
  4. Hash fields cannot expire