# PUBLISH and SUBSCRIBE — Redis Pub/Sub & Streams

Source: https://www.skillbyai.com/en/redis-streams/p-basics

> Use channels to broadcast messages and understand the delivery semantics.

## Live broadcast on named channels

A client **subscribes** to one or more **channels** with `SUBSCRIBE`; from then on, Redis pushes every message **published** to those channels to that connection. `PUBLISH channel message` sends a message to all current subscribers and returns the **number of clients** that received it (in a cluster, this count covers only subscribers connected to the node that ran the command). Messages are delivered in publish order per channel to each subscriber, but there is **no storage, no acknowledgement and no retry**: if a subscriber is disconnected, slow to reconnect, or the server restarts, messages in that window are gone. Channel names are arbitrary strings; use a consistent naming scheme such as `app:domain:event` or `orders.updates`. Pub/Sub is completely separate from the keyspace: channels are not keys, so `DEL`, `TTL` and database numbers do not apply to them.

## One publisher, many subscribers

Each message goes to every subscriber connected at that moment, and is then forgotten.

![A single box sending arrows to four listener boxes, one of which is greyed out and receives nothing.](assets/figures/redis-streams/section-2-map.svg) — Figure 2.1 — Pub/Sub delivery to connected subscribers only.

## Publisher and subscriber in Python (redis-py)

The subscriber's loop blocks and handles each message as it arrives.

```python
import json, redis

r = redis.Redis(host="localhost", port=6379, decode_responses=True)

# publisher
receivers = r.publish("orders.updates", json.dumps({"orderId": "o-1001", "status": "shipped"}))
print("delivered to", receivers, "subscribers")

# subscriber (usually a separate process)
pubsub = r.pubsub(ignore_subscribe_messages=True)
pubsub.subscribe("orders.updates")
for message in pubsub.listen():
    event = json.loads(message["data"])
    print("order", event["orderId"], "is now", event["status"])
```

## PUBLISH returning 0 is information

A return value of 0 means nobody was listening and the message vanished. Log or count it if you expected subscribers; it often reveals a typo in a channel name.

**Quiz:** What does the PUBLISH command return?

- [ ] The message ID
- [ ] The channel length
- [x] The number of clients that received the message
- [ ] Always OK

*Answer:* The number of clients that received the message. PUBLISH returns how many subscribers the message was delivered to.
