0
0
Redisquery~5 mins

Key expiry for memory management in Redis

Choose your learning style9 modes available
Introduction

Key expiry helps automatically remove old or unused data from memory. This keeps the database fast and saves space.

You want to store temporary login sessions that expire after some time.
You need to cache data that should refresh regularly.
You want to limit memory use by deleting old keys automatically.
You want to set reminders or time-limited offers in your app.
You want to avoid manual cleanup of expired data.
Syntax
Redis
EXPIRE key seconds
TTL key
PERSIST key

EXPIRE sets a time (in seconds) after which the key is deleted.

TTL shows how many seconds remain before the key expires.

PERSIST removes the expiration from the key, making it persistent.

Examples
Set the key 'session123' to expire in 300 seconds (5 minutes).
Redis
EXPIRE session123 300
Check how many seconds remain before 'session123' expires.
Redis
TTL session123
Remove the expiry from 'session123' so it stays forever.
Redis
PERSIST session123
Sample Program

This sets a key 'tempKey' with value 'hello', sets it to expire in 10 seconds, then checks how many seconds remain.

Redis
SET tempKey "hello"
EXPIRE tempKey 10
TTL tempKey
OutputSuccess
Important Notes

Expiry time counts down only when the key exists.

If you set EXPIRE on a key that does not exist, it returns 0 (failure).

Use PERSIST to cancel expiry if needed.

Summary

Key expiry automatically deletes keys after a set time.

Use EXPIRE to set expiry, TTL to check time left, and PERSIST to cancel expiry.

This helps manage memory by removing old data.