What is redis maxmemory-policy and when does eviction happen?

maxmemory is the upper limit on memory Redis will use for its dataset. maxmemory-policy determines what happens when that limit is reached. You can set both in redis.conf or change them at runtime with CONFIG SET. On 64-bit builds, the default maxmemory is 0, which means no limit.

When used memory exceeds maxmemory, Redis applies the policy as it processes incoming commands. Under most policies, it evicts keys until usage falls back below the limit, then runs the command. The policy controls which keys are candidates: all keys, or only keys with a TTL. It also controls how they are ranked: least recently used, least frequently used, shortest remaining TTL, or random. Eviction is incremental and approximate, so memory can briefly overshoot the limit during write bursts.

Under noeviction, Redis deletes nothing. Commands that would allocate more memory, such as SET on a new key or LPUSH, fail with an out-of-memory error. Reads such as GET keep working, and so does DEL, which frees memory. Your application must handle these write errors, because Redis will not resolve the situation on its own.

The risky configuration is leaving maxmemory unset on a host or container with a fixed memory budget. Redis then grows until something outside it steps in. That could be the kernel OOM killer, a container runtime terminating the process, or heavy swapping that ruins latency. In all of these cases the outcome is decided by the platform, not by a policy you chose. Setting maxmemory below the real limit, with headroom for fragmentation, client buffers and replication, keeps that decision within Redis.

Who should use maxmemory-policy deliberately?

Every Redis instance has an eviction policy, whether or not anyone chose it. The setting deserves a deliberate decision from the following groups:

  • Application developers using Redis as a cache. If your code assumes a missing key means "recompute and store", you want an allkeys-* policy and a maxmemory limit, so Redis discards cold entries instead of refusing writes.
  • Teams using Redis as a primary store, queue or lock service. If a key is the only copy of the data, you need noeviction and write paths that handle OOM errors. Otherwise data can disappear without any error.
  • Platform, SRE and infrastructure engineers sizing hosts and containers. You own the gap between maxmemory and the real memory limit. If that gap is too small, the platform kills Redis before the policy ever runs.
  • Anyone running a shared instance where sessions, locks, queues and cache entries coexist. This is the case where the policy choice is least obvious and where a wrong choice causes the most damage, so the volatile-* caveats below apply directly to you.

If your dataset is small, bounded and well below available memory, the policy rarely triggers. You should still set it consciously, because datasets tend to grow faster than anyone revisits the configuration.

How does maxmemory-policy work?

The mechanism has a few distinct steps, and knowing them makes the failure modes later in this article easier to predict:

  1. A command arrives. Before executing it, Redis checks whether maxmemory is set and whether used memory is over the limit.
  2. Redis decides whether eviction applies. Under noeviction, nothing is evicted. Under the other policies, Redis selects candidates from either the whole keyspace (allkeys-*) or only keys with an expiry (volatile-*).
  3. Redis picks victims by sampling. It does not scan every key. It samples a few keys, ranks them by the policy's criterion (recency, frequency, remaining TTL, or randomly), keeps the best candidates in a small pool, and deletes the worst one. It repeats this until memory is back under the limit. The next section covers the sampling details.
  4. Evictions are propagated. An evicted key is removed like a deleted key. Replicas and the AOF receive a deletion, so they stay consistent with the primary.
  5. If nothing can be freed, writes are rejected. This happens under noeviction, or under a volatile-* policy when no keys with a TTL remain. Commands that may increase memory then fail with an OOM error, while reads and deletions continue to work.

Two consequences follow from this design. First, eviction runs inline with client commands, so heavy eviction adds latency to the writes that trigger it. Second, the policy only ever sees the keys it is allowed to consider. For that reason, the policy and your key-naming and TTL discipline have to be designed together.

Is your Redis a cache, a store, or both?

Before comparing policies, decide what happens when a key disappears without your application deleting it. That answer eliminates most of the eight options.

Pure cache. Every key can be rebuilt from a database, an API or a computation. Losing one costs a miss and some latency, not correctness. Any key is a fair eviction candidate, so use an allkeys-* policy. It lets Redis pick the best victim from the whole keyspace and doesn't depend on every writer remembering to set a TTL.

