LazyLayersv9.1.0
Learn caching

Delete Redis keys by pattern

Delete Redis keys by pattern safely: SCAN with MATCH and UNLINK in batches, never KEYS. Covers redis-cli, ioredis in Node.js and clearing every server's memory.

To delete Redis keys by pattern, use SCAN with MATCH to find the keys in small pages, and UNLINK to delete each page. Redis has no command that deletes by pattern, and DEL does not accept wildcards. Do not use KEYS in production, because it blocks every other client while it walks the whole keyspace.

Level: one to ten · You need: Redis cache in Node.js and cache invalidation

Rendering diagram...

Each pass touches a few hundred keys. Redis can answer other clients between passes.

Delete keys by pattern from the command line

redis-cli --scan runs SCAN for you and prints the matching keys, one per line. Pipe them into UNLINK:

redis-cli --scan --pattern 'user:42:*' | xargs redis-cli unlink

This is fine for a quick cleanup on a development machine. It has limits:

  • Key names with spaces or quotes break it. xargs splits on whitespace and reads quotes as syntax. Use tr '\n' '\0' | xargs -0 -n 100 redis-cli unlink, which handles spaces and quotes but not newlines.
  • No atomicity. Keys written after the scan passes them are missed, and a failure halfway leaves some keys deleted.
  • Many round trips. Each xargs batch starts a new redis-cli process and a new connection.
  • An empty result can make GNU xargs run redis-cli unlink with no keys. Add -r to skip that.

For application code, do the same thing from Node.js, as shown below.

Why does KEYS block Redis?

KEYS user:42:* looks at every key in the database and returns all the matches in one reply. Its cost is O(N) in the total number of keys, not the number of matches. Redis executes commands on a single thread, so while KEYS runs, no other client gets an answer, including your GET calls for the cache.

With a few thousand keys you will not notice. With a few million, KEYS can hold Redis for seconds, and your app times out. The Redis documentation says to use KEYS in production only with extreme care, and to use SCAN instead.

How does SCAN work?

SCAN walks the keyspace a little at a time. You call it with a cursor, and it returns a new cursor and a page of keys. Start with cursor 0, pass back whatever cursor you receive, and stop when it returns 0 again.

SCAN 0 MATCH user:42:* COUNT 500
1) "9216"                # next cursor
2) 1) "user:42:profile"
   2) "user:42:orders"
SCAN 9216 MATCH user:42:* COUNT 500
1) "0"                   # back to 0, the scan is complete
2) 1) "user:42:settings"

Four rules to know:

  • COUNT is a hint. It sets roughly how many keys Redis examines per call, not how many it returns. A page can be empty and the scan is still not done.
  • MATCH filters after the page is read. A narrow pattern does not make the scan cheaper. Redis still visits every key. It only returns fewer of them.
  • A key can appear twice. Your code must tolerate duplicates. Unlinking a deleted key does nothing, so deletes are safe to repeat.
  • Keys added or removed during the scan may or may not appear. Only keys that existed from start to finish are guaranteed.

Treat the cursor as an opaque string. Do not compute with it.

DEL removes a key and frees its memory right away, on the main thread. For a small string that takes microseconds. For a hash with a million fields it can take long enough to stall Redis.

UNLINK (Redis 4.0 and later) removes the key from the keyspace at once and frees the memory in a background thread. The result is the same for your application and cheaper for Redis. When you delete many keys, prefer UNLINK.

What about FLUSHDB and FLUSHALL?

FLUSHDB deletes every key in the current database. FLUSHALL deletes every key in every database on the server. Both accept ASYNC, which frees the memory in the background and returns at once.

They are the right tool for a throwaway test Redis. They are rarely right for a shared one. A real Redis often holds sessions, job queues and rate-limit counters beside the cache, and a flush wipes them all. Deleting just the cache keys with a pattern touches only what you meant to touch.

Delete Redis keys by pattern in Node.js

ioredis wraps SCAN in scanStream, a stream that follows the cursor for you and emits one page of keys at a time. Awaiting inside the loop applies back pressure, so the script never runs ahead of Redis.

delete-by-pattern.ts
import { Redis } from 'ioredis'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')

export async function deleteByPattern(pattern: string, batchSize = 500): Promise<number> {
  let deleted = 0
  let batch: string[] = []

  const flush = async () => {
    if (batch.length === 0) return
    const keys = batch
    batch = []
    deleted += await redis.unlink(...keys)
  }

  const stream = redis.scanStream({ match: pattern, count: 500 })
  for await (const keys of stream as AsyncIterable<string[]>) {
    batch.push(...keys) // a page can be empty or repeat a key
    if (batch.length >= batchSize) await flush()
  }
  await flush()
  return deleted
}

console.log(await deleteByPattern('user:42:*'))
await redis.quit()

The batch keeps each UNLINK call at a few hundred keys. A repeated key is harmless, because UNLINK returns 0 for a key that is gone. On Redis Cluster, scan every primary node, and unlink one key at a time or through a pipeline, because a multi-key UNLINK fails when the keys sit in different hash slots.

Can a Lua script delete keys by pattern?

Yes, but a long script blocks Redis the same way KEYS does. A script runs as one step, and Redis runs nothing else until it finishes. A Lua loop that scans and deletes the entire keyspace in one call is KEYS with extra steps.

