title: Unicorn and Rails eat up 2x MySQL connections
body: <p>I run 10 Unicorn workers for each server and they eat up all MySQL connections over time, ending up with "too many connections" error. It starts out with 10 connections, but gradually increase up to 20.</p>
  
  <p>When I run the following script on production (using <code>SHOW PROCESSLIST</code>), I can see that each IP (= app server) has 20 connections each, where it should be 10 - excatly double the number of Unicorn workers.</p>
  
  <pre><code>result = ActiveRecord::Base.connection.execute 'show processlist'
  result.group_by{|i| i[2].split(':').first }.map{|k,v| [k, v.size] }
   =&gt; [["192.168.1.2", 20], ["192.168.1.3", 20], ["192.168.1.4", 20], ... ]
  </code></pre>
  
  <p>Here's the database.yml</p>
  
  <pre><code>production:
    adapter: mysql2
    ...
    pool: 1
  </code></pre>
  
  <p>Here's the netstat:</p>
  
  <pre><code># netstat -an | grep :3306
  tcp        0      0 192.168.1.2:58535   192.168.1.123:3306    ESTABLISHED
  tcp        0      0 192.168.1.2:45021   192.168.1.123:3306    ESTABLISHED
  tcp        0      0 192.168.1.2:58537   192.168.1.123:3306    ESTABLISHED
  tcp        0      0 192.168.1.2:45119   192.168.1.123:3306    TIME_WAIT
  ...
  
  # netstat -an | grep :3306 | wc -l
  36
  # netstat -an | grep :3306 | grep ESTABLISHED | wc -l
  33
  </code></pre>
  
  <p>I'm worried that there's a few <code>TIME_WAIT</code> - it shouldn't be there as the connections should be all persistent - it seems that the worker has more connections than necessary. Plenty of free RAM, no swap / OOM.</p>
  
  <p>Ruby 2.0.0p0 / Rails 3.2.13</p>
  
  <p>What's causing this?</p>