How does redis expire keys?

2019-02-07 20:43发布

问题:

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?

回答1:

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/unstable/src/server.c#L781



标签: redis