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.

chore(observability): histogram for template.context render duration (#57646)

Paul D'Ambrac9cd3eab2ce8
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 6eca0e68ba60..cadc615d0a4b 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -929,3 +929,44 @@ class TestSharingOverrideProtection(TestCase):
result = tile_filters_override_requested_by_client(request, tile)
assert result == {"breakdown": "region"}
+
+
+class TestTemplateContextHistogram(TestCase):
+ @staticmethod
+ def _count_for_labels(template_name: str, authenticated: str) -> int:
+ from posthog.utils import TEMPLATE_CONTEXT_DURATION_HISTOGRAM
+
+ for metric in TEMPLATE_CONTEXT_DURATION_HISTOGRAM.collect():
+ for sample in metric.samples:
+ if (
+ sample.name.endswith("_count")
+ and sample.labels.get("template_name") == template_name
+ and sample.labels.get("authenticated") == authenticated
+ ):
+ return int(sample.value)
+ return 0
+
+ @parameterized.expand(
+ [
+ ("authenticated", True, "true"),
+ ("anonymous", False, "false"),
+ ]
+ )
+ def test_template_context_duration_histogram_uses_correct_authenticated_label(
+ self, _name: str, authenticated: bool, expected_label: str
+ ):
+ request = RequestFactory().get("/")
+ # Stash the is_authenticated value via a simple attribute on the request
+ # itself; the wrapper reads it via getattr() so it tolerates any user shape.
+ request.user = cast(Any, type("FakeUser", (), {"is_authenticated": authenticated})())
+
+ before = self._count_for_labels("index.html", expected_label)
+
+ # Drive only the label-selection wrapper; bypass the heavy inner body so this
+ # stays a fast, hermetic unit test of the metric plumbing itself.
+ with patch("posthog.utils._build_template_context", return_value={}):
+ from posthog.utils import get_context_for_template
+
+ get_context_for_template("index.html", request)
+
+ assert self._count_for_labels("index.html", expected_label) == before + 1
diff --git a/posthog/utils.py b/posthog/utils.py
index da029ac649fa..2dc0b983efa7 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -46,6 +46,7 @@ from celery.schedules import crontab
from dateutil import parser
from dateutil.relativedelta import relativedelta
from opentelemetry import trace
+from prometheus_client import Histogram
from rest_framework import serializers
from rest_framework.request import Request
from rest_framework.utils.encoders import JSONEncoder
@@ -61,6 +62,16 @@ from posthog.redis import get_client
tracer = trace.get_tracer(__name__)
+# Cardinality is bounded: render_template is only called with the literal template
+# names "index.html", "demo.html", and "render_query.html" — 3 templates × 2 auth
+# states = 6 series total.
+TEMPLATE_CONTEXT_DURATION_HISTOGRAM = Histogram(
+ "posthog_template_context_duration_seconds",
+ "Time spent building the SPA template context (get_context_for_template).",
+ labelnames=["template_name", "authenticated"],
+ buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),
+)
+
if TYPE_CHECKING:
from django.contrib.auth.models import AbstractBaseUser, AnonymousUser
@@ -387,6 +398,17 @@ def get_context_for_template(
request: HttpRequest,
context: Optional[dict] = None,
team_for_public_context: Optional["Team"] = None,
+) -> dict:
+ authenticated = "true" if request.user.is_authenticated else "false"
+ with TEMPLATE_CONTEXT_DURATION_HISTOGRAM.labels(template_name=template_name, authenticated=authenticated).time():
+ return _build_template_context(template_name, request, context, team_for_public_context)
+
+
+def _build_template_context(
+ template_name: str,
+ request: HttpRequest,
+ context: Optional[dict],
+ team_for_public_context: Optional["Team"],
) -> dict:
if context is None:
context = {}