What does maxmemory do and what is a Redis eviction policy?

maxmemory caps how much memory Redis will use for its dataset. A Redis eviction policy, set with maxmemory-policy, tells Redis what to do when that cap is reached. When a client sends a command that may add memory and used memory is over the limit, Redis first runs the configured policy to free space. Only then does it execute the command. The policy can evict keys, or it can refuse the write with an error. Read-only commands are not blocked this way.

If maxmemory is 0, which on 64-bit builds means no limit, eviction never triggers. Redis keeps allocating until the operating system's OOM killer or the container runtime's memory limit terminates the process. That loses every key in memory at once, not just a chosen few. A deliberate limit set below the container or host ceiling turns that sudden crash into a controlled behavior you have chosen.

That choice is about data loss. Each policy answers one question: when memory runs out, which data can you afford to lose? It might be the least recently used key, a key close to expiry, or nothing at all, in which case the application has to handle rejected writes.

You can set both values in redis.conf, for example maxmemory 2gb and maxmemory-policy allkeys-lru. On a running instance, use CONFIG SET maxmemory 2gb and CONFIG SET maxmemory-policy allkeys-lru. Runtime changes take effect immediately but are lost on restart unless you also persist them with CONFIG REWRITE or by editing the file. To verify the setting, run CONFIG GET maxmemory-policy.

redis-cli CONFIG SET maxmemory 2gb

redis-cli CONFIG SET maxmemory-policy allkeys-lru

redis-cli CONFIG GET maxmemory
redis-cli CONFIG GET maxmemory-policy
redis-cli CONFIG REWRITE

Setting maxmemory and maxmemory-policy in redis.conf and at runtime with CONFIG SET, checking them with CONFIG GET, and saving them with CONFIG REWRITE.

Who should use a Redis eviction policy, and who should not?

Anyone who runs Redis with a memory limit is already using an eviction policy, even if it is just the default noeviction. The question is whether that policy was chosen deliberately. Configuring one is worth the effort for:

  • Backend engineers running Redis as a cache in front of a database or API. They need Redis to discard data on its own instead of failing writes or growing without bound.
  • Platform and SRE teams who set container or host memory limits. They need maxmemory and the policy to match those limits, so Redis evicts or rejects writes before the kernel kills the process.
  • Teams sharing one instance across services, where cache entries sit next to sessions, counters, locks or queues. Here the policy decides whether durable data is safe, and the wrong choice causes silent data loss.
  • Anyone diagnosing OOM command not allowed errors, since the policy and the TTL coverage of the keyspace determine when that error appears.

If Redis is your primary data store and every key must survive, an evicting policy is the wrong tool. Use noeviction, plan capacity, and alert on memory usage and rejected writes. An eviction policy only helps when some of the data is expendable.

How does Redis eviction work?

Eviction is a check that runs as part of command execution, not a separate background process you schedule. In outline:

  1. A client sends a command. Redis knows which commands can grow memory, such as SET, LPUSH and HSET.
  2. Before running such a command, Redis compares its used memory with maxmemory.
  3. If it is under the limit, the command runs normally.
  4. If it is over the limit, Redis applies maxmemory-policy. Under noeviction it returns an OOM error. Under any other policy it picks candidates from the eligible set (all keys for allkeys-*, keys with a TTL for volatile-*), deletes the best one, and checks memory again.
  5. Once memory is back under the limit, the command runs. If no eligible key remains, the command is rejected with an OOM error.

Redis does not maintain a sorted list of every key by age or popularity, because that would cost memory and CPU on every access. Instead, each key stores a small amount of metadata: a last-access timestamp for LRU or a logarithmic access counter for LFU. At eviction time Redis samples a handful of keys, keeps a small pool of the best candidates across samples, and evicts from that pool. The LFU counter grows more slowly as it gets larger and decays over time, controlled by lfu-log-factor and lfu-decay-time, so old popularity fades.

Eviction is separate from expiration. Keys with a TTL are removed when they expire, either lazily when a client accesses them or by Redis's periodic active expiry cycle, regardless of memory pressure. Eviction removes keys early, before their TTL runs out or when they have no TTL at all, and only because memory is over the limit. The next section covers each policy family and the write path in detail.

How do the eviction policy families work?

Policies fall into three groups. noeviction never removes data and rejects writes once the limit is reached. The allkeys-* policies can evict any key. The volatile-* policies only consider keys that have a TTL. Within each group, the suffix sets the selection criterion: lru targets the key idle longest, lfu targets the key with the lowest access-frequency counter, and random skips scoring.

