Skip to content

Keyspace Notifications

Redis can publish a Pub/Sub message whenever certain events happen — a key expires, a SET is issued, a DEL runs, and more. Your application subscribes to these channels to react without polling: for example, invalidate a local cache when a key expires, or trigger a background job when a specific key is written.

Redis exposes two channel types:

  • Keyevent channels — one channel per event type; the message payload is the key name. Pattern: __keyevent@<db>__:<event> (example: __keyevent@0__:expired)
  • Keyspace channels — one channel per key; the message payload is the event type. Pattern: __keyspace@<db>__:<keyname>

Keyspace notifications are disabled by default because publishing every event adds CPU overhead. Enable them with CONFIG SET at runtime or via redis.conf on startup.

The value is a string of flag characters that select which event classes to publish:

FlagEvents enabled
KKeyspace events (__keyspace@... channel)
EKeyevent events (__keyevent@... channel)
xExpired events (key TTL reached zero)
gGeneric commands: DEL, EXPIRE, RENAME, …
sSet commands (SADD, SREM, …)
lList commands (LPUSH, RPOP, …)

For production expiry notifications the common setting is Ex — keyevent channel (E) for expired events only (x):

notify-keyspace-events "Ex"

Or at runtime:

127.0.0.1:6379> CONFIG SET notify-keyspace-events Ex
OK

Keyspace notifications use a two-terminal workflow. Open Terminal 1 and subscribe before the key expires:

127.0.0.1:6379> PSUBSCRIBE __keyevent@0__:expired
Reading messages... (press Ctrl-C to quit)

In Terminal 2, set a key with a short TTL to trigger the event:

127.0.0.1:6379> SET demo:token "abc" EX 3
OK

After 3 seconds, Terminal 1 receives the notification:

1) "pmessage"
2) "__keyevent@0__:expired"
3) "__keyevent@0__:expired"
4) "demo:token"

The fourth line is the key name — your subscriber now knows exactly which key expired.

The commands below enable notifications and set a key with a TTL so you can observe the configuration in action. To see the expired event, open a second redis-cli, run PSUBSCRIBE __keyevent@0__:expired, then in the first terminal run SET demo:token "hello" EX 5 and wait 5 seconds.

CONFIG SET notify-keyspace-events Ex
SET demo:token "hello" EX 5
TTL demo:token
Which CONFIG flag enables keyevent channels (`__keyevent@...`)?
What channel pattern delivers expiry events on database 0?
Are keyspace notifications enabled by default in Redis?
Which PSUBSCRIBE pattern matches all keyevent channels on database 0?