Redis XTRIM in Ruby (Detailed Guide w/ Code Examples)

Use Case(s)

The XTRIM command in Redis is used to trim the number of messages in a stream to a maximum length. Common use cases include:

  • Maintaining fixed log size: Ensuring that logs or event streams do not grow indefinitely by keeping only the most recent entries.
  • Resource management: Constraining memory usage by limiting the number of entries in a stream.

Code Examples

Here are examples of how to use XTRIM in Ruby using the redis-rb client library.

require 'redis' redis = 'localhost', port: 6379) # Trimming a stream to have max 1000 entries approximately redis.xtrim('mystream', 'MAXLEN', '~', 1000) # Trimming a stream to have exactly 1000 entries if possible redis.xtrim('mystream', 'MAXLEN', '=', 1000)


  • The first example trims the stream to a maximum length of approximately 1000 entries. The tilde (~) indicates that the trimming is not strict. Redis might decide to remove more entries in one go for efficiency.
  • The second example uses an equal sign (=) to enforce a stricter limit where Redis will try to trim the stream exactly to the specified length, if possible.

Best Practices

  • When using XTRIM, it's often better to use the approximate trimming (with ~) as it can be more efficient and reduce the number of operations needed to trim the stream.

Common Mistakes

  • Not handling the possibility that XTRIM might remove more elements than specified when using approximate trimming.
  • Using XTRIM without understanding its performance implications, especially on very large streams.


Q: Can I use XTRIM with consumer groups? A: Yes, but you must ensure that you do not trim entries that have pending messages for any consumer group.

Q: How does XTRIM affect memory usage? A: By trimming streams, you reduce the memory footprint of your Redis instance, as old entries are deleted.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.