Skip to content

Commit 4f32fa4

Browse files
authored
Fix feature flag 401 errors causing HTTP request storm (#422)
* Fix feature flag 401 errors causing HTTP request storm Set feature_flags = [] on 401 error to prevent repeated requests. * Clear flag_cache, group_type_mapping, cohorts on 401
1 parent f5719f3 commit 4f32fa4

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

posthog/client.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,13 @@ def _fetch_feature_flags_from_api(self):
13351335
self.log.error(
13361336
"[FEATURE FLAGS] Error loading feature flags: To use feature flags, please set a valid personal_api_key. More information: https://posthog.com/docs/api/overview"
13371337
)
1338+
self.feature_flags = []
1339+
self.group_type_mapping = {}
1340+
self.cohorts = {}
1341+
1342+
if self.flag_cache:
1343+
self.flag_cache.clear()
1344+
13381345
if self.debug:
13391346
raise APIError(
13401347
status=401,

posthog/test/test_client.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,20 @@ def test_load_feature_flags_quota_limited(self, patch_get):
479479
self.assertEqual(client.cohorts, {})
480480
self.assertIn("PostHog feature flags quota limited", logs.output[0])
481481

482+
@mock.patch("posthog.client.get")
483+
def test_load_feature_flags_unauthorized(self, patch_get):
484+
patch_get.side_effect = APIError(401, "Unauthorized")
485+
486+
client = Client(FAKE_TEST_API_KEY, personal_api_key="test")
487+
with self.assertLogs("posthog", level="ERROR") as logs:
488+
client._load_feature_flags()
489+
490+
self.assertEqual(client.feature_flags, [])
491+
self.assertEqual(client.feature_flags_by_key, {})
492+
self.assertEqual(client.group_type_mapping, {})
493+
self.assertEqual(client.cohorts, {})
494+
self.assertIn("please set a valid personal_api_key", logs.output[0])
495+
482496
@mock.patch("posthog.client.flags")
483497
def test_dont_override_capture_with_local_flags(self, patch_flags):
484498
patch_flags.return_value = {"featureFlags": {"beta-feature": "random-variant"}}

0 commit comments

Comments
 (0)