: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
perf(hypercache): skip unchanged writes in ETag-enabled caches (#66209)
Phil Haackfd2bae6b7021
diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex f507b64a4e7a..f1770889ce3e 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -68,6 +68,12 @@ HYPERCACHE_REBUILD_SKIPPED_COUNTER = Counter(labelnames=["namespace", "reason"],)+HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER = Counter(+ "posthog_hypercache_write_skipped_unchanged",+ "Content-propagation writes skipped because the ETag was unchanged, avoiding a redundant rewrite",+ labelnames=["namespace", "value"],+)+CACHE_SYNC_DURATION_HISTOGRAM = Histogram("posthog_hypercache_sync_duration_seconds","Time taken to sync hypercache in seconds",@@ -455,14 +461,36 @@ class HyperCache:emit_cache_sync_metrics(result, self.namespace, self.value, duration=duration, size=size)def set_cache_value(- self, key: KeyType, data: dict | None | HyperCacheStoreMissing, ttl: Optional[int] = None+ self,+ key: KeyType,+ data: dict | None | HyperCacheStoreMissing,+ ttl: Optional[int] = None,+ skip_if_unchanged: bool = False,) -> int | None:"""Set cache value in Redis and S3, returning the serialized size in bytes.Returns None for None/missing values.++ When ``skip_if_unchanged`` is set, an ETag-enabled dict payload whose ETag matches+ the stored one is not rewritten (the counter records the skip; the serialized size+ is still returned). Skipping does not re-stamp expiry, so the cache must own an+ independent refresh path that does. ``expiry_sorted_set_key`` is the structural marker+ for that path (the refresh task reads the set to find expiring entries), so a refresh-less+ cache that opts into skipping raises rather than silently letting entries expire."""- size = self._set_cache_value_redis(key, data, ttl=ttl)+ if skip_if_unchanged and not self.expiry_sorted_set_key:+ raise ValueError(+ "set_cache_value(skip_if_unchanged=True) requires expiry tracking "+ "(expiry_sorted_set_key) with a scheduled refresh that re-stamps the TTL"+ )+ json_data: str | None = None+ if skip_if_unchanged and self.enable_etag and isinstance(data, dict):+ json_data = json.dumps(data, sort_keys=True)+ if self._compute_etag(json_data) == self.get_etag(key):+ HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER.labels(namespace=self.namespace, value=self.value).inc()+ return len(json_data)+ size = self._set_cache_value_redis(key, data, ttl=ttl, json_data=json_data)self._set_cache_value_s3(key, data, ttl=ttl)# Only track expiry when we have a Team object (avoids DB lookup)if isinstance(key, Team):@@ -535,12 +563,19 @@ class HyperCache:capture_exception(e)def _set_cache_value_redis(- self, key: KeyType, data: dict | None | HyperCacheStoreMissing, ttl: Optional[int] = None+ self,+ key: KeyType,+ data: dict | None | HyperCacheStoreMissing,+ ttl: Optional[int] = None,+ json_data: str | None = None,) -> int | None:"""Set cache value in Redis and return the serialized size in bytes.Returns None for None/missing values, otherwise returns len(json_data).++ Pass ``json_data`` to reuse an already-serialized payload (a caller that hashed it+ for an ETag comparison) instead of re-running ``json.dumps`` over a large value."""cache_key = self.get_cache_key(key)etag_key = self.get_etag_key(key)@@ -554,7 +589,8 @@ class HyperCache:else:timeout = ttl if ttl is not None else self.cache_ttl# Use sort_keys for deterministic serialization (consistent ETags)- json_data = json.dumps(data, sort_keys=True)+ if json_data is None:+ json_data = json.dumps(data, sort_keys=True)if self.enable_etag:etag = self._compute_etag(json_data)# Write data and ETag via pipeline (single Redis round trip)diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex 0a616f7722bf..ca28a56b88ae 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -1349,3 +1349,99 @@ class TestHyperCacheSetCacheValueRedisOnly(BaseTest):expected = json.dumps(self.sample_data, sort_keys=True)assert caches["flags_dedicated"].get(cache_key) == expectedassert caches["default"].get(cache_key) == expected+++@override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "skip-if-unchanged-test-cache",+ },+ }+)+class TestHyperCacheSkipIfUnchanged(BaseTest):+ """set_cache_value(skip_if_unchanged=True) avoids redundant rewrites of unchanged content."""++ @property+ def sample_data(self) -> dict:+ return {"key": "value", "nested": {"data": "test"}}++ def _hypercache(self, enable_etag: bool = True) -> HyperCache:+ return HyperCache(+ namespace="skip_ns",+ value="skip_value",+ load_fn=lambda team: {"default": "data"},+ enable_etag=enable_etag,+ expiry_sorted_set_key="skip_ns_expiry",+ )++ def test_requires_expiry_tracking(self):+ """skip_if_unchanged on a cache with no expiry tracking can't keep entries alive,+ so it raises rather than silently letting them expire."""+ hc = HyperCache(+ namespace="skip_ns",+ value="skip_value",+ load_fn=lambda team: {"default": "data"},+ enable_etag=True,+ )+ with pytest.raises(ValueError, match="expiry tracking"):+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)++ def setUp(self):+ super().setUp()+ cache.clear()++ def test_skips_redundant_write_when_unchanged(self):+ """An ETag-enabled signal write of byte-identical data skips the Redis and S3 rewrites."""+ hc = self._hypercache()+ with patch.object(hc, "_set_cache_value_s3") as s3_write:+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)+ etag_before = hc.get_etag(self.team.id)++ with (+ patch.object(hc, "_set_cache_value_redis", wraps=hc._set_cache_value_redis) as redis_write,+ patch("posthog.storage.hypercache.HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER") as skip_counter,+ ):+ size = hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)++ redis_write.assert_not_called()+ # The S3 PUT is the costlier write this optimization skips; only the first write reached it.+ s3_write.assert_called_once()+ # The skip counter is the only signal ops have that the optimization fired.+ skip_counter.labels.assert_called_once_with(namespace="skip_ns", value="skip_value")+ skip_counter.labels.return_value.inc.assert_called_once()+ assert size == len(json.dumps(self.sample_data, sort_keys=True))+ # The stored ETag is untouched, so readers comparing ETags won't refetch.+ assert hc.get_etag(self.team.id) == etag_before++ def test_changed_write_reuses_serialization_correctly(self):+ """When the content changed, the skip path's serialization is threaded into the Redis+ write instead of re-dumped; the stored value and ETag must still match the new payload."""+ hc = self._hypercache()+ changed = {"key": "changed", "extra": [3, 1, 2]}+ with patch.object(hc, "_set_cache_value_s3"):+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)+ hc.set_cache_value(self.team.id, changed, skip_if_unchanged=True)++ assert hc.get_from_cache(self.team.id) == changed+ assert hc.get_etag(self.team.id) == hc._compute_etag(json.dumps(changed, sort_keys=True))++ @parameterized.expand(+ [+ # Each case is a distinct way the skip guard fails to hold, so the write proceeds.+ ("content_changed", True, True, {"key": "changed"}),+ ("etag_disabled", False, True, None),+ ("skip_flag_off", True, False, None),+ ]+ )+ def test_write_proceeds(self, _name, enable_etag, skip_if_unchanged, second_data):+ """The write proceeds whenever the skip guard doesn't hold: content changed, ETags+ disabled, or skip_if_unchanged off (the refresh/backfill path, which rewrites+ unchanged content to extend the TTL)."""+ hc = self._hypercache(enable_etag=enable_etag)+ second = self.sample_data if second_data is None else second_data+ with patch.object(hc, "_set_cache_value_s3"):+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=skip_if_unchanged)+ with patch.object(hc, "_set_cache_value_redis", wraps=hc._set_cache_value_redis) as redis_write:+ hc.set_cache_value(self.team.id, second, skip_if_unchanged=skip_if_unchanged)+ redis_write.assert_called_once()diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex 6f3f6b7f5703..ffbb4bcef488 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -523,8 +523,13 @@ def update_flag_caches(team: Team):# two variants can't drift out of sync.without_cohorts = _get_flags_response_for_local_evaluation(team, include_cohorts=False)- size_with_cohorts = flag_definitions_hypercache.set_cache_value(team, with_cohorts)- size_without_cohorts = flag_definitions_without_cohorts_hypercache.set_cache_value(team, without_cohorts)+ # Signal-driven rebuilds skip the write when the payload is unchanged: most+ # saves that trigger this (notably the nightly cohort recalculation) don't alter+ # flag definitions, so the ETag is identical and a rewrite would only add load.+ size_with_cohorts = flag_definitions_hypercache.set_cache_value(team, with_cohorts, skip_if_unchanged=True)+ size_without_cohorts = flag_definitions_without_cohorts_hypercache.set_cache_value(+ team, without_cohorts, skip_if_unchanged=True+ )success = Trueexcept GroupTypesUnavailable as e:diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 1e1a1d544cb9..3f28f90df918 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -253,6 +253,21 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):response, _ = flag_definitions_hypercache.get_from_cache_with_source(self.team)return (response or {}).get("group_type_mapping", {})+ @patch("posthog.storage.hypercache.HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER")+ def test_unchanged_rebuild_skips_both_variant_writes(self, mock_skip_counter):+ # The signal path opts into skip_if_unchanged=True. A second rebuild with no flag+ # changes must skip the rewrite for both variants; dropping the kwarg silently+ # reverts the optimization and only this assertion would catch it.+ update_flag_caches(self.team)+ mock_skip_counter.labels.assert_not_called()++ update_flag_caches(self.team)++ assert mock_skip_counter.labels.call_count == 2+ mock_skip_counter.labels.assert_any_call(namespace="feature_flags", value="flags_with_cohorts.json")+ mock_skip_counter.labels.assert_any_call(namespace="feature_flags", value="flags_without_cohorts.json")+ assert mock_skip_counter.labels.return_value.inc.call_count == 2+@patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_REBUILD_SKIPPED_COUNTER")def test_skips_write_on_group_types_unavailable(self, mock_skipped_counter):# Warm with the real fetch so a prior good entry exists