Best practices for running Rails in production
Use an error reporting service like Rollbar.
gem 'rollbar'
Run:
rails generate rollbar
And add the following to your environment.
ROLLBAR_ACCESS_TOKEN=test123
Use Rack Timeout.
gem 'rack-timeout', '>= 0.1.0beta3'
Add the following to config/initializers/timeout.rb
.
Rack::Timeout.timeout = ENV["RACK_TIMEOUT"] || 5
Rack::Timeout.unregister_state_change_observer(:logger)
# hack to bubble timeout errors
module ActionView
class Template
def handle_render_error_with_timeout(view, e)
raise e if e.is_a?(Rack::Timeout::Error)
handle_render_error_without_timeout(view, e)
end
alias_method_chain :handle_render_error, :timeout
end
end
Show a custom error page for timeouts. Add the following to app/controllers/application_controller.rb
.
# from https://github.com/heroku/rack-timeout/issues/40#issuecomment-51865104
rescue_from Rack::Timeout::Error, with: :handle_request_timeout
private
def handle_request_timeout(e)
Rollbar.report_exception(e)
respond_to do |format|
format.html { render file: Rails.root.join("public/503.html"), status: 503, layout: nil }
format.all { head 503 }
end
end
And create a public/503.html
.
Use Lograge.
gem 'lograge'
Add the following to config/environments/production.rb
.
config.lograge.enabled = true
config.lograge.custom_options = lambda do |event|
event.payload.slice(:user_id, :visit_id)
end
Add the following to app/controllers/application_controller.rb
.
def append_info_to_payload(payload)
super
payload[:user_id] = current_user.id if current_user
payload[:visit_id] = ahoy.visit_id # if you use Ahoy
end
Use an uptime monitoring service like Pingdom or Uptime Robot.
Monitor web servers, background jobs, and scheduled tasks.
Use a performance monitoring service like New Relic or AppSignal.
Use a high performance web server like Unicorn.
gem 'unicorn'
Use SSL to protect your users. Add the following to config/environments/production.rb
.
config.force_ssl = true