Policy Eligible keys Selection criterion When nothing is eligible
noeviction None None Writes return an OOM error
allkeys-lru All Longest idle time Writes return an OOM error
allkeys-lfu All Lowest frequency counter Writes return an OOM error
allkeys-random All Random Writes return an OOM error
volatile-lru Keys with TTL Longest idle time Writes return an OOM error
volatile-lfu Keys with TTL Lowest frequency counter Writes return an OOM error
volatile-random Keys with TTL Random Writes return an OOM error
volatile-ttl Keys with TTL Shortest remaining TTL Writes return an OOM error

LRU and LFU are approximations. Redis does not keep a global ordering of keys. It samples maxmemory-samples keys (default 5) and evicts the best candidate in the sample. Raising the sample size moves the result closer to true LRU or LFU but costs more CPU on each eviction. volatile-ttl uses the same sampling, with remaining TTL as the priority signal. The key closest to expiring is treated as the least valuable.

Eviction runs inline with the command:

Write path: client command → check used memory against maxmemory → if over the limit: sample keys → evict the best candidate → repeat until under the limit or nothing is eligible → execute the command, or return OOM

Under heavy write pressure, this loop adds latency to the commands that trigger it. On replicated setups, the primary propagates each eviction to replicas as a DEL. Replicas do not run their own eviction decisions.

      +------------------+
      |  Client command  |
      +--------+---------+
               |
               v
      +------------------+  no   +-------------------+   +-----------+
 +--->| used memory >    +------>|  Execute command  +-->| Reply to  |
 |    | maxmemory?       |       +-------------------+   | client    |
 |    +--------+---------+                               +-----------+
 |             | yes
 |             v
 |    +------------------+  yes  +-------------------+
 |    | noeviction?      +------>|  Return OOM error |
 |    +--------+---------+       +-------------------+
 |             | no                        ^
 |             v                           |
 |    +------------------+                 |
 |    | Sample N keys    |  none eligible  |
 |    | from eligible set+-----------------+
 |    | N=maxmemory-     |
 |    |   samples        |
 |    +--------+---------+
 |             |
 |             v
 |    +------------------+       +-------------------+
 |    | Evict best       +------>| DEL propagated to |
 |    | candidate        |       | replicas and AOF  |
 |    +--------+---------+       +-------------------+
 |             |
 +-------------+

Redis write path under maxmemory: the memory check, key sampling and eviction loop run inline before the command executes. Each eviction is sent to replicas and the AOF as a deletion, and the write is rejected with an OOM error if the policy is noeviction or no key is eligible.

Why does Redis return OOM command not allowed?

The error appears when Redis is over maxmemory, needs to free space for a write, and finds nothing it is allowed to remove. Under noeviction this is the intended behavior. Under a volatile-* policy it happens when no keys carry a TTL, because those policies only consider expiring keys. Once the candidate pool is empty, a volatile-* policy behaves exactly like noeviction.

Only commands that can grow memory are rejected, such as SET, LPUSH and HSET. Reads keep working, and so do commands that free memory, such as DEL. As a result, the service looks healthy to read-heavy health checks while writes fail.

Three causes account for most cases:

  • Missing TTLs. A code path writes keys without setting an expiry. Those keys are invisible to volatile-* eviction.
  • Growing durable keys. Data meant to persist, such as sessions, queues or counters, grows until it fills the memory budget.
  • A low maxmemory. The limit was set for an earlier workload and never revisited.

To diagnose the condition, run INFO memory and compare used_memory with maxmemory. The same section reports maxmemory_policy. Next, run INFO keyspace and compare expires with keys for each database. If expires is zero or far below keys under a volatile-* policy, eviction has little or nothing to work with. Finally, check what clients actually receive: an error reply beginning with OOM command not allowed when used memory > 'maxmemory'. Client libraries usually surface this reply as a server or response error, so it is easy to misread as a connection fault.

#!/usr/bin/env bash
set -euo pipefail

HOST="${REDIS_HOST:-127.0.0.1}"
PORT="${REDIS_PORT:-6379}"
cli() { redis-cli -h "$HOST" -p "$PORT" "$@"; }

echo '--- memory ---'
cli INFO memory | tr -d '\r' \
  | grep -E '^(used_memory|maxmemory|maxmemory_policy):'

echo '--- keyspace ---'
cli INFO keyspace | tr -d '\r' | awk -F'[:=,]' '/^db/ {
  pct = ($3 > 0) ? 100 * $5 / $3 : 0
  printf "%s keys=%s expires=%s (%.1f%% evictable under volatile-*)\n", $1, $3, $5, pct
}'

