Search code examples
bashredisnode-redisredis-cli

Best way to delete multiple keys with wildcard in redis-cli


I want to run a bash script from node.js to remove all session keys from redis every time the server restarts. I have read somewhere that Keys shouldn't be used to delete multiple keys with a pattern because it would subject the server to security risks like DoS. Would this bash script a safer way to delete keys? Does xargs -L 1000 mean in each loop it will delete 1000 keys? Am I understanding it correctly?

#!/bin/bash
redis-cli --scan --pattern "SESSION:*" | xargs -L 1000 redis-cli del

I took the comman line from HERE.


Solution

  • I have read somewhere that Keys shouldn't be used to delete multiple keys with a pattern because it would subject the server to security risks like DoS.

    Not security, just denial of service while KEYS is running because it is blocking (and rarely an OOM scenario if the reply is too big).

    Would this bash script a safer way to delete keys?

    I would say politer instead of safer - this one liner will allow other requests to be served between SCANs instead of blocking the server for the duration.

    Does xargs -L 1000 mean in each loop it will delete 1000 keys?

    It means that every DEL will have up to 1000 keys, depending on the scan's results.

    I want to run a bash script from node.js to remove all session keys from redis every time the server restarts.

    If your Redis instance is used solely for storing the sessions, you can consider FLUSHALL. Alternatively, if (and you should) every session key has a TTL, you can just use a per-server-restart prefix for your sessions and let older session expire naturally.