0
0
Redisquery~30 mins

XTRIM for stream capping in Redis - Mini Project: Build & Apply

Choose your learning style9 modes available
Using XTRIM to Cap Redis Streams
📖 Scenario: You are managing a Redis stream that collects temperature sensor readings from a smart home system. To keep the stream size manageable and avoid using too much memory, you want to limit the stream to only the latest 5 readings.
🎯 Goal: Build a Redis stream capped at 5 entries using the XTRIM command to automatically remove older entries when new ones are added.
📋 What You'll Learn
Create a Redis stream called sensor:temperature with initial entries.
Set a maximum length variable max_len to 5.
Use the XADD command with the MAXLEN option to add new entries while trimming the stream.
Verify that the stream never exceeds 5 entries after adding new data.
💡 Why This Matters
🌍 Real World
IoT devices and real-time data systems often use Redis streams to collect sensor data. Capping streams prevents memory overflow and keeps data manageable.
💼 Career
Understanding how to cap Redis streams is useful for backend developers and system administrators managing real-time data pipelines and ensuring efficient resource use.
Progress0 / 4 steps
1
Create the initial Redis stream with 3 temperature readings
Use the XADD command to create a Redis stream called sensor:temperature and add these exact entries: {"temp": "22.5"}, {"temp": "23.0"}, and {"temp": "22.8"}. Use the * ID to let Redis generate IDs automatically.
Redis
Need a hint?

Use XADD with * for automatic IDs and specify the field temp with the given values.

2
Set a maximum length variable for the stream
Create a variable called max_len and set it to 5 to represent the maximum number of entries allowed in the stream.
Redis
Need a hint?

Just assign the number 5 to a variable named max_len.

3
Add new entries using XADD with MAXLEN to cap the stream
Use the XADD command with the MAXLEN option set to ~ and the variable max_len to add two new temperature readings: 23.2 and 23.5. Use the * ID for automatic IDs.
Redis
Need a hint?

Use XADD sensor:temperature MAXLEN ~ 5 * followed by the field and value to add entries while trimming.

4
Verify the stream is capped at 5 entries
Use the XLEN command on the sensor:temperature stream to check that it contains exactly 5 entries after adding the new data.
Redis
Need a hint?

Use XLEN sensor:temperature to get the number of entries in the stream.