How to Use SCAN Command in Redis for Iterating Keys
Use the
SCAN command in Redis to iterate over keys incrementally without blocking the server. It returns a cursor and a list of keys, allowing you to continue scanning until the cursor returns to zero. This helps safely scan large keyspaces in small batches.Syntax
The SCAN command syntax is:
SCAN cursor [MATCH pattern] [COUNT count]
cursor: A number to keep track of the scan position, starting with 0.
MATCH pattern: Optional filter to return only keys matching the pattern.
COUNT count: Optional hint for how many keys to return per call (not guaranteed).
redis
SCAN cursor [MATCH pattern] [COUNT count]
Example
This example shows how to scan all keys in the database in batches of 5, printing each batch until the scan is complete.
redis
127.0.0.1:6379> SET key1 "value1" OK 127.0.0.1:6379> SET key2 "value2" OK 127.0.0.1:6379> SET key3 "value3" OK 127.0.0.1:6379> SET key4 "value4" OK 127.0.0.1:6379> SET key5 "value5" OK 127.0.0.1:6379> SCAN 0 COUNT 5 1) "3" 2) 1) "key1" 2) "key2" 3) "key3" 4) "key4" 5) "key5" 127.0.0.1:6379> SCAN 3 COUNT 5 1) "0" 2) (empty list or set)
Output
1) "3"
2) 1) "key1"
2) "key2"
3) "key3"
4) "key4"
5) "key5"
1) "0"
2) (empty list or set)
Common Pitfalls
1. SCAN does not guarantee to return all keys in one call; you must loop until the cursor returns to 0.
2. The COUNT option is a hint, not a limit; actual returned keys may be more or less.
3. Keys may appear multiple times or be missed if keys are added or deleted during scanning.
4. Avoid using KEYS for large datasets as it blocks Redis; use SCAN instead.
redis
;; Wrong: Using SCAN once and expecting all keys 127.0.0.1:6379> SCAN 0 1) "5" 2) 1) "key1" ;; Right: Loop until cursor is 0 127.0.0.1:6379> SCAN 0 1) "5" 2) 1) "key1" 127.0.0.1:6379> SCAN 5 1) "0" 2) 1) "key2"
Quick Reference
| Option | Description |
|---|---|
| cursor | Position to start scanning, use 0 initially |
| MATCH pattern | Filter keys by pattern (e.g., 'user:*') |
| COUNT count | Hint for number of keys to return per call |
| Return | Array with new cursor and list of keys |
Key Takeaways
Use SCAN with a cursor starting at 0 and loop until cursor returns 0 to scan all keys.
MATCH filters keys by pattern; COUNT hints how many keys to return per call.
SCAN is non-blocking and safe for large datasets, unlike KEYS.
Results may include duplicates or miss keys if data changes during scan.
Always check the returned cursor to know when scanning is complete.