title: python Redis Connections
body: <p>I am using Redis server with python.</p>
  
  <p>My application is multithreaded ( I use 20 - 32 threads per process) and I also
  I run the app in different machines.</p>
  
  <p>I have noticed that sometimes Redis cpu usage is 100% and Redis server became unresponsive/slow.</p>
  
  <p>I would like to use per application 1 Connection Pool of 4 connections in total.
  So for example, if I run my app in 20 machines at maximum, there should be 
  20*4 = 80 connections to the redis Server.</p>
  
  <pre><code>POOL = redis.ConnectionPool(max_connections=4, host='192.168.1.1', db=1, port=6379)
  R_SERVER = redis.Redis(connection_pool=POOL)
  
  class Worker(Thread):
  
      def __init__(self):
          self.start()
  
      def run(self):
          while True:
              key = R_SERVER.randomkey()
              if not key: break
              value = R_SERVER.get(key)
  
  
      def _do_something(self, value):
          # do something with value
          pass
  
  if __name__ = '__main__':
      num_threads = 20
      workers = [Worker() for _ in range(num_threads)]
      for w in workers:
         w.join()
  </code></pre>
  
  <p>The above code should run the 20 threads that get a connection from the connection pool of max size 4 when a command is executed.</p>
  
  <p>When the connection is released?</p>
  
  <p>According to this code (<a href="https://github.com/andymccurdy/redis-py/blob/master/redis/client.py" rel="nofollow">https://github.com/andymccurdy/redis-py/blob/master/redis/client.py</a>):</p>
  
  <pre><code>    #### COMMAND EXECUTION AND PROTOCOL PARSING ####
  def execute_command(self, *args, **options):
      "Execute a command and return a parsed response"
      pool = self.connection_pool
      command_name = args[0]
      connection = pool.get_connection(command_name, **options)
      try:
          connection.send_command(*args)
          return self.parse_response(connection, command_name, **options)
      except ConnectionError:
          connection.disconnect()
          connection.send_command(*args)
          return self.parse_response(connection, command_name, **options)
      finally:
          pool.release(connection)
  </code></pre>
  
  <p>After the execution of each command, the connection is released and gets back to the pool</p>
  
  <p>Can someone verify that I have understood the idea correct and the above example code will work as described?</p>
  
  <p>Because when I see the redis connections, there are always more than 4.</p>
  
  <p>EDIT: I just noticed in the code that the function has a return statement before the finally. What is the purpose of finally then?</p>