Learnings

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

The idea

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:sports or job: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.
Think of a channel as a named pipe: one end to drop messages in, one outlet per subscriber. Each outlet gets its own copy.
Pipe pictureWhat it really is in Redis
The pipeThe channel name
Dropping a message in one endPUBLISH <channel> <message>
An outlet at the other endOne connection that ran SUBSCRIBE <channel>
How many outletsPUBSUB NUMSUB <channel>
No outlets leftThe 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

The idea

Pub/Sub is live radio: a message is heard once, by whoever is listening at that moment.
A key is a notice on a board: it stays until it is deleted or expires, and nobody is told when it changes.
  • 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. SET stays until it is deleted or expires, and anyone can GET it 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

The idea

PropertyWhat it means
Created on useA channel exists from the first SUBSCRIBE until the last UNSUBSCRIBE. You never create or delete it. KEYS never lists it; PUBSUB CHANNELS does.
Fan-outEvery current subscriber gets its own copy of every message.
At-most-onceEach subscriber gets a message once, or not at all if it is disconnected or not yet subscribed. No acknowledgements, no retries.
No historyMessages are never stored. A subscriber that joins later sees only new messages.
OrderingOne subscriber sees the messages of one channel in the order Redis received them.
Not tied to a database numberChannels 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

The idea

Pub/Sub channel: a broadcast. Every subscriber gets its own copy of m1.
Work queue: a ticket counter. Each job goes to exactly one worker. Mixing the two up is the most common design mistake with Pub/Sub.
Pub/Sub channelWork queue (List + BRPOP, or Stream consumer groups)
A message goes toEvery current subscriberExactly one worker
If nobody is listeningThe message is lostThe message waits
Use forNotifying whoever cares, right nowSharing out jobs so each is done once
LikeA radio broadcastA 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

First examples

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

First examples

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, whose data is the number of channels this connection now listens to.
  • publish returned 1: 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. pattern is None because the subscription was to an exact name.

2. The lost message

First examples

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

First examples

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 BRPOP found nothing and gave up after its 1 second timeout.
  • LPUSH adds at the left and BRPOP takes from the right, so the list behaves as a first-in, first-out queue.

4. Pattern subscribe

First examples

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 the pattern that matched and the real channel.
  • payments:new did not match, so publish returned 0.
  • Glob syntax: * any characters, ? one character, [ab] one of a set. A client subscribed to both orders:new and orders:* receives the message twice, once per subscription.

Commands and message shapes

First examples

CommandWhat it doesIn redis-py
PUBLISH channel messageSends to every current subscriber, returns the countr.publish(channel, message)
SUBSCRIBE channel [channel ...]Listens to exact channel namesp.subscribe(...)
UNSUBSCRIBE [channel ...]Stops listening (all channels if none given)p.unsubscribe(...)
PSUBSCRIBE pattern [pattern ...]Listens to every channel matching a globp.psubscribe(...)
PUNSUBSCRIBE [pattern ...]Stops pattern subscriptionsp.punsubscribe(...)
PUBSUB CHANNELS [pattern]Lists channels with at least one direct subscriberr.pubsub_channels()
PUBSUB NUMSUB [channel ...]Counts direct subscribers per channelr.pubsub_numsub(...)
PUBSUB NUMPATCounts pattern subscriptionsr.pubsub_numpat()
SPUBLISH / SSUBSCRIBE / SUNSUBSCRIBESharded Pub/Sub for Redis Cluster (Redis 7 and later), see Cluster and securityr.spublish, p.ssubscribe

What a subscriber receives, on the wire and as a redis-py dict:

KindRaw replyredis-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 connectionsubscribe, 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

How it works underneath

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.

Redis never connects out. It writes to sockets that the subscribers already opened.

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

How it works underneath

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

How it works underneath

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

How it works underneath

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

Lost messages and the fix

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."

Nothing failed and nothing was logged. The receiver simply never hears about it.

The fix: key first, then publish

Lost messages and the fix

