🔴 Redis Advanced

How do you optimize Redis memory usage for a large-scale deployment?

Answer

Optimizing Redis memory at scale requires strategies at multiple levels. Data structure encoding: keep collections below listpack thresholds by chunking large structures. Key naming: use short, consistent key names — long key names waste memory; u:42:sess is more efficient than user:42:session at scale. Expiry policy: always set TTLs on cache keys; monitor the keyspace for keys without TTL using DEBUG SLEEP and custom scanning. Serialization: use compact binary formats (MessagePack, Protocol Buffers) instead of JSON for String values — JSON is verbose. maxmemory and eviction: set maxmemory to leave 10–25% of RAM free for OS and Redis internal overhead; choose allkeys-lfu for caches. Memory analysis: use MEMORY USAGE key, redis-cli --memkeys, or tools like RedisInsight to find the largest consumers. Redis modules: RedisJSON stores JSON more compactly than a serialized String. Monitor mem_fragmentation_ratio and schedule restarts if fragmentation is severe (>1.5).