Skip to content

Hotfix(emergency): replace joined Count() aggregates with per-relation subqueries - #2824

Merged
szabozoltan69 merged 1 commit into
masterfrom
fix/emergency-count-query-fanout
Sep 7, 2026
Merged

Hotfix(emergency): replace joined Count() aggregates with per-relation subqueries#2824
szabozoltan69 merged 1 commit into
masterfrom
fix/emergency-count-query-fanout

Conversation

@susilnem

@susilnem susilnem commented Sep 7, 2026

Copy link
Copy Markdown
Member

Problem

GET /api/v2/emergency/{id}/ was timing out (504) for events with a lot of related data. Root cause: EmergencyViewset.get_queryset() computed 3 counts (projects, surge alerts, active deployments) using Count(distinct=True) on 3 separate relations inside one query. Joining unrelated one-to-many relations multiplies rows instead of adding them — for event 5854 that's 98 × 302 × 330 = 9.7 million rows generated just to get 3 numbers, forcing Postgres to sort/group all of it (spilled 6.9 GiB to disk).

Fix

Replaced the 3 joined Count() aggregates with 3 independent correlated subqueries (one per count, no cross-joining). Same result, no row explosion.

Before / After (event 5854)

Before After
Response time timeout (>120s, prod hit 74s → 504) 0.47s
response_activity_count (never returned) 98
active_deployments_count (never returned) 0
surge_alerts_count (never returned) 302

Before / After (event 6646, smaller: old code could finish here)

Before After
Response time 29.65s 0.28s
response_activity_count 7 7
active_deployments_count 0 0
surge_alerts_count 72 72

Values identical before/after: confirms this is a performance fix only, no behavior change.

…ubqueries

- Three Count(distinct=True) annotations joined in one query fanned out
to 9M+ rows for large events, forcing a disk-spilled sort (504s in
prod).
@susilnem
susilnem marked this pull request as ready for review September 7, 2026 12:56
@szabozoltan69
szabozoltan69 merged commit ead0a4a into master Sep 7, 2026
3 checks passed
@szabozoltan69
szabozoltan69 deleted the fix/emergency-count-query-fanout branch September 7, 2026 13:11
@szabozoltan69

Copy link
Copy Markdown
Contributor

Quick and great solution!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants