# Creating Groups and Reading with XREADGROUP — Redis Pub/Sub & Streams

Source: https://www.skillbyai.com/en/redis-streams/g-basics

> Share a stream between workers with consumer groups.

## Splitting work between consumers

A **consumer group** lets several consumers **share** a stream: each entry is delivered to **only one** consumer in the group, while **other groups** on the same stream each receive every entry independently. Create a group with `XGROUP CREATE stream group <id>`: `$` starts from new entries only, `0` from the beginning; `MKSTREAM` creates the stream if it does not exist. Consumers read with **`XREADGROUP GROUP <group> <consumer> COUNT n BLOCK ms STREAMS <stream> >`**. The special ID **`>`** means "entries never delivered to anyone in this group". Consumer names are identifiers you choose, typically the hostname or pod name plus a suffix; Redis creates the consumer on first use. The group tracks a **last-delivered ID**, so new entries are handed out in order across consumers. This gives Redis Streams the competing-consumers pattern of a message queue, while keeping the log for other groups and for replay.

## Groups share a stream

Within a group, each entry goes to one consumer; each group gets every entry.

![One long strip of entries with two bracket groups below it; within each bracket, entries are distributed to two or three worker icons.](assets/figures/redis-streams/section-5-map.svg) — Figure 5.1 — Two consumer groups reading the same stream.

## A group with two consumers

Each XREADGROUP call with > receives entries nobody in the group has received yet.

```bash
XGROUP CREATE orders billing '$' MKSTREAM
XGROUP CREATE orders analytics 0          # analytics also replays history

# worker A and worker B in the billing group
XREADGROUP GROUP billing worker-a COUNT 10 BLOCK 5000 STREAMS orders '>'
XREADGROUP GROUP billing worker-b COUNT 10 BLOCK 5000 STREAMS orders '>'

# analytics reads the same entries independently
XREADGROUP GROUP analytics etl-1 COUNT 100 STREAMS orders '>'
```

## Create groups idempotently at start-up

`XGROUP CREATE` fails with a BUSYGROUP error if the group exists. Catch that specific error at start-up and continue, so deployments do not crash on restart.

**Quiz:** Two consumers in the same group call XREADGROUP with `>`. What happens to a new entry?

- [x] Exactly one of them receives it
- [ ] Both consumers receive it
- [ ] Neither receives it until acknowledged
- [ ] It is deleted immediately

*Answer:* Exactly one of them receives it. Within a group, each entry is delivered to a single consumer.
