Home / Databases / Redis

DatabasesHow-toBeginner

Deleting Redis keys by pattern without blocking the server - SCAN, UNLINK and batching

Remove thousands or millions of keys that match a pattern safely with SCAN and UNLINK, in standalone Redis and Redis Cluster, without a KEYS-induced latency spike.

Deepak Bhardwaj7 min read

Applies toRedis 6.x, 7.x and 8.x, Valkey 7/8, Amazon ElastiCache, Azure Cache for Redis / Azure Managed Redis

The goal

You need to remove every key that matches a pattern, for example session:* after a release or cache:product:* after a bad data load. The obvious one-liner is:

redis-cli KEYS 'cache:product:*' | xargs redis-cli DEL

On a production server this can freeze Redis for seconds. KEYS walks the whole keyspace in one call, and Redis runs commands on a single main thread, so every other client waits. DEL on a big hash, set or list also frees memory on the main thread.

This guide shows the safe way: find keys with SCAN, delete them with UNLINK, in small batches.

Before you start

Check the size of the job

redis-cli INFO keyspace
redis-cli INFO memory | grep -E 'used_memory_human|lazyfree_pending_objects'
redis-cli INFO server | grep redis_version

INFO keyspace shows the number of keys per database. If the pattern covers most of the database, FLUSHDB ASYNC may be the right tool instead (see the warning below).

Count matches without deleting anything

redis-cli --scan --pattern 'cache:product:*' | wc -l

--scan uses SCAN under the hood: it returns keys in small pages and lets other clients run between pages. Look at a sample before you delete:

redis-cli --scan --pattern 'cache:product:*' | head -20

Warning

Patterns are glob-style. * matches anything, including colons, so cache:* matches cache:product:1 and cache:user:42. Always review a sample of the matches before you run a delete.

Check access

If you use ACLs, the user needs SCAN and UNLINK, and key permissions that cover the pattern. A NOPERM error partway through means some keys are outside the user's key patterns.

Command What happens Use when
DEL Removes the key and frees memory on the main thread Small string keys only
UNLINK Removes the key from the keyspace immediately; frees large values in a background thread Default choice for bulk deletes
EXPIRE key 1 Lets Redis expire the key itself You want Redis to pace the work
FLUSHDB ASYNC Empties the whole current database in the background Every key in the database should go

UNLINK is available from Redis 4.0. From Redis 6.0 you can also set lazyfree-lazy-user-del yes so plain DEL behaves like UNLINK.

Standalone Redis or a primary with replicas

Option 1: redis-cli and xargs

redis-cli -h redis01 -a "$REDIS_PASSWORD" --no-auth-warning \
  --scan --pattern 'cache:product:*' \
| xargs -r -d '\n' -n 500 redis-cli -h redis01 -a "$REDIS_PASSWORD" --no-auth-warning UNLINK
  • -n 500 sends 500 keys per UNLINK call, which keeps each call short.
  • -d '\n' (GNU xargs) treats each line as one key, so keys with spaces work. Keys that contain newlines still break this approach; use the Python script for those.
  • -r stops xargs running UNLINK with no arguments when nothing matches.

To slow the scan down on a busy server, add -i (seconds to wait between scan cycles, sub-second values such as -i 0.05 work) to the first redis-cli.

For TLS endpoints (most managed services), add --tls and use the port your service exposes.

Option 2: a Python script with a pause between batches

This gives you control over batch size, pacing and progress output. It uses redis-py.

import os, time
import redis

r = redis.Redis(host="redis01", port=6379,
                password=os.environ.get("REDIS_PASSWORD"),
                ssl=False, decode_responses=False)

pattern = "cache:product:*"
batch, deleted = [], 0

for key in r.scan_iter(match=pattern, count=1000):
    batch.append(key)
    if len(batch) >= 500:
        deleted += r.unlink(*batch)
        batch.clear()
        time.sleep(0.01)   # give other clients room
        if deleted % 50000 < 500:
            print(f"deleted {deleted}")

