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(users): refresh person properties at most once an hour per project (#119027)

Paul D'Ambra2eb4d1d1f092
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 1ceea5f32ad0..5c893e5fe4b5 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -594,6 +594,31 @@ class TestUserAPI(APIBaseTest):
self.assertEqual(User.objects.count(), count)
+ @parameterized.expand(
+ [
+ ("same_project", [False, False], 1),
+ ("switched_project", [False, True], 2),
+ ("switched_back_to_earlier_project", [False, True, False], 3),
+ ]
+ )
+ @patch("posthoganalytics.capture")
+ def test_retrieve_current_user_refreshes_person_properties_once_per_project(
+ self, _name, use_new_project_per_request, expected_refreshes, mock_capture
+ ):
+ for use_new_project in use_new_project_per_request:
+ if use_new_project:
+ User.objects.filter(pk=self.user.pk).update(
+ current_organization=self.new_org, current_team=self.new_project
+ )
+ else:
+ User.objects.filter(pk=self.user.pk).update(
+ current_organization=self.organization, current_team=self.team
+ )
+ self.client.get("/api/users/@me/")
+
+ refreshes = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "update user properties"]
+ assert len(refreshes) == expected_refreshes
+
# UPDATING USER
@patch("posthoganalytics.capture")
diff --git a/posthog/api/user.py b/posthog/api/user.py
index ff5602a1864f..445cee23bfe6 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -150,7 +150,7 @@ from posthog.tasks.email import (
send_two_factor_auth_enabled_email,
)
from posthog.user_permissions import UserPermissions
-from posthog.utils import render_template
+from posthog.utils import get_safe_cache, render_template, safe_cache_set
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.dashboards.backend.models.dashboard import Dashboard
@@ -165,6 +165,10 @@ NUM_2FA_BACKUP_CODES = 10
# is refused at the ceiling, so an intro the user already dismissed still reopens and closes.
MAX_PRODUCT_INTROS_SEEN = 100
+# Building the person properties runs several queries. The user's own edits refresh them through
+# "user updated", so the per-request refresh only catches slower drift such as project counts.
+PERSON_PROPERTIES_REFRESH_INTERVAL_SECONDS = 60 * 60
+
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
@@ -231,6 +235,18 @@ class OnboardingSkipRequestSerializer(serializers.Serializer):
)
+def _person_properties_refresh_due(user: User) -> bool:
+ # Store the last refreshed project, not one key per project. A project switch through
+ # AutoProjectMiddleware sends no "user updated", so a switch back to an earlier project
+ # must refresh too.
+ key = f"user_person_properties_refreshed:{user.id}"
+ context = f"{user.current_organization_id}:{user.current_team_id}"
+ if get_safe_cache(key) == context:
+ return False
+ safe_cache_set(key, context, timeout=PERSON_PROPERTIES_REFRESH_INTERVAL_SECONDS)
+ return True
+
+
class UserSerializer(serializers.ModelSerializer):
has_password = serializers.SerializerMethodField()
is_impersonated = serializers.SerializerMethodField()
@@ -830,12 +846,13 @@ class UserSerializer(serializers.ModelSerializer):
# 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()},
- )
+ if _person_properties_refresh_due(instance):
+ 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)