Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

The Rails Request Cycle

Follow one HTTP request through Rack, middleware, the Rails router, a controller action and a view. Build a runnable Rack-style app with middleware in plain Ruby to see how the pieces connect.

When someone opens a page of your Rails app, a lot happens in a few milliseconds. Knowing the path of a request makes everything else easier to learn, because you always know which part of the framework to blame or to change. This lesson follows one request from the web server to the response.

The foundation is Rack, a tiny Ruby interface between web servers and Ruby apps. Rails sits on top of it. Because Rack is just a few lines of Ruby, we can build a runnable stand-in with middleware, a router and a controller, and then map it onto the real Rails parts. If you have seen Sinatra and Rack, some of this will be familiar.

The path of a request

A request comes in

Browser Sends GET /articles/1.
Web server Puma accepts the connection.
Rack Calls app.call(env).
1 / 3
sequenceDiagram
  participant B as Browser
  participant P as Puma
  participant M as Middleware stack
  participant R as Router
  participant C as Controller
  participant V as View
  B->>P: GET /articles/1
  P->>M: app.call(env)
  M->>R: request
  R->>C: ArticlesController#show
  C->>V: render show.html.erb
  V-->>C: HTML
  C-->>M: [200, headers, body]
  M-->>B: response

The request travels inward through the middleware stack, the response travels back out.

What Rack is

A Rack application is any Ruby object with a call method. It receives a hash called env (the request: path, method, headers) and returns an array of three things: a status code, a hash of headers, and a body that responds to each.

Ruby
# read-only: the smallest Rack app, in a config.ru file
run ->(env) { [200, { "content-type" => "text/plain" }, ["Hello"]] }

Rails is a Rack app. Rails.application.call(env) is what the web server invokes for every request. Because everything speaks Rack, you can mount other Rack apps inside Rails, or run Rails with any Rack server.

Middleware: layers around your app

Middleware is a Rack app that wraps another one. It can look at the request before passing it on, and change the response after. A default Rails app has around twenty, including ones that manage cookies, sessions, flash messages, CSRF protection, request IDs and exception pages. You can list them with bin/rails middleware.

The order matters. Think of an onion: the request enters through the outer layers, reaches the router at the centre, and the response travels back out through the same layers.

Stand-in: a Rack-style app with middleware

This runs in plain Ruby. We call app.call(env) ourselves instead of using a web server. There is a logger middleware, a timer middleware, a router and two "controllers" (lambdas).

Ruby Stand-in: middleware, router and controller

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Look at what happens: RequestLogger calls the inner app first, then prints after the response is ready, which is exactly how Rails logs the status code of a finished request. PoweredBy changes the headers on the way out.

The router and the controller

In Rails the router is built from config/routes.rb. It matches the verb and path and hands over to a controller class, passing params such as {"id" => "42"}. A new controller object is created for every request, so instance variables never leak between users.

Ruby
# read-only: roughly what Rails does with GET /articles/42
controller = ArticlesController.new
controller.params = { id: "42" }
controller.process(:show)

The action runs; if it does not render or redirect, Rails renders the template matching the action name. The response then travels back out through the middleware.

Stand-in: one controller instance per request

The detail that matters most to beginners is that each request gets a fresh controller. This stand-in proves why that is safe.

Ruby Stand-in: a new controller per request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Where to hook in

Knowing the cycle tells you where each tool belongs:

  • Something for every request (logging, rate limiting)? Middleware.
  • Something for some actions (login check)? A controller filter (filters).
  • Data rules? The model (Active Record).
  • Page layout? The view and layout (layouts).

When something goes wrong, read the development log in log/development.log. It records each request, the controller and action chosen, the parameters, every SQL query and the time the view took.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a Rack application return from call(env)?

    A Rack app returns [status, headers, body], where body responds to each.
  2. 2. What is middleware?

    Middleware wraps the next app in the stack and can change the request or the response.
  3. 3. How many controller objects does Rails create for one request?

    A fresh controller instance handles each request, so instance variables do not leak between users.
  4. 4. Which command lists the middleware stack of a Rails app?

    bin/rails middleware prints every middleware in order.

Summary

  • A request goes web server, Rack, middleware stack, router, controller, view, then back out as a response.
  • Rack apps respond to call(env) and return [status, headers, body]; Rails is one.
  • Middleware wraps the app for every request; filters wrap only some controller actions.
  • A new controller instance is created for each request.
  • log/development.log shows the full story of each request.

Next: Rails Conventions and Naming