0
0
RedisHow-ToBeginner · 3 min read

How to Use XREADGROUP in Redis for Consumer Groups

Use the XREADGROUP command in Redis to read messages from a stream as part of a consumer group. It allows multiple consumers to share the workload by reading new or pending messages with options like GROUP, COUNT, and BLOCK.
📐

Syntax

The XREADGROUP command reads messages from a Redis stream as a consumer in a consumer group. Here is the syntax:

  • GROUP <groupname> <consumername>: Specifies the consumer group and consumer name.
  • COUNT <number>: Optional, limits the number of messages returned.
  • BLOCK <milliseconds>: Optional, waits for new messages if none are available.
  • STREAMS <key> <id>: Specifies the stream key and the ID to start reading from.

The id is usually > to read new messages or a specific ID to read pending messages.

redis
XREADGROUP GROUP <groupname> <consumername> [COUNT <count>] [BLOCK <milliseconds>] STREAMS <key> <id>
💻

Example

This example shows how to create a consumer group and read new messages from a stream using XREADGROUP. It demonstrates reading messages as a consumer named consumer1 in group mygroup from stream mystream.

redis
127.0.0.1:6379> XGROUP CREATE mystream mygroup $ MKSTREAM
OK
127.0.0.1:6379> XADD mystream * name Alice
"1689345600000-0"
127.0.0.1:6379> XREADGROUP GROUP mygroup consumer1 COUNT 1 STREAMS mystream >
1) 1) "mystream"
   2) 1) 1) "1689345600000-0"
         2) 1) "name"
            2) "Alice"
Output
OK "1689345600000-0" 1) 1) "mystream" 2) 1) 1) "1689345600000-0" 2) 1) "name" 2) "Alice"
⚠️

Common Pitfalls

Common mistakes when using XREADGROUP include:

  • Not creating the consumer group before reading, which causes an error.
  • Using 0 or a specific ID instead of > to read new messages, which may cause no messages to be returned.
  • Not acknowledging messages with XACK, causing them to remain pending and be re-delivered.

Always create the group first and use > to read new messages unless you want to process pending messages.

redis
;; Wrong: reading without group creation
127.0.0.1:6379> XREADGROUP GROUP mygroup consumer1 STREAMS mystream >
(error) NOGROUP No such key or consumer group

;; Right: create group first
127.0.0.1:6379> XGROUP CREATE mystream mygroup $ MKSTREAM
OK
📊

Quick Reference

OptionDescription
GROUP Specify consumer group and consumer name
COUNT Limit number of messages returned
BLOCK Wait for new messages if none available
STREAMS Stream key and ID to read from; use '>' for new messages
XACK Acknowledge processed messages to remove from pending

Key Takeaways

Always create a consumer group with XGROUP CREATE before using XREADGROUP.
Use '>' as the ID in XREADGROUP to read new messages for the consumer group.
Use COUNT and BLOCK options to control how many messages to read and wait time.
Acknowledge messages with XACK to prevent reprocessing of the same messages.
XREADGROUP enables multiple consumers to share stream message processing efficiently.