Skip to content

Redis keyspace notifications and expired events — how to configure them and where they stop being reliable

Composing the notify-keyspace-events flag string, subscribing to the keyspace and keyevent channel families, why an expired event lags the TTL, what replication and Cluster change, and when to reach for a Stream consumer group instead.

Redis can publish a Pub/Sub message every time a key is written, deleted, or expires. You switch it on with the notify-keyspace-events parameter, a string of class flags: K enables the __keyspace@<db>__:<key> channels, E enables the __keyevent@<db>__:<event> channels, and the remaining letters select which event classes are emitted — Ex gives you expired-key events and nothing else, KEA gives you almost everything. The mechanism is genuinely useful for cache invalidation and for nudging a worker awake. It is also plain Pub/Sub, which means fire-and-forget: a subscriber that is disconnected at the moment of publication never sees that message, and no reconnect logic will bring it back. This guide covers the configuration properly, then the four caveats — timing, replication, cost, Cluster — that decide whether you should be using it at all.

What you’ll accomplish

  • Compose a notify-keyspace-events flag string deliberately instead of pasting KEA from somewhere and hoping.
  • Subscribe to the right channel family for the question you are asking, and read the message shape correctly.
  • Persist the setting so it survives a restart, on a self-managed server and on a managed provider.
  • Explain why an expired event can arrive seconds after the TTL reached zero, and why a replica reports it differently from the primary.
  • Recognise the workloads where a Stream consumer group or a sorted-set delay queue is the correct tool instead.

Prerequisites

  • Redis 2.8 or newer for the feature itself. Key-miss events (m) arrived in 6.0 and new-key events (n) in 7.0; the overwritten (o) and type-changed (c) classes are newer still. Check what your build actually accepts rather than assuming — CONFIG SET rejects unknown class letters outright.
  • A writable config file if you want the setting to persist. CONFIG SET is runtime only. CONFIG REWRITE writes the running configuration back to the file the server was started with; if the server was started without a config file, CONFIG REWRITE returns an error and you must edit redis.conf and restart instead.
  • Awareness of what your managed provider allows. AWS ElastiCache exposes notify-keyspace-events as a parameter-group value, empty by default; Azure Cache for Redis exposes it through its own configuration surface. Several providers restrict which classes you may enable, and a few refuse the parameter outright.
  • Channel permissions if ACLs are on. From Redis 6, acl-pubsub-default can be set to resetchannels, in which case a user with no explicit channel grant can subscribe to nothing at all. The subscriber needs +subscribe, +psubscribe, and a channel pattern that covers the notification channels.
  • Two terminals with redis-cli, because the only honest way to validate this is to watch one while driving the other.

How it works

Every operation that actually changes a key produces two messages on two different channels. A DEL on mykey in database 0 is exactly equivalent to these two publishes:

PUBLISH __keyspace@0__:mykey del
PUBLISH __keyevent@0__:del mykey

Read that carefully, because it is the detail people get backwards:

  • The key-space channel is named after the key; the message body is the event name.
  • The key-event channel is named after the event; the message body is the key name.

So “tell me everything that happens to session:42” is a key-space subscription, and “tell me every key that expired” is a key-event subscription. Most expiry pipelines want the second one.

The class flags you can compose into notify-keyspace-events:

K   key-space channels, __keyspace@<db>__ prefix
E   key-event channels, __keyevent@<db>__ prefix
g   generic commands (DEL, EXPIRE, RENAME, ...)
$   string commands
l   list commands
s   set commands
h   hash commands
z   sorted set commands
t   stream commands
d   module key type events
a   array commands
x   expired events
e   evicted events
m   key-miss events        (not in A)
n   new-key events         (not in A)
o   overwritten events     (not in A)
c   type-changed events    (not in A)
A   alias for g$lshztdxea

At least one of K or E has to be present, otherwise nothing is delivered no matter what else the string contains — a string of just x is silently inert. Ex means “key-event channels, expired class only”. KEA means “both channel families, every class except m, n, o and c”, which is the right setting while exploring and the wrong one in production.

Path of an expired event from a SET with a TTL through lazy or active removal to the two notification channels, with a disconnected subscriber losing the message permanently

The expired event lags the TTL, sometimes badly. Redis removes a key with a TTL in one of two ways: a command touches the key and finds it expired, or the background active-expire cycle samples keys with a TTL and collects the dead ones. The expired event is generated when the server actually deletes the key, not when the time to live theoretically reaches zero. If nothing touches the key and the instance holds a large volume of volatile keys, the delay between “TTL hit zero” and “event published” can be significant. Treat the event as an eventual signal, never as a scheduler tick.

