Skip to content

Exclude cached queries from N+1 Query issue #117164

@aliismayilov

Description

@aliismayilov

Problem Statement

We've noticed quite a bit of false positive N+1 issues that have a similar pattern. I believe other ORMs also have similar pattern, though our case is based on Rails/ActiveRecord.

Through the lifecycle of a single request, there might be a query like:

Feature.find_by(key: "blabla")
# Filter Load (2.2ms)  SELECT "features".* FROM "features" WHERE "features"."key" = 'blabla' LIMIT 1

The next time the same query is fired, it is loaded from ActiveRecord QueryCache:

Feature.find_by(key: "blabla")
# CACHE Filter Load (0.0ms)  SELECT "features".* FROM "features" WHERE "features"."key" = 'blabla' LIMIT 1

This is correctly tracked by sentry-rails SDK (getsentry/sentry-ruby#1968):
https://github.com/getsentry/sentry-ruby/blob/cdab106225cfc8b6765b612bb34d6263a068dc3c/sentry-rails/lib/sentry/rails/tracing/active_record_subscriber.rb#L40

It is very common to have this kind of queries scattered around the code. They are fast, cheap and the cache comes for free with Rails defaults without having to resort to any kind of memoization. Sentry marks these as N+1 issue, even though the database is touched only once.

Solution Brainstorm

I'd suggest to filter out cached: true spans, so that they are not counted towards N+1 issues.

Product Area

Issues

Metadata

Metadata

Assignees

No fields configured for issues without a type.

Projects

Status
Waiting for: Product Owner

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions