Lesson 5 of 9 · 28m
ActiveRecord Query Performance and N+1 Control
Read query plans, shape associations deliberately, eliminate N+1 queries, and use indexes that match real access patterns.
Most Rails performance incidents are not Ruby problems. They are query-shape problems wearing a Rails costume. The application renders 40 rows, ActiveRecord lazily loads associations, Postgres receives 200 queries, and everyone blames the framework. The fix begins with measuring what the database actually executes.
Development should make N+1 loud
Use the query log locally and in review environments:
config.active_record.verbose_query_logs = trueWatch repeated patterns:
Invoice Load (0.8ms) SELECT * FROM invoices LIMIT 40
Account Load (0.4ms) SELECT * FROM accounts WHERE id = 12
Account Load ... repeated once per invoice rowThat shape is the N+1 fingerprint: one query for the collection, then one query per row.
Preload deliberately
includes can choose preload or eager loading depending on query shape. Be explicit when it matters:
invoices = Invoice.where(account: Current.account)
.includes(:customer, :line_items)
.order(created_at: :desc).limit(40)Use preload when you always want separate queries. Use eager_load when you need a join for filtering or ordering. Use joins when you do not need associated objects instantiated. The correct method is the one whose SQL you have read.
Indexes must match predicates and ordering
An index on status alone is often useless if most rows share the same status. A common access pattern needs a composite key:
add_index :invoices, [:account_id, :status, :created_at], order: { created_at: :desc }, algorithm: :concurrentlyThen inspect the plan:
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM invoices
WHERE account_id = 42 AND status = 'open' ORDER BY created_at DESC LIMIT 40;Look for sequential scans on large tables, sorting outside the index, row estimate errors, and buffer reads that indicate cache pressure.
Counter caches and denormalization are commitments
Rails makes counter_cache easy. Keeping it correct under concurrency, imports, deletes, and backfills is the real work. Denormalize only when the read path justifies the write complexity, and document the reconciliation job. Otherwise the cache becomes a second source of truth with no owner.
Field notes
find_eachbatches by primary key; it is not a license to ignore transaction time or object memory growth.pluckavoids model instantiation but returns raw values with no behavior attached.- PostgreSQL partial indexes are excellent for hot subsets such as active jobs or unpublished records.
- Bullet-style N+1 detection helps development, but production slow-query evidence is the authority.
Was this lesson helpful?