How to Use XREAD in Redis: Syntax and Examples
Use the
XREAD command in Redis to read new entries from one or more streams starting from a given ID. It returns stream entries added after the specified ID, allowing you to consume data in a streaming fashion.Syntax
The XREAD command reads data from one or more Redis streams. Its basic syntax is:
XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...]
Here’s what each part means:
- COUNT count: Optional. Limits the number of entries returned per stream.
- BLOCK milliseconds: Optional. Waits for new entries if none are available, up to the given milliseconds.
- STREAMS: Keyword to specify the streams to read from.
- key [key ...]: One or more stream keys to read from.
- ID [ID ...]: The last ID seen for each stream; Redis returns entries with IDs greater than these.
redis
XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...]
Example
This example shows how to read new entries from a stream named mystream starting after ID 0-0 (which means from the beginning).
redis
127.0.0.1:6379> XADD mystream * sensor-id 1234 temperature 19.8 "1588153560106-0" 127.0.0.1:6379> XREAD STREAMS mystream 0-0 1) 1) "mystream" 2) 1) 1) "1588153560106-0" 2) 1) "sensor-id" 2) "1234" 3) "temperature" 4) "19.8"
Output
1) 1) "mystream"
2) 1) 1) "1588153560106-0"
2) 1) "sensor-id"
2) "1234"
3) "temperature"
4) "19.8"
Common Pitfalls
Common mistakes when using XREAD include:
- Using
0-0as the ID repeatedly, which causes reading the entire stream from the start every time. - Not updating the last seen ID after reading, leading to duplicate data processing.
- Forgetting to specify the
STREAMSkeyword before stream keys and IDs. - Using
BLOCKwithout understanding it causes the command to wait, which might block your application.
redis
/* Wrong: Missing STREAMS keyword */ XREAD mystream 0-0 /* Right: Include STREAMS keyword */ XREAD STREAMS mystream 0-0
Quick Reference
| Option | Description |
|---|---|
| COUNT count | Limits number of entries returned per stream |
| BLOCK milliseconds | Waits for new entries up to given milliseconds |
| STREAMS | Keyword to specify streams to read from |
| key [key ...] | One or more stream keys |
| ID [ID ...] | Last seen IDs for each stream |
Key Takeaways
Use XREAD with STREAMS keyword followed by stream keys and last IDs to read new entries.
Always update the last seen ID to avoid reading duplicate entries.
Use COUNT to limit entries and BLOCK to wait for new data if needed.
Remember to include STREAMS keyword; omitting it causes syntax errors.
XREAD is useful for consuming Redis streams in real-time or batch modes.