Difficulty: Intermediate
Why should you use SCAN instead of KEYS in production Redis, and what guarantees does SCAN give?
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.
0: SCAN 0 MATCH session:* COUNT 1000.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.| Aspect | KEYS | SCAN |
|---|---|---|
| Blocking | Blocks server for the full scan | Short blocks per call |
| Result | All matches at once | Batches with a cursor |
| Duplicates | None | Possible |
| Consistency | Point in time | Keys changing during scan may be missed |
| Safe in production | No | Yes, with sensible COUNT |
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.
cache:product:* and UNLINK each batch. Never KEYS piped into DEL.SCAN only covers the node you send it to. Run it on every primary node; most client libraries offer a helper for this.COUNT like 500 to 1000.KEYS for application users with ACLs (-@dangerous or -keys).| KEYS user:* | SCAN cursor loop | |
|---|---|---|
| Server blocked | For the whole scan | Only per short batch |
| Other clients | Time out | Served between calls |
| Memory for reply | One huge reply | Small batches |
| Duplicates | No | Possible, dedupe in app |
# 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".
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.
SCAN Cursor, KEYS Blocking, MATCH and COUNT, Single-threaded Execution, HSCAN SSCAN ZSCAN