AbstractBrain Answers About us

Rails maintenance mode

Question

Is it possible to activate a maintenance mode in a Rails application?

Basically we need to stop the requests and display a maintenance page while we perform some updates on the database.

Answer

There isn’t a built-in solution in Rails.

Some PaaS, like Heroku, offer their own solution (e.g. heroku maintenance:on).

Otherwise it is simple to implement a maintenance page directly in Rails.

Add this code to the ApplicationController:

before_action :check_maintenance_mode

private

def check_maintenance_mode
  if ENV['MAINTENANCE_MODE']
    respond_to do |format|
      format.html { render file: 'public/503.html', status: :service_unavailable, layout: false }
      format.json { render json: { status: 503, error: 'Service Unavailable' }, status: :service_unavailable }
      format.all { head :service_unavailable }
    end
  end
end

Finally create your maintenance page (public/503.html).

When you need to perform maintenance (e.g. on the database) you can set the MAINTENANCE_MODE env variable to true: all the requests will return a 503 status code and the custom maintenance page.

Also remember to scale down to zero all the background workers and temporary remove the cron jobs during maintenance.