Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Redis: SCAN vs KEYS in production — how bad is KEYS really?

clock icon

asked 1 month ago

message icon

1

eye icon

509

I need to find all keys matching session:* to expire them. KEYS session:* works instantly on my laptop with a few hundred keys. Production has around 8 million. How much trouble am I in?

1 Answer

A lot — Redis is single threaded, so KEYS blocks every other client for the whole scan. At 8 million keys that is comfortably into multi-second territory, and everything else queues behind it.

Use SCAN, which returns a cursor and does bounded work per call:

1let cursor = "0"
2do {
3 const [next, keys] = await redis.scan(cursor, "MATCH", "session:*", "COUNT", 500)
4 cursor = next
5 if (keys.length) await redis.unlink(...keys)
6} while (cursor !== "0")
1let cursor = "0"
2do {
3 const [next, keys] = await redis.scan(cursor, "MATCH", "session:*", "COUNT", 500)
4 cursor = next
5 if (keys.length) await redis.unlink(...keys)
6} while (cursor !== "0")

Note UNLINK rather than DEL — it frees memory on a background thread instead of blocking.

Better still, don't scan at all: set a TTL when you create the session and let Redis expire them for you.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions