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): surface flags-service errors on person profile (#67776)

posthog[bot]2291626cf21f
diff --git a/frontend/src/scenes/persons/RelatedFeatureFlags.tsx b/frontend/src/scenes/persons/RelatedFeatureFlags.tsx
index fd9f4c84b728..d0e9dd0d0377 100644
--- a/frontend/src/scenes/persons/RelatedFeatureFlags.tsx
+++ b/frontend/src/scenes/persons/RelatedFeatureFlags.tsx
@@ -6,6 +6,7 @@ import { LemonInput, LemonSelect, LemonSnack, LemonTable, LemonTag, Tooltip } fr
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import stringWithWBR from 'lib/utils/stringWithWBR'
+import { InsightErrorState } from 'scenes/insights/EmptyStates'
import { urls } from 'scenes/urls'
import { FeatureFlagReleaseType } from '~/types'
@@ -143,8 +144,8 @@ const options = [
export function RelatedFeatureFlags({ distinctId, groupTypeIndex, groups }: Props): JSX.Element {
const relatedFlagsLogic = relatedFeatureFlagsLogic({ distinctId, groupTypeIndex, groups })
- const { filteredMappedFlags, isLoading, searchTerm, filters, pagination } = useValues(relatedFlagsLogic)
- const { setSearchTerm, setFilters } = useActions(relatedFlagsLogic)
+ const { filteredMappedFlags, isLoading, searchTerm, filters, pagination, loadError } = useValues(relatedFlagsLogic)
+ const { setSearchTerm, setFilters, loadRelatedFeatureFlags } = useActions(relatedFlagsLogic)
return (
<>
@@ -235,6 +236,15 @@ export function RelatedFeatureFlags({ distinctId, groupTypeIndex, groups }: Prop
loading={isLoading}
dataSource={filteredMappedFlags}
pagination={pagination}
+ emptyState={
+ loadError && !isLoading ? (
+ <InsightErrorState
+ title="Failed to load this person's feature flags"
+ excludeDetail
+ onRetry={() => loadRelatedFeatureFlags()}
+ />
+ ) : undefined
+ }
/>
</>
)
diff --git a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts
index 56f77fd9c400..982f72ecf201 100644
--- a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts
+++ b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts
@@ -206,4 +206,44 @@ describe('relatedFeatureFlagsLogic', () => {
await expectLogic(logic).toFinishAllListeners()
})
})
+
+ describe('load errors', () => {
+ beforeEach(() => {
+ // oxlint-disable-next-line react-hooks/rules-of-hooks
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/`]: [
+ 200,
+ { results: MOCK_FLAGS, count: MOCK_FLAGS.length },
+ ],
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/evaluation_reasons`]: [
+ 503,
+ { error: 'Feature flag evaluation service is temporarily unavailable. Please try again.' },
+ ],
+ },
+ })
+ flagsLogic = featureFlagsLogic()
+ flagsLogic.mount()
+ logic = relatedFeatureFlagsLogic({ distinctId: 'test-user' })
+ logic.mount()
+ })
+
+ it('sets loadError on a failed load and clears it once a retry succeeds', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.loadError).toBe(true)
+
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/evaluation_reasons`]:
+ MOCK_EVALUATION_REASONS,
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadRelatedFeatureFlags()
+ }).toFinishAllListeners()
+
+ expect(logic.values.loadError).toBe(false)
+ })
+ })
})
diff --git a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts
index c561b88e6beb..f400287ed2fc 100644
--- a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts
+++ b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts
@@ -46,6 +46,7 @@ export interface relatedFeatureFlagsLogicValues {
filteredMappedFlags: RelatedFeatureFlag[]
filters: Partial<RelatedFlagsFilters>
isLoading: boolean
+ loadError: boolean
mappedRelatedFeatureFlags: RelatedFeatureFlag[]
relatedFeatureFlags: RelatedFeatureFlagResponse | null
relatedFeatureFlagsLoading: boolean
@@ -189,6 +190,16 @@ export const relatedFeatureFlagsLogic = kea<relatedFeatureFlagsLogicType>([
},
},
],
+ // Track whether the evaluation_reasons request failed so the table can show a
+ // retry affordance instead of rendering as an empty (looks like "no flags") list.
+ loadError: [
+ false,
+ {
+ loadRelatedFeatureFlags: () => false,
+ loadRelatedFeatureFlagsSuccess: () => false,
+ loadRelatedFeatureFlagsFailure: () => true,
+ },
+ ],
}),
selectors(({ props, selectors }) => ({
isLoading: [
diff --git a/posthog/api/services/flags_service.py b/posthog/api/services/flags_service.py
index 44a593cc4e28..42089832751d 100644
--- a/posthog/api/services/flags_service.py
+++ b/posthog/api/services/flags_service.py
@@ -5,16 +5,25 @@ All flag evaluation (decide, toolbar, local eval API, etc.) now goes through the
flags service. This module provides a shared HTTP client and proxy function.
"""
+import time
from typing import Any
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
+import requests
+
from posthog.security.outbound_proxy import internal_requests_session
# Reusable session for proxying to the flags service with connection pooling
_FLAGS_SERVICE_SESSION = internal_requests_session()
+# Network blips worth a quick retry on non-SDK debug surfaces (opt-in via max_retries).
+# A refused connection or timeout usually clears on the next attempt; a bad response does not.
+# Public so callers (e.g. the evaluation_reasons endpoint) can catch exactly this set
+# themselves, rather than the broader RequestException that also covers HTTP errors.
+RETRYABLE_FLAGS_SERVICE_EXCEPTIONS = (requests.exceptions.ConnectionError, requests.exceptions.Timeout)
+
# One page of batch evaluation covers up to ~10k persons evaluated sequentially in the
# service, so this sits above the service's own per-request timeout (120s) rather than
# the 3s live-proxy timeout.
@@ -36,6 +45,8 @@ def get_flags_from_service(
internal_request_token: str | None = None,
override_flags_definitions: dict[str, dict[str, Any]] | None = None,
evaluation_runtime: str | None = None,
+ max_retries: int = 0,
+ retry_backoff_seconds: float = 0.1,
) -> dict[str, Any]:
"""
Proxy a request to the Rust feature flags service /flags endpoint.
@@ -52,6 +63,11 @@ def get_flags_from_service(
override_flags_definitions: Optional dict of flag key -> flag definition to override database flags (default: None)
evaluation_runtime: Optional override for runtime filtering: "all" | "client" | "server".
When None, the Rust service auto-detects from request headers (User-Agent, origin, sec-fetch-*).
+ max_retries: How many extra attempts to make on a transient connection error or timeout
+ (default 0, i.e. no retries). Only for non-SDK debug/UI surfaces — leave at 0 on the
+ latency-sensitive live evaluation path, since retries block the worker for up to
+ max_retries * (proxy_timeout + retry_backoff_seconds).
+ retry_backoff_seconds: Base delay between retries; grows linearly per attempt (default 0.1s).
Returns:
The full response from the flags service as a dict, typically containing:
@@ -108,15 +124,27 @@ def get_flags_from_service(
if internal_request_token and internal_request_token.strip():
headers["Authorization"] = f"Bearer {internal_request_token}"
- response = _FLAGS_SERVICE_SESSION.post(
- f"{flags_service_url}/flags",
- params=params,
- json=payload,
- headers=headers,
- timeout=proxy_timeout,
- )
- response.raise_for_status()
- return response.json()
+ # Only connection errors / timeouts are retried; a non-2xx HTTP response raises
+ # HTTPError out of raise_for_status() and propagates immediately (retrying it is pointless).
+ # Clamp a negative max_retries to 0 rather than letting range() go empty and falling
+ # through to the "unreachable" branch below.
+ for attempt in range(max(max_retries, 0) + 1):
+ try:
+ response = _FLAGS_SERVICE_SESSION.post(
+ f"{flags_service_url}/flags",
+ params=params,
+ json=payload,
+ headers=headers,
+ timeout=proxy_timeout,
+ )
+ response.raise_for_status()
+ return response.json()
+ except RETRYABLE_FLAGS_SERVICE_EXCEPTIONS:
+ if attempt >= max_retries:
+ raise
+ time.sleep(retry_backoff_seconds * (attempt + 1))
+
+ raise RuntimeError("unreachable: retry loop exited without returning or raising")
def batch_evaluate_flag_for_team(
diff --git a/posthog/api/test/test_flags_service.py b/posthog/api/test/test_flags_service.py
index 3d30067e8cb8..68bfcdce7d50 100644
--- a/posthog/api/test/test_flags_service.py
+++ b/posthog/api/test/test_flags_service.py
@@ -6,7 +6,11 @@ from django.test import SimpleTestCase, override_settings
import requests
from parameterized import parameterized
-from posthog.api.services.flags_service import FlagVersionConflictError, batch_evaluate_flag_for_team
+from posthog.api.services.flags_service import (
+ FlagVersionConflictError,
+ batch_evaluate_flag_for_team,
+ get_flags_from_service,
+)
class TestBatchEvaluateFlagForTeam(SimpleTestCase):
@@ -63,3 +67,68 @@ class TestBatchEvaluateFlagForTeam(SimpleTestCase):
cursor=0,
limit=100,
)
+
+
+class TestGetFlagsFromServiceRetries(SimpleTestCase):
+ @patch("posthog.api.services.flags_service.time.sleep")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_retries_transient_connection_error_then_succeeds(self, mock_post, mock_sleep):
+ ok = MagicMock()
+ ok.json.return_value = {"flags": {}}
+ mock_post.side_effect = [requests.exceptions.ConnectionError("refused"), ok]
+
+ result = get_flags_from_service(token="phc_x", distinct_id="user-1", max_retries=2)
+
+ self.assertEqual(result, {"flags": {}})
+ self.assertEqual(mock_post.call_count, 2)
+ mock_sleep.assert_called_once()
+
+ @patch("posthog.api.services.flags_service.time.sleep")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_raises_after_exhausting_retries(self, mock_post, mock_sleep):
+ mock_post.side_effect = requests.exceptions.ConnectionError("refused")
+
+ with self.assertRaises(requests.exceptions.ConnectionError):
+ get_flags_from_service(token="phc_x", distinct_id="user-1", max_retries=2)
+
+ self.assertEqual(mock_post.call_count, 3)
+
+ @patch("posthog.api.services.flags_service.time.sleep")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_default_makes_no_retries(self, mock_post, mock_sleep):
+ # The latency-sensitive live evaluation path must not gain retries by default.
+ mock_post.side_effect = requests.exceptions.ConnectionError("refused")
+
+ with self.assertRaises(requests.exceptions.ConnectionError):
+ get_flags_from_service(token="phc_x", distinct_id="user-1")
+
+ self.assertEqual(mock_post.call_count, 1)
+ mock_sleep.assert_not_called()
+
+ @patch("posthog.api.services.flags_service.time.sleep")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_negative_max_retries_raises_underlying_error_not_unreachable(self, mock_post, mock_sleep):
+ # range(max_retries + 1) goes empty for a negative max_retries, which used to skip
+ # the loop body entirely and fall through to the "unreachable" RuntimeError instead
+ # of the connection error that actually happened.
+ mock_post.side_effect = requests.exceptions.ConnectionError("refused")
+
+ with self.assertRaises(requests.exceptions.ConnectionError):
+ get_flags_from_service(token="phc_x", distinct_id="user-1", max_retries=-1)
+
+ self.assertEqual(mock_post.call_count, 1)
+ mock_sleep.assert_not_called()
+
+ @patch("posthog.api.services.flags_service.time.sleep")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_does_not_retry_http_error_responses(self, mock_post, mock_sleep):
+ # A 4xx/5xx is a real response, not a connection blip — retrying it just hammers the service.
+ response = MagicMock()
+ response.raise_for_status.side_effect = requests.HTTPError("500 Server Error", response=response)
+ mock_post.return_value = response
+
+ with self.assertRaises(requests.HTTPError):
+ get_flags_from_service(token="phc_x", distinct_id="user-1", max_retries=2)
+
+ self.assertEqual(mock_post.call_count, 1)
+ mock_sleep.assert_not_called()
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 731ce5b953c9..da858a7f5b5a 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -16,6 +16,7 @@ from django.db import transaction
from django.db.models import Count, Prefetch, Q, QuerySet, deletion
import grpc
+import requests
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema_field
@@ -33,7 +34,7 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
-from posthog.api.services.flags_service import get_flags_from_service
+from posthog.api.services.flags_service import RETRYABLE_FLAGS_SERVICE_EXCEPTIONS, get_flags_from_service
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action
@@ -3687,6 +3688,10 @@ class FeatureFlagViewSet(
query_serializer=EvaluationReasonsQuerySerializer,
responses={
200: OpenApiResponse(response=EvaluationReasonsResponseSerializer()),
+ 502: OpenApiResponse(response=ErrorResponseSerializer, description="Flag evaluation service error"),
+ 503: OpenApiResponse(
+ response=ErrorResponseSerializer, description="Flag evaluation service temporarily unavailable"
+ ),
},
examples=[
OpenApiExample(
@@ -3730,15 +3735,48 @@ class FeatureFlagViewSet(
flag_keys = request.validated_query_data.get("flag_keys") or None
# PostHog UI debug endpoint, not customer SDK traffic. Pass the internal
- # token so the call bypasses per-team billing.
- result = get_flags_from_service(
- token=self.team.api_token,
- distinct_id=distinct_id,
- groups=groups,
- flag_keys=flag_keys,
- evaluation_runtime="all",
- internal_request_token=settings.INTERNAL_REQUEST_TOKEN,
- )
+ # token so the call bypasses per-team billing. Retry the transient
+ # connection blips (the service occasionally times out or refuses the
+ # connection) and turn a persistent failure into a clean error instead of
+ # an unhandled 500, so the person-profile flags tab can show a retry
+ # affordance rather than an empty table that looks like "no flags".
+ try:
+ result = get_flags_from_service(
+ token=self.team.api_token,
+ distinct_id=distinct_id,
+ groups=groups,
+ flag_keys=flag_keys,
+ evaluation_runtime="all",
+ internal_request_token=settings.INTERNAL_REQUEST_TOKEN,
+ max_retries=2,
+ )
+ except RETRYABLE_FLAGS_SERVICE_EXCEPTIONS as e:
+ logger.warning("evaluation_reasons flags service call failed: %s", e)
+ capture_exception(e)
+ return Response(
+ {"error": "Feature flag evaluation service is temporarily unavailable. Please try again."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ except (requests.exceptions.HTTPError, requests.exceptions.JSONDecodeError) as e:
+ # A non-2xx response or an unparseable body from the flags service — a real
+ # upstream failure, not the "will probably clear on retry" case above, so it
+ # gets its own status rather than being folded into the 503.
+ logger.warning("evaluation_reasons flags service returned an invalid response: %s", e)
+ capture_exception(e)
+ return Response(
+ {"error": "Feature flag evaluation service returned an unexpected response."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ except requests.exceptions.RequestException as e:
+ # Any other requests failure (SSLError, ProxyError, InvalidSchema, ...) is still an
+ # upstream availability problem, not a "no flags" state — surface the same 503 as
+ # the retryable case above rather than letting it bubble up as an unhandled 500.
+ logger.warning("evaluation_reasons flags service call failed: %s", e)
+ capture_exception(e)
+ return Response(
+ {"error": "Feature flag evaluation service is temporarily unavailable. Please try again."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
# Result from Rust service is always a dictionary with a "flags" key. Parse it to get the flags data.
flags_data = result.get("flags", {})
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 53ce59d13067..c710ade94b75 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -13497,3 +13497,47 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):
self.assertIn("wanted-active", data)
self.assertIn("wanted-disabled", data)
self.assertNotIn("other-disabled", data)
+
+ @parameterized.expand(
+ [
+ ("connection_error", requests.exceptions.ConnectionError("connection refused")),
+ ("timeout", requests.exceptions.Timeout("timed out")),
+ # Not in the retryable tuple, but still a requests failure rather than an
+ # actual HTTP response — must fall into the catch-all 503, not an unhandled 500.
+ ("ssl_error", requests.exceptions.SSLError("certificate verify failed")),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ def test_evaluation_reasons_returns_503_when_flags_service_unreachable(self, _name, exception, mock_get_flags):
+ # A flags-service connection failure must surface as a clean 503 the person-profile
+ # tab can react to, not an unhandled 500 that renders as an empty (looks like "no flags") table.
+ mock_get_flags.side_effect = exception
+
+ response = self.client.get(
+ f"/api/projects/{self.team.pk}/feature_flags/evaluation_reasons/",
+ {"distinct_id": "user-1"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
+ self.assertIn("error", response.json())
+
+ @parameterized.expand(
+ [
+ ("http_error", requests.exceptions.HTTPError("500 Server Error", response=MagicMock(status_code=500))),
+ ("malformed_json", requests.exceptions.JSONDecodeError("Expecting value", "", 0)),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ def test_evaluation_reasons_returns_502_for_non_retryable_failures(self, _name, exception, mock_get_flags):
+ # A real HTTP error or an unparseable body from the flags service is not a transient
+ # connection blip: it must not be folded into the same 503 used for those, and a
+ # malformed response must not fall through to an unhandled 500 either.
+ mock_get_flags.side_effect = exception
+
+ response = self.client.get(
+ f"/api/projects/{self.team.pk}/feature_flags/evaluation_reasons/",
+ {"distinct_id": "user-1"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
+ self.assertIn("error", response.json())