How to Use PERSIST Command in Redis to Remove Key Expiration
In Redis, use the
PERSIST command to remove the expiration time from a key, making it permanent. This command returns 1 if the timeout was removed and 0 if the key did not have an expiration or does not exist.Syntax
The PERSIST command syntax is simple and requires only the key name as an argument.
PERSIST key: Removes the expiration from the specifiedkey.
If the key exists and had an expiration, it becomes persistent (no expiration).
redis
PERSIST key
Example
This example shows how to set a key with expiration and then remove that expiration using PERSIST.
redis
SET mykey "hello" EXPIRE mykey 10 TTL mykey PERSIST mykey TTL mykey
Output
OK
(integer) 1
(integer) 10
(integer) 1
(integer) -1
Common Pitfalls
Common mistakes when using PERSIST include:
- Trying to persist a key that does not exist returns 0 and does nothing.
- Calling
PERSISTon a key without expiration also returns 0 because there is no timeout to remove. - Expecting
PERSISTto delete the key instead of removing expiration is incorrect.
redis
PERSIST nonexistingkey PERSIST mykey_without_expire
Output
(integer) 0
(integer) 0
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| PERSIST key | Removes expiration from key | 1 if timeout removed, 0 otherwise |
| TTL key | Returns time to live in seconds | Remaining seconds or -1 if no expiration |
| EXPIRE key seconds | Sets expiration time | 1 if set, 0 if key missing |
Key Takeaways
Use
PERSIST to remove expiration from a Redis key, making it permanent.PERSIST returns 1 if expiration was removed, 0 if key missing or no expiration.Check key expiration with
TTL before and after using PERSIST.Do not confuse
PERSIST with commands that delete keys; it only removes expiration.If a key has no expiration,
PERSIST has no effect and returns 0.