When Redis keeps evicting keys, it usually means the memory is full, and Redis is forced to remove old keys to store new ones. Instead of just adding more memory, the best way is to optimize how you use the cache 👇
🧠 1. Use Proper TTL (Expiry Times)
Many apps don’t set expiry times, which fills the cache with stale data.
// Good practice — set expiry for each key
await redis.set("user:123", JSON.stringify(userData), "EX", 3600); // expires in 1 hour
✅ This keeps your cache clean and automatically removes old data.
🧠 2. Evict Less Important Data First
Redis eviction policy decides which keys to remove when memory is full.
You can choose smarter policies like allkeys-lru (Least Recently Used) instead of the default.
In redis.conf:
maxmemory-policy allkeys-lru
✅ This removes the least recently used keys instead of critical ones.
🧠 3. Cache Only What’s Needed
Avoid dumping large or unnecessary data in Redis.
For example, don’t cache entire user objects if you only need a few fields.
❌ Bad:
await redis.set("user:123", JSON.stringify(bigUserObject));
✅ Better:
await redis.set("user:123:name", user.name);
🧠 4. Use Compression for Large Data
If the data is big, compress it before storing to reduce memory usage.
import zlib from "zlib";
const compressed = zlib.gzipSync(JSON.stringify(bigData));
await redis.set("data:large", compressed);
🧠 5. Use a Separate Cache Layer for Critical Data
If you have mixed data (like critical session data and temporary search results), separate them using different databases or keys.
// DB 0 for sessions
await client.select(0);
await client.set("session:abc", "active");
// DB 1 for temp data
await client.select(1);
await client.set("temp:search", "results");
✅ This ensures important data doesn’t get evicted by temporary data.
🧠 6. Monitor and Tune Properly
Regularly check memory usage with:
INFO memory
and remove unused keys or lower TTL where possible.
✅ In short:
- Set proper TTL for every cached item.
- Use smarter eviction policies.
- Cache only what’s needed.
- Compress large data.
- Separate critical from non-critical cache.
- Monitor and tune regularly.
👉 This approach keeps your Redis cache healthy without just increasing RAM.