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.

feat(flags): throttle remote_config PSAK usage per key and per team (#67199)

Phil Haack7dc7d1a7c607
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index e63033660784..733076558163 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -30,7 +30,10 @@ from posthog.rate_limit import (
get_route_from_path,
)
-from products.feature_flags.backend.api.feature_flag import RemoteConfigThrottle
+from products.feature_flags.backend.api.feature_flag import (
+ RemoteConfigProjectSecretApiKeyTeamThrottle,
+ RemoteConfigThrottle,
+)
class TestUserAPI(APIBaseTest):
@@ -716,6 +719,26 @@ class TestUserAPI(APIBaseTest):
self.assertEqual(throttle.num_requests, 1200)
self.assertEqual(throttle.duration, 60) # 1 minute in seconds
+ def test_remote_config_team_throttle_uses_custom_rate_for_team(self):
+ throttle = RemoteConfigProjectSecretApiKeyTeamThrottle()
+
+ mock_view = Mock()
+ mock_request = Mock()
+
+ with (
+ patch("products.feature_flags.backend.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {123: "1200/minute"}),
+ patch.object(throttle, "safely_get_team_id_from_view", return_value=123),
+ patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),
+ ):
+ result = throttle.allow_request(mock_request, mock_view)
+
+ self.assertTrue(result)
+ # The per-team throttle must apply the team's REMOTE_CONFIG_RATE_LIMITS override too, not
+ # just the per-key throttle, otherwise a configured per-team cap silently has no effect.
+ self.assertEqual(throttle.rate, "1200/minute")
+ self.assertEqual(throttle.num_requests, 1200)
+ self.assertEqual(throttle.duration, 60)
+
@parameterized.expand(
[
# Test Django route pattern normalization
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 9bbacd5c5f2d..6ffbccd48102 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -62,7 +62,12 @@ from posthog.models.property import Property
from posthog.permissions import TeamSecretTokenPermission, get_authenticator_scopes, is_service_auth
from posthog.ph_client import feature_enabled_or_false
from posthog.queries.base import determine_parsed_date_for_property_matching
-from posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
+from posthog.rate_limit import (
+ ClickHouseBurstRateThrottle,
+ ClickHouseSustainedRateThrottle,
+ PersonalOrProjectSecretApiKeyRateThrottle,
+ ProjectSecretApiKeyTeamRateThrottle,
+)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.settings.feature_flags import REMOTE_CONFIG_RATE_LIMITS
@@ -552,23 +557,46 @@ def check_flag_limits_for_team(
)
-class RemoteConfigThrottle(BurstRateThrottle):
+# Default per-key and per-team cap for remote_config. Both throttles below respect
+# per-team overrides from REMOTE_CONFIG_RATE_LIMITS.
+REMOTE_CONFIG_DEFAULT_RATE = "600/minute"
+
+
+def _apply_remote_config_team_rate_override(throttle, view) -> None:
+ # Raise or lower a specific team's remote_config cap via REMOTE_CONFIG_RATE_LIMITS. On any
+ # lookup/parse failure, leave the default rate in place rather than failing the request.
+ team_id = throttle.safely_get_team_id_from_view(view)
+ if team_id:
+ try:
+ custom_rate = REMOTE_CONFIG_RATE_LIMITS.get(team_id)
+ if custom_rate:
+ num_requests, duration = throttle.parse_rate(custom_rate)
+ throttle.rate = custom_rate
+ throttle.num_requests = num_requests
+ throttle.duration = duration
+ except Exception:
+ logger.exception("Error getting team-specific rate limit for team %s", team_id)
+
+
+class RemoteConfigThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ # Per-key throttle; the PSAK-aware base also throttles PSAK requests, which the plain
+ # PersonalApiKeyRateThrottle would let through.
scope = "feature_flag_remote_config"
- rate = "600/minute"
+ rate = REMOTE_CONFIG_DEFAULT_RATE
def allow_request(self, request, view):
- logger = logging.getLogger(__name__)
+ _apply_remote_config_team_rate_override(self, view)
+ return super().allow_request(request, view)
- team_id = self.safely_get_team_id_from_view(view)
- if team_id:
- try:
- custom_rate = REMOTE_CONFIG_RATE_LIMITS.get(team_id)
- if custom_rate:
- self.rate = custom_rate
- self.num_requests, self.duration = self.parse_rate(self.rate)
- except Exception:
- logger.exception(f"Error getting team-specific rate limit for team {team_id}")
+class RemoteConfigProjectSecretApiKeyTeamThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ # Per-team aggregate cap stacked alongside the per-key RemoteConfigThrottle so a project can't
+ # multiply its budget by minting many keys. Defense-in-depth for the new credential.
+ scope = "feature_flag_remote_config_psak_team"
+ rate = REMOTE_CONFIG_DEFAULT_RATE
+
+ def allow_request(self, request, view):
+ _apply_remote_config_team_rate_override(self, view)
return super().allow_request(request, view)
@@ -4055,7 +4083,7 @@ class FeatureFlagViewSet(
ProjectSecretAPIKeyAuthentication,
],
permission_classes=[TeamSecretTokenPermission],
- throttle_classes=[RemoteConfigThrottle],
+ throttle_classes=[RemoteConfigThrottle, RemoteConfigProjectSecretApiKeyTeamThrottle],
)
def remote_config(self, request: request.Request, **kwargs):
response = self._remote_config_response(request, **kwargs)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 6ad26ffc2d4c..ccfb9fd67e1e 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -2190,6 +2190,47 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
buckets = client.hgetall(f"posthog:remote_config_requests:{self.team.pk}")
self.assertEqual(sum(int(count) for count in buckets.values()), 1)
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch("products.feature_flags.backend.api.feature_flag.RemoteConfigThrottle.rate", new="2/minute")
+ def test_remote_config_throttles_project_secret_api_key_requests(self, *_args):
+ # PSAK requests carry no personal API key, so a plain PersonalApiKeyRateThrottle would let
+ # them through unthrottled. RemoteConfigThrottle's PSAK-aware base must throttle them per key.
+ self._create_remote_config_flag()
+ token, _ = _make_feature_flag_psak(self.team, label="throttle")
+ self.client.logout()
+ cache.clear()
+
+ url = f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config"
+ headers = {"authorization": f"Bearer {token}"}
+ for _ in range(2):
+ self.assertEqual(self.client.get(url, headers=headers).status_code, status.HTTP_200_OK)
+ self.assertEqual(self.client.get(url, headers=headers).status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch(
+ "products.feature_flags.backend.api.feature_flag.RemoteConfigProjectSecretApiKeyTeamThrottle.rate",
+ new="2/minute",
+ )
+ def test_remote_config_team_throttle_caps_across_multiple_psaks(self, *_args):
+ # The per-team throttle exists to stop a project from multiplying its budget by minting keys.
+ # The per-key throttle stays at its default, so the only way the third request trips is the
+ # shared per-team bucket — two distinct keys, one team.
+ self._create_remote_config_flag()
+ token_a, _ = _make_feature_flag_psak(self.team, label="teamcapa")
+ token_b, _ = _make_feature_flag_psak(self.team, label="teamcapb")
+ self.client.logout()
+ cache.clear()
+
+ url = f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config"
+ for _ in range(2):
+ self.assertEqual(
+ self.client.get(url, headers={"authorization": f"Bearer {token_a}"}).status_code, status.HTTP_200_OK
+ )
+ self.assertEqual(
+ self.client.get(url, headers={"authorization": f"Bearer {token_b}"}).status_code,
+ status.HTTP_429_TOO_MANY_REQUESTS,
+ )
+
def test_remote_config_returns_response_even_if_shadow_raises(self):
# The throwaway Rust shadow (phase 2) must never break the live endpoint, even if it raises.
self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)