: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(api): stop /api/projects/ 500ing on broker outage (#65937)
posthog[bot]05ac3922d9be
diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 263deb5fd169..33012af0a6fc 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -65,7 +65,8 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.product_intent.product_intent import (ProductIntent,ProductIntentSerializer,- calculate_product_activation,+ cached_product_intents_for_team,+ enqueue_product_activation_calc_debounced,)from posthog.models.project import Projectfrom posthog.models.team.event_retention import should_enforce_events_retention@@ -930,7 +931,7 @@ class ProjectBackwardCompatSerializer(return TeamSerializer.validate_workflows_config(value)def get_effective_membership_level(self, project: Project) -> Optional[OrganizationMembership.Level]:- team = project.teams.get(pk=project.pk)+ team = project.passthrough_teamreturn self.user_permissions.team(team).effective_membership_leveldef get_has_group_types(self, project: Project) -> bool:@@ -940,7 +941,7 @@ class ProjectBackwardCompatSerializer(return cached_group_types_for_project(project)def get_live_events_token(self, project: Project) -> Optional[str]:- team = project.teams.get(pk=project.pk)+ team = project.passthrough_teamrequest = self.context.get("request")user_id = request.user.id if request and hasattr(request, "user") and request.user.is_authenticated else Nonereturn get_or_mint_live_events_token(team, user_id)@@ -960,12 +961,13 @@ class ProjectBackwardCompatSerializer(})def get_product_intents(self, obj):- project = obj- team = project.passthrough_team- calculate_product_activation.delay(team.id, only_calc_if_days_since_last_checked=1)- return ProductIntent.objects.filter(team=team).values(- "product_type", "created_at", "onboarding_completed_at", "updated_at"- )+ # Mirror TeamSerializer.get_product_intents: debounce-then-enqueue rather than+ # .delay() on every render, and read intents from a per-team cache. The old+ # unconditional .delay() did a broker round-trip on every retrieve and would+ # 500 the endpoint when the broker was unavailable.+ team = obj.passthrough_team+ enqueue_product_activation_calc_debounced(team.id)+ return cached_product_intents_for_team(team.id)@extend_schema_field(serializers.ListField(child=serializers.ChoiceField(choices=[(e.value, e.value) for e in SetupTaskId]))diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex 6b79e41535ca..48d7107b2c57 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -1,5 +1,7 @@from unittest.mock import MagicMock, patch+from django.core.cache import cache+from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIRequestFactory@@ -668,6 +670,22 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore# project_id on a Project equals its own id (Project ↔ Team is 1:1)self.assertEqual(data["project_id"], self.project.id)+ def test_retrieve_project_does_not_500_when_broker_unavailable(self):+ # Regression: get_product_intents used to call calculate_product_activation.delay()+ # on every retrieve, which 500s the whole endpoint when the broker is down. It now+ # goes through the debounced helper, which fails open on broker errors.+ # Clear the cache so the debounce key is unset and the enqueue path actually runs —+ # otherwise the patched .delay() is never reached and this test passes vacuously.+ cache.clear()+ with patch(+ "posthog.models.product_intent.product_intent.calculate_product_activation.delay",+ side_effect=Exception("broker is unavailable"),+ ) as mock_delay:+ response = self.client.get(f"/api/projects/{self.project.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertIn("product_intents", response.json())+ mock_delay.assert_called_once()+def test_new_passthrough_field_writes_through_to_team(self):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex 7552e4b97898..4d2c2b71e067 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -375,7 +375,16 @@ def enqueue_product_activation_calc_debounced(team_id: int) -> bool:capture_exception(e)was_added = Trueif was_added:- calculate_product_activation.delay(team_id, only_calc_if_days_since_last_checked=1)+ try:+ calculate_product_activation.delay(team_id, only_calc_if_days_since_last_checked=1)+ except Exception as e:+ # Broker errors (e.g. kombu.OperationalError when the broker is unavailable)+ # must not 500 the callers — this runs on every team/project retrieve. The+ # debounce key is already set, so the team stays debounced for the window;+ # capture so a chronic broker problem still surfaces in monitoring.+ logger.warning("product_activation_enqueue_failure", team_id=team_id, exc_info=True)+ capture_exception(e)+ return Falsereturn Truereturn Falsediff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex 5cc2438b900b..617cfad4c750 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -841,6 +841,23 @@ class TestEnqueueProductActivationCalcDebounced(BaseTest):assert mock_log.call_args.kwargs == {"team_id": self.team.id, "exc_info": True}mock_capture.assert_called_once()+ def test_broker_failure_falls_open_and_does_not_raise(self):+ # A broker outage (e.g. kombu.OperationalError) on .delay() must not 500 the+ # team/project retrieve endpoints that call this on every render. The helper+ # swallows the error and returns False instead of propagating.+ with (+ patch(+ "posthog.models.product_intent.product_intent.calculate_product_activation.delay",+ side_effect=Exception("broker is unavailable"),+ ),+ patch("posthog.models.product_intent.product_intent.logger.warning") as mock_log,+ patch("posthog.models.product_intent.product_intent.capture_exception") as mock_capture,+ ):+ assert enqueue_product_activation_calc_debounced(self.team.id) is False++ assert mock_log.call_args.args == ("product_activation_enqueue_failure",)+ mock_capture.assert_called_once()+class TestCachedProductIntentsForTeam(BaseTest):def setUp(self):