Back

Rails, Load Balancers and permanent Health Check URL

added on :: 29 September 2014

Load  Balancers has this tendency to do health checks now and then. With Amazon EC2 Load Balancers it is set at default for once every 30 second with a Timeout at 5 seconds. If the check fails few times, there goes the whole site. Load Balancers goes in to out of service and there goes the site with it.


So it is best to have a permanently a available URL to make sure all is good. So best is to keep this URL away from the Rails app. Also if you have SSL it is a challenge trying to make the site available regardless of the SSL status.  Rack comes to the rescue.


Also this is the solution to rid of OpsWork Load Balancer out of service message.


Firstly create a "middleware" directory in the APP folder.

Then create a file "loadbalencertest.rb" or call it anything you like




class Loadbalencertest
  def initialize(app)
    @app = app
  end

  def call(env)
    if env["PATH_INFO"] == "/loadbalencertest"
     [200, {"Content-Type" => "text/html"}, "Hello, World!"]
    #  [200, {"Content-Type" => "appication/json"}, [terms.to_json]]
    else
      @app.call(env)
    end
  end

end



That would give http ok for for that URL.

Also edit the "application.rb" for to add the "config.middleware.insert_before 0, "Loadbalencertest" to include that URL to the application and beofer the request hits the Application Controller

application.rb
 
require File.expand_path('../boot', __FILE__)

 
require 'rails/all'
 
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Mysite
  class Application < Rails::Application
 
    config.active_record.raise_in_transactional_callbacks = true
    config.middleware.insert_before 0, "Loadbalencertest"
  end
end



Then at the health check URL add
"/loadbalencertest"
Back