Go Redis Pubsub
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
Right
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
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - 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
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