Rack
Rack is the seam between Ruby web servers and Ruby web frameworks. Its importance is disproportionate to its size: the entire specification fits on an index card, and it is why Rails, Sinatra, Hanami and Roda can all run on Puma, Falcon or WEBrick without knowing about each other.
The 60-second answer
Section titled “The 60-second answer”A Rack application is any object that responds to
call(env)and returns a three-element array: an integer status, a hash of headers with lowercase string keys, and a body that responds toeachand yields strings.envis a hash of CGI-style keys plus Rack’s ownrack.*namespace. Middleware wraps another Rack app, modifyingenvbeforecallor the response after.config.rubuilds the stack; Puma parses HTTP and calls it.
The interface
Section titled “The interface”class HelloApp def call(env) [200, { "content-type" => "text/plain" }, ["Hello, world\n"]] endendThree rules and that is the whole contract: respond to call with one argument, return exactly three
elements, and return a body that responds to each and yields strings. A lambda responds to call,
so ->(env) { [200, { "content-type" => "text/plain" }, ["ok"]] } is a valid app.
The env hash
Section titled “The env hash”| Key | Meaning |
|---|---|
REQUEST_METHOD |
GET, POST, … |
PATH_INFO / SCRIPT_NAME |
Path after the mount point / the mount prefix |
QUERY_STRING |
Raw query string, unparsed |
HTTP_* |
Request headers, upcased, dashes to underscores |
CONTENT_TYPE / CONTENT_LENGTH |
Special-cased, no HTTP_ prefix |
rack.input |
IO-like body stream (#read, #rewind) |
rack.url_scheme |
http or https |
rack.session, rack.logger |
Added by middleware |
Header normalisation is the detail people get wrong: Accept arrives as HTTP_ACCEPT, but
Content-Type and Content-Length are the exceptions. Rack 3 requires lowercase response header
names.
Middleware
Section titled “Middleware”Middleware is a decorator around a Rack app: it holds the next app and calls it.
class RequestTimer def initialize(app) = @app = app
def call(env) started = Process.clock_gettime(Process::CLOCK_MONOTONIC) status, headers, body = @app.call(env) headers["x-runtime"] = format("%.3f", Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) [status, headers, body] endend
app = RequestTimer.new(HelloApp.new)Composition is explicit and testable — each layer is a plain object you can call in isolation.
Rack::Builder gives the same thing a DSL. Built-ins: Rack::Static, Rack::Deflater,
Rack::ETag, Rack::Session::Cookie, Rack::CommonLogger, Rack::ShowExceptions.
config.ru
Section titled “config.ru”config.ru is the Rackup file: run sets the app, use pushes middleware.
require_relative "app/hello_app"
use Rack::CommonLoggeruse Rack::Deflateruse RequestTimer
run HelloApp.newrackup # uses config.ru, boots the default serverpuma config.ru # same file, Puma explicitlyIn Rails, config.ru is two lines because Rails.application is a Rack app:
require_relative "config/environment"run Rails.applicationWhy Rails runs on Rack
Section titled “Why Rails runs on Rack”ActionDispatch::Routing::RouteSet#call(env) is a Rack app: it inspects PATH_INFO and dispatches
to a controller. config.middleware.use pushes into the same stack, ActionDispatch::Request wraps
env, and ActionDispatch::Response becomes the three-element array. That is why you can mount any
Rack app inside Rails routes:
mount Sidekiq::Web => "/sidekiq"mount GrapeAPI => "/api"Puma and the server’s job
Section titled “Puma and the server’s job”The server owns the socket, parses HTTP into env, calls the app, and writes the response. Puma adds
threads (a pool per process, threads 5, 5), workers (workers 4 forks processes for CPU parallelism
around the GVL), preload_app! (load before forking so children share memory copy-on-write), and Rack
hijacking for WebSockets and streaming.
Falcon (fibers), WEBrick (threads, dev only) and Thin (EventMachine, legacy) implement the same contract; that interchangeability is the point of Rack.
Follow-up questions
Section titled “Follow-up questions”- Why must the body respond to
eachrather than be a string? - What does
Rack::Builderadd over manual wrapping? - Where does a Rails middleware sit relative to the router?
- How would you stream a large CSV without buffering it?
- What changed in Rack 3 regarding headers and bodies?
Common traps
Section titled “Common traps”- Symbol keys in headers. Rack 3 requires lowercase strings.
- Returning a string as the body. It does not respond to
each; wrap it in an array. - Forgetting
env["rack.input"].rewindafter reading the body in middleware. - Assuming middleware runs only before the response. Code after
@app.callruns on the way out. - Buffering a stream. Build an enumerator-backed body instead of joining strings.