🔴 Redis Beginner

How does TTL (Time-To-Live) work in Redis?

Answer

TTL in Redis allows keys to automatically expire and be deleted after a set duration, which is fundamental to cache management. EXPIRE key seconds sets a TTL on an existing key. TTL key returns the remaining time in seconds (-1 means no expiry; -2 means the key doesn't exist). PERSIST key removes the TTL, making the key permanent again. You can also use EXPIREAT key unix-timestamp to expire at a specific absolute time, or PEXPIRE/PTTL for millisecond precision. Redis uses a combination of passive expiration (detected on access) and active expiration (background sampling) to evict expired keys without scanning the entire keyspace on every cycle.