if batch:
    deleted += r.unlink(*batch)

print(f"done, deleted {deleted}")

count is a hint for how much work each SCAN call does, not a page size guarantee. Values between 100 and 1000 are a reasonable start.

SCAN can return the same key more than once, and keys added during the scan may or may not be returned. UNLINK on a key that no longer exists simply returns 0, so duplicates are harmless.

Redis Cluster

Two things change in a cluster:

  1. SCAN only covers the node you are connected to. You have to scan every primary.
  2. A multi-key command fails with CROSSSLOT unless all keys hash to the same slot. Keys on the same node can still sit in different slots.

List the primaries:

redis-cli -c -h node1 CLUSTER NODES | grep master | awk '{print $2}' | cut -d@ -f1

Then scan each primary and delete one key per call:

for node in $(redis-cli -h node1 CLUSTER NODES | grep master | awk '{print $2}' | cut -d@ -f1); do
  host=${node%:*}; port=${node#*:}
  echo "scanning $host:$port"
  redis-cli -h "$host" -p "$port" --scan --pattern 'cache:product:*' \
  | xargs -r -d '\n' -n 1 redis-cli -h "$host" -p "$port" UNLINK > /dev/null
done

One key per call is slower but always works. If your keys use a hash tag such as cache:{product}:1, they all live in one slot and you can batch them again.

In Python, redis.cluster.RedisCluster provides scan_iter, which walks every primary for you. Call unlink per key, or group keys by r.keyslot(key) before batching.

On managed clusters (ElastiCache cluster mode, Azure Managed Redis with the OSS cluster policy) the same rules apply. Check your service's documentation for how to reach each shard; some expose a single endpoint and proxy commands.

Big keys need extra care

A single hash with millions of fields is a "big key". UNLINK handles it in the background, but on old versions or with DEL it blocks. Find them first:

redis-cli --bigkeys
redis-cli --memkeys        # Redis 6+ (samples memory usage per key)

If you must use DEL (for example on Redis 3.x), empty the key in steps first with HSCAN + HDEL, SSCAN + SREM, ZREMRANGEBYRANK or LTRIM, then delete what is left.

Check the result

redis-cli --scan --pattern 'cache:product:*' | wc -l    # should be 0
redis-cli INFO memory | grep -E 'used_memory_human|lazyfree_pending_objects'
redis-cli --latency-history -i 5                        # watch latency while you run the job

lazyfree_pending_objects should drop back to 0 shortly after the job ends. Memory reported by the OS may not shrink straight away; check mem_fragmentation_ratio and, if needed, activedefrag (see the memory optimisation post).

Common problems

Symptom Cause Fix
Latency spikes during the job Batches too large or no pause Lower -n / batch size, add -i or sleep
CROSSSLOT Keys in request don't hash to the same slot Multi-key UNLINK in a cluster Use -n 1 or group keys by slot
Count never reaches 0 Application keeps writing new keys Stop the writer, or set TTLs instead of deleting
ERR unknown command 'UNLINK' Redis older than 4.0 Use DEL with small batches; plan an upgrade
NOPERM ACL key pattern does not cover the keys Use a user whose ~pattern matches
Keys with odd characters skipped or mangled Shell splitting Use the Python script

Caution

FLUSHDB and FLUSHALL delete every key in the database or the instance, and the deletes replicate to all replicas. There is no undo unless you restore an RDB or AOF backup. Check which database number your client uses (-n) before running either.

Prevent it next time

  • Put a TTL on cache keys when you write them, so clean-up is never a manual job.
  • Use a consistent key prefix per feature and per version (cache:v2:product:*) so you can drop an old version safely.
  • Disable or rename KEYS, FLUSHALL and FLUSHDB for application users with ACLs (-@dangerous or per-command rules).
  • Set lazyfree-lazy-user-del yes on Redis 6+ where your platform allows it.
  • Keep a scripted, reviewed clean-up tool in your runbook repository instead of ad hoc one-liners.