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

Use Case(s)

The ZREMRANGEBYRANK command in Redis is used to remove all elements in a sorted set stored at a specific key, which have ranks within the specified inclusive range. Common use cases include:

  • Purging outdated entries from leaderboards or scoreboards.
  • Managing windows of time-series data where older data points are removed based on their rank (not score).

Code Examples

Example 1: Removing Entries by Rank

Suppose you maintain a leaderboard for a game, and you want to limit this leaderboard to the top 100 scores only. You can use ZREMRANGEBYRANK to remove all other entries.

import redis # Connect to Redis client = redis.Redis(host='localhost', port=6379, db=0) # Remove all entries except the top 100 client.zremrangebyrank('game_leaderboard', 0, -101)

In this example, we connect to Redis and remove entries from the 'game_leaderboard' sorted set that do not rank in the top 100. The indices start at 0, so -101 effectively keeps the top 100 scores (from index 0 to 99).

Example 2: Clearing Lower Ranked Data Periodically

If you want to periodically clear data ranked lower than a certain threshold in a real-time analytics scenario, you might use a similar approach.

# Assuming client has been defined as above # Remove the lowest-ranked half of the entries total_entries = client.zcard('realtime_data') client.zremrangebyrank('realtime_data', 0, total_entries // 2 - 1)

Here, we first determine the number of entries (zcard) and then remove the lower half of those entries. This is useful for maintaining only the most relevant data in memory.

Best Practices

  • Backup Before Deletion: Always backup your data before performing mass deletions, especially in production environments.
  • Validate Ranks Dynamically: If your use case involves dynamic thresholds, calculate the ranks using zcard and other Redis commands within your deletion logic to avoid hardcoding values.

Common Mistakes

  • Off-by-One Errors: The ranks are zero-based, so ensure that your rank calculations account for this. Misunderstanding this can lead to removing an incorrect range of data.
  • Ignoring Return Values: ZREMAPEBYRANK returns the count of removed elements. Always check this return value to ensure your operation succeeded as expected.


Q: How does Redis handle non-existent keys with ZREMRANGEBYRANK? A: If the key does not exist, Redis will treat it as an empty sorted set and return 0, indicating no elements were removed.

Q: Can ZREMRANGEBYRANK work with negative indices? A: Yes, negative indices specify offsets from the end of the sorted set, where -1 is the last element, -2 is the penultimate element, etc.

Was this content helpful?

Start building today

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