Skip to main content

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.