Video in progress

Why shouldn't you use KEYS * on a production Redis, and what do you use instead?

KEYS walks through all the keys in one go, and during that time Redis answers nobody else. Use SCAN instead: it returns keys in small batches, using a cursor.

📖 Answer

On a database with a few million keys, KEYS user:* can run for several seconds. Since Redis is single-threaded, the whole application "freezes" during that time: timeouts, 500 errors.

With SCAN:

SCAN 0 MATCH user:* COUNT 500
1) "17408"        # the next cursor
2) 1) "user:12"
   2) "user:98"

You keep going until the cursor comes back as 0. In Java:

var opts = ScanOptions.scanOptions().match("user:*").count(500).build();
try (Cursor<String> c = redis.scan(opts)) {
    c.forEachRemaining(key -> System.out.println(key));
}

Good to know: SCAN may return the same key twice, and it may miss keys that were added while the iteration was running. Many teams disable KEYS and FLUSHALL entirely in prod with rename-command or ACLs.