echo '--- read check ---'
cli PING

echo '--- write check ---'
out=$(cli SET oom:probe 1 EX 10 2>&1 || true)
case "$out" in
  *OOM*) echo "write rejected: $out" ;;
  *)     echo "write accepted: $out"; cli DEL oom:probe >/dev/null ;;
esac

A redis-cli script that checks used_memory against maxmemory, shows the active eviction policy, compares expires with keys per database, and runs a probe write to show the OOM reply while reads still succeed.

When should you use allkeys-lru, and when should you avoid it?

allkeys-lru is the right default when the instance is purely a cache. Every key must be rebuildable from a source of truth such as a database, an API, or a computed result, so losing any key costs only a cache miss and a refetch. The workload should show recency locality, meaning keys read recently are likely to be read again soon. The policy also has a practical advantage: it considers every key as an eviction candidate. Eviction therefore keeps working even if some code path forgets to set a TTL, and the cache's health does not depend on expiry discipline across every service that writes to it. Redis approximates LRU by sampling keys rather than tracking exact order. For cache workloads this approximation is usually close enough.

Avoid it on mixed-use instances. Under memory pressure, allkeys-lru treats every key the same way. It can evict a distributed lock and let two workers enter a critical section. It can drop a rate-limit counter so the limit resets early, log a user out by removing a session, or discard a queue entry. None of these produce an error. You get silent correctness bugs that show up only under load.

LRU also handles one-off bulk access poorly. A batch job or backfill that reads many keys once marks all of them as recently used. That can push out the hot working set, and your hit rate collapses until the job ends. allkeys-lfu resists this because it ranks keys by access frequency, so a key touched once does not outrank one read thousands of times. The trade-off is that LFU counters build up and decay gradually. When the hot set genuinely changes, LFU takes longer than LRU to adapt.

When should you use volatile-ttl or another volatile-* policy?

The volatile-* policies fit instances that hold two kinds of data. Durable keys such as feature config, rate-limit counters and queues carry no TTL and must never disappear. Cache entries carry a TTL and can be rebuilt. Because volatile-* policies only consider keys with an expiry, the durable keys are never eviction candidates. Locks are a caveat: a lock set with a TTL is evictable under any volatile-* policy, so an evicted lock can let a second holder in early.

volatile-ttl evicts the keys whose remaining TTL is shortest. That is only correct when TTL encodes value, meaning the application deliberately gives short TTLs to cheap or low-value entries. Most applications set TTLs for freshness, not value. In that case a hot key with seconds left can be evicted ahead of cold keys with day-long TTLs, and the hit rate drops. volatile-lru and volatile-lfu avoid this. They protect the same durable keys but rank cache keys by recency or frequency, which is usually what you want.

The main operational risk is a forgotten TTL. Any cache key written without an expiry becomes unevictable. These keys accumulate until no eviction candidates remain. Redis then rejects writes with OOM command not allowed, even though most of the memory is cache.

To prevent this, route every cache write through one helper that always issues SET key value EX seconds. Avoid a separate SET followed by EXPIRE. A crash between the two commands leaves a key with no TTL. A plain SET on an existing key also clears its TTL.

import json
import redis

r = redis.Redis(host="localhost", port=6379, decode_responses=True)

DEFAULT_CACHE_TTL = 300  # seconds; placeholder value


def cache_set(key: str, value, ttl: int = DEFAULT_CACHE_TTL) -> None:
    """The only path for cache writes: every entry gets an expiry."""
    if ttl <= 0:
        # Refuse writes that would create an unevictable cache key.
        raise ValueError("cache entries must have a positive TTL")
    # One command, SET key value EX ttl: value and TTL are applied atomically.
    # Avoid SET then EXPIRE: a crash between them leaves a key with no TTL,
    # and a later plain SET on an existing key would clear its TTL anyway.
    r.set(f"cache:{key}", json.dumps(value), ex=ttl)


def cache_get_or_load(key: str, loader, ttl: int = DEFAULT_CACHE_TTL):
    """Read-through cache: on a miss (or after eviction), rebuild and re-cache."""
    raw = r.get(f"cache:{key}")
    if raw is not None:
        return json.loads(raw)
    value = loader()
    cache_set(key, value, ttl)
    return value


profile = cache_get_or_load("user:42", lambda: {"id": 42, "name": "Ada"}, ttl=600)

A single cache-write helper using redis-py that always issues SET with EX, so every cache key stays evictable under a volatile- policy while durable keys without TTLs are left alone.*

What are the alternatives to tuning the eviction policy?

