Skip to content

Rails Performance

Most slow Rails applications are slow for five reasons, and none of them is “Ruby is slow”. A request that takes 800 ms is usually 40 queries of 20 ms rather than one expensive computation. So: measure, find the query count and the time split, then fix the specific thing.

“Start with logs and a profiler, not a guess. In development the server logs every query with timings; in production use rack-mini-profiler, Skylight or Scout. The highest-yield fixes, in order: eliminate N+1 queries with includes, add the indexes the query plan wants, cache what is expensive and rarely changes, move slow work into background jobs, and never render an unbounded collection. Beyond that it is database tuning: composite indexes ordered equality-then-range, EXPLAIN ANALYZE to confirm the index is used, and a connection pool sized to match the web workers. Caching is the last resort, not the first, because every cache is an invalidation problem.”

# 41 queries for 40 posts
@posts = Post.limit(40)
@posts.each { |p| p.author.name }
# 2 queries
@posts = Post.includes(:author).limit(40)

strict_loading raises ActiveRecord::StrictLoadingViolationError on a lazy load instead of silently querying. It is aggressive — enable it per model, or use the bullet gem in development and test.

Bullet flags N+1s, unused eager loads and missing counter caches, and can fail CI. The same shape appears with count inside a loop, exists? per row, and serialisers that touch an association: always load the data in the query, not in the view.

class AddPerformanceIndexes < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
add_index :orders, [:user_id, :created_at], algorithm: :concurrently
add_index :orders, :status, where: "status = 'pending'", algorithm: :concurrently
add_index :users, :email, unique: true, algorithm: :concurrently
end
end
  • algorithm: :concurrently builds without an exclusive lock, so writes continue. It requires disable_ddl_transaction! and cannot add a constraint at the same time.
  • Column order matters. (user_id, created_at) serves WHERE user_id = ?, that filter plus ORDER BY created_at, and WHERE user_id = ? AND created_at > ?. It does not serve WHERE created_at > ? alone.
  • Equality first, range last. (status, created_at) supports status plus a date range; (created_at, status) does not.
  • Partial indexes (where:) are small and fast for a hot subset such as pending jobs.
  • Foreign keys need indexes. t.references adds one; a bare add_column :comments, :post_id does not.

Removing an index is also a migration: remove_index :orders, column: [:user_id, :created_at]. An unused index costs write throughput on every insert.

Layer Caches Invalidated by
HTTP / CDN Whole responses expires_in, ETag, Cache-Control
Fragment Rendered HTML per record cache_key_with_version (updated_at)
Low-level Any serialisable value Manual key or version
Query cache Identical SQL within one request Automatic
Counter columns Aggregates Maintained explicitly
Rails.cache.fetch(["popular-posts", Post.maximum(:updated_at)], expires_in: 10.minutes) do
Post.popular.limit(10).to_a
end
  • Cache Russian-doll style: each item, then the collection keyed on the collection’s updated_at.
  • cache_key_with_version includes updated_at, so touch on a parent busts children. That is the whole invalidation strategy, and it only works if you touch the right parents.
  • Never cache per-user data without the user in the key.
  • Rails 8 defaults to Solid Cache (database-backed), so Redis is optional for most apps.

Anything not needed to render the response belongs out of the request: email, image processing, PDFs, third-party calls, webhooks, fan-out.

The win is not “it is faster” — it is that the request now has a bounded, predictable latency. A slow third party no longer becomes your p99. See Active Job and Action Cable.

@posts = Post.order(created_at: :desc).page(params[:page]).per(25) # kaminari or pagy
Post.find_each(batch_size: 500) { |post| post.reindex }
Post.in_batches(of: 1000).update_all(processed: true)

Never Model.all.each: it loads every row into memory, and a two-million-row table ends the process. find_each keeps memory flat.

Callback traps: a callback touching N associated records turns one save into N+1 writes; dependent: :destroy on a large association loads and destroys each child where delete_all is one statement; as_json(include: :comments) on a collection loads everything.

  • rack-mini-profiler shows SQL time, query count and a flamegraph per request.
  • EXPLAIN ANALYZE tells you whether the plan is a sequential scan, a missing index, or a bad row estimate.
  • ActiveSupport::Notifications.subscribe("sql.active_record") gives the raw query stream when you need to count queries in a script.
  • APM (Skylight, Scout, Datadog) gives the only number that matters: production p95 per endpoint.
  1. How do you find an N+1 in a codebase you just joined?
  2. Why does column order matter in a composite index?
  3. Why is algorithm: :concurrently needed, and what does it forbid?
  4. When is fragment caching the wrong answer?
  5. What is the difference between find_each and in_batches?
  • Caching to hide an N+1. The cache misses eventually and the endpoint is worse than before.
  • Indexes on every column. Each slows writes and bloats the table.
  • Model.count in a view. A query per render; use a counter column or cache it.
  • Deep OFFSET pagination. It scans and discards; use keyset pagination (where("id > ?", last_id)) at large offsets.
  • A connection pool smaller than the thread count. Requests queue on connections and it looks like a database problem.
  • Optimising without a baseline. No before/after number means no way to know it helped.