Skip to content

: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.

fix(flags): label hypercache stats metrics by cache_name (#61270)

Phil Haack91b35500ee2f
diff --git a/posthog/storage/cache_expiry_manager.py b/posthog/storage/cache_expiry_manager.py
index 758cd2fdd713..1514f31d9bc5 100644
--- a/posthog/storage/cache_expiry_manager.py
+++ b/posthog/storage/cache_expiry_manager.py
@@ -137,6 +137,7 @@ def refresh_expiring_caches(
# Push metrics to Pushgateway (Gauges work better than Counters for batch jobs)
push_hypercache_teams_processed_metrics(
namespace=config.namespace,
+ cache_name=config.cache_name,
successful=successful,
failed=failed,
)
diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.py
index 6b065b9e41dd..b5d686f5775b 100644
--- a/posthog/storage/hypercache_manager.py
+++ b/posthog/storage/hypercache_manager.py
@@ -63,6 +63,7 @@ HYPERCACHE_SIGNAL_UPDATE_COUNTER = Counter(
def push_hypercache_stats_metrics(
namespace: str,
+ cache_name: str,
coverage_percent: float,
entries_total: int,
expiry_tracked_total: int,
@@ -74,8 +75,15 @@ def push_hypercache_stats_metrics(
Gauge metrics are pushed to Pushgateway instead of using module-level gauges
to ensure only one value per metric appears in Grafana dashboards.
+ Multiple caches can share a namespace (e.g. the team_metadata cache and the
+ llm_gateway_policy cache both live under namespace="team_metadata"), so
+ metrics are labeled and grouped by cache_name as well — otherwise the two
+ caches collide on a single {namespace} series and overwrite each other's
+ coverage/size values.
+
Args:
namespace: The HyperCache namespace (e.g., "feature_flags", "team_metadata")
+ cache_name: The canonical cache name (e.g., "team_metadata", "llm_gateway_policy")
coverage_percent: Percentage of teams with cached data
entries_total: Total number of entries in the HyperCache
expiry_tracked_total: Number of entries tracked in the expiry sorted set
@@ -84,46 +92,38 @@ def push_hypercache_stats_metrics(
if not settings.PROM_PUSHGATEWAY_ADDRESS:
return
- try:
- with pushed_metrics_registry(f"hypercache_stats_{namespace}") as registry:
- coverage_gauge = Gauge(
- "posthog_hypercache_coverage_percent",
- "Percentage of teams with cached data",
- labelnames=["namespace"],
- registry=registry,
- )
- coverage_gauge.labels(namespace=namespace).set(coverage_percent)
-
- entries_gauge = Gauge(
- "posthog_hypercache_entries_total",
- "Total number of entries in the HyperCache",
- labelnames=["namespace"],
- registry=registry,
- )
- entries_gauge.labels(namespace=namespace).set(entries_total)
+ # (namespace, cache_name) must be unique per cache — caches sharing a namespace
+ # rely on cache_name to keep their series and Pushgateway groups distinct.
+ gauges = [
+ ("posthog_hypercache_coverage_percent", "Percentage of teams with cached data", coverage_percent),
+ ("posthog_hypercache_entries_total", "Total number of entries in the HyperCache", entries_total),
+ (
+ "posthog_hypercache_expiry_tracked_total",
+ "Number of entries tracked in the expiry sorted set",
+ expiry_tracked_total,
+ ),
+ ("posthog_hypercache_size_bytes", "Estimated total cache size in bytes", size_bytes),
+ ]
- expiry_tracked_gauge = Gauge(
- "posthog_hypercache_expiry_tracked_total",
- "Number of entries tracked in the expiry sorted set",
- labelnames=["namespace"],
- registry=registry,
- )
- expiry_tracked_gauge.labels(namespace=namespace).set(expiry_tracked_total)
-
- if size_bytes is not None:
- size_gauge = Gauge(
- "posthog_hypercache_size_bytes",
- "Estimated total cache size in bytes",
- labelnames=["namespace"],
- registry=registry,
- )
- size_gauge.labels(namespace=namespace).set(size_bytes)
+ try:
+ with pushed_metrics_registry(f"hypercache_stats_{namespace}_{cache_name}") as registry:
+ for name, description, value in gauges:
+ if value is None:
+ continue
+ gauge = Gauge(name, description, labelnames=["namespace", "cache_name"], registry=registry)
+ gauge.labels(namespace=namespace, cache_name=cache_name).set(value)
except Exception as e:
- logger.warning("Failed to push hypercache stats to Pushgateway", error=str(e), namespace=namespace)
+ logger.warning(
+ "Failed to push hypercache stats to Pushgateway",
+ error=str(e),
+ namespace=namespace,
+ cache_name=cache_name,
+ )
def push_hypercache_teams_processed_metrics(
namespace: str,
+ cache_name: str,
successful: int,
failed: int,
) -> None:
@@ -134,8 +134,12 @@ def push_hypercache_teams_processed_metrics(
(they reset on each push). Gauges show the count from the most recent batch run,
which is the relevant information for an hourly task.
+ Labeled and grouped by cache_name in addition to namespace so caches sharing a
+ namespace don't overwrite each other's series (see push_hypercache_stats_metrics).
+
Args:
namespace: The HyperCache namespace (e.g., "feature_flags", "team_metadata")
+ cache_name: The canonical cache name (e.g., "team_metadata", "llm_gateway_policy")
successful: Number of teams successfully processed
failed: Number of teams that failed processing
"""
@@ -143,17 +147,22 @@ def push_hypercache_teams_processed_metrics(
return
try:
- with pushed_metrics_registry(f"hypercache_teams_processed_{namespace}") as registry:
+ with pushed_metrics_registry(f"hypercache_teams_processed_{namespace}_{cache_name}") as registry:
success_gauge = Gauge(
"posthog_hypercache_teams_processed_last_run",
"Teams processed in the last batch refresh run",
- labelnames=["namespace", "result"],
+ labelnames=["namespace", "cache_name", "result"],
registry=registry,
)
- success_gauge.labels(namespace=namespace, result="success").set(successful)
- success_gauge.labels(namespace=namespace, result="failure").set(failed)
+ success_gauge.labels(namespace=namespace, cache_name=cache_name, result="success").set(successful)
+ success_gauge.labels(namespace=namespace, cache_name=cache_name, result="failure").set(failed)
except Exception as e:
- logger.warning("Failed to push hypercache teams processed to Pushgateway", error=str(e), namespace=namespace)
+ logger.warning(
+ "Failed to push hypercache teams processed to Pushgateway",
+ error=str(e),
+ namespace=namespace,
+ cache_name=cache_name,
+ )
class UpdateFn(Protocol):
@@ -523,6 +532,7 @@ def get_cache_stats(config: HyperCacheManagementConfig) -> dict[str, Any]:
# Push metrics to Pushgateway for single-value display in Grafana
push_hypercache_stats_metrics(
namespace=config.namespace,
+ cache_name=config.cache_name,
coverage_percent=coverage_percent,
entries_total=total_keys,
expiry_tracked_total=expiry_tracked_count,
diff --git a/posthog/storage/test/test_hypercache_manager.py b/posthog/storage/test/test_hypercache_manager.py
index bd70618ed323..ebe091bca050 100644
--- a/posthog/storage/test/test_hypercache_manager.py
+++ b/posthog/storage/test/test_hypercache_manager.py
@@ -10,11 +10,14 @@ Covers:
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
+from prometheus_client import CollectorRegistry
+
from posthog.storage.hypercache import HyperCache
from posthog.storage.hypercache_manager import (
HyperCacheManagementConfig,
get_cache_stats,
push_hypercache_stats_metrics,
+ push_hypercache_teams_processed_metrics,
warm_caches,
)
@@ -333,21 +336,27 @@ class TestPushHypercacheStatsMetrics(BaseTest):
@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
def test_pushes_metrics_to_pushgateway(self, mock_registry_cm):
- """Test that metrics are pushed to Pushgateway when configured."""
- mock_registry = MagicMock()
- mock_registry_cm.return_value.__enter__ = MagicMock(return_value=mock_registry)
+ """Metrics are pushed to the namespace+cache_name group, labeled by both."""
+ registry = CollectorRegistry()
+ mock_registry_cm.return_value.__enter__ = MagicMock(return_value=registry)
mock_registry_cm.return_value.__exit__ = MagicMock(return_value=False)
with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):
push_hypercache_stats_metrics(
namespace="feature_flags",
+ cache_name="flags",
coverage_percent=85.5,
entries_total=1000,
expiry_tracked_total=950,
size_bytes=1024000,
)
- mock_registry_cm.assert_called_once_with("hypercache_stats_feature_flags")
+ mock_registry_cm.assert_called_once_with("hypercache_stats_feature_flags_flags")
+ labels = {"namespace": "feature_flags", "cache_name": "flags"}
+ assert registry.get_sample_value("posthog_hypercache_coverage_percent", labels) == 85.5
+ assert registry.get_sample_value("posthog_hypercache_entries_total", labels) == 1000
+ assert registry.get_sample_value("posthog_hypercache_expiry_tracked_total", labels) == 950
+ assert registry.get_sample_value("posthog_hypercache_size_bytes", labels) == 1024000
@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
def test_skips_push_when_no_pushgateway_address(self, mock_registry_cm):
@@ -355,6 +364,7 @@ class TestPushHypercacheStatsMetrics(BaseTest):
with self.settings(PROM_PUSHGATEWAY_ADDRESS=None):
push_hypercache_stats_metrics(
namespace="feature_flags",
+ cache_name="flags",
coverage_percent=85.5,
entries_total=1000,
expiry_tracked_total=950,
@@ -366,20 +376,26 @@ class TestPushHypercacheStatsMetrics(BaseTest):
@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
def test_skips_size_gauge_when_size_bytes_is_none(self, mock_registry_cm):
"""Test that size gauge is not created when size_bytes is None."""
- mock_registry = MagicMock()
- mock_registry_cm.return_value.__enter__ = MagicMock(return_value=mock_registry)
+ registry = CollectorRegistry()
+ mock_registry_cm.return_value.__enter__ = MagicMock(return_value=registry)
mock_registry_cm.return_value.__exit__ = MagicMock(return_value=False)
with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):
push_hypercache_stats_metrics(
namespace="team_metadata",
+ cache_name="team_metadata",
coverage_percent=90.0,
entries_total=500,
expiry_tracked_total=500,
size_bytes=None,
)
- mock_registry_cm.assert_called_once_with("hypercache_stats_team_metadata")
+ mock_registry_cm.assert_called_once_with("hypercache_stats_team_metadata_team_metadata")
+ labels = {"namespace": "team_metadata", "cache_name": "team_metadata"}
+ assert registry.get_sample_value("posthog_hypercache_size_bytes", labels) is None
+ assert registry.get_sample_value("posthog_hypercache_coverage_percent", labels) == 90.0
+ assert registry.get_sample_value("posthog_hypercache_entries_total", labels) == 500
+ assert registry.get_sample_value("posthog_hypercache_expiry_tracked_total", labels) == 500
@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
@patch("posthog.storage.hypercache_manager.logger")
@@ -391,6 +407,7 @@ class TestPushHypercacheStatsMetrics(BaseTest):
with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):
push_hypercache_stats_metrics(
namespace="feature_flags",
+ cache_name="flags",
coverage_percent=85.5,
entries_total=1000,
expiry_tracked_total=950,
@@ -400,6 +417,115 @@ class TestPushHypercacheStatsMetrics(BaseTest):
mock_logger.warning.assert_called_once()
assert "Failed to push hypercache stats" in str(mock_logger.warning.call_args)
+ @patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
+ def test_caches_sharing_namespace_use_distinct_groups(self, mock_registry_cm):
+ """Caches sharing a namespace must push to distinct Pushgateway groups.
+
+ team_metadata and llm_gateway_policy both use namespace="team_metadata";
+ without cache_name in the group key they would overwrite each other.
+ """
+ mock_registry = MagicMock()
+ mock_registry_cm.return_value.__enter__ = MagicMock(return_value=mock_registry)
+ mock_registry_cm.return_value.__exit__ = MagicMock(return_value=False)
+
+ with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):
+ push_hypercache_stats_metrics(
+ namespace="team_metadata",
+ cache_name="team_metadata",
+ coverage_percent=100.0,
+ entries_total=409000,
+ expiry_tracked_total=409000,
+ size_bytes=378_000_000,
+ )
+ push_hypercache_stats_metrics(
+ namespace="team_metadata",
+ cache_name="llm_gateway_policy",
+ coverage_percent=2.6,
+ entries_total=10900,
+ expiry_tracked_total=10900,
+ size_bytes=1_000_000,
+ )
+
+ group_names = [call.args[0] for call in mock_registry_cm.call_args_list]
+ assert group_names == [
+ "hypercache_stats_team_metadata_team_metadata",
+ "hypercache_stats_team_metadata_llm_gateway_policy",
+ ]
+
+
+class TestPushHypercacheTeamsProcessedMetrics(BaseTest):
+ """Test push_hypercache_teams_processed_metrics functionality."""
+
+ @patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
+ def test_pushes_metrics_to_pushgateway(self, mock_registry_cm):
+ """Teams-processed counts are pushed to the namespace+cache_name group, labeled by both."""
+ registry = CollectorRegistry()
+ mock_registry_cm.return_value.__enter__ = MagicMock(return_value=registry)
+ mock_registry_cm.return_value.__exit__ = MagicMock(return_value=False)
+
+ with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):
+ push_hypercache_teams_processed_metrics(
+ namespace="feature_flags",
+ cache_name="flags",
+ successful=900,
+ failed=100,
+ )
+
+ mock_registry_cm.assert_called_once_with("hypercache_teams_processed_feature_flags_flags")
+ base = {"namespace": "feature_flags", "cache_name": "flags"}
+ assert (
+ registry.get_sample_value("posthog_hypercache_teams_processed_last_run", {**base, "result": "success"})
+ == 900
+ )
+ assert (
+ registry.get_sample_value("posthog_hypercache_teams_processed_last_run", {**base, "result": "failure"})
+ == 100
+ )
+
+ @patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
+ def test_skips_push_when_no_pushgateway_address(self, mock_registry_cm):
+ """No push happens when PROM_PUSHGATEWAY_ADDRESS is not set."""
+ with self.settings(PROM_PUSHGATEWAY_ADDRESS=None):
+ push_hypercache_teams_processed_metrics(
+ namespace="feature_flags",
+ cache_name="flags",
+ successful=900,
+ failed=100,
+ )
+
+ mock_registry_cm.assert_not_called()
+
+ @patch("posthog.storage.hypercache_manager.pushed_metrics_registry")
+ def test_caches_sharing_namespace_use_distinct_groups(self, mock_registry_cm):
+ """Caches sharing a namespace must push to distinct Pushgateway groups.
+
+ team_metadata and llm_gateway_policy both use namespace="team_metadata";
+ without cache_name in the group key they would overwrite each other.
+ """
+ mock_registry = MagicMock()
+ mock_registry_cm.return_value.__enter__ = MagicMock(return_value=mock_registry)
+ mock_registry_cm.return_value.__exit__ = MagicMock(return_value=False)
+
+ with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):
+ push_hypercache_teams_processed_metrics(
+ namespace="team_metadata",
+ cache_name="team_metadata",
+ successful=409000,
+ failed=0,
+ )
+ push_hypercache_teams_processed_metrics(
+ namespace="team_metadata",
+ cache_name="llm_gateway_policy",
+ successful=10900,
+ failed=0,
+ )
+
+ group_names = [call.args[0] for call in mock_registry_cm.call_args_list]
+ assert group_names == [
+ "hypercache_teams_processed_team_metadata_team_metadata",
+ "hypercache_teams_processed_team_metadata_llm_gateway_policy",
+ ]
+
class TestConfigGetTeamsQuerysetFn(BaseTest):
"""Test HyperCacheManagementConfig.get_teams_queryset_fn and get_teams_queryset()."""