Databases 22 min read

Redis Expiration Mechanisms and Key Deletion Strategies

This article explains how Redis manages key expiration using EXPIRE, PEXPIRE, EXPIREAT, and PEXPIREAT commands, details the internal expires dictionary, demonstrates code examples for setting, retrieving, and removing TTL, and discusses the lazy and periodic deletion strategies along with their impact on persistence and replication.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Redis Expiration Mechanisms and Key Deletion Strategies

Redis provides several commands— EXPIRE , PEXPIRE , EXPIREAT , and PEXPIREAT —to set a key's time‑to‑live (TTL) or absolute expiration time. These commands store the expiration timestamp in the server's expires dictionary, where each entry maps a key object to a millisecond‑precision UNIX timestamp.

Utility commands such as TTL and PTTL return the remaining lifetime of a key, while SETEX combines value setting with expiration. The PERSIST command removes an existing expiration, effectively deleting the key's entry from the expires dictionary.

Redis determines whether a key is expired by checking the expires dictionary and comparing the stored timestamp with the current time. If the current time exceeds the stored expiration, the key is considered expired.

Two deletion strategies are employed:

Lazy deletion : the server checks a key's expiration only when the key is accessed; if expired, it is removed on‑the‑fly.

Periodic deletion : a background routine ( activeExpireCycle ) runs during the server's cron loop, sampling a configurable number of databases and keys, and proactively deletes expired keys while respecting CPU time limits.

The server combines lazy and periodic deletion to balance memory reclamation and CPU usage. Persistence mechanisms respect expiration: expired keys are omitted from RDB snapshots and AOF rewrites, and when an expired key is finally deleted, a DEL command is appended to the AOF file.

In replication, the master is responsible for deleting expired keys and propagates explicit DEL commands to replicas. Replicas do not delete expired keys autonomously, ensuring data consistency across the replication chain.

DatabaseredisexpirationKey DeletionLazy DeletionPeriodic Deletion
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.