Dragonfly

Working with Redis SCAN: Syntax, Examples, Pros & Cons

The Redis SCAN command iterates over keys in the Redis database without blocking the server.

January 20, 2026

Guides Cover | Redis

What Is the Redis SCAN Command?

The Redis SCAN command iterates over keys in the Redis database without blocking the server. Unlike commands such as KEYS, which return all matching keys in a single response, SCAN uses a cursor-based mechanism to fetch a subset of keys at a time. This allows applications to process large datasets in smaller chunks, reducing the risk of performance bottlenecks or server unresponsiveness.

Redis SCAN is useful when dealing with databases containing millions of keys. By iterating over keys or elements in smaller batches, applications maintain interactivity, and the Redis server load stays predictable. SCAN is practical for background or periodic maintenance tasks, such as cleaning up old keys or migrating subsets of data.

This is part of a series of articles about Redis performance.


Redis SCAN Syntax and Parameters

The basic syntax of the SCAN command is:

SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]

Let’s review the parameters:

  • cursor: A numeric value indicating the scan position. Start with 0 and continue using the cursor returned from each call. If the value is back to 0 again, it means a full iteration is done.
  • MATCH pattern: (Optional) Filters results to only return keys matching the specified glob-style pattern. For example, MATCH user:* returns only keys that begin with user:.
  • COUNT count: (Optional) Hints how many elements to return per iteration. This is not a hard limit; the server may return more or fewer elements. The default value is 10.
  • TYPE type: (Optional) Asks SCAN to only return values that match a given data type. The TYPE option is only available for SCAN, not HSCAN or ZSCAN etc.

Other Useful SCAN-Family Commands

Redis provides variations of the SCAN command to iterate over different types of data structures. These include:

  • SCAN: Iterates over the keys in the database.
  • SSCAN: Iterates over the elements of a set.
  • HSCAN: Iterates over the fields and values of a hash.
  • ZSCAN: Iterates over the members and scores of a sorted set.

Each of these commands follows a similar cursor-based pattern and accepts MATCH and COUNT options. The cursor starts at 0 and should be updated with each call using the value returned by Redis. If the cursor value is back to 0 again, a full iteration is done.


Redis SCAN Examples and Usage

The SCAN command can be used in a loop where each call returns a new cursor and a list of elements. A full iteration starts with cursor 0 and continues until the command returns cursor 0 again, signaling completion. Below we provide a few examples that illustrate its use, adapted from the Redis documentation.

Here’s a basic example of a keyspace scan:

> SCAN 0
1) "17"
2)  1) "hll:visitors"
    2) "key"
    3) "users"
    4) "airline:1"
    5) "airline:2"
    6) "mystream"
    7) "user:active:2025-11-06"
    8) "airline:3"
    9) "mycounter"
    10) "counter_value"

> SCAN 17
1) "0"
2) 1) "departments"
   2) "places"
   3) "scores"
   4) "product:1001"
   5) "counter"

In this example, the first command starts the iteration and returns a partial list of keys along with cursor 17. The second command continues from that point using the cursor and ends when the returned cursor is 0.

SCAN can also filter results using the MATCH option. For example, to return keys that contain "airline:":

> SCAN 0 MATCH airline:*
1) "9"
2) 1) "airline:1"
   2) "airline:2"

Here, MATCH is applied after scanning. Thus, many calls may return empty results if the pattern is rare. Using a larger COUNT value (e.g., 1000) can increase the chance of retrieving matches in fewer calls.

SCAN also supports the TYPE option to filter by Redis key type:

> SCAN 2 TYPE zset
1) "3"
2) 1) "airline:on_time:international"

In this case, the scan only returns keys of data type sort set (zset), including other data types implemented using the same internal structure (such as Geo hashes).

For structured data types like sets, hashes, or sorted sets, Redis provides specific commands: SSCAN, HSCAN, and ZSCAN. These work similarly to SCAN. Here’s an example of using SSCAN with a pattern:

