Skip to content

perf(issues): Fix N+1 queries in starred views endpoint#112424

Merged
scttcper merged 2 commits intomasterfrom
scttcper/starred-views-n-plus-1
Apr 8, 2026
Merged

perf(issues): Fix N+1 queries in starred views endpoint#112424
scttcper merged 2 commits intomasterfrom
scttcper/starred-views-n-plus-1

Conversation

@scttcper
Copy link
Copy Markdown
Member

@scttcper scttcper commented Apr 7, 2026

The starred views serializer was calling serialize() individually per item, triggering separate get_attrs() calls for each view - roughly 4N+1 queries for N starred views. Saw this endpoint taking 1.3s in production.

Batch-serialize all views in a single get_attrs() call instead. Also adds prefetch_related for the projects M2M and switches values_list() to .all() so Django's prefetch cache is actually used.

example trace w/ n+1
transaction summary

The starred views serializer was calling serialize() per item, which
triggered separate get_attrs() calls for each starred view — roughly
4N+1 queries for N views. Batch-serialize all views in get_attrs()
instead.

Also adds prefetch_related for the projects M2M and switches
values_list() to .all() so the prefetch cache is actually used.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@github-actions github-actions bot added the Scope: Backend Automatically applied to PRs that change backend components label Apr 7, 2026
@scttcper scttcper marked this pull request as ready for review April 7, 2026 22:13
@scttcper scttcper requested review from a team as code owners April 7, 2026 22:13
Comment on lines +34 to +40
starred_views = (
GroupSearchViewStarred.objects.filter(
organization=organization, user_id=request.user.id
)
.select_related("group_search_view")
.prefetch_related("group_search_view__projects")
)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it might be better to do this in get_attrs instead, so this this is fixed for all callers. You can use prefetch_related_objects to perform on a list of objects and just do it on everything passed to the get_attrs call

Move `prefetch_related` for the projects M2M into `get_attrs` using
`prefetch_related_objects` so all callers benefit, not just the starred
endpoint.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@scttcper scttcper merged commit 691ef34 into master Apr 8, 2026
55 checks passed
@scttcper scttcper deleted the scttcper/starred-views-n-plus-1 branch April 8, 2026 15:51
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.

3 participants