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(query): consolidate query result caching into posthog/query_cache (#73425)

Andy Zhaodd25283cd3a8
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index aefe265c2056..5c323490394d 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -99,6 +99,7 @@ jobs:
- 'posthog/models/**'
- 'posthog/hogql/**'
- 'posthog/hogql_queries/**'
+ - 'posthog/query_cache/**'
- 'posthog/settings/**'
- 'posthog/kafka_client/**'
- 'posthog/session/**'
diff --git a/conftest.py b/conftest.py
index 6e718bd4844f..8978779c7edd 100644
--- a/conftest.py
+++ b/conftest.py
@@ -287,6 +287,6 @@ 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
+ from posthog.query_cache import size_tracker # noqa: PLC0415
- monkeypatch.setattr(cache_size_tracker, "get_redis_connection", lambda alias: redis.get_client())
+ monkeypatch.setattr(size_tracker, "get_redis_connection", lambda alias: redis.get_client())
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 51d765178bf7..809c8564affa 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -17,7 +17,7 @@ from rest_framework import status
from posthog.schema import DateRange, EventPropertyFilter, EventsNode, PropertyOperator, TrendsQuery
from posthog.api.test.dashboards import DashboardAPI
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.constants import AvailableFeature
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
from posthog.models import Filter, Team, User
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 73ae7d914ab9..013202d604cb 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -1451,9 +1451,9 @@ class TestExportCacheKeyFlow(APIBaseTest):
)
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
- @patch("products.product_analytics.backend.api.insight.fetch_cached_response_by_key")
+ @patch("products.product_analytics.backend.api.insight.QueryCache")
@mock_exporter_template
- def test_cache_keys_parameter_triggers_direct_cache_lookup(self, mock_fetch_cached, mock_calculate):
+ def test_cache_keys_parameter_triggers_direct_cache_lookup(self, mock_query_cache_cls, mock_calculate):
"""Test that cache_keys param causes InsightSerializer to use direct cache lookup and skip calculation."""
cached_response = {
"results": [{"count": 42}],
@@ -1461,7 +1461,9 @@ class TestExportCacheKeyFlow(APIBaseTest):
"last_refresh": "2024-01-01T00:00:00Z",
"timezone": "UTC",
}
- mock_fetch_cached.return_value = cached_response
+ mock_entry = MagicMock()
+ mock_entry.as_full_response.return_value = cached_response
+ mock_query_cache_cls.return_value.lookup.return_value.entry = mock_entry
cache_keys = {str(self.insight.id): "expected_cache_key_abc123"}
cache_keys_param = quote(json.dumps(cache_keys))
@@ -1469,17 +1471,19 @@ class TestExportCacheKeyFlow(APIBaseTest):
response = self.client.get(f"/shared/{self.sharing_config.access_token}?cache_keys={cache_keys_param}")
assert response.status_code == 200
- mock_fetch_cached.assert_called_once_with("expected_cache_key_abc123", team_id=self.insight.team_id)
+ mock_query_cache_cls.assert_called_once_with(
+ team_id=self.insight.team_id, cache_key="expected_cache_key_abc123"
+ )
mock_calculate.assert_not_called()
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
- @patch("products.product_analytics.backend.api.insight.fetch_cached_response_by_key")
+ @patch("products.product_analytics.backend.api.insight.QueryCache")
@mock_exporter_template
- def test_cache_miss_falls_back_to_normal_calculation(self, mock_fetch_cached, mock_calculate):
+ def test_cache_miss_falls_back_to_normal_calculation(self, mock_query_cache_cls, mock_calculate):
"""Test that cache miss on expected key falls back to normal calculation."""
- from posthog.caching.fetch_from_cache import InsightResult
+ from posthog.caching.insight_result import InsightResult
- mock_fetch_cached.return_value = None # Cache miss
+ mock_query_cache_cls.return_value.lookup.return_value.entry = None # Cache miss
mock_calculate.return_value = InsightResult(
result=[{"count": 50}],
cache_key="calculated_cache_key",
@@ -1494,15 +1498,15 @@ class TestExportCacheKeyFlow(APIBaseTest):
response = self.client.get(f"/shared/{self.sharing_config.access_token}?cache_keys={cache_keys_param}")
assert response.status_code == 200
- mock_fetch_cached.assert_called_once_with("missing_cache_key", team_id=self.insight.team_id)
+ mock_query_cache_cls.assert_called_once_with(team_id=self.insight.team_id, cache_key="missing_cache_key")
mock_calculate.assert_called_once()
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
- @patch("products.product_analytics.backend.api.insight.fetch_cached_response_by_key")
+ @patch("products.product_analytics.backend.api.insight.QueryCache")
@mock_exporter_template
- def test_invalid_cache_keys_param_continues_without_it(self, mock_fetch_cached, mock_calculate):
+ def test_invalid_cache_keys_param_continues_without_it(self, mock_query_cache_cls, mock_calculate):
"""Test that invalid cache_keys parameter is ignored and normal flow continues."""
- from posthog.caching.fetch_from_cache import InsightResult
+ from posthog.caching.insight_result import InsightResult
mock_calculate.return_value = InsightResult(
result=[{"count": 25}],
@@ -1516,8 +1520,8 @@ class TestExportCacheKeyFlow(APIBaseTest):
response = self.client.get(f"/shared/{self.sharing_config.access_token}?cache_keys=not_valid_json")
assert response.status_code == 200
- # fetch_cached_response_by_key should not be called since cache_keys parsing failed
- mock_fetch_cached.assert_not_called()
+ # QueryCache should not be constructed since cache_keys parsing failed
+ mock_query_cache_cls.assert_not_called()
mock_calculate.assert_called_once()
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index b725e99f98a3..fc30c3871410 100644
--- a/posthog/caching/calculate_results.py
+++ b/posthog/caching/calculate_results.py
@@ -21,7 +21,7 @@ from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hash
if TYPE_CHECKING:
- from posthog.caching.fetch_from_cache import InsightResult
+ from posthog.caching.insight_result import InsightResult
from posthog.rbac.user_access_control import UserAccessControl
@@ -91,7 +91,7 @@ def calculate_for_query_based_insight(
analytics_props: Optional[AnalyticsProps] = None,
allow_raw_results: bool = False,
) -> "InsightResult":
- from posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResult
+ from posthog.caching.insight_result import InsightResult, NothingInCacheResult
tag_queries(**get_team_query_tags(team), insight_id=insight.pk)
if dashboard:
diff --git a/posthog/caching/insight_result.py b/posthog/caching/insight_result.py
new file mode 100644
index 000000000000..1612d34863ae
--- /dev/null
+++ b/posthog/caching/insight_result.py
@@ -0,0 +1,35 @@
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any, Optional
+
+from posthog.schema import QueryTiming
+
+
+@dataclass(frozen=True)
+class InsightResult:
+ result: Optional[Any]
+ last_refresh: Optional[datetime]
+ cache_key: Optional[str]
+ is_cached: bool
+ timezone: Optional[str]
+ has_more: Optional[bool] = None
+ next_allowed_client_refresh: Optional[datetime] = None
+ cache_target_age: Optional[datetime] = None
+ timings: Optional[list[QueryTiming]] = None
+ columns: Optional[list] = None
+ query_status: Optional[Any] = None
+ hogql: Optional[str] = None
+ types: Optional[list] = None
+ # A ResolvedDateRangeResponse-shaped dict — the field carries model_dump output
+ resolved_date_range: Optional[dict] = None
+
+
+@dataclass(frozen=True)
+class NothingInCacheResult(InsightResult):
+ result: Optional[Any] = None
+ last_refresh: Optional[datetime] = None
+ cache_key: Optional[str] = None
+ is_cached: bool = False
+ timezone: Optional[str] = None
+ next_allowed_client_refresh: Optional[datetime] = None
+ columns: Optional[list] = None
diff --git a/posthog/caching/test/test_query_cache_format.py b/posthog/caching/test/test_query_cache_format.py
deleted file mode 100644
index d15c6ca10615..000000000000
--- a/posthog/caching/test/test_query_cache_format.py
+++ /dev/null
@@ -1,48 +0,0 @@
-from posthog.test.base import BaseTest
-
-from django.core.cache import caches
-
-from posthog.cache_utils import OrjsonJsonSerializer
-from posthog.caching.fetch_from_cache import fetch_cached_response_by_key, fetch_split_cached_response_by_key
-from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
-from posthog.hogql_queries.query_cache_factory import get_query_cache_manager
-
-
-class TestQueryCacheWriteFormat(BaseTest):
- def test_writes_split_format_and_round_trips(self):
- response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}
- manager = get_query_cache_manager(team=self.team, cache_key=f"cache_format_test_{self.team.pk}", insight_id=1)
-
- manager.set_cache_data(response=response, target_age=None)
-
- split = fetch_split_cached_response_by_key(manager.cache_key, self.team.pk)
- assert split is not None
- assert split.results_bytes == b'[{"data":[1]}]'
- assert fetch_cached_response_by_key(manager.cache_key, self.team.pk) == {
- "is_cached": False,
- "results": [{"data": [1]}],
- "cache_key": "k",
- }
-
- def test_non_list_results_write_legacy_format(self):
- response = {"is_cached": False, "results": None, "cache_key": "k"}
- manager = get_query_cache_manager(
- team=self.team, cache_key=f"cache_format_test_legacy_{self.team.pk}", insight_id=1
- )
-
- manager.set_cache_data(response=response, target_age=None)
-
- split = fetch_split_cached_response_by_key(manager.cache_key, self.team.pk)
- assert split is not None
- assert split.results_bytes is None
- assert split.header == response
-
- 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"}
- 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 None
- assert split.results_bytes is None
- assert fetch_cached_response_by_key(cache_key, self.team.pk) == response
diff --git a/posthog/caching/test/test_redis_cluster_keys.py b/posthog/caching/test/test_redis_cluster_keys.py
index 7b3e8a106887..3c9d20d7fed2 100644
--- a/posthog/caching/test/test_redis_cluster_keys.py
+++ b/posthog/caching/test/test_redis_cluster_keys.py
@@ -4,7 +4,7 @@ from unittest.mock import MagicMock
from parameterized import parameterized
from redis.crc import key_slot
-from posthog.caching.cache_size_tracker import TeamCacheSizeTracker
+from posthog.query_cache.size_tracker import TeamCacheSizeTracker
class TestRedisClusterKeySlots(BaseTest):
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.py
index dced4c1cbfa3..c04efbeb7fb3 100644
--- a/posthog/caching/test/test_warming.py
+++ b/posthog/caching/test/test_warming.py
@@ -49,13 +49,13 @@ class TestWarming(APIBaseTest):
team=self.team, user=self.user, insight=self.insight5, last_viewed_at=datetime.now(UTC) - timedelta(days=1)
)
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_no_stale_insights(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = []
insights = list(insights_to_keep_fresh(self.team))
self.assertEqual(insights, [])
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_no_stale_dashboard_insights(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = [
"2345:",
@@ -66,7 +66,7 @@ class TestWarming(APIBaseTest):
]
self.assertEqual(insights, exptected_results)
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_only_insights_with_dashboards(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = [
"1234:5678",
@@ -78,7 +78,7 @@ class TestWarming(APIBaseTest):
]
self.assertEqual(insights, expected_results)
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_mixed_valid_and_invalid_combos(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = [
"1234:5678",
@@ -92,19 +92,19 @@ class TestWarming(APIBaseTest):
]
self.assertEqual(insights, expected_results)
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_insights_not_viewed_recently(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = ["4567:"]
insights = list(insights_to_keep_fresh(self.team))
self.assertEqual(insights, [])
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_dashboards_not_accessed_recently(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = ["5678:8901"]
insights = list(insights_to_keep_fresh(self.team))
self.assertEqual(insights, [])
- @patch("posthog.hogql_queries.query_cache.QueryCacheManagerBase.get_stale_insights")
+ @patch("posthog.caching.warming.get_stale_insights")
def test_insights_to_keep_fresh_combination_of_cases(self, mock_get_stale_insights):
mock_get_stale_insights.return_value = [
"1234:5678",
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index 1ef328ff82f3..0bb1a1e75266 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -21,10 +21,10 @@ from posthog.clickhouse.query_tagging import Feature, get_team_query_tags, tag_q
from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.event_usage import EventSource
from posthog.exceptions_capture import capture_exception
-from posthog.hogql_queries.query_cache_base import QueryCacheManagerBase
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
+from posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insights
from posthog.query_creator_access import creator_access_revoked, report_creator_access_revoked
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.scoping_audit import skip_team_scope_audit
@@ -100,10 +100,10 @@ def insights_to_keep_fresh(team: Team, shared_only: bool = False) -> Generator[t
LAST_VIEWED_THRESHOLD if not shared_only else SHARED_INSIGHTS_LAST_VIEWED_THRESHOLD
)
- QueryCacheManagerBase.clean_up_stale_insights(team_id=team.pk, threshold=threshold)
+ clean_up_stale_insights(team_id=team.pk, threshold=threshold)
# get all insights currently in the cache for the team
- combos = QueryCacheManagerBase.get_stale_insights(team_id=team.pk, limit=500)
+ combos = get_stale_insights(team_id=team.pk, limit=500)
STALE_INSIGHTS_GAUGE.labels(team_id=team.pk).set(len(combos))
diff --git a/posthog/hogql_queries/query_cache_base.py b/posthog/hogql_queries/query_cache_base.py
deleted file mode 100644
index fc53c55a69d6..000000000000
--- a/posthog/hogql_queries/query_cache_base.py
+++ /dev/null
@@ -1,115 +0,0 @@
-from abc import ABC, abstractmethod
-from datetime import UTC, datetime
-from typing import Optional
-
-from posthog import redis
-from posthog.caching.fetch_from_cache import SplitCachedResponse
-
-
-class QueryCacheManagerBase(ABC):
- """
- Abstract base class for query cache managers.
-
- All cache managers use Redis for sorted set operations (stale insights tracking)
- but can use different storage backends for the actual cache data (Django cache, S3, etc.).
- """
-
- def __init__(
- self,
- *,
- team_id: int,
- cache_key: str,
- insight_id: Optional[int] = None,
- dashboard_id: Optional[int] = None,
- ):
- self.team_id = team_id
- self.cache_key = cache_key
- self.insight_id = insight_id
- self.dashboard_id = dashboard_id
- self.redis_client = redis.get_client()
-
- @property
- def identifier(self) -> str:
- """Unique identifier for tracking insight freshness."""
- return f"{self.insight_id}:{self.dashboard_id or ''}"
-
- @classmethod
- def _redis_key_prefix(cls) -> str:
- """Redis key prefix for cache timestamps. Can be overridden by subclasses."""
- return "cache_timestamps"
-
- @classmethod
- def get_stale_insights(cls, *, team_id: int, limit: Optional[int] = None) -> list[str]:
- """
- Use redis sorted set to get stale insights. We sort by the timestamp and get the insights that are
- stale compared to the current time.
-
- We start with the least stale insights: Because we want to keep in mind
- that we might not have enough time to refresh all insights. This way, and only if we don't manage to refresh
- all insights, we try our best to keep a number of insights fully up-to-date, instead of only achieving to
- refresh the most stale ones while failing to refresh the rest. Should an insight be refreshed by user or other
- means it will be the freshest anyway again.
-
- It is accepted that we store all combinations of insight + dashboard, even if the dashboard might not have
- additional filters (which makes this dashboard insight the same as the single one). This is easily mitigated by
- the fact we should have the very same cache key for these and we calculate the insights in sequence. Thus, the
- first calculation to refresh it will refresh all of them.
- """
- current_time = datetime.now(UTC)
- redis_key = f"{cls._redis_key_prefix()}:{team_id}"
- # get least stale insights first
- if limit is not None:
- insights = redis.get_client().zrevrangebyscore(
- name=redis_key, max=current_time.timestamp(), min="-inf", start=0, num=limit
- )
- else:
- insights = redis.get_client().zrevrangebyscore(name=redis_key, max=current_time.timestamp(), min="-inf")
- return [insight.decode("utf-8") for insight in insights]
-
- @classmethod
- def clean_up_stale_insights(cls, *, team_id: int, threshold: datetime) -> None:
- """
- Remove all stale insights that are older than the given timestamp.
- """
- redis_key = f"{cls._redis_key_prefix()}:{team_id}"
- redis.get_client().zremrangebyscore(
- redis_key,
- "-inf",
- threshold.timestamp(),
- )
-
- def update_target_age(self, target_age: datetime) -> None:
- """Update the target age for insight freshness tracking using Redis sorted sets."""
- if not self.insight_id:
- return
-
- redis_key = f"{self._redis_key_prefix()}:{self.team_id}"
- self.redis_client.zadd(
- redis_key,
- {self.identifier: target_age.timestamp()},
- )
-
- def remove_last_refresh(self) -> None:
- """Remove insight from freshness tracking using Redis sorted sets."""
- if not self.insight_id:
- return
-
- redis_key = f"{self._redis_key_prefix()}:{self.team_id}"
- self.redis_client.zrem(redis_key, self.identifier)
-
- @abstractmethod
- def set_cache_data(self, *, response: dict, target_age: Optional[datetime]) -> None:
- """Store query results in cache."""
- pass
-
- @abstractmethod
- def get_cache_data(self) -> Optional[dict]:
- """Retrieve query results from cache."""
- pass
-
- def get_cache_data_split(self) -> Optional[SplitCachedResponse]:
- """Retrieve cached results, keeping the results segment as raw bytes when the backend supports it."""
- data = self.get_cache_data()
- if data is None:
- return None
- return SplitCachedResponse(header=data, results_bytes=None)
diff --git a/posthog/hogql_queries/query_cache_factory.py b/posthog/hogql_queries/query_cache_factory.py
deleted file mode 100644
index 502562a6e336..000000000000
--- a/posthog/hogql_queries/query_cache_factory.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Optional
-
-from posthog.hogql_queries.query_cache import DjangoCacheQueryCacheManager
-from posthog.hogql_queries.query_cache_base import QueryCacheManagerBase
-from posthog.models import Team
-
-
-def get_query_cache_manager(
- *,
- team: Team,
- cache_key: str,
- insight_id: Optional[int] = None,
- dashboard_id: Optional[int] = None,
-) -> QueryCacheManagerBase:
- return DjangoCacheQueryCacheManager(
- team_id=team.pk,
- cache_key=cache_key,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
- )
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 39f6bfbde970..001f43417130 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -117,9 +117,6 @@ from posthog.hogql_queries.access_controlled_resources import queried_access_con
from posthog.hogql_queries.insights.utils.breakdowns import has_multi_breakdown, has_single_breakdown
from posthog.hogql_queries.insights.utils.entities import has_data_warehouse_node
from posthog.hogql_queries.insights.utils.properties import has_any_property_filters
-from posthog.hogql_queries.query_cache import count_query_cache_hit
-from posthog.hogql_queries.query_cache_base import QueryCacheManagerBase
-from posthog.hogql_queries.query_cache_factory import get_query_cache_manager
from posthog.hogql_queries.query_metadata import extract_query_metadata
from posthog.hogql_queries.utils.event_usage import log_event_usage_from_query_metadata
from posthog.hogql_queries.validation.validation import (
@@ -130,6 +127,7 @@ from posthog.hogql_queries.validation.validation import (
from posthog.models import Team, User
from posthog.models.team import WeekStartDay
from posthog.models.team.event_retention import events_retention_months_for_team
+from posthog.query_cache import QueryCache, count_query_cache_hit
from posthog.rbac.user_access_control import WAREHOUSE_ACCESS_SCOPES, UserAccessControl, UserAccessControlError
from posthog.schema_helpers import to_dict
from posthog.scopes import APIScopeObject
@@ -1425,7 +1423,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
def enqueue_async_calculation(
self,
*,
- cache_manager: QueryCacheManagerBase,
+ cache_manager: QueryCache,
refresh_requested: bool = False,
user: Optional[User] = None,
analytics_props: Optional[AnalyticsProps] = None,
@@ -1471,7 +1469,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
def handle_cache_and_async_logic(
self,
execution_mode: ExecutionMode,
- cache_manager: QueryCacheManagerBase,
+ cache_manager: QueryCache,
user: Optional[User] = None,
analytics_props: Optional[AnalyticsProps] = None,
) -> Optional[CR | CacheMissResponse]:
@@ -1480,6 +1478,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
cached_response_candidate: Optional[dict]
self.raw_cached_results_bytes = None
raw_results: Optional[bytes] = None
+ entry = cache_manager.lookup().entry
if self.serve_raw_cached_results:
# Serving results as raw bytes skips parsing (and later re-serializing) the results
# payload. Only safe when the caller opted in AND validation of the parsed results
@@ -1488,7 +1487,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# the schema-drift check that triggers recomputation) AND neither the query nor
# the cached results carry custom series names — otherwise
# apply_series_custom_names below must be able to patch the parsed results.
- split_candidate = cache_manager.get_cache_data_split()
+ split_candidate = entry
if split_candidate is None:
cached_response_candidate = None
else:
@@ -1503,7 +1502,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
else:
raw_results = split_candidate.results_bytes
else:
- cached_response_candidate = cache_manager.get_cache_data()
+ cached_response_candidate = entry.as_full_response() if entry else None
if self.is_cached_response(cached_response_candidate):
assert cached_response_candidate is not None
@@ -1536,7 +1535,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if custom_names_modified:
# Update cache with patched response so subsequent requests get the updated names
- cache_manager.set_cache_data(
+ cache_manager.store_result(
response=cached_response.model_dump(),
target_age=cached_response.cache_target_age,
)
@@ -1763,8 +1762,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
trigger: str | None = get_query_tag_value("trigger")
CachedResponse: type[CR] = self.cached_response_type
- cache_manager = get_query_cache_manager(
- team=self.team,
+ cache_manager = QueryCache(
+ team_id=self.team.pk,
cache_key=cache_key,
insight_id=insight_id,
dashboard_id=dashboard_id,
@@ -1876,7 +1875,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self,
*,
cache_key: str,
- cache_manager: QueryCacheManagerBase,
+ cache_manager: QueryCache,
execution_mode: ExecutionMode,
insight_id: Optional[int],
dashboard_id: Optional[int],
@@ -1969,7 +1968,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# Guard against response classes that don't carry the field: every analytics response
# inherits `warnings` from AnalyticsQueryResponseBase, and several standalone classes
# add it explicitly — but a future response class that omits it would otherwise crash
- # pydantic validation on the extra key (and poison the cache, which set_cache_data has
+ # pydantic validation on the extra key (and poison the cache, which store_result has
# already written by the time CachedResponse(**dict) raises).
if warnings_accumulator and "warnings" in CachedResponse.model_fields:
# The accumulator is authoritative for sync warnings (it collects across every inner
@@ -1988,7 +1987,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
errors: Optional[list[Any]] = fresh_response_dict.get("error", None)
has_error = errors is not None and len(errors) > 0
if not has_error and self.limit_context != LimitContext.EXPORT:
- cache_manager.set_cache_data(
+ cache_manager.store_result(
response=fresh_response_dict,
# This would be a possible place to decide to not ever keep this cache warm
# Example: Not for super quickly calculated insights
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index f5d656d95fa6..57cfdb2245ce 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -574,17 +574,19 @@ class TestQueryRunner(BaseTest):
assert response.clickhouse is not None
assert "events.`mat_$browser" not in response.clickhouse
- @mock.patch("posthog.hogql_queries.query_runner.get_query_cache_manager")
- def test_schema_change_triggers_recalculation(self, mock_get_cache_manager):
+ @mock.patch("posthog.hogql_queries.query_runner.QueryCache")
+ def test_schema_change_triggers_recalculation(self, mock_query_cache_cls):
TestQueryRunner = self.setup_test_query_runner_class()
mock_cache_manager = mock.MagicMock()
mock_cache_manager.cache_key = "test_cache_key"
- mock_cache_manager.get_cache_data.return_value = {
+ mock_entry = mock.MagicMock()
+ mock_entry.as_full_response.return_value = {
"is_cached": True,
"invalid_field": "this will cause validation to fail",
# Missing all the actual required fields like results, last_refresh, etc.
}
- mock_get_cache_manager.return_value = mock_cache_manager
+ mock_cache_manager.lookup.return_value.entry = mock_entry
+ mock_query_cache_cls.return_value = mock_cache_manager
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
with freeze_time(datetime(2023, 2, 4, 13, 37, 42)):
@@ -593,8 +595,8 @@ class TestQueryRunner(BaseTest):
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
self.assertEqual(response.is_cached, False, "Should get a fresh response, not a cached one")
self.assertEqual(response.last_refresh.isoformat(), "2023-02-04T13:37:42+00:00")
- mock_cache_manager.get_cache_data.assert_called_once()
- mock_cache_manager.set_cache_data.assert_called_once()
+ mock_cache_manager.lookup.assert_called_once()
+ mock_cache_manager.store_result.assert_called_once()
@parameterized.expand(
[
diff --git a/posthog/query_cache/__init__.py b/posthog/query_cache/__init__.py
new file mode 100644
index 000000000000..5e00088542f0
--- /dev/null
+++ b/posthog/query_cache/__init__.py
@@ -0,0 +1,13 @@
+from posthog.query_cache.cache import CacheLookup, QueryCache
+from posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insights
+from posthog.query_cache.metrics import count_query_cache_hit
+from posthog.query_cache.serialization import CachedEntry
+
+__all__ = [
+ "CachedEntry",
+ "CacheLookup",
+ "QueryCache",
+ "clean_up_stale_insights",
+ "count_query_cache_hit",
+ "get_stale_insights",
+]
diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.py
new file mode 100644
index 000000000000..46506c3681c6
--- /dev/null
+++ b/posthog/query_cache/cache.py
@@ -0,0 +1,67 @@
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Optional
+
+from django.conf import settings
+
+from posthog.cache_utils import OrjsonJsonSerializer
+from posthog.query_cache.freshness_index import remove_last_refresh, update_target_age
+from posthog.query_cache.metrics import count_cache_write_data
+from posthog.query_cache.results import fetch_entry
+from posthog.query_cache.serialization import CachedEntry, encode_split_cached_response
+from posthog.query_cache.size_tracker import TeamCacheSizeTracker
+
+
+@dataclass(frozen=True)
+class CacheLookup:
+ """Everything the cache knows about a cache key in one read."""
+
+ entry: Optional[CachedEntry]
+
+
+class QueryCache:
+ """Facade over query result cache storage: blob store, wire format, per-team size limits,
+ and the freshness index. Code outside posthog/query_cache goes through this class."""
+
+ def __init__(
+ self,
+ *,
+ team_id: int,
+ cache_key: str,
+ insight_id: Optional[int] = None,
+ dashboard_id: Optional[int] = None,
+ ) -> None:
+ self.team_id = team_id
+ self.cache_key = cache_key
+ self.insight_id = insight_id
+ self.dashboard_id = dashboard_id
+
+ def lookup(self) -> CacheLookup:
+ return CacheLookup(entry=fetch_entry(self.cache_key, self.team_id))
+
+ def store_result(self, *, response: dict, target_age: Optional[datetime]) -> None:
+ if isinstance(response.get("results"), list):
+ # Split format keeps `results` as its own JSON segment so cache hits can skip
+ # parsing it — see CachedEntry. Pods that predate this
+ # format treat split entries as cache misses and recompute, so entries written
+ # during a rolling deploy may be recomputed once — accepted, deploys are quick.
+ fresh_response_serialized = encode_split_cached_response(response)
+ else:
+ fresh_response_serialized = OrjsonJsonSerializer({}).dumps(response)
+ data_size = len(fresh_response_serialized)
+
+ # Set cache with per-team size limit enforcement
+ tracker = TeamCacheSizeTracker(self.team_id)
+ tracker.set(self.cache_key, fresh_response_serialized, data_size, settings.CACHED_RESULTS_TTL)
+
+ if target_age:
+ update_target_age(
+ team_id=self.team_id,
+ insight_id=self.insight_id,
+ dashboard_id=self.dashboard_id,
+ target_age=target_age,
+ )
+ else:
+ remove_last_refresh(team_id=self.team_id, insight_id=self.insight_id, dashboard_id=self.dashboard_id)
+
+ count_cache_write_data(self.team_id, data_size)
diff --git a/posthog/query_cache/freshness_index.py b/posthog/query_cache/freshness_index.py
new file mode 100644
index 000000000000..d7f7396faa03
--- /dev/null
+++ b/posthog/query_cache/freshness_index.py
@@ -0,0 +1,63 @@
+from datetime import UTC, datetime
+from typing import Optional
+
+from posthog import redis
+
+_REDIS_KEY_PREFIX = "cache_timestamps"
+
+
+def _redis_key(team_id: int) -> str:
+ return f"{_REDIS_KEY_PREFIX}:{team_id}"
+
+
+def _identifier(insight_id: int, dashboard_id: Optional[int]) -> str:
+ return f"{insight_id}:{dashboard_id or ''}"
+
+
+def get_stale_insights(*, team_id: int, limit: Optional[int] = None) -> list[str]:
+ """
+ Use redis sorted set to get stale insights. We sort by the timestamp and get the insights that are
+ stale compared to the current time.
+
+ We start with the least stale insights: Because we want to keep in mind
+ that we might not have enough time to refresh all insights. This way, and only if we don't manage to refresh
+ all insights, we try our best to keep a number of insights fully up-to-date, instead of only achieving to
+ refresh the most stale ones while failing to refresh the rest. Should an insight be refreshed by user or other
+ means it will be the freshest anyway again.
+
+ It is accepted that we store all combinations of insight + dashboard, even if the dashboard might not have
+ additional filters (which makes this dashboard insight the same as the single one). This is easily mitigated by
+ the fact we should have the very same cache key for these and we calculate the insights in sequence. Thus, the
+ first calculation to refresh it will refresh all of them.
+ """
+ current_time = datetime.now(UTC)
+ redis_key = _redis_key(team_id)
+ # get least stale insights first
+ if limit is not None:
+ insights = redis.get_client().zrevrangebyscore(
+ name=redis_key, max=current_time.timestamp(), min="-inf", start=0, num=limit
+ )
+ else:
+ insights = redis.get_client().zrevrangebyscore(name=redis_key, max=current_time.timestamp(), min="-inf")
+ return [insight.decode("utf-8") for insight in insights]
+
+
+def clean_up_stale_insights(*, team_id: int, threshold: datetime) -> None:
+ """Remove all stale insights that are older than the given timestamp."""
+ redis.get_client().zremrangebyscore(_redis_key(team_id), "-inf", threshold.timestamp())
+
+
+def update_target_age(
+ *, team_id: int, insight_id: Optional[int], dashboard_id: Optional[int], target_age: datetime
+) -> None:
+ """Update the target age for insight freshness tracking using Redis sorted sets."""
+ if not insight_id:
+ return
+ redis.get_client().zadd(_redis_key(team_id), {_identifier(insight_id, dashboard_id): target_age.timestamp()})
+
+
+def remove_last_refresh(*, team_id: int, insight_id: Optional[int], dashboard_id: Optional[int]) -> None:
+ """Remove insight from freshness tracking using Redis sorted sets."""
+ if not insight_id:
+ return
+ redis.get_client().zrem(_redis_key(team_id), _identifier(insight_id, dashboard_id))
diff --git a/posthog/hogql_queries/query_cache.py b/posthog/query_cache/metrics.py
similarity index 64%
rename from posthog/hogql_queries/query_cache.py
rename to posthog/query_cache/metrics.py
index a006016083e3..b32fa9250608 100644
--- a/posthog/hogql_queries/query_cache.py
+++ b/posthog/query_cache/metrics.py
@@ -1,25 +1,13 @@
from collections.abc import Generator
from contextlib import contextmanager
-from datetime import datetime
-from typing import TYPE_CHECKING, NamedTuple, Optional
+from typing import NamedTuple, Optional
-if TYPE_CHECKING:
- from posthog.caching.fetch_from_cache import SplitCachedResponse
-
-from django.conf import settings
-
-import structlog
from prometheus_client import CollectorRegistry, Counter, Histogram
-from posthog.cache_utils import OrjsonJsonSerializer
-from posthog.caching.cache_size_tracker import TeamCacheSizeTracker
from posthog.clickhouse.query_tagging import get_query_tag_value
from posthog.exceptions_capture import capture_exception
-from posthog.hogql_queries.query_cache_base import QueryCacheManagerBase
from posthog.metrics import LABEL_TEAM_ID, pushed_metrics_registry
-logger = structlog.get_logger(__name__)
-
class CacheMetrics(NamedTuple):
hit_counter: Counter
@@ -156,48 +144,3 @@ def count_cache_write_data(team_id: int, data_size: int) -> None:
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):
- """
- Storing query results in Django cache (typically Redis) keyed by the hash of the query (cache_key param).
- '{cache_key}' -> query_results
-
- Uses Redis sorted sets (from base class) to store the time query results were calculated.
- 'cache_timestamps:{team_id}' -> '{self.insight_id}:{self.dashboard_id or ''}' -> timestamp (epoch time when calculated)
- """
-
- def set_cache_data(self, *, response: dict, target_age: Optional[datetime]) -> None:
- from posthog.caching.fetch_from_cache import encode_split_cached_response
-
- if isinstance(response.get("results"), list):
- # Split format keeps `results` as its own JSON segment so cache hits can skip
- # parsing it — see fetch_from_cache.SplitCachedResponse. Pods that predate this
- # format treat split entries as cache misses and recompute, so entries written
- # during a rolling deploy may be recomputed once — accepted, deploys are quick.
- fresh_response_serialized = encode_split_cached_response(response)
- else:
- fresh_response_serialized = OrjsonJsonSerializer({}).dumps(response)
- data_size = len(fresh_response_serialized)
-
- # Set cache with per-team size limit enforcement
- tracker = TeamCacheSizeTracker(self.team_id)
- tracker.set(self.cache_key, fresh_response_serialized, data_size, settings.CACHED_RESULTS_TTL)
-
- if target_age:
- self.update_target_age(target_age)
- else:
- self.remove_last_refresh()
-
- # Track cache write metrics
- 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_key
-
- return fetch_cached_response_by_key(self.cache_key, self.team_id)
-
- def get_cache_data_split(self) -> Optional["SplitCachedResponse"]:
- from posthog.caching.fetch_from_cache import fetch_split_cached_response_by_key
-
- return fetch_split_cached_response_by_key(self.cache_key, self.team_id)
diff --git a/posthog/query_cache/results.py b/posthog/query_cache/results.py
new file mode 100644
index 000000000000..6d0341c03989
--- /dev/null
+++ b/posthog/query_cache/results.py
@@ -0,0 +1,32 @@
+from typing import Optional
+
+from django.core.cache import caches
+
+import structlog
+
+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
+from posthog.query_cache.serialization import CachedEntry, split_cached_response_bytes
+
+logger = structlog.get_logger(__name__)
+
+
+def fetch_entry(cache_key: str, team_id: int) -> Optional[CachedEntry]:
+ query_cache = caches[QUERY_CACHE_ALIAS]
+ try:
+ cached_response_bytes = query_cache.get(cache_key)
+ except Exception:
+ logger.warning("query_cache_read_error", cache_key=cache_key, team_id=team_id, exc_info=True)
+ try:
+ query_cache.delete(cache_key)
+ except Exception:
+ pass
+ return None
+
+ if not cached_response_bytes:
+ return None
+
+ try:
+ return split_cached_response_bytes(cached_response_bytes, cache_key=cache_key, team_id=team_id)
+ except Exception:
+ logger.exception("query_cache_deserialize_error", cache_key=cache_key, team_id=team_id, exc_info=True)
+ return None
diff --git a/posthog/caching/fetch_from_cache.py b/posthog/query_cache/serialization.py
similarity index 50%
rename from posthog/caching/fetch_from_cache.py
rename to posthog/query_cache/serialization.py
index d23a59818c48..cef92e4f4a24 100644
--- a/posthog/caching/fetch_from_cache.py
+++ b/posthog/query_cache/serialization.py
@@ -1,25 +1,12 @@
from dataclasses import dataclass
-from datetime import datetime
from typing import Any, Optional
-from django.core.cache import caches
-
import structlog
-from prometheus_client import Counter
-
-from posthog.schema import QueryTiming
from posthog.cache_utils import OrjsonJsonSerializer
-from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
logger = structlog.get_logger(__name__)
-insight_cache_read_counter = Counter(
- "posthog_cloud_insight_cache_read",
- "A read from the redis insight cache",
- labelnames=["result"],
-)
-
# Split cache format: magic + flags byte + 4-byte big-endian header length + header JSON + results JSON.
# Storing `results` as a separate JSON segment lets cache hits skip parsing (and later re-serializing)
# the results payload, which dominates CPU for large cached insights. Blobs without the magic prefix
@@ -31,7 +18,7 @@ _SPLIT_FLAG_CUSTOM_NAMES = 0b00000001
@dataclass(frozen=True)
-class SplitCachedResponse:
+class CachedEntry:
"""A cached query response with the `results` segment kept as raw, unparsed JSON bytes."""
header: dict
@@ -39,6 +26,19 @@ class SplitCachedResponse:
"""Raw JSON bytes of the `results` field; None means `header` is the full legacy response."""
results_have_custom_names: bool = False
"""Whether any series/step in results carries a non-null custom_name (so a cache hit may need patching)."""
+ cache_key: Optional[str] = None
+ team_id: Optional[int] = None
+
+ def as_full_response(self) -> Optional[dict]:
+ """Merge the results segment back into the header; None on deserialization error."""
+ if self.results_bytes is None:
+ return self.header
+ try:
+ self.header["results"] = OrjsonJsonSerializer({}).loads(self.results_bytes)
+ except Exception:
+ logger.exception("query_cache_deserialize_error", cache_key=self.cache_key, team_id=self.team_id)
+ return None
+ return self.header
def _item_has_custom_name(item: Any) -> bool:
@@ -74,88 +74,23 @@ def encode_split_cached_response(response: dict) -> bytes:
)
-def split_cached_response_bytes(cached_response_bytes: bytes) -> SplitCachedResponse:
+def split_cached_response_bytes(
+ cached_response_bytes: bytes, *, cache_key: Optional[str] = None, team_id: Optional[int] = None
+) -> CachedEntry:
serializer = OrjsonJsonSerializer({})
if not cached_response_bytes.startswith(QUERY_CACHE_SPLIT_MAGIC):
- return SplitCachedResponse(header=serializer.loads(cached_response_bytes), results_bytes=None)
+ return CachedEntry(
+ header=serializer.loads(cached_response_bytes), results_bytes=None, cache_key=cache_key, team_id=team_id
+ )
offset = len(QUERY_CACHE_SPLIT_MAGIC)
flags = cached_response_bytes[offset]
header_length = int.from_bytes(cached_response_bytes[offset + 1 : offset + 5], "big")
header_start = offset + 5
header = serializer.loads(cached_response_bytes[header_start : header_start + header_length])
- return SplitCachedResponse(
+ return CachedEntry(
header=header,
results_bytes=cached_response_bytes[header_start + header_length :],
results_have_custom_names=bool(flags & _SPLIT_FLAG_CUSTOM_NAMES),
+ cache_key=cache_key,
+ team_id=team_id,
)
-
-
-def fetch_split_cached_response_by_key(cache_key: str, team_id: int) -> Optional[SplitCachedResponse]:
- query_cache = caches[QUERY_CACHE_ALIAS]
- try:
- cached_response_bytes = query_cache.get(cache_key)
- except Exception:
- logger.warning("query_cache_read_error", cache_key=cache_key, team_id=team_id, exc_info=True)
- try:
- query_cache.delete(cache_key)
- except Exception:
- pass
- return None
-
- if not cached_response_bytes:
- return None
-
- try:
- return split_cached_response_bytes(cached_response_bytes)
- except Exception:
- logger.exception(
- "query_cache_deserialize_error",
- cache_key=cache_key,
- team_id=team_id,
- exc_info=True,
- )
- return None
-
-
-def fetch_cached_response_by_key(cache_key: str, team_id: int) -> Optional[dict]:
- split = fetch_split_cached_response_by_key(cache_key, team_id)
- if split is None:
- return None
- if split.results_bytes is None:
- return split.header
- try:
- split.header["results"] = OrjsonJsonSerializer({}).loads(split.results_bytes)
- except Exception:
- logger.exception("query_cache_deserialize_error", cache_key=cache_key, team_id=team_id, exc_info=True)
- return None
- return split.header
-
-
-@dataclass(frozen=True)
-class InsightResult:
- result: Optional[Any]
- last_refresh: Optional[datetime]
- cache_key: Optional[str]
- is_cached: bool
- timezone: Optional[str]
- has_more: Optional[bool] = None
- next_allowed_client_refresh: Optional[datetime] = None
- cache_target_age: Optional[datetime] = None
- timings: Optional[list[QueryTiming]] = None
- columns: Optional[list] = None
- query_status: Optional[Any] = None
- hogql: Optional[str] = None
- types: Optional[list] = None
- # A ResolvedDateRangeResponse-shaped dict — the field carries model_dump output
- resolved_date_range: Optional[dict] = None
-
-
-@dataclass(frozen=True)
-class NothingInCacheResult(InsightResult):
- result: Optional[Any] = None
- last_refresh: Optional[datetime] = None
- cache_key: Optional[str] = None
- is_cached: bool = False
- timezone: Optional[str] = None
- next_allowed_client_refresh: Optional[datetime] = None
- columns: Optional[list] = None
diff --git a/posthog/caching/cache_size_tracker.py b/posthog/query_cache/size_tracker.py
similarity index 100%
rename from posthog/caching/cache_size_tracker.py
rename to posthog/query_cache/size_tracker.py
diff --git a/posthog/query_cache/test/test_cache.py b/posthog/query_cache/test/test_cache.py
new file mode 100644
index 000000000000..dccb37703687
--- /dev/null
+++ b/posthog/query_cache/test/test_cache.py
@@ -0,0 +1,54 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+
+from django.core.cache import caches
+
+from posthog.cache_utils import OrjsonJsonSerializer
+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
+from posthog.query_cache import QueryCache, get_stale_insights
+
+
+class TestQueryCacheFacade(BaseTest):
+ def test_writes_split_format_and_round_trips(self):
+ response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}
+ cache = QueryCache(team_id=self.team.pk, cache_key=f"cache_format_test_{self.team.pk}", insight_id=1)
+
+ cache.store_result(response=response, target_age=None)
+
+ entry = cache.lookup().entry
+ assert entry is not None
+ assert entry.results_bytes == b'[{"data":[1]}]'
+ assert entry.as_full_response() == {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}
+
+ def test_non_list_results_write_legacy_format(self):
+ response = {"is_cached": False, "results": None, "cache_key": "k"}
+ cache = QueryCache(team_id=self.team.pk, cache_key=f"cache_format_test_legacy_{self.team.pk}", insight_id=1)
+
+ cache.store_result(response=response, target_age=None)
+
+ entry = cache.lookup().entry
+ assert entry is not None
+ assert entry.results_bytes is None
+ assert entry.header == response
+
+ 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"}
+ caches[QUERY_CACHE_ALIAS].set(cache_key, OrjsonJsonSerializer({}).dumps(response), 60)
+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key)
+
+ entry = cache.lookup().entry
+ assert entry is not None
+ assert entry.results_bytes is None
+ assert entry.as_full_response() == response
+
+ def test_store_result_updates_and_clears_freshness_index(self):
+ cache = QueryCache(team_id=self.team.pk, cache_key=f"cache_fresh_test_{self.team.pk}", insight_id=42)
+ past = datetime.now(UTC) - timedelta(minutes=5)
+
+ cache.store_result(response={"results": []}, target_age=past)
+ assert "42:" in get_stale_insights(team_id=self.team.pk)
+
+ cache.store_result(response={"results": []}, target_age=None)
+ assert "42:" not in get_stale_insights(team_id=self.team.pk)
diff --git a/posthog/caching/test/test_cache_size_tracker.py b/posthog/query_cache/test/test_size_tracker.py
similarity index 99%
rename from posthog/caching/test/test_cache_size_tracker.py
rename to posthog/query_cache/test/test_size_tracker.py
index 7fecd8711f70..e1ecaaa1b8ff 100644
--- a/posthog/caching/test/test_cache_size_tracker.py
+++ b/posthog/query_cache/test/test_size_tracker.py
@@ -3,8 +3,8 @@ from posthog.test.base import BaseTest
from django.core.cache import cache
from django.test import override_settings
-from posthog.caching.cache_size_tracker import TeamCacheSizeTracker, get_team_cache_limit
from posthog.models import Team
+from posthog.query_cache.size_tracker import TeamCacheSizeTracker, get_team_cache_limit
class TestTeamCacheSizeTracker(BaseTest):
diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.py
index ae4b6c26dbcb..47acab1895a1 100644
--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py
+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py
@@ -19,7 +19,7 @@ from posthog.schema import (
)
from posthog.api.services.query import ExecutionMode
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
from products.alerts.backend.evaluation.detector import (
diff --git a/posthog/tasks/alerts/trends.py b/posthog/tasks/alerts/trends.py
index c2c78e0c6613..a95b5d6c738c 100644
--- a/posthog/tasks/alerts/trends.py
+++ b/posthog/tasks/alerts/trends.py
@@ -4,7 +4,7 @@ import numpy as np
from posthog.schema import FunnelsQuery, IntervalType, TrendsAlertConfig, TrendsQuery
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter
from posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py b/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py
index 52f91b19df2b..f80dc54ed5bd 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py
@@ -4,7 +4,7 @@ from unittest.mock import MagicMock, patch
from posthog.schema import BaseMathType, ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.temporal.ai.anomaly_investigation.tools import _run_detector_simulation
from products.alerts.backend.models.alert import AlertConfiguration
diff --git a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
index 2f99dd1e1f87..62f11cdb8e40 100644
--- a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
+++ b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
@@ -18,7 +18,7 @@ from posthog.schema import (
)
from posthog.api.services.query import ExecutionMode
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from products.alerts.backend.evaluation.contract import execution_mode_for_alert
from products.alerts.backend.evaluation.detector import extract_detector_series
diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.py
index 686868f72eb2..aac902f1e285 100644
--- a/products/alerts/backend/evaluation/trends.py
+++ b/products/alerts/backend/evaluation/trends.py
@@ -13,7 +13,7 @@ from posthog.schema import (
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.event_usage import EventSource
from posthog.hogql_queries.insights.utils.breakdowns import humanize_breakdown_label
diff --git a/products/exports/backend/tasks/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.py
index 451150b1b111..a221290de6ff 100644
--- a/products/exports/backend/tasks/test/test_image_exporter.py
+++ b/products/exports/backend/tasks/test/test_image_exporter.py
@@ -19,7 +19,7 @@ from prometheus_client import REGISTRY
from posthog.hogql.errors import QueryError
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.settings import (
OBJECT_STORAGE_ACCESS_KEY_ID,
diff --git a/products/exports/backend/temporal/subscriptions/insight_snapshot.py b/products/exports/backend/temporal/subscriptions/insight_snapshot.py
index a66acd02a9ae..399b2e3d8ba5 100644
--- a/products/exports/backend/temporal/subscriptions/insight_snapshot.py
+++ b/products/exports/backend/temporal/subscriptions/insight_snapshot.py
@@ -22,7 +22,7 @@ from pydantic_core import to_jsonable_python
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_cache_key, calculate_for_query_based_insight
-from posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResult
+from posthog.caching.insight_result import InsightResult, NothingInCacheResult
from posthog.models import Team, User
from products.dashboards.backend.models.dashboard import Dashboard
diff --git a/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py b/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py
index d3c9d991f119..398c5de295ec 100644
--- a/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py
+++ b/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py
@@ -4,7 +4,7 @@ from decimal import Decimal
import pytest
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from products.exports.backend.temporal.subscriptions.insight_snapshot import (
_has_comparison_enabled,
diff --git a/products/notebooks/backend/sql_v2_frame_store.md b/products/notebooks/backend/sql_v2_frame_store.md
index 27033857dd50..402e9d701bef 100644
--- a/products/notebooks/backend/sql_v2_frame_store.md
+++ b/products/notebooks/backend/sql_v2_frame_store.md
@@ -74,7 +74,7 @@ Every building block already runs in production. Inventory (per deep-dive, 2026-
### Relevant negative
-There is **no generic S3-backed query-result cache** — `query_cache_factory.py` only returns the Redis manager.
+There is **no generic S3-backed query-result cache** — the query cache (`posthog/query_cache/`) is Redis-only.
That cache exists to reuse identical insight queries within a TTL; the notebook flow gets its reuse from
`query_hash`-keyed frames (in-flight dedup and retry re-fetch today; cross-run reuse is phase 3), so we are
not duplicating (or blocked on) any platform facility.
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index ac578d1c0e07..c3486d0ce5d0 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -64,7 +64,7 @@ from posthog.auth import (
SharingAccessTokenAuthentication,
SharingPasswordProtectedAuthentication,
)
-from posthog.caching.fetch_from_cache import InsightResult, fetch_cached_response_by_key
+from posthog.caching.insight_result import InsightResult
from posthog.clickhouse.cancel import cancel_query_on_cluster
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import AccessMethod, tags_context
@@ -111,6 +111,7 @@ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
from posthog.ph_client import feature_enabled_or_false
+from posthog.query_cache import QueryCache
from posthog.rate_limit import (
AIObservabilitySummarizationBurstThrottle,
AIObservabilitySummarizationDailyThrottle,
@@ -1289,7 +1290,8 @@ class InsightSerializer(InsightBasicSerializer):
export_cache_keys: dict[int, str] | None = self.context.get("export_cache_keys")
if export_cache_keys and insight.id in export_cache_keys:
expected_cache_key = export_cache_keys[insight.id]
- cached_response = fetch_cached_response_by_key(expected_cache_key, team_id=insight.team_id)
+ entry = QueryCache(team_id=insight.team_id, cache_key=expected_cache_key).lookup().entry
+ cached_response = entry.as_full_response() if entry else None
if cached_response:
return InsightResult(
result=cached_response.get("results"),
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index 3decb6611159..72f93cb64ca5 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -47,7 +47,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog import settings
from posthog.api.test.dashboards import DashboardAPI
-from posthog.caching.fetch_from_cache import InsightResult
+from posthog.caching.insight_result import InsightResult
from posthog.constants import AvailableFeature
from posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionMode
from posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, User
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 0ff4d75b459b..b6adaf061716 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -22,10 +22,10 @@ from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tag_quer
from posthog.dags.common import JobOwners
from posthog.event_usage import EventSource
from posthog.exceptions_capture import capture_exception
-from posthog.hogql_queries.query_cache import DjangoCacheQueryCacheManager
from posthog.hogql_queries.query_runner import get_query_runner_or_none
from posthog.models import Team
from posthog.models.instance_setting import get_instance_setting
+from posthog.query_cache import QueryCache
from posthog.settings import CLICKHOUSE_CLUSTER
from posthog.storage import object_storage
@@ -531,8 +531,8 @@ def warm_queries_op(context: dagster.OpExecutionContext, queries: list[dict]) ->
return "skipped_duplicate"
seen_cache_keys.add((team.pk, cache_key))
- cache_manager = DjangoCacheQueryCacheManager(team_id=team.pk, cache_key=cache_key)
- cached_data = cache_manager.get_cache_data()
+ entry = QueryCache(team_id=team.pk, cache_key=cache_key).lookup().entry
+ cached_data = entry.as_full_response() if entry else None
if cached_data is not None:
last_refresh = parse_datetime(cached_data["last_refresh"])
diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.py
index c797d8154272..f22c6190a41a 100644
--- a/products/web_analytics/dags/tests/test_cache_warming.py
+++ b/products/web_analytics/dags/tests/test_cache_warming.py
@@ -304,9 +304,9 @@ class TestWarmQueriesOp(BaseTest):
"products.web_analytics.dags.cache_warming.build_replay_runner",
return_value=(runner, {}, lazy_eligible),
),
- patch("products.web_analytics.dags.cache_warming.DjangoCacheQueryCacheManager") as mock_cm,
+ patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,
):
- mock_cm.return_value.get_cache_data.return_value = None
+ mock_cm.return_value.lookup.return_value.entry = None
warm_queries_op(
dagster.build_op_context(),
[
@@ -329,9 +329,9 @@ class TestWarmQueriesOp(BaseTest):
runner.get_cache_key.return_value = "same-key"
with (
patch("products.web_analytics.dags.cache_warming.build_replay_runner", return_value=(runner, {}, True)),
- patch("products.web_analytics.dags.cache_warming.DjangoCacheQueryCacheManager") as mock_cm,
+ patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,
):
- mock_cm.return_value.get_cache_data.return_value = None
+ mock_cm.return_value.lookup.return_value.entry = None
warm_queries_op(
dagster.build_op_context(),
[