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(team): cache product_intents on team serializer per team (#57610)

Paul D'Ambraf61a985a0fe5
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 81372f2ed1be..77b4272447fc 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -46,6 +46,7 @@ from posthog.models.group_type_mapping import cached_group_types_for_team
from posthog.models.organization import OrganizationMembership
from posthog.models.product_intent.product_intent import (
ProductIntentSerializer,
+ cached_product_intents_for_team,
enqueue_product_activation_calc_debounced,
)
from posthog.models.project import Project
@@ -560,9 +561,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
# we've already enqueued for this team in the last 24h. 99% of renders
# become a cache hit; the remaining ones still enqueue exactly as before.
enqueue_product_activation_calc_debounced(obj.id)
- return ProductIntent.objects.filter(team=obj).values(
- "product_type", "created_at", "onboarding_completed_at", "updated_at"
- )
+ return cached_product_intents_for_team(obj.id)
@extend_schema_field(serializers.DictField(child=serializers.BooleanField()))
@tracer.start_as_current_span("team_serializer.managed_viewsets")
diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.py
index 2fff08708bec..f6cfc27c8001 100644
--- a/posthog/models/product_intent/product_intent.py
+++ b/posthog/models/product_intent/product_intent.py
@@ -1,8 +1,10 @@
from datetime import UTC, datetime
-from typing import Optional
+from typing import Any, Optional
from django.core.cache import cache
-from django.db import models
+from django.db import models, transaction
+from django.db.models.signals import post_delete, post_save, pre_save
+from django.dispatch import receiver
import structlog
from celery import shared_task
@@ -18,7 +20,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import RootTeamMixin, UUIDTModel
from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed
-from posthog.utils import get_instance_realm
+from posthog.utils import get_instance_realm, get_safe_cache, safe_cache_delete, safe_cache_set
from products.dashboards.backend.models.dashboard import Dashboard
from products.error_tracking.backend.models import ErrorTrackingIssue
@@ -375,3 +377,66 @@ def enqueue_product_activation_calc_debounced(team_id: int) -> bool:
calculate_product_activation.delay(team_id, only_calc_if_days_since_last_checked=1)
return True
return False
+
+
+PRODUCT_INTENTS_CACHE_TTL_SECONDS = 60 * 60
+
+
+def _team_product_intents_cache_key(team_id: int) -> str:
+ return f"team_serializer:product_intents:{team_id}"
+
+
+def _fetch_product_intents(team_id: int) -> list[dict[str, Any]]:
+ return list(
+ ProductIntent.objects.filter(team_id=team_id).values(
+ "product_type", "created_at", "onboarding_completed_at", "updated_at"
+ )
+ )
+
+
+def cached_product_intents_for_team(team_id: int) -> list[dict[str, Any]]:
+ """Per-team cache for the product_intents response on the team serializer.
+
+ Production traces showed `team_serializer.product_intents` taking up to 532ms
+ on the home view. The query result changes only when a ProductIntent row writes
+ or deletes; the post_save / post_delete receivers below invalidate immediately.
+ A 1h TTL caps staleness for any path that bypasses the ORM signals.
+ """
+ cache_key = _team_product_intents_cache_key(team_id)
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached
+ result = _fetch_product_intents(team_id)
+ safe_cache_set(cache_key, result, timeout=PRODUCT_INTENTS_CACHE_TTL_SECONDS)
+ return result
+
+
+def _invalidate_product_intents_cache(team_id: int) -> None:
+ safe_cache_delete(_team_product_intents_cache_key(team_id))
+ transaction.on_commit(lambda: safe_cache_delete(_team_product_intents_cache_key(team_id)))
+
+
+@receiver(pre_save, sender=ProductIntent)
+def _capture_original_team_id(sender: type[ProductIntent], instance: ProductIntent, **kwargs: Any) -> None:
+ # Stash the persisted team_id before save so post_save can invalidate the previous
+ # team's cache when an intent is reassigned (instance.team_id != original).
+ # For new rows the filter returns None (no row yet), which is the right value to stash.
+ try:
+ instance._original_team_id = ( # type: ignore[attr-defined]
+ ProductIntent.objects.filter(pk=instance.pk).values_list("team_id", flat=True).first()
+ )
+ except Exception:
+ instance._original_team_id = None # type: ignore[attr-defined]
+
+
+@receiver(post_save, sender=ProductIntent)
+def _invalidate_product_intents_on_save(sender: type[ProductIntent], instance: ProductIntent, **kwargs: Any) -> None:
+ _invalidate_product_intents_cache(instance.team_id)
+ original_team_id = getattr(instance, "_original_team_id", None)
+ if original_team_id is not None and original_team_id != instance.team_id:
+ _invalidate_product_intents_cache(original_team_id)
+
+
+@receiver(post_delete, sender=ProductIntent)
+def _invalidate_product_intents_on_delete(sender: type[ProductIntent], instance: ProductIntent, **kwargs: Any) -> None:
+ _invalidate_product_intents_cache(instance.team_id)
diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.py
index 74a1ca335ed9..f7e58c603610 100644
--- a/posthog/models/test/test_product_intent.py
+++ b/posthog/models/test/test_product_intent.py
@@ -17,9 +17,13 @@ from posthog.models.hog_flow.hog_flow import HogFlow
from posthog.models.insight import Insight
from posthog.models.product_intent.product_intent import (
ProductIntent,
+ _fetch_product_intents,
+ _team_product_intents_cache_key,
+ cached_product_intents_for_team,
calculate_product_activation,
enqueue_product_activation_calc_debounced,
)
+from posthog.models.team.team import Team
from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.utils import get_instance_realm
@@ -836,3 +840,72 @@ class TestEnqueueProductActivationCalcDebounced(BaseTest):
assert mock_log.call_args.args == ("product_activation_debounce_cache_failure",)
assert mock_log.call_args.kwargs == {"team_id": self.team.id, "exc_info": True}
mock_capture.assert_called_once()
+
+
+class TestCachedProductIntentsForTeam(BaseTest):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+
+ def test_caches_results(self):
+ ProductIntent.objects.create(team=self.team, product_type=ProductKey.SURVEYS)
+
+ with patch(
+ "posthog.models.product_intent.product_intent._fetch_product_intents",
+ wraps=_fetch_product_intents,
+ ) as spy:
+ first = cached_product_intents_for_team(self.team.id)
+ second = cached_product_intents_for_team(self.team.id)
+ assert spy.call_count == 1
+ assert first == second
+ assert {row["product_type"] for row in first} == {"surveys"}
+
+ @parameterized.expand(
+ [
+ (
+ "create",
+ lambda self: ProductIntent.objects.create(team=self.team, product_type=ProductKey.FEATURE_FLAGS),
+ ),
+ (
+ "delete",
+ lambda self: ProductIntent.objects.get(team=self.team, product_type=ProductKey.EXPERIMENTS).delete(),
+ ),
+ ]
+ )
+ def test_invalidates_on_signal(self, _name, mutate):
+ # Seed an existing intent so the delete path has something to remove and both
+ # cases share the same starting point.
+ ProductIntent.objects.create(team=self.team, product_type=ProductKey.EXPERIMENTS)
+ cached_product_intents_for_team(self.team.id)
+ assert cache.get(_team_product_intents_cache_key(self.team.id)) is not None
+
+ with self.captureOnCommitCallbacks(execute=True):
+ mutate(self)
+
+ assert cache.get(_team_product_intents_cache_key(self.team.id)) is None
+
+ def test_invalidates_both_teams_on_reassignment(self):
+ # Codex P2: when an intent's team_id changes, the previous team's cache must
+ # also be evicted, otherwise its /api/users/@me/ payload returns the moved
+ # intent for up to PRODUCT_INTENTS_CACHE_TTL_SECONDS.
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.SURVEYS)
+ cached_product_intents_for_team(self.team.id)
+ cached_product_intents_for_team(other_team.id)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ intent.team = other_team
+ intent.save()
+
+ assert cache.get(_team_product_intents_cache_key(self.team.id)) is None
+ assert cache.get(_team_product_intents_cache_key(other_team.id)) is None
+
+ def test_isolates_per_team(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ ProductIntent.objects.create(team=self.team, product_type=ProductKey.SURVEYS)
+ ProductIntent.objects.create(team=other_team, product_type=ProductKey.EXPERIMENTS)
+
+ team_a = cached_product_intents_for_team(self.team.id)
+ team_b = cached_product_intents_for_team(other_team.id)
+ assert {row["product_type"] for row in team_a} == {"surveys"}
+ assert {row["product_type"] for row in team_b} == {"experiments"}