Memory optimization.

Inspect

redis-cli INFO memory
redis-cli MEMORY USAGE key
redis-cli MEMORY STATS
redis-cli --bigkeys
redis-cli --memkeys
redis-cli --hotkeys           # needs LFU

maxmemory

maxmemory 4gb
maxmemory-policy allkeys-lru

Recommend setting; default no limit → OOM kills.

Eviction policies

  • noeviction: error on full.
  • allkeys-lru / allkeys-lfu: across all keys.
  • volatile-lru / -lfu: only TTL keys.
  • volatile-ttl: nearest expiry first.
  • volatile-random / allkeys-random.

For cache: allkeys-lru typical.

Encodings (compact storage)

Small structures use compact encodings:

OBJECT ENCODING key

Returns: embstr, raw, int, listpack, hashtable, quicklist, intset, skiplist.

Tunables:

hash-max-listpack-entries 128
hash-max-listpack-value 64
list-max-listpack-size -2
set-max-intset-entries 512
zset-max-listpack-entries 128
zset-max-listpack-value 64

Below these thresholds: compact ziplist/listpack (memory-efficient, slower). Above: hashtable/skiplist (memory-heavy, faster).

Tips

  • Use hashes for objects (cheaper than separate keys).
  • Use sets for unique collections.
  • Use bitmaps for boolean per-id.
  • Use HyperLogLog for cardinality.
  • Avoid long key names (kept in RAM).
  • Avoid huge single values.

Compress

Compress values >1KB:

import zstandard

cctx = zstandard.ZstdCompressor()
redis.set(key, cctx.compress(big_data))

Sample big keys

redis-cli --bigkeys
# Or
redis-cli --memkeys

SCAN + size

redis-cli --scan --pattern "*" | xargs -L 1 redis-cli MEMORY USAGE

Reduce overhead

  • Use integer keys when possible (smaller).
  • Group related fields in hash, not separate keys.
  • Short keys: u:1:p vs user:1:profile.

RAM vs disk swap

Don’t let Redis swap. Set vm.overcommit_memory=1. Use maxmemory.

Active expiration

Redis lazily expires + samples. Tune:

hz 10                                # default 10/sec
maxmemory-eviction-tenacity 10

Forking cost

BGSAVE / replication forks: COW pages. Big dataset = big fork latency. Mitigate:

  • repl-diskless-sync yes.
  • Less frequent BGSAVE.
  • Bigger RAM headroom.

Common mistakes

  • No maxmemory → OOM.
  • Tiny TTL on huge values → constant churn.
  • Encoding flipped (hash → hashtable) → memory spike.
  • 1M+ hot key → all reads to one shard.
  • Storing big binary blobs.

Read this next

If you want my memory tuning checklist, it’s at rajpoot.dev .


Building something AI-, backend-, or data-heavy and want a second pair of eyes? I do consulting and freelance work — see my projects and ways to reach me at rajpoot.dev .