Replication changes who emits what, and when. A replica does not expire keys on its own clock. The primary decides a key is gone and propagates an explicit deletion, which the replica applies — so expiry events on a replica follow replication, not the replica’s own TTL bookkeeping. The timing there tracks replication lag, and if you subscribe on the primary and on a replica the same logical expiry surfaces twice. Pin these subscriptions to one node explicitly rather than letting a failover-aware client wander.

Notifications cost CPU on the write path. Each qualifying write builds channel names and dispatches through the Pub/Sub machinery, and every published message is matched against every registered psubscribe pattern. On a write-heavy instance running KEA with a few broad patterns, that shows up in latency percentiles. Enable the narrowest class set that answers the question you have.

Cluster does not broadcast keyspace events. Ordinary Pub/Sub traffic is propagated across the cluster bus; keyspace notifications are not. Each node generates events only for the slots it owns, so a client connected to one node sees only that node’s keyspace. Observing everything takes one subscriber per master, connected directly. Sharded Pub/Sub (SSUBSCRIBE and SPUBLISH, Redis 7.0) gives you slot-scoped channels for messages you publish yourself — it does not turn keyspace notifications into a cluster-wide feed.

Step-by-step

1. Check what is configured today. The default is off.

redis-cli CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) ""

2. Enable the narrowest thing that works. For an expiry pipeline, that is expired events on the key-event channels only.

redis-cli CONFIG SET notify-keyspace-events "Ex"
OK

Read it back. The server normalises and reorders the string, which surprises people the first time:

redis-cli CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) "xE"

xE and Ex are the same setting. If you get an empty string back after a successful CONFIG SET, you passed class letters with neither K nor E.

3. Persist the setting. CONFIG SET alone dies with the process.

redis-cli CONFIG REWRITE
OK
grep -n '^notify-keyspace-events' /etc/redis/redis.conf
1053:notify-keyspace-events "xE"

If CONFIG REWRITE errors out complaining about the absence of a config file, the server was started without one — edit the file yourself and restart.

4. Or set it in the config file directly, which is the form that survives a rebuild of the host from configuration management:

notify-keyspace-events "Ex"
sudo systemctl restart redis-server && redis-cli CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) "xE"

5. Subscribe to the expired channel. The @0 is a literal database number, not a wildcard.

redis-cli psubscribe '__keyevent@0__:expired'
Reading messages... (press Ctrl-C to quit or any key to type command)
1) "psubscribe"
2) "__keyevent@0__:expired"
3) (integer) 1

A client working in database 3 must subscribe to __keyevent@3__:expired; widen the pattern to __keyevent@*__:expired for every database at once. Always quote the pattern in the shell, or the * gets expanded before it reaches Redis.

6. Watch every event while you are still exploring. This is the fastest way to learn which command emits which event name, and it is exactly what the Redis documentation suggests:

redis-cli --csv psubscribe '__key*__:*'
"psubscribe","__key*__:*",1
"pmessage","__key*__:*","__keyspace@0__:foo","set"
"pmessage","__key*__:*","__keyevent@0__:set","foo"

That pattern needs KEA; both belong in a development environment only.

7. Grant channel access if you run with ACLs.

redis-cli ACL SETUSER expiry-worker on '&__keyevent@0__:expired' +subscribe +psubscribe +ping
OK
redis-cli ACL LIST
1) "user default on nopass sanitize-payload ~* &* +@all"
2) "user expiry-worker on sanitize-payload resetchannels &__keyevent@0__:expired -@all +ping +psubscribe +subscribe"

The resetchannels in that line is the important part: the user can reach exactly one channel pattern and nothing else. Give the worker a password and persist the ACL file separately — see Redis ACL users and roles for the full treatment.

Validate it works

Terminal one, subscribe:

redis-cli --csv psubscribe '__keyevent@0__:expired'
"psubscribe","__keyevent@0__:expired",1

Terminal two, create a key with a three-second TTL:

redis-cli SET session:42 abc PX 3000
OK

Back in terminal one, within a few seconds:

"pmessage","__keyevent@0__:expired","__keyevent@0__:expired","session:42"

If nothing appears after ten seconds or so, force the lazy path by reading the key:

redis-cli GET session:42
(nil)

The read finds the key expired, removes it, and the event fires immediately. That is a useful diagnostic in itself: if events only ever appear when you touch the key, the active expire cycle is not keeping up — look at hz and at the instance’s CPU headroom.

Confirm from the server’s side that the subscription is really registered, rather than trusting the client:

redis-cli PUBSUB NUMPAT
(integer) 1

