0
0
RedisComparisonBeginner · 4 min read

KEYS vs SCAN in Redis: Key Differences and When to Use Each

In Redis, 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.

FactorKEYSSCAN
Operation TypeImmediate full key retrievalIncremental cursor-based iteration
Performance ImpactBlocks Redis during executionNon-blocking, low impact
Use CaseSmall datasets or debuggingLarge datasets or production
Return TypeAll matching keys at onceSubset of keys per call
ComplexitySimple to useRequires multiple calls with cursor
Pattern SupportSupports glob-style patternsSupports 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

redis
127.0.0.1:6379> KEYS user:*
1) "user:1"
2) "user:2"
3) "user:100"
Output
1) "user:1" 2) "user:2" 3) "user:100"
↔️

SCAN Command Equivalent

redis
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"
Output
1) "3" 2) 1) "user:1" 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

Use KEYS only for small datasets or debugging because it blocks Redis.
Use SCAN for large datasets to iterate keys without blocking.
SCAN returns keys incrementally using a cursor, requiring multiple calls.
Both commands support pattern matching with glob-style syntax.
SCAN is safer and recommended for production environments.