How Redis TTL works ?

Mayank Jain
Javarevisited
Published in
2 min readApr 21, 2023

We all must have used Redis at some point of time while building large scale applications. Redis is an in-memory key value data store. It is a single threaded application.

Note — When we say that Redis is a single threaded application, we basically mean that one thread is used for all network calls for read and write. Other functionalities of redis like asynchronous replication and expiring keys are done in different threads.

We simply set a timeout on a key and when that timeout has elapsed the key will be marked as expired and it will be deleted from redis. So keys that have a timeout with them are also known as volatile keys.

Note — If we delete the key using DEL, then we can explicitly remove the key with TTL even if timeout has not elapsed.

Note — If we overwrite the value of any key using SET, then the the TTL associated with it will also be removed.

Note — We can also PERSIST a key, if there is a timeout attached with that key, the timeout will be removed and the key will remain in the redis memory unless cleared explicitly.

We created a key and set Expire as 100 seconds, and then we persisted it. So if we did TTL on that key it gives us -1. That means there is no TTL attached on the given key. TTL returns -2 if the mentioned key does not exist.

Have you ever wondered how redis expire keys ?

Let me explain it a bit. There are basically two ways that are used in redis —

  1. Passive way — In this way, the expired keys are deleted when they are accessed. Basically when a read request comes, the TTL of key is checked if it is expired then it is removed from redis memory. One problem with this approach is if keys are not accessed in the application then they will not be removed.
  2. Active way — Redis runs an expire cycle inside the keyspace and searches for the keys that have expire configured —

a) Selects a number of keys from the keyspace.

b) Removes the ones that are expired.

c) Repeats the process if more than 25% of the keys are expired.

References — https://redis.io/commands/expire/

--

--