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(otel): tag RedisCluster spans with connection attributes (#84193)

Sam Penningtonb035a4f36977
diff --git a/posthog/otel_instrumentation.py b/posthog/otel_instrumentation.py
index db913d513b16..56a01b50082f 100644
--- a/posthog/otel_instrumentation.py
+++ b/posthog/otel_instrumentation.py
@@ -2,6 +2,7 @@ import os
import atexit
import typing
import logging
+from collections.abc import Sequence
from django.http import HttpRequest, HttpResponse
@@ -48,6 +49,45 @@ def _otel_django_response_hook(span: Span, request: HttpRequest, response: HttpR
span.update_name("HTTP" if http_method == "_OTHER" else f"{http_method} {route}")
+def _otel_redis_request_hook(span: Span, instance: object, args: Sequence[object], kwargs: dict[str, object]) -> None:
+ """Tag cluster-client spans with the connection attributes the instrumentor leaves off.
+
+ opentelemetry-instrumentation-redis reads `db.system` and `net.peer.*` off
+ `client.connection_pool.connection_kwargs`, and returns early for any client that has no
+ `connection_pool`. `redis.cluster.RedisCluster` keeps per-node pools under `nodes_manager`
+ instead, so its spans arrive carrying a command name and nothing else, which hides them from
+ every query that selects Redis spans by `db.system` or groups them by host.
+
+ A command's shard is chosen inside `execute_command`, after this hook runs, so `net.peer.name`
+ is a node from the client's own topology: it identifies the cluster, not the hop that served
+ the command. `db.redis.cluster` marks that distinction.
+ """
+ # This runs inside the traced Redis call, and the instrumentor does not guard hook calls, so a
+ # raise here would fail the command itself. An unfamiliar client shape degrades to an untagged
+ # span instead, which is the behavior without this hook.
+ try:
+ if not span or not span.is_recording() or hasattr(instance, "connection_pool"):
+ return
+
+ startup_nodes = getattr(getattr(instance, "nodes_manager", None), "startup_nodes", None)
+ if not startup_nodes:
+ return
+
+ span.set_attribute("db.system", "redis")
+ span.set_attribute("db.redis.cluster", True)
+ span.set_attribute("net.transport", "ip_tcp")
+
+ node = next(iter(startup_nodes.values()), None)
+ host = getattr(node, "host", None)
+ port = getattr(node, "port", None)
+ if host:
+ span.set_attribute("net.peer.name", host)
+ if port:
+ span.set_attribute("net.peer.port", port)
+ except Exception:
+ logger.debug("otel_redis_request_hook_failed", exc_info=True)
+
+
def initialize_otel():
# App tracing targets a real OTLP collector (dev/prod). In tests, booting the app
# (e.g. posthog/test/test_asgi_lifespan.py imports posthog.asgi) would otherwise arm a
@@ -165,7 +205,7 @@ def instrument_celery(provider: trace.TracerProvider):
def instrument_redis(provider: trace.TracerProvider):
try:
- RedisInstrumentor().instrument(tracer_provider=provider)
+ RedisInstrumentor().instrument(tracer_provider=provider, request_hook=_otel_redis_request_hook)
logger.info("otel_instrumentation_attempt", instrumentor="RedisInstrumentor", status="success")
except Exception as e:
logger.exception("otel_instrumentation_attempt", instrumentor="RedisInstrumentor", status="error", exc_info=e)
diff --git a/posthog/test/test_otel_instrumentation.py b/posthog/test/test_otel_instrumentation.py
index dad96560d2d8..f9bb1ac8d6c8 100644
--- a/posthog/test/test_otel_instrumentation.py
+++ b/posthog/test/test_otel_instrumentation.py
@@ -1,15 +1,26 @@
# posthog/test/test_otel_instrumentation.py
import os
import logging
+from types import SimpleNamespace
+from typing import NoReturn
from unittest import mock
from django.test import SimpleTestCase
from opentelemetry import trace
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from opentelemetry.util.types import AttributeValue
from parameterized import parameterized
-from posthog.otel_instrumentation import _otel_django_request_hook, _otel_django_response_hook, initialize_otel
+from posthog.otel_instrumentation import (
+ _otel_django_request_hook,
+ _otel_django_response_hook,
+ _otel_redis_request_hook,
+ initialize_otel,
+)
class TestOtelInstrumentation(SimpleTestCase):
@@ -132,7 +143,9 @@ class TestOtelInstrumentation(SimpleTestCase):
# Assert RedisInstrumentor call
mock_redis_instrumentor_cls.assert_called_once_with()
- mock_redis_instrumentor_instance.instrument.assert_called_once_with(tracer_provider=mock_provider_instance)
+ mock_redis_instrumentor_instance.instrument.assert_called_once_with(
+ tracer_provider=mock_provider_instance, request_hook=_otel_redis_request_hook
+ )
# Assert PsycopgInstrumentor call
mock_psycopg_instrumentor_cls.assert_called_once_with()
@@ -372,3 +385,43 @@ class TestOtelInstrumentation(SimpleTestCase):
# Assert AIOKafkaInstrumentor call
mock_aio_kafka_instrumentor_cls.assert_called_once_with()
mock_aio_kafka_instrumentor_instance.instrument.assert_called_once_with(tracer_provider=mock_provider_instance)
+
+
+class TestOtelRedisRequestHook(SimpleTestCase):
+ def _span_attributes_after_hook(self, instance: object) -> dict[str, AttributeValue]:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ with provider.get_tracer(__name__).start_as_current_span("GET") as span:
+ _otel_redis_request_hook(span, instance, ("GET", "some-key"), {})
+
+ return dict(exporter.get_finished_spans()[0].attributes or {})
+
+ def test_cluster_client_command_is_attributed_to_a_backend(self) -> None:
+ node = SimpleNamespace(host="cache.example.com", port=6379)
+ instance = SimpleNamespace(nodes_manager=SimpleNamespace(startup_nodes={"cache.example.com:6379": node}))
+
+ self.assertEqual(
+ self._span_attributes_after_hook(instance),
+ {
+ "db.system": "redis",
+ "db.redis.cluster": True,
+ "net.transport": "ip_tcp",
+ "net.peer.name": "cache.example.com",
+ "net.peer.port": 6379,
+ },
+ )
+
+ def test_pooled_client_command_is_left_to_the_instrumentor(self) -> None:
+ instance = SimpleNamespace(connection_pool=SimpleNamespace(connection_kwargs={"host": "cache.example.com"}))
+
+ self.assertEqual(self._span_attributes_after_hook(instance), {})
+
+ def test_client_that_cannot_be_inspected_still_runs_its_command(self) -> None:
+ class ClientWithoutTopology:
+ @property
+ def nodes_manager(self) -> NoReturn:
+ raise RuntimeError("topology unavailable")
+
+ self.assertEqual(self._span_attributes_after_hook(ClientWithoutTopology()), {})