Robust Event Processing: Redis Streams
7 min read
Robust Event Processing: Redis Streams ⚙️
Welcome to the world of Redis Streams! If you've ever dealt with real-time data, message queues, or event-driven systems, you're in for a treat. Redis Streams provide a powerful and efficient way to handle a continuous flow of data.
1. Introduction to Streams: The Modern Append-only Log 📜
The Problem: Imagine you're building a system to track user activity on a website. Every click, every page view, every purchase is an event. You need a way to capture these events in the order they happen and process them reliably. A simple list might work, but what if you have millions of events per hour? What if multiple services need to process these events independently? This is where a simple list falls short.
The Solution: Redis Streams
A Redis Stream is an append-only log data structure. Think of it like a diary where you can only add new entries at the end. Each entry in the stream gets a unique ID and can hold multiple field-value pairs.
Key Characteristics:
- Append-Only: You can only add new data to the end of the stream, which ensures the order of events is preserved.
- Unique IDs: Every entry has a unique ID, typically composed of a timestamp and a sequence number. This allows for precise navigation and tracking of events.
- Persistence: Unlike Redis Pub/Sub, where messages are "fire and forget," Streams persist messages in memory and can be saved to disk. This means consumers can read the stream's history at any time.
- Consumer Groups: This is a game-changer for scalability and reliability. You can have multiple consumers reading from the same stream, and Redis ensures that each message is delivered to only one consumer within the group.
A Fun Fact: Redis Streams were introduced in Redis 5.0 and were heavily inspired by Apache Kafka, a popular distributed streaming platform.
2. Adding and Reading Entries: XADD and XREAD ➕📖
Now, let's get our hands dirty and see how to interact with streams.
Adding Data with XADD
The XADD command is your go-to for adding new entries to a stream. If the stream doesn't exist, Redis will create it for you.
Syntax:XADD <stream_key> * <field1> <value1> [field2 value2 ...]
<stream_key>: The name of your stream.*: This tells Redis to automatically generate a unique ID for the new entry.<field1> <value1> ...: The data you want to store, as one or more key-value pairs.
Example: Let's add some sensor data to a stream called sensor_data.
XADD sensor_data * sensor-id 1234 temperature 25.5 humidity 60.2Redis will respond with the ID of the newly created entry.
Reading Data with XREAD
To read entries from a stream, you use the XREAD command. It allows you to read from one or more streams starting from a specific ID.
Syntax:XREAD [COUNT <count>] [BLOCK <milliseconds>] STREAMS <stream_key_1> [stream_key_2 ...] <id_1> [id_2 ...]
COUNT <count>: The maximum number of entries to return.BLOCK <milliseconds>: If no new entries are available, this option will make the command block for the specified duration, waiting for new data. This is incredibly useful for real-time applications.STREAMS <stream_key_1> ...: The stream(s) you want to read from.<id_1> ...: The ID from which to start reading. Use0-0to read from the very beginning. Use$to only get new messages that arrive after you start listening.
Example: Let's read the first two entries from our sensor_data stream.
XREAD COUNT 2 STREAMS sensor_data 0-0This will return the stream name and a list of entries with their IDs and data.
3. Understanding Consumer Groups for Work Distribution 🤝
The Problem: Imagine you have a high volume of events in your stream, and a single consumer can't keep up with processing them. You need a way to distribute the workload across multiple consumers without them stepping on each other's toes.
The Solution: Consumer Groups
Consumer groups allow multiple consumers to work together to process messages from a stream. Redis ensures that each message is delivered to only one consumer within the group, effectively load balancing the processing.
Creating a Consumer Group with XGROUP CREATE
First, you need to create a consumer group associated with a stream.
Syntax:XGROUP CREATE <stream_key> <group_name> <id>
<stream_key>: The name of the stream.<group_name>: The name you want to give your consumer group.<id>: The ID from which the group should start reading.$means the group will only consume new messages arriving after its creation.0means it will consume the entire history of the stream.
Example:
XGROUP CREATE sensor_data my_processors $Reading as a Consumer with XREADGROUP
Now that we have a group, consumers can start reading messages.
Syntax:XREADGROUP GROUP <group_name> <consumer_name> [COUNT <count>] STREAMS <stream_key> >
<group_name>: The name of the consumer group.<consumer_name>: A unique name for the consumer within the group.>: This special ID tells Redis to give this consumer messages that have not been delivered to any other consumer in the group.
Example:
# Consumer 1
XREADGROUP GROUP my_processors consumer_1 COUNT 1 STREAMS sensor_data >
# Consumer 2
XREADGROUP GROUP my_processors consumer_2 COUNT 1 STREAMS sensor_data >Each consumer will get a different message from the stream to process.
4. Acknowledging Messages and Handling Failures ✅🤕
The Problem: What happens if a consumer reads a message but crashes before it can finish processing it? The message might be lost forever. We need a way to ensure that messages are processed reliably.
The Solution: Acknowledgments and Pending Entries
When a consumer in a group reads a message, that message is added to a Pending Entries List (PEL) for that consumer. This list keeps track of messages that have been delivered but not yet acknowledged.
Acknowledging Messages with XACK
Once a consumer has successfully processed a message, it should send an XACK command to Redis. This tells Redis that the message has been handled, and it can be removed from the PEL.
Syntax:XACK <stream_key> <group_name> <id>
Example:
XACK sensor_data my_processors 1677293456789-0Handling Failures: Claiming Pending Messages
If a consumer crashes, its pending messages will remain in the PEL. Other consumers in the group can then claim these messages using the XCLAIM command and take over the processing, ensuring no message is lost.
Checking for Pending Messages:
You can inspect the PEL using the XPENDING command to see which messages are pending and for how long.
Claiming a Message:
Syntax:XCLAIM <stream_key> <group_name> <new_consumer_name> <min_idle_time> <id>
<min_idle_time>: The minimum time in milliseconds that the message must have been pending before it can be claimed.
Example:
XCLAIM sensor_data my_processors consumer_2 60000 1677293456789-0This command would allow consumer_2 to claim a message that has been pending for at least 60 seconds.
Real-life Scenario Simulation:
Imagine an online food delivery service. Every new order is an event added to a "new_orders" stream.
- Producers: The customer-facing app and website are the producers, adding new orders with
XADD. - Stream: The
new_ordersstream acts as a central log of all incoming orders. - Consumer Group: A consumer group named "kitchen_staff" is responsible for processing these orders.
- Consumers: Multiple "kitchen_station" consumers (e.g.,
station_1,station_2) read from the stream usingXREADGROUP. This ensures that each order is picked up by only one station. - Processing & Acknowledgment: When a station finishes preparing an order, it sends an
XACKto confirm it's done. - Failure Handling: If a kitchen station's tablet dies mid-order, that order remains pending. After a timeout, another available station can
XCLAIMthe order and continue the preparation, preventing a hungry customer from waiting forever.
This robust system ensures that every order is processed efficiently and reliably, even when things go wrong.
References 📚
Challenge
Redis Streams: Order Processing and Failure Recovery
You are responsible for a backend order processing system that uses Redis Streams to manage incoming orders. Your task is to write a sequence of Redis commands to simulate the entire lifecycle of order processing, including a consumer failure and recovery scenario.
Scenario:
An orders stream receives new orders. A consumer group named processors is responsible for handling them. A consumer, worker-1, processes one order but then crashes while handling a second. A recovery consumer, worker-2, must then claim and process the abandoned order.
Your Tasks:
- Add two new orders to a stream named
orders. The first order is foritem_idbk-123with aquantityof1. The second is foritem_iddv-456with aquantityof5. - Create a consumer group called
processorsto handle theordersstream. The group should be configured to read messages from the very beginning of the stream. - Have a consumer named
worker-1read a single message from the group. worker-1successfully processes the message. Write the command to acknowledge it. For this step, assume the message ID is1700000000000-0.worker-1now reads the next available message but crashes before it can be acknowledged.- A new consumer,
worker-2, is brought online to handle recovery. It needs to claim the message thatworker-1failed to process. Write the command forworker-2to claim the unacknowledged message fromworker-1, assuming the message has been idle for at least30000milliseconds. For this step, assume the message ID to be claimed is1700000000001-0. - Finally,
worker-2successfully processes the claimed message. Write the command to acknowledge this message.
Expected result
Your solution should be a sequence of seven Redis CLI commands that correctly perform the operations described in the instructions.
XADD orders * item_id bk-123 quantity 1
XADD orders * item_id dv-456 quantity 5
XGROUP CREATE orders processors 0-0
XREADGROUP GROUP processors worker-1 COUNT 1 STREAMS orders >
XACK orders processors 1700000000000-0
XREADGROUP GROUP processors worker-1 COUNT 1 STREAMS orders >
XCLAIM orders processors worker-2 30000 1700000000001-0
XACK orders processors 1700000000001-0