0
0
RedisHow-ToBeginner · 3 min read

How to Set Cache Expiration in Redis: Simple Guide

In Redis, you set cache expiration using the EXPIRE command to specify a time-to-live (TTL) in seconds for a key. Alternatively, you can use the SET command with the EX option to set a key with an expiration time in one step.
📐

Syntax

The EXPIRE command sets a timeout on a key in seconds, after which the key is deleted automatically. The SET command can also set a key with expiration using the EX option for seconds or PX for milliseconds.

  • EXPIRE key seconds: Set expiration time in seconds.
  • SET key value EX seconds: Set key with value and expiration in seconds.
redis
EXPIRE mykey 60
SET mykey "value" EX 60
💻

Example

This example shows how to set a key with a value and expire it after 10 seconds using both EXPIRE and SET commands.

redis
SET session_token "abc123"
EXPIRE session_token 10
TTL session_token

SET cache_item "data" EX 10
TTL cache_item
Output
OK 1 10 OK 10
⚠️

Common Pitfalls

One common mistake is forgetting to set expiration, which causes keys to persist indefinitely and can fill up memory. Another is setting expiration on a key that does not exist, which returns 0 and does nothing. Also, using SET without expiration when you want a temporary cache is a frequent error.

redis
EXPIRE missing_key 30  # returns 0 because key does not exist

# Correct way:
SET temp_key "value" EX 30  # sets key with expiration in one step
📊

Quick Reference

CommandDescriptionExample
EXPIRE key secondsSet expiration time in secondsEXPIRE mykey 60
SET key value EX secondsSet key with value and expirationSET mykey "val" EX 60
TTL keyCheck remaining time to liveTTL mykey

Key Takeaways

Use EXPIRE to add expiration to existing keys in seconds.
Use SET with EX option to set key and expiration in one command.
Check TTL to see how much time is left before a key expires.
Remember keys without expiration persist and can fill memory.
Setting expiration on non-existing keys does nothing.