How to Use XGROUP in Redis for Stream Consumer Groups
Use the
XGROUP command in Redis to create and manage consumer groups for streams, enabling multiple clients to read messages cooperatively. The basic syntax is XGROUP CREATE <key> <groupname> <id> to create a group, where <id> is the starting point for reading messages.Syntax
The XGROUP command manages consumer groups on Redis streams. Its main subcommands include:
CREATE <key> <groupname> <id>: Creates a new consumer group on the streamkeystarting atid.DESTROY <key> <groupname>: Deletes a consumer group.CREATECONSUMER <key> <groupname> <consumername>: Creates a consumer in a group.DELCONSUMER <key> <groupname> <consumername>: Removes a consumer from a group.
The most common usage is XGROUP CREATE to start a group for stream processing.
redis
XGROUP CREATE <key> <groupname> <id>
Example
This example shows how to create a consumer group named mygroup on a stream called mystream, starting from the beginning of the stream (0), then how to read messages as a consumer.
redis
127.0.0.1:6379> XGROUP CREATE mystream mygroup 0 OK 127.0.0.1:6379> XADD mystream * name Alice "1588151234567-0" 127.0.0.1:6379> XREADGROUP GROUP mygroup consumer1 COUNT 1 STREAMS mystream > 1) 1) "mystream" 2) 1) 1) "1588151234567-0" 2) 1) "name" 2) "Alice"
Output
OK
"1588151234567-0"
1) 1) "mystream"
2) 1) 1) "1588151234567-0"
2) 1) "name"
2) "Alice"
Common Pitfalls
Common mistakes when using XGROUP include:
- Trying to create a group on a non-existing stream without the
MKSTREAMoption, which causes an error. - Using
0as the starting ID when you want to read only new messages; use$instead. - Not acknowledging messages after processing, which causes them to remain pending.
Example of creating a group with MKSTREAM to avoid errors if the stream does not exist:
redis
XGROUP CREATE mystream mygroup $ MKSTREAM
Quick Reference
| Subcommand | Description | Notes |
|---|---|---|
| CREATE | Create a consumer group on a stream | Use MKSTREAM to create stream if missing |
| DESTROY | Delete a consumer group | Removes group and all consumers |
| CREATECONSUMER | Add a consumer to a group | Optional, consumers auto-create on first read |
| DELCONSUMER | Remove a consumer from a group | Frees pending messages for that consumer |
Key Takeaways
Use XGROUP CREATE to start a consumer group on a Redis stream for cooperative message processing.
Specify the starting ID as 0 to read all messages or $ to read only new messages added after group creation.
Use MKSTREAM option to create the stream automatically if it does not exist.
Remember to acknowledge messages after processing to avoid buildup in the pending entries list.
Manage consumers with CREATECONSUMER and DELCONSUMER subcommands to track active readers.