Databases 6 min read

Understanding Redis Expiration Strategies: Lazy Deletion, Periodic Deletion, and New EXPIRE Options

This article explains Redis's two expiration strategies—periodic active deletion and lazy deletion—detailing how the EXPIRE command works, the new NX/XX/GT/LT options introduced in version 7.0, the impact of unsynchronized clocks, and the underlying implementation code.

IT Services Circle
IT Services Circle
IT Services Circle
Understanding Redis Expiration Strategies: Lazy Deletion, Periodic Deletion, and New EXPIRE Options

Redis uses two main strategies to delete expired keys: periodic active deletion and lazy deletion.

In versions prior to 2.6, expiration granularity was up to one second; from 2.6 onward it is 0‑1 ms. The EXPIRE key seconds [NX|XX|GT|LT] command sets a TTL, and without a TTL the key persists until explicitly deleted.

Expiration and Persistence

Expiration timestamps are stored as absolute Unix times, so clock synchronization between master and replica nodes is essential; otherwise keys may be considered expired prematurely during RDB transfer.

Lazy Deletion

When a client accesses a key, Redis checks if the key is expired; if so, it removes the key. This check is performed by the expireIfNeeded function (see code below) and is the only way a key can be deleted without the periodic scan.

int expireIfNeeded(redisDb *db, robj *key, int force_delete_expired) {
    // key not expired
    if (!keyIsExpired(db,key)) return 0;
    if (server.masterhost != NULL) {
        if (server.current_client == server.master) return 0;
        if (!force_delete_expired) return 1;
    }
    if (checkClientPauseTimeoutAndReturnIfPaused()) return 1;
    /* Delete the key */
    deleteExpiredKeyAndPropagate(db,key);
    return 1;
}

Periodic Deletion

Redis runs an active expiration cycle ten times per second, each time randomly sampling a subset of keys with TTLs (default 20 keys). Expired keys are deleted, and if more than 25 % of sampled keys are expired, the cycle repeats.

The implementation resides in src/db.c (function expireIfNeeded ) and expire.c (function activeExpireCycle ).

If expired keys accumulate faster than they can be removed, Redis relies on its memory eviction policies to free space.

performanceDatabaseRedisexpirationLazy DeletionActive Expiration
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

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.