CodePark/ questions / What Redis is & how it works
START PRACTICINGPRACTICE
Backend question · Redis & caching › What Redis is & how it works

How does SCAN work, and what guarantees does it give (and not give)?

SCAN 0 MATCH user:* COUNT 100
1) "17408"
2) 1) "user:42"
   2) "user:7"
SCAN 17408 MATCH user:* COUNT 100
...repeat until the returned cursor is "0"

SCAN goes through the keys in small steps, using a cursor. A cursor is a number that marks where the scan is. Each call does only a little work, so other clients are not blocked.

How it works:

  • Start with cursor 0.
  • Each call returns a new cursor and a batch of keys.
  • Pass the new cursor to the next call.
  • The scan is finished when the server returns cursor 0 again.

Options:

  • COUNT is only a hint about how much work to do in each call. It is not an exact page size.
  • MATCH filters keys after Redis fetches them. So one call can return few keys, or none, even though the scan is not finished.

What it guarantees:

  • A key that exists for the whole scan is always returned.

What it does not guarantee:

  • A key may be returned more than once, so the client must remove duplicates.
  • A key added or removed during the scan may or may not appear.

SSCAN, HSCAN and ZSCAN work the same way, for the members of a set, hash or sorted set.

  • The cursor starts at 0, and the scan ends when 0 comes back.
  • COUNT is only a hint and MATCH filters after fetching, so a page can be empty.
  • Keys that exist for the whole scan are returned at least once.
  • Duplicates are possible, so remove them in the client.
  • SSCAN, HSCAN and ZSCAN work the same way.