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(error-tracking): per-issue rate-limit metrics in app_metrics2 + history view (#65536)

Aleksander Błaszkiewicz585edd6a29bb
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
index cf300dc1af44..ac198265cbee 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
@@ -643,6 +643,43 @@ describe('ErrorTrackingConsumer', () => {
await drainProduces()
expect(producedCount()).toBe(5)
})
+
+ it('emits per-issue app_metrics2 rows keyed by the Cymbal-assigned issue id', async () => {
+ await upsertSettings({ perIssueRateLimit: 2 })
+ await enableRateLimiter()
+
+ // issue-foo bucket of 2: 4 events → 2 allowed, 2 rate_limited.
+ const events = Array.from({ length: 4 }, () => exceptionEvent('foo'))
+ await consumer.handleKafkaBatch(createKafkaMessages(events))
+ await drainProduces()
+
+ const appMetrics = mockProducerObserver
+ .getProducedKafkaMessagesForTopic('clickhouse_app_metrics2_test')
+ .map((m) => m.value)
+
+ expect(appMetrics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ team_id: team.id,
+ app_source: 'exceptions',
+ app_source_id: 'issue-foo',
+ metric_kind: 'rate_limiting',
+ metric_name: 'allowed',
+ count: 2,
+ }),
+ expect.objectContaining({
+ team_id: team.id,
+ app_source: 'exceptions',
+ app_source_id: 'issue-foo',
+ metric_kind: 'rate_limiting',
+ metric_name: 'rate_limited',
+ count: 2,
+ }),
+ ])
+ )
+ // Every rate-limiting row is keyed by the issue id, not collapsed per team.
+ expect(appMetrics.every((v) => v?.app_source_id === 'issue-foo')).toBe(true)
+ })
})
})
})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
index 5731653e12eb..ca91353b2361 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
@@ -324,9 +324,11 @@ export class ErrorTrackingConsumer {
? `${input.team.id}:exceptions:issue:${issueId}`
: null
},
- // Per-issue keys are high-cardinality; collapse every issue's outcomes into a
- // single app_metrics2 row per team rather than one row per issue.
- getAppSourceId: (input) => `${input.team.id}:exceptions:per_issue`,
+ // Record the allowed/rate_limited decision per issue so the per-issue view can
+ // show counts keyed by the Cymbal-assigned issue id. getAppSourceId is only called
+ // for inputs whose getKey was non-null, which guarantees $exception_issue_id is a
+ // non-empty string here.
+ getAppSourceId: (input) => input.event.properties?.$exception_issue_id as string,
getTeamId: (input) => input.team.id,
reportingMode: this.config.rateLimiterReportingMode,
dropReason: 'rate_limited:per_issue',
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx
index ef82996b5a59..953c3be68899 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx
@@ -1,7 +1,8 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'
+import { IconRefresh } from '@posthog/icons'
+import { LemonSegmentedButton, LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -12,6 +13,7 @@ import { urls } from 'scenes/urls'
import { issueRateLimitConfigLogic } from './issueRateLimitConfigLogic'
import { BUCKET_OPTIONS } from './rateLimitConfigLogic'
+import { RateLimitHistoryChart } from './RateLimitHistoryChart'
import { formatTotalDuration, RateLimitSimulationChart } from './RateLimitSimulationChart'
export function IssueRateLimitSettings(): JSX.Element {
@@ -184,17 +186,25 @@ function IssuesListColumn(): JSX.Element {
}
function PreviewColumn(): JSX.Element {
- const { selectedIssue, selectedIssueVolume, selectedIssueVolumeLoading, configForm, topIssues } =
- useValues(issueRateLimitConfigLogic)
+ const {
+ selectedIssue,
+ selectedIssueVolume,
+ selectedIssueVolumeLoading,
+ selectedIssueHistory,
+ selectedIssueHistoryLoading,
+ chartMode,
+ configForm,
+ topIssues,
+ } = useValues(issueRateLimitConfigLogic)
+ const { setChartMode, refreshChart } = useActions(issueRateLimitConfigLogic)
const limit = configForm.per_issue_rate_limit_value
const bucketMinutes = configForm.per_issue_rate_limit_bucket_size_minutes
+ const chartLoading = chartMode === 'history' ? selectedIssueHistoryLoading : selectedIssueVolumeLoading
const heading = (
<div className="text-sm font-medium mb-1 truncate">
- {selectedIssue
- ? `Exception volume for "${selectedIssue.name || 'Untitled issue'}" — past ${formatTotalDuration(bucketMinutes)}`
- : 'Volume'}
+ {selectedIssue ? `"${selectedIssue.name || 'Untitled issue'}"` : 'Volume'}
</div>
)
@@ -209,19 +219,58 @@ function PreviewColumn(): JSX.Element {
)
}
- if (selectedIssueVolumeLoading) {
- return (
- <div className="space-y-1">
- {heading}
- <LemonSkeleton className="w-full h-80" />
- </div>
- )
- }
-
return (
- <div className="space-y-1">
+ <div className="space-y-2">
{heading}
- <RateLimitSimulationChart volume={selectedIssueVolume} rateLimit={limit} bucketMinutes={bucketMinutes} />
+ <p className="text-muted-foreground text-xs">
+ {chartMode === 'simulation'
+ ? "This shows the issue's past traffic to help you choose a rate limit."
+ : "This shows how many of the issue's exceptions were recorded vs dropped based on your rate limits."}
+ </p>
+ <div className="relative">
+ <div className="absolute top-2 left-2 right-2 z-10 flex items-center justify-between gap-2 pointer-events-none">
+ <LemonSegmentedButton
+ className="pointer-events-auto bg-surface-primary rounded"
+ size="xsmall"
+ value={chartMode}
+ onChange={setChartMode}
+ options={[
+ { value: 'simulation', label: 'Simulation' },
+ { value: 'history', label: 'History' },
+ ]}
+ />
+ <div className="pointer-events-auto flex items-center gap-2 bg-surface-primary rounded pl-2">
+ <span className="text-muted-foreground text-xs">Past {formatTotalDuration(bucketMinutes)}</span>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconRefresh />}
+ onClick={refreshChart}
+ loading={chartLoading}
+ tooltip="Refresh with the latest data"
+ />
+ </div>
+ </div>
+ {chartMode === 'simulation' ? (
+ selectedIssueVolumeLoading && selectedIssueVolume.length === 0 ? (
+ <LemonSkeleton className="w-full h-80" />
+ ) : (
+ <RateLimitSimulationChart
+ volume={selectedIssueVolume}
+ rateLimit={limit}
+ bucketMinutes={bucketMinutes}
+ />
+ )
+ ) : selectedIssueHistoryLoading && selectedIssueHistory.length === 0 ? (
+ <LemonSkeleton className="w-full h-80" />
+ ) : (
+ <RateLimitHistoryChart
+ history={selectedIssueHistory}
+ bucketMinutes={bucketMinutes}
+ emptyMessage="No rate limiting activity recorded yet for this issue. Exceptions dropped by your per-issue limit will appear here."
+ />
+ )}
+ </div>
</div>
)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx
index d1fabc82a717..e720f6f9fcfb 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx
@@ -25,9 +25,11 @@ function fillHistoryBuckets(history: RateLimitHistoryBucket[], bucketMinutes: nu
export function RateLimitHistoryChart({
history,
bucketMinutes,
+ emptyMessage = 'No rate limiting activity recorded yet. Exceptions dropped by your project-wide limit will appear here.',
}: {
history: RateLimitHistoryBucket[]
bucketMinutes: number
+ emptyMessage?: string
}): JSX.Element {
const { xData, yData, isEmpty } = useMemo(() => {
const filled = fillHistoryBuckets(history, bucketMinutes)
@@ -74,7 +76,7 @@ export function RateLimitHistoryChart({
if (isEmpty) {
return (
<div className="h-80 border rounded flex items-center justify-center text-muted-foreground text-sm p-4 text-center">
- No rate limiting activity recorded yet. Exceptions dropped by your project-wide limit will appear here.
+ {emptyMessage}
</div>
)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts
index e1eaf468e262..3fa601d8fd3f 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts
@@ -10,7 +10,16 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { HogQLQueryResponse, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import type { issueRateLimitConfigLogicType } from './issueRateLimitConfigLogicType'
-import { DEFAULT_BUCKET_MINUTES, ExceptionVolumeBucket, getBucketOption } from './rateLimitConfigLogic'
+import {
+ DEFAULT_BUCKET_MINUTES,
+ DROPPED_METRIC_NAME,
+ EXCEPTIONS_APP_SOURCE,
+ ExceptionVolumeBucket,
+ getBucketOption,
+ RateLimitChartMode,
+ RateLimitHistoryBucket,
+ RECORDED_METRIC_NAME,
+} from './rateLimitConfigLogic'
export interface IssueRateLimitConfigForm {
per_issue_rate_limit_value: number | null
@@ -41,6 +50,8 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
actions({
selectIssue: (issueId: string | null) => ({ issueId }),
+ setChartMode: (mode: RateLimitChartMode) => ({ mode }),
+ refreshChart: true,
}),
reducers({
@@ -56,6 +67,12 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
selectIssue: (_, { issueId }) => issueId,
},
],
+ chartMode: [
+ 'simulation' as RateLimitChartMode,
+ {
+ setChartMode: (_, { mode }) => mode,
+ },
+ ],
}),
loaders(() => ({
@@ -109,31 +126,37 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
{
issueId,
bucketMinutes,
+ force,
}: {
issueId: string
bucketMinutes: number
+ force?: boolean
},
breakpoint
) => {
const option = getBucketOption(bucketMinutes)
const totalMinutes = option.minutes * option.bucketCount
await breakpoint(300)
- const response = (await api.query({
- kind: NodeKind.HogQLQuery,
- query: `
+ const response = (await api.query(
+ {
+ kind: NodeKind.HogQLQuery,
+ query: `
SELECT
toStartOfInterval(timestamp, INTERVAL ${option.minutes} MINUTE) AS bucket,
count() AS count
FROM events
WHERE event = '$exception'
AND timestamp >= now() - INTERVAL ${totalMinutes} MINUTE
- AND toString(issue_id_v2) = '${issueId}'
+ AND toString(issue_id_v2) = {issueId}
GROUP BY bucket
ORDER BY bucket
LIMIT ${option.bucketCount + 1}
`,
- tags: { productKey: ProductKey.ERROR_TRACKING },
- })) as HogQLQueryResponse
+ values: { issueId },
+ tags: { productKey: ProductKey.ERROR_TRACKING },
+ },
+ force ? { refresh: 'force_blocking' } : undefined
+ )) as HogQLQueryResponse
breakpoint()
return (response.results ?? []).map(([bucket, count]) => ({
bucket: String(bucket),
@@ -142,6 +165,63 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
},
},
],
+ selectedIssueHistory: [
+ [] as RateLimitHistoryBucket[],
+ {
+ loadSelectedIssueHistory: async (
+ {
+ issueId,
+ bucketMinutes,
+ force,
+ }: {
+ issueId: string
+ bucketMinutes: number
+ force?: boolean
+ },
+ breakpoint
+ ) => {
+ const option = getBucketOption(bucketMinutes)
+ const totalMinutes = option.minutes * option.bucketCount
+ await breakpoint(300)
+ // The per-issue rate limiter emits app_metrics2 rows keyed by the issue id directly.
+ const response = (await api.query(
+ {
+ kind: NodeKind.HogQLQuery,
+ query: `
+ SELECT
+ toStartOfInterval(timestamp, INTERVAL ${option.minutes} MINUTE) AS bucket,
+ metric_name,
+ sum(count) AS count
+ FROM app_metrics
+ WHERE app_source = '${EXCEPTIONS_APP_SOURCE}'
+ AND app_source_id = {issueId}
+ AND metric_name IN ('${RECORDED_METRIC_NAME}', '${DROPPED_METRIC_NAME}')
+ AND timestamp >= now() - INTERVAL ${totalMinutes} MINUTE
+ GROUP BY bucket, metric_name
+ ORDER BY bucket
+ LIMIT ${(option.bucketCount + 1) * 2}
+ `,
+ values: { issueId },
+ tags: { productKey: ProductKey.ERROR_TRACKING },
+ },
+ force ? { refresh: 'force_blocking' } : undefined
+ )) as HogQLQueryResponse
+ breakpoint()
+ const byBucket = new Map<string, RateLimitHistoryBucket>()
+ for (const [bucket, metricName, count] of response.results ?? []) {
+ const key = String(bucket)
+ const entry = byBucket.get(key) ?? { bucket: key, recorded: 0, dropped: 0 }
+ if (metricName === RECORDED_METRIC_NAME) {
+ entry.recorded = Number(count)
+ } else if (metricName === DROPPED_METRIC_NAME) {
+ entry.dropped = Number(count)
+ }
+ byBucket.set(key, entry)
+ }
+ return [...byBucket.values()]
+ },
+ },
+ ],
})),
forms(({ actions }) => ({
@@ -196,12 +276,14 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
}
},
selectIssue: ({ issueId }) => {
- if (issueId) {
- actions.loadSelectedIssueVolume({
- issueId,
- bucketMinutes: values.configForm.per_issue_rate_limit_bucket_size_minutes,
- })
+ if (!issueId) {
+ return
}
+ const bucketMinutes = values.configForm.per_issue_rate_limit_bucket_size_minutes
+ // Fetch both charts once per issue; toggling between Simulation and History then reuses
+ // them without refetching. The reload button forces a refresh when fresh data is wanted.
+ actions.loadSelectedIssueVolume({ issueId, bucketMinutes })
+ actions.loadSelectedIssueHistory({ issueId, bucketMinutes })
},
loadTopIssuesSuccess: ({ topIssues }) => {
const current = values.selectedIssueId
@@ -211,6 +293,18 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
actions.selectIssue(nextId)
}
},
+ refreshChart: () => {
+ const issueId = values.selectedIssueId
+ if (!issueId) {
+ return
+ }
+ const bucketMinutes = values.configForm.per_issue_rate_limit_bucket_size_minutes
+ if (values.chartMode === 'history') {
+ actions.loadSelectedIssueHistory({ issueId, bucketMinutes, force: true })
+ } else {
+ actions.loadSelectedIssueVolume({ issueId, bucketMinutes, force: true })
+ }
+ },
})),
afterMount(({ actions, values }) => {
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts
index e39649ee4af1..f59d18b24498 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts
@@ -60,10 +60,12 @@ export interface ChartLoadParams {
force?: boolean
}
-// app_metrics2 fields emitted by the team-global rate limiter in the error tracking ingestion pipeline.
-const EXCEPTIONS_APP_SOURCE = 'exceptions'
-const RECORDED_METRIC_NAME = 'allowed'
-const DROPPED_METRIC_NAME = 'rate_limited'
+// app_metrics2 fields emitted by the rate limiters in the error tracking ingestion pipeline.
+// The team-global limiter uses app_source_id `${teamId}:exceptions:global`; the per-issue
+// limiter uses the issue id directly. Both share the same source and metric names.
+export const EXCEPTIONS_APP_SOURCE = 'exceptions'
+export const RECORDED_METRIC_NAME = 'allowed'
+export const DROPPED_METRIC_NAME = 'rate_limited'
export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([
path([