Learn how to manage expiration and TTL (Time-To-Live) in Redis using PHP. Automatically remove outdated data and optimize memory usage with EXPIRE
, TTL
, and PERSIST
.
Introduction
Redis provides automatic expiration (TTL) to remove outdated keys, preventing memory overflow and ensuring fresh data. By setting expiration times, you can efficiently manage:
- Session expiration for logged-in users
- Temporary caching for frequently accessed data
- Token expiration for authentication systems
This guide covers:
- Setting and checking TTL (Time-To-Live) for Redis keys
- Using
EXPIRE
,TTL
,PERSIST
, andSETEX
for key management - Implementing auto-expiring cache in PHP
1. Understanding Redis Expiration and TTL
Redis allows setting a time-to-live (TTL) for each key. When a key reaches its TTL, Redis automatically removes it.
Commands used for expiration management:
Command | Description |
---|---|
EXPIRE key seconds |
Set expiration time (in seconds) for a key |
TTL key |
Check the remaining TTL for a key |
PERSIST key |
Remove expiration and make key permanent |
SETEX key seconds value |
Set a key with expiration in one step |
PEXPIRE key milliseconds |
Set expiration in milliseconds |
2. Setting Expiration for Redis Keys in PHP
Using EXPIRE
to Set Key Expiration
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set("session:user123", "John Doe");
$redis->expire("session:user123", 3600); // Expires in 1 hour
Using SETEX
for Expiring Keys
SETEX
combines setting a value and defining expiration in a single command.
$redis->setex("auth_token:abc123", 600, "Token Data"); // Expires in 10 minutes
Using PEXPIRE
for Millisecond-Level Expiration
$redis->pexpire("temp_data", 1500); // Expires in 1.5 seconds
3. Checking Expiration Status with TTL
To check how much time remains before a key expires:
$ttl = $redis->ttl("session:user123");
echo "Time remaining: $ttl seconds";
Possible Outputs:
600
→ 10 minutes left-2
→ Key does not exist-1
→ Key exists without expiration
4. Removing Expiration Using PERSIST
If a key has an expiration time but needs to be made permanent, use PERSIST
.
$redis->persist("session:user123"); // Removes TTL, key never expires
5. Implementing Auto-Expiring Cache in PHP
Example: Caching API Data with Expiration
$cacheKey = "weather:city:NewYork";
$cachedData = $redis->get($cacheKey);
if ($cachedData) {
echo "Serving from cache: " . json_decode($cachedData, true);
exit;
}
// Fetch data from API
$weatherData = ["temp" => 72, "humidity" => 50]; // Simulated API response
$redis->setex($cacheKey, 1800, json_encode($weatherData)); // Cache for 30 minutes
echo "Fetched new data: " . json_encode($weatherData);
This ensures:
- API calls are minimized
- Fresh data is served when cache expires
6. Automatically Removing Expired Keys with EXPIRE
Keys with expiration do not require manual deletion. Redis automatically removes them when TTL reaches zero.
However, you can manually delete keys:
$redis->del("session:user123");
7. Best Practices for Managing Redis Expiration
✅ Use expiration (EXPIRE
, SETEX
) for temporary data to prevent memory issues.
✅ Check TTL (TTL key
) before assuming data exists.
✅ Use PERSIST
carefully—removing expiration means the key never expires.
✅ Monitor Redis memory to track expired key removals.
✅ Use PEXPIRE
for high-precision timing when needed.
Conclusion
Managing expiration and TTL in Redis optimizes memory usage and ensures data freshness.
This guide covered:
- Setting expiration using
EXPIRE
,SETEX
, andPEXPIRE
- Checking TTL with
TTL
command - Making keys permanent with
PERSIST
- Implementing auto-expiring cache in PHP
By applying these techniques, your PHP applications can efficiently manage Redis data storage while preventing outdated information from persisting unnecessarily.