0
0
Redisquery~5 mins

XTRIM for stream capping in Redis

Choose your learning style9 modes available
Introduction
XTRIM helps keep a Redis stream from growing too big by removing old entries. This saves space and keeps your data fresh.
You want to keep only the latest 100 messages in a chat app.
You need to limit event logs to the last 1000 entries to save memory.
You want to keep sensor data streams capped to recent readings only.
You want to prevent a stream from growing endlessly in a real-time feed.
You want to keep your Redis storage under control by trimming old stream data.
Syntax
Redis
XTRIM key MAXLEN [~] count
Use MAXLEN to specify the maximum number of entries to keep.
The optional '~' makes trimming approximate for better performance.
Examples
Trim 'mystream' to keep only the latest 100 entries exactly.
Redis
XTRIM mystream MAXLEN 100
Trim 'mystream' approximately to keep about 1000 entries for faster trimming.
Redis
XTRIM mystream MAXLEN ~ 1000
Sample Program
Add three entries to 'mystream', then trim it to keep only the last 2 entries. Finally, read all entries to see the result.
Redis
XADD mystream * sensor-id 1 temperature 22.5
XADD mystream * sensor-id 2 temperature 23.0
XADD mystream * sensor-id 3 temperature 21.8
XTRIM mystream MAXLEN 2
XRANGE mystream - +
OutputSuccess
Important Notes
Trimming a stream helps control memory but removes old data permanently.
Using '~' for approximate trimming is faster but may keep slightly more entries than the limit.
XTRIM can be used automatically with XADD by adding MAXLEN option there.
Summary
XTRIM limits the size of a Redis stream by removing old entries.
Use MAXLEN to set how many entries to keep.
Approximate trimming (~) improves speed but is less exact.