Go Redis Stream
In this tutorial, you'll learn about Go Redis: Stream Messages. We cover key concepts, practical examples, and best practices.
Redis streams -- Use XADD, XREADGROUP, XACK for message streaming with consumer groups.
The Problem
Redis streams persist messages. Consumer groups track delivery. Unacknowledged messages are redelivered. Always XACK after processing.
Wrong
rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "mystream",
Values: map[string]interface{}{"key": "value"},
}).Err()
Output:
// Message added but no consumer to read it
Right
// Producer:
rdb.XAdd(ctx, &redis.XAddArgs{Stream: "orders", Values: []string{"user", "Alice"}})
// Consumer group:
rdb.XGroupCreate(ctx, "orders", "processors", "0")
msgs, _ := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "processors", Consumer: "worker1",
Streams: []string{"orders"}, Count: 1, Block: 0,
}).Result()
// Process then acknowledge:
rdb.XAck(ctx, "orders", "processors", msgID)
Output:
// Messages processed and acknowledged. No redelivery.
Prevention
- Use XADD to add messages
- Create consumer group with XGroupCreate
- Use XReadGroup for consumers
- Always XAck after processing
- Use XPending to check unacknowledged
Common Mistakes with redis stream
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
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