Lab 15: Redis Pub/Sub & Streams

Time: 40 minutes | Level: Practitioner | DB: Redis 7

Redis Pub/Sub enables real-time messaging (fire-and-forget, no persistence). Redis Streams (added in Redis 5.0) add persistence, consumer groups, and at-least-once delivery — making them suitable for event sourcing and reliable message queues.


Step 1 — Pub/Sub: Concepts

Publisher                  Redis               Subscriber(s)
──────────              ──────────           ──────────────
PUBLISH channel msg  →   channel:msg    →   SUBSCRIBE channel
                                        →   SUBSCRIBE channel (multiple)

Key characteristics:

  • Fire-and-forget: messages are lost if no subscriber is listening

  • No message persistence

  • Fan-out: one publish reaches all subscribers

  • Pattern subscriptions: PSUBSCRIBE events.* matches multiple channels


Step 2 — Pub/Sub: Basic Example

Open two terminals:

Terminal 1 (subscriber):

Terminal 2 (publisher):

Terminal 1 sees:

💡 SUBSCRIBE blocks the connection — you can only issue SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, or QUIT on a subscribed connection.


Step 3 — Pattern Subscriptions with PSUBSCRIBE

Terminal 1 (pattern subscriber):

Terminal 2 (publisher):

Terminal 1 sees:


Step 4 — Redis Streams: Adding Messages

Redis Streams store data as append-only logs. Each entry has a unique ID and key-value fields.

📸 Verified Output:

💡 Stream IDs are milliseconds-sequenceNumber. You can specify explicit IDs like XADD stream '1699900000000-0' ... for deterministic testing or event replay.


Step 5 — XREAD and Stream Trimming


Step 6 — Consumer Groups: Reliable Processing

Consumer groups allow multiple workers to process messages, track delivery, and handle failures.

📸 Verified Output:

📸 Verified XINFO GROUPS:


Step 7 — Multiple Consumer Groups and XCLAIM

💡 The pending entry list (PEL) tracks messages delivered but not acknowledged. If a consumer crashes, its pending messages can be claimed by another consumer using XCLAIM.


Step 8 — Capstone: Event Processing Pipeline

📸 Verified XLEN:


Summary

Feature
Pub/Sub
Streams

Persistence

No

Yes (AOF/RDB)

Delivery guarantee

At-most-once

At-least-once (with groups)

Message history

None

Retained until XTRIM

Consumer groups

No

Yes (XGROUP)

Acknowledgment

N/A

XACK

Multiple consumers

Fan-out (all get all)

Partitioned (each message once per group)

Pattern matching

PSUBSCRIBE

Stream filter in app

Blocking read

SUBSCRIBE

XREAD BLOCK / BLPOP

Use case

Real-time notifications

Event sourcing, reliable queues

Last updated