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(home-view): drop celery broker round-trips on the render path (#57491)

Paul D'Ambraac88939cc33a
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 121b7ad1486a..81372f2ed1be 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -44,7 +44,10 @@ from posthog.models.evaluation_context import EvaluationContext, TeamDefaultEval
from posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig
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, calculate_product_activation
+from posthog.models.product_intent.product_intent import (
+ ProductIntentSerializer,
+ enqueue_product_activation_calc_debounced,
+)
from posthog.models.project import Project
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.setup_tasks import SetupTaskId
@@ -552,7 +555,11 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
@extend_schema_field(serializers.ListField(child=serializers.DictField()))
@tracer.start_as_current_span("team_serializer.product_intents")
def get_product_intents(self, obj):
- calculate_product_activation.delay(obj.id, only_calc_if_days_since_last_checked=1)
+ # Debounce-then-enqueue rather than .delay() on every render. The helper
+ # checks a cache key first and skips the broker round-trip entirely if
+ # 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"
)
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 31b85468dae6..37ebc0b1fa24 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -188,9 +188,8 @@ class TestLoginAPI(APIBaseTest):
CONFIG_AUTO_LOGIN = False
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_user_logs_in_with_email_and_password(self, mock_capture, mock_identify):
+ def test_user_logs_in_with_email_and_password(self, mock_capture):
self.user.is_email_verified = True
self.user.save()
response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})
@@ -203,7 +202,7 @@ class TestLoginAPI(APIBaseTest):
self.assertEqual(response.json()["email"], self.user.email)
# Assert the event was captured.
- mock_capture.assert_called_once_with(
+ mock_capture.assert_any_call(
distinct_id=self.user.distinct_id,
event="user logged in",
properties={"social_provider": ""},
@@ -1361,9 +1360,8 @@ class TestPasswordResetAPI(APIBaseTest):
# Password reset completion
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_user_can_reset_password(self, mock_capture, mock_identify):
+ def test_user_can_reset_password(self, mock_capture):
self.client.logout() # extra precaution to test login
self.user.requested_password_reset_at = datetime.now()
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index d4b150397798..2ca65e865cc2 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -809,7 +809,9 @@ class TestSignupAPI(APIBaseTest):
cast(OrganizationMembership, user.organization_memberships.first()).level,
OrganizationMembership.Level.MEMBER,
)
- self.assertFalse(mock_capture.call_args.kwargs["properties"]["is_organization_first_user"])
+ signup_calls = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user signed up"]
+ assert signup_calls, "expected a 'user signed up' capture call"
+ self.assertFalse(signup_calls[-1].kwargs["properties"]["is_organization_first_user"])
if use_invite and not expired_invite:
# make sure the org invite no longer exists
@@ -840,11 +842,8 @@ class TestSignupAPI(APIBaseTest):
@patch("posthoganalytics.capture")
@mock.patch("social_core.backends.base.BaseAuth.request")
@mock.patch("posthog.api.authentication.get_instance_available_sso_providers")
- @mock.patch("posthog.tasks.user_identify.identify_task")
@pytest.mark.ee
- def test_social_signup_with_allowed_domain_on_self_hosted(
- self, mock_identify, mock_sso_providers, mock_request, mock_capture
- ):
+ def test_social_signup_with_allowed_domain_on_self_hosted(self, mock_sso_providers, mock_request, mock_capture):
self.run_test_for_allowed_domain(mock_sso_providers, mock_request, mock_capture)
@unittest.skip("Skipping until fixed in Python 3.12+")
@@ -852,11 +851,9 @@ class TestSignupAPI(APIBaseTest):
@mock.patch("ee.billing.billing_manager.BillingManager.update_billing_organization_users")
@mock.patch("social_core.backends.base.BaseAuth.request")
@mock.patch("posthog.api.authentication.get_instance_available_sso_providers")
- @mock.patch("posthog.tasks.user_identify.identify_task")
@pytest.mark.ee
def test_social_signup_with_allowed_domain_on_cloud(
self,
- mock_identify,
mock_sso_providers,
mock_request,
mock_update_billing_organization_users,
@@ -871,11 +868,9 @@ class TestSignupAPI(APIBaseTest):
@mock.patch("ee.billing.billing_manager.BillingManager.update_billing_organization_users")
@mock.patch("social_core.backends.base.BaseAuth.request")
@mock.patch("posthog.api.authentication.get_instance_available_sso_providers")
- @mock.patch("posthog.tasks.user_identify.identify_task")
@pytest.mark.ee
def test_social_signup_with_allowed_domain_on_cloud_with_existing_invite(
self,
- mock_identify,
mock_sso_providers,
mock_request,
mock_update_billing_organization_users,
@@ -890,11 +885,9 @@ class TestSignupAPI(APIBaseTest):
@mock.patch("ee.billing.billing_manager.BillingManager.update_billing_organization_users")
@mock.patch("social_core.backends.base.BaseAuth.request")
@mock.patch("posthog.api.authentication.get_instance_available_sso_providers")
- @mock.patch("posthog.tasks.user_identify.identify_task")
@pytest.mark.ee
def test_social_signup_with_allowed_domain_on_cloud_with_existing_expired_invite(
self,
- mock_identify,
mock_sso_providers,
mock_request,
mock_update_billing_organization_users,
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index caf328dfb2e6..502d4b0e2634 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1627,7 +1627,7 @@ def team_api_test_factory():
team=self.team,
)
- @patch("posthog.api.team.calculate_product_activation.delay", MagicMock())
+ @patch("posthog.api.team.enqueue_product_activation_calc_debounced", MagicMock())
@patch("posthog.models.product_intent.ProductIntent.check_and_update_activation", return_value=False)
@patch("posthog.event_usage.report_user_action")
@freeze_time("2024-01-01T00:00:00Z")
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 840c65e4fcf2..5933b22a810b 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -296,9 +296,8 @@ class TestUserAPI(APIBaseTest):
# UPDATING USER
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_update_current_user(self, mock_capture, mock_identify_task):
+ def test_update_current_user(self, mock_capture):
another_org = Organization.objects.create(name="Another Org")
another_team = Team.objects.create(name="Another Team", organization=another_org)
user = self._create_user("[email protected]", password="12345678")
@@ -340,7 +339,10 @@ class TestUserAPI(APIBaseTest):
self.assertEqual(user.has_seen_product_intro_for, {"feature_flags": True})
self.assertEqual(user.role_at_organization, "engineering")
- mock_capture.assert_called_once_with(
+ # UserSerializer.to_representation also fires posthoganalytics.capture
+ # for the "update user properties" identify, so use assert_any_call to
+ # find the "user updated" event we actually care about here.
+ mock_capture.assert_any_call(
event="user updated",
distinct_id=user.distinct_id,
properties={
@@ -361,9 +363,8 @@ class TestUserAPI(APIBaseTest):
},
)
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_user_can_cancel_own_email_change_request(self, _mock_capture, _mock_identify_task):
+ def test_user_can_cancel_own_email_change_request(self, _mock_capture):
self.user.pending_email = "[email protected]"
self.user.save()
@@ -373,20 +374,16 @@ class TestUserAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response_data["pending_email"] is None
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_user_cannot_cancel_email_change_request_if_it_doesnt_exist(self, _mock_capture, _mock_identify_task):
+ def test_user_cannot_cancel_email_change_request_if_it_doesnt_exist(self, _mock_capture):
# Fire a call to the endpoint without priming the User with a pending_email field
response = self.client.patch("/api/users/cancel_email_change_request")
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_set_scene_personalisation_for_user_dashboard_must_be_in_current_team(
- self, _mock_capture, _mock_identify_task
- ):
+ def test_set_scene_personalisation_for_user_dashboard_must_be_in_current_team(self, _mock_capture):
a_third_team = Team.objects.create(name="A Third Team", organization=self.organization)
dashboard_one = Dashboard.objects.create(team=a_third_team, name="Dashboard 1")
@@ -403,9 +400,8 @@ class TestUserAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_set_scene_personalisation_for_user_dashboard_must_exist(self, _mock_capture, _mock_identify_task):
+ def test_set_scene_personalisation_for_user_dashboard_must_exist(self, _mock_capture):
response = self.client.post(
"/api/users/@me/scene_personalisation",
# even if someone tries to send a different user or team they are ignored
@@ -413,9 +409,8 @@ class TestUserAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_set_scene_personalisation_for_user_must_send_dashboard(self, _mock_capture, _mock_identify_task):
+ def test_set_scene_personalisation_for_user_must_send_dashboard(self, _mock_capture):
response = self.client.post(
"/api/users/@me/scene_personalisation",
# even if someone tries to send a different user or team they are ignored
@@ -423,9 +418,8 @@ class TestUserAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_set_scene_personalisation_for_user_must_send_scene(self, _mock_capture, _mock_identify_task):
+ def test_set_scene_personalisation_for_user_must_send_scene(self, _mock_capture):
dashboard_one = Dashboard.objects.create(team=self.team, name="Dashboard 1")
response = self.client.post(
@@ -439,9 +433,8 @@ class TestUserAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_set_scene_personalisation_for_user(self, _mock_capture, _mock_identify_task):
+ def test_set_scene_personalisation_for_user(self, _mock_capture):
another_org = Organization.objects.create(name="Another Org")
another_team = Team.objects.create(name="Another Team", organization=another_org)
user = self._create_user("[email protected]", password="12345678")
@@ -735,9 +728,8 @@ class TestUserAPI(APIBaseTest):
self.user.refresh_from_db()
self.assertEqual(self.user.is_staff, False)
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_can_update_current_organization(self, mock_capture, mock_identify):
+ def test_can_update_current_organization(self, mock_capture):
response = self.client.patch("/api/users/@me/", {"set_current_organization": str(self.new_org.id)})
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()
@@ -752,7 +744,7 @@ class TestUserAPI(APIBaseTest):
self.assertEqual(self.user.current_organization, self.new_org)
self.assertEqual(self.user.current_team, self.new_project)
- mock_capture.assert_called_once_with(
+ mock_capture.assert_any_call(
event="user updated",
distinct_id=self.user.distinct_id,
properties={"updated_attrs": ["current_organization", "current_team"], "$set": mock.ANY},
@@ -763,9 +755,8 @@ class TestUserAPI(APIBaseTest):
},
)
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_can_update_current_project(self, mock_capture, mock_identify):
+ def test_can_update_current_project(self, mock_capture):
team = Team.objects.create(name="Local Team", organization=self.new_org)
response = self.client.patch("/api/users/@me/", {"set_current_team": team.id})
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -780,7 +771,7 @@ class TestUserAPI(APIBaseTest):
self.assertEqual(self.user.current_organization, self.new_org)
self.assertEqual(self.user.current_team, team)
- mock_capture.assert_called_once_with(
+ mock_capture.assert_any_call(
event="user updated",
distinct_id=self.user.distinct_id,
properties={"updated_attrs": ["current_organization", "current_team"], "$set": mock.ANY},
@@ -997,10 +988,9 @@ class TestUserAPI(APIBaseTest):
self.assertIn(result_organization, [self.organization, new_org])
self.assertEqual(self.user.current_organization, result_organization)
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
@patch("posthog.tasks.email.send_password_changed_email.delay")
- def test_user_can_update_password(self, mock_send_password_changed_email, mock_capture, mock_identify):
+ def test_user_can_update_password(self, mock_send_password_changed_email, mock_capture):
user = self._create_user("[email protected]", password="A12345678")
self.client.force_login(user)
@@ -1022,7 +1012,7 @@ class TestUserAPI(APIBaseTest):
user.refresh_from_db()
self.assertTrue(user.check_password("a_new_password"))
- mock_capture.assert_called_once_with(
+ mock_capture.assert_any_call(
event="user updated",
distinct_id=user.distinct_id,
properties={"updated_attrs": ["password"], "$set": mock.ANY},
@@ -1040,12 +1030,9 @@ class TestUserAPI(APIBaseTest):
# Assert password changed email was sent
mock_send_password_changed_email.assert_called_once_with(user.id)
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
@patch("posthog.tasks.email.send_password_changed_email.delay")
- def test_user_with_no_password_set_can_set_password(
- self, mock_send_password_changed_email, mock_capture, mock_identify
- ):
+ def test_user_with_no_password_set_can_set_password(self, mock_send_password_changed_email, mock_capture):
user = self._create_user("[email protected]", password=None)
self.client.force_login(user)
@@ -1067,7 +1054,7 @@ class TestUserAPI(APIBaseTest):
user.refresh_from_db()
self.assertTrue(user.check_password("a_new_password"))
- mock_capture.assert_called_once_with(
+ mock_capture.assert_any_call(
event="user updated",
distinct_id=user.distinct_id,
properties={"updated_attrs": ["password"], "$set": mock.ANY},
@@ -1106,9 +1093,8 @@ class TestUserAPI(APIBaseTest):
user.refresh_from_db()
self.assertTrue(user.check_password("a_new_password"))
- @patch("posthog.tasks.user_identify.identify_task")
@patch("posthoganalytics.capture")
- def test_cannot_update_to_insecure_password(self, mock_capture, mock_identify):
+ def test_cannot_update_to_insecure_password(self, mock_capture):
response = self.client.patch(
"/api/users/@me/",
{"current_password": self.CONFIG_PASSWORD, "password": "123"},
@@ -1131,7 +1117,11 @@ class TestUserAPI(APIBaseTest):
# Password was not changed
self.user.refresh_from_db()
self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD))
- mock_capture.assert_not_called()
+ # The GET on /api/users/@me/ fires the inline identify ("update user properties")
+ # via UserSerializer.to_representation. The 4xx PATCH must NOT fire "user updated"
+ # because the update was rejected.
+ update_calls = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user updated"]
+ assert update_calls == []
def test_user_cannot_update_password_without_current_password(self):
response = self.client.patch("/api/users/@me/", {"password": "12345678"})
diff --git a/posthog/api/user.py b/posthog/api/user.py
index e862a2b97b87..dcc647fa02f9 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -96,7 +96,6 @@ from posthog.rate_limit import (
UserAuthenticationThrottle,
UserEmailVerificationThrottle,
)
-from posthog.tasks import user_identify
from posthog.tasks.email import (
send_email_change_emails,
send_password_changed_email,
@@ -355,13 +354,19 @@ class UserSerializer(serializers.ModelSerializer):
OrganizationDomain.objects.get_sso_enforcement_for_email_address(instance.email, organization=organization)
)
+ def _is_self_request(self, instance: User) -> bool:
+ # True when the requesting user is the same as the user being serialized.
+ # Several SerializerMethodFields short-circuit when this is False so we don't
+ # pay extra queries on staff retrievals or leak per-user data across users.
+ request = self.context.get("request")
+ return bool(request and request.user.id == instance.id)
+
@tracer.start_as_current_span("user_serializer.is_organization_first_user")
def get_is_organization_first_user(self, instance: User) -> bool | None:
# Only compute when the serialized user is the requesting user. Avoids paying an
# extra membership query on every /api/users/@me/ hit for admin/staff flows that
# don't need this field, and ensures invitee attribution can't leak across users.
- request = self.context.get("request")
- if not request or request.user.id != instance.id:
+ if not self._is_self_request(instance):
return None
organization = instance.current_organization
@@ -388,8 +393,7 @@ class UserSerializer(serializers.ModelSerializer):
Only returned when the serialized user is the requesting user — staff retrieving
another account should not see that user's private invites.
"""
- request = self.context.get("request")
- if not request or request.user.id != instance.id or not instance.email:
+ if not self._is_self_request(instance) or not instance.email:
return []
normalized_email = EmailNormalizer.normalize(instance.email)
@@ -613,8 +617,21 @@ class UserSerializer(serializers.ModelSerializer):
return instance
def to_representation(self, instance: Any) -> Any:
- with tracer.start_as_current_span("user_serializer.identify_task_delay"):
- user_identify.identify_task.delay(user_id=instance.id)
+ # Refresh PostHog person properties so the dogfood instance keeps the user's
+ # org/project/role properties current. posthoganalytics.capture is non-blocking
+ # (the SDK ships events on a background thread) so this call doesn't add request
+ # latency. Inline rather than via celery — the previous celery .delay() was a
+ # synchronous broker round-trip that spiked to ~500ms+ in slow traces, which
+ # was the whole reason for moving away from it. Server-side capture also keeps
+ # working for clients running ad blockers, which a frontend-side identify would
+ # silently miss.
+ with tracer.start_as_current_span("user_serializer.identify"):
+ posthoganalytics.capture(
+ distinct_id=instance.distinct_id,
+ event="update user properties",
+ properties={"$set": instance.get_analytics_metadata()},
+ )
+
with tracer.start_as_current_span("user_serializer.default_fields"):
data = super().to_representation(instance)
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.py
index 9bc2c4750f19..4d30c1a1f566 100644
--- a/posthog/tasks/__init__.py
+++ b/posthog/tasks/__init__.py
@@ -25,7 +25,6 @@ from . import (
tasks,
team_access_cache_tasks,
usage_report,
- user_identify,
verify_persons_data_in_sync,
warehouse,
)
@@ -55,7 +54,6 @@ __all__ = [
"tasks",
"team_access_cache_tasks",
"usage_report",
- "user_identify",
"verify_persons_data_in_sync",
"warehouse",
]
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 3d4749203e05..4c30ef56bc5c 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -147,7 +147,6 @@
'posthog.tasks.usage_report.capture_report',
'posthog.tasks.usage_report.send_all_org_usage_reports',
'posthog.tasks.usage_report.send_report_to_billing_service',
- 'posthog.tasks.user_identify.identify_task',
'posthog.tasks.verify_persons_data_in_sync.verify_persons_data_in_sync',
'posthog.tasks.warehouse.validate_data_warehouse_table_columns',
])
diff --git a/posthog/tasks/user_identify.py b/posthog/tasks/user_identify.py
deleted file mode 100644
index ef0bb5a0b818..000000000000
--- a/posthog/tasks/user_identify.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import posthoganalytics
-from celery import shared_task
-
-from posthog.models import User
-
-
-@shared_task(ignore_result=True)
-def identify_task(user_id: int) -> None:
- user = User.objects.get(id=user_id)
- posthoganalytics.capture(
- distinct_id=user.distinct_id,
- event="update user properties",
- properties={"$set": user.get_analytics_metadata()},
- )
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index f7d3da242850..ec5c17b82cbd 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -193,7 +193,7 @@ class TestAutoProjectMiddleware(APIBaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- cls.base_app_num_queries = 53
+ cls.base_app_num_queries = 52
# Create another team that the user does have access to
cls.second_team = create_team(organization=cls.organization, name="Second Life")