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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Rack middleware sits in the request chain and can short-circuit responses before they reach the app.
- 2A 503 with a Retry-After header tells clients and crawlers the outage is temporary, not permanent.
- 3Combining an env flag with a file toggle lets you flip maintenance mode without a deploy.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-rack-maintenance-mode-middleware-in-rails-explained-ruby-358a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.