: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): spread hourly insight cache warming over ten minutes (#106986)
Sandy Spicercc6c74a16bde
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.pyindex a5120f87a415..bfecaa5adf85 100644--- a/posthog/caching/test/test_warming.py+++ b/posthog/caching/test/test_warming.py@@ -1,12 +1,21 @@from datetime import UTC, datetime, timedelta+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patchfrom posthog.hogql.errors import QueryError-from posthog.caching.warming import insights_to_keep_fresh, schedule_warming_for_teams_task, warm_insight_cache_task+from posthog.caching.warming import (+ WARMING_CHAIN_LIFETIME,+ WARMING_START_WINDOW,+ insights_to_keep_fresh,+ schedule_warming_for_teams_task,+ warm_insight_cache_task,+)from posthog.exceptions import ClickHouseAtCapacity+from posthog.query_cache.freshness_index import update_target_age+from posthog.scheduling.jitter import deterministic_offsetfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -159,22 +168,48 @@ class TestScheduleWarmingForTeamsTask(APIBaseTest):mock_insights_to_keep_fresh.assert_called()mock_warm_insight_cache_task_si.assert_not_called()- @patch("posthog.caching.warming.largest_teams")- @patch("posthog.caching.warming.insights_to_keep_fresh")- @patch("posthog.caching.warming.warm_insight_cache_task.si")- def test_schedule_warming_for_teams_task_with_non_empty_insight_tuples(- self, mock_warm_insight_cache_task_si, mock_insights_to_keep_fresh, mock_largest_teams- ):- mock_largest_teams.return_value = [self.team1.pk, self.team2.pk]- mock_insights_to_keep_fresh.return_value = iter([("1234", "5678"), ("2345", None)])-- schedule_warming_for_teams_task()-- mock_insights_to_keep_fresh.assert_called()- self.assertEqual(mock_warm_insight_cache_task_si.call_count, 2)- self.assertEqual(mock_warm_insight_cache_task_si.call_args_list[0][0][0], "1234")- self.assertEqual(mock_warm_insight_cache_task_si.call_args_list[0][0][1], "5678")- self.assertEqual(mock_warm_insight_cache_task_si.call_args_list[1][0][0], "2345")+ def test_schedule_warming_for_teams_task_with_non_empty_insight_tuples(self) -> None:+ dispatched_at = datetime.now(UTC)+ team_by_insight: dict[int, int] = {}+ with time_machine.travel(dispatched_at, tick=False) as clock:+ for team in (self.team1, self.team2):+ team.extra_settings = {"insights_cache_warming": True}+ team.save(update_fields=["extra_settings"])+ dashboard = Dashboard.objects.create(team=team, last_accessed_at=dispatched_at)+ for _ in range(2):+ insight = Insight.objects.create(team=team)+ DashboardTile.objects.create(insight=insight, dashboard=dashboard)+ team_by_insight[insight.pk] = team.pk+ update_target_age(+ team_id=team.pk,+ insight_id=insight.pk,+ dashboard_id=dashboard.pk,+ target_age=dispatched_at - timedelta(minutes=1),+ )++ celery_config = warm_insight_cache_task.app.conf+ self.addCleanup(setattr, celery_config, "task_always_eager", celery_config.task_always_eager)+ celery_config.task_always_eager = False+ with (+ patch("posthog.caching.utils.sync_execute", return_value=[]),+ patch("posthog.caching.warming.posthoganalytics.feature_enabled", return_value=False),+ patch.object(warm_insight_cache_task.app, "send_task") as send_task,+ ):+ send_task.side_effect = lambda *args, **kwargs: clock.shift(timedelta(minutes=2))+ schedule_warming_for_teams_task()++ self.assertEqual(send_task.call_count, 2)+ for call in send_task.call_args_list:+ insight_id, _ = call.args[1]+ expected_start = dispatched_at + deterministic_offset(+ str(team_by_insight[insight_id]), WARMING_START_WINDOW+ )+ self.assertEqual(call.kwargs["eta"], expected_start)+ self.assertEqual(call.kwargs["expires"], expected_start + WARMING_CHAIN_LIFETIME)+ remaining_tasks = call.kwargs["chain"]+ self.assertEqual(len(remaining_tasks), 1)+ self.assertNotIn("eta", remaining_tasks[0].options)+ self.assertEqual(remaining_tasks[0].options["expires"], expected_start + WARMING_CHAIN_LIFETIME)class TestWarmInsightCacheTask(APIBaseTest):diff --git a/posthog/caching/warming.py b/posthog/caching/warming.pyindex dfd69cd1c74a..5a6074ce5a73 100644--- a/posthog/caching/warming.py+++ b/posthog/caching/warming.py@@ -25,6 +25,7 @@ from posthog.models import Teamfrom posthog.ph_client import ph_scoped_capturefrom posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insightsfrom posthog.query_creator_access import creator_access_revoked, report_creator_access_revoked+from posthog.scheduling.jitter import deterministic_offsetfrom posthog.schema_migrations.upgrade_manager import upgrade_insightfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue@@ -51,6 +52,13 @@ PRIORITY_INSIGHTS_COUNTER = Counter(LAST_VIEWED_THRESHOLD = timedelta(days=7)SHARED_INSIGHTS_LAST_VIEWED_THRESHOLD = timedelta(days=3)+# Each team's chain starts at its own offset inside this window, so the largest teams do not all+# send their insight queries to ClickHouse in the same minute.+WARMING_START_WINDOW = timedelta(minutes=10)+# How long a team's chain may run after it starts. The start offset plus this stays under an hour,+# so a chain has expired before the next hourly dispatch starts the same team again.+WARMING_CHAIN_LIFETIME = timedelta(minutes=50)+# ClickHouse capacity/concurrency errors that should retry with backoff rather than fail the task.# ClickHouseAtCapacity is included via CH_TRANSIENT_ERRORS (it's what codes 202/439 surface as).RETRIABLE_WARMING_ERRORS = (*CH_TRANSIENT_ERRORS, ConcurrencyLimitExceeded)@@ -150,7 +158,8 @@ def insights_to_keep_fresh(team: Team, shared_only: bool = False) -> Generator[tdef schedule_warming_for_teams_task():"""Runs every hour and schedule warming for all insights (picked from insights_to_cache)- for each team enabled for cache warming.+ for each team enabled for cache warming. Each team's warming starts at a stable+ offset within WARMING_START_WINDOW.We trigger recalculation using ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALEso even though we might pick all insights for a team to recalculate,@@ -184,8 +193,7 @@ def schedule_warming_for_teams_task():zip(teams_with_recently_viewed_shared, [True] * len(teams_with_recently_viewed_shared)),)- # Use a fixed expiration time since tasks in the chain are executed sequentially- expire_after = datetime.now(UTC) + timedelta(minutes=50)+ dispatched_at = datetime.now(UTC)with ph_scoped_capture() as capture_ph_event:for team, shared_only in all_teams:@@ -204,13 +212,19 @@ def schedule_warming_for_teams_task():},)+ # Anchored to the dispatch time, so the time this loop spends on earlier teams does not delay+ # this team. A start time that has already passed runs at once.+ start_at = dispatched_at + deterministic_offset(str(team.pk), WARMING_START_WINDOW)+ # Use a fixed expiration time since tasks in the chain are executed sequentially+ expire_after = start_at + WARMING_CHAIN_LIFETIME+# We chain the task execution to prevent queries *for a single team* running at the same timechain(*(warm_insight_cache_task.si(*insight_tuple).set(expires=expire_after)for insight_tuple in insight_tuples)- )()+ ).apply_async(eta=start_at)@shared_task(diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 3eb6a5d6de01..b0a9e6cd51b9 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -293,8 +293,9 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="query performance heartbeat",)+ # Just after the hour. The task then starts each team at its own point in the next ten minutes.sender.add_periodic_task(- crontab(hour="*", minute="0"),+ crontab(hour="*", minute="2"),schedule_warming_for_teams_task.s(),name="schedule warming for largest teams",)