Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): stagger the refresh TTL so a bulk-written cohort disperses (#105023)

James Gill3d1fe0498160
diff --git a/posthog/storage/cache_expiry_manager.py b/posthog/storage/cache_expiry_manager.py
index d65efbf1f552..e7822549708f 100644
--- a/posthog/storage/cache_expiry_manager.py
+++ b/posthog/storage/cache_expiry_manager.py
@@ -8,6 +8,7 @@ across different HyperCache types (flags, team metadata, etc.).
from __future__ import annotations
import time
+import random
from typing import Literal
import structlog
@@ -410,11 +411,25 @@ def _refresh_teams(
return CacheRefreshCounts(successful=successful, failed=failed, enqueued=enqueued)
+def _staggered_refresh_ttl(config: HyperCacheManagementConfig) -> int | None:
+ """The band only ever shortens: an entry that outlived `cache_ttl` would break
+ whatever staleness bound that TTL was chosen to enforce.
+ """
+ fraction = config.refresh_ttl_min_fraction
+ if fraction is None:
+ return None
+ cache_ttl = config.hypercache.cache_ttl
+ # The floor is truncated to an int, so a short enough cache_ttl gives a floor of zero.
+ # Redis treats a timeout of zero as expired, so the entry would come due on arrival.
+ floor = max(1, int(cache_ttl * fraction))
+ return random.randint(floor, cache_ttl)
+
+
def _refresh_one_team(config: HyperCacheManagementConfig, team: Team) -> RefreshOutcome:
try:
if config.route_refresh_fn is not None and config.route_refresh_fn(team.id):
return "enqueued"
- return "successful" if config.update_fn(team) else "failed"
+ return "successful" if config.update_fn(team, ttl=_staggered_refresh_ttl(config)) else "failed"
except Exception as e:
logger.exception(
f"Failed to refresh {config.log_prefix[:-1]}",
diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.py
index 91c3fefb3f92..2c9cf9b9e3bc 100644
--- a/posthog/storage/hypercache_manager.py
+++ b/posthog/storage/hypercache_manager.py
@@ -303,6 +303,17 @@ class HyperCacheManagementConfig:
# label value (e.g. "python", "rust", "unknown"). None labels every fix "python".
get_primary_writer_fn: Callable[[int], str] | None = None
+ # Lowest fraction of the cache's TTL a refreshed entry may be given. A flat refresh TTL
+ # preserves whatever bunching the entries already have and never widens it, so a cohort
+ # written together keeps coming due together for as long as the cache lives. The bound is
+ # a fraction rather than a duration because the sweep serves every hypercache, and their
+ # TTLs span a minute to a month.
+ refresh_ttl_min_fraction: float | None = None
+
+ def __post_init__(self) -> None:
+ if self.refresh_ttl_min_fraction is not None and not 0 < self.refresh_ttl_min_fraction <= 1:
+ raise ValueError(f"refresh_ttl_min_fraction must be within (0, 1], got {self.refresh_ttl_min_fraction}")
+
# Derived properties (computed from required properties using conventions)
@property
def namespace(self) -> str:
diff --git a/posthog/storage/test/test_cache_expiry_manager.py b/posthog/storage/test/test_cache_expiry_manager.py
index 5e85b2c6af7d..99d073f56dbc 100644
--- a/posthog/storage/test/test_cache_expiry_manager.py
+++ b/posthog/storage/test/test_cache_expiry_manager.py
@@ -1,6 +1,6 @@
import time
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
from django.test import SimpleTestCase
@@ -89,6 +89,36 @@ class TestRefreshExpiringCaches(SimpleTestCase):
assert (counts.successful, counts.failed, counts.enqueued) == (1, 2, 1)
assert counts.successful + counts.failed + counts.enqueued == 4
+ def test_a_cache_that_has_not_opted_in_keeps_its_flat_ttl(self) -> None:
+ update_fn = MagicMock(return_value=True)
+ config = build_config(update_fn=update_fn, cache_ttl=1000)
+
+ with patch(f"{MODULE}.random.randint") as mock_randint:
+ refresh_expiring_caches(config)
+
+ assert mock_randint.call_count == 0
+ assert [c.kwargs["ttl"] for c in update_fn.call_args_list] == [None, None, None]
+
+ @parameterized.expand(
+ [
+ ("a_fraction_of_the_cache_ttl", 1000, 0.7, (700, 1000), 850),
+ # The floor truncates to an int, so without a clamp this band starts at zero
+ # and can draw a ttl of 0, which Redis expires on arrival.
+ ("at_least_one_second", 60, 0.01, (1, 60), 30),
+ ]
+ )
+ def test_an_opted_in_cache_draws_its_ttl_from_the_band_above_the_floor(
+ self, _name: str, cache_ttl: int, fraction: float, expected_band: tuple[int, int], drawn: int
+ ) -> None:
+ update_fn = MagicMock(return_value=True)
+ config = build_config(update_fn=update_fn, refresh_ttl_min_fraction=fraction, cache_ttl=cache_ttl)
+
+ with patch(f"{MODULE}.random.randint", return_value=drawn) as mock_randint:
+ refresh_expiring_caches(config)
+
+ assert mock_randint.call_args_list == [call(*expected_band)] * 3
+ assert [c.kwargs["ttl"] for c in update_fn.call_args_list] == [drawn] * 3
+
def test_a_hook_that_raises_counts_as_failed_and_does_not_build(self):
update_fn = MagicMock(return_value=True)
route_refresh_fn = MagicMock(side_effect=RuntimeError("flag client down"))
diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.py
index 592570853198..dec16d1b8b52 100644
--- a/posthog/storage/test/test_hypercache.py
+++ b/posthog/storage/test/test_hypercache.py
@@ -1471,6 +1471,20 @@ class TestHyperCacheSetCacheValueRedisOnly(BaseTest):
# The value is readable from the Redis tier afterwards.
assert hc.get_from_cache(self.team.api_token) == self.sample_data
+ @patch("posthog.storage.hypercache.get_client")
+ def test_an_explicit_ttl_sets_the_expiry_score(self, mock_get_client):
+ mock_redis = Mock()
+ mock_get_client.return_value = mock_redis
+
+ hc = self._make_hypercache()
+ with patch("posthog.storage.hypercache.time.time", return_value=1_000_000):
+ hc.set_cache_value_redis_only(self.team, self.sample_data, ttl=900, track_expiry=True)
+
+ # The refresh sweep staggers entries by varying this ttl. A score that fell back to
+ # cache_ttl would leave the sorted set flat, and the sweep selects on the score.
+ _, member_map = mock_redis.zadd.call_args[0]
+ assert member_map == {str(self.team.api_token): 1_000_900}
+
@patch("posthog.storage.hypercache.get_client")
def test_default_does_not_track_expiry(self, mock_get_client):
hc = self._make_hypercache()
diff --git a/posthog/storage/test/test_hypercache_manager.py b/posthog/storage/test/test_hypercache_manager.py
index 90c03c4708c0..af3924553196 100644
--- a/posthog/storage/test/test_hypercache_manager.py
+++ b/posthog/storage/test/test_hypercache_manager.py
@@ -10,10 +10,13 @@ Covers:
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
from prometheus_client import CollectorRegistry
from posthog.models.team.team import Team
-from posthog.storage.hypercache import HyperCache
+from posthog.storage.hypercache import DEFAULT_CACHE_TTL, HyperCache
from posthog.storage.hypercache_manager import (
HyperCacheManagementConfig,
get_cache_stats,
@@ -28,6 +31,7 @@ def create_test_hypercache(
value: str = "test_value",
token_based: bool = False,
expiry_sorted_set_key: str = "test_cache_expiry",
+ cache_ttl: int = DEFAULT_CACHE_TTL,
) -> HyperCache:
"""Create a test HyperCache with minimal setup."""
@@ -40,6 +44,7 @@ def create_test_hypercache(
load_fn=load_fn,
token_based=token_based,
expiry_sorted_set_key=expiry_sorted_set_key,
+ cache_ttl=cache_ttl,
)
@@ -49,6 +54,8 @@ def create_test_config(
token_based: bool = False,
update_fn=None,
route_refresh_fn=None,
+ refresh_ttl_min_fraction: float | None = None,
+ cache_ttl: int = DEFAULT_CACHE_TTL,
) -> HyperCacheManagementConfig:
"""Create a test HyperCacheManagementConfig with minimal setup."""
@@ -61,6 +68,7 @@ def create_test_config(
namespace=namespace,
value=value,
token_based=token_based,
+ cache_ttl=cache_ttl,
)
return HyperCacheManagementConfig(
@@ -68,9 +76,17 @@ def create_test_config(
update_fn=update_fn,
cache_name="test_cache",
route_refresh_fn=route_refresh_fn,
+ refresh_ttl_min_fraction=refresh_ttl_min_fraction,
)
+class TestRefreshTtlMinFractionValidation(SimpleTestCase):
+ @parameterized.expand([("zero", 0.0), ("above_one", 1.5), ("days_mistaken_for_a_fraction", 7.0)])
+ def test_a_fraction_outside_the_unit_range_is_refused(self, _name: str, fraction: float) -> None:
+ with self.assertRaises(ValueError):
+ create_test_config(refresh_ttl_min_fraction=fraction)
+
+
class TestDjangoKeyPrefix(BaseTest):
"""Test _django_key_prefix property extraction."""
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index c3575f1054d4..128af11cc218 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -773,6 +773,9 @@ FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(
# group_type_mapping (personhog lag), same as the signal-driven write path.
should_skip_write=_skip_write_if_group_mapping_emptied,
refresh_only_fields=_FLAG_DEFINITIONS_REFRESH_ONLY_FIELDS,
+ # This cache is built in bulk, so its entries come due in bulk. The cost of dispersing
+ # them is that each entry is refreshed more often than a flat TTL would refresh it.
+ refresh_ttl_min_fraction=0.7,
)