skip to content

Middleware Stack & Dispatch

Each request enters through config.ru, passes Rails.application's Rack middleware stack, and reaches controller#action through the router. Interviewers probe the stack order and how to change it.

part ofRuby on Railsread it →
on this pageshow

explore

questions

4

In a Rails 8.1 app, what path does an HTTP request take from config.ru to a controller action?

level: juniorimportance: must knowfreq 62%

answer

  1. config.ru runs one object
  2. Rails.application answers call(env)
  3. middleware first, router innermost
  4. "parcels" becomes ParcelsController
  5. new controller instance per request

basics

~20 s

The Rack server loads config.ru, which boots the app and runs Rails.application. Its call(env) sends the request down the middleware stack to the router, which matches a route and dispatches to a new controller instance's action.

solid answer

~40 s

The generated `config.ru` requires `config/environment` (which boots the app) and does `run Rails.application`, so the Rack server calls `Rails.application.call(env)` for every request. That object holds a middleware stack built once at boot, with `Rails.application.routes` as its innermost app. Each middleware wraps the next: executor, logging, request id, cookies, session and flash run on the way in, ETags and 304s on the way out. The router matches verb and path, fills `path_parameters` such as `{controller: "parcels", action: "show", id: "42"}`, constantizes `ParcelsController` and calls `ParcelsController.dispatch(:show, request, response)`. That creates a **fresh controller instance**, runs `process(:show)` with its callbacks, and returns the Rack triple `[status, headers, body]` back up the stack. In Rails 8.1 a route that points to a missing controller answers 500, not 404.

code

ruby · 5 lines
ruby
# config.ru (as generated by rails new in 8.1)
require_relative "config/environment"

run Rails.application
Rails.application.load_server

go deeper

for a junior

Recall the chain in order: config.ru runs Rails.application, middleware wraps the request, the router picks controller and action, a new controller instance runs the action and returns status, headers and body.

for a middle

Explain the mechanics: the stack is built once at boot, path_parameters name the controller, request.controller_class constantizes it, dispatch creates a fresh instance and process runs callbacks and the action.

for a senior

Show where things can stop early and why it matters: Static and HostAuthorization answer above the router, X-Cascade 404s become RoutingError, and a missing controller is a 500 to report in 8.1.

for a principal

Use the request path to reason about where cross-cutting work belongs: Rack middleware for every request, controller-level use or callbacks for one controller, and what each placement costs in per-request work.

