Deleting Large Sorted Sets in Redis

To learn more about why deleting large objects is slow in Redis, read this quick overview

To delete a large sorted set in Redis:

  1. Rename the key to a unique, namespaced key so that the sorted set appears “deleted” to other Redis clients immediately.

  2. Incrementally delete members from the sorted set in small batches until it is empty. By limiting the size of our delete commands, we ensure that we don’t block the server for too long.

Please note that the following code doesn’t gracefully handle Redis connection failures. If any Redis command fails and raises an exception, you’ll need to clean up manually.

Pseudo-code

# Rename the key
newkey = "gc:hashes:" + redis.INCR("gc:index")
redis.RENAME("my.zset.key", newkey)

# Delete members from the sorted set in batche of 100s
while redis.ZCARD(newkey) > 0
  redis.ZREMRANGEBYRANK(newkey, 0, 99)
end

Ruby

$redis = Redis.new

def delete_sorted_set(key)
  # Rename the key
  newkey = "gc:zsets:#{$redis.incr("gc:index")}"
  $redis.rename(key, newkey)

  # Delete members from the sorted set in batches of 100
  while $redis.zcard(newkey) > 0
    $redis.zremrangebyrank(newkey, 0, 99)
  end
end

# Example:
#
#   delete_sorted_set("my.large.set")

Here are some example implementations of the above using background jobs in Ruby:

← Back to “Deleting Large Objects in Redis”

Last updated 09 Jun 2015. Originally written by Tyson Mote

← Back to docs