Skip to content

: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.

fix(data-warehouse): remove N+1 in managed sources list (#72860)

Paul D'Ambraeac71b20c508
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index b858c405e6bd..5bb202010d46 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -19,6 +19,7 @@ import temporalio
from dateutil import parser
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_field
from openai import APIConnectionError
+from opentelemetry import trace
from psycopg import OperationalError
from rest_framework import filters, serializers, status, viewsets
from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
@@ -1747,6 +1748,24 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
]
return super().get_throttles()
+ def finalize_response(self, request: Request, response: Response, *args: Any, **kwargs: Any) -> Response:
+ response = super().finalize_response(request, response, *args, **kwargs)
+ # Tag the request span with the two things that drive source-list load cost — source count and
+ # total serialized schema count — so the historically-slow list endpoint is diagnosable in
+ # tracing. Done here rather than by overriding `list`, since a method named `list` would shadow
+ # the builtin `list[...]` type used in annotations elsewhere in this class. Guarded for shape
+ # because finalize_response also runs for error responses (no `results`) and other actions.
+ if self.action == "list" and isinstance(response.data, dict):
+ results = response.data.get("results")
+ if isinstance(results, list):
+ span = trace.get_current_span()
+ span.set_attribute("data_warehouse.sources.count", len(results))
+ span.set_attribute(
+ "data_warehouse.sources.schemas.count",
+ sum(len(source.get("schemas") or []) for source in results if isinstance(source, dict)),
+ )
+ return response
+
def get_serializer_class(self) -> type[serializers.Serializer]:
if self.action == "create":
return ExternalDataSourceCreateSerializer
@@ -1769,8 +1788,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
def safely_get_queryset(self, queryset):
return (
queryset.exclude(deleted=True)
+ # created_by (FK) and revenue_analytics_config (reverse 1:1) are read per source during
+ # serialization. select_related folds them into the main query instead of firing one
+ # extra SELECT per source — the reverse 1:1 was an unprefetched N+1 that dominated the
+ # list load (up to one query, and a get_or_create write, per source).
+ .select_related("created_by", "revenue_analytics_config")
.prefetch_related(
- "created_by",
Prefetch(
"jobs",
queryset=ExternalDataJob.objects.filter(status="Completed", team_id=self.team_id).order_by(
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index a8592680e05d..911c4dc8354b 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -6,12 +6,13 @@ from datetime import date, timedelta
from typing import Any, cast
from freezegun import freeze_time
-from posthog.test.base import APIBaseTest, FuzzyInt
+from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, Mock, PropertyMock, patch
from django.conf import settings
from django.db import connection
from django.test import SimpleTestCase, override_settings
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
import psycopg
@@ -2089,19 +2090,32 @@ class TestExternalDataSource(APIBaseTest):
assert "'private_key'" in response.json()["message"]
assert "'private_key_id'" in response.json()["message"]
- def test_list_external_data_source(self):
+ def test_list_external_data_source_query_count_does_not_scale_with_sources(self):
+ # N+1 regression guard: created_by, revenue_analytics_config, schemas and the latest job are
+ # all fetched up front, so listing must cost the same number of queries regardless of how many
+ # sources exist. Comparing two source counts catches a re-introduced per-source query (e.g.
+ # dropping select_related on the revenue_analytics_config reverse 1:1) without pinning a magic
+ # number. A warm-up request first primes any per-process caches so the two measurements match.
self._create_external_data_source()
self._create_external_data_source()
+ self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")
- # A cached instance setting lookup can shave off one query depending on test order.
- # The list no longer builds the full HogQL Database (only needed to serialize table columns,
- # which the list omits), so it's much cheaper than the single-source read path.
- with self.assertNumQueries(FuzzyInt(13, 15)):
+ with CaptureQueriesContext(connection) as two_sources:
response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")
- payload = response.json()
-
self.assertEqual(response.status_code, 200)
- self.assertEqual(len(payload["results"]), 2)
+ self.assertEqual(len(response.json()["results"]), 2)
+
+ self._create_external_data_source()
+ self._create_external_data_source()
+ with CaptureQueriesContext(connection) as four_sources:
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")
+ self.assertEqual(len(response.json()["results"]), 4)
+
+ self.assertEqual(
+ len(four_sources.captured_queries),
+ len(two_sources.captured_queries),
+ "Listing external data sources should not issue additional queries per source",
+ )
def test_list_omits_table_columns_but_retrieve_includes_them(self):
source = ExternalDataSource.objects.create(