SCAN over KEYS

Difficulty: Intermediate

Question

Why should you use SCAN instead of KEYS in production Redis, and what guarantees does SCAN give?

Answer

KEYS pattern walks the entire keyspace in one go and, because Redis executes commands on a single main thread, blocks every other client until it finishes. On a database with tens of millions of keys that can take seconds, which looks like an outage. SCAN does the same job incrementally: each call returns a small batch of keys plus a cursor, so other commands run between batches and the server stays responsive.

How SCAN works

  1. Start with cursor 0: SCAN 0 MATCH session:* COUNT 1000.
  2. Redis returns a new cursor and a batch of keys.
  3. Call again with the returned cursor.
  4. When the returned cursor is 0, the iteration is complete.

Options:

  • MATCH pattern filters keys, but the filter is applied after a batch is fetched. A call can return zero matches while iteration is still ongoing, so never stop just because a page was empty.
  • COUNT n is a hint for how much work to do per call (default 10). It is not a page size guarantee.
  • TYPE string|hash|... (6.0+) filters by data type.

What SCAN guarantees, and what it does not

  • Every key that exists for the whole duration of the scan will be returned at least once.
  • A key may be returned more than once, especially if the hash table resizes. Deduplicate in your app if that matters.
  • Keys added or deleted during the scan may or may not appear.
  • Redis documents each call as O(1); a complete iteration is still O(N), just spread across many short calls.

KEYS vs SCAN

AspectKEYSSCAN
BlockingBlocks server for the full scanShort blocks per call
ResultAll matches at onceBatches with a cursor
DuplicatesNonePossible
ConsistencyPoint in timeKeys changing during scan may be missed
Safe in productionNoYes, with sensible COUNT

The same idea for big collections

HSCAN, SSCAN and ZSCAN iterate the fields of one large hash, set or sorted set. Prefer them over HGETALL or SMEMBERS on collections with hundreds of thousands of members, which have the same blocking problem as KEYS.

Real use cases and pitfalls

  • Bulk delete by pattern: scan for cache:product:* and UNLINK each batch. Never KEYS piped into DEL.
  • Data migrations: scan, transform and rewrite keys gradually.
  • Redis Cluster: SCAN only covers the node you send it to. Run it on every primary node; most client libraries offer a helper for this.
  • Scanning is still work. On a hot primary, run big scans on a replica or with a modest COUNT like 500 to 1000.
  • The best fix is often design: if you regularly need "all keys for user 42", keep them in a set or use a hash instead of searching by pattern.
  • Block KEYS for application users with ACLs (-@dangerous or -keys).
KEYS vs SCAN on 50 million keys. SCAN spreads the work so other clients keep getting served.
KEYS user:*SCAN cursor loop
Server blockedFor the whole scanOnly per short batch
Other clientsTime outServed between calls
Memory for replyOne huge replySmall batches
DuplicatesNoPossible, dedupe in app

Code examples

SCAN from redis-cli

# One step of the iteration
redis-cli SCAN 0 MATCH 'session:*' COUNT 1000

# redis-cli can loop the cursor for you
redis-cli --scan --pattern 'session:*' --count 1000 | head

# Delete keys by pattern safely, in batches of 500
redis-cli --scan --pattern 'cache:product:*' | xargs -r -n 500 redis-cli UNLINK

# Iterate a large hash without HGETALL
redis-cli HSCAN cart:42 0 COUNT 100

The first element is the next cursor. Iteration finishes when it returns "0".

Async iteration in Node.js with node-redis

import { createClient } from 'redis';
const client = await createClient().connect();

// node-redis v4 handles the cursor loop for you
// (v5 yields arrays of keys per batch instead of single keys)
const toDelete = [];
for await (const key of client.scanIterator({ MATCH: 'cache:product:*', COUNT: 1000 })) {
  toDelete.push(key);
  if (toDelete.length === 500) {
    await client.unlink(toDelete.splice(0));
  }
}
if (toDelete.length) await client.unlink(toDelete);
await client.quit();

Deleting in batches with UNLINK keeps each call small and frees memory in the background.

Key points

  • KEYS is O(N) and blocks the single main thread; never run it in production.
  • SCAN is cursor based; iteration ends when the cursor returns to 0.
  • MATCH is applied after fetching, so empty pages are normal mid-scan.
  • COUNT is a hint, not a page size; default is 10.
  • SCAN may return duplicates and may miss keys changed during the scan.
  • In Redis Cluster, scan each primary node separately.

Common follow-up questions

  • Why can SCAN return the same key twice?
  • How would you delete a million keys matching a pattern without hurting latency?
  • How does SCAN work in Redis Cluster?
  • How would you redesign the data model so you never need to scan by pattern?

Interview tips

  • Explain why KEYS blocks: single-threaded command execution, not just "it is slow".
  • State SCAN's guarantees precisely, including duplicates and the empty-page gotcha.
  • Suggest a data-model fix, like keeping an index set, to show design thinking.

Concepts covered

SCAN Cursor, KEYS Blocking, MATCH and COUNT, Single-threaded Execution, HSCAN SSCAN ZSCAN

More Redis & Caching questions