And cross-check the expiry counters, which move independently of whether anyone is listening:

redis-cli INFO stats | grep -E '^expired_'
expired_keys:1482
expired_stale_perc:0.00
expired_time_cap_reached_count:0

A climbing expired_keys with no messages arriving means the notification path is broken, not the expiry path.

Troubleshooting

No events at all, on any channel. In order: confirm the flag string contains K or E (CONFIG GET returning "" right after a successful CONFIG SET is the tell); confirm the database number in the channel name matches the database your writes go to; confirm the subscriber’s ACL grants the channel. On a managed instance, also confirm the provider actually applied the parameter — several require a reboot before a parameter-group change takes effect on the running node.

The expired event never arrives for a key you know had a TTL. Two real causes. First, the key was removed by something other than expiry: an explicit DEL, an EXPIRE with a timestamp already in the past (which deletes the key and emits del, not expired), or eviction under maxmemory (which emits evicted). Second, nothing has touched the key and the active cycle has not reached it yet. Widen the classes temporarily to see which one it is:

redis-cli CONFIG SET notify-keyspace-events "KEgxe"
OK

Eviction is the common surprise on instances running near their memory ceiling — Redis eviction policies and their trade-offs covers why a key can vanish long before its TTL.

Events stop arriving after a network blip, and the subscriber looks healthy. This is the expected behaviour, not a bug. Client libraries reconnect and resubscribe quietly, so the connection looks fine while everything published during the outage is gone. Instrument it: log every reconnect on the subscriber and emit a metric, then reconcile state on reconnect — scan the affected key range, compare against your own records — rather than assuming the message flow was continuous. If reconciliation is impractical, the design is wrong; see the next section.

Nothing arrives in Cluster mode. You are subscribed to one node and watching keys that hash to a different node. List the masters and put a subscriber on each:

redis-cli -c CLUSTER NODES | awk '$3 ~ /master/ {print $2}'
10.0.1.11:6379@16379
10.0.1.12:6379@16379
10.0.1.13:6379@16379

Then run one subscriber per address, connecting directly rather than through a cluster-aware client that will redirect you elsewhere. A failover changes which node owns which slots, so the subscriber set has to be rebuilt when the topology moves.

The setting is gone after a restart. CONFIG SET is runtime state. Either you skipped CONFIG REWRITE, or the rewrite landed in a config file your deployment tooling overwrites on the next run, or a maintenance event reset a managed node to its parameter group. Put the value where configuration management can assert it, and add a startup check that reads CONFIG GET notify-keyspace-events and alerts when it comes back empty.

When this is the wrong approach

  • Anything where a lost event costs money or correctness. Delayed job execution, order timeouts, billing state transitions, “delete the object storage blob when the session dies”. Pub/Sub offers best-effort delivery with no delivery guarantee, and a subscriber restart during a deploy is enough to drop events. Use a Stream instead: XADD on the producing side, a consumer group reading with XREADGROUP, XACK when the work is genuinely done, and XAUTOCLAIM to recover entries a dead consumer never acknowledged. The pending-entries list is an at-least-once ledger you can inspect.

Best-effort Pub/Sub loses the event published while the subscriber is offline, while a Stream consumer group keeps the entry until it is acknowledged

redis-cli XADD jobs:expiry '*' key session:42 reason ttl
"1785000000000-0"
redis-cli XGROUP CREATE jobs:expiry cleanup 0
OK

From there, XREADGROUP GROUP cleanup worker-1 COUNT 10 BLOCK 5000 STREAMS jobs:expiry '>' hands entries to a named consumer, and anything not acknowledged stays visible. Redis Streams with XADD and XREAD walks through the whole pattern.

  • Scheduling work at a specific time. The expired event is not a timer — it fires when the server gets around to deleting the key. A sorted set keyed by due timestamp gives you an ordered, durable, inspectable backlog and a polling interval you control: ZADD the job with its due time as the score, then have workers pop everything scored below “now”. Redis key expiration patterns compares the options.

  • High write volume with broad classes. If covering your cases means enabling A on an instance doing tens of thousands of writes per second, the notification overhead is a real tax for a signal you cannot rely on. Publish the events you care about explicitly from the application, where you control the shape and the cost.

  • You need one connection to see the whole cluster. Keyspace events are node-local by design. If the operational model cannot tolerate one subscriber per master plus a rebuild on failover, do not build on this — and check first whether your managed provider even exposes the parameter, since some restrict the class set and a few disallow it entirely.

The authoritative reference is the Redis documentation on keyspace notifications, which lists the event name generated by every command, alongside the Streams page for the durable alternative.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.