Skip to content

fix(perf): Avoid extra queries in MonitorEnvironmentSerializer#106428

Merged
kcons merged 1 commit intomasterfrom
kcons/noextra
Jan 20, 2026
Merged

fix(perf): Avoid extra queries in MonitorEnvironmentSerializer#106428
kcons merged 1 commit intomasterfrom
kcons/noextra

Conversation

@kcons
Copy link
Copy Markdown
Member

@kcons kcons commented Jan 16, 2026

MonitorEnvironmentSerializer relies on Monitor data, but fetching it via implicit query results in lots of unnecessary queries.
We can avoid this by batch fetching when it isn't cached, and using the cached value when available.
By ensuring the Monitor is cached in MonitorSerializer, where we already have the Monitors, no queries are required.

@kcons kcons requested a review from a team as a code owner January 16, 2026 00:43
@github-actions github-actions bot added the Scope: Backend Automatically applied to PRs that change backend components label Jan 16, 2026
@kcons kcons requested a review from a team January 16, 2026 19:56
@saponifi3d saponifi3d requested a review from wedamija January 16, 2026 20:00
Comment on lines +112 to +128
# Build date_added mapping, starting with cached monitors
date_added_by_monitor_id = {}
uncached_monitor_ids = set[int]()

for monitor_env in item_list:
if monitor_env.is_field_cached("monitor"):
# Extract date_added from cached monitor
date_added_by_monitor_id[monitor_env.monitor_id] = monitor_env.monitor.date_added
else:
# Need to fetch this monitor
uncached_monitor_ids.add(monitor_env.monitor_id)

# Batch query for uncached monitors - only fetch date_added field
if uncached_monitor_ids:
date_added_by_monitor_id.update(
Monitor.objects.filter(id__in=uncached_monitor_ids).values_list("id", "date_added")
)
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.

Nit: No need to change if you don't want to , but a simple way to do this is prefetch_related_objects like

prefetch_related_objects(item_list, "project__organization")

The way you're doing it is more efficient since we bring down fewer fields, but this way is more concise.

@kcons kcons merged commit ff02406 into master Jan 20, 2026
67 checks passed
@kcons kcons deleted the kcons/noextra branch January 20, 2026 23:51
@github-actions github-actions bot locked and limited conversation to collaborators Feb 5, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants