Introducing Dragonfly Cloud! Learn More

Redis XACK in Golang (Detailed Guide w/ Code Examples)

Use Case(s)

The XACK command in Redis is used with stream data structures. It's specifically utilized to acknowledge the processing of a message from a stream by a consumer. When consumers read messages, they can ensure that no message gets lost during processing by using XACK. Typically, this is used in a system where reliability is required and message loss cannot be tolerated such as in messaging queues, event-driven architectures, etc.

Code Examples

Consider a scenario where your application is consuming messages from a stream named "mystream" and the consumer group is named "mygroup".

For the purpose of this example, let's assume that you have already connected to your Redis instance and created a new stream and consumer group.

Let's say that you have read a message and its ID is "1577836800000-0", now you want to acknowledge it:

package main import ( "fmt" "" "context" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, }) ctx := context.Background() err := rdb.XAck(ctx, "mystream", "mygroup", "1577836800000-0").Err() if err != nil { panic(err) } fmt.Println("Message Acknowledged Successfully") }

This script connects to the Redis server running on localhost and acknowledges the processing of the message with ID "1577836800000-0" in "mystream" by "mygroup".

Best Practices

  • Always handle errors after the XACK. If an error occurs and it's not handled, your application might behave unexpectedly.
  • Make sure to use context with timeout or deadlines in production code. The above example uses context.Background() which never expires and can cause a goroutine leak if the redis server doesn't respond.

Common Mistakes

  • Not acknowledging messages once processed can lead to them being delivered again when a consumer crashes and restarts. This could lead to duplicate processing of messages.
  • Acknowledging messages before they are processed can lead to message loss if a consumer crashes after acknowledgement but before processing.


Q: Can I acknowledge multiple messages at once?

A: Yes, you can pass multiple IDs to the XAck function to acknowledge multiple messages in one command.

err := rdb.XAck(ctx, "mystream", "mygroup", "1577836800000-0", "1577836900000-0").Err()

Q: What happens if I try to acknowledge a message that does not exist or has already been acknowledged?

A: Redis will silently ignore non-existing IDs or IDs for messages that have already been acknowledged. The XACK command returns the count of IDs actually acknowledged.

Was this content helpful?

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.