0
0
RedisHow-ToBeginner · 3 min read

How to Use EXPIRE Command in Redis for Key Expiration

Use the EXPIRE command in Redis to set a time-to-live (TTL) in seconds on a key, after which Redis will automatically delete it. The syntax is EXPIRE key seconds, where key is the name of the key and seconds is the expiration time.
📐

Syntax

The EXPIRE command sets a timeout on a key in seconds. After the timeout, the key is deleted automatically.

  • key: The name of the key you want to expire.
  • seconds: The time in seconds before the key expires.
redis
EXPIRE key seconds
💻

Example

This example shows how to set a key with a value and then set it to expire after 10 seconds.

redis
SET mykey "Hello"
EXPIRE mykey 10
TTL mykey
Output
OK (integer) 1 (integer) 10
⚠️

Common Pitfalls

Common mistakes include:

  • Setting expiration on a key that does not exist returns 0 and does nothing.
  • Using EXPIRE with a negative or zero time deletes the key immediately.
  • Forgetting that expiration time is in seconds, not milliseconds.
redis
EXPIRE nonexistingkey 10
# Returns 0 because key does not exist

EXPIRE mykey 0
# Deletes the key immediately
Output
(integer) 0 (integer) 1
📊

Quick Reference

CommandDescriptionReturn Value
EXPIRE key secondsSet expiration time in seconds1 if timeout set, 0 if key does not exist
TTL keyGet remaining time to live in secondsRemaining seconds or -1 if no timeout
PERSIST keyRemove expiration from key1 if timeout removed, 0 if key does not exist or has no timeout

Key Takeaways

Use EXPIRE to set a time-to-live on keys in seconds.
EXPIRE returns 1 if successful, 0 if the key does not exist.
Expiration time is in seconds, not milliseconds.
Keys expire automatically after the timeout and are deleted.
Use TTL to check remaining time before expiration.