How to Use XLEN Command in Redis for Stream Length
Use the
XLEN command in Redis to get the number of entries in a stream. The syntax is XLEN key, where key is the stream name. It returns an integer representing the stream length.Syntax
The XLEN command syntax is simple:
XLEN key: Returns the number of entries in the stream stored atkey.
If the stream does not exist, it returns 0.
redis
XLEN mystream
Example
This example shows how to add entries to a Redis stream and then use XLEN to get the number of entries.
redis
127.0.0.1:6379> XADD mystream * sensor-id 1234 temperature 19.8 "1588151234567-0" 127.0.0.1:6379> XADD mystream * sensor-id 1235 temperature 20.1 "1588151234568-0" 127.0.0.1:6379> XLEN mystream (integer) 2
Output
(integer) 2
Common Pitfalls
Common mistakes when using XLEN include:
- Using
XLENon a key that is not a stream, which causes an error. - Expecting
XLENto return the total size in bytes instead of the number of entries. - Not handling the case when the stream does not exist, which returns 0.
Always ensure the key is a stream before calling XLEN.
redis
127.0.0.1:6379> XLEN notastream (error) WRONGTYPE Operation against a key holding the wrong kind of value # Correct usage: 127.0.0.1:6379> XLEN mystream (integer) 2
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
(integer) 2
Quick Reference
| Command | Description |
|---|---|
| XLEN key | Returns the number of entries in the stream at key |
| XADD key * field value | Adds an entry to the stream |
| XRANGE key - + | Reads entries from the stream |
Key Takeaways
Use XLEN to get the count of entries in a Redis stream quickly.
XLEN returns 0 if the stream does not exist.
Do not use XLEN on keys that are not streams to avoid errors.
XLEN counts entries, not the byte size of the stream.
Combine XLEN with XADD and XRANGE for full stream management.