skip to content

A Jbuilder flight-search endpoint is slow; how do N+1 queries hide in its partials, and when do json.cache! and cached: true actually cache?

level: seniorimportance: should knowfreq 35%

answer

  1. one partial render per element
  2. associations touched inside partials
  3. preload in the controller
  4. perform_caching gates json.cache!
  5. cached: true reads many keys at once

basics

~20 s

Each element's partial loads any association it touches, so preload them in the controller. json.cache! and cached: true store fragments in Rails.cache only when controller.perform_caching is on; otherwise they just render, which is the default in development.

solid answer

~50 s

A collection partial runs once per element, and every `flight.fares` or `fare.airline` it touches is a query per element unless the controller preloaded it, for example `Flight.includes(fares: :airline)`. Jbuilder does not batch anything. For caching, `json.cache! ["v1", flight], expires_in: 5.minutes do ... end` reads and writes `Rails.cache`, but only when `controller.perform_caching` is true; otherwise it simply yields. That is false in development until `bin/rails dev:cache` and true in production, so caching looks broken locally. On a collection, `json.array! @flights, partial: ..., as: :flight, cached: true` fetches all elements' fragments in one multi-read and renders only the misses, also gated on `perform_caching`. Keys include the template digest and the record's cache version, so a changed flight gets a fresh key; for prices that change on another table, add their timestamp to the key with `cached: ->(flight) { [flight, flight.fares.map(&:updated_at).max] }` or touch the parent.

code

ruby · 10 lines
ruby
# app/controllers/api/v1/flights_controller.rb
def index
  @flights = Flight.where(origin: params[:from], destination: params[:to])
                   .includes(fares: :airline)
end

# app/views/api/v1/flights/index.json.jbuilder
json.array! @flights,
  partial: "api/v1/flights/flight", as: :flight,
  cached: ->(flight) { [flight, flight.fares.map(&:updated_at).max] }

go deeper

for a junior

Know that partials run per element and that json.cache! depends on caching being enabled.

for a middle

Explain the perform_caching gate per environment and how cached: true multi-reads fragments.

for a senior

Diagnose view time versus query time, preload what templates touch, and design keys that expire when fares change.

for a principal

Decide whether a hot search endpoint should keep Jbuilder with caching or move to hand-built hashes for throughput.

## Where the time goes A Jbuilder search endpoint usually looks like this: ```ruby # index.json.jbuilder json.array! @flights, partial: "api/v1/flights/flight", as: :flight # _flight.json.jbuilder json.extract! flight, :id, :flight_number, :departs_at json.fares flight.fares, partial: "api/v1/fares/fare", as: :fare # _fare.json.jbuilder json.extract! fare, :cabin, :amount_cents, :currency json.airline fare.airline.name ``` For 50 flights with 4 fares each, that is 50 `fares` queries and 200 `airline` queries if nothing was preloaded, plus 250 partial renders through Action View. Two separate costs, two separate fixes. ## Fix 1: load data before the view Jbuilder runs Ruby; it has no idea which association calls will repeat. The controller has to load them up front: ```ruby @flights = Flight.search(params).includes(fares: :airline) ``` `includes` loads all fares and all their airlines in a fixed number of queries, so the partials read from memory. The same applies to `render json:` with `include:`: that option nests output but does not preload, so it has the same per-record queries. Choosing between `includes`, `preload` and `eager_load` is its own topic; the JSON-side rule is that **every association a template touches must be preloaded or it is a per-row query**. ## Fix 2: cache rendered fragments | Tool | What it caches | When it caches | |---|---|---| | `json.cache! key, expires_in: ... do ... end` | the block's JSON, under `key` | only if `controller.perform_caching` | | `json.cache_if! condition, key do ... end` | same, only when `condition` is true | same gate | | `json.cache_root! key do ... end` | the whole template as a string, at the root only | same gate | | `cached: true` on a collection partial | each element's partial output | same gate, via multi-read | With the gate off, `cache!` just **yields**: the block renders every time and nothing is stored. Defaults: 1. **Development:** off, until `bin/rails dev:cache` creates `tmp/caching-dev.txt` and the server restarts. 2. **Test:** the generated `config.cache_store = :null_store` stores nothing, so cached blocks render every time. 3. **Production:** `config.action_controller.perform_caching = true`, using whatever store `Rails.cache` is configured with. This is why a developer can add `json.cache!`, see no speedup locally, and conclude it does nothing. ## How keys are built `json.cache! ["v1", flight]` expands through Action View's fragment naming: the key includes the **template's digest** (so editing the partial invalidates it) and the record's `cache_key_with_version` (so updating the flight invalidates it). Two consequences for fares: - A fare update does **not** change the flight's `updated_at`, so a flight fragment that contains fares stays stale unless fares `belongs_to :flight, touch: true` or the key includes the fares' latest timestamp. - Prices that depend on the request, such as the user's currency, must be part of the key: `cached: ->(flight) { [flight, params[:currency]] }`. ## Collection caching `cached: true` makes Jbuilder ask the cache for every element's key in one **multi-read**, render only the misses, and write them back. On a warm cache, 50 flights cost one cache round trip instead of 50. It still needs the preloads from fix 1 for the misses, and the misses still pay the full render. ## Deciding what to cache - Cache per element (`cached: true`) when elements are reused across many searches and change rarely. - Use a short `expires_in:` for fare data that changes by the minute rather than relying on touches across tables. - Measure first: the log line for each action reports view time and Active Record time separately, which tells you whether rendering or queries dominate. ## Confirming the fix Each request's completion line in the development log reports both costs, for example `Completed 200 OK in 182ms (Views: 121.4ms | ActiveRecord: 38.0ms (251 queries, 0 cached) | GC: 9.1ms)`. Use it before and after each change: 1. After adding the preloads, the query count should drop from hundreds to a handful while view time stays similar. 2. After enabling `bin/rails dev:cache` and warming the cache, a repeated search should show view time falling, because cached elements skip their partials. 3. If view time does not move, check that the cache key varies only with what really changes; a key that includes something per request, such as a timestamp, never hits.

  • Why use flight.fares.map(&:updated_at).max in the cache key instead of flight.fares.maximum(:updated_at)?
    With `includes(:fares)` the fares are already in memory, and `map(&:updated_at).max` reads them without SQL. `maximum(:updated_at)` always runs an aggregate query, one per flight, which reintroduces the per-row queries the preload removed, just to build cache keys.
  • When is json.cache_root! better than json.cache!?
    `cache_root!` caches the whole template's output as a JSON string, which skips rebuilding the hash on a hit and is faster. It must wrap the entire template: Jbuilder raises if anything was set before it, and it cannot be used inside partials. Use `cache!` for pieces and `cache_root!` when the full response is reusable.

  • Jbuilder batches association loads across partials automatically.
  • json.cache! caches in development as soon as it is added.
  • include: in render json: preloads the nested association.
  • Wrapping a partial in json.cache! removes its N+1 queries on cache misses.
  • cached: true caches the compiled partial, not its output.