Implementing Pub/Sub Messaging

1. Publishing Messages

CommandReturns
PUBLISH channel messageCount of clients that received
SPUBLISH channel messageSharded variant for Cluster 7.0+

2. Subscribing to Channels

CommandDescription
SUBSCRIBE ch1 ch2 ...Enters subscribe state; limited commands allowed
SSUBSCRIBE ch1 ...Sharded subscribe for Cluster

3. Unsubscribing from Channels

CommandBehavior
UNSUBSCRIBE [ch ...]No args unsubscribes from all
PUNSUBSCRIBE [pat ...]Pattern unsubscribe

4. Using Pattern Subscriptions

CommandDescription
PSUBSCRIBE pat [pat ...]Glob pattern (e.g. news.*)

5. Using Sharded Pub/Sub

CommandNotes
SPUBLISH / SSUBSCRIBEChannel hashed to slot; scales horizontally in Cluster 7.0+

6. Listing Active Channels

CommandReturns
PUBSUB CHANNELS [pattern]Channels with ≥1 subscriber
PUBSUB SHARDCHANNELSSharded equivalent

7. Counting Subscribers

CommandReturns
PUBSUB NUMSUB [ch ...]Per-channel subscriber count

8. Counting Pattern Subscribers

CommandReturns
PUBSUB NUMPATTotal active pattern subscriptions

9. Understanding Message Delivery Guarantees

Warning: Pub/Sub is fire-and-forget. Offline subscribers miss messages. Use Streams for durable delivery.
GuaranteeDetail
At-most-onceNo persistence, no retries
OrderPer publisher, FIFO

10. Handling Connection Issues

RiskMitigation
Slow consumersTune client-output-buffer-limit pubsub
DisconnectRe-subscribe on reconnect; backfill via Stream

11. Implementing Fan-Out Pattern

Example: Broadcast event to all listeners

// Publisher
jedis.publish("events.user.signup", json);

// Subscriber
jedis.subscribe(new JedisPubSub() {
    public void onMessage(String ch, String msg) { handle(msg); }
}, "events.user.signup");