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.

fix(app-context): refresh person properties after the response (#125167)

Paul D'Ambra872296906cc5
diff --git a/posthog/after_response.py b/posthog/after_response.py
new file mode 100644
index 000000000000..023a4768476e
--- /dev/null
+++ b/posthog/after_response.py
@@ -0,0 +1,47 @@
+from collections.abc import Callable
+
+from django.http import HttpRequest, HttpResponseBase
+
+from rest_framework.request import Request
+
+from posthog.exceptions_capture import capture_exception
+
+_CALLBACKS_ATTR = "_posthog_after_response_callbacks"
+
+
+def run_after_response(request: HttpRequest | Request | None, callback: Callable[[], None]) -> None:
+ """
+ Runs `callback` once the response has gone to the client, so the user does not wait for it.
+ Outside a request that passed through `AfterResponseMiddleware`, it runs at once.
+ """
+ callbacks: list[Callable[[], None]] | None = getattr(request, _CALLBACKS_ATTR, None)
+ if callbacks is None:
+ callback()
+ else:
+ callbacks.append(callback)
+
+
+class AfterResponseMiddleware:
+ def __init__(self, get_response: Callable[[HttpRequest], HttpResponseBase]) -> None:
+ self.get_response = get_response
+
+ def __call__(self, request: HttpRequest) -> HttpResponseBase:
+ callbacks: list[Callable[[], None]] = []
+ setattr(request, _CALLBACKS_ATTR, callbacks)
+ response = self.get_response(request)
+ # Django calls these closers after it sends the last byte of the response, and before it
+ # closes the request's database connections. The list is private, so the stubs leave it out.
+ response._resource_closers.extend( # type: ignore[attr-defined]
+ _reporting_failures(callback) for callback in callbacks
+ )
+ return response
+
+
+def _reporting_failures(callback: Callable[[], None]) -> Callable[[], None]:
+ def run() -> None:
+ try:
+ callback()
+ except Exception as e:
+ capture_exception(e)
+
+ return run
diff --git a/posthog/api/user.py b/posthog/api/user.py
index e4593af99624..989d55e77f06 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -49,6 +49,7 @@ from two_factor.utils import default_device
from posthog.schema import UserUIConfiguration
+from posthog.after_response import run_after_response
from posthog.api.email_verification import email_verification_code_verifier
from posthog.api.notification_settings import validate_notification_settings
from posthog.api.oauth.toolbar_service import (
@@ -263,6 +264,15 @@ def _reserve_person_properties_refresh_if_due(user: User) -> bool:
return True
[email protected]_as_current_span("user_serializer.identify")
+def _refresh_person_properties(user: User) -> None:
+ posthoganalytics.capture(
+ distinct_id=user.distinct_id,
+ event="update user properties",
+ properties={"$set": user.get_analytics_metadata()},
+ )
+
+
class UserSerializer(serializers.ModelSerializer):
has_password = serializers.SerializerMethodField()
is_impersonated = serializers.SerializerMethodField()
@@ -897,12 +907,7 @@ class UserSerializer(serializers.ModelSerializer):
# working for clients running ad blockers, which a frontend-side identify would
# silently miss.
if _reserve_person_properties_refresh_if_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()},
- )
+ run_after_response(self.context.get("request"), lambda: _refresh_person_properties(instance))
with tracer.start_as_current_span("user_serializer.default_fields"):
data = super().to_representation(instance)
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 025d836a1262..8319a0009b4a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -181,6 +181,8 @@ _UNVERSIONED_STATIC_MIDDLEWARE = (
MIDDLEWARE = [
"django_prometheus.middleware.PrometheusBeforeMiddleware",
+ # Outside every middleware that can swap the response, so the deferred work rides on the one sent.
+ "posthog.after_response.AfterResponseMiddleware",
"posthog.gzip_middleware.ScopedGZipMiddleware",
# Must precede per_request_logging_context_middleware, the only client-IP reader that runs on
# the request path. AllowIPMiddleware and axes read the IP at or after the view.
diff --git a/posthog/test/test_after_response.py b/posthog/test/test_after_response.py
new file mode 100644
index 000000000000..822c5191c442
--- /dev/null
+++ b/posthog/test/test_after_response.py
@@ -0,0 +1,51 @@
+from unittest import mock
+
+from django.http import HttpRequest, HttpResponse
+from django.test import RequestFactory, SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework.request import Request
+
+from posthog.after_response import AfterResponseMiddleware, run_after_response
+
+
+class TestRunAfterResponse(SimpleTestCase):
+ @parameterized.expand([("django_request", lambda request: request), ("drf_request", Request)])
+ def test_runs_after_the_response_is_closed(self, _name, wrap):
+ calls: list[str] = []
+
+ def view(request: HttpRequest) -> HttpResponse:
+ run_after_response(wrap(request), lambda: calls.append("after response"))
+ calls.append("view")
+ return HttpResponse()
+
+ response = AfterResponseMiddleware(view)(RequestFactory().get("/"))
+ assert calls == ["view"]
+
+ response.close()
+ assert calls == ["view", "after response"]
+
+ def test_runs_at_once_outside_the_middleware(self):
+ calls: list[str] = []
+
+ run_after_response(RequestFactory().get("/"), lambda: calls.append("ran"))
+
+ assert calls == ["ran"]
+
+ def test_reports_a_failure_and_still_runs_the_rest(self):
+ calls: list[str] = []
+ error = ValueError("boom")
+
+ def failing() -> None:
+ raise error
+
+ def view(request: HttpRequest) -> HttpResponse:
+ run_after_response(request, failing)
+ run_after_response(request, lambda: calls.append("second"))
+ return HttpResponse()
+
+ with mock.patch("posthog.after_response.capture_exception") as capture_exception:
+ AfterResponseMiddleware(view)(RequestFactory().get("/")).close()
+
+ capture_exception.assert_called_once_with(error)
+ assert calls == ["second"]