:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(dashboards): prefetch alert threshold and subscribers on read paths (#70832)
Thomas Obermüller774320f568e3
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex 5a404e0080b6..8cdaf6ca42ee 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -2260,9 +2260,17 @@"posthog_user"."onboarding_delegated_to_organization_id","posthog_user"."onboarding_delegation_accepted_at","posthog_user"."events_column_config",- "posthog_user"."email_opt_in"+ "posthog_user"."email_opt_in",+ "posthog_threshold"."created_by_id",+ "posthog_threshold"."created_at",+ "posthog_threshold"."id",+ "posthog_threshold"."team_id",+ "posthog_threshold"."insight_id",+ "posthog_threshold"."name",+ "posthog_threshold"."configuration"FROM "posthog_alertconfiguration"LEFT OUTER JOIN "posthog_user" ON ("posthog_alertconfiguration"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_threshold" ON ("posthog_alertconfiguration"."threshold_id" = "posthog_threshold"."id")WHERE "posthog_alertconfiguration"."insight_id" IN (1,2,3,@@ -7730,9 +7738,17 @@"posthog_user"."onboarding_delegated_to_organization_id","posthog_user"."onboarding_delegation_accepted_at","posthog_user"."events_column_config",- "posthog_user"."email_opt_in"+ "posthog_user"."email_opt_in",+ "posthog_threshold"."created_by_id",+ "posthog_threshold"."created_at",+ "posthog_threshold"."id",+ "posthog_threshold"."team_id",+ "posthog_threshold"."insight_id",+ "posthog_threshold"."name",+ "posthog_threshold"."configuration"FROM "posthog_alertconfiguration"LEFT OUTER JOIN "posthog_user" ON ("posthog_alertconfiguration"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_threshold" ON ("posthog_alertconfiguration"."threshold_id" = "posthog_threshold"."id")WHERE "posthog_alertconfiguration"."insight_id" IN (1,2,3,diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 6c98789fe0d2..a4d8fa6a135c 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -33,8 +33,10 @@ from posthog.models.project import Projectfrom posthog.models.quick_filter import QuickFilterfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.signals import mute_selected_signals+from posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Thresholdfrom products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text@@ -681,6 +683,45 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):with self.assertNumQueries(baseline + 11 + 9):self.dashboard_api.get_dashboard(dashboard_id, query_params={"no_items_field": "true"})+ def test_insight_alerts_do_not_nplus1_dashboard_gets(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})++ def _add_insight_with_alerts() -> None:+ insight_id, _ = self.dashboard_api.create_insight({"dashboards": [dashboard_id]})+ threshold = Threshold.objects.create(+ team=self.team,+ insight_id=insight_id,+ created_by=self.user,+ configuration={"type": "absolute", "bounds": {"upper": 1}},+ )+ # one threshold alert and one detector alert — AlertSerializer emits threshold and+ # subscribed_users per alert, the two relations that regress to per-alert queries+ for alert_threshold in (threshold, None):+ alert = AlertConfiguration.objects.create(+ team=self.team,+ insight_id=insight_id,+ created_by=self.user,+ name="alert",+ threshold=alert_threshold,+ condition={"type": "absolute_value"},+ config={"type": "TrendsAlertConfig", "series_index": 0},+ detector_config=None if alert_threshold else {"type": "zscore", "threshold": 3},+ )+ AlertSubscription.objects.create(user=self.user, alert_configuration=alert, created_by=self.user)++ def _dashboard_query_count() -> int:+ with capture_db_queries() as ctx:+ self.dashboard_api.get_dashboard(dashboard_id, query_params={"no_items_field": "true"})+ return len(ctx.captured_queries)++ _add_insight_with_alerts()+ _dashboard_query_count() # warmup: absorbs one-off writes like last_accessed_at+ baseline = _dashboard_query_count()++ _add_insight_with_alerts()+ _add_insight_with_alerts()+ self.assertEqual(_dashboard_query_count(), baseline)+@snapshot_postgres_queriesdef test_listing_dashboards_is_not_nplus1(self) -> None:self.client.logout()diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 5aed2cff1716..7ab274866123 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -1996,7 +1996,11 @@ class DashboardSerializer(DashboardMetadataSerializer):),Prefetch("insight__alertconfiguration_set",- queryset=AlertConfiguration.objects.select_related("created_by"),+ # AlertSerializer emits threshold and subscribed_users per alert; without these,+ # every alert on the dashboard costs two extra queries+ queryset=AlertConfiguration.objects.select_related("created_by", "threshold").prefetch_related(+ "subscribed_users"+ ),to_attr="_prefetched_alerts",),)diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 8fa32770d2cb..1355a91b59a7 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -1558,7 +1558,11 @@ class InsightViewSet(),Prefetch("alertconfiguration_set",- queryset=AlertConfiguration.objects.select_related("created_by"),+ # AlertSerializer emits threshold and subscribed_users per alert; without these,+ # every alert in the list costs two extra queries+ queryset=AlertConfiguration.objects.select_related("created_by", "threshold").prefetch_related(+ "subscribed_users"+ ),to_attr="_prefetched_alerts",),)diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 874f68040464..59379caf3b3d 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -54,7 +54,7 @@ from posthog.models.project import Projectfrom posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.persons import create_person-from products.alerts.backend.models.alert import AlertConfiguration+from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Thresholdfrom products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text@@ -1080,6 +1080,51 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):f"adding insights should not grow the per-request query count.")+ @override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)+ def test_listing_insights_with_alerts_does_not_nplus1(self) -> None:+ url = f"/api/projects/{self.team.id}/insights/?saved=true&limit=30"++ def _create_insight_with_alerts(short_id: str) -> None:+ insight_id, _ = self.dashboard_api.create_insight(+ data={"short_id": short_id, "filters": {"events": [{"id": "$pageview"}]}}+ )+ threshold = Threshold.objects.create(+ team=self.team,+ insight_id=insight_id,+ created_by=self.user,+ configuration={"type": "absolute", "bounds": {"upper": 1}},+ )+ # one threshold alert and one detector alert — AlertSerializer emits threshold and+ # subscribed_users per alert, the two relations that regress to per-alert queries+ for alert_threshold in (threshold, None):+ alert = AlertConfiguration.objects.create(+ team=self.team,+ insight_id=insight_id,+ created_by=self.user,+ name="alert",+ threshold=alert_threshold,+ condition={"type": "absolute_value"},+ config={"type": "TrendsAlertConfig", "series_index": 0},+ detector_config=None if alert_threshold else {"type": "zscore", "threshold": 3},+ )+ AlertSubscription.objects.create(user=self.user, alert_configuration=alert, created_by=self.user)++ _create_insight_with_alerts("first")+ with capture_db_queries() as ctx:+ assert self.client.get(url).status_code == status.HTTP_200_OK+ baseline = len(ctx.captured_queries)++ for n in range(2, 5):+ _create_insight_with_alerts(f"insight-{n}")+ with capture_db_queries() as ctx:+ response = self.client.get(url)+ assert response.status_code == status.HTTP_200_OK+ assert len(response.json()["results"]) == n+ assert len(ctx.captured_queries) == baseline, (+ f"n={n}: {len(ctx.captured_queries)} queries vs baseline {baseline}; "+ f"adding insights with alerts should not grow the per-request query count."+ )+def test_listing_insights_shows_legacy_and_hogql_ones(self) -> None:self.dashboard_api.create_insight(data={