skip to content

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%

answer

  1. config.middleware records, boot replays
  2. insert_before the session store class
  3. use appends at the bottom
  4. missing anchor fails the boot
  5. stack frozen after boot

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.

solid answer

~40 s

Write the middleware as a plain class in `lib/middleware/parcel_timer.rb`, `require` it in `config/application.rb`, and add `config.middleware.insert_before ActionDispatch::Session::CookieStore, ParcelTimer`. `config.middleware` is a recorder: Rails replays the calls onto the default stack when it builds it at boot, so the line can live in `application.rb`, an environment file or an initializer. Then check `bin/rails middleware`. What breaks: the anchor must exist in **every** environment, or boot raises `No such middleware to insert before`, the classic case being `ActionDispatch::Reloader`, which production does not have. Changing the session store changes the class name you anchor on. `use` appends below the session, too late; `swap` would replace the session store. After boot the stack is frozen, so later calls raise `FrozenError`, and a restart is needed for any change.

code

ruby · 14 lines
ruby
# lib/middleware/parcel_timer.rb
class ParcelTimer
  def initialize(app)
    @app = app
  end

  def call(env)
    started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    status, headers, body = @app.call(env)
    elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
    headers["x-parcel-timing"] = format("%.1fms", elapsed * 1000)
    [status, headers, body]
  end
end

go deeper

for a junior

Recall that config.middleware.use appends a middleware and that bin/rails middleware shows where it landed.

for a middle

Explain insert_before, insert_after, swap, delete and move_before, and pick the one that places a class exactly where the task needs it.

for a senior

Anticipate the failures: anchors missing in some environments, a configurable session store class, the frozen stack after boot, and a reloadable middleware class going stale.

for a principal

Decide whether the concern belongs in the global stack at all, or in controller-level use or callbacks, given that a global middleware runs on every request including static files.

## The goal and the placement The parcel-tracking app wants a header with how long the request took, including the session store's own work. In the default Rails 8.1 stack the session store, `ActionDispatch::Session::CookieStore`, sits below `ActionDispatch::Cookies` and above `ActionDispatch::Flash`. The store wraps the rest of the app: it attaches a lazily loaded session on the way in (the cookie is decoded on first read, wherever that happens) and commits the session after the inner app returns. To have that commit inside the measurement, the timer must wrap the session store, so it goes **directly before it**: ```ruby # config/application.rb require_relative "../lib/middleware/parcel_timer" module ParcelTrack class Application < Rails::Application config.middleware.insert_before ActionDispatch::Session::CookieStore, ParcelTimer end end ``` Then run `bin/rails middleware` and check that `use ParcelTimer` appears directly above the session store line. ## The editing API `config.middleware` offers these operations, all taking a middleware class (or an integer index) as the anchor: | Call | Effect | |---|---| | `use Klass, *args` | appends at the bottom, just above the router | | `insert_before anchor, Klass` | inserts directly above `anchor` (`insert` is an alias) | | `insert_after anchor, Klass` | inserts directly below `anchor` | | `unshift Klass` | puts it at the very top | | `swap anchor, Klass` | replaces `anchor` with `Klass` | | `delete anchor` / `delete! anchor` | removes it; `delete!` raises if it is absent | | `move_before` / `move_after target, source` | moves an existing entry | For this task `use` is wrong: the timer would land below the session store, so the store's commit on the way out would fall outside the measurement. `swap` is dangerous: it would remove the session store. `unshift` or `insert_before 0` would also measure the session, but would wrap host checks and static files too, which changes what the number means. ## How configuration becomes the stack `config.middleware` is a `Rails::Configuration::MiddlewareStackProxy`. It does not touch a stack; it **records** each call. During boot, the `build_middleware_stack` initializer builds the default stack, replays the recorded calls on it and builds the chain once: - inserts, `use`, `swap` and `unshift` are replayed first, and `delete` and the `move_*` calls after them, whatever order you wrote them in; - the anchor is looked up at replay time, in the stack of the environment that is booting; - after the build, the stack's list is frozen. ## What can break 1. **A missing anchor fails boot.** If the anchor is not in that environment's stack, replay raises `RuntimeError` with `No such middleware to insert before: ...`. `ActionDispatch::Reloader` is the usual trap: it exists only when reloading is enabled, so an anchor on it boots in development and fails in production. 2. **The session class is configuration.** `config.session_store :cache_store` makes the class `ActionDispatch::Session::CacheStore`, and an app with no cookie session has no session middleware at all. Anchoring on `ActionDispatch::Cookies` with `insert_after` would place the timer in the same spot without naming the store class. 3. **Edits after boot do not apply.** Once built, the stack is frozen: a call from an `after_initialize` block raises `FrozenError`, and editing the middleware file needs a server restart, because the stack is not rebuilt per request or on code reload. 4. **A reloadable class goes stale.** The stack holds the object created at boot, so the timer should be loaded with `require` from `lib/` and excluded from autoloading, not placed in `app/`. 5. **Measuring the right thing.** `Rack::Runtime` already adds `x-runtime`, and development has `ActionDispatch::ServerTiming`. A custom timer earns its place only if it measures something they do not. ## Verifying the change 1. Run `bin/rails middleware` and `RAILS_ENV=production bin/rails middleware`; both must boot and both must show the timer directly above the session store. 2. Add an integration test that requests a page and asserts the response carries the timing header, so a later stack change that drops or moves the timer fails a build. 3. Read the number against `x-runtime`: `Rack::Runtime` sits above the session store and so wraps the timer, which means the timer's value should be equal or smaller; the gap is the time spent in the layers between them. ## A narrower alternative If only one controller needs the behaviour, `use ParcelTimer, only: :show` inside `ParcelsController` wraps just that controller's actions. That runs after routing, below the whole application stack, so the session store's commit on the way out is outside it.

  • In Rails 8.1, why does config.middleware.insert_before ActionDispatch::Reloader, ParcelTimer boot in development but fail in production?
    `ActionDispatch::Reloader` is added to the default stack only when reloading is enabled, and the generated `production.rb` sets `config.enable_reloading = false`. When boot replays the recorded insert, the anchor lookup finds nothing and raises `No such middleware to insert before: ActionDispatch::Reloader`. Anchor on a middleware present in every environment instead.
  • In a Rails 8.1 app, what happens if config/application.rb calls config.middleware.delete Rack::Runtime and later config.middleware.insert_before Rack::Runtime, ParcelTimer?
    Boot succeeds and the timer ends up where `Rack::Runtime` was. The proxy replays inserts before deletes, regardless of source order, so the insert finds `Rack::Runtime` as its anchor and the delete removes `Rack::Runtime` afterwards.

  • config.middleware.use ParcelTimer puts it at the top of the stack.
  • config.middleware.swap adds the new middleware next to the old one.
  • Inserting before ActionDispatch::Reloader works the same in every environment.
  • Middleware added in an after_initialize block takes effect on the next request.
  • Code reloading in development picks up edits to the middleware class.