Redis Expired Key Deletion Strategies: Lazy Deletion and Periodic Deletion
The article explains Redis's two expiration key removal mechanisms—lazy deletion, which removes keys only when accessed, and periodic deletion, which randomly scans and deletes expired keys at regular intervals—detailing their concepts, pros, cons, and underlying source‑code implementations.
Lazy Deletion
Concept: When a client accesses a key, Redis checks if the key has expired; if it has, the key is deleted and no value is returned.
Advantages: No unnecessary CPU cycles are spent deleting unrelated keys.
Disadvantages: Expired keys that are never accessed remain in memory, potentially causing memory bloat.
Source‑code analysis: The function expireIfNeeded in db.c is invoked by every command to verify a key's expiration before execution.
Periodic Deletion
Concept: Every 100 ms (default), Redis randomly samples a subset of keys with an expiration time, checks their TTL, and deletes those that have expired.
Advantages:
Limits the duration and frequency of deletion work, reducing CPU impact.
Prevents memory waste caused by expired keys.
Disadvantages:
If the periodic task runs too frequently or for too long, it can consume excessive CPU time.
If it runs too infrequently or for too short a duration, memory leakage similar to lazy deletion may occur.
Source‑code analysis: The server’s cron function redis.c/serverCron calls activeExpireCycle , which, within a time budget, iterates over databases, randomly checks a portion of the expires dictionary, and deletes expired keys. The variable current_db tracks which database is being processed, ensuring a round‑robin scan across all databases.
Summary: Redis combines lazy deletion and periodic active expiration to balance immediate cleanup of accessed expired keys with background scanning to reclaim memory from unaccessed expired keys, each approach having distinct trade‑offs in CPU usage and memory efficiency.
Wukong Talks Architecture
Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.