: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
fix(caching): back off hourly warming of failing queries (#106091)
Vasco de Krijger450702ad1603
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex e2624660267b..4f5543fb4b0c 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -159,7 +159,7 @@ from posthog.clickhouse.query_tagging import get_query_tag_value, is_api_key_accfrom posthog.constants import AvailableFeaturefrom posthog.dataclasses import frozenfrom posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_error_type-from posthog.event_usage import AnalyticsProps, groups, report_team_action, report_user_or_team_action+from posthog.event_usage import AnalyticsProps, EventSource, groups, report_team_action, report_user_or_team_actionfrom posthog.exceptions import APIQueriesBudgetExceeded, QueryRanConcurrentlyfrom posthog.exceptions_capture import capture_exceptionfrom posthog.git import get_git_commit_short@@ -193,7 +193,9 @@ from posthog.query_cache.failures import (QUERY_FAILURE_CACHE_COUNTER,QUERY_FAILURE_CACHING_FLAG,Budget,+ QueryFailureCache,QueryFailureRecord,+ WarmingQueryFailureCache,)from posthog.query_cache.single_flight import (QUERY_SINGLE_FLIGHT_COUNTER,@@ -2431,6 +2433,12 @@ class QueryRunner(ABC, Generic[Q, R, CR]):raisecache_manager = QueryCache(+ failure_cache=(+ WarmingQueryFailureCache(cache_key)+ if analytics_props is not None+ and analytics_props.get("source") == EventSource.CACHE_WARMING+ else QueryFailureCache(cache_key)+ ),team_id=self.team.pk,cache_key=cache_key,insight_id=insight_id,diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 5b618327d070..2bed8a002628 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -70,6 +70,7 @@ from posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import reset_query_tags, tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.errors import ExposedCHQueryError, wrap_clickhouse_query_error+from posthog.event_usage import EventSourcefrom posthog.exceptions import (ClickHouseQueryMemoryLimitExceeded,ClickHouseQuerySizeExceeded,@@ -107,6 +108,7 @@ from posthog.query_cache.failures import (KIND_POLICIES,QUERY_FAILURE_CACHING_FLAG,QueryFailureCache,+ WarmingQueryFailureCache,)from posthog.query_cache.single_flight import QUERY_SINGLE_FLIGHT_FLAG, FlightWait, QuerySingleFlight, SharedFailurefrom posthog.query_cache.storage import entry_redis_key@@ -2568,7 +2570,8 @@ class TestQueryFailureCaching(BaseTest):runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)assert QueryFailureCache(runner.get_cache_key()).get_open() is None- def test_extended_budget_run_ignores_interactive_breaker(self):+ @parameterized.expand([(None,), (EventSource.CACHE_WARMING,)])+ def test_extended_budget_run_ignores_interactive_breaker(self, source: EventSource | None) -> None:# The async worker executes with CALCULATE_BLOCKING_ALWAYS under a 10x execution budget,# so a breaker opened by interactive timeouts must not stop it.runner_class = setup_test_query_runner_class()@@ -2579,10 +2582,100 @@ class TestQueryFailureCaching(BaseTest):assert failure_cache.get_open() is not Nonewith mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):- response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ response = runner.run(+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ analytics_props={"source": source} if source is not None else None,+ )assert response.is_cached is Falseassert failure_cache.get_open() is None # the success closed the breaker+ def _warm(+ self,+ runner: QueryRunner,+ execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ ) -> TheTestCachedBasicQueryResponse:+ return cast(+ TheTestCachedBasicQueryResponse,+ runner.run(execution_mode=execution_mode, analytics_props={"source": EventSource.CACHE_WARMING}),+ )++ @parameterized.expand([("fresh_cache", True), ("cache_miss", False)])+ def test_warming_backoff_preserves_cached_results_and_foreground_recovery(+ self, _name: str, has_fresh_cache: bool+ ) -> None:+ runner_class = setup_test_query_runner_class()+ runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)+ failure_cache = WarmingQueryFailureCache(runner.get_cache_key())+ with (+ time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen,+ mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag),+ ):+ if has_fresh_cache:+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ for _ in range(3):+ failure_cache.record_failure("timeout", "timed out", budget=BUDGET_EXTENDED)+ frozen.shift(BASE_BACKOFF if has_fresh_cache else timedelta(hours=1))+ assert failure_cache.get_open() is not None+ with mock.patch.object(runner_class, "_calculate", autospec=True) as calculate:+ if has_fresh_cache:+ assert self._warm(runner).is_cached is True+ else:+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:+ self._warm(runner)+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)+ calculate.assert_not_called()+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert response.is_cached is False+ assert failure_cache.get_open() is None+ assert self._warm(runner).is_cached is True++ @parameterized.expand(+ [+ ("ordinary_cooldown", None, (1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 9, 10)),+ ("warming_cooldown", EventSource.CACHE_WARMING, (1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5)),+ ]+ )+ def test_hourly_ten_minute_timeouts_without_user_views_back_off_and_recover(+ self, _name: str, source: EventSource | None, executions_by_hour: tuple[int, ...]+ ) -> None:+ runner_class = setup_test_query_runner_class()+ runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)+ start = datetime(2026, 1, 1, tzinfo=UTC)+ with (+ time_machine.travel(start, tick=False) as frozen,+ mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag),+ ):++ def time_out_after_ten_minutes(_runner: QueryRunner) -> None:+ frozen.shift(timedelta(minutes=10))+ raise ClickHouseQueryTimeOut()++ with mock.patch.object(+ runner_class, "_calculate", autospec=True, side_effect=time_out_after_ten_minutes+ ) as calculate:+ for hour, expected_executions in enumerate(executions_by_hour):+ with self.subTest(hour=hour, expected_executions=expected_executions):+ frozen.move_to(start + timedelta(hours=hour))+ previous_executions = calculate.call_count+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:+ runner.run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ analytics_props={"source": source} if source is not None else None,+ )+ assert calculate.call_count == expected_executions+ assert bool(getattr(ctx.exception, "served_from_query_failure_cache", False)) is (+ expected_executions == previous_executions+ )+ frozen.move_to(start + timedelta(hours=17))+ assert self._warm(runner).is_cached is False+ assert WarmingQueryFailureCache(runner.get_cache_key()).get_open() is None+ with (+ mock.patch.object(runner_class, "_calculate", autospec=True, side_effect=ClickHouseQueryTimeOut()),+ self.assertRaises(ClickHouseQueryTimeOut),+ ):+ self._warm(runner, ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert WarmingQueryFailureCache(runner.get_cache_key()).get_open() is None+def test_extended_budget_run_blocked_by_extended_breaker(self):runner_class = setup_test_query_runner_class()runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)@@ -2596,15 +2689,22 @@ class TestQueryFailureCaching(BaseTest):runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)assert getattr(ctx.exception, "served_from_query_failure_cache", False)- def test_no_behavior_change_when_flag_disabled(self):+ @parameterized.expand([(None,), (EventSource.CACHE_WARMING,)])+ def test_no_behavior_change_when_flag_disabled(self, source: EventSource | None) -> None:runner_class = setup_test_query_runner_class()runner = runner_class(query={"some_attr": "bla"}, team=self.team)+ failure_cache = QueryFailureCache(runner.get_cache_key())+ for _ in range(KIND_POLICIES["timeout"].open_threshold):+ failure_cache.record_failure("timeout", "timed out", budget=BUDGET_EXTENDED)with mock.patch.object(runner_class, "_calculate", autospec=True, side_effect=ClickHouseQueryTimeOut()) as mock_calculate:for _ in range(KIND_POLICIES["timeout"].open_threshold + 2):with self.assertRaises(ClickHouseQueryTimeOut) as ctx:- runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)+ runner.run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ analytics_props={"source": source} if source is not None else None,+ )assert not getattr(ctx.exception, "served_from_query_failure_cache", False)assert mock_calculate.call_count == KIND_POLICIES["timeout"].open_threshold + 2diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.pyindex 8e5152b8aef4..3d8d4dc2a6f6 100644--- a/posthog/query_cache/cache.py+++ b/posthog/query_cache/cache.py@@ -66,7 +66,9 @@ class QueryCache:insight_id: Optional[int] = None,dashboard_id: Optional[int] = None,ttl: Optional[int] = None,+ failure_cache: Optional[QueryFailureCache] = None,) -> None:+ self._failure_cache = failure_cache if failure_cache is not None else QueryFailureCache(cache_key)self.team_id = team_idself.cache_key = cache_keyself.insight_id = insight_id@@ -76,7 +78,7 @@ class QueryCache:def lookup(self, *, include_failure: bool = False) -> CacheLookup:# The failure read is opt-in so callers that never consult the breaker (and the# feature-flag-off path) don't pay an extra cache roundtrip per query.- failure = QueryFailureCache(self.cache_key).get_open() if include_failure else None+ failure = self._failure_cache.get_open() if include_failure else Nonereturn CacheLookup(entry=fetch_entry(self.cache_key, self.team_id), failure=failure)def freshness(self) -> Optional[EntryFreshness]:@@ -85,7 +87,7 @@ class QueryCache:def open_failure(self) -> Optional[QueryFailureRecord]:"""The open breaker record alone, for paths that skip the result cache entirely."""- return QueryFailureCache(self.cache_key).get_open()+ return self._failure_cache.get_open()def record_failure(self,@@ -96,12 +98,12 @@ class QueryCache:cache_key: Optional[str] = None,query_scan: Optional[dict[str, Any]] = None,) -> Optional[QueryFailureRecord]:- return QueryFailureCache(self.cache_key).record_failure(+ return self._failure_cache.record_failure(kind, detail, budget=budget, cache_key=cache_key, query_scan=query_scan)def clear_failure(self) -> None:- QueryFailureCache(self.cache_key).clear()+ self._failure_cache.clear()def flight(self, budget: Budget, variant: str = "") -> QuerySingleFlight:return QuerySingleFlight(self.cache_key, budget, variant)diff --git a/posthog/query_cache/failures.py b/posthog/query_cache/failures.pyindex 116971a325d7..6825cc604efe 100644--- a/posthog/query_cache/failures.py+++ b/posthog/query_cache/failures.py@@ -1,4 +1,4 @@-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom datetime import UTC, datetime, timedeltafrom typing import Any, Literal, Optional, cast@@ -43,6 +43,7 @@ KIND_POLICIES: dict[FailureKind, KindPolicy] = {}BASE_BACKOFF = timedelta(minutes=2)+WARMING_BASE_BACKOFF = timedelta(hours=2)RECORD_TTL = timedelta(hours=24)@@ -85,8 +86,15 @@ class QueryFailureCache:def __init__(self, cache_key: str) -> None:self.key = f"query_failure:{cache_key}"+ def retry_after(self, record: QueryFailureRecord) -> Optional[datetime]:+ """Return the retry deadline; None or a past deadline allows a retry."""+ return record.open_until+def get_open(self) -> Optional[QueryFailureRecord]:+ """Return a failure still in cooldown, or None. Callers must also check record.forbids(budget)."""record = self._load()+ if record is not None:+ record = replace(record, open_until=self.retry_after(record))return record if record is not None and record.is_open else Nonedef record_failure(@@ -114,17 +122,18 @@ class QueryFailureCache:# Once the big-budget path has failed, a later small-budget failure must# not narrow what the breaker forbids.record_budget = BUDGET_EXTENDED- open_until: Optional[datetime] = None+ now = datetime.now(UTC)+ open_until = Noneif failures >= policy.open_threshold:max_doublings = (policy.max_backoff // BASE_BACKOFF).bit_length()doublings = min(failures - policy.open_threshold, max_doublings)- open_until = datetime.now(UTC) + min(BASE_BACKOFF * 2**doublings, policy.max_backoff)+ open_until = now + min(BASE_BACKOFF * 2**doublings, policy.max_backoff)record = QueryFailureRecord(kind=kind,# Capped so record size stays bounded no matter what copy a caller passes.detail=detail[:1000],consecutive_failures=failures,- last_failed_at=datetime.now(UTC),+ last_failed_at=now,open_until=open_until,budget=record_budget,cache_key=cache_key,@@ -179,3 +188,25 @@ class QueryFailureCache:"cache_key": record.cache_key,"query_scan": record.query_scan,}+++class WarmingQueryFailureCache(QueryFailureCache):+ """Make cache warming wait longer before retrying a recently failed query.++ We override retry_after() instead of record_failure() because warming and+ frontend requests share the stored failure history. Changing the deadline in+ record_failure() would also make frontend requests wait longer. This override+ applies the longer wait only when warming checks a failure, once the failure+ threshold is reached. It does not change the stored deadline.++ A successful frontend calculation for the same cache key clears the failure+ history for both paths, so warming can resume without the old cooldown.+ """++ def retry_after(self, record: QueryFailureRecord) -> Optional[datetime]:+ policy = KIND_POLICIES[record.kind]+ if record.consecutive_failures < policy.open_threshold:+ return None+ max_doublings = (policy.max_backoff // WARMING_BASE_BACKOFF).bit_length()+ doublings = min(record.consecutive_failures - policy.open_threshold, max_doublings)+ return record.last_failed_at + min(WARMING_BASE_BACKOFF * 2**doublings, policy.max_backoff)diff --git a/posthog/query_cache/test/test_failures.py b/posthog/query_cache/test/test_failures.pyindex 89c65f310b6c..8fa2d0af3f36 100644--- a/posthog/query_cache/test/test_failures.py+++ b/posthog/query_cache/test/test_failures.py@@ -1,6 +1,7 @@from datetime import UTC, datetime, timedeltaimport time_machine+from unittest import mockfrom django.core.cache import cachesfrom django.test import SimpleTestCase@@ -13,7 +14,10 @@ from posthog.query_cache.failures import (BUDGET_EXTENDED,BUDGET_INTERACTIVE,KIND_POLICIES,+ RECORD_TTL,+ FailureKind,QueryFailureCache,+ WarmingQueryFailureCache,)@@ -49,7 +53,8 @@ class TestQueryFailureCache(SimpleTestCase):with self.assertRaises(ValueError):QueryFailureCache("cache_key_bad").record_failure("not_a_kind", "failed") # type: ignore[arg-type]- def test_unknown_kind_in_cache_fails_open(self):+ @parameterized.expand([("foreground", QueryFailureCache), ("warming", WarmingQueryFailureCache)])+ def test_unknown_kind_in_cache_fails_open(self, _name: str, cache_class: type[QueryFailureCache]) -> None:caches[QUERY_CACHE_ALIAS].set("query_failure:cache_key_future",{@@ -62,58 +67,76 @@ class TestQueryFailureCache(SimpleTestCase):},300,)- assert QueryFailureCache("cache_key_future").get_open() is None+ assert cache_class("cache_key_future").get_open() is None- def test_load_dependent_breaker_opens_after_threshold_and_backs_off_exponentially(self):- failure_cache = QueryFailureCache("cache_key_1")+ @parameterized.expand(+ [+ (f"{name}_{kind}", cache_class, kind, threshold, backoffs)+ for name, cache_class, backoffs in [+ ("foreground", QueryFailureCache, (2, 4, 8)),+ ("warming", WarmingQueryFailureCache, (120, 240, 240)),+ ]+ for kind, threshold in [+ ("timeout", 3),+ ("too_slow", 3),+ ("memory_limit", 1),+ ("query_size", 1),+ ("too_many_bytes", 1),+ ]+ ]+ )+ def test_breaker_threshold_backoff_and_expiry(+ self,+ _name: str,+ cache_class: type[QueryFailureCache],+ kind: FailureKind,+ threshold: int,+ backoffs: tuple[int, ...],+ ) -> None:+ failure_cache = cache_class("cache_key_backoff")+ foreground_cache = QueryFailureCache("cache_key_backoff")with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:- for _ in range(KIND_POLICIES["timeout"].open_threshold - 1):- failure_cache.record_failure("timeout", "failed")+ for _ in range(threshold - 1):+ failure_cache.record_failure(kind, "failed", budget=BUDGET_EXTENDED)assert failure_cache.get_open() is None- record = failure_cache.record_failure("timeout", "failed")- assert record is not None- assert record.open_until == datetime.now(UTC) + BASE_BACKOFF- assert failure_cache.get_open() is not None-- frozen.shift(BASE_BACKOFF + timedelta(seconds=1))- assert failure_cache.get_open() is None- record = failure_cache.record_failure("timeout", "failed")- assert record is not None- assert record.open_until == datetime.now(UTC) + BASE_BACKOFF * 2-- @parameterized.expand([("memory_limit",), ("query_size",), ("too_many_bytes",)])- def test_deterministic_kinds_open_on_first_failure(self, kind):- failure_cache = QueryFailureCache(f"cache_key_instant_{kind}")- with time_machine.travel("2026-01-01T00:00:00Z", tick=False):- record = failure_cache.record_failure(kind, "failed")- assert record is not None- assert record.consecutive_failures == 1- assert record.open_until == datetime.now(UTC) + BASE_BACKOFF- assert failure_cache.get_open() is not None-- record = failure_cache.record_failure(kind, "failed")- assert record is not None- assert record.open_until == datetime.now(UTC) + BASE_BACKOFF * 2+ for attempt, minutes in enumerate(backoffs):+ record = failure_cache.record_failure(kind, "failed", budget=BUDGET_EXTENDED)+ assert record is not None+ assert record.consecutive_failures == threshold + attempt+ assert record.open_until == datetime.now(UTC) + BASE_BACKOFF * 2**attempt+ opened = failure_cache.get_open()+ assert opened is not None+ assert opened.open_until == datetime.now(UTC) + timedelta(minutes=minutes)+ frozen.shift(timedelta(minutes=minutes) - timedelta(microseconds=1))+ assert failure_cache.get_open() is not None+ frozen.shift(timedelta(microseconds=1))+ assert failure_cache.get_open() is None+ assert foreground_cache.get_open() is None- def test_backoff_is_capped_and_survives_high_failure_counts(self):+ def test_backoff_is_capped_and_survives_high_failure_counts(self) -> None:# 50 failures is past the point where uncapped backoff math overflows timedelta.failure_cache = QueryFailureCache("cache_key_2")- with time_machine.travel("2026-01-01T00:00:00Z", tick=False):+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:record = Nonefor _ in range(50):record = failure_cache.record_failure("timeout", "failed")assert record is not Noneassert record.consecutive_failures == 50assert record.open_until == datetime.now(UTC) + KIND_POLICIES["timeout"].max_backoff+ frozen.shift(KIND_POLICIES["timeout"].max_backoff - timedelta(microseconds=1))+ assert WarmingQueryFailureCache("cache_key_2").get_open() is not None+ frozen.shift(timedelta(microseconds=1))+ assert WarmingQueryFailureCache("cache_key_2").get_open() is None- def test_kind_change_resets_the_consecutive_count(self):+ def test_kind_change_resets_the_consecutive_count(self) -> None:failure_cache = QueryFailureCache("cache_key_kind_change")failure_cache.record_failure("timeout", "failed")failure_cache.record_failure("timeout", "failed")record = failure_cache.record_failure("too_slow", "failed")assert record is not Noneassert record.consecutive_failures == 1+ assert WarmingQueryFailureCache("cache_key_kind_change").get_open() is Nonedef test_clear_closes_breaker_and_resets_count(self):failure_cache = QueryFailureCache("cache_key_3")@@ -124,10 +147,39 @@ class TestQueryFailureCache(SimpleTestCase):failure_cache.clear()assert failure_cache.get_open() is None+ assert WarmingQueryFailureCache("cache_key_3").get_open() is Nonerecord = failure_cache.record_failure("memory_limit", "failed")assert record is not Noneassert record.consecutive_failures == 1+ def test_warming_lookups_do_not_renew_or_mutate_failure_history(self) -> None:+ failure_cache = QueryFailureCache("warming_read_only")+ warming_cache = WarmingQueryFailureCache("warming_read_only")+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:+ original = warming_cache.record_failure("memory_limit", "failed", budget=BUDGET_EXTENDED)+ assert original is not None+ assert original.open_until == datetime.now(UTC) + timedelta(minutes=2)+ for _ in range(4):+ frozen.shift(timedelta(minutes=30))+ warming_cache.get_open()+ assert failure_cache.get_open() is None+ assert warming_cache.get_open() is None+ record = failure_cache.record_failure("memory_limit", "failed", budget=BUDGET_EXTENDED)+ assert record is not None+ assert record.consecutive_failures == 2+ assert record.open_until == datetime.now(UTC) + timedelta(minutes=4)+ frozen.shift(RECORD_TTL - timedelta(seconds=1))+ warming_cache.get_open()+ frozen.shift(timedelta(seconds=2))+ record = failure_cache.record_failure("memory_limit", "failed", budget=BUDGET_EXTENDED)+ assert record is not None+ assert record.consecutive_failures == 1++ def test_warming_fails_open_when_cache_is_unavailable(self) -> None:+ warming_cache = WarmingQueryFailureCache("warming_unavailable")+ with mock.patch.object(caches[QUERY_CACHE_ALIAS], "get", side_effect=ConnectionError("unavailable")):+ assert warming_cache.get_open() is None+def test_detail_is_capped(self):record = QueryFailureCache("cache_key_detail").record_failure("timeout", "x" * 5000)assert record is not None