Finding slow ActiveRecord queries with Scout
Once your Rails app begins seeing consistent traffic, slow SQL queries will likely rear their ugly head. Simple things like using find_by_sql can make a big improvement, but how can you easily tell where your app is slowing down?
While PostgreSQL and MySQL can log slow queries, it's difficult to gleam actionable information from this raw stream. The slow query logs lack application context: where's the LOC generating the query? Is this slow all of the time, or just some of the time? Which controller-action or background job is the caller?
Enter Scout.
Scout and the scout_apm
gem help you prioritize your database optimization efforts. Once the gem is installed and the database monitoring addon is enabled, Scout continually analyzes your SQL queries. Slow queries are bubbled up as insights on your app dashboard:
Queries are analyzed across three primary dimensions, helping you focus on database optimizations that will most improve your app:
- Which queries are most impacting app performance? This is based on the total time consumed of each query, where time consumed is the average query latency multiplied by the query throughput.
- Which queries are significant bottlenecks inside web endpoints and background jobs? A single query that is responsible for a large percentage of the time spent in a transaction is a great place to investigate for a performance win.
- Which queries are consistently slow? These are queries that have a high average latency.
When you click on a slow query query insight, you'll see that query's call time information in the context of the calling controller-action:
From there, you can view individual transaction traces where the query occurred and the source code location that's responsible for the query:
TL;DR
Every production Rails app has slow queries: knowing which are most worth your time to optimize is the challenge. Scout helps you prioritize your efforts and tracks queries down to the source and git commit.
Start hunting down those slow ActiveRecord queries today with a 14-day trial of Scout.