Database Performance in Rails: The 80/20 of Indexing, 1+Ns, and Query Plans
Frontline lessons learned on db performance.
After a decade of scaling Rails applications, I’ve learned that database performance rarely fails because of exotic edge cases. It fails because of the same three things: missing or misaligned indexes, 1+N queries hiding in plain sight, and query plans we never bothered to read. This post is the playbook I wish I had earlier: the 20% of techniques that eliminate 80% of the pain.
The Query Plan Is the Source of Truth
ActiveRecord is a beautiful abstraction until it isn’t. When a query takes 400ms in production but 40ms in staging, the answer is never in the Ruby code. It’s in the plan.
EXPLAIN ANALYZE actually executes the statement and shows you both the planner’s estimates and the reality of what happened. The single most valuable signal is the gap between estimated rows and actual rows. When the planner expects 10 rows and gets 100,000, it almost certainly chose the wrong strategy: usually a Nested Loop where a Hash Join belonged, or a Seq Scan where an Index Scan was possible.
Here’s the pattern I use in staging (never casually in production):
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders
WHERE customer_id = 12345
AND created_at > '2025-01-01';
BUFFERS adds the memory and disk I/O breakdown, while shared hit vs. shared read tells you whether the data was cached or fetched from disk. If you see read dominating, you have an I/O problem, not a CPU problem. That distinction changes your fix entirely.
The nodes to recognize immediately: Seq Scan (full table), Index Scan (index + heap), Bitmap Index Scan (index lookup then batch heap access), and Nested Loop (repeats inner scan per outer row). A Nested Loop with a high loops count is the smoking gun for a missing index on a join key.
One caution: EXPLAIN ANALYZE on writes actually modifies data. Wrap it:
BEGIN;
EXPLAIN ANALYZE UPDATE ...;
ROLLBACK;
1+N: Bullet vs. Prosopite
Every Rails developer knows the 1+N shape. You load Post.all, then in the view call post.author.name, and suddenly you have 101 queries for 100 posts. The fix with includes, preload, or eager_load is well-trodden ground. The harder question is detection.
Bullet has been the default for years. It hooks into Rails and warns you about 1+Ns, unused eager loading, and missing counter caches. Configure it with Bullet.raise = true in tests and you’ll catch regressions before they ship. It’s mature and the warnings are actionable.
But Bullet has blind spots. It can miss 1+Ns after record creation (common in tests with FactoryBot), 1+Ns triggered by explicit find calls rather than associations, and 1+Ns on collection methods like .first, .last, and .pluck. Prosopite emerged specifically to close these gaps. Its mechanism is fundamentally different: it monitors Active Support instrumentation and flags repeated query fingerprints with the same call stack, which catches 1+Ns regardless of whether they come through an association.
My recommendation: use both. Bullet for development-time feedback and unused eager load detection; Prosopite in CI with Prosopite.raise = true to catch the cases Bullet misses. Prosopite’s zero-false-positive claim is aggressive, but in practice, its stricter fingerprinting means you spend less time dismissing noise and more time fixing real issues.
Indexing: The 80/20
Most Rails apps have too many indexes on low-selectivity columns and too few on the columns that actually matter.
Composite Indexes: Order Is Everything
A composite index on (user_id, created_at) serves queries filtering on user_id, and queries filtering on both user_id and created_at. It does not serve queries filtering only on created_at ie. the leftmost prefix rule is absolute.
The column order heuristic that works: equality predicates first, range predicates last. If your query is WHERE status = 'pending' AND created_at > ?, the index should be (status, created_at). Reversed, and PostgreSQL can’t use the range efficiently.
A real-world example from a sales table: adding CREATE INDEX idx_sales_product_id_sale_date ON sales(product_id, sale_date) dropped a query from 19ms to 0.074ms - a 275x improvement. That’s the 80/20 in action.
Partial Indexes: Index Less, Get More
If you always query a subset of rows, index only those rows. A WHERE status = 'active' clause in your index definition means PostgreSQL maintains a smaller, faster index that only covers the data you actually query.
The canonical Rails use cases:
- Soft deletes:
WHERE deleted_at IS NULL - Queue tables:
WHERE status IN ('pending', 'retry') - Active subscriptions:
WHERE cancelled_at IS NULL
Partial indexes reduce storage, reduce write amplification (fewer index updates on INSERT/UPDATE), and make the planner’s job easier. For a background job table with millions of completed records and a few thousand pending ones, a partial index on pending status is transformative.
The Rails Patterns That Quietly Kill Performance
Using .size in a loop without eager loading. post.comments.size looks innocent. Without a loaded association, it fires SELECT COUNT(*) per post. If you’ve already loaded the comments, .size uses the cache. The fix: includes(:comments) and then .length if you need the count without a query, or a counter cache for a permanent solution.
Background jobs without eager loading. 1+Ns in Sidekiq workers don’t show up in browser performance bars. A weekly digest job iterating User.active.each { |u| u.posts.recent } is 1+N in slow motion. Audit your jobs with the same rigor as your controllers.
Serializer-induced 1+Ns. Your controller loads @posts = Post.all, the serializer calls post.author, and you’ve reintroduced the 1+N you fixed in the view. The fix is always in the controller: Post.includes(:author), but it’s easy to forget when the serializer is a separate file.
Missing statistics. When estimated rows diverges wildly from actual rows, the planner is flying blind. ANALYZE your tables after large data changes. On modern PostgreSQL, autovacuum handles this, but bulk imports and migrations can leave statistics stale until autovacuum catches up.
The Checklist
Before any PR that touches queries:
- Run
EXPLAIN (ANALYZE, BUFFERS)on the new query in staging with production-like data. - Check the estimated/actual row gap. If it’s off by orders of magnitude, fix statistics or the query shape first.
- Verify index usage: no
Seq Scanon tables over ~10k rows unless you’re intentionally fetching a large fraction. - Confirm
includes/preload/eager_loadmatches the access pattern. - Let Prosopite run in CI with
raise = true.
The 80/20 isn’t glamorous. It’s reading plans, ordering composite indexes correctly, and not letting .size run in a loop. But these three things - query plans, 1+N detection, and intentional indexing - account for the vast majority of Rails database performance wins I’ve seen in production. Master them, and you’ll spend your time on architecture instead of firefighting.