## The entry point: config.ru A Rails app is a **Rack application**: an object with a `call(env)` method that takes the request environment Hash and returns a status, headers and a body. The Rack server (Puma, which a new Rails 8.1 app's Gemfile includes) finds the app by reading `config.ru` at the project root. The generated file does three things: 1. `require_relative "config/environment"` loads `config/application.rb`, which defines the application class, and then calls `Rails.application.initialize!`, which runs the initializers and **builds the middleware stack once**. 2. `run Rails.application` hands that booted object to the server as the app to call for every request. 3. `Rails.application.load_server` runs any `server` blocks that railties registered for code that should only run under a web server. `bin/rails server` starts the same thing through `Rails::Server`, a subclass of `Rackup::Server`, so the entry point is identical whether you type `bin/rails server` or start the server binary yourself. ## Rails.application is the Rack app `Rails.application` is the single instance of the class in `config/application.rb`, for example `ParcelTrack::Application < Rails::Application`. Its `call(env)`: - wraps `env` in an `ActionDispatch::Request` and records `ORIGINAL_FULLPATH` and `ORIGINAL_SCRIPT_NAME` in it; - passes `env` to the **built app**: the middleware stack, with the router as the innermost endpoint. Nothing is rebuilt per request. The stack is a chain of middleware objects created at boot, each holding a reference to the next. ## Down through the middleware stack `bin/rails middleware` prints the stack top first. Each entry wraps everything below it, so it can act before the request goes in and after the response comes out: - **On the way in:** `ActionDispatch::Executor` opens a unit of work, `ActionDispatch::RequestId` assigns `X-Request-Id`, `Rails::Rack::Logger` writes the `Started GET` line, `ActionDispatch::Cookies`, the session store and `ActionDispatch::Flash` load state. - **On the way out:** `Rack::ETag` computes an ETag and `Rack::ConditionalGet` turns a matching request into a 304. - **Short-circuits:** any middleware may answer by itself. `ActionDispatch::Static` serves a file from `public/` and `ActionDispatch::HostAuthorization` rejects a blocked host; in both cases the router never runs. ## The router as the innermost app The innermost app is `Rails.application.routes`, an `ActionDispatch::Routing::RouteSet`. Its `call` normalizes the path and asks its Journey router for the first route whose verb, path and constraints match. Matching fills `request.path_parameters`. With `resources :parcels`, `GET /parcels/42` yields `{controller: "parcels", action: "show", id: "42"}`. ## From route to action 1. The route's dispatcher calls `request.controller_class`, which turns `"parcels"` into `"ParcelsController"` and constantizes it; in development Zeitwerk autoloads `app/controllers/parcels_controller.rb` on that first reference. 2. `ParcelsController.make_response!` builds an `ActionDispatch::Response` tied to the request. 3. `ParcelsController.dispatch(:show, request, response)` runs any controller-level middleware registered with `use` in the controller, then creates a **new controller instance** for this request. 4. The instance's `process(:show)` runs the `before_action` callbacks, the action, the implicit render and the `after_action` callbacks. 5. `dispatch` commits the flash and returns `to_a`, the `[status, headers, body]` triple, which travels back up through every middleware to the server. Because each request gets its own controller object, instance variables such as `@parcel` never leak between requests or threads. Class-level state, by contrast, is shared by every thread in the process. ## When dispatch does not reach an action | Situation | What happens | |---|---| | No route matches | Journey returns 404 with `X-Cascade: pass`; `ActionDispatch::DebugExceptions` raises `ActionController::RoutingError` ("No route matches [GET] ...") | | Route names a controller class that does not exist | `ActionDispatch::MissingController`, a `NameError`, propagates; Rails 8.1 answers **500** (earlier versions answered 404) | | The action raises | The exception climbs back up the stack to `ActionDispatch::DebugExceptions` and `ActionDispatch::ShowExceptions` | The 8.1 change reflects that a route to a missing controller is a programming error to report, not a URL the client got wrong. ## Seeing the path for yourself Three checks make the chain visible without reading framework code: - `bin/rails middleware` prints every layer the request crosses, ending with `run ParcelTrack::Application.routes`. - `bin/rails routes -c ParcelsController` prints the routes that dispatch to `ParcelsController`, with verb, path and `controller#action`. - In `bin/rails console`, `Rails.application.call(Rack::MockRequest.env_for("/parcels/42"))` returns the same `[status, headers, body]` triple the server would receive, because the application object is an ordinary Rack app. Knowing the order also tells you where to look when something is missing: a header added by middleware is absent on a response that a higher middleware produced on its own, and a callback in the controller never runs for a request that the router did not match.

  • In Rails 8.1, what does a request get when its route points to a controller class that does not exist?
    A 500. `request.controller_class` raises `ActionDispatch::MissingController`, which is a `NameError`, not an `ActionController::RoutingError`, so the route's dispatcher does not turn it into a cascading 404. The error propagates up the stack and is reported like any other bug. Before Rails 8.1 the same mistake answered 404.
  • In a Rails app, what happens when no route matches the request at all?
    The Journey router returns a 404 with an `X-Cascade: pass` header. On the way back up, `ActionDispatch::DebugExceptions` sees that header and raises `ActionController::RoutingError` with "No route matches [GET] ...", which the exception middleware then renders as the debug page locally or as a 404 page in production.
  • In Rails, can you get a Rack endpoint for one controller action without going through the router?
    Yes. `ParcelsController.action(:show)` returns a Rack app: a lambda that builds an `ActionDispatch::Request`, makes a response and dispatches the action on a new controller instance, wrapped in that controller's own middleware if it declared any with `use`. It skips the application middleware stack, so cookies, session and the executor are not set up for it.

  • A Rails controller instance is created at boot and reused for every request.
  • config.ru runs Rails.application.routes, so the middleware stack is skipped.
  • before_action callbacks are entries in the Rack middleware stack.
  • Rails rebuilds the middleware stack for every incoming request.
  • In Rails 8.1 a route to a missing controller still answers 404.

Assumes Rails 8.1; since 8.1.0 a route whose controller class does not exist answers 500 instead of 404.

open as a page

In a Rails 8.1 app, what does bin/rails middleware print, and why does the order of the default stack matter?

level: middleimportance: must knowfreq 45%

basics

~20 s

bin/rails middleware prints the built stack for the current environment, outermost first, ending with run App.routes. Order matters because each middleware wraps everything below it: it decides what runs before it, what it can short-circuit and which exceptions it catches.

open as a page

In Rails 8.1, what do ActionDispatch::Executor and ActionDispatch::Reloader do for each request, and when must you wrap code yourself?

level: seniorimportance: should knowfreq 30%

basics

~20 s

ActionDispatch::Executor wraps every request in the app's executor, whose callbacks enable the query cache, release database connections and reset Current attributes. ActionDispatch::Reloader, present only when reloading is on, reloads changed code first. Threads you start need Rails.application.executor.wrap.

open as a page

In a Rails 8.1 parcel-tracking app, how would you insert a request-timing middleware ahead of the session store, and what can break?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Call config.middleware.insert_before ActionDispatch::Session::CookieStore, ParcelTimer in config/application.rb and confirm with bin/rails middleware. It breaks when the anchor class is absent in some environment (boot fails), when you edit the stack after boot, or when a reloadable class goes stale.

open as a page