← Back to Blog

ActiveRecord Performance Monitoring: What to Measure in Production (With Code)

November 23, 2026

A request to your dashboard takes 900ms. The log line at the end says ActiveRecord: 140ms. So the database is fine, right? Then you notice the same request loaded 30,000 records into memory, ran 400 queries, and waited for a free database connection before it even started. None of that shows up as "ActiveRecord time", and that gap is exactly what ActiveRecord performance monitoring is for.

The single number Rails prints for you is real, but it only covers time spent waiting on SQL. The cost of ActiveRecord is spread across several places, and you need to see all of them on real production traffic to know which one is hurting you.

Good ActiveRecord monitoring tracks every one of those costs. This guide walks through the five numbers worth tracking, how to collect each one with plain Rails instrumentation, and how to trace a slow query back to the line of code that ran it.

The five numbers that matter

When people say "the database is slow", they usually mean one of these:

  1. SQL time per request. How long the request spent waiting on the database.
  2. Query count per request. How many round trips it made, including the ones served from the query cache.
  3. Records loaded per request. How many rows ActiveRecord turned into Ruby objects.
  4. Slow statements and where they come from. Which queries are slow, and which controller, job, or line of code ran them.
  5. Connection pool waits. Whether requests are queuing for a connection before they can run any SQL at all.

A request can look healthy on one of these and terrible on another. A page that runs 400 fast queries has low SQL time per query but a lot of network round trips. A page that runs one query returning 50,000 rows has a small query count and a huge memory and CPU bill on the Ruby side. If you only watch one number, you'll keep missing the other four.

Step 1: Collect per-request stats from ActiveRecord's own events

Rails already publishes everything you need through ActiveSupport::Notifications. The sql.active_record event fires for every query. Its payload includes the SQL, a name like "User Load", a :cached flag for query cache hits, and on recent Rails versions a :row_count with the number of rows returned. The instantiation.active_record event fires when records are built, with a :record_count and :class_name.

Start with a CurrentAttributes class to hold the numbers. Rails resets it around every request and job, so counts never leak from one request into the next:

# app/models/ar_stats.rb
class ArStats < ActiveSupport::CurrentAttributes
  attribute :sql_ms, :queries, :cached, :rows, :records

  def self.add(name, amount)
    public_send("#{name}=", (public_send(name) || 0) + amount)
  end

  def self.summary
    {
      sql_ms: (sql_ms || 0).round(1),
      queries: queries || 0,
      cached: cached || 0,
      rows: rows || 0,
      records: records || 0
    }
  end
end

Then subscribe to both events in an initializer:

# config/initializers/ar_stats.rb
IGNORED_SQL_NAMES = %w[SCHEMA TRANSACTION].freeze

ActiveSupport::Notifications.subscribe("sql.active_record") do |event|
  payload = event.payload
  next if IGNORED_SQL_NAMES.include?(payload[:name])

  if payload[:cached]
    ArStats.add(:cached, 1)
    next
  end

  ArStats.add(:queries, 1)
  ArStats.add(:sql_ms, event.duration)
  ArStats.add(:rows, payload[:row_count].to_i)
end

ActiveSupport::Notifications.subscribe("instantiation.active_record") do |event|
  ArStats.add(:records, event.payload[:record_count])
end

event.duration is in milliseconds. On older Rails versions that don't send :row_count, the value is nil and to_i turns it into zero, so the rest still works.

Ignoring SCHEMA and TRANSACTION keeps schema lookups and BEGIN/COMMIT statements out of your counts. Leave them in if you suspect transactions themselves are part of the problem.

Step 2: Write one line per request

Now emit the stats once per request. The process_action.action_controller event fires when the controller finishes, including view rendering, and its payload includes the controller, action, status and Rails' own :db_runtime. Hooking into it means you don't have to touch any controller:

# config/initializers/ar_stats.rb (continued)
ActiveSupport::Notifications.subscribe("process_action.action_controller") do |event|
  payload = event.payload
  pool = ActiveRecord::Base.connection_pool.stat

  line = {
    endpoint: "#{payload[:controller]}##{payload[:action]}",
    status: payload[:status],
    total_ms: event.duration.round(1),
    pool_waiting: pool[:waiting],
    pool_busy: pool[:busy],
    pool_size: pool[:size]
  }.merge(ArStats.summary)

  Rails.logger.info("[ar] #{line.to_json}")
end

A request now produces a line like this:

[ar] {"endpoint":"DashboardsController#show","status":200,"total_ms":912.4,"pool_waiting":0,"pool_busy":3,"pool_size":5,"sql_ms":141.2,"queries":402,"cached":37,"rows":31877,"records":31877}

That one line answers most "is it the database?" questions:

  • High sql_ms and low queries means a few slow statements. Go to step 3 and find them.
  • High queries means too many round trips, which is usually an N+1 or a loop that calls find or count.
  • High records compared to what the page shows means you're loading far more than you render. The fix is usually pluck, select, pagination, or moving an aggregation into SQL.
  • total_ms much bigger than sql_ms with a big records number means the time is going into building and walking Ruby objects, not into the database. The Real Cost of ActiveRecord goes into why that happens.

Because the line is JSON, any log tool can group it by endpoint and give you percentiles instead of single samples. Look at the slow end of each endpoint, not the average. The requests that hurt are the ones for your biggest customers, and the average hides them.

Background jobs deserve the same treatment. The perform.active_job event works the same way:

ActiveSupport::Notifications.subscribe("perform.active_job") do |event|
  job = event.payload[:job]

  line = {
    job: job.class.name,
    queue: job.queue_name,
    total_ms: event.duration.round(1)
  }.merge(ArStats.summary)

  Rails.logger.info("[ar] #{line.to_json}")
end

Step 3: Find out where slow queries come from

