Scheduling Heroku Free Node Downtime

My current company takes advantage of Heroku’s free nodes for running non-production environment applications. Recently we ran into an issue where nodes where not reliably sleeping for the required six hours. I put together a small Rake file we use with the Heroku Scheduler to ensure apps sleep during the night.

Setup:

First off, add the Heroku Platform API gem to your Gemfile:

gem 'platform-api'

Install:

$ bundle install

Now create a Rake file:

# lib/tasks/heroku.rake

require 'platform-api'

namespace :heroku do
  def conn
    @conn ||= PlatformAPI.connect_oauth(ENV['HEROKU_API_KEY'])
  end

  def scale_to(count)
    %w{web worker}.each do |type|
      conn.formation.update(ENV['HEROKU_APP_NAME'], type, 'quantity' => count)
    end 
  end

  desc 'shut down nodes for mandatory downtime'
  task :shutdown do
    scale_to(0)
  end

  desc 'start nodes back up'
  task :startup do
    scale_to(1)
  end
end

You’ll need to set a couple of environment variables locally and in each Heroku application environment you want to bring up and down:

  • HEROKU_APP_NAME – The name of the application as listed in Heroku.
  • HEROKU_API_KEY – Your Heroku API key. You can generate a key with the following command:
$ heroku auth:token

 

Check your code in and deploy it to Heroku. Next, log into Heroku.

Configure Scheduler:
If you don’t have the Heroku Scheduler Add-on enabled, add it to the application.

Shutdown: Click the Scheduler Add-on, and click the ‘Add new job’ button to add a shutdown task:

$ rake heroku:shutdown

Select ‘Daily’ for the frequency. Select the time (UTC) that you’d like your application to go offline. Click the ‘Save’ button to save the job.

Startup: In the Scheduler view, click the ‘Add new job’ button to add a startup task:

$ rake heroku:startup

Select ‘Daily’ for the frequency. Select the time (UTC) that you’d like your application to come back online (Heroku free nodes require six hours of downtime). Click the ‘Save’ button to save the job.

That’s it. Now you can run your non-production application environments on free nodes an insure it’s available when you need it to be.

This entry was posted in dev ops, Heroku, ruby, sys admin. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *