Redis Key Expiration: Mechanisms and Performance Considerations

Redis provides fine-grained control over key lifecycle through expiration mechanisms. All data structures support TTL (Time To Live) settings, enabling automatic cleanup of stale entries.

Configuring Key Expiration

Basic Expiration Commands

The primary command for setting expiration is EXPIRE, which accepts key name and duration in seconds:

127.0.0.1:6379> SET user_session "authenticated_user"
OK
127.0.0.1:6379> EXPIRE user_session 3600
(integer) 1
127.0.0.1:6379> TTL user_session
(integer) 3599

For atomic set-with-expiration operations, SETEX provides efficiency:

127.0.0.1:6379> SETEX temp_data 60 "temporary_value"
OK
127.0.0.1:6379> GET temp_data
"temporary_value"
# After 60 seconds
127.0.0.1:6379> GET temp_data
(nil)

Important: Expiration metadata gets cleared when a key is deleted via DEL or overwritten by commnads like SET or GETSET.

Command Reference

Command Purpose Unit
EXPIRE key seconds Set lifespan in seconds Seconds
PEXPIRE key milliseconds Set liefspan in milliseconds Milliseconds
EXPIREAT key timestamp Set expiration UNIX timestamp Seconds
PEXPIREAT key ms-timestamp Set expiration UNIX timestamp Milliseconds
TTL key Query remaining time Seconds
PTTL key Query remaining time Milliseconds
PERSIST key Remove expiration permanently N/A

Expiration Strategy Implementation

Redis employs three complementary approaches to reclaim memory from expired keys, balancing CPU utilization and memory efficiency.

Strategy Methodology Trade-off
Scheduled Deletion Per-key timers trigger immediate removal Max CPU overhead, optimal memory usage
Periodic Deletion Background sampling and selective cleanup Balanced CPU/memory usage
Lazy Deletion Expiration check on key access Minimal CPU, potential memory bloat

Scheduled Deletion

This theoretical approach creates individual timers for each expiring key. While it guarantees immediate memory release, the CPU cost scales linearly with key volume. Redis explicitly avoids this strategy in production due to its prohibitive performance impact on the single-threaded architecture.

Periodic Deletion

The default mechanism conducts probabilistic sampling of expirable keys. Redis maintains a dedicated dictionary tracking keys with TTLs. The system performs 10 iterations per second, each examining a random subset rather than full scans.

Sampling Process:

  1. Randomly select 20 keys from the expiration dictionary
  2. Remove expired entries from the sample
  3. If >25% of sampled keys expired, repeat the process

This adaptive approach scales deletion intensity with expiration density. To prevent latency spikes, each scan iteration caps execution at 25ms. Short client timeouts (e.g., 10ms) may experience connection drops during heavy expiration bursts, even without slowlog entries, as slowlog only captures command processing time, not waiting time.

Key Consideration: Synchronizing massive key expirations simultaneously can trigger "expiration storms," causing temporary latency increases and potential cache avalanche scenarios under high concurrency.

Lazy Deletion

This complementary strategy checks expiration only during key access operations. When a client requests a key, Redis first validates its TTL before returning data. Expired keys are purged on-the-fly.

Advantages: Near-zero CPU overhead for untouched expired keys, ideal for write-heavy workloads.

Drawbacks: Memory pressure from permanently unaccessed expired keys. For time-series data like logs, where access patterns decay sharply after generation, substantial memory may remain occupied indefinitely despite logical expiration.

Tags: Redis expiration Caching memory-management Performance

Posted on Wed, 04 Nov 2026 16:34:18 +0000 by newyear498