Introducing Dragonfly Cloud! Learn More

Redis XTRIM in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

XTRIM is a Redis command used to trim the size of a stream to a maximum number of elements. Common use cases include:

  • Limiting the memory footprint of streams by trimming old data.
  • Maintaining a fixed-size log or event history.

Code Examples

Example 1: Trimming a Stream by Maximum Length

const redis = require('redis'); const client = redis.createClient(); client.xadd('mystream', '*', 'field1', 'value1', 'field2', 'value2', err => { if (err) throw err; // Trim the stream to only keep the latest 1000 entries client.xtrim('mystream', 'MAXLEN', '~', 1000, (trimErr, res) => { if (trimErr) throw trimErr; console.log(`Stream trimmed, ${res} items removed.`); }); });

In this example, XTRIM is used with MAXLEN which means the stream will be trimmed to the specified length. The ~ argument indicates that the trim operation is approximate and Redis may remove slightly more than 1000 items to improve performance.

Example 2: Using XTRIM in a Transaction

const redis = require('redis'); const client = redis.createClient(); // Start a Redis transaction client.multi() .xadd('mystream', '*', 'field1', 'value1') .xtrim('mystream', 'MAXLEN', '~', 1000) .exec((err, replies) => { if (err) throw err; console.log(`Transaction completed with responses: ${replies}`); });

Here, xadd and xtrim are part of a multi/exec transaction, ensuring atomicity. If one command fails, none of the commands take effect.

Best Practices

  • Use the ~ option for better performance if an exact trim is not necessary.
  • Consider using XTRIM in a Lua script or transaction if you need to perform multiple operations atomically.

Common Mistakes

  • Not handling errors properly - always check for errors in callbacks.
  • Over-trimming or under-trimming due to not understanding how the ~ option affects the operation.

FAQs

Q: When should I avoid using the ~ option with XTRIM? A: Avoid using the ~ option when you need precise control over the number of elements in the stream.

Q: Is XTRIM an expensive operation? A: It can be, especially on large streams. However, the ~ option can help mitigate performance costs by trimming less precisely but more efficiently.

Was this content helpful?

Start building today 

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