Questions
What are Redis Streams and what are they used for?
The Scenario
You are a backend engineer at a social media company. You are building a new real-time notification service.
You need to find a way to send notifications to users in a way that is reliable and scalable.
The Challenge
Explain what Redis Streams are and how you would use them to solve this problem. What are the key benefits of using Redis Streams?
A junior engineer might try to solve this problem by using a Redis list. This would work, but it would not be a very robust solution. They might not be aware of Redis Streams, which is the correct tool for this job.
A senior engineer would know that Redis Streams are the perfect tool for this job. They would be able to explain what Redis Streams are and how to use them to build a reliable and scalable notification service.
Step 1: Understand What Redis Streams Are
A Redis Stream is a data structure that is similar to a log file. It is an append-only data structure, which means that you can only add new entries to the end of the stream.
Step 2: The Key Commands
| Command | Description |
|---|---|
XADD | Adds a new entry to a stream. |
XREAD | Reads one or more entries from a stream. |
XGROUP | Creates, destroys, and manages consumer groups. |
XREADGROUP | Reads from a stream via a consumer group. |
Step 3: Solve the Problem
Here’s how we can use Redis Streams to build a real-time notification service:
1. Create a stream for each user:
We can create a separate stream for each user to store their notifications.
2. Add notifications to the stream:
When a new notification comes in, we can use the XADD command to add it to the user’s stream.
XADD notifications:123 * message "You have a new follower!"3. Read notifications from the stream:
The user’s client can then use the XREAD command to read the notifications from the stream.
XREAD COUNT 1 STREAMS notifications:123 0Consumer Groups
For a more robust solution, we can use consumer groups to allow multiple clients to read from the same stream. This is useful if a user is connected to the service from multiple devices.
Practice Question
You want to be able to read all the messages in a stream, starting from the beginning. Which of the following would you use?