How to use Heroku efficiently
I love Heroku. It's amazing for hosting Rails apps and it takes away a huge amount of the sysadmin headaches. The uptime is incredible, the support is great - but there is one drawback. It can get expensive.
If your Rails app has tasks that you want to run in the background - and this is an extremely common use case - then out of the box you need to have an instance of a Worker running, which costs you money for each second it's up whether it's active or not.
Sometimes, you only need a Worker to run for a couple of minutes each day (if you have a simple daily cron job that needs to be run, for instance), but Heroku's standard setup means that you'd always need to have that Worker running. Clearly, that's pretty wasteful.
This is where the Workless gem comes in. Once you add the gem (along with Delayed Job) you can set it so that it'll spin up a Worker only when a background task is executed. When the delayed job queue is empty, it spins your worker back down until it's needed again.
Here's how quick and painless it was to get Workless running on Submarine (this works for any app that's on Rails 3.x).
Step 1: Add the delayed job active record and workless gems to your gemfile:
gem "delayed_job_active_record" gem "workless", "~> 1.1.3"
Step 2: Get your Heroku API key by going to your Account page and clicking "Show API Key".
Step 3: Add your API key to your Heroku config by adding this in a terminal:
heroku config:add HEROKU_API_KEY=yourapikey APP_NAME=yourappname
Run bundle, and that's it. If you want to offload tasks to the background, you can start using Delayed Job if you don't use it already (details on this Github page or in this Railscasts episode), and you can also start using Heroku scheduler to get rake tasks running at set time intervals in the background without having a Worker active all the time.
Published March, 2014