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(caching): share query_cache RedisCluster client process-wide (#61363)

Paul D'Ambra9d1d07ec51d9
diff --git a/posthog/caching/redis_cluster_connection_factory.py b/posthog/caching/redis_cluster_connection_factory.py
index 1d0c18b54389..d821648a4a58 100644
--- a/posthog/caching/redis_cluster_connection_factory.py
+++ b/posthog/caching/redis_cluster_connection_factory.py
@@ -1,7 +1,9 @@
+import os
import threading
from django.conf import settings
from django.core.cache import caches
+from django.core.exceptions import ImproperlyConfigured
import structlog
from django_redis.pool import ConnectionFactory
@@ -27,37 +29,84 @@ class RedisClusterConnectionFactory(ConnectionFactory):
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.
+
+ Discovered clients are cached at class scope (process-global), mirroring
+ django_redis's ConnectionFactory._pools. Django builds a new cache client --
+ and therefore a new factory instance -- per request, and `caches` is
+ thread-local, so per-instance state would be discarded constantly and every
+ request thread would re-run discovery. Class-level state is shared across all
+ instances, so discovery runs once per process and the post-fork prewarm
+ populates the same client the request threads read.
+
+ A RedisCluster holds open sockets, so the cache is pid-bound and rediscovered
+ after a fork (see _reset_if_forked) -- workers must never share inherited file
+ descriptors.
+
+ This relies on the client being long-lived, so CLOSE_CONNECTION is
+ unsupported on this alias and rejected in __init__: django_redis closes
+ connections per request when it is set, which would tear down and rediscover
+ the shared client on every request -- the exact per-request discovery this
+ class exists to avoid.
"""
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self._cluster_clients: dict[str, RedisCluster] = {}
- self._lock = threading.Lock()
+ # Class scope (process-global), not per-instance -- see the class docstring.
+ _cluster_clients: dict[str, RedisCluster] = {}
+ _lock = threading.Lock()
+ _owner_pid: int | None = None
+
+ def __init__(self, options: dict) -> None:
+ super().__init__(options)
+ close_connection = options.get("CLOSE_CONNECTION", getattr(settings, "DJANGO_REDIS_CLOSE_CONNECTION", False))
+ if close_connection:
+ raise ImproperlyConfigured(
+ "CLOSE_CONNECTION is not supported on a RedisClusterConnectionFactory alias: "
+ "the cluster client is shared process-wide and long-lived, so closing it per "
+ "request would force topology rediscovery on every request."
+ )
def connect(self, url: str) -> RedisCluster:
- if url not in self._cluster_clients:
+ pid = os.getpid()
+ client = self._cluster_clients.get(url) if self._owner_pid == pid else None
+ if client is None:
with self._lock:
- if url not in self._cluster_clients:
- self._cluster_clients[url] = self._discover_cluster(url)
- return self._cluster_clients[url]
+ self._reset_if_forked(pid)
+ client = self._cluster_clients.get(url)
+ if client is None:
+ client = self._discover_cluster(url)
+ self._cluster_clients[url] = client
+ return client
+
+ @classmethod
+ def _reset_if_forked(cls, pid: int) -> None:
+ # A classmethod so the cache/owner-pid writes land on the class
+ # (process-global) with no `self` in scope to shadow them onto an
+ # instance. Caller must hold _lock.
+ if cls._owner_pid == pid:
+ return
+ if cls._owner_pid is not None:
+ logger.info("redis_cluster_rediscovering_after_fork", previous_pid=cls._owner_pid, pid=pid)
+ cls._cluster_clients.clear()
+ cls._owner_pid = pid
@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()
+ # socket_keepalive enables TCP keepalive on the long-lived pooled
+ # connections -- best-effort protection against an idle LB/NAT silently
+ # dropping them and forcing a reconnect (and fresh discovery) mid-request.
+ # With OS-default keepalive timing this isn't a hard guarantee; tune
+ # socket_keepalive_options below the real idle timeout if drops persist.
+ return RedisCluster.from_url(url, socket_keepalive=True)
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.
+ first cacheable query, putting it on a user's query critical path. Both
+ wsgi.py and asgi.py call this (via the background helper) from a first-request
+ post-fork hook, so discovery runs in the worker process and is warm before the
+ first real query. 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
@@ -70,11 +119,13 @@ def prewarm_query_cache_cluster() -> None:
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.
+ The first-request post-fork hooks (wsgi.py and asgi.py) use this so the
+ blocking cluster discovery never runs inline -- it would block the ASGI event
+ loop, and needlessly delay the first WSGI request. 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,
diff --git a/posthog/caching/test/test_redis_cluster_connection_factory.py b/posthog/caching/test/test_redis_cluster_connection_factory.py
index 2c56578a2d31..48682b632589 100644
--- a/posthog/caching/test/test_redis_cluster_connection_factory.py
+++ b/posthog/caching/test/test_redis_cluster_connection_factory.py
@@ -1,7 +1,15 @@
+import os
+import threading
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
from unittest.mock import MagicMock, patch
+from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
+from parameterized import parameterized
+
from posthog.caching.redis_cluster_connection_factory import (
QUERY_CACHE_ALIAS,
RedisClusterConnectionFactory,
@@ -11,6 +19,16 @@ from posthog.caching.redis_cluster_connection_factory import (
class TestRedisClusterConnectionFactory(TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ RedisClusterConnectionFactory._cluster_clients.clear()
+ RedisClusterConnectionFactory._owner_pid = None
+
+ def tearDown(self) -> None:
+ RedisClusterConnectionFactory._cluster_clients.clear()
+ RedisClusterConnectionFactory._owner_pid = None
+ super().tearDown()
+
def _factory(self) -> RedisClusterConnectionFactory:
return RedisClusterConnectionFactory(options={})
@@ -25,12 +43,12 @@ class TestRedisClusterConnectionFactory(TestCase):
assert first is sentinel
assert second is sentinel
- from_url.assert_called_once_with("redis://node-a:6379")
+ from_url.assert_called_once_with("redis://node-a:6379", socket_keepalive=True)
@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)
+ from_url.side_effect = lambda url, **kwargs: MagicMock(name=url)
factory.connect("redis://node-a:6379")
factory.connect("redis://node-b:6379")
@@ -38,6 +56,117 @@ class TestRedisClusterConnectionFactory(TestCase):
assert from_url.call_count == 2
+ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")
+ def test_discovered_client_is_shared_across_factory_instances(self, from_url: MagicMock) -> None:
+ sentinel = MagicMock()
+ from_url.return_value = sentinel
+
+ # Django builds a fresh factory per request/thread; discovery must still
+ # happen only once because the cache is process-global, not per-instance.
+ first = self._factory().connect("redis://node-a:6379")
+ second = self._factory().connect("redis://node-a:6379")
+
+ assert first is second is sentinel
+ from_url.assert_called_once_with("redis://node-a:6379", socket_keepalive=True)
+
+ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")
+ def test_concurrent_connect_discovers_once_and_returns_one_shared_client(self, from_url: MagicMock) -> None:
+ # A thundering herd of request threads must not each run discovery: the
+ # double-checked lock means exactly one construction even when every
+ # thread races into connect() at the same instant.
+ sentinel = MagicMock()
+ from_url.return_value = sentinel
+
+ thread_count = 16
+ start = threading.Barrier(thread_count)
+ results: list[object] = []
+ results_lock = threading.Lock()
+
+ def worker() -> None:
+ factory = self._factory() # a fresh per-thread factory, as Django builds per request
+ start.wait()
+ client = factory.connect("redis://node-a:6379")
+ with results_lock:
+ results.append(client)
+
+ with ThreadPoolExecutor(max_workers=thread_count) as pool:
+ for future in [pool.submit(worker) for _ in range(thread_count)]:
+ future.result()
+
+ assert from_url.call_count == 1
+ assert results == [sentinel] * thread_count
+
+ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")
+ def test_cache_hit_never_acquires_the_global_lock(self, from_url: MagicMock) -> None:
+ # The lock guards construction only. If it leaked onto the cache-hit path
+ # it would serialize every query-cache access process-wide and block the
+ # server under load, so assert the warm path takes it zero times.
+ from_url.return_value = MagicMock()
+
+ class CountingLock:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self.enter_count = 0
+
+ def __enter__(self) -> None:
+ self.enter_count += 1
+ self._lock.acquire()
+
+ def __exit__(self, *args: object) -> None:
+ self._lock.release()
+
+ counting_lock = CountingLock()
+ with patch.object(RedisClusterConnectionFactory, "_lock", counting_lock):
+ factory = self._factory()
+ factory.connect("redis://node-a:6379") # cold: one construction → one acquire
+ enters_after_warmup = counting_lock.enter_count
+ for _ in range(50):
+ factory.connect("redis://node-a:6379") # warm: must not touch the lock
+
+ assert enters_after_warmup == 1
+ assert counting_lock.enter_count == 1
+
+ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")
+ def test_shared_state_lives_on_the_class_not_the_instance(self, from_url: MagicMock) -> None:
+ # The fork guard only works if _owner_pid and the client cache are
+ # process-global. If either were ever written through `self` it would
+ # shadow onto the instance, every fresh per-request factory would look
+ # unforked, and discovery would run per request again. Pin them to the class.
+ from_url.return_value = MagicMock()
+ factory = self._factory()
+
+ factory.connect("redis://node-a:6379")
+
+ assert RedisClusterConnectionFactory._owner_pid == os.getpid()
+ assert "_owner_pid" not in factory.__dict__
+ assert "_cluster_clients" not in factory.__dict__
+
+ @patch("posthog.caching.redis_cluster_connection_factory.os.getpid")
+ @patch("posthog.caching.redis_cluster_connection_factory.RedisCluster.from_url")
+ def test_connect_rediscovers_after_a_fork(self, from_url: MagicMock, getpid: MagicMock) -> None:
+ # A client discovered pre-fork holds the parent's sockets; once getpid()
+ # changes (the worker is a forked child) connect() must drop the inherited
+ # cache and rediscover so workers never share file descriptors.
+ from_url.side_effect = lambda url, **kwargs: MagicMock(name=url)
+ getpid.return_value = 1000
+ parent_client = self._factory().connect("redis://node-a:6379")
+
+ getpid.return_value = 2000 # forked worker
+ child_client = self._factory().connect("redis://node-a:6379")
+
+ assert child_client is not parent_client
+ assert from_url.call_count == 2
+
+ @parameterized.expand(
+ [
+ ("alias_option", {"CLOSE_CONNECTION": True}, {}),
+ ("global_setting", {}, {"DJANGO_REDIS_CLOSE_CONNECTION": True}),
+ ]
+ )
+ def test_init_rejects_close_connection(self, _name: str, options: dict, settings_overrides: dict) -> None:
+ with self.settings(**settings_overrides), pytest.raises(ImproperlyConfigured):
+ RedisClusterConnectionFactory(options=options)
+
class TestPrewarmQueryCacheCluster(TestCase):
def test_no_op_when_alias_not_configured(self) -> None:
diff --git a/posthog/wsgi.py b/posthog/wsgi.py
index 1a1ae48f63bf..df3254cb1c34 100644
--- a/posthog/wsgi.py
+++ b/posthog/wsgi.py
@@ -11,7 +11,7 @@ import os
from django.core.wsgi import get_wsgi_application
-from posthog.caching.redis_cluster_connection_factory import prewarm_query_cache_cluster
+from posthog.caching.redis_cluster_connection_factory import prewarm_query_cache_cluster_in_background
from posthog.continuous_profiling import start_continuous_profiling
from posthog.otel_instrumentation import initialize_otel
@@ -20,5 +20,25 @@ os.environ.setdefault("SERVER_GATEWAY_INTERFACE", "WSGI")
start_continuous_profiling()
initialize_otel()
-application = get_wsgi_application()
-prewarm_query_cache_cluster()
+_django_application = get_wsgi_application()
+
+# Nginx Unit forks workers from a prototype process that imported this module, so
+# the query_cache RedisCluster must be discovered post-fork: a client built here at
+# import time would be inherited -- sockets and all -- by every worker. Defer the
+# prewarm to the first request so discovery runs in the worker; the factory also
+# pid-guards the cache as a backstop. (start_continuous_profiling/initialize_otel
+# above still run pre-fork here, unlike asgi.py which defers them -- that is a
+# separate, pre-existing concern, not addressed by this change.)
+#
+# Best-effort once-guard: a concurrent first-request race may spawn a couple of
+# redundant prewarm threads, which is harmless -- prewarm is idempotent and the
+# factory dedups discovery under its own lock -- so it intentionally takes no lock.
+_prewarmed = False
+
+
+def application(environ, start_response):
+ global _prewarmed
+ if not _prewarmed:
+ prewarm_query_cache_cluster_in_background()
+ _prewarmed = True
+ return _django_application(environ, start_response)