title: Ruby on Rails with IMAP IDLE for multiple accounts
body: <p>I'm currently building a Ruby on Rails app that allows users to sign in via Gmail and it have a constant IDLE connection to their Inbox. Emails need to arrive in the app as soon as they come into their Gmail Inbox.</p>
  
  <p>Currently I have the following in terms of implementation, and some issues that I really need some help figuring out.</p>
  
  <p>At the moment, when the Rails app boots up, it creates a thread per user which authenticates and runs in a loop to keep the IDLE connection alive.</p>
  
  <p>Every 10-15 minutes, the thread will "bounce IDLE", so that a little data is transferred to make sure the IDLE connection stays alive.</p>
  
  <p>The major issue I think is in terms of scalability and how many connections the app has to Postgres. It seems that each thread requires a connection to Postgres, this will be heavily limited on Heroku by the number of max connections (20 for basic and 500 for any plans after that).</p>
  
  <p>I really need help with the following:</p>
  
  <ul>
  <li>What's the best way to keep all these IDLE connections alive, but reducing the number of threads and connections needed to the database?
  
  <ul>
  <li>Note: user token refresh may happen if the refresh token to Gmail runs out, so this requires access to the database</li>
  </ul></li>
  <li>Are there any other suggestions for how this may be implemented?</li>
  </ul>
  
  <p>EDIT:</p>
  
  <p>I have implemented something similar to the OP in this question: <a href="https://stackoverflow.com/questions/5604480/ruby-imap-idle-concurrency-how-to-tackle?rq=1">Ruby IMAP IDLE concurrency - how to tackle?</a></p>