: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: Add hard refresh to health checks (#58382)
Jordan Mryyanad842345139c
diff --git a/frontend/src/scenes/health/HealthScene.tsx b/frontend/src/scenes/health/HealthScene.tsxindex f5ae4bab8190..264f9117922a 100644--- a/frontend/src/scenes/health/HealthScene.tsx+++ b/frontend/src/scenes/health/HealthScene.tsx@@ -6,6 +6,7 @@ import { LemonBanner, LemonButton, LemonMenu, Link } from '@posthog/lemon-ui'import { supportLogic } from 'lib/components/Support/supportLogic'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { humanFriendlyDuration } from 'lib/utils'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -86,10 +87,22 @@ const LegacyHealthScene = (): JSX.Element => {}const UnifiedHealthScene = (): JSX.Element => {- const { showDismissed, healthIssuesLoading } = useValues(healthSceneLogic)+ const { showDismissed, healthIssuesLoading, isRefreshInFlight, nextRefreshAvailableAt } =+ useValues(healthSceneLogic)const { refreshHealthData, setShowDismissed } = useActions(healthSceneLogic)const { openSupportForm } = useActions(supportLogic)+ const now = Date.now()+ const inCooldown = nextRefreshAvailableAt !== null && nextRefreshAvailableAt > now+ const cooldownLabel = inCooldown+ ? `Refresh available in ${humanFriendlyDuration(Math.ceil((nextRefreshAvailableAt! - now) / 1000), {+ maxUnits: 2,+ })}`+ : undefined+ const refreshTooltip = isRefreshInFlight+ ? 'Refreshing health checks...'+ : (cooldownLabel ?? 'Re-run all health checks for this project')+return (<SceneContent><SceneTitleSection name="Health" description={null} resourceType={{ type: 'health' }} />@@ -109,8 +122,9 @@ const UnifiedHealthScene = (): JSX.Element => {icon={<IconRefresh />}type="tertiary"size="small"- tooltip="Refresh"- loading={healthIssuesLoading}+ tooltip={refreshTooltip}+ loading={isRefreshInFlight || healthIssuesLoading}+ disabledReason={cooldownLabel}onClick={() => refreshHealthData()}/><LemonMenudiff --git a/frontend/src/scenes/health/healthSceneLogic.tsx b/frontend/src/scenes/health/healthSceneLogic.tsxindex 7bf06c909d71..526641689c40 100644--- a/frontend/src/scenes/health/healthSceneLogic.tsx+++ b/frontend/src/scenes/health/healthSceneLogic.tsx@@ -1,7 +1,7 @@import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'+import api, { ApiError } from 'lib/api'import { unifiedHealthMenuLogic } from 'lib/components/HealthMenu/unifiedHealthMenuLogic'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -25,6 +25,10 @@ export interface HealthIssuesResponse {previous?: string | null}+const REFRESH_COOLDOWN_MS = 15 * 60 * 1000+const REFRESH_POLL_INTERVAL_MS = 5000+const REFRESH_POLL_COUNT = 12+export const healthSceneLogic = kea<healthSceneLogicType>([path(['scenes', 'health', 'healthSceneLogic']),tabAwareScene(),@@ -37,6 +41,8 @@ export const healthSceneLogic = kea<healthSceneLogicType>([undismissIssue: (id: string) => ({ id }),refreshHealthData: true,resetManualRefresh: true,+ setNextRefreshAvailableAt: (timestamp: number | null) => ({ timestamp }),+ clearRefreshInFlight: true,}),reducers({showDismissed: [@@ -52,6 +58,20 @@ export const healthSceneLogic = kea<healthSceneLogicType>([resetManualRefresh: () => false,},],+ nextRefreshAvailableAt: [+ null as number | null,+ { persist: true },+ {+ setNextRefreshAvailableAt: (_, { timestamp }) => timestamp,+ },+ ],+ isRefreshInFlight: [+ false,+ {+ refreshHealthData: () => true,+ clearRefreshInFlight: () => false,+ },+ ],}),loaders(({ values }) => ({healthIssues: [@@ -133,8 +153,57 @@ export const healthSceneLogic = kea<healthSceneLogicType>([],}),listeners(({ actions, values }) => ({- refreshHealthData: () => {- actions.loadHealthIssues()+ refreshHealthData: async (_, breakpoint) => {+ const url = `api/environments/${values.currentTeamIdStrict}/health_issues/refresh/`+ try {+ const response = await api.create<{+ scheduled_kinds: string[]+ kinds_failed: string[]+ team_id: number+ }>(url)+ breakpoint()++ actions.setNextRefreshAvailableAt(Date.now() + REFRESH_COOLDOWN_MS)++ if ((response?.scheduled_kinds ?? []).length === 0) {+ actions.clearRefreshInFlight()+ actions.resetManualRefresh()+ lemonToast.info('No health checks are registered for this project.')+ return+ }++ lemonToast.success('Refreshing health checks...', { autoClose: 2000 })++ for (let i = 0; i < REFRESH_POLL_COUNT; i++) {+ await breakpoint(REFRESH_POLL_INTERVAL_MS)+ actions.loadHealthIssues()+ }+ actions.clearRefreshInFlight()+ } catch (error: unknown) {+ actions.clearRefreshInFlight()+ actions.resetManualRefresh()+ if (error instanceof ApiError && error.status === 429) {+ const retryAfterSeconds = Number(error.headers?.get('Retry-After'))+ if (!isNaN(retryAfterSeconds) && retryAfterSeconds > 0) {+ actions.setNextRefreshAvailableAt(Date.now() + retryAfterSeconds * 1000)+ }+ lemonToast.warning(`Refresh available again ${error.formattedRetryAfter ?? 'in a few minutes'}`)+ } else {+ lemonToast.error('Failed to refresh health checks')+ }+ }+ },+ setNextRefreshAvailableAt: async ({ timestamp }, breakpoint) => {+ if (timestamp === null) {+ return+ }+ const delay = timestamp - Date.now()+ if (delay <= 0) {+ actions.setNextRefreshAvailableAt(null)+ return+ }+ await breakpoint(delay)+ actions.setNextRefreshAvailableAt(null)},loadHealthIssuesSuccess: () => {if (values.isManualRefresh) {@@ -172,5 +241,9 @@ export const healthSceneLogic = kea<healthSceneLogicType>([if (values.unifiedHealthPageEnabled) {actions.loadHealthIssues()}++ if (values.nextRefreshAvailableAt !== null) {+ actions.setNextRefreshAvailableAt(values.nextRefreshAvailableAt)+ }}),])diff --git a/posthog/api/health_issue.py b/posthog/api/health_issue.pyindex cf96ca4424b0..818d488ed52b 100644--- a/posthog/api/health_issue.py+++ b/posthog/api/health_issue.py@@ -1,16 +1,19 @@from django.db.models import Case, Count, QuerySet, When+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializersfrom rest_framework.decorators import actionfrom rest_framework.mixins import ListModelMixin, RetrieveModelMixinfrom rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.request import Requestfrom rest_framework.response import Response-from rest_framework.status import HTTP_400_BAD_REQUEST+from rest_framework.status import HTTP_202_ACCEPTED, HTTP_400_BAD_REQUESTfrom rest_framework.viewsets import GenericViewSetfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.exceptions_capture import capture_exceptionfrom posthog.models.health_issue import HealthIssue+from posthog.rate_limit import HealthIssueRefreshThrottlefrom products.growth.backend.sdk_health import sdks_within_freshness_grace_period@@ -125,3 +128,43 @@ class HealthIssueViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMi"by_kind": by_kind,})++ @extend_schema(+ request=None,+ responses={+ 202: OpenApiResponse(description="Health check refresh jobs scheduled for the team."),+ 429: OpenApiResponse(description="Refresh was triggered recently; try again later."),+ },+ )+ @action(+ methods=["POST"],+ detail=False,+ url_path="refresh",+ throttle_classes=[HealthIssueRefreshThrottle],+ required_scopes=["health_issue:write"],+ )+ def refresh(self, request: Request, **kwargs) -> Response:+ from posthog.tasks.health_checks import evaluate_health_check_for_team+ from posthog.temporal.health_checks.registry import HEALTH_CHECKS, ensure_registry_loaded++ ensure_registry_loaded()+ kinds = list(HEALTH_CHECKS.keys())++ scheduled: list[str] = []+ failed: list[str] = []+ for kind in kinds:+ try:+ evaluate_health_check_for_team.delay(kind=kind, team_id=self.team_id)+ scheduled.append(kind)+ except Exception as exc:+ capture_exception(exc)+ failed.append(kind)++ return Response(+ {+ "scheduled_kinds": scheduled,+ "kinds_failed": failed,+ "team_id": self.team_id,+ },+ status=HTTP_202_ACCEPTED,+ )diff --git a/posthog/api/test/test_health_issue.py b/posthog/api/test/test_health_issue.pyindex 5ca3c5a5a38b..c2f22e916ff9 100644--- a/posthog/api/test/test_health_issue.py+++ b/posthog/api/test/test_health_issue.py@@ -1,4 +1,7 @@from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.cache import cachefrom parameterized import parameterizedfrom rest_framework import status@@ -8,8 +11,13 @@ from posthog.models.team import Teamclass TestHealthIssueAPI(APIBaseTest):- def _url(self, path: str = "") -> str:- return f"/api/environments/{self.team.id}/health_issues{path}"+ def _url(self, path: str = "", team_id: int | None = None) -> str:+ return f"/api/environments/{team_id or self.team.id}/health_issues{path}"++ def _reset_refresh_throttle(self, team_id: int | None = None) -> None:+ key = f"throttle_health_issue_refresh_team_{team_id or self.team.id}"+ cache.delete(key)+ self.addCleanup(cache.delete, key)def _create_issue(self, **kwargs) -> HealthIssue:defaults = {@@ -209,6 +217,58 @@ class TestHealthIssueAPI(APIBaseTest):response = self.client.post(self._url(f"/{issue.id}/resolve"))self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ @patch("posthog.tasks.health_checks.evaluate_health_check_for_team.delay")+ def test_refresh_schedules_a_task_per_registered_kind(self, mock_delay):+ self._reset_refresh_throttle()++ response = self.client.post(self._url("/refresh"))+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ data = response.json()+ self.assertGreater(mock_delay.call_count, 0)+ self.assertEqual(len(data["scheduled_kinds"]), mock_delay.call_count)+ self.assertEqual(data["team_id"], self.team.id)+ self.assertEqual(data["kinds_failed"], [])+ self.assertEqual(set(data["scheduled_kinds"]), {call.kwargs["kind"] for call in mock_delay.call_args_list})+ for call in mock_delay.call_args_list:+ self.assertEqual(call.kwargs["team_id"], self.team.id)++ @patch("posthog.tasks.health_checks.evaluate_health_check_for_team.delay")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_refresh_is_throttled_per_team_after_one_call(self, _enabled, _delay):+ self._reset_refresh_throttle()++ first = self.client.post(self._url("/refresh"))+ self.assertEqual(first.status_code, status.HTTP_202_ACCEPTED)++ second = self.client.post(self._url("/refresh"))+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertIn("Retry-After", second.headers)++ @patch("posthog.tasks.health_checks.evaluate_health_check_for_team.delay")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_refresh_throttle_is_per_team_not_global(self, _enabled, _delay):+ other = Team.objects.create(organization=self.organization, name="Other")+ self._reset_refresh_throttle()+ self._reset_refresh_throttle(team_id=other.id)++ response_a = self.client.post(self._url("/refresh"))+ self.assertEqual(response_a.status_code, status.HTTP_202_ACCEPTED)++ response_b = self.client.post(self._url("/refresh", team_id=other.id))+ self.assertEqual(response_b.status_code, status.HTTP_202_ACCEPTED)++ @patch("posthog.tasks.health_checks.evaluate_health_check_for_team.delay", side_effect=Exception("broker down"))+ def test_refresh_handles_partial_broker_failure(self, _delay):+ self._reset_refresh_throttle()++ response = self.client.post(self._url("/refresh"))+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ data = response.json()+ self.assertEqual(data["scheduled_kinds"], [])+ self.assertGreater(len(data["kinds_failed"]), 0)+@parameterized.expand([("POST", ""),diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 4ea7887e667a..973e9c349b65 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -952,6 +952,25 @@ class GitHubRepositoryRefreshThrottle(PersonalApiKeyOrUserRateThrottle):return super().get_cache_key(request, view)+class HealthIssueRefreshThrottle(PersonalApiKeyOrUserRateThrottle):+ scope = "health_issue_refresh"+ rate = "1/15minutes"++ def parse_rate(self, rate):+ if rate is None:+ return (None, None)+ num, period = rate.split("/")+ if period.endswith("minutes"):+ return (int(num), int(period[:-7]) * 60)+ return super().parse_rate(rate)++ def get_cache_key(self, request, view):+ team_id = self.safely_get_team_id_from_view(view)+ if team_id:+ return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}+ return super().get_cache_key(request, view)++class ToolbarOAuthRefreshThrottle(IPThrottle):"""Rate limit the unauthenticated toolbar OAuth refresh endpoint by IP."""diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.pyindex 6397d4e3dd8b..1e7df4c92604 100644--- a/posthog/test/test_rate_limit.py+++ b/posthog/test/test_rate_limit.py@@ -860,3 +860,17 @@ class TestUserAPI(APIBaseTest):self.assertEqual(num_requests, 6)self.assertEqual(duration, 1200) # 20 minutes * 60 seconds++ def test_health_issue_refresh_throttle_parses_15_minute_window(self):+ throttle = rate_limit.HealthIssueRefreshThrottle()+ num_requests, duration = throttle.parse_rate("1/15minutes")++ self.assertEqual(num_requests, 1)+ self.assertEqual(duration, 15 * 60)++ def test_health_issue_refresh_throttle_falls_back_to_default_parser(self):+ throttle = rate_limit.HealthIssueRefreshThrottle()+ num_requests, duration = throttle.parse_rate("5/hour")++ self.assertEqual(num_requests, 5)+ self.assertEqual(duration, 3600)