What is Stream in Redis: Explanation and Usage
stream in Redis is a data structure that stores an ordered sequence of messages or events, similar to a log or a timeline. It allows you to append new entries and read them in order, making it useful for real-time data processing and messaging.How It Works
Think of a Redis stream like a diary or a message board where you keep adding new notes one after another. Each note is called an entry, and it has a unique ID that helps you find it later. The entries are stored in the order they arrive, so you can read them from oldest to newest.
When you add data to a stream, Redis assigns it a special ID based on the current time and a sequence number to keep everything unique. You can then read entries starting from any ID, which is helpful if you want to process new messages only or catch up from where you left off.
This makes streams perfect for situations where you want to track events, logs, or messages continuously and process them in order without losing any data.
Example
This example shows how to add entries to a Redis stream and read them back.
XADD mystream * sensor-id 1234 temperature 19.8 XADD mystream * sensor-id 1235 temperature 20.1 XRANGE mystream - +
When to Use
Use Redis streams when you need to handle real-time data flows like logs, events, or messages that come in continuously. For example, you can use streams to collect sensor data, track user activity on a website, or build a chat system.
Streams help you process data in order and allow multiple consumers to read the data independently without losing messages. This makes them great for building scalable and reliable messaging or event-driven systems.
Key Points
- Redis streams store ordered sequences of messages with unique IDs.
- They support appending new entries and reading them in order.
- Streams are useful for real-time event processing and messaging.
- Multiple consumers can read from the same stream independently.
- Entries have IDs based on time and sequence for uniqueness.