Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does redis expire keys?

Tags:

redis

How does Redis implement the expiration of keys? From here I learnt that Redis stores the time at which the key will expire, but how exactly is this implemented?

like image 595
Ayush Gupta Avatar asked Mar 23 '16 08:03

Ayush Gupta


People also ask

Does Redis delete keys?

Deleting Keys Deleting a key in Redis is as simple as creating one. We use the DEL command followed by the name of the key we wish to remove. Redis will drop the key and its associated data if the specified key exists in the data store. You can also use the DEL command to remove multiple keys in a single instance.

How do I set Redis to expire?

To create a Redis with an expiration time, use the SET command and the EX option to set the expiration time. The EX option takes a number in seconds and sets the number of seconds the key is valid until expiration. You can also use PX to specify the expiration time in Milliseconds.

Which command is used to remove the expiration from a Redis key?

Redis - Keys Persist Command Redis PERSIST command is used to remove the expiration from the key.

How do Redis keys work?

Redis keys are binary safe, this means that you can use any binary sequence as a key, from a string like "foo" to the content of a JPEG file. The empty string is also a valid key. A few other rules about keys: Very long keys are not a good idea.


1 Answers

In short - for each redis object, there is an expiration time. Unless you set the object to expire, that time is "never".

Now, the expiration mechanism itself is semi-lazy. Lazy expiration means that you don't actually expire the objects until they are read. When reading an object, we check its expiration timestamp, and if it's in the past, we return nothing, and delete the object while we're at it. But the problem is that if a key is never touched, it just takes up memory for no reason.

So Redis adds a second layer of random active expiration. It just reads random keys all the time, and when an expired key is touched it is deleted based on the lazy mechanism. This does not affect the expire behavior, it just adds "garbage collection" of expired keys.

Of course the actual implementation is more complicated than this, but this is the main idea.

You can read more about it here: http://redis.io/commands/expire

And the source code for the active expiration cycle can be found here: https://github.com/antirez/redis/blob/a92921da135e38eedd89138e15fe9fd1ffdd9b48/src/expire.c#L98

like image 82
Not_a_Golfer Avatar answered Oct 07 '22 23:10

Not_a_Golfer