The other option is to stop asking one instance to serve two purposes. Run cache data and durable data in separate Redis instances, and give each the policy that matches its contract. The cache instance uses allkeys-lru, so any key can be evicted and no key needs a TTL to be evictable. The durable instance uses noeviction. This is a deliberate choice: when memory runs out, writes fail with OOM command not allowed instead of Redis silently dropping data. A failed write is visible and alertable. A missing session or job record is often found only after a user reports it.

The cost is operational. You have two instances to provision, monitor, fail over and back up, and clients need two connection configurations. The development cost goes down, though. In a mixed instance, every code path that writes a cache key must set a TTL, and reviewers must check for it. A split removes that requirement. It also removes a whole class of silent data-loss bugs that are slow to reproduce and diagnose, which saves debugging and review time later.

Setup Failure mode when full Required application discipline Operational cost
Mixed, allkeys-lru Durable keys evicted silently Keep durable data out, or accept loss Low
Mixed, volatile-ttl / volatile-lru Cache keys without a TTL never evicted; writes fail once no TTL keys remain TTL on every cache write Low
Mixed, noeviction All writes fail, including cache Application-side cache size limits Low
Split: cache allkeys-lru, durable noeviction Cache evicts; durable writes fail loudly Route each key to the correct instance Higher: two instances

How can the right eviction policy save engineering time?

A deliberate policy choice saves time mostly by preventing incidents that are slow to investigate.

  • Fewer full-restart incidents. With maxmemory set below the container limit and an evicting policy on a cache, Redis frees memory itself instead of being OOM-killed. Nobody has to restart the process, warm the cache again, or investigate why every key vanished at once.
  • No hand-written cleanup jobs. Without eviction, teams often write scripts that scan for and delete old keys when memory gets tight. Under allkeys-lru or allkeys-lfu, Redis does this continuously as part of normal writes, so there is no script to write, schedule or debug.
  • Less review overhead. On a pure cache instance with an allkeys-* policy, reviewers do not need to check that every write sets a TTL just to keep eviction working. On a mixed volatile-* instance, a single cache-write helper like the one above turns a rule that every engineer must remember into one function that enforces it.
  • Faster diagnosis. When the policy matches the data's contract, failures are predictable. A cache that evicts shows up as a higher evicted_keys rate and more misses. A durable instance under noeviction shows up as explicit OOM errors. Engineers can go straight from the symptom to the cause instead of chasing silent data loss, such as an evicted lock or session, that only reproduces under load.
  • Clearer capacity decisions. A rising eviction rate on a cache, or OOM errors on a durable instance, is a direct signal to add memory or reduce the dataset. That replaces guesswork about whether memory growth is a problem.

The split-instance setup trades some operational work for this predictability. Whether it saves time overall depends on how much of your engineering effort currently goes into TTL discipline and data-loss investigations compared with running a second instance.

How do you size, monitor and choose a Redis eviction policy?

Sizing headroom

maxmemory limits the dataset Redis tracks. The process can still use more than that. Client output buffers, replication buffers, allocator fragmentation and copy-on-write pages during a background save all count against the container limit. If maxmemory equals the container limit, the kernel's OOM killer can stop Redis before eviction ever runs.

Illustrative estimate. These inputs are assumptions, not measurements:

  • 4 GiB container limit.
  • 512 MiB reserved for client and replication buffers.
  • A fragmentation ratio of 1.2.

That leaves 3.5 GiB. Dividing by 1.2 gives about 2.9 GiB. Setting maxmemory near 2.75 GiB leaves margin for fork overhead. Replace the assumptions with your observed mem_fragmentation_ratio and buffer usage.

Monitoring

Check the current settings with CONFIG GET maxmemory and CONFIG GET maxmemory-policy.

INFO memory reports used_memory, used_memory_rss and mem_fragmentation_ratio.

INFO stats reports evicted_keys. That field is a cumulative counter, so graph its rate of change. A steady low rate can be normal for a cache. A rising rate means the working set is outgrowing memory.

Alert on two signals:

  • Eviction rate. Catch it trending upward before data goes missing.
  • Client-side OOM command not allowed errors. Count them in application metrics, because under noeviction and the volatile-* policies these errors are the first symptom.

Decision checklist

  • Can every key be rebuilt from a source of truth? If yes, use allkeys-lru.
  • Do all cache keys carry TTLs? If not, volatile-* policies cannot evict them.
  • Is losing a key without a TTL acceptable? If not, avoid allkeys-* on that instance.
  • For this workload, which is worse: failing writes or silently dropped data? Failing writes point to noeviction. Dropped data points to an eviction policy.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to redis eviction policy, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.