Why KEYS Can Crash Your Redis and How SCAN Keeps It Running
The article explains how using the KEYS command on large Redis datasets can block the single‑threaded server and cause outages, and demonstrates how the incremental SCAN command safely retrieves keys without impacting performance, including syntax, options, and practical examples.
Introduction
When you need to inspect online Redis data, especially keys with a specific prefix, you may face massive key spaces that make naive queries risky.
Incident
In a production environment the token cache used keys like user_token:userid. Operations staff ran keys user_token* to count logged‑in users, which caused Redis to become unresponsive.
Root Cause Analysis
Redis may store millions of keys; the KEYS command performs a full O(N) scan, and because Redis processes commands sequentially on a single thread, the command blocks all other operations, leading to a “dead” server.
Solution
Replace KEYS with the incremental SCAN command, which iterates over the keyspace in small steps without blocking the server.
Complexity remains O(N) but works with a cursor, so the thread is not blocked.
The COUNT argument controls how many entries are examined per iteration.
Supports pattern matching just like KEYS.
No server‑side cursor state is kept; the client tracks the cursor value.
Results may contain duplicates; the client must deduplicate.
An empty result does not mean completion; the cursor must be zero to finish.
SCAN Command Syntax
SCAN cursor [MATCH pattern] [COUNT count]Explanation
SCANreturns a cursor and a subset of matching keys; repeat the call with the new cursor until the cursor returned is 0, indicating the iteration is complete.
Example
Starting with cursor 0 returns cursor 6 and some keys; subsequent calls use cursor 6 to continue scanning until the cursor reaches 0.
Conclusion
For small datasets KEYS may be acceptable, but with large key spaces you must use SCAN to avoid performance degradation; this pattern is also a common interview question.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
