The symptom and four explanations#
The example is fictional. The pricing service reads prices from a Redis cache and falls back to PostgreSQL on a miss. At 03:00 UTC the cache hit ratio fell from 97% to 40%, and queries per second on the database tripled. Four explanations fit the two graphs:
- Eviction. A new feature started caching large report objects in the same Redis. Memory reached
maxmemory, and the eviction policy removed price keys to make room. - Synchronized expiry. A nightly job wrote every price at 02:00 with a one-hour time to live, so they all expired in the same minute.
- A cold cache. Redis restarted without saved data, or someone flushed it.
- Changed keys. A deploy changed how the service builds its keys, so it asks for keys nobody has written yet.
Each leads to a different fix: memory or a separate cache for eviction, spread-out TTLs for expiry, warm-up or persistence for a cold cache, and a versioned key rollout for changed keys. Change a cached object's format during a rolling deploy
What each explanation predicts#
| Observation | Eviction | Synchronized expiry | Cold cache | Changed keys |
|---|---|---|---|---|
| Hit ratio and database load | fall and rise | fall and rise | fall and rise | fall and rise |
evicted_keys | rising | flat | reset on restart, continuous on flush | flat |
expired_keys | flat | a step of about the number of keys | reset on restart, continuous on flush | flat |
uptime_in_seconds | continuous | continuous | short after restart, continuous after flush | continuous |
| Keys in the keyspace | near the memory limit | a sudden drop | near zero | unchanged or growing |
| TTLs of a sample of keys | spread out | bunched before expiry | few or no keys left to sample | spread out |
The hit ratio and the database load are where the alert came from, and all four explanations predict them. Redis's own documentation on eviction suggests exactly the next step: when hits are lower than expected, check evicted_keys, and if it is low and keys have a TTL, check expired_keys for keys disappearing earlier than intended. Key eviction Both counters are running totals, so read their change across the drop rather than their values. INFO
Redis counts expiry in two ways: a key expires passively when a client reads it after its TTL, and actively when a periodic background test finds it expired. How Redis expires keys Either way it shows in expired_keys, which is why the step appears even for keys nobody reads again.
The lab: reading the counters across a cache miss spike#
The script starts Redis 7 in Docker with a 4 MB memory limit, the allkeys-lru policy and persistence off, a setup Redis's documentation mentions for caching. Redis persistence It writes 10,000 product entries and verifies that every first read hits. The expiry run then shortens every product's TTL in one command on the disposable server. The eviction run adds larger report entries, restart restarts the server, and flush clears the lab database. Each run prints counters on either side of the change. It needs Docker and a POSIX shell and removes its container on exit.
#!/bin/sh
# usage: sh cache-lab.sh expiry|eviction|restart|flush
set -eu
world=${1:-}
case "$world" in
expiry|eviction|restart|flush) ;;
*) echo "Usage: sh cache-lab.sh expiry|eviction|restart|flush" >&2; exit 2 ;;
esac
container=$(docker run -d redis:7 redis-server --save '' --maxmemory 4mb --maxmemory-policy allkeys-lru)
trap 'docker rm -fv "$container" >/dev/null' EXIT
trap 'exit 1' HUP INT TERM
r() { docker exec -i "$container" redis-cli -e "$@"; }
stats() {
r INFO | tr -d '\r' | awk -F'[:,=]' -v label="$1" '
$1 ~ /^(uptime_in_seconds|keyspace_hits|keyspace_misses|expired_keys|evicted_keys)$/ { v[$1] = $2 }
$1 == "db0" { keys = $3 }
END { printf " %-6s uptime %4ss keys %5d hits %6d misses %6d expired %6d evicted %6d\n",
label, v["uptime_in_seconds"], keys, v["keyspace_hits"], v["keyspace_misses"],
v["expired_keys"], v["evicted_keys"] }'
}
ready() {
for attempt in $(seq 1 30); do
if [ "$(r PING 2>/dev/null)" = PONG ]; then return 0; fi
sleep 1
done
echo "Redis did not become ready" >&2
return 1
}
ready
seq 1 10000 | awk '{printf "SET product:%d %0100d EX 3600\n", $1, $1}' | r >/dev/null
hits=$(seq 1 10000 | awk '{print "GET product:" $1}' | r | awk 'length == 100 {n++} END {print n+0}')
[ "$hits" -eq 10000 ] || { echo "Only $hits of 10000 baseline reads hit" >&2; exit 1; }
echo "world=$world"
stats before
case "$world" in
expiry) r EVAL 'for i=1,10000 do redis.call("EXPIRE","product:"..i,1) end return 10000' 0 >/dev/null
sleep 2 ;;
eviction) seq 1 10000 | awk '{printf "SET report:%d %0300d EX 3600\n", $1, $1}' | r >/dev/null ;;
restart) docker restart "$container" >/dev/null; ready ;;
flush) r FLUSHDB >/dev/null ;;
esac
seq 1 10000 | awk '{print "GET product:" $1}' | r >/dev/null # second read
stats after
Save it as cache-lab.sh. Before you run it, write down which counter will move in each world. Then run:
for world in expiry eviction restart flush; do sh cache-lab.sh "$world"; done
With the redis:7 image (Redis 7.4.12) it printed:
world=expiry
before uptime 3s keys 10000 hits 10000 misses 0 expired 0 evicted 0
after uptime 6s keys 0 hits 10000 misses 10000 expired 10000 evicted 0
world=eviction
before uptime 2s keys 10000 hits 10000 misses 0 expired 0 evicted 0
after uptime 5s keys 7203 hits 10172 misses 9828 expired 0 evicted 12797
world=restart
before uptime 2s keys 10000 hits 10000 misses 0 expired 0 evicted 0
after uptime 1s keys 0 hits 0 misses 10000 expired 0 evicted 0
world=flush
before uptime 3s keys 10000 hits 10000 misses 0 expired 0 evicted 0
after uptime 4s keys 0 hits 10000 misses 10000 expired 0 evicted 0
The second read missed in every run. Expiry added 10,000 to expired_keys. Eviction removed 12,797 keys, including report entries, and 9,828 product reads missed. Restart and flush both emptied the database without recording an expiry or eviction. After restart, uptime fell from two seconds to one and the first 10,000 hits disappeared from the counters. After flush, uptime advanced and the hit counter kept all 10,000. Redis evicts by sampling keys rather than by an exact least-recently-used order, so the eviction numbers differ from run to run. Approximated LRU algorithm
A rise in expired_keys during the eviction run would contradict the prediction that eviction alone explains those misses.
Read it on a real system#
INFO is read-only. Take it twice, a minute or so apart, and compare: INFO
redis-cli INFO stats | grep -E '^(expired_keys|evicted_keys|keyspace_hits|keyspace_misses):'
redis-cli INFO server | grep -E '^uptime_in_seconds:'
redis-cli INFO memory | grep -E '^(used_memory|maxmemory|maxmemory_policy):'
redis-cli INFO keyspace
The keyspace line counts keys and keys with an expiry for each database. To see whether expirations cluster, sample up to 2,000 distinct matching keys on the affected node. This Python example uses redis-py and an authorized connection URL in REDIS_URL. It passes each key to TTL as bytes, including any spaces or newlines. SCAN · TTL · redis-py
import os
from collections import Counter
from itertools import islice
import redis
client = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=False)
keys = set(islice(client.scan_iter(match=b"price:*", count=100), 2000))
buckets = Counter()
for key in keys:
ttl = client.ttl(key)
if ttl == -1:
buckets["persistent"] += 1
elif ttl == -2:
buckets["gone since scan"] += 1
else:
buckets[f"{ttl // 60} minutes left"] += 1
for label, count in buckets.most_common():
print(count, label)
A large count in adjacent minute buckets predicts a cluster of expirations if nobody refreshes those keys. Keys written at different times can share an expiry deadline.
Managed Redis exposes the same counters. Amazon ElastiCache publishes Evictions from evicted_keys, Reclaimed from expired_keys and CacheMisses from keyspace_misses. ElastiCache metrics for Redis OSS Memorystore for Redis charts evicted and expired keys, and its uptime metric drops when the instance restarts after a failover, maintenance or a crash. Memorystore for Redis monitoring metrics If memory is at the limit and writes are failing too, the memory state is read the same way as for an out-of-memory error. Read the memory state
Limits#
CONFIG RESETSTAT resets the hit, miss and expired counters, so a counter that dropped may have been reset rather than restarted. Check the uptime before reading a low counter as a restart. CONFIG RESETSTAT
A cluster or a replica set has a counter per node. Read the node that serves the misses. After a failover the new primary has its own uptime and counters, and because Redis replicates asynchronously by default, it may lack the last writes the old primary accepted. Redis replication
Expiry and eviction can happen together. A cache near its memory limit that also holds synchronized TTLs moves both counters; then compare the size of each step with the number of misses. A cache with several kinds of keys can also hide a cause in one prefix, so sample TTLs and key counts per prefix.
Changed keys leave all three counters flat, which makes them easy to miss when you look only for a step. Confirm by reading one of the missed keys from the application log with EXISTS, then the key the previous release would have used. The general method for choosing the observation is in Choose the observation where explanations disagree.
Questions#
How do I tell eviction from expiry in Redis?
Read evicted_keys and expired_keys from INFO stats before and after the drop. Eviction raises the first and is driven by maxmemory; expiry raises the second and is driven by TTLs. A rise in neither points to a restart, a flush or a change in the keys the application asks for.
Why did all our cache keys expire at once?
They were written at the same moment with the same TTL, often by a warm-up job, a deploy or a batch import. Add a random amount to each TTL, for example up to 10% of it, so the keys written together expire over a spread of minutes.
Does a Redis restart clear the cache?
It does when persistence is off, which Redis's documentation mentions as a choice for caches. With an append-only file, Redis replays the logged writes at startup and rebuilds the data; with RDB snapshots it loads the last snapshot, so the cache comes back as warm as that save. Redis persistence The counters in INFO stats start again from zero, as the lab's restart world shows.