XLEN for stream length in Redis - Time & Space Complexity
We want to understand how the time it takes to get the length of a Redis stream changes as the stream grows.
Specifically, how does the XLEN command perform when the stream has more or fewer entries?
Analyze the time complexity of the following Redis command.
XLEN mystream
This command returns the number of entries in the stream named "mystream".
Look for any repeated work the command might do.
- Primary operation: Accessing the stored length value of the stream.
- How many times: Exactly once, no loops or traversals.
The command simply reads a stored number, so the work stays the same no matter how big the stream is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays constant regardless of stream size.
Time Complexity: O(1)
This means the time to get the stream length does not change even if the stream grows very large.
[X] Wrong: "XLEN must scan all entries to count them, so it gets slower with bigger streams."
[OK] Correct: Redis keeps track of the stream length internally, so XLEN just reads that number instantly without scanning.
Knowing that some commands like XLEN run in constant time helps you understand how Redis handles data efficiently behind the scenes.
"What if we used XRANGE to get all entries instead of XLEN? How would the time complexity change?"