Redis Keyspace Notifications for Expired Keys:

saurav omar
2 min readJun 8, 2019

--

Actually, I was trying to figuring out how to listen or subscribe on expired keys in Redis, then I came across notifications events in Redis. In this article, I will give you an overview of how to configure key space notifications events.

Enable keyspace notifications:

By default keyspace notifications are disabled in Redis due to performance impact. There are two ways we can enable this either using redis-cli or redis.conf file.

Enable Using Redis-CLI:

$ redis-cli config set notify-keyspace-events ExOK

Here we are only configured for expired events on keys so we used Ex

E: key events or events happening on keys

x: expired events

check for more events type these are the events which are present are copied from Redis documentation.

K     Keyspace events, published with __keyspace@<db>__ prefix.
E Keyevent events, published with __keyevent@<db>__ prefix.
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
$ String commands
l List commands
s Set commands
h Hash commands
z Sorted set commands
x Expired events (events generated every time a key expires)
e Evicted events (events generated when a key is evicted for maxmemory)
A Alias for g$lshzxe, so that the "AKE" string means all the events.

Enable Using Redis.conf:

Add line notify-keyspace-events Ex in redis.conf

See the second last line which is uncommented. We have configured this let’s see with an example.

  • Let’s set value and expire time as 5 sec for key redis first and subscriber for expired events
127.0.0.1:6379> SETEX redis  5 test OK
  • Now adding subscriber for expired events.
$redis-cli — csv psubscribe ‘__key*__:*’
Reading messages... (press Ctrl-C to quit)
"psubscribe","__key*__:*",1

After 5 seconds

redis-cli — csv psubscribe ‘__key*__:*’Reading messages… (press Ctrl-C to quit)“psubscribe”,”__key*__:*”,1“pmessage”,”__key*__:*”,”__keyevent@0__:expired”,”redis

Yay !!! it’s working.

That’s it.

PS: If you like these articles please clap and share it, It motivates to write more articles.

--

--