Redis maxmemory and eviction policies for cache workloads
- Set a limit
- Choose a policy by workload
- Do not mix queue and cache in one instance
- Watch the numbers
- Persistence for caches
Redis without a memory limit will grow until the server runs out of RAM. On a small VPS, that usually ends with the kernel killing Redis or, worse, your database. Two settings, maxmemory and maxmemory-policy, decide what happens instead.
Set a limit
Pick a limit that leaves room for everything else on the server, plus overhead. Redis uses more than the configured value for buffers and fragmentation, so set it to roughly 70 to 80 percent of what you can spare:
services:
cache:
image: redis:7
command: ["redis-server", "--maxmemory", "256mb",
"--maxmemory-policy", "allkeys-lru"]
deploy:
resources:
limits:
memory: 384m
The container memory limit is a backstop. maxmemory is what makes Redis evict keys politely before the container limit is hit.
Choose a policy by workload
- allkeys-lru: evict the least recently used keys. The right default for a pure cache.
- allkeys-lfu: evict the least frequently used keys. Better when a small set of keys is very hot and many are touched once.
- volatile-lru or volatile-ttl: only evict keys with an expiry. Useful when cache keys have TTLs and other keys must never be evicted.
- noeviction: refuse writes when full. The right choice for queues, sessions you cannot lose, and job data.
The default is noeviction. For a cache, that means writes start failing with “OOM command not allowed” once the limit is reached, which applications often handle badly.
Do not mix queue and cache in one instance
Job queues such as Sidekiq, BullMQ or Celery need noeviction. Caches need an eviction policy. If both share one Redis, either the cache cannot evict or the queue loses jobs. Run two instances with different settings. Each is cheap.
Watch the numbers
redis-cli INFO memory | grep -E "used_memory_human|maxmemory_human|mem_fragmentation_ratio"
redis-cli INFO stats | grep -E "evicted_keys|keyspace_hits|keyspace_misses"
Rising evicted_keys with a falling hit rate means the cache is too small for the working set. A fragmentation ratio well above 1.5 suggests enabling activedefrag or restarting during a quiet period.
Persistence for caches
A pure cache can run without persistence. Disable RDB snapshots with --save "" to avoid fork spikes on a small server. After a restart the cache warms again from the database.
For security, persistence and backups when Redis holds data that matters, see this guide to running Redis in production.
Disclosure: I help build Peon.
Write a comment