Databases 4 min read

Why Using Redis KEYS Can Crash Production and How SCAN Saves the Day

The article explains how the Redis KEYS command can block a production server when scanning millions of keys, analyzes the root cause, and demonstrates how the incremental SCAN command provides a safe, non‑blocking alternative for large datasets.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Why Using Redis KEYS Can Crash Production and How SCAN Saves the Day

Introduction

Sometimes we need to check online Redis usage, especially key prefixes, but large data sets make naive queries risky.

Incident

Using a key pattern like keys user_token* to count logged‑in users caused Redis to become unresponsive.

Root Cause

With millions of login keys, the KEYS command performs a full O(n) scan; because Redis is single‑threaded, this blocks other commands.

Solution

Replace KEYS with the incremental SCAN command, which iterates using a cursor and does not block the server.

Complexity remains O(n) but works in small steps.

Supports a COUNT argument to control how many slots are examined per iteration.

Provides pattern matching like KEYS.

No server‑side cursor state is kept; the client tracks the cursor returned by SCAN.

Results may contain duplicates, so the client must deduplicate.

An empty result does not mean the scan is finished; the cursor value must be checked for zero.

SCAN Command Syntax

SCAN cursor [MATCH pattern] [COUNT count]

Example

Starting with cursor 0 returns a new cursor (e.g., 6) and a subset of keys; subsequent calls continue from that cursor until it returns 0.

Conclusion

The SCAN approach is interview‑friendly and safe for large datasets; using KEYS on production can severely impact performance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisKEYSSCAN
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.