Skip to main content

Chapter 5: Pub/Sub

Redis Pub/Sub enables real-time messaging between clients. Publishers send messages to channels, and all subscribers to those channels receive them instantly. Let’s build it! Pub/Sub is a fundamentally different pattern from the request-response commands you’ve built so far. With GET/SET, the client asks and the server answers. With Pub/Sub, the server pushes data to clients without being asked — a subscriber sits idle until a message arrives. This “push” model is the backbone of real-time features like chat, live dashboards, and notifications. Building it yourself will teach you how event-driven systems work at the socket level, and why concepts like “fan-out” and “backpressure” matter in production.
Prerequisites: Chapter 2: TCP Server
Further Reading: System Design: Message Queues
Time: 2-3 hours
Outcome: Working publish/subscribe system

Pub/Sub Architecture


Part 1: Pub/Sub Hub

The hub manages channel subscriptions and message routing.
internal/pubsub/hub.go

Part 2: Pattern Matching

Redis uses glob-style pattern matching for PSUBSCRIBE:
internal/pubsub/pattern.go

Part 3: Client Integration

Integrate Pub/Sub with the connection handler:
internal/server/connection.go

Part 4: Message Serialization

internal/server/writer.go

Usage Example


Real-World Use Cases

Real-time Chat

Each chat room is a channel. Users subscribe to rooms they’re in.

Live Notifications

Push updates to connected clients (price changes, status updates).

Cache Invalidation

Publish when cache entries change; subscribers update local caches.

Event Broadcasting

Decouple services - publisher doesn’t know who’s listening.

Exercises

In Redis Cluster, implement shard-aware channels:
Store recent messages so new subscribers can catch up:
Track which clients are subscribed to what:

Key Takeaways

Fire and Forget

Messages aren’t stored - if no one is listening, they’re lost

Pattern Matching

PSUBSCRIBE enables flexible channel matching with globs

Push Model

Server pushes to clients - no polling needed

Decoupling

Publishers and subscribers are completely independent

Limitations to Consider


Congratulations! 🎉

You’ve built a working Redis clone with:
  • ✅ RESP protocol parser
  • ✅ TCP server with concurrent connections
  • ✅ Multiple data structures (Strings, Lists, Sets, Hashes, Sorted Sets)
  • ✅ Persistence (RDB snapshots, AOF logging)
  • ✅ Pub/Sub messaging

Redis Project Complete!

You now understand how Redis works internally!

What’s Next?

Continue with other Build Your Own X projects:

Build Your Own Docker

Understand containers from the ground up

Build Your Own Git

Learn version control internals