Detecting N+1 Queries in Rails with APM‑Based Monitoring

man in black dress shirt writing on dry-erase board
Learn how to automatically spot N+1 database queries in a Ruby on Rails app using Lescopr's APM‑driven monitoring, with step‑by‑step instructions for beginners.

Introduction

Performance regressions in Ruby on Rails applications frequently stem from hidden database inefficiencies. One of the most common culprits is the N+1 query problem, where a single request unintentionally triggers a cascade of identical SELECT statements. For developers who are just starting out, the concept can feel abstract, and spotting it manually is time‑consuming. This guide walks you through the entire process—starting from zero knowledge—to automatically detect N+1 queries using APM‑driven database monitoring provided by Lescopr. By the end, you’ll have a concrete, observable metric that highlights problematic queries in real time.


Understanding the N+1 Query Problem

What Is an N+1 Query?

An N+1 query occurs when an application loads a collection of records (the "N" part) and then, for each record, issues an additional query to fetch related data (the "+1" part). In Rails, this often happens when iterating over an association without eager loading.

Why It Hurts Performance

  • Increased latency – Each extra query adds round‑trip time to the database.
  • Higher CPU usage – The database must parse and execute many similar statements.
  • Resource contention – More connections can saturate the pool, raising the risk of timeouts.

In production, a single N+1 pattern can inflate request latency by 200 ms or more, directly impacting SLA compliance.

How Traditional Tools Miss It

Standard logging or ad‑hoc profiling captures raw SQL, but without correlation to request context, developers often overlook repetitive patterns. This is where Application Performance Monitoring (APM) shines: it correlates queries with request traces and can flag anomalies automatically.


Setting Up Lescopr APM for Automatic Detection

1. Install the Lescopr Ruby Agent

gem install lescopr-apm

Add the agent to your Gemfile and bundle install. Then initialise it in config/initializers/lescopr.rb:

Lescopr::APM.configure do |config|
  config.api_key = ENV['LESCOPR_API_KEY']
  config.environment = Rails.env
end

2. Enable Database Query Tracing

Lescopr automatically instruments ActiveRecord, but you must enable the query‑pattern detector:

Lescopr::APM.enable_feature(:query_pattern_detection)

3. Define the N+1 Detection Rule

Within the Lescopr dashboard, navigate to Observability → Rules and create a new rule:

  • Name: Detect N+1 Queries
  • Condition: query_count > 1 && query_pattern == "SELECT * FROM ... WHERE id = ?"
  • Threshold: 5 occurrences within a 30‑second window
  • Action: Trigger an alert and annotate the request trace.

4. Verify the Configuration Locally

Run your Rails server in development mode and execute a controller action that loads a collection with associated records. Open the Lescopr UI; you should see a trace labeled "N+1 Query Detected" with the offending SQL pattern highlighted.


Interpreting the Alerts and Acting on Them

5. Review the Annotated Trace

When an alert fires, the Lescopr dashboard presents a timeline:

  • Request ID – Unique identifier for the HTTP request.
  • SQL Calls – Chronological list of queries, with repeats grouped.
  • Heatmap – Visual representation of query latency.

Use this information to pinpoint the exact line of code causing the N+1 pattern.

6. Refactor with Eager Loading

Replace lazy loading (object.association.each) with eager loading using includes or preload:

# Before (potential N+1)
@posts = Post.all
@posts.each { |p| puts p.comments.count }

# After (eager loaded)
@posts = Post.includes(:comments)
@posts.each { |p| puts p.comments.size }

7. Validate the Fix

Re‑run the same request and confirm that the Lescopr alert no longer appears. The query count should drop from N+1 to a single joined query.


Advanced Tips for Ongoing Observability

  • Threshold Tuning – Adjust the alert threshold based on your traffic volume; high‑throughput services may need a higher count to avoid noise.
  • Combine with SLA Dashboards – Correlate N+1 alerts with SLA breach metrics to prioritize remediation.
  • Automate Remediation – Use Lescopr’s webhook integration to trigger CI/CD pipelines that run automated tests when a new N+1 pattern is detected.

Conclusion

Automatic detection of N+1 queries transforms a vague performance symptom into a concrete, actionable alert. By integrating Lescopr’s APM‑driven database monitoring, even developers with no prior observability experience can quickly locate and eliminate inefficient query patterns, improving latency, reducing database load, and keeping SLA commitments intact.

To go further, Lescopr's documentation covers step‑by‑step setup.


Feature Image Alt Text: "Rails developer reviewing performance metrics on a laptop screen"