Redis TTL vs Eviction: Diagnose Missing Keys and Memory Pressure
Diagnose Redis keys that disappear or lose their TTL. Compare expiration and eviction, inspect INFO deltas, and choose safer cache recovery steps.
Expiration removes a key after its configured lifetime; eviction removes eligible keys to satisfy a memory policy. A TTL is not a retention guarantee. Inspect the key’s TTL, the active memory policy, and counter changes on the same Redis process before changing settings or blaming a cache miss on one mechanism.
A missing key does not identify the removal mechanism
A cached report disappears while its application log still says it was written five minutes ago. Another key remains present long after the expected lifetime. A third request receives a memory-related write error. These symptoms can occur in the same system, but they need different explanations and different repairs.
Start with the exact endpoint, logical database, key name and observation time. Confirm that the writer and reader address the same environment. A naming mismatch, a different database number, an explicit deletion or a failed write can resemble expiration. Recreating a missing key repeatedly can conceal the original fault and amplify load on the source database.
This guide concerns whole-key expiration and Redis memory eviction. It uses established commands, with KEEPTTL requiring Redis 6.0 or later. Check the installed version and managed-service restrictions. Redis binaries were unavailable during preparation: Redis command sequences below are documentation-reviewed, not server-executed. The Python snapshot helper was executed against synthetic fixtures; those checks do not simulate Redis eviction.
Read TTL as a state observation, not a promise
TTL reports remaining lifetime in seconds; PTTL uses milliseconds. A nonnegative TTL means the key has an expiration at the instant of inspection. The special value -1 means an existing key has no expiration, while -2 means the key is absent. These distinct negative replies apply to Redis 2.8 and later.
A positive TTL does not reserve memory for the key until that deadline. An eligible key may be evicted earlier under memory pressure, or the application may delete or replace it. Conversely, checking TTL and then reading the key are separate operations: another client can change it between those observations. Avoid interpreting the two results as an atomic history.
Redis expiration includes access-time checks and background work. Do not treat physical removal from memory as a precise timer callback for an external action. If a business process must run at a deadline, use an explicit scheduling and recovery design rather than assuming that a key’s disappearance constitutes reliable job delivery.
| Observation | What it establishes | Next check |
|---|---|---|
| TTL >= 0 | Expiration currently exists | Whether writes refresh it or pressure can evict it |
| TTL = -1 | Key exists without expiration | Overwrite and PERSIST paths |
| TTL = -2 | Key is absent now | Write success, names, deletion, expiration and eviction evidence |
| Write returns an OOM error | The attempted operation was rejected | Effective memory limit, policy and available eviction candidates |
Audit the write path that owns the lifetime
A successful ordinary SET replaces the value and discards the old TTL unless an expiration option or KEEPTTL is supplied. This explains a common incident: the initial cache fill sets a lifetime, but a later refresh performs a plain SET and creates a persistent key. Look at every writer, not just the code path that created the first value.
SET with EX or PX attaches a lifetime as part of the same command. A separate SET followed by EXPIRE creates a gap in which failure can leave the value without expiration. KEEPTTL preserves an existing deadline rather than starting a fresh interval; it does not invent a deadline for a previously persistent or nonexistent key.
The sequence below intentionally changes only a named teaching key. Run it in an isolated development instance, not against an operational session or production cache entry. TTL values count down, so expect ranges rather than an exact repeated number. The two -1 observations are the important outcomes, assuming no other writer or eviction intervenes.
# Use a disposable development Redis instance and its connection options.
redis-cli SET pwp:ttl-demo first EX 120
redis-cli TTL pwp:ttl-demo
redis-cli SET pwp:ttl-demo replacement
redis-cli TTL pwp:ttl-demo
# Expected: -1, because the plain replacement removed the old expiry.
redis-cli SET pwp:ttl-demo fresh EX 120
redis-cli SET pwp:ttl-demo retained KEEPTTL
redis-cli PTTL pwp:ttl-demo
# Expected: a remaining lifetime, not a new guaranteed 120-second interval.
redis-cli PERSIST pwp:ttl-demo
redis-cli TTL pwp:ttl-demo
# Expected: -1 after removing the expiry.
redis-cli DEL pwp:ttl-demoSource: Redis: SET expiration options ↗
Define what a successful refresh should preserve
Before modifying the writer, make the lifetime rule testable. Decide whether freshness is measured from the original insertion, the most recent refresh or the last application activity. Those are different policies. A value can be frequently read while its original deadline keeps approaching; popularity does not by itself establish that the contents are still current.
For a report cache, an acceptance check might require a successful fill to create both the value and a bounded lifetime, then require a refresh to replace the value and start a fresh interval. A different workload may intentionally preserve the original deadline. State that choice explicitly so a developer does not switch between EX and KEEPTTL merely to make a test pass.
Also define the fallback when the fill is rejected or the key is missing. Can the reader rebuild safely, return a controlled temporary response, or use an older value under a documented rule? Exercise the failure path as well as the happy path. This separates the application contract from whichever eviction policy the current server happens to use.
Choose eviction policy from the data’s role
Expiration answers how long a cached value is useful. Eviction answers which data may be sacrificed when the configured memory budget is reached. Write down whether each workload is disposable cache data, durable state or coordination state before selecting a policy. A cache can rebuild a value; losing a coordination key may change application behavior.
With allkeys-lru or allkeys-lfu, keys are eligible even when they have no TTL. The volatile variants restrict candidates to keys with expiration. If no eligible expiring keys exist, volatile policies behave like noeviction. Adding TTLs changes eligibility as well as freshness, so it is not a neutral repair.
noeviction avoids memory-policy key removal, but memory-growing writes can fail instead. The application must handle those failures. It is not a durability guarantee, and it does not disable ordinary expiration. Separate workloads when they require incompatible loss and capacity policies; do not rely on a shared cache policy to provide storage guarantees.
Inspect INFO memory and the effective configuration exposed by your platform. maxmemory is not a promise that total process memory or container consumption will remain below that value. Leave headroom for the actual deployment and inspect replication or persistence buffers, allocator behavior and host limits before simply raising the budget.
Measure a bounded window on the same process
Capture INFO server, INFO memory and INFO stats before and after a representative workload interval. Use your existing authenticated connection options consistently; the simple CLI commands assume you have selected the intended development endpoint. Keep snapshots restricted because server metadata can reveal infrastructure details.
Compare changes rather than cumulative totals. Rising expired_keys indicates expiration activity; rising evicted_keys indicates memory-policy eviction activity. Neither identifies which individual application key was removed. Both can increase during one observation window, so a system-wide counter is supporting evidence rather than a per-key audit trail.
The helper below rejects a changed run_id, nonincreasing uptime and decreasing counters. Capture each node separately in a cluster. A reconnect, failover or restart can invalidate a comparison. The three INFO calls are not an atomic snapshot; use the result for incident direction, not precise subsecond attribution.
# Capture the baseline using the same endpoint and database options each time.
{
redis-cli --raw INFO server
redis-cli --raw INFO memory
redis-cli --raw INFO stats
} > before.info
# After the chosen workload observation interval, capture again.
{
redis-cli --raw INFO server
redis-cli --raw INFO memory
redis-cli --raw INFO stats
} > after.info
python info_delta.py before.info after.infoA small INFO delta checker you can run locally
Save this as info_delta.py. It reads text files only and opens no network connection. Extra INFO fields are allowed, while the fields needed for comparison must be present. Missing fields produce an error rather than silently becoming zero, which matters when a platform omits statistics or a command failed.
The lookup percentage describes the recorded Redis key lookups in this window, not an end-user request success rate. Multiple lookups may belong to one request. A null percentage means no recorded lookups occurred; it is not zero-percent success. Known statistics resets invalidate the baseline even if counters later grow beyond their earlier values and escape the decrease check.
import json
import re
import sys
from pathlib import Path
COUNTERS = ("expired_keys", "evicted_keys", "keyspace_hits", "keyspace_misses")
def parse_info(text):
fields = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
name, separator, value = line.partition(":")
if not separator or name in fields:
raise ValueError("Malformed INFO snapshot or duplicate field")
fields[name] = value
if not fields.get("run_id"):
raise ValueError("Snapshot requires run_id")
for name in ("uptime_in_seconds", *COUNTERS):
value = fields.get(name, "")
if not re.fullmatch(r"[0-9]+", value):
raise ValueError("Missing or invalid counter: " + name)
fields[name] = int(value)
return fields
def compare(before, after):
if before["run_id"] != after["run_id"]:
raise ValueError("Different Redis processes; start a new baseline")
elapsed = after["uptime_in_seconds"] - before["uptime_in_seconds"]
if elapsed <= 0:
raise ValueError("Snapshots need increasing server uptime")
delta = {name: after[name] - before[name] for name in COUNTERS}
if any(value < 0 for value in delta.values()):
raise ValueError("Counter decreased; possible statistics reset")
lookups = delta["keyspace_hits"] + delta["keyspace_misses"]
return {"observed_seconds": elapsed, "deltas": delta,
"lookup_hit_percent": (100 * delta["keyspace_hits"] / lookups
if lookups else None)}
if __name__ == "__main__":
if len(sys.argv) != 3:
raise SystemExit("Usage: python info_delta.py before.info after.info")
try:
snapshots = [parse_info(Path(p).read_text(encoding="utf-8"))
for p in sys.argv[1:]]
print(json.dumps(compare(*snapshots), indent=2))
except (OSError, ValueError) as exc:
raise SystemExit(str(exc))
Read the output without inventing a key history
The following two short fixtures are invented teaching data, not measurements from a production server. Save the first as before.info and the second as after.info, then run the helper. It should report 60 observed seconds, 3 expirations, 2 evictions, 40 hits, 10 misses and an 80 percent lookup hit ratio.
That output supports investigating both expiry and memory pressure during the window. It does not prove that a particular missing report expired, that a particular key was evicted, or that the underlying request failed. Correlate the window with application write outcomes, deployment changes and the intended cache lifetime.
# before.info — synthetic fixture
run_id:teaching-process-a
uptime_in_seconds:100
expired_keys:10
evicted_keys:4
keyspace_hits:100
keyspace_misses:20
# after.info — save separately, without the before fields
run_id:teaching-process-a
uptime_in_seconds:160
expired_keys:13
evicted_keys:6
keyspace_hits:140
keyspace_misses:30Repair the cause and verify recovery at the application boundary
For keys that unexpectedly have no expiration, repair the writer that removes or omits it and test both creation and refresh. For rising eviction counts, inspect key sizes, workload growth, policy eligibility and capacity. For rejected writes, fix the handling path as well as the memory pressure; a cache fill that fails silently will look like a mysterious miss later.
Reproduce the original request with a controlled learning key, then check the stored value and lifetime. Observe the workload again over a comparable interval. A lower miss count alone is insufficient if values have become too old, errors have moved downstream or persistent keys are consuming the intended cache budget.
When a large group of cached values expires together, consider spreading refresh times and controlling concurrent rebuilds. Use the existing HTTP retry-budget resource when cache misses lead to remote API calls: repeated misses and retries can multiply backend work. Evaluate such changes against freshness requirements rather than extending every TTL.
Close the investigation with separate evidence for value freshness, memory behavior and successful work. Keep the counter baseline and the corrected write behavior alongside the incident record. The practical goal is predictable cache behavior under its real workload, not merely making the next GET return something.
Your next steps
- Treat TTL, eviction policy and application write behavior as separate parts of the diagnosis.
- Compare counters on the same process over a known window; do not turn global deltas into a per-key claim.
- Verify creation, refresh, failure handling and downstream work after the repair.
Sources & official resources
Linked resources checked on 2026-10-26. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →