Find Slow Queries in Rails with PostgreSQL
Find slow queries first, then explain them. Rails publishes every query as a sql.active_record event with a duration in milliseconds. Subscribe and log anything over your threshold.
Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.
The conversion
SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM posts WHERE published = true
ActiveRecord
ActiveSupport::Notifications.subscribe("sql.active_record") do |event|
next if event.payload[:name] == "SCHEMA"
if event.duration > 200
Rails.logger.warn("SLOW #{event.duration.round}ms #{event.payload[:sql]}")
end
end
SQL that Rails 8.1.1 generates
event.duration is a Float in milliseconds.
We captured: name "Post Count", sql SELECT COUNT(*) FROM "posts".
A cleaner alternative
SHOW log_min_duration_statement;
PostgreSQL can log slow statements itself with log_min_duration_statement. The default is -1, which logs nothing. Set it in postgresql.conf or with ALTER SYSTEM.
What goes wrong
The threshold is yours
The 200 ms in the example is a starting point. Pick a value that flags the top few queries in your app, then lower it as you fix them.
Log the SQL, not only the duration
The payload holds the SQL string. Add query log tags so each slow line also shows the controller or job that sent it.
pg_stat_statements ranks by total time
The pg_stat_statements extension aggregates by query shape. It must be listed in shared_preload_libraries and needs a PostgreSQL restart. It was available but not loaded on our test server.
Then explain the worst query
Copy the slow SQL into explain(:analyze) from the explain page. Fix the plan, for example with an index, and measure again.
Convert your own slow query query
Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.
Questions
How do I find slow queries in Rails?
Subscribe to the sql.active_record notification and log events over a duration threshold. Combine it with PostgreSQL log_min_duration_statement.
What is the default log_min_duration_statement?
-1 on our PostgreSQL 16 test server, which means slow statements are not logged.
How do I know why a query is slow?
Run explain(:analyze) on it and read the plan. See the ActiveRecord explain page.
Related conversions
ActiveRecord explain: Read the Query Plan
Run EXPLAIN and EXPLAIN ANALYZE from ActiveRecord with relation.explain. Real PostgreSQL 16 plan output, options like :buffers, and how to read Seq Scan.
Rails N+1 Query Fix: includes and strict_loading
Fix N+1 queries in Rails with includes, preload and strict_loading. Query counts measured on Rails 8.1 and PostgreSQL 16: 10 queries drop to 2.
Rails find_each vs each
find_each loads records in batches of 1000 by primary key, each loads every row at once. Tested on Rails 8.1: ignored order, start and finish, and cursor.
All SQL converters
Every tested SQL to ActiveRecord conversion on this site.
Safe conversion guide
How to check that a converted query returns the same rows.