: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(remote-config): dual-write hypercache to shared redis (#59296)
Patricio2d44133a0707
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex 5c66756256b4..cf416dfe2286 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -75,15 +75,16 @@ class RemoteConfig(UUIDTModel):except RemoteConfig.DoesNotExist:return HyperCacheStoreMissing()+ has_dedicated_cache = FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHESreturn HyperCache(namespace="array",value="config.json",token_based=True, # We store and load via the team tokenload_fn=load_config,- # Route writes to the dedicated cache the Rust feature-flags service reads from.- # Without this, prod writes land in the shared cache while Rust reads from the- # dedicated one, forcing every /flags config_response to fall through to S3.- cache_alias=FLAGS_DEDICATED_CACHE_ALIAS if FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHES else None,+ 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,)def _build_session_recording_config(self, team: Team) -> dict:diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex f401e1803876..1910396a9218 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -138,6 +138,7 @@ class HyperCache:cache_ttl: int = DEFAULT_CACHE_TTL,cache_miss_ttl: int = DEFAULT_CACHE_MISS_TTL,cache_alias: Optional[str] = None,+ secondary_cache_alias: Optional[str] = None,batch_load_fn: Optional[Callable[[list[Team]], dict[int, dict]]] = None,enable_etag: bool = False,expiry_sorted_set_key: Optional[str] = None,@@ -160,6 +161,13 @@ class HyperCache:self.cache_client = cacheself.redis_url = settings.REDIS_URL+ # Optional secondary cache; writes are mirrored on a best-effort basis.+ self.secondary_cache_client = (+ caches[secondary_cache_alias]+ if secondary_cache_alias and secondary_cache_alias in settings.CACHES+ else None+ )+@staticmethoddef team_from_key(key: KeyType) -> Team:if isinstance(key, Team):@@ -413,6 +421,21 @@ class HyperCache:finally:self._remove_expiry_tracking(key)+ def _mirror_to_secondary(self, op: Callable[..., None]) -> None:+ """Best-effort mirror write; failures are logged and captured, never propagated."""+ if self.secondary_cache_client is None:+ return+ try:+ op(self.secondary_cache_client)+ except Exception as e:+ logger.warning(+ "HyperCache secondary cache write failed",+ namespace=self.namespace,+ value=self.value,+ exc_info=True,+ )+ capture_exception(e)+def _set_cache_value_redis(self, key: KeyType, data: dict | None | HyperCacheStoreMissing, ttl: Optional[int] = None) -> int | None:@@ -425,8 +448,10 @@ class HyperCache:etag_key = self.get_etag_key(key)if data is None or isinstance(data, HyperCacheStoreMissing):self.cache_client.set(cache_key, _HYPER_CACHE_EMPTY_VALUE, timeout=self.cache_miss_ttl)+ self._mirror_to_secondary(lambda c: c.set(cache_key, _HYPER_CACHE_EMPTY_VALUE, timeout=self.cache_miss_ttl))# Always delete ETag key to clean up stale ETags from when enable_etag was Trueself.cache_client.delete(etag_key)+ self._mirror_to_secondary(lambda c: c.delete(etag_key))return Noneelse:timeout = ttl if ttl is not None else self.cache_ttl@@ -437,10 +462,13 @@ class HyperCache:# Write data and ETag via pipeline (single Redis round trip)# Note this is not strictly atomic, but good enough for our use caseself.cache_client.set_many({cache_key: json_data, etag_key: etag}, timeout=timeout)+ self._mirror_to_secondary(lambda c: c.set_many({cache_key: json_data, etag_key: etag}, timeout=timeout))else:self.cache_client.set(cache_key, json_data, timeout=timeout)+ self._mirror_to_secondary(lambda c: c.set(cache_key, json_data, timeout=timeout))# Clean up stale ETag if ETags were previously enabledself.cache_client.delete(etag_key)+ self._mirror_to_secondary(lambda c: c.delete(etag_key))return len(json_data)def _set_cache_value_s3(self, key: KeyType, data: dict | None | HyperCacheStoreMissing, ttl: Optional[int] = None):diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex 10564150b902..2c41b79fd12e 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -460,6 +460,150 @@ class TestHyperCacheCustomCacheClient(BaseTest):assert default_etag is None+class TestHyperCacheSecondaryCache(BaseTest):+ """Test the secondary_cache_alias dual-write path used during cluster migrations."""++ @property+ def sample_data(self) -> dict:+ return {"key": "value", "nested": {"data": "test"}}++ @parameterized.expand(+ [+ # (name, enable_etag, input_kind, key_kind)+ # input_kind: "sample" passes self.sample_data; "missing" passes HyperCacheStoreMissing()+ # key_kind: which key on the HyperCache to assert against ("cache_key" or "etag_key")+ ("data_payload", False, "sample", "cache_key"),+ ("etag_alongside_data", True, "sample", "etag_key"),+ ("missing_sentinel", False, "missing", "cache_key"),+ ]+ )+ @override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "default-secondary-test-cache",+ },+ "flags_dedicated": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "flags-dedicated-secondary-test-cache",+ },+ }+ )+ def test_dual_writes_to_both_caches(self, _name, enable_etag, input_kind, key_kind):+ """Every write branch in _set_cache_value_redis is mirrored to the secondary cache."""+ from django.core.cache import caches++ caches["default"].clear()+ caches["flags_dedicated"].clear()++ data: dict | HyperCacheStoreMissing = self.sample_data if input_kind == "sample" else HyperCacheStoreMissing()++ def load_fn(team):+ return data++ hc = HyperCache(+ namespace="test",+ value="value",+ load_fn=load_fn,+ cache_alias="flags_dedicated",+ secondary_cache_alias="default",+ enable_etag=enable_etag,+ )++ team_id = self.team.id+ hc.set_cache_value(team_id, data)++ target_key = hc.get_etag_key(team_id) if key_kind == "etag_key" else hc.get_cache_key(team_id)+ primary_value = caches["flags_dedicated"].get(target_key)+ secondary_value = caches["default"].get(target_key)++ # Both caches must hold the same value. sort_keys=True ensures byte-for-byte+ # equality of the serialized payload, which also keeps ETags consistent.+ assert primary_value is not None+ assert primary_value == secondary_value++ # Branch-specific shape check on the dual-written value.+ if input_kind == "missing":+ assert primary_value == "__missing__"+ elif key_kind == "etag_key":+ # 16-char hex hash from HyperCache._compute_etag.+ assert isinstance(primary_value, str) and len(primary_value) == 16+ else:+ assert primary_value == json.dumps(self.sample_data, sort_keys=True)++ @override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "default-secondary-failure-test-cache",+ },+ "flags_dedicated": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "flags-dedicated-secondary-failure-test-cache",+ },+ }+ )+ def test_secondary_failure_does_not_block_primary(self):+ """A broken secondary cache must not raise — primary write stays authoritative."""+ from django.core.cache import caches++ caches["default"].clear()+ caches["flags_dedicated"].clear()++ def load_fn(team):+ return self.sample_data++ hc = HyperCache(+ namespace="test",+ value="value",+ load_fn=load_fn,+ cache_alias="flags_dedicated",+ secondary_cache_alias="default",+ )++ team_id = self.team.id++ # Replace the secondary client with one that raises on every write op.+ broken = Mock()+ broken.set.side_effect = RuntimeError("secondary down")+ broken.set_many.side_effect = RuntimeError("secondary down")+ broken.delete.side_effect = RuntimeError("secondary down")+ hc.secondary_cache_client = broken++ # Must not raise.+ hc.set_cache_value(team_id, self.sample_data)++ # Primary cache still got the write.+ cache_key = hc.get_cache_key(team_id)+ primary_value = caches["flags_dedicated"].get(cache_key)+ assert primary_value == json.dumps(self.sample_data, sort_keys=True)++ # The broken secondary received the write attempt.+ broken.set.assert_called()++ def test_unknown_secondary_alias_falls_back_to_no_op(self):+ """A secondary_cache_alias not in settings.CACHES is silently ignored."""++ def load_fn(team):+ return self.sample_data++ hc = HyperCache(+ namespace="test",+ value="value",+ load_fn=load_fn,+ secondary_cache_alias="does_not_exist",+ )++ assert hc.secondary_cache_client is None++ # set_cache_value should still work via the primary (default) cache.+ team_id = self.team.id+ cache.clear()+ hc.set_cache_value(team_id, self.sample_data)+ cache_key = hc.get_cache_key(team_id)+ assert cache.get(cache_key) == json.dumps(self.sample_data, sort_keys=True)++class TestHyperCacheBatchGetFromCache(BaseTest):"""Tests for batch_get_from_cache() method using MGET optimization."""