Advertisement
Beginner Redis, Expiration & Eviction

What is the difference between the EXPIRE, TTL, and PERSIST commands in Redis?

Short answer

EXPIRE sets a countdown timer on a key after which it will be automatically deleted, TTL checks how much time remains before that countdown reaches zero, and PERSIST removes any existing expiration from a key, making it permanent again until explicitly deleted or given a new…

Save Redis mock interview
Advertisement
AModel answer
EXPIRE sets a countdown timer on a key after which it will be automatically deleted, TTL checks how much time remains before that countdown reaches zero, and PERSIST removes any existing expiration from a key, making it permanent again until explicitly deleted or given a new expiration.
Example

EXPIRE mykey 60 TTL mykey -- returns remaining seconds PERSIST mykey -- removes the expiration entirely

Real-world example
A promotional discount code is given a temporary expiration using EXPIRE, checked periodically with TTL to show a countdown to customers, and made permanent using PERSIST if the promotion is later extended indefinitely.
Likely follow-ups
  • What does TTL return if a key has no expiration set at all?
  • What does TTL return if the key does not exist at all?
Related topics