The sender writes durable state first, then publishes. The receiver subscribes first, then reads the state.

Whichever order the two sides run in, the receiver finds out: from the live message, or from the key.
TimingHow the receiver learns
Receiver subscribed before the sender publishedThe live message arrives
Sender finished before the receiver subscribedThe GET right after subscribing returns the state
Both at the same momentOne 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

Lost messages and the fix

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 GET and the SET. Job 44 was already completed, and stayed so.
  • Give the status key a TTL (EX), or finished jobs pile up for ever.

Naming channels and keys

Lost messages and the fix

TipExampleWhy
Use {env}:{app}:{purpose}:{id}prod:shop:cache-invalidate:product:123The environment prefix stops dev and prod clients that share a Redis from crossing wires
Put state in values, not in key namesOne job:42:status whose value changes, not job:42:queued then job:42:runningOne key to read, one to expire, no stale leftovers
Name by purpose, with nounsstatus, cancel-signal, eventsNames such as channel or string say what the Redis type is, not what it is for
Normalise ids the same way on both sidesLower-case canonical UUIDsPublisher 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 cases

Use caseHow Pub/Sub is usedNotes
Cache invalidation across app serversEach 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 nodesUsers 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 notificationsWorkers 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 reloadWrite 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 serverOne 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 indicatorsPUBLISH room:7:typing aliceLosing one is harmless, which suits at-most-once delivery.
Keyspace notificationsRedis itself publishes when keys change or expire.Example 9.
DebuggingPSUBSCRIBE app:* in redis-cli to watch events live.Fan-out means listening in never disturbs the real subscribers.

5. Cache invalidation across app servers

Use cases

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.

Each server reloads the entry from the database the next time it is asked for it.

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

Use cases

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

Use cases

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 CancelledError inside it at its next await, 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 cancel first and run second, and the job stops at once: that is the GET after SUBSCRIBE doing its work. Note that run_job sets the status to running at the start, so in real code use the Lua script to avoid overwriting a cancel that arrived first.

9. Keyspace notifications

Use cases

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 @0 in the channel name.

Bad fits, and what to use instead

Use cases

NeedWhy Pub/Sub failsUse instead
Every message must be processed, even after a crash or restartAt-most-once, no historyRedis Streams (XADD, consumer groups, XACK), or a broker such as Kafka or RabbitMQ
Each job done by exactly one workerFan-out gives it to allA List with BRPOP, or Stream consumer groups
Replay or audit of past eventsNothing is storedStreams or a database
Very slow consumersThey get disconnected at the output buffer limitStreams or a queue
Pub/SubStreamsLists
StoredNoYes, until trimmedYes
DeliveryTo all current subscribersReaders choose; consumer groups split the workOne consumer pops each item
Late joinerMisses past messagesCan read from any idGets what is still in the list
AcknowledgementNoYes, XACKNo (use LMOVE for reliability)
Best forInstant notificationsEvent logs, reliable processing, resumingSimple job queues

12. Streams contrast

Use cases

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

Operating it

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 ConnectionPool raises at once when it is full. BlockingConnectionPool waits 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=handler to subscribe makes get_message call the handler and return None for that message.

Sizing connections

Operating it

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

Operating it

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-cliShows
PUBSUB CHANNELSChannels with at least one direct subscriber. Pattern subscriptions do not appear, which is why orders:* is missing above.
PUBSUB NUMSUB news:sportsDirect subscribers of that channel
PUBSUB NUMPATNumber of pattern subscriptions on the server
CLIENT LISTOne line per connection; sub= and psub= count its subscriptions
INFO clientsConnected client totals, including pubsub_clients on recent versions
SUBSCRIBE news:sports / PSUBSCRIBE app:*Listen in from the terminal
MONITOREvery command the server runs. Debugging only: it slows a busy server noticeably.

Cluster and security

Operating it

  • Redis Cluster: a classic PUBLISH is 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 &pattern rules, for example ACL 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

Operating it

QuestionShort 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.