: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(hypercache): degrade primary Redis reads instead of raising (#70600)
posthog[bot]fab559ca1064
diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex f1770889ce3e..def3bfcb2c94 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -8,7 +8,9 @@ from django.conf import settingsfrom django.core.cache import cache, cachesimport structlog+import redis.exceptionsfrom botocore.exceptions import BotoCoreError, ClientError+from django_redis.exceptions import ConnectionInterruptedfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counter, Histogram@@ -19,6 +21,17 @@ from posthog.storage.object_storage import ObjectStorageErrorlogger = structlog.get_logger(__name__)+# Redis/transport failures the primary cache read degrades on, mirroring the S3/load_fn tiers below.+# django-redis wraps the underlying redis error in ConnectionInterrupted; we also catch the raw redis+# errors (and the builtin socket errors under OSError) in case a backend surfaces them directly.+_REDIS_READ_ERRORS = (+ ConnectionInterrupted,+ redis.exceptions.RedisError,+ ConnectionError,+ TimeoutError,+ OSError,+)+DEFAULT_CACHE_MISS_TTL = 60 * 60 * 24 # 1 day - it will be invalidated by the daily syncDEFAULT_CACHE_TTL = 60 * 60 * 24 * 30 # 30 days@@ -242,7 +255,14 @@ class HyperCache:def get_from_cache_with_source(self, key: KeyType) -> tuple[dict | None, str]:cache_key = self.get_cache_key(key)- data = self.cache_client.get(cache_key)+ try:+ data = self.cache_client.get(cache_key)+ except _REDIS_READ_ERRORS as e:+ # A Redis outage on the primary read must degrade to the S3/DB tiers below, never+ # bubble a 500 up to the request handler. Capture it for visibility, the way the S3+ # branch does, then fall through as a cache miss.+ capture_exception(e)+ data = Noneif data:HYPERCACHE_CACHE_COUNTER.labels(result="hit_redis", namespace=self.namespace, value=self.value).inc()@@ -319,7 +339,13 @@ class HyperCache:cache_keys = [self.get_cache_key(team) for team in teams]etag_keys = [self.get_etag_key(team) for team in teams] if self.enable_etag else []- cached_values = self.cache_client.get_many(cache_keys + etag_keys)+ try:+ cached_values = self.cache_client.get_many(cache_keys + etag_keys)+ except _REDIS_READ_ERRORS as e:+ # Degrade a Redis outage to an all-miss result rather than raising; there is no+ # S3/DB fallback in batch mode, so every team resolves to a clean "miss" below.+ capture_exception(e)+ cached_values = {}# Map results back to team IDs, counting hits and misses for batch metricsresults: dict[int, tuple[dict | None, str, str | None]] = {}@@ -356,7 +382,13 @@ class HyperCache:"""Get just the ETag for a cached value without loading the full response."""if not self.enable_etag:return None- return self.cache_client.get(self.get_etag_key(key))+ try:+ return self.cache_client.get(self.get_etag_key(key))+ except _REDIS_READ_ERRORS as e:+ # Degrade a Redis outage to a missing ETag rather than raising; callers treat a+ # None ETag as a miss/mismatch and fall back to the full response.+ capture_exception(e)+ return Nonedef get_if_none_match(self, key: KeyType, client_etag: str | None) -> tuple[dict | None, str | None, bool]:"""diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex ca28a56b88ae..00802dfd2554 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -7,9 +7,12 @@ from unittest.mock import Mock, patchfrom django.core.cache import cachefrom django.test import override_settings+import redis.exceptionsfrom botocore.exceptions import BotoCoreError, ClientError+from django_redis.exceptions import ConnectionInterruptedfrom parameterized import parameterized+from posthog.models.team.team import Teamfrom posthog.storage import object_storagefrom posthog.storage.hypercache import (DEFAULT_CACHE_MISS_TTL,@@ -152,6 +155,59 @@ class TestHyperCacheGetFromCache(HyperCacheTestBase):assert source == "db"+class TestHyperCacheRedisFailureDegrades(HyperCacheTestBase):+ """A Redis outage on a primary read must degrade to the next tier, never bubble a 500."""++ @parameterized.expand(+ [+ ("connection_interrupted", ConnectionInterrupted(connection=None)),+ ("redis_connection_error", redis.exceptions.ConnectionError("Error 111 connecting to redis:6379")),+ ("timeout_error", redis.exceptions.TimeoutError()),+ ]+ )+ def test_get_from_cache_redis_error_falls_back_to_s3(self, _name, exception):+ hc = self.hypercache++ with (+ patch.object(hc.cache_client, "get", side_effect=exception),+ patch.object(object_storage, "read", return_value=json.dumps(self.sample_data)),+ ):+ result, source = hc.get_from_cache_with_source(self.team_id)++ assert result == self.sample_data+ assert source == "s3"++ def test_get_from_cache_redis_error_falls_back_to_db_when_s3_empty(self):+ hc = self.hypercache++ with (+ patch.object(hc.cache_client, "get", side_effect=redis.exceptions.ConnectionError("redis down")),+ patch.object(object_storage, "read", return_value=None),+ ):+ result, source = hc.get_from_cache_with_source(self.team_id)++ assert result == {"default": "data"}+ assert source == "db"++ def test_batch_get_from_cache_redis_error_degrades_to_all_miss(self):+ hc = self.hypercache+ teams = [Team(id=1), Team(id=2)]++ with patch.object(hc.cache_client, "get_many", side_effect=ConnectionInterrupted(connection=None)):+ results = hc.batch_get_from_cache(teams)++ assert results == {1: (None, "miss", None), 2: (None, "miss", None)}++ def test_get_etag_redis_error_returns_none(self):+ def load_fn(team):+ return {"default": "data"}++ hc = HyperCache(namespace="etag_ns", value="etag_value", load_fn=load_fn, enable_etag=True)++ with patch.object(hc.cache_client, "get", side_effect=redis.exceptions.ConnectionError("redis down")):+ assert hc.get_etag(self.team_id) is None++class TestHyperCacheUpdateCache(HyperCacheTestBase):def test_update_cache_success(self):"""Test successful cache update"""