: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(caching): cache empty active-teams result to avoid repeated SELECT (#58217)
Robbie0b218a6ac418
diff --git a/posthog/caching/test/test_caching_utils.py b/posthog/caching/test/test_caching_utils.pyindex 80a3c3e16541..32dc3ab05a0c 100644--- a/posthog/caching/test/test_caching_utils.py+++ b/posthog/caching/test/test_caching_utils.py@@ -1,16 +1,25 @@import pytestfrom unittest.mock import patch-from posthog.caching.utils import IN_A_DAY, RECENTLY_ACCESSED_TEAMS_REDIS_KEY, is_team_active+from posthog.caching.utils import (+ IN_A_DAY,+ IN_AN_HOUR,+ RECENTLY_ACCESSED_TEAMS_POPULATED_KEY,+ RECENTLY_ACCESSED_TEAMS_REDIS_KEY,+ active_teams,+ is_team_active,+)from posthog.redis import get_client@pytest.fixture(autouse=True)-def clear_redis_key():+def clear_redis_keys():redis = get_client()redis.delete(RECENTLY_ACCESSED_TEAMS_REDIS_KEY)+ redis.delete(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY)yieldredis.delete(RECENTLY_ACCESSED_TEAMS_REDIS_KEY)+ redis.delete(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY)@pytest.mark.parametrize(@@ -25,6 +34,7 @@ def clear_redis_key():def test_is_team_active_with_existing_key(members, expected):redis = get_client()redis.zadd(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, members)+ redis.set(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY, "1")with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:assert is_team_active(42) is expected@@ -39,21 +49,70 @@ def test_is_team_active_populates_when_key_missing():def test_is_team_active_returns_false_when_clickhouse_empty():+ with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:+ mock_sync_execute.return_value = []+ assert is_team_active(42) is False+ mock_sync_execute.assert_called_once()+++def test_is_team_active_caches_empty_clickhouse_result():redis = get_client()with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:mock_sync_execute.return_value = []+assert is_team_active(42) is False- # no populate should have happened — key still missing, no TTL set- assert not redis.exists(RECENTLY_ACCESSED_TEAMS_REDIS_KEY)+ assert is_team_active(43) is False+ assert is_team_active(44) is False++ assert mock_sync_execute.call_count == 1+ assert redis.exists(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY)-def test_populate_sets_24h_ttl():+def test_active_teams_caches_empty_clickhouse_result():+ redis = get_client()+ with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:+ mock_sync_execute.return_value = []++ assert active_teams() == set()+ assert active_teams() == set()++ assert mock_sync_execute.call_count == 1+ assert redis.exists(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY)+++def test_populate_sets_24h_ttl_on_both_keys():redis = get_client()with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:mock_sync_execute.return_value = [(42, 10.0), (43, 20.0)]is_team_active(42)- ttl = redis.ttl(RECENTLY_ACCESSED_TEAMS_REDIS_KEY)- # TTL is approximate due to the brief gap between EXPIRE and TTL calls- assert 0 < ttl <= IN_A_DAY- assert ttl >= IN_A_DAY - 5+ for key in (RECENTLY_ACCESSED_TEAMS_REDIS_KEY, RECENTLY_ACCESSED_TEAMS_POPULATED_KEY):+ ttl = redis.ttl(key)+ # TTL is approximate due to the brief gap between EXPIRE and TTL calls+ assert 0 < ttl <= IN_A_DAY, f"{key} ttl={ttl}"+ assert ttl >= IN_A_DAY - 5, f"{key} ttl={ttl}"+++def test_populate_clears_stale_zset_when_clickhouse_empty():+ redis = get_client()+ redis.zadd(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, {"42": 10.0})++ with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:+ mock_sync_execute.return_value = []+ assert is_team_active(99) is False++ assert not redis.exists(RECENTLY_ACCESSED_TEAMS_REDIS_KEY)+ with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:+ assert is_team_active(42) is False+ mock_sync_execute.assert_not_called()+++def test_populate_sets_short_ttl_on_marker_when_clickhouse_empty():+ redis = get_client()+ with patch("posthog.caching.utils.sync_execute") as mock_sync_execute:+ mock_sync_execute.return_value = []+ is_team_active(42)++ ttl = redis.ttl(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY)+ assert 0 < ttl <= IN_AN_HOUR+ assert ttl >= IN_AN_HOUR - 5diff --git a/posthog/caching/utils.py b/posthog/caching/utils.pyindex ec23e82e1adc..03082b827307 100644--- a/posthog/caching/utils.py+++ b/posthog/caching/utils.py@@ -13,7 +13,10 @@ from posthog.models.team.team import Teamfrom posthog.redis import get_clientRECENTLY_ACCESSED_TEAMS_REDIS_KEY = "INSIGHT_CACHE_UPDATE_RECENTLY_ACCESSED_TEAMS"+# Separate from the zset so an empty result has somewhere to land without a sentinel team.+RECENTLY_ACCESSED_TEAMS_POPULATED_KEY = "INSIGHT_CACHE_UPDATE_RECENTLY_ACCESSED_TEAMS_POPULATED"+IN_AN_HOUR = 3_600IN_A_DAY = 86_400@@ -51,11 +54,18 @@ def _populate_active_teams(redis) -> dict[int, float]:ORDER BY age;""")- if not teams_by_recency:- return {}teams = dict(teams_by_recency)- redis.zadd(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, teams)- redis.expire(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, IN_A_DAY)+ # Marker is set even on empty results, so callers don't re-query for every inactive team.+ # Empty results get a shorter TTL so a newly-active team gets picked up within an hour.+ marker_ttl = IN_A_DAY if teams else IN_AN_HOUR+ pipe = redis.pipeline()+ if teams:+ pipe.zadd(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, teams)+ pipe.expire(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, IN_A_DAY)+ else:+ pipe.delete(RECENTLY_ACCESSED_TEAMS_REDIS_KEY)+ pipe.set(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY, "1", ex=marker_ttl)+ pipe.execute()return teams@@ -69,9 +79,8 @@ def is_team_active(team_id: int) -> bool:score = redis.zscore(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, team_id)if score is not None:return True- # ZSCORE None: either the team isn't recently active, or the key has expired /- # doesn't exist yet. EXISTS disambiguates.- if redis.exists(RECENTLY_ACCESSED_TEAMS_REDIS_KEY):+ # ZSCORE None: either the team isn't recently active, or we haven't populated yet.+ if redis.exists(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY):return Falsepopulated = _populate_active_teams(redis)return team_id in populated@@ -93,11 +102,12 @@ def active_teams() -> set[int]:"""redis = get_client()all_teams: list[tuple[bytes, float]] = redis.zrange(RECENTLY_ACCESSED_TEAMS_REDIS_KEY, 0, -1, withscores=True)- if not all_teams:- teams = _populate_active_teams(redis)- return set(teams.keys())-- return {int(team_id) for team_id, _ in all_teams}+ if all_teams:+ return {int(team_id) for team_id, _ in all_teams}+ if redis.exists(RECENTLY_ACCESSED_TEAMS_POPULATED_KEY):+ return set()+ teams = _populate_active_teams(redis)+ return set(teams.keys())def last_refresh_from_cached_result(cached_result: dict | object) -> Optional[datetime]: