: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
chore(query): collapse dead dual-backend query cache routing (#73331)
Andy Zhao342bff0153c6
diff --git a/conftest.py b/conftest.pyindex f1783a0613dd..6e718bd4844f 100644--- a/conftest.py+++ b/conftest.py@@ -280,3 +280,13 @@ def _clean_persons_db_for_direct_tests(request):if tables:cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} RESTART IDENTITY CASCADE")yield++[email protected](autouse=True)+def _query_cache_raw_redis_uses_fakeredis(monkeypatch):+ """In tests the query_cache alias is backed by LocMem, which has no Redis connection+ to hand out, so raw-client lookups against it get the shared fakeredis instead."""+ from posthog import redis # noqa: PLC0415+ from posthog.caching import cache_size_tracker # noqa: PLC0415++ monkeypatch.setattr(cache_size_tracker, "get_redis_connection", lambda alias: redis.get_client())diff --git a/posthog/caching/cache_size_tracker.py b/posthog/caching/cache_size_tracker.pyindex 78832a490937..065d18c786cf 100644--- a/posthog/caching/cache_size_tracker.py+++ b/posthog/caching/cache_size_tracker.py@@ -3,33 +3,34 @@ from datetime import timedeltafrom typing import Optionalfrom django.conf import settings-from django.core.cache import cache+from django.core.cache import BaseCache, cachesimport structlog+from django_redis import get_redis_connectionfrom prometheus_client import Counter, Histogram+from redis import Redis, RedisCluster-from posthog import redisfrom posthog.cache_utils import cache_for-from posthog.caching.query_cache_routing import BACKEND_CLUSTER, BACKEND_DEFAULT+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIASlogger = structlog.get_logger(__name__)CACHE_EVICTION_COUNTER = Counter("query_cache_size_limit_evictions_total","Cache entries evicted due to per-team size limits",- labelnames=["team_id", "backend"],+ labelnames=["team_id"],)CACHE_EVICTION_BYTES_COUNTER = Counter("query_cache_size_limit_evicted_bytes_total","Bytes evicted due to per-team size limits",- labelnames=["team_id", "backend"],+ labelnames=["team_id"],)CACHE_EVICTION_AGE_HISTOGRAM = Histogram("query_cache_eviction_age_seconds","Age of cache entries at eviction time (seconds since write)",- labelnames=["team_id", "backend"],+ labelnames=["team_id"],buckets=[1800, # 30 min3600, # 1 hour@@ -46,7 +47,7 @@ CACHE_EVICTION_AGE_HISTOGRAM = Histogram(CACHE_SIZE_HISTOGRAM = Histogram("query_cache_team_size_bytes","Distribution of per-team cache sizes in bytes",- labelnames=["team_id", "backend"],+ labelnames=["team_id"],buckets=[1_000_000, # 1MB10_000_000, # 10MB@@ -140,17 +141,24 @@ class TeamCacheSizeTracker:- posthog:cache_total:{team_id} - String counter: total bytes (for O(1) total size lookup)"""- def __init__(self, team_id: int, cache_backend=None, redis_client=None, is_cluster: bool = False):+ def __init__(+ self,+ team_id: int,+ cache_backend: BaseCache | None = None,+ redis_client: Redis | RedisCluster | None = None,+ ):self.team_id = team_id- self._cache = cache_backend or cache- self.redis_client = redis_client or redis.get_client()- self._is_cluster = is_cluster+ self._cache = cache_backend if cache_backend is not None else caches[QUERY_CACHE_ALIAS]+ self.redis_client: Redis | RedisCluster = (+ redis_client if redis_client is not None else get_redis_connection(QUERY_CACHE_ALIAS)+ )self.entries_key = f"posthog:cache_sizes:{{{team_id}}}"self.sizes_key = f"posthog:cache_entry_sizes:{{{team_id}}}"self.total_key = f"posthog:cache_total:{{{team_id}}}"- self._track_write_script = self.redis_client.register_script(TRACK_CACHE_WRITE_SCRIPT)- self._remove_tracking_script = self.redis_client.register_script(REMOVE_TRACKING_SCRIPT)+ # redis-py's stubs omit register_script on RedisCluster; the runtime supports it.+ self._track_write_script = self.redis_client.register_script(TRACK_CACHE_WRITE_SCRIPT) # type: ignore[union-attr]+ self._remove_tracking_script = self.redis_client.register_script(REMOVE_TRACKING_SCRIPT) # type: ignore[union-attr]def set(self, cache_key: str, data: bytes, data_size: int, ttl: int) -> list[str]:"""@@ -176,8 +184,7 @@ class TeamCacheSizeTracker:total_size = self.get_total_size()entry_count = self.redis_client.zcard(self.entries_key)- backend = BACKEND_CLUSTER if self._is_cluster else BACKEND_DEFAULT- CACHE_SIZE_HISTOGRAM.labels(team_id=self.team_id, backend=backend).observe(total_size)+ CACHE_SIZE_HISTOGRAM.labels(team_id=self.team_id).observe(total_size)logger.info("query_cache_write",@@ -235,11 +242,10 @@ class TeamCacheSizeTracker:current_size -= removed_sizeevicted_keys.append(cache_key)- backend = BACKEND_CLUSTER if self._is_cluster else BACKEND_DEFAULT- CACHE_EVICTION_COUNTER.labels(team_id=self.team_id, backend=backend).inc()- CACHE_EVICTION_BYTES_COUNTER.labels(team_id=self.team_id, backend=backend).inc(removed_size)+ CACHE_EVICTION_COUNTER.labels(team_id=self.team_id).inc()+ CACHE_EVICTION_BYTES_COUNTER.labels(team_id=self.team_id).inc(removed_size)eviction_age = time.time() - float(write_timestamp)- CACHE_EVICTION_AGE_HISTOGRAM.labels(team_id=self.team_id, backend=backend).observe(eviction_age)+ CACHE_EVICTION_AGE_HISTOGRAM.labels(team_id=self.team_id).observe(eviction_age)return evicted_keysdiff --git a/posthog/caching/fetch_from_cache.py b/posthog/caching/fetch_from_cache.pyindex b30541dae38f..d23a59818c48 100644--- a/posthog/caching/fetch_from_cache.py+++ b/posthog/caching/fetch_from_cache.py@@ -2,13 +2,15 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import Any, Optional+from django.core.cache import caches+import structlogfrom prometheus_client import Counterfrom posthog.schema import QueryTimingfrom posthog.cache_utils import OrjsonJsonSerializer-from posthog.caching.query_cache_routing import get_query_cache+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIASlogger = structlog.get_logger(__name__)@@ -89,7 +91,7 @@ def split_cached_response_bytes(cached_response_bytes: bytes) -> SplitCachedRespdef fetch_split_cached_response_by_key(cache_key: str, team_id: int) -> Optional[SplitCachedResponse]:- query_cache = get_query_cache()+ query_cache = caches[QUERY_CACHE_ALIAS]try:cached_response_bytes = query_cache.get(cache_key)except Exception:diff --git a/posthog/caching/query_cache_routing.py b/posthog/caching/query_cache_routing.pydeleted file mode 100644index 49d5aa94e30d..000000000000--- a/posthog/caching/query_cache_routing.py+++ /dev/null@@ -1,45 +0,0 @@-from typing import NamedTuple, Union--from django.conf import settings-from django.core.cache import BaseCache, cache, caches--from django_redis import get_redis_connection-from redis import Redis, RedisCluster--from posthog import redis--QUERY_CACHE_ALIAS = "query_cache"--BACKEND_CLUSTER = "cluster"-BACKEND_DEFAULT = "default"---class QueryCacheSelection(NamedTuple):- cache_backend: BaseCache- redis_client: Union[Redis, RedisCluster]- is_cluster: bool---def use_cluster_cache() -> bool:- return QUERY_CACHE_ALIAS in settings.CACHES---def get_query_cache():- if use_cluster_cache():- return caches[QUERY_CACHE_ALIAS]- return cache---def get_query_cache_selection() -> QueryCacheSelection:- if use_cluster_cache():- return QueryCacheSelection(- cache_backend=caches[QUERY_CACHE_ALIAS],- redis_client=get_redis_connection(QUERY_CACHE_ALIAS),- is_cluster=True,- )-- return QueryCacheSelection(- cache_backend=cache,- redis_client=redis.get_client(),- is_cluster=False,- )diff --git a/posthog/caching/redis_cluster_connection_factory.py b/posthog/caching/redis_cluster_connection_factory.pyindex d821648a4a58..03440c6feec6 100644--- a/posthog/caching/redis_cluster_connection_factory.py+++ b/posthog/caching/redis_cluster_connection_factory.py@@ -13,6 +13,8 @@ from redis.cluster import RedisClusterlogger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)+# The alias constant lives here because this module is loaded from settings (via the+# CONNECTION_FACTORY string) and must not import app code.QUERY_CACHE_ALIAS = "query_cache"@@ -105,10 +107,11 @@ def prewarm_query_cache_cluster() -> None:first cacheable query, putting it on a user's query critical path. Bothwsgi.py and asgi.py call this (via the background helper) from a first-requestpost-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.+ first real query. Safe to call when no dedicated cluster is configured — it is+ a no-op then (the query_cache alias points at the default Redis, which needs no+ topology discovery)."""- if QUERY_CACHE_ALIAS not in settings.CACHES:+ if not settings.QUERY_CACHE_REDIS_CLUSTER_URL:returntry:caches[QUERY_CACHE_ALIAS].get("__prewarm__")diff --git a/posthog/caching/test/test_cache_size_tracker.py b/posthog/caching/test/test_cache_size_tracker.pyindex 5d4df1df5ac2..7fecd8711f70 100644--- a/posthog/caching/test/test_cache_size_tracker.py+++ b/posthog/caching/test/test_cache_size_tracker.py@@ -228,7 +228,7 @@ class TestTeamCacheSizeTracker(BaseTest):from django.core.cache.backends.locmem import LocMemCachecluster_cache = LocMemCache("query-cache-test", {})- tracker = TeamCacheSizeTracker(self.team.pk, cache_backend=cluster_cache, is_cluster=True)+ tracker = TeamCacheSizeTracker(self.team.pk, cache_backend=cluster_cache)tracker.purge()data = b"test_data_content"diff --git a/posthog/caching/test/test_query_cache_format.py b/posthog/caching/test/test_query_cache_format.pyindex fc1a4ae6e010..d15c6ca10615 100644--- a/posthog/caching/test/test_query_cache_format.py+++ b/posthog/caching/test/test_query_cache_format.py@@ -1,8 +1,10 @@from posthog.test.base import BaseTest+from django.core.cache import caches+from posthog.cache_utils import OrjsonJsonSerializerfrom posthog.caching.fetch_from_cache import fetch_cached_response_by_key, fetch_split_cached_response_by_key-from posthog.caching.query_cache_routing import get_query_cache+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIASfrom posthog.hogql_queries.query_cache_factory import get_query_cache_manager@@ -38,7 +40,7 @@ class TestQueryCacheWriteFormat(BaseTest):def test_legacy_blobs_written_before_split_rollout_stay_readable(self):cache_key = f"cache_format_test_preexisting_{self.team.pk}"response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}- get_query_cache().set(cache_key, OrjsonJsonSerializer({}).dumps(response), 60)+ caches[QUERY_CACHE_ALIAS].set(cache_key, OrjsonJsonSerializer({}).dumps(response), 60)split = fetch_split_cached_response_by_key(cache_key, self.team.pk)assert split is not Nonediff --git a/posthog/caching/test/test_query_cache_routing.py b/posthog/caching/test/test_query_cache_routing.pydeleted file mode 100644index c227441f7625..000000000000--- a/posthog/caching/test/test_query_cache_routing.py+++ /dev/null@@ -1,26 +0,0 @@-from posthog.test.base import BaseTest--from django.core.cache import cache-from django.test import override_settings--from posthog.caching.query_cache_routing import QUERY_CACHE_ALIAS, get_query_cache, use_cluster_cache---class TestQueryCacheRouting(BaseTest):- def test_returns_default_cache_when_no_cluster_configured(self):- result = get_query_cache()- self.assertIs(result, cache)-- @override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})- def test_returns_default_cache_when_alias_not_in_caches(self):- self.assertFalse(use_cluster_cache())-- @override_settings(- CACHES={- "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},- QUERY_CACHE_ALIAS: {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},- }- )- def test_routes_to_cluster_cache_when_alias_configured(self):- self.assertTrue(use_cluster_cache())- self.assertIsNot(get_query_cache(), cache)diff --git a/posthog/caching/test/test_redis_cluster_connection_factory.py b/posthog/caching/test/test_redis_cluster_connection_factory.pyindex 48682b632589..622a814257c1 100644--- a/posthog/caching/test/test_redis_cluster_connection_factory.py+++ b/posthog/caching/test/test_redis_cluster_connection_factory.py@@ -169,23 +169,23 @@ class TestRedisClusterConnectionFactory(TestCase):class TestPrewarmQueryCacheCluster(TestCase):- def test_no_op_when_alias_not_configured(self) -> None:+ def test_no_op_when_no_cluster_configured(self) -> None:with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:- mock_settings.CACHES = {}+ mock_settings.QUERY_CACHE_REDIS_CLUSTER_URL = Nonewith 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:+ def test_issues_trivial_read_when_cluster_configured(self) -> None:with patch("posthog.caching.redis_cluster_connection_factory.settings") as mock_settings:- mock_settings.CACHES = {QUERY_CACHE_ALIAS: {}}+ mock_settings.QUERY_CACHE_REDIS_CLUSTER_URL = "redis://cluster:6379"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: {}}+ mock_settings.QUERY_CACHE_REDIS_CLUSTER_URL = "redis://cluster:6379"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:@@ -196,7 +196,7 @@ class TestPrewarmQueryCacheCluster(TestCase):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: {}}+ mock_settings.QUERY_CACHE_REDIS_CLUSTER_URL = "redis://cluster:6379"with patch("posthog.caching.redis_cluster_connection_factory.caches") as mock_caches:thread = prewarm_query_cache_cluster_in_background()thread.join(timeout=5)@@ -206,7 +206,7 @@ class TestPrewarmInBackground(TestCase):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: {}}+ mock_settings.QUERY_CACHE_REDIS_CLUSTER_URL = "redis://cluster:6379"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"):diff --git a/posthog/caching/test/test_redis_cluster_keys.py b/posthog/caching/test/test_redis_cluster_keys.pyindex 655a9bf8d580..7b3e8a106887 100644--- a/posthog/caching/test/test_redis_cluster_keys.py+++ b/posthog/caching/test/test_redis_cluster_keys.py@@ -20,7 +20,7 @@ class TestRedisClusterKeySlots(BaseTest):mock_redis = MagicMock()mock_redis.register_script = MagicMock(return_value=MagicMock())- tracker = TeamCacheSizeTracker(team_id, cache_backend=mock_cache, redis_client=mock_redis, is_cluster=True)+ tracker = TeamCacheSizeTracker(team_id, cache_backend=mock_cache, redis_client=mock_redis)slots = {key_slot(tracker.entries_key.encode()),diff --git a/posthog/caching/utils.py b/posthog/caching/utils.pyindex c8c9fe6e3a88..c699f9a4baa5 100644--- a/posthog/caching/utils.py+++ b/posthog/caching/utils.py@@ -1,8 +1,8 @@from datetime import UTC, datetime, timedeltafrom enum import Enum-from typing import Optional, Union+from typing import Optional-from dateutil.parser import isoparse, parser+from dateutil.parser import isoparsefrom posthog.clickhouse.client import sync_executefrom posthog.interval_specs import INTERVAL_SPECS@@ -10,14 +10,6 @@ from posthog.models.event.new_events_schema import events_read_table, use_new_evfrom posthog.models.team.team import Team-def ensure_is_date(candidate: Optional[Union[str, datetime]]) -> Optional[datetime]:- if candidate is None:- return None- if isinstance(candidate, datetime):- return candidate- return parser().parse(candidate)--def largest_teams(limit: int) -> set[int]:# nosemgrep: clickhouse-fstring-param-audit - events table comes from the internal schema gateteams_by_event_count = sync_execute(@@ -45,9 +37,7 @@ def last_refresh_from_cached_result(cached_result: dict | object) -> Optional[dareturn last_refresh-# enum legacy, default, lazyclass ThresholdMode(Enum):- LEGACY = "legacy"DEFAULT = "default"LAZY = "lazy"AI = "ai"diff --git a/posthog/hogql_queries/query_cache.py b/posthog/hogql_queries/query_cache.pyindex 41a0a3e2f2aa..a006016083e3 100644--- a/posthog/hogql_queries/query_cache.py+++ b/posthog/hogql_queries/query_cache.py@@ -13,12 +13,6 @@ from prometheus_client import CollectorRegistry, Counter, Histogramfrom posthog.cache_utils import OrjsonJsonSerializerfrom posthog.caching.cache_size_tracker import TeamCacheSizeTracker-from posthog.caching.query_cache_routing import (- BACKEND_CLUSTER,- BACKEND_DEFAULT,- get_query_cache_selection,- use_cluster_cache,-)from posthog.clickhouse.query_tagging import get_query_tag_valuefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_cache_base import QueryCacheManagerBase@@ -85,28 +79,28 @@ def _create_cache_metrics(registry: Optional[CollectorRegistry] = None) -> Cachehit_counter = Counter(name="posthog_query_cache_hit_total",documentation="Whether we could fetch the query from the cache or not.",- labelnames=[LABEL_TEAM_ID, "cache_hit", "trigger", "backend"],+ labelnames=[LABEL_TEAM_ID, "cache_hit", "trigger"],registry=registry,)write_counter = Counter(name="posthog_query_cache_write_total",documentation="When a query result was persisted in the cache.",- labelnames=[LABEL_TEAM_ID, "backend"],+ labelnames=[LABEL_TEAM_ID],registry=registry,)bytes_counter = Counter(name="posthog_query_cache_write_bytes_total",documentation="Total bytes written to cache (uncompressed JSON)",- labelnames=[LABEL_TEAM_ID, "backend"],+ labelnames=[LABEL_TEAM_ID],registry=registry,)size_histogram = Histogram(name="posthog_query_cache_write_size_bytes",documentation="Distribution of cache write data sizes in bytes (uncompressed JSON)",- labelnames=[LABEL_TEAM_ID, "backend"],+ labelnames=[LABEL_TEAM_ID],buckets=[100, # Small responses < 100B1000, # 100B - 1KB@@ -147,26 +141,21 @@ def is_cache_warming() -> bool:return (get_query_tag_value("trigger") or "").startswith("warming")-def _cache_backend_label() -> str:- return BACKEND_CLUSTER if use_cluster_cache() else BACKEND_DEFAULT--def count_query_cache_hit(team_id: int, hit: str, trigger: str = "") -> None:"""Count cache hit/miss, excluding cache warming requests."""if is_cache_warming():return- backend = _cache_backend_label()with get_cache_metrics_context("query_cache_hits") as metrics:- metrics.hit_counter.labels(team_id=team_id, cache_hit=hit, trigger=trigger, backend=backend).inc()+ metrics.hit_counter.labels(team_id=team_id, cache_hit=hit, trigger=trigger).inc()-def count_cache_write_data(team_id: int, data_size: int, backend: str = BACKEND_DEFAULT) -> None:+def count_cache_write_data(team_id: int, data_size: int) -> None:"""Count cache write operations and data size metrics."""with get_cache_metrics_context("query_cache_writes") as metrics:- metrics.write_counter.labels(team_id=team_id, backend=backend).inc()- metrics.bytes_counter.labels(team_id=team_id, backend=backend).inc(data_size)- metrics.size_histogram.labels(team_id=team_id, backend=backend).observe(data_size)+ metrics.write_counter.labels(team_id=team_id).inc()+ metrics.bytes_counter.labels(team_id=team_id).inc(data_size)+ metrics.size_histogram.labels(team_id=team_id).observe(data_size)class DjangoCacheQueryCacheManager(QueryCacheManagerBase):@@ -192,13 +181,7 @@ class DjangoCacheQueryCacheManager(QueryCacheManagerBase):data_size = len(fresh_response_serialized)# Set cache with per-team size limit enforcement- selection = get_query_cache_selection()- tracker = TeamCacheSizeTracker(- self.team_id,- cache_backend=selection.cache_backend,- redis_client=selection.redis_client,- is_cluster=selection.is_cluster,- )+ tracker = TeamCacheSizeTracker(self.team_id)tracker.set(self.cache_key, fresh_response_serialized, data_size, settings.CACHED_RESULTS_TTL)if target_age:@@ -207,8 +190,7 @@ class DjangoCacheQueryCacheManager(QueryCacheManagerBase):self.remove_last_refresh()# Track cache write metrics- backend = BACKEND_CLUSTER if selection.is_cluster else BACKEND_DEFAULT- count_cache_write_data(self.team_id, data_size, backend=backend)+ count_cache_write_data(self.team_id, data_size)def get_cache_data(self) -> Optional[dict]:from posthog.caching.fetch_from_cache import fetch_cached_response_by_keydiff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 15494a7172d8..c7faaf0979ff 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -670,9 +670,12 @@ if QUERY_CACHE_REDIS_CLUSTER_URL:},"KEY_PREFIX": "posthog",}+else:+ CACHES["query_cache"] = CACHES["default"]if TEST:CACHES["default"] = {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}+ CACHES["query_cache"] = CACHES["default"]# Cache timeout for materialized columns metadata (in seconds)MATERIALIZED_COLUMNS_CACHE_TIMEOUT: int = get_from_env("MATERIALIZED_COLUMNS_CACHE_TIMEOUT", 900, type_cast=int)