How do you trim a Redis list to keep only a specific number of the most recent items, discarding older entries automatically?
Short answer
You use the LTRIM command after adding a new item, specifying a range that keeps only the desired portion of the list, such as the most recent one hundred items, which is a common pattern for maintaining a bounded size activity feed or log without letting the list grow…
Advertisement
AModel answer
You use the LTRIM command after adding a new item, specifying a range that keeps only the desired portion of the list, such as the most recent one hundred items, which is a common pattern for maintaining a bounded size activity feed or log without letting the list grow indefinitely and consume unlimited memory.
Example
LPUSH recent_activity 'new event' LTRIM recent_activity 0 99 -- keep only the most recent 100 items
Real-world example
A user activity feed pushes each new event to the front of a list and immediately trims it to keep only the hundred most recent entries, preventing the list from growing without bound over a user's entire history on the platform.
Likely follow-ups
- Does LTRIM remove items from the beginning or the end of the list?
- How do you decide an appropriate maximum size for a trimmed list?
Related topics