Video in progress

You're paying a lot per month for Redis memory and the dataset keeps growing. What technical decisions do you consider to cut the cost?

First I measure what is taking the space: size by key prefix, keys without a TTL, one-time keys. Then the cheap wins: shorter TTLs, grouping small objects into hashes, making values more compact or compressing them, HyperLogLog or Bloom where an exact count isn't needed; and finally moving part of the data out of Redis.

📖 Answer

On one project we analyzed a 120 GB cluster and found that 40% of the memory was keys of an old feature that nobody reads, left without a TTL. Optimization always starts with measuring.

Measuring: sample with SCAN on a replica, then group by prefix using MEMORY USAGE and OBJECT IDLETIME (in LRU mode), or analyze the RDB file offline. The result: prefix → size → last access.

The cheap wins:

  • put a TTL on keys without one; delete the keys of obsolete features (with UNLINK, slowly);
  • key names: up: instead of application:production:user-profile:, which is gigabytes at 100 million keys;
  • value format: long field names in JSON, unneeded fields. MessagePack/Protobuf, or just removing the unneeded fields. For big values, compression (LZ4/Snappy), saving 3-5 times at the cost of CPU;
  • group millions of small strings into bucketed hashes; thanks to the listpack encoding, the per-key overhead goes away.

Probabilistic structures:

  • the count of unique visitors: PFADD instead of SADD for each ID: a HyperLogLog counts billions of elements in about 12 KB with an error of about 0.81%;
  • a Bloom filter for "does this element exist";
  • a bitmap (SETBIT) for boolean flags: the "visited today" state of 10 million users is about 1.2 MB.

Architecture-level decisions:

  • does everything have to be in RAM? Move the long tail (rarely read) data to the DB or a disk-based key-value store, and keep only the hot part in Redis;
  • set maxmemory based on the working set, not the dataset, and rely on LFU eviction;
  • the replica count: each replica is one more copy of the memory. Does a cache need 2 replicas?

Watch every change together with the hit ratio and latency: if you cut memory but raise the DB load, the total cost doesn't go down.