ruby 49 lines · 8 steps

A Rack maintenance-mode middleware in Rails

A middleware that intercepts requests and serves a 503 page while an app is under maintenance, with IP bypass.

Explained by highlit
1module Rack
2 class MaintenanceMode
3 RETRY_AFTER = 3600
4 
5 def initialize(app, flag_path: Rails.root.join("tmp", "maintenance.txt"))
6 @app = app
7 @flag_path = flag_path
8 end
9 
10 def call(env)
11 return @app.call(env) unless maintenance_enabled?
12 
13 request = Rack::Request.new(env)
14 return @app.call(env) if bypass?(request)
15 
16 [
17 503,
18 {
19 "Content-Type" => "text/html; charset=utf-8",
20 "Retry-After" => RETRY_AFTER.to_s,
21 "Cache-Control" => "no-store"
22 },
23 [page_body]
24 ]
25 end
26 
27 private
28 
29 def maintenance_enabled?
30 ENV["MAINTENANCE_MODE"] == "1" || File.exist?(@flag_path)
31 end
32 
33 def bypass?(request)
34 allowed = ENV.fetch("MAINTENANCE_ALLOW_IPS", "").split(",").map(&:strip)
35 allowed.include?(request.ip)
36 end
37 
38 def page_body
39 @page_body ||= File.read(Rails.public_path.join("maintenance.html"))
40 rescue Errno::ENOENT
41 "<h1>We\u2019ll be back shortly</h1>"
42 end
43 end
44end
45 
46Rails.application.config.middleware.insert_before(
47 Rack::Runtime,
48 Rack::MaintenanceMode
49)
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Rack middleware sits in the request chain and can short-circuit responses before they reach the app.
  2. 2A 503 with a Retry-After header tells clients and crawlers the outage is temporary, not permanent.
  3. 3Combining an env flag with a file toggle lets you flip maintenance mode without a deploy.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A Rack maintenance-mode middleware in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code