Redis notes
Redis Pub/Sub: How It Works and Where to Use It
Publish/subscribe lets one program announce something to every program that is listening right now, without knowing who they are. These notes cover what Redis guarantees and what it does not, how delivery works underneath, the classic lost-message race and its fix, and twelve small Python examples with redis-py. Every example was run with redis-py 7 against a local Redis 8.10.3, and its output is pasted from that run.
The idea
Part 1 of 6 · channels, and what Redis promises about them
What Pub/Sub is
Publish/subscribe is a messaging pattern where senders (publishers) do not send to specific receivers. They send to a named channel, and Redis delivers the message to every client subscribed to that channel at that moment.
- A channel is just a name, such as
news:sportsorjob:42:cancel. Nothing is stored under it. - SUBSCRIBE means "send me everything published on this channel from now on". The connection then waits and listens.
- PUBLISH means "send this to whoever is listening on this channel right now". It returns how many clients received it.
| Pipe picture | What it really is in Redis |
|---|---|
| The pipe | The channel name |
| Dropping a message in one end | PUBLISH <channel> <message> |
| An outlet at the other end | One connection that ran SUBSCRIBE <channel> |
| How many outlets | PUBSUB NUMSUB <channel> |
| No outlets left | The last subscriber unsubscribed: the channel disappears, and PUBLISH returns 0 |
Decoupling: publishers and subscribers share only the channel name. Neither knows the other exists, how many there are, or where they run.
Live radio, not a mailbox
- Pub/Sub works like live radio. If your radio is on, you hear the announcement. If it was off, the announcement is gone, and there is no replay.
- A Redis key works like a notice on a board.
SETstays until it is deleted or expires, and anyone canGETit later, but nobody is notified when it changes.
Robust designs combine the two: the key holds the truth, the message says "go and look". See Lost messages and the fix.
Guarantees, and what you do not get
| Property | What it means |
|---|---|
| Created on use | A channel exists from the first SUBSCRIBE until the last UNSUBSCRIBE. You never create or delete it. KEYS never lists it; PUBSUB CHANNELS does. |
| Fan-out | Every current subscriber gets its own copy of every message. |
| At-most-once | Each subscriber gets a message once, or not at all if it is disconnected or not yet subscribed. No acknowledgements, no retries. |
| No history | Messages are never stored. A subscriber that joins later sees only new messages. |
| Ordering | One subscriber sees the messages of one channel in the order Redis received them. |
| Not tied to a database number | Channels are global to the server, not per SELECTed database. Keyspace notifications are the exception. |
Interview line: Redis Pub/Sub is fire-and-forget fan-out with at-most-once delivery and no persistence. If a message must not be lost, it is the wrong tool on its own.
Fan-out versus a work queue
| Pub/Sub channel | Work queue (List + BRPOP, or Stream consumer groups) | |
|---|---|---|
| A message goes to | Every current subscriber | Exactly one worker |
| If nobody is listening | The message is lost | The message waits |
| Use for | Notifying whoever cares, right now | Sharing out jobs so each is done once |
| Like | A radio broadcast | A ticket at a counter |
Both halves run in example 3.
First examples
Part 2 of 6 · setup, then four programs of a dozen lines each
Setup
You need a Redis server on the default port and the Python client.
Each example is followed by its real output. Details that depend on timing, such as how many chunks a job prints before it is cancelled, will differ a little on your machine.
Every example connects with redis.Redis(decode_responses=True): localhost, port 6379, and strings returned as str, not bytes. All channel and key names are made up.
Use a throwaway Redis. The examples create and delete a few keys (jobs, orders, job:42:status and similar). Do not point them at a server that holds real data.
1. Hello Pub/Sub
One subscriber, one publisher, in one script. r.pubsub() creates a subscriber object with its own connection; r.publish() uses the normal one.
- The first thing a subscriber receives is a confirmation, type
subscribe, whosedatais the number of channels this connection now listens to. publishreturned1: one client received the message. It is a count of deliveries at that instant, not a promise that anything was processed.- A real message has type
message.patternisNonebecause the subscription was to an exact name.
2. The lost message
Publish before anyone subscribes, then subscribe and wait. The message does not turn up.
Remember this output. receivers: 0 is not an error and raises nothing. The publisher cannot tell "nobody cares" from "the listener was one millisecond late". Part 4 is about living with that.
3. Fan-out vs queue
The same two consumers, first as subscribers to a channel, then as workers popping from a list.
- On the channel both subscribers got
order-1. If they were workers, the order would be processed twice. - On the list each job went to one worker, and the third
BRPOPfound nothing and gave up after its 1 second timeout. LPUSHadds at the left andBRPOPtakes from the right, so the list behaves as a first-in, first-out queue.
4. Pattern subscribe
PSUBSCRIBE takes a glob. One subscription then covers every channel whose name matches, including channels that do not exist yet.
- The message type is
pmessage, and it carries both thepatternthat matched and the realchannel. payments:newdid not match, sopublishreturned0.- Glob syntax:
*any characters,?one character,[ab]one of a set. A client subscribed to bothorders:newandorders:*receives the message twice, once per subscription.
Commands and message shapes
| Command | What it does | In redis-py |
|---|---|---|
PUBLISH channel message | Sends to every current subscriber, returns the count | r.publish(channel, message) |
SUBSCRIBE channel [channel ...] | Listens to exact channel names | p.subscribe(...) |
UNSUBSCRIBE [channel ...] | Stops listening (all channels if none given) | p.unsubscribe(...) |
PSUBSCRIBE pattern [pattern ...] | Listens to every channel matching a glob | p.psubscribe(...) |
PUNSUBSCRIBE [pattern ...] | Stops pattern subscriptions | p.punsubscribe(...) |
PUBSUB CHANNELS [pattern] | Lists channels with at least one direct subscriber | r.pubsub_channels() |
PUBSUB NUMSUB [channel ...] | Counts direct subscribers per channel | r.pubsub_numsub(...) |
PUBSUB NUMPAT | Counts pattern subscriptions | r.pubsub_numpat() |
SPUBLISH / SSUBSCRIBE / SUNSUBSCRIBE | Sharded Pub/Sub for Redis Cluster (Redis 7 and later), see Cluster and security | r.spublish, p.ssubscribe |
What a subscriber receives, on the wire and as a redis-py dict:
| Kind | Raw reply | redis-py type |
|---|---|---|
| Message | ["message", channel, data] | message |
| Message from a pattern subscription | ["pmessage", pattern, channel, data] | pmessage |
| Confirmation | ["subscribe", channel, count], where count is the subscriptions on this connection | subscribe, unsubscribe, psubscribe, punsubscribe |
Three ways to read in redis-py: p.get_message(timeout=1) returns one message or None; for message in p.listen() blocks for ever; and p.run_in_thread() reads in a background thread and calls your handlers.
How it works underneath
Part 3 of 6 · connections, the channel table and the wire format
Clients dial Redis, never the reverse
Every publisher and subscriber opens its own TCP connection to Redis (port 6379 by default). Redis keeps a table in memory: channel name to the list of subscribed connections, and pattern to the list of pattern-subscribed connections.
On PUBLISH, Redis looks up the channel name and the matching patterns and writes the message to each of those already-open sockets. It never needs a subscriber's IP address or host name. That is why Pub/Sub works across many app servers, containers or pods: each one connects out to the same Redis.
A subscribed connection is busy
In RESP2, the protocol most clients use by default, a connection that has subscribed may only run SUBSCRIBE, PSUBSCRIBE, SSUBSCRIBE, their unsubscribe forms, PING, QUIT and RESET. It cannot GET or SET.
So client libraries give subscriptions a dedicated connection. In redis-py that is what r.pubsub() is: a second connection beside the one used for normal commands. RESP3 lifts the restriction by sending pushes alongside normal replies.
Plan for it: one extra connection per subscriber object. Example 10 shows what happens when that is forgotten.
On the wire: RESP
Redis speaks RESP: text lines ending in \r\n, where *N starts an array of N items, $N a string of N bytes and :N an integer.
redis-py turns that last reply into the dict printed in example 1. There is no message id, no timestamp and no sender in it: if the receiver needs any of those, put them in the payload, for example as JSON.
Slow subscribers get disconnected
Redis buffers outgoing messages per client. If a subscriber reads too slowly, its buffer grows, and past the limit Redis closes the connection. The setting is client-output-buffer-limit pubsub, by default 32mb 8mb 60: disconnect at 32 MB, or when the buffer stays above 8 MB for 60 seconds.
- Keep message handlers fast. Hand heavy work to a queue, a thread pool or an asyncio task.
- Publish small messages: an id or a key name, not the whole object.
- After a disconnect the subscriber has missed messages, with no way to know which. Reconnect, re-subscribe, and re-read state from keys.
Lost messages and the fix
Part 4 of 6 · the classic race, and the pattern that removes it
The race
PUBLISH to a channel with no subscribers returns 0 and the message is gone. Subscribing a moment later does not bring it back. This bites whenever two things happen close together: "I published the event just before the other side finished subscribing."
The fix: key first, then publish
The sender writes durable state first, then publishes. The receiver subscribes first, then reads the state.
| Timing | How the receiver learns |
|---|---|
| Receiver subscribed before the sender published | The live message arrives |
| Sender finished before the receiver subscribed | The GET right after subscribing returns the state |
| Both at the same moment | One of the two, sometimes both, so the receiver's action must be safe to run twice |
The rule: the key is the source of truth, the message is only a fast nudge. The order matters on both sides: SET before PUBLISH, and SUBSCRIBE before GET. Reverse either and a gap opens again.
7. Key-then-publish in code
The race, the fix, and a Lua script for when the state change has to be conditional and atomic: "only set cancelled if the job has not already completed".
- Both publishes reached 0 receivers. The first lost the signal; the second did not matter, because the key held it.
- A Lua script runs inside Redis as one step, so no other client can change the key between the
GETand theSET. Job 44 was alreadycompleted, and stayed so. - Give the status key a TTL (
EX), or finished jobs pile up for ever.
Naming channels and keys
| Tip | Example | Why |
|---|---|---|
Use {env}:{app}:{purpose}:{id} | prod:shop:cache-invalidate:product:123 | The environment prefix stops dev and prod clients that share a Redis from crossing wires |
| Put state in values, not in key names | One job:42:status whose value changes, not job:42:queued then job:42:running | One key to read, one to expire, no stale leftovers |
| Name by purpose, with nouns | status, cancel-signal, events | Names such as channel or string say what the Redis type is, not what it is for |
| Normalise ids the same way on both sides | Lower-case canonical UUIDs | Publisher and subscriber must build exactly the same string, or they never meet |
Use cases
Part 5 of 6 · where it fits, in running code, and where it does not
Good fits
| Use case | How Pub/Sub is used | Notes |
|---|---|---|
| Cache invalidation across app servers | Each server keeps an in-memory cache and subscribes to cache-invalidate. On a write, publish the key, and every server drops that entry. | Fan-out is exactly what is wanted. A missed message means a stale entry, so pair it with short TTLs. Example 5. |
| Scaling WebSockets or SSE across nodes | Users are connected to different nodes. A node publishes to chat:room:7, and every node subscribed for that room pushes the message to its own users. | The standard way to make chat or notifications horizontal. Store history separately. Example 6. |
| Live dashboards and notifications | Workers publish orders:new, deploy:status, metrics:cpu; a gateway subscribes and forwards to browsers. | Good when the latest value matters and history does not. |
| Config or feature-flag reload | Write the new config to a key, then PUBLISH config:reload v42; every service reloads. | Key-then-publish, so a restarting service still picks up the latest version. |
| Cancel a long-running job on another server | One channel per job, job:{id}:cancel. The server running the job subscribes; any server can publish. | Combine with a status key. Example 8. |
| Presence and typing indicators | PUBLISH room:7:typing alice | Losing one is harmless, which suits at-most-once delivery. |
| Keyspace notifications | Redis itself publishes when keys change or expire. | Example 9. |
| Debugging | PSUBSCRIBE app:* in redis-cli to watch events live. | Fan-out means listening in never disturbs the real subscribers. |
5. Cache invalidation across app servers
Each app server keeps prices in a local dict so it does not ask the database on every request. When a price changes, every server must forget its copy.
The "database" here is a plain Redis key, db:product:123. Start two servers in two terminals, then run the update in a third.
- Write the database first, then publish. In the other order a server could reload the old price.
- The message carries only the key name. Each server reads the new value itself, so there is one source of truth.
- A server that was restarting misses the message, but it also starts with an empty cache. A server whose connection dropped for a moment keeps a stale entry: give cache entries a short lifetime as a safety net.
6. Chat across nodes
A WebSocket is a connection to one server. With two servers behind a load balancer, Alice and Bob may be on different ones, and a node can only write to its own sockets. Pub/Sub is the link between the nodes.
The demo connects Alice to the node on port 9001 and Bob to the node on port 9002.
- A node never sends a user's message straight to its local sockets. It publishes, and delivers only what comes back from Redis. The sender's own node is just another subscriber, which keeps one code path and one ordering.
- One subscriber connection per node serves every user on that node. Do not create one per WebSocket.
- Someone who joins late sees nothing from before. Chat history belongs in a database or a Stream.
8. Cancel a job on another server
A long job runs on one server. The "cancel" request lands on a different one. Per-job channel plus status key: the key-then-publish pattern with asyncio.
- Nothing is killed. Cancelling an asyncio task raises
CancelledErrorinside it at its nextawait, so the job can clean up: save partial output, close upstream connections. - One channel per job means only the server running that job receives the message. No broadcast to filter, no lookup of "which server has job 42".
- No sticky sessions needed. Any server can publish, and Redis delivers down the subscriber's own connection.
- Run
cancelfirst andrunsecond, and the job stops at once: that is theGETafterSUBSCRIBEdoing its work. Note thatrun_jobsets the status torunningat the start, so in real code use the Lua script to avoid overwriting a cancel that arrived first.
9. Keyspace notifications
Redis can publish its own events when keys change. They are off by default. notify-keyspace-events Ex turns on one kind: a message on __keyevent@0__:expired each time a key in database 0 expires.
- The message data is the name of the key that expired. The value is already gone.
- The event fires when Redis actually removes the key, which can be a little after the TTL, and later still on a busy server.
- It is ordinary Pub/Sub, so it is at-most-once: a listener that is down misses expiries. Do not build billing or anything that must happen on it.
- This is the one place where the database number matters: the
@0in the channel name.
Bad fits, and what to use instead
| Need | Why Pub/Sub fails | Use instead |
|---|---|---|
| Every message must be processed, even after a crash or restart | At-most-once, no history | Redis Streams (XADD, consumer groups, XACK), or a broker such as Kafka or RabbitMQ |
| Each job done by exactly one worker | Fan-out gives it to all | A List with BRPOP, or Stream consumer groups |
| Replay or audit of past events | Nothing is stored | Streams or a database |
| Very slow consumers | They get disconnected at the output buffer limit | Streams or a queue |
| Pub/Sub | Streams | Lists | |
|---|---|---|---|
| Stored | No | Yes, until trimmed | Yes |
| Delivery | To all current subscribers | Readers choose; consumer groups split the work | One consumer pops each item |
| Late joiner | Misses past messages | Can read from any id | Gets what is still in the list |
| Acknowledgement | No | Yes, XACK | No (use LMOVE for reliability) |
| Best for | Instant notifications | Event logs, reliable processing, resuming | Simple job queues |
12. Streams contrast
The same order events, written with XADD before any reader exists. Compare with example 2.
- The late reader got all three. Every entry has an id, and a reader says where to start:
"0"for the beginning,"$"for only new entries, or the last id it handled. - Remembering that last id is what lets a consumer restart and carry on where it stopped.
- The entries stay in the stream. Trim it, for example
XADD ... MAXLEN ~ 10000, or it grows without limit.
Operating it
Part 6 of 6 · connections, visibility, cluster and a recap
10. Connection limits
Each subscriber object holds a connection for as long as it lives. A process that creates one per request, user or job runs out. Here the pool allows 5 connections and six jobs each want their own subscriber.
- redis-py's default
ConnectionPoolraises at once when it is full.BlockingConnectionPoolwaits for a free connection instead, which turns the error into a stall. - The second half is the design to prefer: one shared subscriber per process, subscribed to many channels and dispatching each message to a local handler. One connection carried 100 subscriptions here, and can carry thousands.
- Passing
channel=handlertosubscribemakesget_messagecall the handler and returnNonefor that message.
Sizing connections
If each in-flight task holds k long-lived connections:
Then check the server side: maxclients (10000 by default) against processes x pool size. With a shared subscriber, k drops to the connections a task really needs for commands, and the subscriber costs one per process.
11. Inspecting a live server
Because nothing is stored, you cannot look at a channel's contents. You can see who is listening, and watch traffic go by.
In redis-cli | Shows |
|---|---|
PUBSUB CHANNELS | Channels with at least one direct subscriber. Pattern subscriptions do not appear, which is why orders:* is missing above. |
PUBSUB NUMSUB news:sports | Direct subscribers of that channel |
PUBSUB NUMPAT | Number of pattern subscriptions on the server |
CLIENT LIST | One line per connection; sub= and psub= count its subscriptions |
INFO clients | Connected client totals, including pubsub_clients on recent versions |
SUBSCRIBE news:sports / PSUBSCRIBE app:* | Listen in from the terminal |
MONITOR | Every command the server runs. Debugging only: it slows a busy server noticeably. |
Cluster and security
- Redis Cluster: a classic
PUBLISHis forwarded to every node in the cluster, so any node can serve any subscriber, and it gets expensive at scale. Sharded Pub/Sub (SPUBLISH/SSUBSCRIBE, Redis 7 and later) routes a channel to the shard that owns its hash slot, like a key. - Replication: messages published on a primary are also delivered to subscribers connected to its replicas.
- Security: with ACLs (Redis 6 and later) a user can be limited to certain channels with
&patternrules, for exampleACL SETUSER worker on >secret &job:* +subscribe. - Persistence and restarts: RDB and AOF do not cover Pub/Sub. A server restart drops every subscription; clients must reconnect and subscribe again.
Recap
| Question | Short answer |
|---|---|
| What is a channel? | A name. It exists while someone is subscribed, and stores nothing. |
| Who gets a message? | Every client subscribed at that instant, each with its own copy |
| What if nobody is listening? | PUBLISH returns 0 and the message is gone |
| Delivery guarantee? | At-most-once. No acknowledgement, retry or history. |
| How do I not lose an important signal? | Write a key first, then publish. Subscribe first, then read the key. |
| One worker per job? | Not Pub/Sub. A List with BRPOP, or a Stream consumer group. |
| Need replay or guaranteed processing? | Streams |
| Why a separate connection? | A subscribed RESP2 connection cannot run normal commands |
| How many subscriber connections? | One shared per process, many channels on it |
| What kills a subscriber? | Reading too slowly: the output buffer limit closes the connection |
Back to the Redis notes.