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.

perf(query): avoid redundant Team re-fetches when building query cache key (#71730)

posthog[bot]f5bcafa9d68c
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 8f1b836c4178..32fb6e1cce78 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from datetime import UTC, datetime, timedelta
from enum import StrEnum
from functools import cache, cached_property
@@ -9,6 +9,7 @@ from typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, Type
from zoneinfo import ZoneInfo
from django.conf import settings as django_settings
+from django.db import OperationalError
import orjson
import structlog
@@ -2425,11 +2426,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
"query": query,
"team_id": self.team.pk,
"hogql_modifiers": to_dict(self.modifiers),
- "products_modifiers": {
- "revenue_analytics": self.team.revenue_analytics_config.to_cache_key_dict(),
- "marketing_analytics": self.team.marketing_analytics_config.to_cache_key_dict(),
- "customer_analytics": self.team.customer_analytics_config.to_cache_key_dict(),
- },
+ "products_modifiers": self._products_modifiers_for_cache(),
"limit_context": self._limit_context_aliased_for_cache,
"timezone": self.team.timezone,
"week_start_day": self.team.week_start_day or WeekStartDay.SUNDAY,
@@ -2451,6 +2448,24 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
return payload
+ def _products_modifiers_for_cache(self) -> dict:
+ # The team-extension configs are loaded lazily and can hit the DB. Under connection-pool
+ # saturation these reads can time out (OperationalError); degrade to a stable "unavailable"
+ # marker instead of 500-ing the whole query. Failures then share one cache namespace,
+ # separate from the successfully-loaded key.
+ def read(name: str, fn: Callable[[], Any]) -> dict | str:
+ try:
+ return fn().to_cache_key_dict()
+ except OperationalError:
+ logger.warning("Failed to read %s for cache key, degrading gracefully", name, exc_info=True)
+ return "unavailable"
+
+ return {
+ "revenue_analytics": read("revenue_analytics_config", lambda: self.team.revenue_analytics_config),
+ "marketing_analytics": read("marketing_analytics_config", lambda: self.team.marketing_analytics_config),
+ "customer_analytics": read("customer_analytics_config", lambda: self.team.customer_analytics_config),
+ }
+
def _get_property_access_restrictions(self) -> list[tuple[str, int]] | None:
"""Returns a sorted list of restricted (property_name, type) pairs for the current user, or None if no restrictions.
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index c4dc717f99fc..015faf8bd0ca 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -9,7 +9,7 @@ from unittest import mock
from django.conf import settings
from django.core.cache import cache
-from django.db import connection
+from django.db import OperationalError, connection
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
@@ -65,6 +65,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.organization import OrganizationMembership
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team.team import Team, WeekStartDay
+from posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyticsConfig
from posthog.query_cache.failures import (
BASE_BACKOFF,
BUDGET_EXTENDED,
@@ -348,6 +349,21 @@ class TestQueryRunner(BaseTest):
"version": 2,
}
+ def test_cache_payload_degrades_when_product_config_read_fails(self):
+ # A DB pool timeout while loading a product config for the cache key must not 500 the whole
+ # query; the failing config degrades to a stable marker while the others still resolve.
+ TestQueryRunner = self.setup_test_query_runner_class()
+ team = Team.objects.create(organization=self.organization, base_currency=CurrencyCode.USD.value)
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)
+
+ with mock.patch.object(
+ TeamRevenueAnalyticsConfig, "to_cache_key_dict", side_effect=OperationalError("query_wait_timeout")
+ ):
+ products_modifiers = runner.get_cache_payload()["products_modifiers"]
+
+ assert products_modifiers["revenue_analytics"] == "unavailable"
+ assert products_modifiers["customer_analytics"]["signup_event"] == {}
+
def test_cache_payload_week_interval(self):
TestQueryRunner = self.setup_test_query_runner_class()
# set the pk directly as it affects the hash in the _cache_key call
diff --git a/posthog/models/team/extensions.py b/posthog/models/team/extensions.py
index befdef536f08..e1a1f355e3b7 100644
--- a/posthog/models/team/extensions.py
+++ b/posthog/models/team/extensions.py
@@ -32,14 +32,20 @@ def get_or_create_team_extension(
"""
defaults = defaults or {}
try:
- return model_class.objects.get(team=team) # type: ignore[attr-defined]
+ config = model_class.objects.get(team=team) # type: ignore[attr-defined]
except model_class.DoesNotExist: # type: ignore[attr-defined]
try:
with transaction.atomic():
- return model_class.objects.create(team=team, **defaults) # type: ignore[attr-defined]
+ config = model_class.objects.create(team=team, **defaults) # type: ignore[attr-defined]
except IntegrityError:
# Race condition: another thread created it first
- return model_class.objects.get(team=team) # type: ignore[attr-defined]
+ config = model_class.objects.get(team=team) # type: ignore[attr-defined]
+
+ # Populate the reverse FK cache with the team we already hold. `.get(team=team)` filters by
+ # team_id but leaves the `team` relation uncached, so a later `config.team.<field>` read (e.g.
+ # base_currency/timezone in to_cache_key_dict) would otherwise fire a fresh Team query per config.
+ config.team = team
+ return config
def register_team_extension_signal(
diff --git a/posthog/models/team/test/test_extensions.py b/posthog/models/team/test/test_extensions.py
new file mode 100644
index 000000000000..d434c53959f3
--- /dev/null
+++ b/posthog/models/team/test/test_extensions.py
@@ -0,0 +1,18 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyticsConfig
+
+
+class TestGetOrCreateTeamExtension(BaseTest):
+ def test_reuses_loaded_team_without_refetching(self) -> None:
+ # Prime the row so the second call takes the get() (not create()) path.
+ get_or_create_team_extension(self.team, TeamRevenueAnalyticsConfig)
+
+ config = get_or_create_team_extension(self.team, TeamRevenueAnalyticsConfig)
+
+ # The config's team FK must be populated with the team we passed in, so reads such as
+ # to_cache_key_dict()'s base_currency don't fire a fresh Team query per config.
+ with self.assertNumQueries(0):
+ assert config.team is self.team
+ config.to_cache_key_dict()