> SADD city:set "karachi" "dubai" "doha" "london" "lausanne"
(integer) 5

> SSCAN city:set 0 MATCH l*
1) "0"
2) 1) "london"
   2) "lausanne"

To retrieve only hash fields without values, HSCAN supports the NOVALUES option:

> HSET user:stats logins 10 purchases 3
(integer) 2

> HSCAN user:stats 0 NOVALUES
1) "0"
2) 1) "logins"
   2) "purchases"

Important notes: 

  • SCAN may return duplicates, and elements may be missed if they are added or removed during the iteration. Applications should handle duplicates and ensure they don’t assume strong consistency.
  • The number of elements returned per call is not fixed. It can vary depending on internal representation, collection size, and the COUNT hint. Smaller keyspaces or collections may be returned entirely in one call, while larger ones are processed in chunks.
  • SCAN can be safely used in multiple parallel iterations or stopped midway without server impact, as all state is client-side via the cursor.

Under the Hood: How Redis SCAN Works

Internally, the SCAN command uses a cursor-based iteration mechanism over the keyspace’s hash table. Each call to SCAN returns a new cursor and a subset of keys. The cursor is a numeric value that represents the scan position. A cursor value of 0 indicates the start of a new scan, and when the server returns 0 again, the full scan is complete.

SCAN does not guarantee a full snapshot of the keyspace at a single point in time. Since Redis is single-threaded and SCAN is non-blocking, keys may be added or removed during iteration. This means keys can appear more than once or be missed if deleted mid-scan. Applications using SCAN should handle duplicates or inconsistencies across scans.


Redis SCAN vs. KEYS

The KEYS command in Redis returns all keys matching a pattern in a single call, blocking the server until it completes. This makes KEYS dangerous to use in production or with large datasets, as it can freeze the Redis server, impacting responsiveness for other clients. In contrast, SCAN provides a non-blocking, incremental way to enumerate keys, minimizing the impact on server performance.

Although both commands support pattern matching, their operational characteristics make them suitable for different purposes. KEYS is practical only for small datasets or one-off debugging tasks, while SCAN is for regular usage, background tasks, or applications where availability is critical. Developers should avoid mixing the two indiscriminately and prefer SCAN for scalable, production-safe operations.


Redis SCAN Pros and Cons 

The SCAN command offers an efficient way to iterate over large Redis datasets without overwhelming the server. However, it also comes with trade-offs that developers need to understand. Below are the key advantages and limitations.

Pros

  • Non-blocking operation: SCAN does not block the Redis server, giving space to other commands to be processed. This makes it safe for use in production environments.
  • Incremental iteration: By returning only a subset of elements per call, SCAN enables applications to process data in manageable chunks, reducing memory and CPU pressure.
  • Supports filtering: The MATCH option allows pattern-based filtering of keys or elements during iteration, improving efficiency when searching within large datasets.
  • Data type coverage: Specialized variants like SSCAN, HSCAN, and ZSCAN bring SCAN functionality to sets, hashes, and sorted sets, making it broadly applicable.
  • Safe to interrupt: Since scan state is maintained client-side, iterations can be stopped or resumed without affecting Redis server state.

Cons

  • No snapshot consistency: SCAN does not provide a consistent view of the dataset. Keys can be missed or duplicated if modified during the scan.
  • Unpredictable results: Returned elements per call may vary, even with a specified COUNT, depending on the internal data layout and key distribution.
  • Duplicates possible: Keys may appear more than once in a full iteration. Applications must handle and deduplicate results if needed.
  • MATCH filtering is post-scan: The MATCH pattern is applied after the scan step, so some calls may return no matches even if matching elements exist.
  • Requires client-side state: The client is responsible for managing cursor values and tracking scan progress, adding complexity to implementation.

Best Practices for Using Redis SCAN Effectively 

1. Understand When You Need To Iterate Until Cursor = 0

SCAN is a cursor-based iterator, not a one-shot command. Each SCAN call returns a new cursor along with a partial result set. The iteration is only complete when the returned cursor is back to 0, as SCAN does not guarantee all matches will appear in a single call or even in a fixed number of calls.

