Skip to content

perf(relay): Avoid N+1 project queries when debouncing config invalidations - #130894

Open
sentry[bot] wants to merge 1 commit into
masterfrom
seer/fix-relay-invalidation-n1-query
Open

sentry[bot] wants to merge 1 commit into
masterfrom
seer/fix-relay-invalidation-n1-query

Conversation

@sentry

@sentry sentry Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Fixes an N+1 query observed during project creation (and any other flow writing multiple ProjectOptions inside a single transaction).

Root Cause

When TeamProjectsEndpoint.post runs, it calls apply_default_project_settings inside transaction.atomic, which writes ~10-15 default project options on the new project. Each write goes through ProjectOptionManager.reload_cache -> schedule_invalidate_project_config(project_id=...), which registers an on_commit callback.

On transaction commit, every callback runs _schedule_invalidate_project_config. Each callback issued Project.objects.values_list("organization__id").get(id=project_id) before calling projectconfig_debounce_cache.invalidation.is_debounced, producing repeated identical SELECT "sentry_project"."organization_id" FROM "sentry_project" WHERE "sentry_project"."id" = %s queries even though only the very first callback actually scheduled a task.

Solution

In _schedule_invalidate_project_config, check is_debounced(project_id=project_id) before querying the Project model. If an invalidation for this project is already queued, emit the existing relay.projectconfig_cache.skipped metric and return immediately. The first invocation still looks up organization_id so that organization-level debouncing remains respected.

Legal Boilerplate

Look, I get it. The entity doing business as "Sentry" was incorporated in the State of Delaware in 2015 as Functional Software, Inc. and is gonna need some rights from me in order to utilize my contributions in this here PR. So here's the deal: I retain all rights, title and interest in and to my contributions, and by keeping this boilerplate intact I confirm that Sentry can use, modify, copy, and redistribute my contributions, under Sentry's choice of terms.

Fixes SENTRY-5R56

@sentry <feedback>: Autofix iterates on these changes
@sentry stop iterating: Autofix stops iterating on this run

This PR was automatically generated by Sentry. You can adjust this setting at any time.

@sentry
sentry Bot requested a review from a team as a code owner November 12, 2026 10:43
@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 12, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant