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(dashboards): retry capacity failures and track recovery accurately (#106001)

posthog[bot]34b7b80a96e9
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index f61545c2b423..83678add18f3 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -2816,8 +2816,8 @@ describe('dashboardLogic', () => {
query_async: true,
complete: false,
error: true,
- error_code: null,
- error_message: 'concurrency_limit_exceeded',
+ error_code: 'rate_limited',
+ error_message: 'Queries are a little too busy right now.',
},
}))
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index c144e442b9a5..79ed3c582bc9 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -1,8 +1,11 @@
+import posthog from 'posthog-js'
+
import api from 'lib/api'
import { ApiError } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { BreakdownFilter, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
+import { BreakdownFilter, DashboardFilter, HogQLVariable, QueryStatus } from '~/queries/schema/schema-general'
import {
AnyPropertyFilter,
DashboardPlacement,
@@ -281,9 +284,25 @@ describe('dashboardSearchParamsFromOverrides', () => {
describe('getInsightWithRetry', () => {
const insight = { id: 300, short_id: 'abc123', name: 'Test insight' } as InsightModel
const MAX_ATTEMPTS = 3
+ const capacityStatus: QueryStatus = {
+ id: 'q',
+ team_id: 1,
+ query_async: true,
+ complete: true,
+ error: true,
+ error_code: 'rate_limited',
+ error_message: 'Queries are a little too busy right now. Please try again later.',
+ }
+ const insightResponse = (value: Partial<InsightModel> | null): Response =>
+ new Response(JSON.stringify(value), { status: 200 })
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
afterEach(() => {
jest.restoreAllMocks()
+ jest.useRealTimers()
})
it.each<[string, number, number | undefined]>([
@@ -294,8 +313,119 @@ describe('getInsightWithRetry', () => {
])('on %s, requests %i time(s) before throwing', async (_, expectedAttempts, status) => {
const getResponseSpy = jest.spyOn(api, 'getResponse').mockRejectedValue(new ApiError('some error', status))
- await expect(
- getInsightWithRetry(
+ const request = getInsightWithRetry(
+ 1,
+ insight,
+ 60,
+ 'query-id',
+ 'blocking',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ MAX_ATTEMPTS,
+ 1
+ )
+ await Promise.all([expect(request).rejects.toThrow('some error'), jest.runAllTimersAsync()])
+ expect(getResponseSpy).toHaveBeenCalledTimes(expectedAttempts)
+ })
+
+ it.each([
+ ['a structured capacity code', 'rate_limited', capacityStatus.error_message],
+ ['a legacy concurrency response', 'concurrency_limit_exceeded', 'concurrency_limit_exceeded'],
+ ])('retries %s', async (_name, error_code, error_message) => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ const getResponseSpy = jest
+ .spyOn(api, 'getResponse')
+ .mockResolvedValueOnce(
+ insightResponse({
+ ...insight,
+ result: null,
+ query_status: { ...capacityStatus, error_code, error_message },
+ })
+ )
+ .mockResolvedValueOnce(insightResponse({ ...insight, result: [{ count: 1 }] }))
+
+ const request = getInsightWithRetry(
+ 1,
+ insight,
+ 60,
+ 'query-id',
+ 'blocking',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ MAX_ATTEMPTS,
+ 1
+ )
+ await jest.runAllTimersAsync()
+ const result = await request
+
+ expect(getResponseSpy).toHaveBeenCalledTimes(2)
+ expect(result?.result).toEqual([{ count: 1 }])
+ expect(capture).toHaveBeenCalledWith(
+ 'dashboard tile recovered from capacity error',
+ { insight_short_id: 'abc123', dashboard_id: 60, attempts: 1 },
+ undefined
+ )
+ })
+
+ describe.each([
+ ['blocking retry', 2],
+ ['async fallback', 1],
+ ] as const)('%s recovery', (_path, maxAttempts) => {
+ it.each<{ name: string; response: Partial<InsightModel> | null; recovered: boolean; hasError: boolean }>([
+ {
+ name: 'a usable result',
+ response: { ...insight, result: [{ count: 1 }] },
+ recovered: true,
+ hasError: false,
+ },
+ { name: 'an empty result', response: { ...insight, result: [] }, recovered: true, hasError: false },
+ {
+ name: 'a failed calculation',
+ response: {
+ ...insight,
+ result: null,
+ query_status: { ...capacityStatus, error_code: 'hogql_error', error_message: 'Invalid query' },
+ },
+ recovered: false,
+ hasError: true,
+ },
+ {
+ name: 'an error with results',
+ response: {
+ ...insight,
+ result: [],
+ query_status: { ...capacityStatus, error_code: 'hogql_error', error_message: 'Invalid query' },
+ },
+ recovered: false,
+ hasError: true,
+ },
+ { name: 'a missing result', response: { ...insight, result: null }, recovered: false, hasError: false },
+ { name: 'no insight', response: null, recovered: false, hasError: maxAttempts === 1 },
+ ])('records recovery only for usable data: $name', async ({ response, recovered, hasError }) => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ jest.spyOn(lemonToast, 'error').mockImplementation()
+ jest.spyOn(api, 'getResponse')
+ .mockResolvedValueOnce(insightResponse({ ...insight, result: null, query_status: capacityStatus }))
+ .mockResolvedValueOnce(insightResponse(response))
+ jest.spyOn(api, 'get').mockResolvedValue({
+ ...insight,
+ query_status: {
+ ...capacityStatus,
+ complete: false,
+ error: false,
+ error_code: null,
+ error_message: null,
+ },
+ })
+ jest.spyOn(api.queryStatus, 'get').mockResolvedValue({
+ query_status: { ...capacityStatus, error: false, error_code: null, error_message: null },
+ })
+
+ const request = getInsightWithRetry(
1,
insight,
60,
@@ -305,11 +435,18 @@ describe('getInsightWithRetry', () => {
undefined,
undefined,
undefined,
- MAX_ATTEMPTS,
+ maxAttempts,
1
)
- ).rejects.toThrow('some error')
- expect(getResponseSpy).toHaveBeenCalledTimes(expectedAttempts)
+ await jest.runAllTimersAsync()
+ const result = await request
+
+ expect(
+ capture.mock.calls.filter(([event]) => event === 'dashboard tile recovered from capacity error')
+ ).toHaveLength(recovered ? 1 : 0)
+ expect(result?.result ?? null).toEqual(response?.result ?? null)
+ expect(Boolean(result?.query_status?.error)).toBe(hasError)
+ })
})
})
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index d57ecac38796..e521205c8431 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -8,6 +8,7 @@ import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
import { ApiError } from 'lib/api-error'
import type { Dayjs } from 'lib/dayjs'
import { currentSessionId } from 'lib/internalMetrics'
+import posthog from 'lib/posthog-typed'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { objectClean } from 'lib/utils/objects'
@@ -200,6 +201,9 @@ export const SEARCH_PARAM_FILTERS_KEY = 'query_filters'
export const AUTO_PREVIEW_TILE_LIMIT: number = 22
+// The backend labels every transient capacity failure with this code, whatever its message: PostHog's
+// own per-org concurrency limit, and ClickHouse refusing the query because the cluster is busy.
+const RATE_LIMITED_ERROR_CODE = 'rate_limited'
const RATE_LIMIT_ERROR_MESSAGE = 'concurrency_limit_exceeded'
// A refresh that was rejected (concurrency limit, server-side calculation error) still resolves with an
@@ -324,6 +328,17 @@ export async function getInsightWithRetry(
}
let attempt = 0
+ let rateLimitedAttempts = 0
+
+ const captureRecovery = (result: InsightModel | null): void => {
+ if (rateLimitedAttempts > 0 && result?.result != null && !result.query_status?.error) {
+ posthog.capture('dashboard tile recovered from capacity error', {
+ insight_short_id: insight.short_id,
+ dashboard_id: dashboardId,
+ attempts: rateLimitedAttempts,
+ })
+ }
+ }
while (attempt < maxAttempts) {
try {
@@ -341,8 +356,12 @@ export async function getInsightWithRetry(
const legacyInsight: InsightModel | null = await getJSONOrNull(insightResponse)
const result = legacyInsight !== null ? getQueryBasedInsightModel(legacyInsight) : null
- if (result?.query_status?.error_message === RATE_LIMIT_ERROR_MESSAGE) {
+ if (
+ result?.query_status?.error_code === RATE_LIMITED_ERROR_CODE ||
+ result?.query_status?.error_message === RATE_LIMIT_ERROR_MESSAGE
+ ) {
attempt++
+ rateLimitedAttempts++
if (attempt >= maxAttempts) {
// We've exhausted all attempts, so we need to try the async endpoint.
@@ -380,7 +399,13 @@ export async function getInsightWithRetry(
const legacyInsight: InsightModel | null = await getJSONOrNull(refreshedInsightResponse)
if (legacyInsight) {
const queryBasedInsight = getQueryBasedInsightModel(legacyInsight)
- return { ...queryBasedInsight, query_status: finalStatus }
+ captureRecovery(queryBasedInsight)
+ return {
+ ...queryBasedInsight,
+ query_status: queryBasedInsight.query_status?.error
+ ? queryBasedInsight.query_status
+ : finalStatus,
+ }
}
}
}
@@ -412,6 +437,7 @@ export async function getInsightWithRetry(
continue // Retry
}
+ captureRecovery(result)
return result
} catch (e: any) {
if (shouldCancelQuery(e)) {
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index f61d239e30c0..9c8ef3a4ef8c 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -58,8 +58,9 @@ from posthog.clickhouse.cancel import cancel_query_on_cluster
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import AccessMethod, tags_context
from posthog.constants import INSIGHT, AvailableFeature
-from posthog.errors import ExposedCHQueryError
+from posthog.errors import ExposedCHQueryError, QueryErrorCategory, classify_query_error
from posthog.event_usage import EventSource, get_event_source, get_request_analytics_properties, report_user_action
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.helpers.trigram_search import (
@@ -1422,28 +1423,33 @@ class InsightSerializer(InsightBasicSerializer):
error_code=getattr(e, "code_name", None),
last_refresh=None,
)
- except ConcurrencyLimitExceeded as e:
- logger.warn(
- "concurrency_limit_exceeded_api", exception=e, insight_id=insight.id, team_id=insight.team_id
- )
- return self._degraded_insight_result(
- insight,
- dashboard,
- error=e,
- error_message="concurrency_limit_exceeded",
- error_code="concurrency_limit_exceeded",
- last_refresh=now(),
- )
except Exception as e:
- # Capture unexpected crashes so the API list doesn't fail
- logger.exception("insight_calculation_error", insight_id=insight.id, team_id=insight.team_id)
+ is_rate_limited = classify_query_error(e) == QueryErrorCategory.RATE_LIMITED
+ error_message = str(e)
+ if is_rate_limited:
+ # Older dashboard clients retry on this marker. Other capacity messages can
+ # contain internal Redis keys, task IDs or raw ClickHouse details.
+ error_message = (
+ "concurrency_limit_exceeded"
+ if isinstance(e, ConcurrencyLimitExceeded)
+ else ClickHouseAtCapacity.default_detail
+ )
+ logger.warn(
+ "insight_calculation_rate_limited",
+ exception=e,
+ insight_id=insight.id,
+ team_id=insight.team_id,
+ )
+ else:
+ # Capture unexpected crashes so the API list doesn't fail
+ logger.exception("insight_calculation_error", insight_id=insight.id, team_id=insight.team_id)
return self._degraded_insight_result(
insight,
dashboard,
error=e,
- error_message=str(e),
- error_code=None,
- last_refresh=None,
+ error_message=error_message,
+ error_code=QueryErrorCategory.RATE_LIMITED if is_rate_limited else None,
+ last_refresh=now() if is_rate_limited else None,
)
def _degraded_insight_result(
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 9484b0b0657b..28a88ddbebb7 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -22,6 +22,7 @@ from django.test import override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
+from clickhouse_driver.errors import ServerException
from parameterized import parameterized
from rest_framework import status
@@ -52,8 +53,10 @@ from posthog.hogql.query import execute_hogql_query
from posthog import settings
from posthog.api.test.dashboards import DashboardAPI
from posthog.caching.insight_result import InsightResult
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.constants import AvailableFeature
-from posthog.exceptions import ClickHouseQueryTimeOut
+from posthog.errors import wrap_clickhouse_query_error
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryTimeOut
from posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionMode
from posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -4190,15 +4193,32 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):
+ def _query_status_of_a_failed_refresh(self) -> dict:
+ insight = Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ },
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/insights/{insight.id}/?refresh=blocking")
+
+ # The failure must ride on query_status so a dashboard tile renders its own error state
+ # while the response as a whole succeeds.
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ return response.json()["query_status"]
+
@parameterized.expand(
[
("ExposedCHQueryError", "NO_COMMON_TYPE error from ClickHouse", None),
("ExposedHogQLError", "Invalid HogQL syntax", "hogql_error"),
("HogVMException", "Global variable not found: variables", None),
+ ("RuntimeError", "Unexpected calculation failure", None),
]
)
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
- def test_retrieve_degrades_in_place_for_exposed_errors(
+ def test_retrieve_degrades_in_place_for_non_capacity_errors(
self, _name: str, error_message: str, expected_error_code: str | None, mock_calculate: mock.MagicMock
) -> None:
from posthog.hogql.errors import ExposedHogQLError
@@ -4211,27 +4231,44 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):
"ExposedCHQueryError": ExposedCHQueryError,
"ExposedHogQLError": ExposedHogQLError,
"HogVMException": HogVMException,
+ "RuntimeError": RuntimeError,
}
mock_calculate.side_effect = error_classes[_name](error_message)
- insight = Insight.objects.create(
- team=self.team,
- query={
- "kind": "TrendsQuery",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- )
-
- response = self.client.get(f"/api/environments/{self.team.id}/insights/{insight.id}/?refresh=blocking")
+ query_status = self._query_status_of_a_failed_refresh()
- # The failure must ride on query_status so a dashboard tile renders its own error state
- # while the response as a whole succeeds.
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- query_status = response.json()["query_status"]
self.assertTrue(query_status["error"])
self.assertIn(error_message, query_status["error_message"])
self.assertEqual(query_status["error_code"], expected_error_code)
+ @parameterized.expand(
+ [
+ ("cluster_at_capacity", ClickHouseAtCapacity(), ClickHouseAtCapacity.default_detail),
+ (
+ "org_concurrency_limit",
+ ConcurrencyLimitExceeded("internal limiter details"),
+ "concurrency_limit_exceeded",
+ ),
+ (
+ "no_free_clickhouse_connection",
+ wrap_clickhouse_query_error(ServerException("no free connection", 203)),
+ ClickHouseAtCapacity.default_detail,
+ ),
+ ]
+ )
+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
+ def test_retrieve_labels_every_capacity_failure_as_rate_limited(
+ self, _name: str, error: Exception, expected_message: str, mock_calculate: mock.MagicMock
+ ) -> None:
+ mock_calculate.side_effect = error
+
+ query_status = self._query_status_of_a_failed_refresh()
+
+ # The dashboard retries on this code, so every transient capacity failure has to carry it.
+ self.assertTrue(query_status["error"])
+ self.assertEqual(query_status["error_code"], "rate_limited")
+ self.assertEqual(query_status["error_message"], expected_message)
+
class TestInsightQueryScan(APIBaseTest):
FLAG = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)