2. Combine MATCH And COUNT Wisely

The MATCH and COUNT options allow you to optimize scan efficiency by filtering results and controlling batch size. Using MATCH allows applications to focus on relevant keys, reducing the total data processed and transferred. However, overly broad patterns can still yield large result sets, so patterns should be as specific as possible without being too restrictive.

COUNT serves as a performance tuning lever. A high COUNT value can reduce the total number of network round trips but increases the load per call and may spike latency. A lower COUNT spreads the scan across more iterations, lowering per-call impact but increasing overall operation duration. Choose MATCH and COUNT combinations that match your performance and consistency requirements for both server and client.

3. Monitor Latency And Throughput

When integrating SCAN operations into production workflows, consistently measure their impact on server latency and throughput. Large COUNT values or repeated SCAN operations during busy periods can degrade performance for other clients, leading to latency spikes or even dropped connections. It’s important to observe how your settings affect the actual response time and system load during real usage scenarios.

Instrument your application and Redis itself with monitoring to capture trends and identify anomalies. Review metrics such as average scan time, memory spikes, and client-side processing delays. Use this data to adjust SCAN parameters dynamically or schedule scans during off-peak times, ensuring ongoing reliability and user experience.

Learn more in our detailed guide to Redis latency.

4. Avoid Scanning Production Keyspace During Peak Load

Running SCAN operations against the production keyspace during peak traffic periods can impact latency for other clients and risk timeouts or degraded responses. Although SCAN is non-blocking, it still consumes CPU and memory resources, and aggressive scanning can stress a heavily loaded server. Plan scan operations during maintenance windows or periods of low activity whenever possible.

If you must scan in a live environment, use conservative COUNT values and narrowly tailored MATCH patterns to minimize server impact. Consider rate limiting or throttling your iteration loops, especially if scans are part of automated scripts. This cautious approach helps preserve system stability and ensures SCAN-based tasks do not disrupt mission-critical operations.


Dragonfly: Next-Gen In-Memory Data Store with Limitless Scalability

Dragonfly is a modern, source-available, multi-threaded, Redis-compatible in-memory data store that stands out by delivering unmatched performance and efficiency. Designed from the ground up to disrupt legacy technologies, Dragonfly redefines what an in-memory data store can achieve.

Dragonfly Scales Both Vertically and Horizontally

Dragonfly’s architecture allows a single instance to fully utilize a modern multi-core server, handling up to millions of requests per second (RPS) and 1TB of in-memory data. This high vertical scalability often eliminates the need for clustering—unlike Redis, which typically requires a cluster even on a powerful single server (premature horizontal scaling). As a result, Dragonfly significantly reduces operational overhead while delivering superior performance.

For workloads that exceed even these limits, Dragonfly offers a horizontal scaling solution: Dragonfly Swarm. Swarm seamlessly extends Dragonfly’s capabilities to handle 100 million+ RPS and 100 TB+ of memory capacity, providing a path for massive growth.

Key Advancements of Dragonfly

  • Multi-Threaded Architecture: Efficiently leverages modern multi-core processors to maximize throughput and minimize latency.
  • Unmatched Performance: Achieves 25x better performance than Redis, ensuring your applications run with extremely high throughput and consistent latency.
  • Cost Efficiency: Reduces hardware and operational costs without sacrificing performance, making it an ideal choice for budget-conscious enterprises.
  • Redis API Compatibility: Offers seamless integration with existing applications and frameworks running on Redis while overcoming its limitations.
  • Innovative Design: Built to scale vertically and horizontally, providing a robust solution for rapidly growing data needs.

Dragonfly Cloud

Dragonfly Cloud is a fully managed service from the creators of Dragonfly, handling all operations and delivering effortless scaling so you can focus on what matters without worrying about in-memory data infrastructure anymore.

Was this content helpful?

Help us improve by giving us your feedback.

Switch & save up to 80%

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost