Redis Tips & Tricks #2 - Connections

As it turns out, connecting to redis may introduce a bit of problem if you're not aware of the conection handling.

I haven't tried with every client out there but especially the redis ruby client has this problem.

So imagine this scenario:

(1..10000).each{|num| Redis.connect.get("key_#{num}")}

Every iteration will open a new file handle and will keep it open (I have not been waiting forever but I have seen open files for more than 24 hours).

Try this on a ruby console and monitor the open files with:

 watch -n1 "lsof -p <PID> | grep <REDIS_PORT>"

Of course it's easy to fix in the example above but imagine you are writing a threaded program that accesses redis (e.g. Sidekiq worker).

In that case you want to implement a connection pool.

So be careful when spawning redis connections.