Redis ships with maxmemory 0, which means no limit. It keeps adding keys until the container runs out of room. Two settings and one alert stop it. The policy depends on what the instance holds.
“Redis OOM” names two different failures. Find out which one you have before you change anything:
- The kernel kills Redis. The container reaches its memory limit, and the OOM killer ends the process with exit code 137. Kubernetes reports
OOMKilledas the last termination reason. - Redis refuses writes. Redis has reached
maxmemoryand has nothing it may evict. Write commands fail withOOM command not allowed when used memory > 'maxmemory', and reads keep working.
What breaks at peak
Peak traffic brings more sessions, more cached pages and more queued jobs. If nothing caps the dataset, used_memory grows until the container limit stops it. The kernel kills Redis, and your client library starts throwing connection errors. Every request that needed the cache falls through to the database at its busiest moment. If PostgreSQL then runs out of connections, put PgBouncer in front of it.
Restarting brings the same crash back. With persistence off, Redis comes back empty and your app refills the cache under full load. With RDB or AOF on, Redis reloads the dataset that just outgrew the container. On Kubernetes, repeated OOM kills push the pod into CrashLoopBackOff, and each back-off keeps Redis down for longer.
A cap with the wrong policy fails a different way. The default policy is noeviction. A volatile-* policy behaves the same when your keys carry no TTL, because it may only evict keys that have one. In both cases Redis stays up and returns the OOM error on every write.
The Redis maxmemory and eviction policy config
This example suits a pure cache in a container with a 4Gi memory limit and persistence off. Redis reads 3gb as 3 GiB, because its units are 1024-based, so the cap sits at three quarters of the limit:
maxmemory 3gb
maxmemory-policy allkeys-lru
maxmemory-samples 5
Four changes make the defaults safe:
- Pick the policy from the role of the instance.
- Size
maxmemorybelow the container limit. - Give replicas the same limits as the primary.
- Apply the change at runtime, policy first.
Pick the policy. Redis has eight eviction policies, and Redis 8.6 adds two more:
| Policy | What it evicts | Use when |
|---|---|---|
noeviction | Nothing. Writes fail with the OOM error. | Queues, primary data and sessions you can’t lose |
allkeys-lru | Any key, idle longest first | A pure cache. The safe default. |
allkeys-lfu | Any key, least often accessed first, reads and writes both | A cache where a small hot set takes most traffic |
allkeys-random | Any key, at random | A cache with even access across keys |
volatile-lru | Keys with a TTL, idle longest first | A mixed instance where every expendable key has a TTL |
volatile-lfu | Keys with a TTL, least often accessed first | The same, with a hot set |
volatile-random | Keys with a TTL, at random | The same, with even access |
volatile-ttl | Keys with a TTL, shortest remaining TTL first | Your code gives short TTLs to the keys it can lose first |
allkeys-lrm | Any key, least recently modified first. Redis 8.6+, not in Valkey or most managed services. | A cache whose reads don’t prove a key is current, so stale writes should go first |
volatile-lrm | Keys with a TTL, least recently modified first. Same availability. | The same, on a mixed instance |
Then match the policy to what the instance holds:
- Pure cache. On a pure cache I start with
allkeys-lru, and move toallkeys-lfuonly when a few keys take most of the traffic. Any key can go, and your app rebuilds it on the next miss. - Queue or primary store. Sidekiq and BullMQ need
noeviction, and BullMQ warns at startup if it finds another policy. Sessions and data you can’t rebuild need it too. An evicted job disappears with no error, while a refused write gives your app an error it can retry. Pairnoevictionwithmaxmemoryand an alert at about 85% of the cap. - Mixed instance. A
volatile-*policy works only when every key you can lose carries a TTL. Locks carry a TTL too (SET lock:job42 owner NX PX 30000). Undervolatile-lru, Redis can evict a held lock and let two workers run one job. I’d rather split the instance: queues and locks on their ownnoevictionRedis, the cache on anallkeys-*one.
Redis approximates LRU. On each eviction it samples maxmemory-samples keys (default 5), keeps a pool of candidates and evicts the one idle longest. Raising samples to 10 gets closer to true LRU for a little more CPU. LFU keeps a small counter per key. lfu-log-factor (default 10) sets how many accesses saturate it, and lfu-decay-time (default 1 minute) sets how fast it drops for idle keys. If you store large hashes, sets or lists, turn on lazyfree-lazy-eviction yes. Redis then frees evicted values in a background thread and keeps the main thread serving.
Valkey takes the same settings and the same eight policies. Valkey rejects the two LRM policies.
Size the cap. maxmemory limits the memory Redis counts, and the process needs more than that:
- For a pure cache with persistence off, set
maxmemorynear 75% of the container limit. - With RDB snapshots, AOF rewrites or replicas on a write-heavy instance, cap it nearer 50%. A background save forks Redis, and the kernel copies every page your writes touch during the save. A busy instance can need close to double its dataset while the fork runs.
- Output buffers for normal and pub/sub clients count against
maxmemory, so one slow subscriber can trigger evictions. Replica output buffers and the AOF buffer don’t count, andINFO memoryreports them asmem_not_counted_for_evict. Bound client buffers withclient-output-buffer-limit. On Redis 7 or later,maxmemory-clientscaps memory for all clients together. - Check
mem_fragmentation_ratioinINFO memoryon a busy instance. It divides resident memory byused_memory. Near 1.0 is healthy, and 1.5 means the process holds half again what Redis counts. Divide your cap by the ratio, or turn onactivedefrag yeson a jemalloc build, the default on Linux.
As a starting rule, take container limit × 0.75 for a cache or × 0.5 with persistence, then divide by your fragmentation ratio.
Give replicas the same room. replica-ignore-maxmemory defaults to yes, so a replica never evicts on its own. It deletes keys only when the primary sends the evictions. A replica with a smaller container gets OOM-killed first. After a failover it becomes the primary and starts evicting with less room. Give every replica the same container limit and maxmemory as the primary.
On managed Redis, change the policy in the service settings. ElastiCache sets maxmemory from the node type, and you can’t raise it. Its default policy is volatile-lru, which refuses writes once memory fills if your cache keys have no TTL. Set maxmemory-policy in a custom parameter group. ElastiCache holds back headroom with reserved-memory-percent, 25% by default, so raise it for backups on a write-heavy cluster. Azure Cache for Redis and Google Cloud Memorystore for Redis both expose maxmemory-policy as a setting, and Azure reserves headroom with maxmemory-reserved.
Apply the change, policy first. Save the current values, then set the policy before the cap:
redis-cli CONFIG GET 'maxmemory*' > redis-maxmemory-before.txt
redis-cli CONFIG SET maxmemory-policy allkeys-lru
redis-cli CONFIG SET maxmemory 3gb
redis-cli CONFIG REWRITE
Under noeviction, a cap set first refuses writes the moment it drops below used_memory. With the policy set first, Redis evicts instead. Since Redis 6.2, eviction runs in small slices, paced by maxmemory-eviction-tenacity. If used_memory already sits above the new cap, Redis evicts until it is under the cap, and command latency rises while it works. Lower the cap in steps, and watch evicted_keys and latency between them.
CONFIG REWRITE writes the running config to redis.conf, so a restart keeps it. It fails with ERR The server is running without a config file if Redis started without one. On Kubernetes, change the ConfigMap or Helm values as well, or the next pod starts with the old settings.
Test it on your system
Use a staging instance with the same container limit, Redis version and persistence settings as production. Fill it past maxmemory with values and TTLs that look like your real keys. Run MEMORY USAGE on a sample of production keys to get realistic sizes.
memtier_benchmark lets you set value sizes, a read and write ratio and TTLs. Raise --key-maximum until the key count times the average value size passes your cap:
memtier_benchmark -s redis-staging -p 6379 --protocol=redis \
--ratio=1:4 --data-size-range=200-4000 \
--key-pattern=R:R --key-maximum=20000000 \
--expiry-range=300-3600 \
--clients=20 --threads=4 --test-time=600
For a mixed instance, run a second copy without --expiry-range at the same time, sized to your share of keys with no TTL. redis-benchmark -t set -r 20000000 -d 1024 -n 50000000 also fills an instance, but it writes one value size with no TTL.
While it runs, watch Redis every few seconds:
watch -n 5 "redis-cli INFO memory | grep -E '^(used_memory|maxmemory|mem_fragmentation_ratio|mem_not_counted_for_evict):'; \
redis-cli INFO stats | grep -E '^(evicted_keys|keyspace_hits|keyspace_misses):'; \
redis-cli INFO errorstats"
Watch the container too, with kubectl top pod or container_memory_working_set_bytes against the pod’s memory limit. The working set includes active page cache. When AOF or RDB writes files, it can climb while Redis itself doesn’t grow, so compare it with container_memory_rss. Trigger redis-cli BGSAVE partway through if production runs snapshots, because the fork is where memory peaks. Keep an eye on your app’s Redis client errors as well.
Set your own pass criteria before the run. A reasonable set looks like this:
- Redis runs the whole test with no restart and no
OOMKilled. - Container memory stays under your chosen share of the limit, such as 90%, during the
BGSAVEtoo. - On a cache,
evicted_keysclimbs,errorstat_OOMnever appears, and the hit ratio stays where your app needs it. - On a
noevictioninstance, the 85% alert fires before the firsterrorstat_OOM. Your app retries or returns an error, and no job goes missing.
If your app runs several Node.js workers per pod, test with the real worker count. Each worker opens its own connections and its own share of keys, as the Node.js cluster mode recipe explains.
Keep it healthy
Scrape Redis with redis_exporter and the pod with cAdvisor and kube-state-metrics. The six rules below catch a missing cap, a full noeviction instance, refused writes, heavy eviction, container pressure and the OOM kill:
groups:
- name: redis-memory
rules:
- alert: RedisNoMaxmemory
expr: redis_memory_max_bytes == 0
for: 10m
labels:
severity: warning
annotations:
summary: "Redis {{ $labels.instance }} has no maxmemory set"
description: "Nothing stops this instance growing until the kernel kills it. Set maxmemory below the container limit and pick an eviction policy."
- alert: RedisMemoryNearMax
expr: |
redis_memory_used_bytes{usage!="cache"} / redis_memory_max_bytes{usage!="cache"} > 0.85
and redis_memory_max_bytes{usage!="cache"} > 0
for: 10m
labels:
severity: warning
annotations:
summary: "Redis {{ $labels.instance }} above 85% of maxmemory"
description: "On a noeviction instance, writes fail once it reaches the cap. Find the keys that grew with MEMORY USAGE, then add TTLs, trim data or raise the cap and container limit together."
- alert: RedisRejectingWritesOOM
expr: increase(redis_errors_total{err="OOM"}[5m]) > 0
for: 1m
labels:
severity: critical
annotations:
summary: "Redis {{ $labels.instance }} is refusing writes at maxmemory"
description: "Writes fail with the OOM error. Check that the eviction policy matches the instance's role; under volatile-* check that keys carry TTLs. Free memory or raise the cap."
- alert: RedisEvictingWithLowHitRatio
expr: |
rate(redis_evicted_keys_total[10m]) > 0
and
rate(redis_keyspace_hits_total[10m])
/ (rate(redis_keyspace_hits_total[10m]) + rate(redis_keyspace_misses_total[10m])) < 0.8
for: 15m
labels:
severity: warning
annotations:
summary: "Redis {{ $labels.instance }} is evicting and the hit ratio dropped"
description: "The working set no longer fits in maxmemory. Raise the cap and container limit together, or shorten TTLs on keys you rarely read."
- alert: RedisContainerNearMemoryLimit
expr: |
max by (namespace, pod, container) (container_memory_working_set_bytes{container="redis"})
/ on (namespace, pod, container)
max by (namespace, pod, container) (kube_pod_container_resource_limits{resource="memory", container="redis"})
> 0.9
for: 5m
labels:
severity: warning
annotations:
summary: "Redis container {{ $labels.pod }} above 90% of its memory limit"
description: "Compare with container_memory_rss to rule out page cache. If RSS is high, lower maxmemory, check fragmentation and client buffers, or raise the limit."
- alert: RedisContainerOOMKilled
expr: |
increase(kube_pod_container_status_restarts_total{container="redis"}[10m]) > 0
and on (namespace, pod, container)
kube_pod_container_status_last_terminated_reason{reason="OOMKilled", container="redis"} == 1
for: 0m
labels:
severity: critical
annotations:
summary: "Redis container {{ $labels.pod }} was OOM-killed"
description: "The process outgrew the container. Set maxmemory lower, nearer 50% of the limit with persistence, and check that replicas have the same limit as the primary."
RedisMemoryNearMax matters most under noeviction, where it’s your only warning before writes fail. On a cache, used memory sits at the cap by design, so add a usage="cache" label to cache instances in your scrape config and the rule skips them. Set the 0.8 hit-ratio threshold from your own baseline. A steady eviction rate is normal on a full cache. A jump in evictions next to a falling hit ratio means the dataset outgrew maxmemory.
Roll back
You saved the old values with CONFIG GET 'maxmemory*' before the change. Put them back, then persist:
redis-cli CONFIG SET maxmemory-policy noeviction # your previous policy
redis-cli CONFIG SET maxmemory 0 # your previous cap
redis-cli CONFIG REWRITE
Each rollback trades one failure for another:
| Rollback | What comes back |
|---|---|
noeviction with a cap | Refused writes once memory fills, in place of evictions |
maxmemory 0 | The OOM-kill risk at peak |
If evictions broke a feature that expected its keys to stay, roll back the policy now. That data belongs on its own noeviction instance, so move it there and reapply the cache policy. If you’re reverting for any other reason, pick a quiet hour, because a policy change shifts which keys go.
More recipes
- Find Redis High Latency, Slow Commands and Hot Keys
Alert on per-command p99, slow log growth and a busy main thread, then trace Redis hot keys and big keys, so p99 spikes get a cause before users notice.
- Redis Sentinel Failover Without Lost or Refused Writes
Run three Sentinels and make clients ask Sentinel for the primary, so writes stop failing with READONLY You can't write against a read only replica.
- Improve Cache Hit Ratio to Protect Your Origin at Peak
Trim the cache key, send cache headers from the origin and serve stale while revalidating, so the CDN absorbs peak traffic instead of passing it to your origin.
- Fix ALB 502 Bad Gateway and 504 Gateway Timeout
Set each target's keep-alive above the ALB idle timeout and keep slow requests under it, so the load balancer stops answering peak traffic with 502 and 504.