KEYS vs SCAN in Redis: Key Differences and When to Use Each
KEYS returns all keys matching a pattern immediately but can block the server if the dataset is large. SCAN iterates keys incrementally without blocking, making it safer for production use when working with many keys.Quick Comparison
Here is a quick side-by-side comparison of KEYS and SCAN commands in Redis.
| Factor | KEYS | SCAN |
|---|---|---|
| Operation Type | Immediate full key retrieval | Incremental cursor-based iteration |
| Performance Impact | Blocks Redis during execution | Non-blocking, low impact |
| Use Case | Small datasets or debugging | Large datasets or production |
| Return Type | All matching keys at once | Subset of keys per call |
| Complexity | Simple to use | Requires multiple calls with cursor |
| Pattern Support | Supports glob-style patterns | Supports glob-style patterns |
Key Differences
The KEYS command scans the entire keyspace at once and returns all keys matching a given pattern. This means it can cause Redis to pause and block other operations if the dataset is large, which can hurt performance and responsiveness.
On the other hand, SCAN uses a cursor-based approach to incrementally return keys in small batches. It does not block Redis and allows other commands to run concurrently. However, it requires multiple calls to retrieve all matching keys and may return some keys multiple times or miss some during iteration if keys are added or removed concurrently.
Both commands support glob-style patterns like * and ?, but SCAN is designed for safe use in production environments where performance matters.
KEYS Command Example
127.0.0.1:6379> KEYS user:* 1) "user:1" 2) "user:2" 3) "user:100"
SCAN Command Equivalent
127.0.0.1:6379> SCAN 0 MATCH user:* 1) "3" 2) 1) "user:1" 127.0.0.1:6379> SCAN 3 MATCH user:* 1) "0" 2) 1) "user:2" 2) "user:100"
When to Use Which
Choose KEYS when you have a small dataset or are debugging and want all matching keys immediately without concern for blocking.
Choose SCAN when working with large datasets in production to avoid blocking Redis and to safely iterate keys in batches.
Using SCAN helps keep your Redis server responsive and stable under load.
Key Takeaways
KEYS only for small datasets or debugging because it blocks Redis.SCAN for large datasets to iterate keys without blocking.SCAN returns keys incrementally using a cursor, requiring multiple calls.SCAN is safer and recommended for production environments.