Skip to content

Go Redis Pubsub

DodaTech 1 min read

In this tutorial, you'll learn about Go Redis: Pub/Sub Pattern. We cover key concepts, practical examples, and best practices.

Redis Pub/Sub -- Use Redis publish/subscribe for real-time messaging between services.

The Problem

Redis Pub/Sub requires the subscriber to be listening before the publisher sends. Messages are not queued -- if no subscriber, the message is lost. Use channels with go-redis.

Wrong

rdb.Publish(ctx, "channel", "hello").Err()

Output:

// No subscriber, message lost forever
pubsub := rdb.Subscribe(ctx, "channel")
defer pubsub.Close()
// Wait for subscription
_, err := pubsub.Receive(ctx)
ch := pubsub.Channel()
for msg := range ch {
    fmt.Println(msg.Payload)
}
// In another goroutine:
rdb.Publish(ctx, "channel", "hello")

Output:

// Subscriber receives: hello

Prevention

  • Subscribe before publishing
  • Messages are not queued
  • Use pubsub.Channel() for Go channel
  • Use Receive() to confirm subscription
  • Close pubsub when done

Common Mistakes with redis pubsub

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Can I subscribe to multiple channels?**

Yes. rdb.Subscribe(ctx, "ch1", "ch2").

What is the difference between Pub/Sub and Streams?

Pub/Sub is fire-and-forget. Streams persist messages.

How to unsubscribe?

pubsub.Unsubscribe(ctx, "channel").


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro