A dashboard that loads in 300 ms on your laptop and 9 seconds in production usually has the same cause: an N+1 query. With ten rows of seed data it is invisible. With two thousand orders, each pulling its customer, its address and its line items, one request quietly becomes six thousand database round trips.
This tutorial walks through how to spot N+1 queries in a Rails API, the three loading strategies Active Record gives you and when each one is right, and how to stop new N+1s from reaching production at all.
You will need a Rails 7 app and PostgreSQL. The examples use a small order-dispatch domain, but the patterns apply to any app.
The setup
class Order < ApplicationRecord belongs_to :customer belongs_to :delivery_slot has_many :line_items end
class Customer < ApplicationRecord has_many :orders has_one :address end
Enter fullscreen mode
Exit fullscreen mode
And a controller that powers a dispatch screen:
class Api :: OrdersController < ApplicationController def index orders = Order .…