Primary store or queue. The key is the only copy: a job in a list, a counter, a ledger entry. Eviction here is silent data loss. Use noeviction, so writes fail loudly and the application or an alert has to deal with the full instance.

Mixed instance. Sessions, locks and queues share memory with cache entries. A volatile-* policy only evicts keys that have an expiry, so the TTL becomes your "safe to evict" marker. This only works if the marking is accurate. Locks and sessions usually carry TTLs too, which makes them eligible for eviction. And if too few keys have an expiry, Redis can't free memory and writes fail as they would under noeviction.

Decision flow:

  • Can every key be regenerated? → yes → allkeys-*
    • Recent access predicts reuse → LRU
    • Access frequency is skewed and stable → LFU
  • Is any key the only copy (store, queue)? → yes, and nothing is disposable → noeviction
  • Mixed, and only cache keys carry TTLs? → volatile-*
    • Recency matters → LRU
    • Popularity matters → LFU
    • Shortest remaining lifetime should go first → TTL
                 +----------------------------------+
                 | When Redis evicts a key, is that |
                 | a cache miss or data loss?       |
                 +----------------------------------+
                                   |
         +-------------------------+--------------------------+
         |                         |                          |
         v                         v                          v
+-----------------+     +--------------------+     +--------------------+
| Pure cache:     |     | Mixed: sessions,   |     | Store or queue:    |
| every key can   |     | locks, queues and  |     | key is the only    |
| be regenerated  |     | cache share memory |     | copy of the data   |
+-----------------+     +--------------------+     +--------------------+
         |                         |                          |
         v                         v                          v
+-----------------+     +--------------------+     +--------------------+
|   allkeys-*     |     |     volatile-*     |     |     noeviction     |
| any key may be  |     | only keys with a   |     | writes fail loudly |
| evicted         |     | TTL are evictable  |     | when memory is full|
+-----------------+     +--------------------+     +--------------------+
     |       |             |       |       |                  |
     v       v             v       v       v                  v
  +-----+ +-----+       +-----+ +-----+ +-----+    +--------------------+
  | LRU | | LFU |       | LRU | | LFU | | TTL |    | app/alert must act |
  +-----+ +-----+       +-----+ +-----+ +-----+    +--------------------+
  recency skewed        recency popular soonest
          stable                        expiry

Decide whether eviction means a cache miss or data loss to pick the policy family (allkeys-, volatile-, or noeviction), then pick LRU, LFU or TTL by access pattern; volatile- only works if TTLs mark exactly the keys that are safe to lose.*

How do the eight eviction policies compare?

Policy Eligible keys Selection criterion Typical workload Main failure mode
noeviction None Nothing is evicted; writes that need memory are rejected Primary store, queues, locks Write errors under memory pressure
allkeys-lru All Least recently accessed General-purpose cache Large scans push out hot keys
allkeys-lfu All Least frequently accessed, with decay Cache with a stable hot set New keys can be evicted before they build up hits
allkeys-random All Random Uniform access patterns Hot keys are evicted as readily as cold ones
volatile-lru Keys with a TTL Least recently accessed Mixed cache plus persistent data Write errors if no TTL keys remain
volatile-lfu Keys with a TTL Least frequently accessed Mixed workload with a skewed cache Same as volatile-lru, plus cold-start bias
volatile-random Keys with a TTL Random Mixed workload where TTL keys are equally disposable Write errors if no TTL keys remain; ignores access patterns
volatile-ttl Keys with a TTL Shortest remaining TTL Data where expiry time reflects value Evicts short-TTL keys that may be hot

The volatile-* policies only evict keys that have an expiry set. If none of the keys carry a TTL, for example because a deploy dropped the EX argument or because only persistent keys remain, Redis has nothing to evict. It then behaves exactly like noeviction and rejects writes. This failure stays hidden until memory fills up, so watch the ratio of keys with an expiry to total keys rather than assuming it holds.

