skip to content

A slow statement shows up in the production database's logs of a Rails 8.1 grades portal; how do you trace it to the controller action or job, and what does that cost?

level: seniorimportance: should knowfreq 25%

answer

  1. enable tags in production.rb
  2. the comment names controller, action or job
  3. prepared statements switched off
  4. cache_query_log_tags: per-execution reuse
  5. prepend_comment against truncation

basics

~20 s

Enable query log tags in production so every statement carries a comment naming the controller and action, or the job; the slow statement in the database's logs then names its origin. The cost is prepared statements and some work per query.

solid answer

~40 s

Set `config.active_record.query_log_tags_enabled = true` in `production.rb` (only `development.rb` has it by default). Every statement then ends with a SQLCommenter comment such as `/*action='index',application='GradesPortal',controller='gradebooks'*/`, so the slow statement the database logged names the action or job; add a request-id or tenant lambda tag to narrow it to one request or school. Then reproduce it in development, where `verbose_query_logs` gives the exact line. Costs: enabling tags turns off prepared statements app-wide, so the database parses and plans every statement again; tag lambdas run per query unless `cache_query_log_tags` reuses the comment within an execution, which goes stale if a tag value changes after the first query; `query_log_tags_prepend_comment` keeps the comment visible to tools that truncate long SQL. Leave `:source_location` and `verbose_query_logs` out of production.

code

ruby · 13 lines
ruby
class ApplicationController < ActionController::Base
  include Authentication                 # runs a Session query first
  before_action :set_current_school      # sets Current.school afterwards

  private
    def set_current_school
      Current.school = Current.user&.school
    end
end

# With config.active_record.cache_query_log_tags = true, the comment built for the
# first (Session) query lacks school_id, and every later query in the request
# reuses it: setting a Current attribute does not clear the cache.

go deeper

for a junior

Know that query log tags let a slow statement in the database's logs name the Rails controller action or job that sent it.

for a middle

Explain how to enable tags in production, which tags help narrow a request, and why verbose_query_logs stays in development.

for a senior

Weigh the prepared-statement cost, use cache_query_log_tags only for tags fixed per execution, prepend comments for truncating tools, and reproduce locally for the exact line.

for a principal

Decide whether tags are permanently on in production as part of the observability baseline, given the prepared-statement trade-off and the tooling that consumes them.

## The situation The grades portal slows down at the end of term. The database's slow-statement log (its own tooling is outside this answer) shows a heavy `SELECT` on `grades`, but nothing in it says which of the app's dozens of actions and jobs sent it. In production the Rails log runs at `info`, so SQL lines are not logged, and `verbose_query_logs` is off. The tool for this gap is **query log tags**: they write the Rails origin into the SQL text itself, where the database's logs can see it. ## Step by step 1. **Enable tags in production.** The generated `production.rb` does not; add it: ```ruby # config/environments/production.rb config.active_record.query_log_tags_enabled = true config.active_record.query_log_tags = [ :application, :controller, :action, :job, { request_id: ->(context) { context[:controller]&.request&.request_id }, school_id: -> { Current.school&.id } } ] ``` 2. **Deploy and wait for the statement to recur.** It now arrives as `... /*action='index',application='GradesPortal',controller='gradebooks',request_id='...',school_id='7'*/`. On `load_defaults` 7.1 or later the format is SQLCommenter, which tracing tools that understand that convention can parse. 3. **Join it to the request.** The `request_id` matches the request id that the generated `production.rb` already tags each log line with, so the application log for that one request is easy to find. 4. **Reproduce in development** with the same school's data size. There, `verbose_query_logs` prints the `↳` line under the statement, pointing at the line of code that built the relation. 5. **Fix and verify** by watching the tagged statement's frequency and duration in the database's logs. ## What it costs | Cost | Why | Mitigation | |---|---|---| | Prepared statements disabled | enabling tags sets `ActiveRecord.disable_prepared_statements = true`, since the comment makes statements differ | measure before and after; accept or enable tags only where it pays | | Comment built per statement | every tag handler runs for every query | `config.active_record.cache_query_log_tags = true` | | Truncated comments | some tools cut long statements, losing a trailing comment | `config.active_record.query_log_tags_prepend_comment = true` | | Slow tags | `:source_location` walks the stack per query | leave it out of production | ## The caching trap `cache_query_log_tags` stores the built comment per thread and reuses it until Rails' execution context changes, which happens when a new action or job starts. That is safe for tags fixed for the whole execution. It is **not** safe when a tag's value changes after the first query: - the authentication `before_action` looks up the session (first query: comment built with `school_id` nil, so omitted); - a later `before_action` sets `Current.school`; - every following query reuses the cached comment, still without `school_id`. Setting a `Current` attribute does not clear the cache. Either keep caching off, or make sure such values are set before the first query. ## What not to use in production - **`verbose_query_logs`**: walks the call stack for each query, and its output is `debug`-level anyway. - **Raising the log level to `debug`** to see SQL lines: it multiplies log volume and still does not tell the database side anything. ## Turning it on safely - Roll the change out like any production config change and compare database CPU and latency before and after, since prepared statements switch off with it. - Start with the default tags plus one or two lambdas; add `cache_query_log_tags` only after confirming every tag is fixed per execution. - Agree the tag names with whoever reads the database logs, so searches keep working. ## Limits of the method - A statement issued before the action starts (from middleware, for example) has no controller or action tag; that absence is itself a clue. - Tags name the code path, not the line; the line comes from reproducing locally. - Comments show where a query came from, not why it is slow. The plan and indexes are a database question.

  • Why not simply set the production log level to debug so you can see every SQL line?
    It multiplies log volume and cost, and it only shows SQL in the Rails log, which you would then have to match to the database's slow statement by time. Query log tags put the origin into the statement the database already logged, at no log-volume cost.
  • When is cache_query_log_tags safe to turn on?
    When every tag's value is fixed for the whole request or job: the application, controller, action, job, or a request id read from the controller. It is unsafe for values set partway through, such as a `Current` attribute assigned after the first query, because only changes to the execution context clear the cached comment.
  • Should prepared statements being disabled stop you from enabling tags in production?
    Not automatically. Measure: the portal may not notice the extra parse and plan work, and the observability gain is large. If it does matter, enable tags temporarily while investigating, or accept the cost only on the database role that needs it.

  • rails new already enables query log tags in production.rb.
  • Setting a Current attribute clears the cached query log comment.
  • Query log tags keep prepared statements working exactly as before.
  • verbose_query_logs is the cheap way to trace queries in production.
  • The SQL comment tells you why the query is slow, not just where it came from.

Assumes Rails 8.1 with load_defaults 7.1 or later, so tags use the SQLCommenter format; the generated production.rb does not enable query log tags.