: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
feat(flags): track remote config requests as unbilled usage telemetry (#61767)
Phil Haacka8ddc9cd2e04
diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.pyindex 22aee49eb2a4..f1b8818fbe6e 100644--- a/posthog/test/test_feature_flag_analytics.py+++ b/posthog/test/test_feature_flag_analytics.py@@ -87,6 +87,29 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):)self.assertEqual(client.hgetall(f"posthog:decide_requests:other"), {})+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)+ def test_increment_request_count_remote_config_uses_own_bucket(self):+ team_id = 3++ with freeze_time("2022-05-07 12:23:07"):+ for _ in range(4):+ increment_request_count(team_id)+ for _ in range(6):+ increment_request_count(team_id, 1, FlagRequestType.REMOTE_CONFIG)++ client = redis.get_client()++ # Remote config fetches are telemetry-only, so they must never leak into the+ # decide bucket that billing consumes.+ self.assertEqual(+ client.hgetall(f"posthog:decide_requests:{team_id}"),+ {b"165192618": b"4"},+ )+ self.assertEqual(+ client.hgetall(f"posthog:remote_config_requests:{team_id}"),+ {b"165192618": b"6"},+ )+@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_capture_team_decide_usage(self):mock_capture = MagicMock()@@ -103,6 +126,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):# 10 requests in first bucketincrement_request_count(team_id)increment_request_count(team_id, 1, FlagRequestType.LOCAL_EVALUATION)+ increment_request_count(team_id, 1, FlagRequestType.REMOTE_CONFIG)for _ in range(7):# 7 requests for other teamincrement_request_count(other_team_id)@@ -113,6 +137,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):# 5 requests in second bucketincrement_request_count(team_id)increment_request_count(team_id, 1, FlagRequestType.LOCAL_EVALUATION)+ increment_request_count(team_id, 1, FlagRequestType.REMOTE_CONFIG)for _ in range(3):# 3 requests for other teamincrement_request_count(other_team_id)@@ -123,13 +148,14 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):# 5 requests in third bucketincrement_request_count(team_id)increment_request_count(team_id, 1, FlagRequestType.LOCAL_EVALUATION)+ increment_request_count(team_id, 1, FlagRequestType.REMOTE_CONFIG)increment_request_count(other_team_id)capture_team_decide_usage(mock_capture, team_id, team_uuid)# these other requests should not add duplicate countscapture_team_decide_usage(mock_capture, team_id, team_uuid)capture_team_decide_usage(mock_capture, team_id, team_uuid)- assert mock_capture.capture.call_count == 2+ assert mock_capture.capture.call_count == 3mock_capture.capture.assert_any_call(distinct_id=team_id,event="decide usage",@@ -154,6 +180,18 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):"token": "token",},)+ mock_capture.capture.assert_any_call(+ distinct_id=team_id,+ event="remote config usage",+ properties={+ "count": 15,+ "team_id": team_id,+ "team_uuid": team_uuid,+ "max_time": 1651926190,+ "min_time": 1651926180,+ "token": "token",+ },+ )mock_capture.reset_mock()capture_team_decide_usage(mock_capture, other_team_id, other_team_uuid)diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 5025028c2bd6..a212756d1536 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -3746,8 +3746,16 @@ class FeatureFlagViewSet(if not feature_flag.is_remote_configuration:return Response(status=status.HTTP_404_NOT_FOUND)+ # Remote config usage is tracked for telemetry only (never billed), and only genuine SDK+ # fetches (team secret token, phs_…) count. Session and personal-key requests are the app's+ # own preview/decrypt feature, not customer usage, and a session-authenticated GET would+ # otherwise let a cross-site request inflate the team's usage numbers.+ should_count = isinstance(request.successful_authenticator, TeamSecretTokenAuthentication)+if not feature_flag.has_encrypted_payloads:payloads = feature_flag.filters.get("payloads", {})+ if should_count:+ increment_request_count(self.team.pk, 1, FlagRequestType.REMOTE_CONFIG)return Response(payloads.get("true") or None)# Note: This decryption step is protected by the feature_flag:read scope, so we can assume the@@ -3757,9 +3765,9 @@ class FeatureFlagViewSet(request, feature_flag.filters.get("payloads", {}))- sampling_rate = getattr(settings, "DECIDE_BILLING_SAMPLING_RATE", 1.0)- count = int(1 / sampling_rate)- increment_request_count(self.team.pk, count, FlagRequestType.REMOTE_CONFIG)+ # Count after a successful decryption so a decrypt failure (500) is never counted.+ if should_count:+ increment_request_count(self.team.pk, 1, FlagRequestType.REMOTE_CONFIG)return Response(decrypted_flag_payloads["true"] or None)diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex be21b19a7fbe..08d7856604de 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -2059,12 +2059,17 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.client.logout()+ client = redis.get_client()+ client.delete(f"posthog:remote_config_requests:{self.team.pk}")+response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",headers={"authorization": f"Bearer {personal_api_key}"},)self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json(), '{"test": true}')+ # Personal-key requests are the app's preview feature, not SDK usage, so they aren't counted.+ self.assertEqual(client.hgetall(f"posthog:remote_config_requests:{self.team.pk}"), {})def test_remote_config_with_project_secret_api_key(self):self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)@@ -2092,6 +2097,89 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json(), '{"test": true}')+ @parameterized.expand([("plaintext_payloads", False), ("encrypted_payloads", True)])+ def test_remote_config_increments_remote_config_bucket_by_one_per_request(+ self, _name: str, has_encrypted_payloads: bool+ ):+ self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)+ FeatureFlag.objects.create(+ team=self.team,+ key="my-remote-config-flag",+ name="Remote Config Flag",+ active=True,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": '{"test": true}'},+ },+ is_remote_configuration=True,+ has_encrypted_payloads=has_encrypted_payloads,+ )+ self.client.logout()++ client = redis.get_client()+ client.delete(f"posthog:remote_config_requests:{self.team.pk}")+ client.delete(f"posthog:decide_requests:{self.team.pk}")++ with freeze_time("2022-05-07 12:23:07"):+ for _ in range(3):+ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",+ headers={"authorization": f"Bearer {self.team.secret_api_token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ # Remote config usage is telemetry-only: it accumulates in its own bucket and must+ # never reach the decide bucket that billing consumes.+ buckets = client.hgetall(f"posthog:remote_config_requests:{self.team.pk}")+ self.assertEqual(sum(int(count) for count in buckets.values()), 3)+ self.assertEqual(client.hgetall(f"posthog:decide_requests:{self.team.pk}"), {})++ def test_remote_config_does_not_count_when_flag_is_not_remote_config(self):+ self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)+ FeatureFlag.objects.create(+ team=self.team,+ key="not-a-remote-config-flag",+ name="Regular Flag",+ active=True,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ is_remote_configuration=False,+ )+ self.client.logout()++ client = redis.get_client()+ client.delete(f"posthog:remote_config_requests:{self.team.pk}")++ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/not-a-remote-config-flag/remote_config",+ headers={"authorization": f"Bearer {self.team.secret_api_token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(client.hgetall(f"posthog:remote_config_requests:{self.team.pk}"), {})++ def test_remote_config_does_not_count_session_authenticated_requests(self):+ # Only team-secret-token fetches are counted. A session-authenticated GET must not increment+ # usage, otherwise a logged-in member could be driven to the URL cross-site to inflate the+ # team's usage telemetry.+ FeatureFlag.objects.create(+ team=self.team,+ key="my-remote-config-flag",+ name="Remote Config Flag",+ active=True,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": '{"test": true}'},+ },+ is_remote_configuration=True,+ )++ client = redis.get_client()+ client.delete(f"posthog:remote_config_requests:{self.team.pk}")++ # self.client is still logged in as self.user (session auth), no secret key supplied.+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(client.hgetall(f"posthog:remote_config_requests:{self.team.pk}"), {})+def test_remote_config_with_secret_api_key_prevents_cross_team_access(self):# Create two teams with different secret keysself.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)diff --git a/products/feature_flags/backend/flag_analytics.py b/products/feature_flags/backend/flag_analytics.pyindex 1eda0b105da5..adb652865829 100644--- a/products/feature_flags/backend/flag_analytics.py+++ b/products/feature_flags/backend/flag_analytics.py@@ -47,23 +47,35 @@ SDK_LIBRARIES = [# locally. It's not included in CI because of tricky patching freeze time in thread issues.+# Remote config requests are tracked for telemetry only; billing consumes just the decide and+# local evaluation events (see usage_report.py), so the remote config event never bills.+_REQUEST_BUCKET_PREFIXES = {+ FlagRequestType.DECIDE: "decide_requests",+ FlagRequestType.LOCAL_EVALUATION: "local_evaluation_requests",+ FlagRequestType.REMOTE_CONFIG: "remote_config_requests",+}++USAGE_EVENT_NAMES = {+ FlagRequestType.DECIDE: "decide usage",+ FlagRequestType.LOCAL_EVALUATION: "local evaluation usage",+ FlagRequestType.REMOTE_CONFIG: "remote config usage",+}+++def _request_bucket_prefix(request_type: FlagRequestType) -> str:+ try:+ return _REQUEST_BUCKET_PREFIXES[request_type]+ except KeyError:+ raise ValueError(f"Unknown request type: {request_type}") from None++def get_team_request_key(team_id: int, request_type: FlagRequestType) -> str:- if request_type == FlagRequestType.DECIDE:- return f"posthog:decide_requests:{team_id}"- elif request_type == FlagRequestType.LOCAL_EVALUATION:- return f"posthog:local_evaluation_requests:{team_id}"- else:- raise ValueError(f"Unknown request type: {request_type}")+ return f"posthog:{_request_bucket_prefix(request_type)}:{team_id}"def get_team_request_library_key(team_id: int, request_type: FlagRequestType, library: str) -> str:"""Get the Redis key for SDK-specific request counts."""- if request_type == FlagRequestType.DECIDE:- return f"posthog:decide_requests:sdk:{team_id}:{library}"- elif request_type == FlagRequestType.LOCAL_EVALUATION:- return f"posthog:local_evaluation_requests:sdk:{team_id}:{library}"- else:- raise ValueError(f"Unknown request type: {request_type}")+ return f"posthog:{_request_bucket_prefix(request_type)}:sdk:{team_id}:{library}"def increment_request_count(@@ -158,71 +170,51 @@ def capture_usage_for_all_teams(ph_client: "Posthog") -> None:capture_team_decide_usage(ph_client, team.id, team.uuid)+def _capture_team_usage_for_request_type(+ ph_client: "Posthog",+ client: redis.Redis,+ team_id: int,+ team_uuid: str,+ request_type: FlagRequestType,+ billing_token: str | None,+) -> None:+ key_name = get_team_request_key(team_id, request_type)+ total_count, min_time, max_time = _extract_total_count_for_key_from_redis_hash(client, key_name)+ sdk_breakdown = _extract_sdk_breakdown_from_redis(client, team_id, request_type)++ if total_count == 0 or not billing_token:+ return++ properties: dict = {+ "count": total_count,+ "team_id": team_id,+ "team_uuid": team_uuid,+ "min_time": min_time,+ "max_time": max_time,+ "token": billing_token,+ }+ if sdk_breakdown:+ properties["sdk_breakdown"] = sdk_breakdown++ ph_client.capture(+ distinct_id=team_id,+ event=USAGE_EVENT_NAMES[request_type],+ properties=properties,+ )++def capture_team_decide_usage(ph_client: "Posthog", team_id: int, team_uuid: str) -> None:try:client = get_client()- total_decide_request_count = 0- total_local_evaluation_request_count = 0with client.lock(f"{REDIS_LOCK_TOKEN}:{team_id}", timeout=60, blocking=False):- decide_key_name = get_team_request_key(team_id, FlagRequestType.DECIDE)- (- total_decide_request_count,- min_time,- max_time,- ) = _extract_total_count_for_key_from_redis_hash(client, decide_key_name)-- # Extract SDK breakdown for decide requests- decide_sdk_breakdown = _extract_sdk_breakdown_from_redis(client, team_id, FlagRequestType.DECIDE)-billing_token = settings.DECIDE_BILLING_ANALYTICS_TOKEN- if total_decide_request_count > 0 and billing_token:- properties: dict = {- "count": total_decide_request_count,- "team_id": team_id,- "team_uuid": team_uuid,- "min_time": min_time,- "max_time": max_time,- "token": billing_token,- }- if decide_sdk_breakdown:- properties["sdk_breakdown"] = decide_sdk_breakdown-- ph_client.capture(- distinct_id=team_id,- event="decide usage",- properties=properties,- )-- local_evaluation_key_name = get_team_request_key(team_id, FlagRequestType.LOCAL_EVALUATION)- (- total_local_evaluation_request_count,- min_time,- max_time,- ) = _extract_total_count_for_key_from_redis_hash(client, local_evaluation_key_name)-- # Extract SDK breakdown for local evaluation requests- local_eval_sdk_breakdown = _extract_sdk_breakdown_from_redis(- client, team_id, FlagRequestType.LOCAL_EVALUATION- )-- if total_local_evaluation_request_count > 0 and billing_token:- properties = {- "count": total_local_evaluation_request_count,- "team_id": team_id,- "team_uuid": team_uuid,- "min_time": min_time,- "max_time": max_time,- "token": billing_token,- }- if local_eval_sdk_breakdown:- properties["sdk_breakdown"] = local_eval_sdk_breakdown-- ph_client.capture(- distinct_id=team_id,- event="local evaluation usage",- properties=properties,- )+ for request_type in (+ FlagRequestType.DECIDE,+ FlagRequestType.LOCAL_EVALUATION,+ FlagRequestType.REMOTE_CONFIG,+ ):+ _capture_team_usage_for_request_type(ph_client, client, team_id, team_uuid, request_type, billing_token)except redis.exceptions.LockError:# lock wasn't acquired, which means another worker is working on this, so we don't need to do anything