: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(flags): keep array/config.json warm to avoid S3 fallback on TTL expiry (#65340)
Matheus Batistaa878297d044b
diff --git a/posthog/management/commands/test/test_warm_remote_configs_cache.py b/posthog/management/commands/test/test_warm_remote_configs_cache.pyindex 754ada3373e7..dd9fd15c1fd9 100644--- a/posthog/management/commands/test/test_warm_remote_configs_cache.py+++ b/posthog/management/commands/test/test_warm_remote_configs_cache.py@@ -1,7 +1,7 @@from io import StringIOfrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.core.management import call_commandfrom django.core.management.base import CommandError@@ -111,6 +111,21 @@ class TestWarmRemoteConfigsCache(BaseTest):with self.assertRaisesMessage(CommandError, "row(s) failed to warm"):call_command("warm_remote_configs_cache", stdout=StringIO())+ @patch("posthog.storage.hypercache.get_client")+ def test_warm_seeds_expiry_tracking(self, mock_get_client):+ # The warm seeds the remote_config_cache_expiry sorted set the hourly refresh reads.+ from posthog.models.remote_config import REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET++ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis++ call_command("warm_remote_configs_cache", stdout=StringIO())++ mock_redis.zadd.assert_called()+ sorted_set_key, member_map = mock_redis.zadd.call_args[0]+ assert sorted_set_key == REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET+ assert self.team.api_token in member_map+def test_does_not_write_to_s3(self):# Regression guard: the warm path must be Redis-only. Writing to S3 per# row would dominate runtime at the scale this command is built fordiff --git a/posthog/management/commands/warm_remote_configs_cache.py b/posthog/management/commands/warm_remote_configs_cache.pyindex 17d9fb8f1f03..b9bba0449d46 100644--- a/posthog/management/commands/warm_remote_configs_cache.py+++ b/posthog/management/commands/warm_remote_configs_cache.py@@ -9,11 +9,12 @@ for teams that haven't been organically re-synced. This command warms it from thpersisted RemoteConfig.config column without calling build_config(), avoiding theexpense and side effects of a full rebuild across tens of thousands of teams.-Writes go through `HyperCache.set_cache_value_redis_only`, which writes to Redis-only and skips S3 and expiry tracking. S3 already has fresh data via the normal-sync() path, and the goal here is specifically to populate the Redis tier the-Rust service reads first. A per-row S3 PUT would turn a fast Redis backfill-into hours of synchronous boto3 round-trips for tens of thousands of teams.+Writes go through `HyperCache.set_cache_value_redis_only` with `track_expiry=True`,+which writes to Redis (plus the secondary mirror) and seeds the+`remote_config_cache_expiry` sorted set, but skips S3 — S3 already holds fresh data+via the normal sync() path, and the goal here is to populate the Redis tier the Rust+service reads first. A per-row S3 PUT would turn a fast Redis backfill into hours of+synchronous boto3 round-trips for tens of thousands of teams.Race note: this reads `RemoteConfig.config` via a cursored snapshot and writesit to Redis. If an organic `sync()` for the same team writes a newer config to@@ -118,7 +119,8 @@ class Command(BaseCommand):continuetry:- hypercache.set_cache_value_redis_only(team.api_token, remote_config.config)+ # Pass the Team (not the token) so track_expiry stamps the expiry sorted set.+ hypercache.set_cache_value_redis_only(team, remote_config.config, track_expiry=True)warmed += 1except Exception:failed += 1diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex 2030bdee38f9..c8ef4d3f5b57 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -1,3 +1,4 @@+import osimport jsonfrom typing import Any@@ -46,6 +47,14 @@ REMOTE_CONFIG_CDN_PURGE_COUNTER = Counter(logger = structlog.get_logger(__name__)+# Sorted set tracking each team's array/config.json cache-entry expiry, so the hourly+# refresh task can re-stamp entries before the TTL lapses and reads fall through to S3.+REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET = "remote_config_cache_expiry"++# 30-day Redis TTL for array/config.json (env-tunable). The refresh task and sync()+# re-stamp entries well within this window, so the TTL is only a backstop.+REMOTE_CONFIG_CACHE_TTL = int(os.environ.get("REMOTE_CONFIG_CACHE_TTL", str(60 * 60 * 24 * 30)))+@tracer.start_as_current_span("RemoteConfig.indent_js")def indent_js(js_content: str, indent: int = 4) -> str:@@ -69,10 +78,12 @@ class RemoteConfig(UUIDTModel):@classmethoddef get_hypercache(cls):- def load_config(token):+ def load_config(key):+ # Key may be a Team, api_token, or team id depending on the caller.try:- return RemoteConfig.objects.select_related("team").get(team__api_token=token).build_config()- except RemoteConfig.DoesNotExist:+ team = HyperCache.team_from_key(key)+ return RemoteConfig.objects.select_related("team").get(team=team).build_config()+ except (Team.DoesNotExist, RemoteConfig.DoesNotExist):return HyperCacheStoreMissing()has_dedicated_cache = FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHES@@ -81,10 +92,12 @@ class RemoteConfig(UUIDTModel):value="config.json",token_based=True, # We store and load via the team tokenload_fn=load_config,+ cache_ttl=REMOTE_CONFIG_CACHE_TTL,cache_alias=FLAGS_DEDICATED_CACHE_ALIAS if has_dedicated_cache else None,# Mirror to the shared Redis so the hypercache-server doesn't fall# through to (potentially stale) S3.secondary_cache_alias="default" if has_dedicated_cache else None,+ expiry_sorted_set_key=REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET,)def _build_session_recording_config(self, team: Team) -> dict:@@ -398,6 +411,14 @@ class RemoteConfig(UUIDTModel):config = self.build_config(bypass_recordings_quota_cache=bypass_recordings_quota_cache)if not force and config == self.config:+ # Content is unchanged: skip S3 + CDN purge, but still re-stamp the Redis+ # TTL and expiry entry so an unchanged team's cache never silently expires.+ try:+ RemoteConfig.get_hypercache().set_cache_value_redis_only(self.team, config, track_expiry=True)+ except Exception as e:+ logger.exception(f"Failed to refresh hypercache TTL for team {self.team_id}")+ capture_exception(e)+CELERY_TASK_REMOTE_CONFIG_SYNC.labels(result="no_changes").inc()logger.info(f"RemoteConfig for team {self.team_id} is unchanged")return@@ -407,7 +428,9 @@ class RemoteConfig(UUIDTModel):self.save()try:- RemoteConfig.get_hypercache().update_cache(self.team.api_token)+ # Pass the already-built config via data= so update_cache() reuses it+ # instead of rebuilding via load_fn.+ RemoteConfig.get_hypercache().update_cache(self.team, data=config)except Exception as e:logger.exception(f"Failed to update hypercache for team {self.team_id}")capture_exception(e)diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex ca9ff461fc25..096df3395288 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -3,7 +3,7 @@ from typing import Anyimport pytestfrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import override_settingsfrom django.utils import timezone@@ -11,7 +11,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom posthog.models.project import Project-from posthog.models.remote_config import RemoteConfig+from posthog.models.remote_config import REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET, RemoteConfigfrom products.actions.backend.models.action import Actionfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -510,6 +510,48 @@ class TestRemoteConfigCaching(_RemoteConfigBase):self.remote_config.sync()assert RemoteConfig.get_hypercache().get_from_cache(self.team.api_token) is not None+ @patch("posthog.storage.hypercache.get_client")+ def test_change_path_writes_s3_and_tracks_expiry_with_single_build(self, mock_get_client):+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis++ # Force a content change so sync() takes the change path.+ self.remote_config.config["token"] = "FORCE_CHANGE"++ with (+ patch("posthog.storage.object_storage.write") as mock_s3_write,+ patch.object(RemoteConfig, "build_config", wraps=self.remote_config.build_config) as mock_build,+ ):+ self.remote_config.sync()++ # The already-built config is reused — build_config() runs exactly once.+ assert mock_build.call_count == 1+ # Change path writes through to S3 and stamps expiry tracking.+ mock_s3_write.assert_called()+ mock_redis.zadd.assert_called_once()+ assert mock_redis.zadd.call_args[0][0] == REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET++ @patch("posthog.storage.hypercache.get_client")+ def test_no_change_path_restamps_redis_and_expiry_without_s3_or_cdn(self, mock_get_client):+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis++ with (+ patch("posthog.storage.object_storage.write") as mock_s3_write,+ patch.object(RemoteConfig, "_purge_cdn") as mock_purge,+ ):+ # No content change → self-heal path.+ self.remote_config.sync()++ # Self-heal must skip the content-dependent work (S3 PUT, CDN purge)...+ mock_s3_write.assert_not_called()+ mock_purge.assert_not_called()+ # ...but still re-stamp the expiry sorted set so the entry stays tracked.+ mock_redis.zadd.assert_called_once()+ assert mock_redis.zadd.call_args[0][0] == REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET+ # And the Redis tier is repopulated with the unchanged config.+ assert RemoteConfig.get_hypercache().get_from_cache(self.team.api_token) is not None+def test_hypercache_uses_dedicated_cache_when_alias_registered(self):from django.core.cache import cachesdiff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex c564836a6abd..f507b64a4e7a 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -412,20 +412,27 @@ class HyperCache:key: KeyType,ttl: Optional[int] = None,should_skip_write: Optional[Callable[[KeyType, dict], bool]] = None,+ data: dict | None = None,) -> bool:+ """+ Load (or accept a pre-built) value, write it to all tiers, and emit sync metrics.++ Pass ``data`` to write an already-built value and skip ``load_fn``; when None the+ value is loaded via ``load_fn``.+ """logger.info(f"Syncing {self.namespace} cache for team {key}")start_time = time.time()success = Falsesize: int | None = Nonetry:- data = self.load_fn(key)- if should_skip_write is not None and isinstance(data, dict) and should_skip_write(key, data):+ value = self.load_fn(key) if data is None else data+ if should_skip_write is not None and isinstance(value, dict) and should_skip_write(key, value):# A caller-supplied predicate vetoed persisting this freshly loaded# value (e.g. it would overwrite good data with a degraded one). Keep# the existing entry; the predicate owns its own metric/logging.return False- size = self.set_cache_value(key, data, ttl=ttl)+ size = self.set_cache_value(key, value, ttl=ttl)success = Truereturn Trueexcept HyperCacheDependencyUnavailable:@@ -467,18 +474,29 @@ class HyperCache:key: KeyType,data: dict | None | HyperCacheStoreMissing,ttl: Optional[int] = None,+ track_expiry: bool = False,) -> int | None:"""- Write only to the configured cache backend (self.cache_client), skipping S3- and expiry tracking.+ Write only to the configured cache backend (self.cache_client), skipping S3.++ Use this for backfills and TTL refreshes where S3 already holds fresh data+ (e.g. via the normal sync() path) and the only cold tier is the cache backend.+ In prod with cache_alias=FLAGS_DEDICATED_CACHE_ALIAS this is the dedicated flags+ Redis; in dev/test it's whatever the alias resolves to.++ When track_expiry=True the expiry sorted-set entry is re-stamped too, keeping a+ redis-only refresh visible to the refresh task. Requires a Team key (the identifier+ derives from it without a DB lookup); raises ValueError otherwise rather than+ silently skipping the stamp.- Use this for backfills where S3 is known to already hold fresh data- (e.g. populated by the normal sync() path) and the only cold tier is the- cache backend. In prod with cache_alias=FLAGS_DEDICATED_CACHE_ALIAS this is- the dedicated flags Redis; in dev/test it's whatever the alias resolves to.Returns the serialized size in bytes, or None for None/missing values."""- return self._set_cache_value_redis(key, data, ttl=ttl)+ if track_expiry and not isinstance(key, Team):+ raise ValueError("set_cache_value_redis_only(track_expiry=True) requires a Team key")+ size = self._set_cache_value_redis(key, data, ttl=ttl)+ if track_expiry and isinstance(key, Team):+ self._track_expiry(key, data, ttl=ttl)+ return sizedef clear_cache(self, key: KeyType, kinds: Optional[list[str]] = None):"""Test helper alias for delete_cache_entry."""diff --git a/posthog/storage/remote_config_cache.py b/posthog/storage/remote_config_cache.pynew file mode 100644index 000000000000..fbe97d9fb903--- /dev/null+++ b/posthog/storage/remote_config_cache.py@@ -0,0 +1,138 @@+"""+Expiry management for the array/config.json HyperCache.++The HyperCache is built and owned by RemoteConfig (`posthog/models/remote_config.py`);+this module wraps that instance with the shared expiry-tracking machinery+(`cache_expiry_manager` / `hypercache_manager`) so the hourly refresh task keeps the+dedicated flags Redis warm and reads don't fall through to S3.++The refresh path is deliberately lightweight: it re-stamps the last-synced+`RemoteConfig.config` rather than calling `build_config()`, because the daily+`sync_all_remote_configs` already rebuilds content fleet-wide. The hourly task's only+job is to prevent TTL expiry, so re-stamping the persisted blob is enough.+"""++from typing import Any++import structlog++from posthog.exceptions_capture import capture_exception+from posthog.metrics import TOMBSTONE_COUNTER+from posthog.models.remote_config import RemoteConfig+from posthog.models.team.team import Team+from posthog.storage.cache_expiry_manager import (+ cleanup_stale_expiry_tracking as cleanup_generic,+ get_teams_with_expiring_caches as get_teams_generic,+)+from posthog.storage.hypercache_manager import (+ HyperCacheManagementConfig,+ get_cache_stats as get_cache_stats_generic,+ push_hypercache_teams_processed_metrics,+)++logger = structlog.get_logger(__name__)+++# Module-level singleton so the management config and refresh task share one instance+# (and tests can patch it); RemoteConfig.get_hypercache() otherwise builds one per call.+remote_config_hypercache = RemoteConfig.get_hypercache()+++def update_remote_config_cache(team: Team | int, ttl: int | None = None) -> bool:+ """+ Re-stamp a team's array/config.json Redis entry to prevent TTL expiry.++ Reads the persisted RemoteConfig.config (not build_config()) and writes it+ redis-only with expiry tracking, skipping S3. Returns False without writing when+ the team has no RemoteConfig row or an empty config.++ Args:+ team: Team (or team id) whose cache entry should be refreshed+ ttl: Optional custom TTL in seconds (defaults to the HyperCache's cache_ttl)++ Returns:+ True if the cache entry was re-stamped, False if skipped+ """+ try:+ remote_config = RemoteConfig.objects.select_related("team").get(team=team)+ except RemoteConfig.DoesNotExist:+ logger.debug("No RemoteConfig to refresh", team=team)+ return False++ config = remote_config.config+ if not config:+ return False++ # Pass the loaded Team (the input may be a bare id) so track_expiry fires.+ remote_config_hypercache.set_cache_value_redis_only(remote_config.team, config, ttl=ttl, track_expiry=True)+ return True+++REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(+ hypercache=remote_config_hypercache,+ update_fn=update_remote_config_cache,+ cache_name="remote_config",+)+++def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) -> tuple[int, int]:+ """+ Refresh array/config.json caches expiring within ``ttl_threshold_hours``; returns (successful, failed).++ Batch-loads every expiring team's config in one query — the config lives in a separate+ table from Team, so re-stamping per team would be an N+1.+ """+ teams = get_teams_generic(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)+ if not teams:+ return 0, 0++ team_by_id = {team.id: team for team in teams}+ configs = dict(RemoteConfig.objects.filter(team__in=teams).values_list("team_id", "config"))++ successful = 0+ failed = 0+ for team_id, team in team_by_id.items():+ config = configs.get(team_id)+ if not config:+ # No config (missing row or empty) — nothing to re-stamp.+ failed += 1+ continue+ try:+ remote_config_hypercache.set_cache_value_redis_only(team, config, track_expiry=True)+ successful += 1+ except Exception as e:+ logger.exception("Failed to refresh remote config cache", team_id=team_id)+ capture_exception(e)+ failed += 1++ push_hypercache_teams_processed_metrics(+ namespace=REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG.namespace,+ cache_name=REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG.cache_name,+ successful=successful,+ failed=failed,+ )+ return successful, failed+++def cleanup_stale_expiry_tracking() -> int:+ """+ Remove expiry-tracking entries for teams that no longer exist in the database.++ Returns the number of stale entries removed. Should run daily to keep the+ ``remote_config_cache_expiry`` sorted set from accumulating deleted teams.+ """+ removed = cleanup_generic(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG)++ if removed > 0:+ TOMBSTONE_COUNTER.labels(+ namespace="array",+ operation="stale_expiry_tracking",+ component="remote_config_cache",+ ).inc(removed)++ return removed+++def get_cache_stats() -> dict[str, Any]:+ """Coverage / TTL-distribution / size statistics for the array/config.json cache."""+ return get_cache_stats_generic(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG)diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex 0d3cae220051..0a616f7722bf 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -1263,3 +1263,89 @@ class TestHyperCacheRemoveExpiryTracking(BaseTest):hc.clear_cache(42)mock_redis.zrem.assert_called_once_with(self.SORTED_SET_KEY, "42")+++class TestHyperCacheSetCacheValueRedisOnly(BaseTest):+ """Tests for set_cache_value_redis_only, focused on the track_expiry option."""++ SORTED_SET_KEY = "test_redis_only_expiry_sorted_set"++ @property+ def sample_data(self) -> dict:+ return {"key": "value"}++ def _make_hypercache(self, secondary: bool = False) -> HyperCache:+ return HyperCache(+ namespace="test",+ value="value",+ load_fn=lambda key: {"data": "test"},+ token_based=True,+ expiry_sorted_set_key=self.SORTED_SET_KEY,+ cache_alias="flags_dedicated" if secondary else None,+ secondary_cache_alias="default" if secondary else None,+ )++ @patch("posthog.storage.object_storage.write")+ @patch("posthog.storage.hypercache.get_client")+ def test_track_expiry_stamps_sorted_set_without_writing_s3(self, mock_get_client, mock_s3_write):+ mock_redis = Mock()+ mock_get_client.return_value = mock_redis++ hc = self._make_hypercache()+ hc.set_cache_value_redis_only(self.team, self.sample_data, track_expiry=True)++ # Redis-only path never touches S3.+ mock_s3_write.assert_not_called()+ # Expiry tracking is stamped with the team's api_token (token-based cache).+ mock_redis.zadd.assert_called_once()+ sorted_set_key, member_map = mock_redis.zadd.call_args[0]+ assert sorted_set_key == self.SORTED_SET_KEY+ assert str(self.team.api_token) in member_map+ # 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_default_does_not_track_expiry(self, mock_get_client):+ hc = self._make_hypercache()+ hc.set_cache_value_redis_only(self.team, self.sample_data)++ # No expiry tracking by default → no Redis client for the sorted set is requested.+ mock_get_client.assert_not_called()++ @patch("posthog.storage.hypercache.get_client")+ def test_track_expiry_raises_for_non_team_key(self, mock_get_client):+ # track_expiry needs a Team to derive the identifier, so a non-Team key must fail+ # loud rather than silently skip the stamp.+ hc = self._make_hypercache()+ with pytest.raises(ValueError, match="requires a Team key"):+ hc.set_cache_value_redis_only(self.team.api_token, self.sample_data, track_expiry=True)++ mock_get_client.assert_not_called()++ @override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "redis-only-secondary",+ },+ "flags_dedicated": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "redis-only-primary",+ },+ }+ )+ @patch("posthog.storage.hypercache.get_client")+ def test_track_expiry_mirrors_to_secondary_cache(self, mock_get_client):+ from django.core.cache import caches++ caches["default"].clear()+ caches["flags_dedicated"].clear()+ mock_get_client.return_value = Mock()++ hc = self._make_hypercache(secondary=True)+ hc.set_cache_value_redis_only(self.team, self.sample_data, track_expiry=True)++ cache_key = hc.get_cache_key(self.team)+ expected = json.dumps(self.sample_data, sort_keys=True)+ assert caches["flags_dedicated"].get(cache_key) == expected+ assert caches["default"].get(cache_key) == expecteddiff --git a/posthog/storage/test/test_remote_config_cache.py b/posthog/storage/test/test_remote_config_cache.pynew file mode 100644index 000000000000..696e44b29dad--- /dev/null+++ b/posthog/storage/test/test_remote_config_cache.py@@ -0,0 +1,102 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from posthog.models.remote_config import RemoteConfig+from posthog.storage.remote_config_cache import (+ cleanup_stale_expiry_tracking,+ refresh_expiring_caches,+ update_remote_config_cache,+)+++class TestUpdateRemoteConfigCache(BaseTest):+ def setUp(self):+ super().setUp()+ RemoteConfig.objects.filter(team=self.team).delete()+ self.remote_config = RemoteConfig.objects.create(+ team=self.team,+ config={"token": self.team.api_token, "hasFeatureFlags": False},+ )++ @patch("posthog.storage.remote_config_cache.remote_config_hypercache")+ def test_writes_redis_only_with_expiry_tracking(self, mock_hypercache):+ result = update_remote_config_cache(self.team)++ assert result is True+ mock_hypercache.set_cache_value_redis_only.assert_called_once()+ args, kwargs = mock_hypercache.set_cache_value_redis_only.call_args+ # Keyed by Team so expiry tracking fires; re-stamps the persisted config; skips S3.+ assert args[0] == self.team+ assert args[1] == self.remote_config.config+ assert kwargs["track_expiry"] is True++ @patch("posthog.storage.remote_config_cache.remote_config_hypercache")+ def test_skips_empty_config(self, mock_hypercache):+ self.remote_config.config = {}+ self.remote_config.save(update_fields=["config"])++ result = update_remote_config_cache(self.team)++ assert result is False+ mock_hypercache.set_cache_value_redis_only.assert_not_called()++ @patch("posthog.storage.remote_config_cache.remote_config_hypercache")+ def test_skips_when_no_remote_config_row(self, mock_hypercache):+ self.remote_config.delete()++ result = update_remote_config_cache(self.team)++ assert result is False+ mock_hypercache.set_cache_value_redis_only.assert_not_called()+++class TestRefreshExpiringRemoteConfigCaches(BaseTest):+ @patch("posthog.storage.remote_config_cache.remote_config_hypercache")+ @patch("posthog.storage.cache_expiry_manager.get_client")+ @patch("posthog.storage.cache_expiry_manager.time")+ def test_refreshes_only_expiring_entries(self, mock_time, mock_get_client, mock_hypercache):+ RemoteConfig.objects.filter(team=self.team).delete()+ RemoteConfig.objects.create(team=self.team, config={"token": self.team.api_token})++ mock_time.time.return_value = 1_000_000+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis+ mock_redis.zrangebyscore.return_value = [self.team.api_token.encode()]++ successful, failed = refresh_expiring_caches(ttl_threshold_hours=24)++ assert (successful, failed) == (1, 0)+ mock_redis.zrangebyscore.assert_called_once_with(+ "remote_config_cache_expiry",+ "-inf",+ 1_000_000 + (24 * 3600),+ start=0,+ num=5000,+ )+ # The expiring team's entry was re-stamped redis-only with expiry tracking.+ mock_hypercache.set_cache_value_redis_only.assert_called_once()+ _, kwargs = mock_hypercache.set_cache_value_redis_only.call_args+ assert kwargs["track_expiry"] is True++ @patch("posthog.storage.cache_expiry_manager.get_client")+ def test_returns_zero_when_nothing_expiring(self, mock_get_client):+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis+ mock_redis.zrangebyscore.return_value = []++ assert refresh_expiring_caches(ttl_threshold_hours=24) == (0, 0)+++class TestCleanupStaleRemoteConfigExpiryTracking(BaseTest):+ @patch("posthog.storage.cache_expiry_manager.get_client")+ def test_removes_only_entries_for_deleted_teams(self, mock_get_client):+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis+ # One live team (kept) and one stale token (removed).+ mock_redis.zrange.return_value = [self.team.api_token.encode(), b"phc_does_not_exist"]+ mock_redis.zrem.return_value = 1++ removed = cleanup_stale_expiry_tracking()++ assert removed == 1+ mock_redis.zrem.assert_called_once_with("remote_config_cache_expiry", "phc_does_not_exist")diff --git a/posthog/tasks/remote_config.py b/posthog/tasks/remote_config.pyindex 10a5ebb877eb..2175e8a4b75a 100644--- a/posthog/tasks/remote_config.py+++ b/posthog/tasks/remote_config.py@@ -1,9 +1,14 @@+import time++from django.conf import settings+import structlogfrom celery import shared_taskfrom posthog.models.remote_config import RemoteConfigfrom posthog.models.team import Teamfrom posthog.scoping_audit import skip_team_scope_audit+from posthog.storage.remote_config_cache import cleanup_stale_expiry_tracking, get_cache_stats, refresh_expiring_cachesfrom posthog.tasks.utils import CeleryQueuelogger = structlog.get_logger(__name__)@@ -39,3 +44,75 @@ def sync_all_remote_configs() -> None:# Only select the id from the team querysetfor team_id in Team.objects.values_list("id", flat=True):update_team_remote_config.delay(team_id)+++@shared_task(+ ignore_result=True,+ # Long batch loop kept off the latency-sensitive default queue.+ queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,+ # Bound the worker slot so a stalled iteration can't pin it.+ soft_time_limit=15 * 60,+ time_limit=16 * 60,+)+def refresh_expiring_remote_config_cache_entries() -> None:+ """+ Hourly task that re-stamps array/config.json cache entries expiring within 24h,+ keeping the dedicated flags Redis warm so reads don't fall through to S3.+ """+ if not settings.FLAGS_REDIS_URL:+ logger.info("Flags Redis URL not set, skipping remote config cache refresh")+ return++ start_time = time.time()+ logger.info("Starting remote config cache refresh")++ try:+ successful, failed = refresh_expiring_caches(ttl_threshold_hours=24)++ # Scan after refresh to push coverage/TTL metrics to Pushgateway.+ stats_after = get_cache_stats()++ duration = time.time() - start_time++ logger.info(+ "Completed remote config cache refresh",+ successful_refreshes=successful,+ failed_refreshes=failed,+ total_cached=stats_after.get("total_cached", 0),+ total_teams=stats_after.get("total_teams", 0),+ cache_coverage=stats_after.get("cache_coverage", "unknown"),+ ttl_distribution=stats_after.get("ttl_distribution", {}),+ duration_seconds=duration,+ )+ except Exception as e:+ duration = time.time() - start_time+ logger.exception(+ "Failed to complete remote config cache refresh",+ error=str(e),+ duration_seconds=duration,+ )+ raise+++@shared_task(+ ignore_result=True,+ # Shares the refresh task's queue.+ queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,+ soft_time_limit=5 * 60,+ time_limit=6 * 60,+)+def cleanup_stale_remote_config_expiry_tracking_task() -> None:+ """+ Daily task that prunes expiry-tracking entries for deleted teams, keeping the+ remote_config_cache_expiry sorted set from growing unbounded.+ """+ if not settings.FLAGS_REDIS_URL:+ logger.info("Flags Redis URL not set, skipping remote config expiry tracking cleanup")+ return++ try:+ removed_count = cleanup_stale_expiry_tracking()+ logger.info("Completed remote config expiry tracking cleanup", removed_count=removed_count)+ except Exception as e:+ logger.exception("Failed to cleanup remote config expiry tracking", error=str(e))+ raisediff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 07ee935e9258..fd5c5fda8b86 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -27,7 +27,11 @@ from posthog.tasks.hypercache_verification import ()from posthog.tasks.integrations import refresh_integrationsfrom posthog.tasks.js_snippet_versioning import sync_js_snippet_manifest-from posthog.tasks.remote_config import sync_all_remote_configs+from posthog.tasks.remote_config import (+ cleanup_stale_remote_config_expiry_tracking_task,+ refresh_expiring_remote_config_cache_entries,+ sync_all_remote_configs,+)from posthog.tasks.surveys import sync_all_surveys_cachefrom posthog.tasks.tasks import (calculate_cohort,@@ -280,6 +284,20 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="flag definitions cache expiry tracking cleanup",)+ # Remote config (array/config.json) cache refresh - hourly at minute 45+ sender.add_periodic_task(+ crontab(hour="*", minute="45"),+ refresh_expiring_remote_config_cache_entries.s(),+ name="refresh expiring remote config cache entries",+ )++ # Remote config cache expiry tracking cleanup - daily at 3:45 AM+ sender.add_periodic_task(+ crontab(hour="3", minute="45"),+ cleanup_stale_remote_config_expiry_tracking_task.s(),+ name="remote config cache expiry tracking cleanup",+ )+# Team metadata cache verification - hourly at minute 20add_periodic_task_with_expiry(sender,diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 9277cf98bf7a..14a70ba266a6 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -80,6 +80,8 @@'posthog.tasks.plugin_server.fatal_plugin_error','posthog.tasks.plugin_server.hog_function_state_transition','posthog.tasks.push_notifications.send_user_push',+ 'posthog.tasks.remote_config.cleanup_stale_remote_config_expiry_tracking_task',+ 'posthog.tasks.remote_config.refresh_expiring_remote_config_cache_entries','posthog.tasks.remote_config.sync_all_remote_configs','posthog.tasks.remote_config.update_team_remote_config','posthog.tasks.split_person.split_person',diff --git a/posthog/tasks/test/test_remote_config.py b/posthog/tasks/test/test_remote_config.pyindex d0aadadfaa8e..c5866cd81ea4 100644--- a/posthog/tasks/test/test_remote_config.py+++ b/posthog/tasks/test/test_remote_config.py@@ -1,9 +1,20 @@+from collections.abc import Callable+from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.test import override_settings++from parameterized import parameterized+from posthog.models.project import Projectfrom posthog.models.remote_config import RemoteConfig-from posthog.tasks.remote_config import sync_all_remote_configs, update_team_remote_config+from posthog.tasks.remote_config import (+ cleanup_stale_remote_config_expiry_tracking_task,+ refresh_expiring_remote_config_cache_entries,+ sync_all_remote_configs,+ update_team_remote_config,+)class TestRemoteConfig(BaseTest):@@ -72,3 +83,43 @@ class TestRemoteConfig(BaseTest):mock_sync.reset_mock()update_team_remote_config(self.team.id)mock_sync.assert_called_once_with(bypass_recordings_quota_cache=False)+++class TestRemoteConfigCacheTasks(BaseTest):+ @parameterized.expand(+ [+ (+ "refresh",+ refresh_expiring_remote_config_cache_entries,+ "posthog.tasks.remote_config.refresh_expiring_caches",+ ),+ (+ "cleanup",+ cleanup_stale_remote_config_expiry_tracking_task,+ "posthog.tasks.remote_config.cleanup_stale_expiry_tracking",+ ),+ ]+ )+ def test_task_skips_work_when_flags_redis_url_unset(+ self, _name: str, task: Callable[[], None], inner_path: str+ ) -> None:+ with override_settings(FLAGS_REDIS_URL=""), patch(inner_path) as mock_inner:+ task()+ mock_inner.assert_not_called()++ def test_refresh_runs_work_when_flags_redis_url_set(self) -> None:+ with (+ override_settings(FLAGS_REDIS_URL="redis://test:6379/0"),+ patch("posthog.tasks.remote_config.refresh_expiring_caches", return_value=(0, 0)) as mock_refresh,+ patch("posthog.tasks.remote_config.get_cache_stats", return_value={}),+ ):+ refresh_expiring_remote_config_cache_entries()+ mock_refresh.assert_called_once_with(ttl_threshold_hours=24)++ def test_cleanup_runs_work_when_flags_redis_url_set(self) -> None:+ with (+ override_settings(FLAGS_REDIS_URL="redis://test:6379/0"),+ patch("posthog.tasks.remote_config.cleanup_stale_expiry_tracking", return_value=0) as mock_cleanup,+ ):+ cleanup_stale_remote_config_expiry_tracking_task()+ mock_cleanup.assert_called_once_with()