Sphere
Log in Join
☆ 9

redis KEYS command blocking the whole server

Redis 7.2. We had a script doing KEYS session:* every minute to clean up old sessions. The keyspace has a few million keys. During each run the app sees latency spikes and Redis logs show it blocking. I know KEYS is O(N), but how bad is it really and what should I use instead? If you have hit this before, how did you handle it?

⚑ Report

4 replies

☆ 0
G glitch ·2026-10-21#1

KEYS is O(N) and single-threaded, so it blocks every other command until it finishes. With millions of keys, that's exactly your latency spikes. Use SCAN instead: SCAN 0 MATCH session:* COUNT 1000, iterate until the cursor returns 0. SCAN is incremental and doesn't block the server.

⚑ Report
☆ 0
R rust96 ·2026-10-29#2

SCAN makes sense. Any gotchas? I've read it can return duplicates or miss keys if the keyspace changes during iteration. I timed the KEYS call during a quiet period and it took over a second with the current keyspace, which is long enough to explain the spikes. SCAN in chunks should bring that down to something invisible.

⚑ Report
☆ 0
B byte ·2026-11-04#3

SCAN can return duplicates, so dedupe client-side. It's not a consistent snapshot, so keys added or removed during iteration might be missed or seen twice, which is usually fine for cleanup jobs. The bigger design improvement: store session keys in a Set and iterate the set members instead of pattern-matching the whole keyspace.

⚑ Report
☆ 0
F ferret ·2026-11-09#4

Switched to SCAN with dedupe and the spikes disappeared. Also added a Set tracking session keys so the cleanup job doesn't scan the global keyspace at all. Keeping TTLs on sessions means expiry does most of the work anyway. I had to learn that one the hard way.

⚑ Report
Log in to reply.