Skip to content

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.

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 to each and yields strings. env is a hash of CGI-style keys plus Rack’s own rack.* namespace. Middleware wraps another Rack app, modifying env before call or the response after. config.ru builds the stack; Puma parses HTTP and calls it.

class HelloApp
def call(env)
[200, { "content-type" => "text/plain" }, ["Hello, world\n"]]
end
end

Three 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.

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 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]
end
end
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 is the Rackup file: run sets the app, use pushes middleware.

require_relative "app/hello_app"
use Rack::CommonLogger
use Rack::Deflater
use RequestTimer
run HelloApp.new
Terminal window
rackup # uses config.ru, boots the default server
puma config.ru # same file, Puma explicitly

In Rails, config.ru is two lines because Rails.application is a Rack app:

require_relative "config/environment"
run Rails.application

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"

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.

  1. Why must the body respond to each rather than be a string?
  2. What does Rack::Builder add over manual wrapping?
  3. Where does a Rails middleware sit relative to the router?
  4. How would you stream a large CSV without buffering it?
  5. What changed in Rack 3 regarding headers and bodies?
  • 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"].rewind after reading the body in middleware.
  • Assuming middleware runs only before the response. Code after @app.call runs on the way out.
  • Buffering a stream. Build an enumerator-backed body instead of joining strings.