The safe form runs one SCAN page per script call and keeps the loop in Node.js:

delete-by-pattern-lua.ts
import { Redis } from 'ioredis'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')

const scanAndUnlink = `
local page = redis.call('SCAN', ARGV[1], 'MATCH', ARGV[2], 'COUNT', ARGV[3])
if #page[2] > 0 then redis.call('UNLINK', unpack(page[2])) end
return page[1]
`

let cursor = '0'
do {
  cursor = String(await redis.eval(scanAndUnlink, 0, cursor, 'user:42:*', 500))
} while (cursor !== '0')
await redis.quit()

This saves one round trip per page but gives up Redis Cluster compatibility, because the script touches keys it did not receive in KEYS. For the Lua basics, see Redis Lua scripts.

The real problem: other copies are still stale

Suppose each app server keeps a small in-memory copy of hot values in front of Redis, as in the Redis cache lesson. After you delete user:42:* from Redis, the three servers still hold user:42:profile in memory. Each one keeps serving the old value until its own TTL ends.

await db.users.update('42', { plan: 'pro' })
await deleteByPattern('user:42:*') // Redis is clean, memory on every server is not

Fixing it by hand means publishing a message on Pub/Sub, subscribing on every server, deleting local keys that match the pattern, and handling a server that was offline when the message went out.

The same idea with invalidateByPattern

cache.invalidateByPattern does the whole job: the local memory layer, Redis, and every other server.

users.ts
import { setupCache } from 'lazy-layers-cache'
import { db } from './db.ts'

const cache = await setupCache<string, unknown>({
  namespace: 'users-api',
  redis: { required: true },
})

export async function changePlan(id: string, plan: string): Promise<void> {
  await db.users.update(id, { plan })
  await cache.invalidateByPattern(`user:${id}:*`)
}
Rendering diagram...

What it does:

  • SCAN, never KEYS. Redis keys are matched with SCAN ... MATCH limited to this cache's namespace, so user:42:* cannot reach another application's keys.
  • Batches. Matches are deleted in batches. With the Redis store on its default layout, each batch goes out as one Lua script per 64 keys, and each delete also stops a load that was in flight from writing the old value back.
  • Every server. Each server clears its own memory when the event arrives on the event bus.

In a recorded run on 9.0, a 500-key pattern delete took 1.9 ms, down from 36.3 ms before batching. The cost of the scan still follows the number of keys in Redis, not the number that matched.

Pattern or tags?

Patterns need keys that share a prefix. When they do not, use a tag.

invalidateByPattern('user:42:*')invalidateTags(['team:7'])
Keys must shareA prefixNothing, you tag them when storing
CostScans the keyspaceDoes not grow with the number of keys
Wildcards* onlyNone
Set atInvalidation timeWrite time: getOrSet(key, loader, { tags: ['team:7'] })

For example, order:9 and invoice:31 have no common prefix but can both carry the tag team:7. See invalidation for how tags work.

Keep patterns narrow, and never build one from user input. * is the only wildcard in lazy-layers-cache, and invalidateByPattern('*') clears everything on every server. Redis itself accepts more glob characters, such as ? and [ae], which makes raw user input in a MATCH argument risky.

See the API reference for the full behavior.

Next lesson: database caching with PostgreSQL.

Further reading

  • Redis, KEYS: its warning not to use KEYS in regular application code, and its O(N) cost.
  • Redis, SCAN: incremental iteration, and why a key can be returned more than once.
  • Redis, UNLINK: like DEL, but it reclaims memory in a different thread so it does not block.
  • Redis, client-side caching reference: the invalidation messages that remove stale copies held outside Redis.

Questions

How do I delete Redis keys by pattern?

Run SCAN with MATCH and COUNT until the cursor returns 0, and pass each page of keys to UNLINK. From a shell, redis-cli --scan --pattern 'user:42:*' | xargs redis-cli unlink does this. Redis has no single command that deletes by pattern, and DEL does not accept wildcards.

Why should I not use the KEYS command in production?

KEYS walks the whole keyspace in one command, so it costs O(N) in the number of keys. Redis runs commands on one thread, so every other client waits until KEYS finishes. On a large dataset that is seconds of downtime. SCAN returns a small page per call and lets other commands run between pages.

What is the difference between DEL and UNLINK in Redis?

Both remove keys. DEL frees the memory right away on the main thread, which is slow for a large hash, list or set. UNLINK removes the key from the keyspace at once and frees the memory in a background thread, so it blocks Redis less. UNLINK is available from Redis 4.0.

How do I delete all keys in Redis?

FLUSHDB deletes every key in the current database and FLUSHALL deletes every key in every database. Both accept ASYNC to free memory in the background. Use them only on a Redis you own alone. On a shared Redis they also delete other applications' sessions, queues and rate-limit counters.

Can SCAN return the same key twice?

Yes. A full SCAN returns every key that existed for the whole iteration, but it may return a key more than once, and keys added or removed during the scan may or may not appear. Code that processes keys must tolerate duplicates. Unlinking an already deleted key is harmless.

Does deleting keys in Redis clear the in-memory cache on my servers?

No. If each app server keeps its own in-memory copy in front of Redis, deleting the Redis keys leaves those copies in place until they expire. Each server needs to be told to drop them, for example over Pub/Sub. cache.invalidateByPattern in lazy-layers-cache does both steps.

On this page