: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(caching): instrument and prewarm query_cache RedisCluster discovery (#60912)
Paul D'Ambra31ba0307936a
diff --git a/posthog/asgi.py b/posthog/asgi.pyindex 3196195f5748..a56291b00749 100644--- a/posthog/asgi.py+++ b/posthog/asgi.py@@ -33,11 +33,13 @@ def _ensure_post_fork_init():if _post_fork_initialized:return+ from posthog.caching.redis_cluster_connection_factory import prewarm_query_cache_cluster_in_backgroundfrom posthog.continuous_profiling import start_continuous_profilingfrom posthog.otel_instrumentation import initialize_otelstart_continuous_profiling()initialize_otel()+ prewarm_query_cache_cluster_in_background()_post_fork_initialized = Truediff --git a/posthog/caching/redis_cluster_connection_factory.py b/posthog/caching/redis_cluster_connection_factory.pyindex 4c56c57f16ea..1d0c18b54389 100644--- a/posthog/caching/redis_cluster_connection_factory.py+++ b/posthog/caching/redis_cluster_connection_factory.py@@ -1,8 +1,18 @@import threading+from django.conf import settings+from django.core.cache import caches++import structlogfrom django_redis.pool import ConnectionFactory+from opentelemetry import tracefrom redis.cluster import RedisCluster+logger = structlog.get_logger(__name__)+tracer = trace.get_tracer(__name__)++QUERY_CACHE_ALIAS = "query_cache"+class RedisClusterConnectionFactory(ConnectionFactory):"""ConnectionFactory for django_redis that creates RedisCluster connections.@@ -12,6 +22,11 @@ class RedisClusterConnectionFactory(ConnectionFactory):Redis(connection_pool=pool) pattern. RedisCluster inherits from Redis andimplements the same command interface, so django_redis's DefaultClient(compression, serialization) works unchanged.++ Constructing a RedisCluster issues COMMAND + CLUSTER SLOTS topology+ discovery. We wrap that construction in a "redis_cluster.discovery" span so+ its place in a trace is visible: nested under a request span means discovery+ is on a user's critical path; a parentless span means it ran during warmup."""def __init__(self, *args, **kwargs):@@ -23,8 +38,48 @@ class RedisClusterConnectionFactory(ConnectionFactory):if url not in self._cluster_clients:with self._lock:if url not in self._cluster_clients:- self._cluster_clients[url] = RedisCluster.from_url(url)+ self._cluster_clients[url] = self._discover_cluster(url)return self._cluster_clients[url]+ @tracer.start_as_current_span("redis_cluster.discovery")+ def _discover_cluster(self, url: str) -> RedisCluster:+ return RedisCluster.from_url(url)+def disconnect(self, connection) -> None:connection.close()+++def prewarm_query_cache_cluster() -> None:+ """Force RedisCluster topology discovery during worker warmup.++ Discovery (COMMAND + CLUSTER SLOTS) otherwise happens lazily on the worker's+ first cacheable query, putting it on a user's query critical path. Issuing a+ trivial read here moves it earlier: to module import under WSGI, and to a+ background thread spawned from the post-fork init hook under ASGI (so it never+ blocks the event loop). Safe to call when the query_cache alias is not+ configured — it is a no-op then.+ """+ if QUERY_CACHE_ALIAS not in settings.CACHES:+ return+ try:+ caches[QUERY_CACHE_ALIAS].get("__prewarm__")+ except Exception:+ logger.warning("prewarm_query_cache_cluster_failure", exc_info=True)+++def prewarm_query_cache_cluster_in_background() -> threading.Thread:+ """Run prewarm_query_cache_cluster() on a daemon thread.++ Callers on an event loop (the ASGI post-fork hook) must not run the blocking+ cluster discovery inline. prewarm_query_cache_cluster swallows and logs its+ own failures, so the thread cannot raise into the interpreter; daemon=True+ keeps a still-running warmup from delaying shutdown. Start this only after+ fork — never at module import on a server that forks workers.+ """+ thread = threading.Thread(+ target=prewarm_query_cache_cluster,+ name="prewarm-query-cache-cluster",+ daemon=True,+ )+ thread.start()+ return threaddiff --git a/posthog/caching/test/test_redis_cluster_connection_factory.py b/posthog/caching/test/test_redis_cluster_connection_factory.pynew file mode 100644index 000000000000..2c56578a2d31--- /dev/null+++ b/posthog/caching/test/test_redis_cluster_connection_factory.py@@ -0,0 +1,86 @@+from unittest.mock import MagicMock, patch++from django.test import TestCase++from posthog.caching.redis_cluster_connection_factory import (+ QUERY_CACHE_ALIAS,+ RedisClusterConnectionFactory,+ prewarm_query_cache_cluster,+ prewarm_query_cache_cluster_in_background,+)+++class TestRedisClusterConnectionFactory(TestCase):+ def _factory(self) -> RedisClusterConnectionFactory:+ return RedisClusterConnectionFactory(options={})++ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")+ def test_connect_constructs_cluster_client_once_per_url(self, from_url: MagicMock) -> None:+ factory = self._factory()+ sentinel = MagicMock()+ from_url.return_value = sentinel++ first = factory.connect("redis://node-a:6379")+ second = factory.connect("redis://node-a:6379")++ assert first is sentinel+ assert second is sentinel+ from_url.assert_called_once_with("redis://node-a:6379")++ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")+ def test_connect_constructs_one_client_per_distinct_url(self, from_url: MagicMock) -> None:+ factory = self._factory()+ from_url.side_effect = lambda url: MagicMock(name=url)++ factory.connect("redis://node-a:6379")+ factory.connect("redis://node-b:6379")+ factory.connect("redis://node-a:6379")++ assert from_url.call_count == 2+++class TestPrewarmQueryCacheCluster(TestCase):+ def test_no_op_when_alias_not_configured(self) -> None:+ with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:+ mock_settings.CACHES = {}+ with patch("posthog.caching.redis_cluster_connection_factory.caches") as mock_caches:+ prewarm_query_cache_cluster()+ mock_caches.__getitem__.assert_not_called()++ def test_issues_trivial_read_when_alias_configured(self) -> None:+ with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:+ mock_settings.CACHES = {QUERY_CACHE_ALIAS: {}}+ with patch("posthog.caching.redis_cluster_connection_factory.caches") as mock_caches:+ prewarm_query_cache_cluster()+ mock_caches[QUERY_CACHE_ALIAS].get.assert_called_once_with("__prewarm__")++ def test_swallows_and_logs_connection_errors(self) -> None:+ with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:+ mock_settings.CACHES = {QUERY_CACHE_ALIAS: {}}+ with patch("posthog.caching.redis_cluster_connection_factory.caches") as mock_caches:+ mock_caches[QUERY_CACHE_ALIAS].get.side_effect = ConnectionError("cluster down")+ with patch("posthog.caching.redis_cluster_connection_factory.logger") as mock_logger:+ prewarm_query_cache_cluster()+ mock_logger.warning.assert_called_once()+++class TestPrewarmInBackground(TestCase):+ def test_runs_prewarm_on_a_completed_daemon_thread(self) -> None:+ with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:+ mock_settings.CACHES = {QUERY_CACHE_ALIAS: {}}+ with patch("posthog.caching.redis_cluster_connection_factory.caches") as mock_caches:+ thread = prewarm_query_cache_cluster_in_background()+ thread.join(timeout=5)+ assert thread.daemon is True+ assert not thread.is_alive()+ mock_caches[QUERY_CACHE_ALIAS].get.assert_called_once_with("__prewarm__")++ def test_thread_never_raises_when_prewarm_fails(self) -> None:+ with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:+ mock_settings.CACHES = {QUERY_CACHE_ALIAS: {}}+ with patch("posthog.caching.redis_cluster_connection_factory.caches") as mock_caches:+ mock_caches[QUERY_CACHE_ALIAS].get.side_effect = ConnectionError("cluster down")+ with patch("posthog.caching.redis_cluster_connection_factory.logger"):+ thread = prewarm_query_cache_cluster_in_background()+ thread.join(timeout=5)+ assert not thread.is_alive()diff --git a/posthog/wsgi.py b/posthog/wsgi.pyindex a412a9a6f58c..1a1ae48f63bf 100644--- a/posthog/wsgi.py+++ b/posthog/wsgi.py@@ -11,6 +11,7 @@ import osfrom django.core.wsgi import get_wsgi_application+from posthog.caching.redis_cluster_connection_factory import prewarm_query_cache_clusterfrom posthog.continuous_profiling import start_continuous_profilingfrom posthog.otel_instrumentation import initialize_otel@@ -20,3 +21,4 @@ os.environ.setdefault("SERVER_GATEWAY_INTERFACE", "WSGI")start_continuous_profiling()initialize_otel()application = get_wsgi_application()+prewarm_query_cache_cluster()