: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(error-tracking): add rate limit history chart to project-wide limit (#61395)
Aleksander Błaszkiewicz57e028d1b9d6
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsxnew file mode 100644index 000000000000..d1fabc82a717--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx@@ -0,0 +1,93 @@+import { useMemo } from 'react'++import { getColorVar } from 'lib/colors'+import { dayjs } from 'lib/dayjs'++import { LineGraph } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'+import { ChartDisplayType } from '~/types'++import { getBucketOption, RateLimitHistoryBucket } from './rateLimitConfigLogic'+import { formatBucketLabel, getBucketTimeline } from './RateLimitSimulationChart'++function fillHistoryBuckets(history: RateLimitHistoryBucket[], bucketMinutes: number): RateLimitHistoryBucket[] {+ const bucketMs = getBucketOption(bucketMinutes).minutes * 60_000+ const byBucket = new Map<number, RateLimitHistoryBucket>()+ history.forEach((b) => {+ const aligned = Math.floor(dayjs(b.bucket).valueOf() / bucketMs) * bucketMs+ byBucket.set(aligned, b)+ })+ return getBucketTimeline(bucketMinutes).map((ms) => {+ const entry = byBucket.get(ms)+ return { bucket: dayjs(ms).toISOString(), recorded: entry?.recorded ?? 0, dropped: entry?.dropped ?? 0 }+ })+}++export function RateLimitHistoryChart({+ history,+ bucketMinutes,+}: {+ history: RateLimitHistoryBucket[]+ bucketMinutes: number+}): JSX.Element {+ const { xData, yData, isEmpty } = useMemo(() => {+ const filled = fillHistoryBuckets(history, bucketMinutes)+ const labels = filled.map((b) => formatBucketLabel(b.bucket, bucketMinutes))+ const recorded = filled.map((b) => b.recorded)+ const dropped = filled.map((b) => b.dropped)++ return {+ isEmpty: recorded.every((c) => c === 0) && dropped.every((c) => c === 0),+ xData: {+ column: {+ name: 'bucket',+ type: { name: 'STRING' as const, isNumerical: false },+ label: 'Bucket',+ dataIndex: 0,+ },+ data: labels,+ },+ yData: [+ {+ column: {+ name: 'recorded',+ type: { name: 'INTEGER' as const, isNumerical: true },+ label: 'Recorded',+ dataIndex: 0,+ },+ data: recorded,+ settings: { display: { displayType: 'bar' as const } },+ },+ {+ column: {+ name: 'dropped',+ type: { name: 'INTEGER' as const, isNumerical: true },+ label: 'Dropped',+ dataIndex: 0,+ },+ data: dropped,+ settings: { display: { displayType: 'bar' as const, color: getColorVar('danger') } },+ },+ ],+ }+ }, [history, bucketMinutes])++ 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.+ </div>+ )+ }++ return (+ <div className="h-80 border rounded">+ <LineGraph+ className="h-full p-4"+ xData={xData}+ yData={yData}+ visualizationType={ChartDisplayType.ActionsStackedBar}+ chartSettings={{ showXAxisTicks: false, showXAxisBorder: false }}+ />+ </div>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsxindex f485fba972eb..d248e2689c1f 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx@@ -1,7 +1,8 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'-import { LemonSelect } from '@posthog/lemon-ui'+import { IconRefresh } from '@posthog/icons'+import { LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -11,6 +12,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { IssueRateLimitSettings } from './IssueRateLimitSettings'import { BUCKET_OPTIONS, rateLimitConfigLogic } from './rateLimitConfigLogic'+import { RateLimitHistoryChart } from './RateLimitHistoryChart'import { formatTotalDuration, RateLimitSimulationChart } from './RateLimitSimulationChart'export function RateLimitSettings(): JSX.Element {@@ -33,7 +35,12 @@ function ProjectRateLimitSection(): JSX.Element {volume,volumeLoading,volumeBucketMinutes,+ chartMode,+ history,+ historyLoading,} = useValues(rateLimitConfigLogic)+ const { setChartMode, refreshChart } = useActions(rateLimitConfigLogic)+ const chartLoading = chartMode === 'history' ? historyLoading : volumeLoadingif (configLoading) {return (@@ -97,19 +104,54 @@ function ProjectRateLimitSection(): JSX.Element {</div></div>- <div className="md:col-span-7">- <div className="text-sm font-medium mb-1">- Exception volume — past {formatTotalDuration(volumeBucketMinutes)}+ <div className="md:col-span-7 space-y-2">+ <p className="text-muted-foreground text-xs">+ {chartMode === 'simulation'+ ? 'This shows your past traffic to help you choose a rate limit.'+ : 'This shows how many 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(volumeBucketMinutes)}+ </span>+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconRefresh />}+ onClick={refreshChart}+ loading={chartLoading}+ tooltip="Refresh with the latest data"+ />+ </div>+ </div>+ {chartMode === 'simulation' ? (+ volumeLoading && volume.length === 0 ? (+ <LemonSkeleton className="w-full h-80" />+ ) : (+ <RateLimitSimulationChart+ volume={volume}+ rateLimit={configForm.project_rate_limit_value}+ bucketMinutes={volumeBucketMinutes}+ />+ )+ ) : historyLoading && history.length === 0 ? (+ <LemonSkeleton className="w-full h-80" />+ ) : (+ <RateLimitHistoryChart history={history} bucketMinutes={volumeBucketMinutes} />+ )}</div>- {volumeLoading ? (- <LemonSkeleton className="w-full h-80" />- ) : (- <RateLimitSimulationChart- volume={volume}- rateLimit={configForm.project_rate_limit_value}- bucketMinutes={volumeBucketMinutes}- />- )}</div></div></Form>diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsxindex 3bc188ba9ec3..b448e1b416bd 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx@@ -21,24 +21,31 @@ export function formatTotalDuration(bucketMinutes: number): string {return pluralize(Math.round(totalMinutes / 60), 'hour')}-function fillBuckets(volume: ExceptionVolumeBucket[], bucketMinutes: number): ExceptionVolumeBucket[] {+export function getBucketTimeline(bucketMinutes: number): number[] {const option = getBucketOption(bucketMinutes)const bucketMs = option.minutes * 60_000+ const endMs = Math.floor(Date.now() / bucketMs) * bucketMs+ const timeline: number[] = []+ for (let i = option.bucketCount - 1; i >= 0; i--) {+ timeline.push(endMs - i * bucketMs)+ }+ return timeline+}++function fillBuckets(volume: ExceptionVolumeBucket[], bucketMinutes: number): ExceptionVolumeBucket[] {+ const bucketMs = getBucketOption(bucketMinutes).minutes * 60_000const counts = new Map<number, number>()volume.forEach((b) => {const aligned = Math.floor(dayjs(b.bucket).valueOf() / bucketMs) * bucketMscounts.set(aligned, b.count)})- const endMs = Math.floor(Date.now() / bucketMs) * bucketMs- const buckets: ExceptionVolumeBucket[] = []- for (let i = option.bucketCount - 1; i >= 0; i--) {- const ms = endMs - i * bucketMs- buckets.push({ bucket: dayjs(ms).toISOString(), count: counts.get(ms) ?? 0 })- }- return buckets+ return getBucketTimeline(bucketMinutes).map((ms) => ({+ bucket: dayjs(ms).toISOString(),+ count: counts.get(ms) ?? 0,+ }))}-function formatBucketLabel(iso: string, bucketMinutes: number): string {+export function formatBucketLabel(iso: string, bucketMinutes: number): string {const ts = dayjs(iso)if (bucketMinutes >= 1440) {return ts.format('MMM D')diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.tsindex e92ae7f67ce9..c400ca8af007 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts@@ -1,4 +1,4 @@-import { afterMount, kea, listeners, path, reducers } from 'kea'+import { actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'@@ -6,6 +6,7 @@ import posthog from 'posthog-js'import api from 'lib/api'import { ErrorTrackingSettings } from 'lib/components/Errors/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { teamLogic } from 'scenes/teamLogic'import { HogQLQueryResponse, NodeKind, ProductKey } from '~/queries/schema/schema-general'@@ -45,6 +46,25 @@ export interface ExceptionVolumeBucket {count: number}+export interface RateLimitHistoryBucket {+ bucket: string+ recorded: number+ dropped: number+}++export type RateLimitChartMode = 'simulation' | 'history'++// `force` recomputes server-side instead of serving cached results — used by the chart refresh button.+export interface ChartLoadParams {+ bucketMinutes: number+ 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'+export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([path(['products',@@ -55,6 +75,15 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>(['rateLimitConfigLogic',]),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),++ actions({+ setChartMode: (mode: RateLimitChartMode) => ({ mode }),+ refreshChart: true,+ }),+reducers({hasLoadedConfig: [false,@@ -62,16 +91,22 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([loadConfigSuccess: () => true,},],+ chartMode: [+ 'simulation' as RateLimitChartMode,+ {+ setChartMode: (_, { mode }: { mode: RateLimitChartMode }) => mode,+ },+ ],volumeBucketMinutes: [DEFAULT_BUCKET_MINUTES,{- loadVolumeSuccess: (state, { payload: requestedBucketMinutes }: { payload?: number }) =>- requestedBucketMinutes ?? state,+ loadVolumeSuccess: (state, { payload }: { payload?: ChartLoadParams }) =>+ payload?.bucketMinutes ?? state,},],}),- loaders({+ loaders(({ values }) => ({config: [null as ErrorTrackingSettings | null,{@@ -83,12 +118,13 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([volume: [[] as ExceptionVolumeBucket[],{- loadVolume: async (bucketMinutes: number) => {+ loadVolume: async ({ bucketMinutes, force }: ChartLoadParams) => {const option = getBucketOption(bucketMinutes)const totalMinutes = option.minutes * option.bucketCount- const response = (await api.query({- kind: NodeKind.HogQLQuery,- query: `+ const response = (await api.query(+ {+ kind: NodeKind.HogQLQuery,+ query: `SELECTtoStartOfInterval(timestamp, INTERVAL ${option.minutes} MINUTE) AS bucket,count() AS count@@ -98,8 +134,10 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([GROUP BY bucketORDER BY bucket`,- tags: { productKey: ProductKey.ERROR_TRACKING },- })) as HogQLQueryResponse+ tags: { productKey: ProductKey.ERROR_TRACKING },+ },+ force ? { refresh: 'force_blocking' } : undefined+ )) as HogQLQueryResponsereturn (response.results ?? []).map(([bucket, count]) => ({bucket: String(bucket),count: Number(count),@@ -107,7 +145,49 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([},},],- }),+ history: [+ [] as RateLimitHistoryBucket[],+ {+ loadHistory: async ({ bucketMinutes, force }: ChartLoadParams) => {+ const option = getBucketOption(bucketMinutes)+ const totalMinutes = option.minutes * option.bucketCount+ const appSourceId = `${values.currentTeamId}:exceptions:global`+ 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 = '${appSourceId}'+ AND metric_name IN ('${RECORDED_METRIC_NAME}', '${DROPPED_METRIC_NAME}')+ AND timestamp >= now() - INTERVAL ${totalMinutes} MINUTE+ GROUP BY bucket, metric_name+ ORDER BY bucket+ `,+ tags: { productKey: ProductKey.ERROR_TRACKING },+ },+ force ? { refresh: 'force_blocking' } : undefined+ )) as HogQLQueryResponse+ 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 }) => ({configForm: {@@ -133,7 +213,7 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([},})),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({loadConfigSuccess: ({ config }) => {const bucket = getBucketOption(config?.project_rate_limit_bucket_size_minutes ?? DEFAULT_BUCKET_MINUTES@@ -144,12 +224,31 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([project_rate_limit_bucket_size_minutes: bucket,})}- actions.loadVolume(bucket)+ actions.loadVolume({ bucketMinutes: bucket })},setConfigFormValue: ({ name, value }) => {const fieldName = Array.isArray(name) ? name[name.length - 1] : nameif (fieldName === 'project_rate_limit_bucket_size_minutes' && typeof value === 'number') {- actions.loadVolume(value)+ actions.loadVolume({ bucketMinutes: value })+ if (values.chartMode === 'history') {+ actions.loadHistory({ bucketMinutes: value })+ }+ }+ },+ setChartMode: ({ mode }) => {+ if (mode === 'history') {+ actions.loadHistory({ bucketMinutes: values.configForm.project_rate_limit_bucket_size_minutes })+ }+ },+ refreshChart: () => {+ const params: ChartLoadParams = {+ bucketMinutes: values.configForm.project_rate_limit_bucket_size_minutes,+ force: true,+ }+ if (values.chartMode === 'history') {+ actions.loadHistory(params)+ } else {+ actions.loadVolume(params)}},})),