Unraveling the Mystery: Identifying Unknown Queries in Rails

In Ruby on Rails ecosystem, encountering unknown or unexpected queries can be a perplexing challenge. This blog post delves into a practical approach to identifying the source of such queries, leveraging the active_record_query_trace gem. The journey begins with a peculiar issue that I found in RDS Performance Insight and NewRelic report, where an unknown query surfaced, its origin a mystery. The quest to uncover the source of this query led to the utilization of active_record_query_trace, a powerful tool in the arsenal of a Rails developer.

While working on a Rails application, it’s not uncommon to stumble upon queries that seem to originate from nowhere. These queries can be particularly baffling when they don’t directly correspond to the code you’re actively working on or when they appear to be generated by external libraries or gems. The challenge lies in pinpointing the exact location within the codebase that triggers these queries, a task that can be daunting without the right tools.

The active_record_query_trace gem emerges as a beacon of hope in such scenarios. It is designed to log and display a backtrace for each SQL query executed by Active Record, thereby allowing developers to trace the origin of queries back to specific lines of code within their application. This gem proves invaluable in debugging efforts, offering insights into how and where queries are generated.

Configuration for ActiveRecordQueryTrace

To leverage active_record_query_trace for our purpose, a specific configuration was employed:

if defined?(ActiveRecordQueryTrace)
  ActiveRecordQueryTrace.enabled = ENV['ENABLE_QUERY_TRACE'].to_s.downcase == 'true'
  ActiveRecordQueryTrace.level = :full
  ActiveRecordQueryTrace.query_type = :all
  ActiveRecordQueryTrace.suppress_logging_of_db_reads = false
  ActiveRecordQueryTrace.ignore_cached_queries = true
  ActiveRecordQueryTrace.lines = 0
  ActiveRecordQueryTrace.colorize = true

This configuration was meticulously crafted to ensure that every query, regardless of its nature, was logged with a complete backtrace. The use of environment variables for enabling the trace allows for flexible deployment across different environments, ensuring that this powerful debugging feature is only activated when necessary.


Leave a comment