Knowing that DashboardsController#show spends 600ms in SQL is useful. Knowing which line of code ran the slow query is what lets you fix it.

Log slow queries with their source

You can catch slow statements in the same sql.active_record subscriber. Only compute the source location for the slow ones, because walking the call stack on every query adds up:

# config/initializers/slow_queries.rb
SLOW_QUERY_MS = 100

ActiveSupport::Notifications.subscribe("sql.active_record") do |event|
  next if event.duration < SLOW_QUERY_MS
  next if event.payload[:cached]

  source = Rails.backtrace_cleaner.clean(caller).first

  Rails.logger.warn(
    "[slow-sql] #{event.duration.round(1)}ms " \
    "#{event.payload[:name]} at #{source} | " \
    "#{event.payload[:sql].truncate(300)}"
  )
end

Rails' backtrace cleaner drops framework and gem frames, so the first line left is usually the line in your app that triggered the query. One caveat: queries started with load_async run on a background thread, so their call stack won't point back at your code. Pick a threshold that fits your app. 100ms is a starting point, not a rule.

Rails also has a built-in version of this for development. With config.active_record.verbose_query_logs turned on, the log shows the source location under each query. It's on by default in development and off everywhere else.

Tag queries so the database knows who sent them

The other direction is to tag the SQL itself. With query log tags, Rails adds a comment to every query naming the controller, action or job that ran it:

# config/application.rb
config.active_record.query_log_tags_enabled = true
config.active_record.query_log_tags = [:application, :controller, :action, :job]

Your queries then arrive at the database looking something like this:

SELECT "orders".* FROM "orders" WHERE "orders"."account_id" = $1
/*application='Shop',controller='dashboards',action='show'*/

That comment shows up in your database's slow query log and in pg_stat_statements, so a slow query found on the database side points straight back to the Rails code that sent it.

Two things to know before turning this on in production. The Rails guide notes that enabling query log tags disables prepared statements. There's also a :source_location tag, which the guide warns can be slow to calculate in production. Try both on a staging environment with realistic load before you ship them.

Step 4: Look at the database's side of the story

Per-request numbers tell you which endpoints are slow. The database can tell you which statements cost the most in total, across every request. On PostgreSQL, the pg_stat_statements extension tracks this for you. Once it's enabled, this query lists the statements that used the most database time:

SELECT
  calls,
  round(total_exec_time::numeric, 1) AS total_ms,
  round(mean_exec_time::numeric, 1)  AS mean_ms,
  rows,
  left(query, 200) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

Sort by total time, not by mean time. A query that takes 3ms but runs two million times a day usually costs more than one that takes two seconds and runs twice. The mean column tells you which queries are slow. The total column tells you which ones are worth fixing first.

You can run the same query from a Rails console when you don't have direct database access:

ActiveRecord::Base.connection.select_all(<<~SQL).to_a
  SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, left(query, 200) AS query
  FROM pg_stat_statements
  ORDER BY total_exec_time DESC
  LIMIT 20
SQL

Step 5: Watch the connection pool

Some of the slowest "database" requests never run a slow query. They spend their time waiting for a connection.

Every Rails process has a connection pool, and connection_pool.stat reports how it's doing:

ActiveRecord::Base.connection_pool.stat
# => { size: 5, connections: 5, busy: 5, dead: 0, idle: 0, waiting: 2, checkout_timeout: 5 }

waiting is the number to watch. If it's above zero, threads are queued for a connection, and that time is added to the request without ever appearing as SQL time. The per-request line from step 2 already records it. If you see it regularly, check that your pool size matches the number of threads that can use it: Puma threads in web processes, and your job runner's concurrency in worker processes. If threads wait long enough, you'll eventually see ActiveRecord::ConnectionTimeoutError, which is the same problem at full volume.

Step 6: Confirm the fix with EXPLAIN

Once you've found the query, check what the database actually does with it before you change anything. ActiveRecord can run EXPLAIN on any relation, and on PostgreSQL, MySQL and MariaDB it accepts options:

Order.where(account_id: 42, status: "paid")
     .order(created_at: :desc)
     .limit(50)
     .explain(:analyze)

Look for sequential scans on large tables, sorts that can't use an index, and row estimates far away from the actual row counts. Be careful with :analyze in production: it really runs the query, so an UPDATE or DELETE will change data. Use it on reads, or inside a transaction you roll back.

After you ship the fix, go back to the per-request line and pg_stat_statements and check that the numbers moved. A fix that looks right in EXPLAIN but doesn't change sql_ms for the endpoint usually means the slow query wasn't the main cost.

A short checklist

If you only do a few of these, do them in this order:

  • Log SQL time, query count and records loaded per request and per job, as JSON.
  • Log slow queries with the line of code that ran them.
  • Enable pg_stat_statements and look at the top statements by total time once a week.
  • Record connection_pool.stat[:waiting] so pool waits stop hiding as general slowness.
  • Use EXPLAIN before changing indexes, and check the numbers again after.

If your requests are slow and the numbers above all look fine, the time is going somewhere else. Why Is My Rails App Slow? covers the other usual suspects, and if you added caching to hide a slow query, check that the cache is actually hitting.

Keeping an eye on it over time

The instrumentation above is a solid start, and for a small app it might be enough. Where it gets harder is turning log lines into answers: which endpoint got slower after Tuesday's deploy, which query is new, and whether the pool waits line up with traffic spikes.

That's the job DeadBro does for Rails apps. Add the dead_bro gem and it records SQL time, queries and memory for each request and job, so you can see the same numbers from this guide per endpoint without maintaining the subscribers yourself. You can read more about how it approaches Rails performance monitoring or see the Rails APM overview. Either way, the important part is measuring all five numbers in production, where the slow requests actually happen.