Upstash Documentation

SCAN

Incrementally iterate keys.
3 min read

Use SCAN to walk through the keys of the database incrementally, a batch at a time.

Each call takes a cursor and returns the next cursor together with a batch of keys. Start with cursor 0 and keep calling with the cursor from the previous reply until the server returns 0 again, which marks the end of the iteration. Because the work is split over many short calls, SCAN never blocks the server the way KEYS can on a large keyspace.

MATCH filters the returned keys with a glob-style pattern, COUNT hints at how much work each call should do (a hint about effort, not a page size, so batches vary in length), and TYPE limits the reply to keys of one type. Filtering is applied after a batch has been read, so a call can legitimately return no keys at all while the cursor is still non-zero: only the cursor tells you when the iteration is over.

The guarantee is that every key present for the whole iteration is returned at least once. Keys added or removed while the scan runs may or may not show up, and a key can be returned more than once, so make the processing of each key idempotent. HSCAN, SSCAN, and ZSCAN apply the same mechanism inside a single collection.

Syntax#

Arguments#

ArgumentRequiredRepeatableDescription
<cursor>YesNoCursor returned by the previous call; start at 0.
MATCH <pattern>NoNoReturn only elements matching this glob-style pattern.
COUNT <count>NoNoHint for how much work each iteration should do.
TYPE <type>NoNoReturn only keys of this type, such as string, list, or hash.

Important points#

  • This operation can inspect a large part of the database. Prefer cursor-based scans where possible and avoid unbounded use on hot paths.
  • The cursor is opaque. Start with 0 and continue until the server returns cursor 0; a single iteration may return no elements.

Response#

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

ProtocolReply
RESP2Two-element array: cursor and array of bulk-string keys
RESP3Two-element array: cursor and array of bulk-string keys
Note

Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.

Examples#

TCP examples use the TLS REDIS_URL from the Upstash console. REST examples use UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN.

Redis CLI
@upstash/redis
upstash_redis
ioredis
node-redis
redis-py
go-redis
jedis
redis-rs