volatile-ttl has a less obvious trap. It ranks keys by remaining lifetime, not by usefulness. Consider a session token or rate-limit counter that is rewritten every few seconds with a 30-second TTL. It is among the most-accessed keys in the instance, yet it always sits near the front of the eviction queue. Long-TTL keys that nobody has read in hours survive instead. Only use volatile-ttl when you deliberately set TTLs so that shorter means less valuable.

How do Redis LRU and LFU actually work?

Neither policy keeps an exact ordering of keys. Tracking a true LRU list or exact access counts would cost extra memory per key and extra work on every access. Instead, each key carries a small field holding either a coarse last-access timestamp (LRU) or a compact access counter (LFU). At eviction time, Redis samples a handful of keys, compares those fields, and evicts the worst candidate it finds. It keeps a small pool of candidates between rounds to improve its picks.

maxmemory-samples sets how many keys each round examines, and the default is 5. Raising it brings eviction closer to true LRU or LFU, but every eviction then costs more CPU. That cost matters when writes force evictions continuously. Because the choice is sampled, a still-warm key will occasionally lose simply because colder keys weren't in the sample.

LFU's counter is logarithmic. Each access only probably increments it, with lfu-log-factor controlling how quickly it saturates. The counter decays over time according to lfu-decay-time. The consequence is inertia: a key that was hot an hour ago keeps a high count for a while, so allkeys-lfu adapts slowly when popularity shifts.

That inertia also makes LFU the better choice for a stable hot set. Under allkeys-lru, a one-off bulk read or export touches thousands of cold keys and makes them all look recent, which pushes the real hot set out. Under LFU, one access barely moves a key's counter, so the established hot keys survive the scan.

#!/usr/bin/env bash
R="redis-cli -h 127.0.0.1 -p 6379"

$R CONFIG SET maxmemory 100mb
$R CONFIG SET maxmemory-policy allkeys-lfu

$R CONFIG SET maxmemory-samples 10

$R CONFIG SET lfu-log-factor 10
$R CONFIG SET lfu-decay-time 1

$R SET user:42:profile '{"name":"example"}' > /dev/null
$R SET report:2026:row:9001 'cold-data' > /dev/null
for i in $(seq 1 1000); do $R GET user:42:profile > /dev/null; done
$R GET report:2026:row:9001 > /dev/null

echo "hot key freq:  $($R OBJECT FREQ user:42:profile)"
echo "scan key freq: $($R OBJECT FREQ report:2026:row:9001)"

$R CONFIG SET maxmemory-policy allkeys-lru
echo "scan key idle: $($R OBJECT IDLETIME report:2026:row:9001)s"

$R INFO stats | grep '^evicted_keys'

Sets maxmemory-samples and the LFU decay parameters, then uses OBJECT FREQ to show that a key touched once by a scan keeps a much lower LFU counter than a genuinely hot key, while under LRU that same key would simply look recent.

When should you avoid allkeys or volatile policies and use noeviction?

Eviction is the wrong tool when Redis holds data that has no other copy: a primary store for sessions you cannot regenerate, a job queue, a rate-limit ledger, or a lock table. Under any allkeys-* or volatile-* policy, Redis removes keys without telling the client that wrote them. A dropped queue entry is a job that never runs, and nothing in the logs says so. For this kind of data, a rejected write is better because the caller knows it failed and can react.

noeviction does this, but it moves the problem into your application. Once used memory exceeds maxmemory, commands that can add data fail with an error that begins with OOM. Reads still succeed, and so do deletions and pops that free memory. Every write path therefore needs explicit handling:

  • Detect the error by its OOM prefix, not as a generic Redis failure. It means the instance is full, not that the connection broke.
  • Do not retry blindly. The instance will stay full until something frees memory, so tight retry loops only add load.
  • Apply backpressure. Producers should return an error to their caller, divert work to a fallback, or pause. They should not drop the work silently.
  • Alert on it. An OOM rejection should page someone.

A full instance can also stall work that depends on writes. Consumers may still drain a queue, but a worker that records progress or reschedules a retry will fail on that write.

The volatile-* policies give no protection here. They only evict keys that have a TTL. If non-expiring keys keep growing, Redis runs out of eligible keys and starts returning the same OOM errors. You get the failure mode of noeviction after already having discarded your cache.

import logging
import redis

log = logging.getLogger("jobs")
r = redis.Redis(host="redis.internal.example", port=6379)

class QueueFull(Exception):
    """Raised to the caller so it can reject, divert, or pause the work."""

def is_oom(err: redis.exceptions.ResponseError) -> bool:
    # Some redis-py versions map OOM to a dedicated subclass and strip the
    # prefix; older ones raise a plain ResponseError whose text starts with "OOM".
    return type(err).__name__ == "OutOfMemoryError" or str(err).startswith("OOM")

def enqueue(job_id: str, payload: bytes) -> None:
    try:
        r.lpush("queue:jobs", payload)
    except redis.exceptions.ResponseError as err:
        if is_oom(err):
            # Instance is at maxmemory under noeviction. Retrying right away
            # will hit the same wall, so surface it and let the caller back off.
            log.error("redis OOM, rejected job %s: %s", job_id, err)  # alert on this
            raise QueueFull(job_id) from err
        raise  # other server errors are a different problem
    # ConnectionError and TimeoutError are not caught here: they mean the
    # link failed, not that the instance is full, and need separate handling.

def handle_request(job_id: str, payload: bytes) -> int:
    try:
        enqueue(job_id, payload)
        return 202
    except QueueFull:
        # Backpressure: tell the client to retry later instead of dropping the job.
        return 503

A Python producer using redis-py that treats an OOM rejection under noeviction as a distinct, alertable condition and returns backpressure to the caller rather than retrying in a loop or silently losing the job.

How do you implement, test and size maxmemory-policy in production?

Trial the change at runtime with CONFIG SET maxmemory-policy allkeys-lru (or whichever policy you chose). It takes effect immediately and needs no restart, so you can roll it back the same way. Once you are satisfied, persist it in redis.conf, either by editing the file or by running CONFIG REWRITE. Otherwise the next restart quietly reverts the change.

Verify with INFO

Sample INFO stats and INFO memory at intervals and compare the deltas, not the absolute values:

  • used_memory should plateau near maxmemory.
  • evicted_keys shows how often eviction runs.
  • expired_keys shows how much space TTLs are reclaiming on their own.
  • keyspace_hits and keyspace_misses give you the hit ratio.

If evictions climb and the hit ratio drops, the policy is discarding keys your application still needs.

Why production behaves differently

A standalone dev instance has no replicas and often no persistence. In production, Redis does not count replication and AOF buffers toward maxmemory when it decides what to evict, but those buffers still consume RAM. A fork for BGSAVE or an AOF rewrite adds copy-on-write pages on top. Eviction also runs inside the write path, so freeing a large hash or sorted set stalls the command that triggered it. Enabling lazyfree-lazy-eviction moves the actual freeing to a background thread.

Illustrative estimate (assumed inputs)

These inputs are assumptions for the example, not measurements:

  • Container limit: 8 GiB
  • Fragmentation ratio: 1.2
  • Replication and client output buffers: 0.5 GiB
  • Copy-on-write during a fork: 20% of the dataset

The memory budget is 1.2M + 0.2M + 0.5 ≤ 8, which gives M ≈ 5.3 GiB. Set maxmemory to 5 GiB.

#!/usr/bin/env bash
set -euo pipefail
RC=(redis-cli -h 127.0.0.1 -p 6379)   # set REDISCLI_AUTH in the env if auth is enabled

"${RC[@]}" CONFIG SET maxmemory 5368709120
"${RC[@]}" CONFIG SET maxmemory-policy allkeys-lru
"${RC[@]}" CONFIG SET lazyfree-lazy-eviction yes

sample() {
  { "${RC[@]}" INFO stats; "${RC[@]}" INFO memory; } | tr -d '\r' |
    awk -F: '/^(used_memory|evicted_keys|expired_keys|keyspace_hits|keyspace_misses):/ {print $1"="$2}'
}

declare -A A B
while IFS='=' read -r k v; do A[$k]=$v; done < <(sample)
sleep 300   # compare deltas over a window of real traffic, not absolute values
while IFS='=' read -r k v; do B[$k]=$v; done < <(sample)

hits=$(( B[keyspace_hits] - A[keyspace_hits] ))
miss=$(( B[keyspace_misses] - A[keyspace_misses] ))
echo "used_memory:  ${B[used_memory]} bytes (should plateau near maxmemory)"
echo "evicted:      $(( B[evicted_keys] - A[evicted_keys] ))"
echo "expired:      $(( B[expired_keys] - A[expired_keys] ))"
awk -v h="$hits" -v m="$miss" 'BEGIN { if (h+m > 0) printf "hit ratio:    %.3f\n", h/(h+m); else print "hit ratio:    n/a (no reads)" }'

read -rp "Persist to redis.conf? [y/N] " ok
[[ $ok == y ]] && "${RC[@]}" CONFIG REWRITE

A shell script that applies maxmemory, the eviction policy and lazy eviction at runtime, samples INFO counters twice to compute eviction, expiry and hit-ratio deltas, and then persists the settings with CONFIG REWRITE.

What are the alternatives to tuning a volatile policy, and what do they cost?

Tuning a volatile-* policy on a shared instance makes one memory limit serve two contracts: cache keys that may disappear, and persistent keys that must not. The coupling shows up under pressure. If cache writes fill memory and no keys with a TTL remain, a volatile policy has nothing it can evict, so writes fail with out-of-memory errors. Those failures hit your persistent writes too. A cache key written without a TTL can never be evicted, and one missing EXPIRE in application code can slowly crowd out durable data. Persistence settings chosen for the store, such as RDB snapshots or AOF, also apply to cache data that never needed to be on disk.

Splitting into two instances gives each one a single, simple rule. The cache instance uses allkeys-lru or allkeys-lfu with no persistence. The store instance uses noeviction with persistence enabled. This cuts engineering time in three ways:

  • Fewer error-handling paths. Cache clients treat a miss as normal. Store clients treat an OOM error as a real failure.
  • Clearer alerts. Evictions on the cache are expected and need no alert. Any OOM error on the store should page someone.
  • Less incident debugging. You no longer have to work out which kind of key caused memory pressure.

The cost is operational. Each additional instance adds its own connection config, monitoring, failover setup and memory headroom for fragmentation and buffers.

Concern Mixed instance, volatile-* Separate instances
Failure isolation Cache growth can block durable writes Independent
Missing-TTL bugs Silently consume memory Not possible on cache
Persistence overhead Applies to all data Store only
Alerting Ambiguous One clear signal per instance
Ops overhead One instance Two sets of config, monitoring, failover
Memory headroom Shared Reserved per instance

How can the right eviction policy save engineering time?

Most of the time cost of a wrong policy is not in setting it. It is in the incidents that come later and in the investigations they require. A deliberate choice removes several recurring sources of work:

  • No platform-killed processes to diagnose. With maxmemory set below the container or host limit, Redis handles memory pressure itself. You avoid investigating restarts caused by the OOM killer, along with the cold-cache and resync load that follows each one.
  • No silent data-loss hunts. Keeping irreplaceable data under noeviction turns "a job vanished and nobody knows why" into an explicit OOM error with a log line and an alert. Tracing a loud failure is much faster than reconstructing a silent one.
  • Fewer hit-ratio regressions to chase. Matching LRU or LFU to the access pattern, for example LFU when bulk scans would otherwise flush the hot set, prevents unexplained latency spikes on the backing database.
  • Less TTL bookkeeping. On a pure cache, allkeys-* evicts correctly even when a writer forgets to set a TTL. Nobody has to audit every code path for a missing EX argument just to keep the instance writable.
  • Faster, repeatable rollouts. The runtime CONFIG SET trial, the INFO delta check and CONFIG REWRITE form a short procedure that can be scripted and reused on every instance. Without it, each change becomes a new experiment.
  • Unambiguous on-call signals. When each instance has a single contract, as in the split-instance setup above, evicted_keys and OOM errors each mean one thing. Responders can act on the signal without first figuring out what kind of data is involved.

The one-time work is short: classify the instance as cache, store or mixed, pick the policy, size maxmemory with headroom, and verify with INFO. Each of those steps prevents a class of incident that would otherwise be debugged under pressure.

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 maxmemory-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.