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): move issue/project rate limiting to after cymbal (#62162)

Aleksander Błaszkiewicz4018b0ae03bc
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
index 237f90cd4809..230d9b00fa27 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
@@ -68,18 +68,24 @@ const createMockPersonRepository = (): jest.Mocked<PersonReadRepository> => ({
jest.mock('./cymbal', () => ({
CymbalClient: jest.fn().mockImplementation(() => ({
processExceptions: jest.fn().mockImplementation((items) =>
- // Return a valid response for each item, preserving input properties
- items.map((item: any) => ({
- uuid: item.request.uuid,
- event: item.request.event,
- team_id: item.request.team_id,
- timestamp: item.request.timestamp,
- properties: {
- ...item.request.properties,
- $exception_fingerprint: `fingerprint-${item.request.uuid}`,
- $exception_issue_id: `issue-${item.request.uuid}`,
- },
- }))
+ items.map((item: any) => {
+ const signature = (item.request.properties?.$exception_list ?? [])
+ .flatMap((exc: any) => exc?.stacktrace?.frames ?? [])
+ .map((frame: any) => frame?.function ?? '')
+ .join('|')
+ const issueKey = signature || item.request.uuid
+ return {
+ uuid: item.request.uuid,
+ event: item.request.event,
+ team_id: item.request.team_id,
+ timestamp: item.request.timestamp,
+ properties: {
+ ...item.request.properties,
+ $exception_fingerprint: `fingerprint-${issueKey}`,
+ $exception_issue_id: `issue-${issueKey}`,
+ },
+ }
+ })
),
})),
}))
@@ -603,8 +609,8 @@ describe('ErrorTrackingConsumer', () => {
expect(producedCount()).toBe(5)
- // foo with different `value` → same key as foo's burst (value is
- // dropped from the hash when a stack exists) → bucket already empty,
+ // foo with different `value` → same Cymbal-resolved issue as foo's burst
+ // (the message doesn't affect issue grouping) → bucket already empty,
// request denied.
await send('foo', 'different')
await drainProduces()
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
index ead38ffc858d..c01576306eb4 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
@@ -34,13 +34,12 @@ import { CymbalClient } from './cymbal'
import {
ErrorTrackingOutputs,
ErrorTrackingPipelineOutput,
- PreCymbalRateLimiterInput,
+ PostCymbalRateLimiterInput,
createErrorTrackingPipeline,
runErrorTrackingPipeline,
} from './error-tracking-pipeline'
import { KeyedRateLimiterStepOptions } from './keyed-rate-limiter-step'
import { PerIssueGuardedRateLimiterService } from './per-issue-guarded-rate-limiter.service'
-import { preCymbalGroupKey } from './pre-cymbal-group-key'
/**
* Configuration values for ErrorTrackingConsumer.
@@ -295,7 +294,7 @@ export class ErrorTrackingConsumer {
preservePartitionLocality: this.config.preservePartitionLocality,
overflowRedirectService: this.overflowRedirectService,
overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,
- preCymbalRateLimiters: this.buildPreCymbalRateLimiterSpecs(),
+ postCymbalRateLimiters: this.buildPostCymbalRateLimiterSpecs(),
errorTrackingSettingsManager: this.rateLimiter ? this.deps.errorTrackingSettingsManager : undefined,
topHog: this.topHog,
})
@@ -304,7 +303,7 @@ export class ErrorTrackingConsumer {
}
/** Per-issue spec uses the guarded service; team-global spec uses the base service. */
- private buildPreCymbalRateLimiterSpecs(): KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[] {
+ private buildPostCymbalRateLimiterSpecs(): KeyedRateLimiterStepOptions<PostCymbalRateLimiterInput>[] {
if (!this.rateLimiter || !this.perIssueGuardedRateLimiter) {
return []
}
@@ -321,8 +320,10 @@ export class ErrorTrackingConsumer {
if (input.errorTrackingSettings?.perIssueRateLimitValue == null) {
return null
}
- const scopeKey = preCymbalGroupKey(input.event)
- return scopeKey ? `${input.team.id}:exceptions:issue:${scopeKey}` : null
+ const issueId = input.event.properties?.$exception_issue_id
+ return typeof issueId === 'string' && issueId
+ ? `${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.
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts
index 5407bb1685b0..dec16f454905 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts
@@ -91,14 +91,10 @@ export interface ErrorTrackingPipelineConfig {
/** Service for refreshing TTLs on overflow lane events. */
overflowLaneTTLRefreshService?: OverflowRedirectService
/**
- * Rate limiter step specs to apply pre-Cymbal. Each becomes its own batch step in
+ * Rate limiter step specs to apply post-Cymbal. Each becomes its own batch step in
* the pipeline, run in array order. Empty / undefined → no rate limiting.
- *
- * Pre-Cymbal placement saves symbolication cost on dropped events. If a future
- * limiter needs Cymbal-derived data (e.g. the proper exception fingerprint), add
- * a `postCymbalRateLimiters` slot rather than reorder this one.
*/
- preCymbalRateLimiters?: KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[]
+ postCymbalRateLimiters?: KeyedRateLimiterStepOptions<PostCymbalRateLimiterInput>[]
/**
* When provided, an error-tracking-settings load step runs before the rate limiter
* chain so per-team overrides can be read synchronously from the input.
@@ -109,17 +105,17 @@ export interface ErrorTrackingPipelineConfig {
}
/**
- * Shape consumed by pre-Cymbal rate limiter step specs. The pipeline guarantees these
- * fields are present at the insertion point (after team resolution, before Cymbal).
+ * Shape consumed by post-Cymbal rate limiter step specs. The pipeline guarantees these
+ * fields are present at the insertion point (after Cymbal, before enrichment).
*/
-export interface PreCymbalRateLimiterInput {
+export interface PostCymbalRateLimiterInput {
team: { id: number }
event: PluginEvent
errorTrackingSettings?: ErrorTrackingSettings | null
}
/**
- * Apply each rate limiter spec as its own pre-Cymbal batch step. The chain's TOutput
+ * Apply each rate limiter spec as its own post-Cymbal batch step. The chain's TOutput
* is wider than the spec's input type, but `KeyedRateLimiterStepOptions<T>` is
* contravariant in T, so a narrower spec assigns into the wider chain context.
*/
@@ -143,8 +139,8 @@ function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends stri
* 6. Apply cookieless processing - Rewrite distinct_id for cookieless events
* 7. Only-cookieless rate limit - Redirect cookieless rate-limited events to overflow
* using the hashed distinct_id from step 6
- * 8. Team-global rate limit - Drop events that exceed per-team caps (optional)
- * 9. Cymbal processing - Symbolicate, fingerprint, and link issues
+ * 8. Cymbal processing - Symbolicate, fingerprint, and link issues
+ * 9. Team-global rate limit - Drop events that exceed per-team caps (optional)
* 10. Person properties - Fetch person by distinct_id (read-only)
* 11. Hog transformations - Run team transformations (including GeoIP if enabled)
* 12. Prepare event - Convert to PreIngestionEvent format, track if person found
@@ -179,7 +175,7 @@ export function createErrorTrackingPipeline(
preservePartitionLocality,
overflowRedirectService,
overflowLaneTTLRefreshService,
- preCymbalRateLimiters,
+ postCymbalRateLimiters,
errorTrackingSettingsManager,
topHog,
} = config
@@ -257,29 +253,26 @@ export function createErrorTrackingPipeline(
overflowRedirectService
)
)
- // Pre-Cymbal team-global rate-limit chain. Drops events the team
- // has explicitly capped, so they never consume symbolication
- // budget. Empty / undefined → no-op.
- const afterRateLimit = applyKeyedRateLimiters(
- afterCookieless,
- preCymbalRateLimiters ?? []
- )
- const preCymbal = afterRateLimit
+ const preCymbal = afterCookieless
// Refresh TTLs for overflow lane events (keeps Redis flags alive)
.pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
+ const afterCymbal = preCymbal
+ // Process through Cymbal as a batch (before enrichment - Cymbal only
+ // needs raw exception data, not person/geoip/group data).
+ // Retry on transient failures (5xx, timeout, network errors).
+ // 3 retries keeps the worst-case batch time (3 × 45s timeout =
+ // 135s) well within the 180s liveness interval, and reduces
+ // amplification pressure on Cymbal during degradation.
+ .pipeBatchWithRetry(createCymbalProcessingStep(cymbalClient), {
+ tries: 3,
+ sleepMs: 100,
+ name: 'cymbal_processing',
+ })
+ // Post-Cymbal team-global rate-limit chain. Drops events the team
+ // has explicitly capped. Empty / undefined → no-op.
+ const afterRateLimit = applyKeyedRateLimiters(afterCymbal, postCymbalRateLimiters ?? [])
return (
- preCymbal
- // Process through Cymbal as a batch (before enrichment - Cymbal only
- // needs raw exception data, not person/geoip/group data).
- // Retry on transient failures (5xx, timeout, network errors).
- // 3 retries keeps the worst-case batch time (3 × 45s timeout =
- // 135s) well within the 180s liveness interval, and reduces
- // amplification pressure on Cymbal during degradation.
- .pipeBatchWithRetry(createCymbalProcessingStep(cymbalClient), {
- tries: 3,
- sleepMs: 100,
- name: 'cymbal_processing',
- })
+ afterRateLimit
// Enrich, prepare, create, and emit events
// Batch fetch person (read-only, no updates)
.pipeBatch(createFetchPersonBatchStep(personRepository))
diff --git a/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.test.ts b/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.test.ts
deleted file mode 100644
index 159a6231c82a..000000000000
--- a/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.test.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
-
-import { preCymbalGroupKey } from './pre-cymbal-group-key'
-
-const exceptionEvent = (exception: Record<string, unknown>) =>
- createTestPluginEvent({ properties: { $exception_list: [exception] } })
-
-describe('preCymbalGroupKey', () => {
- it('returns null when $exception_list is missing', () => {
- expect(preCymbalGroupKey(createTestPluginEvent())).toBeNull()
- })
-
- it('returns null when $exception_list is a non-array object with a numeric length', () => {
- const event = createTestPluginEvent({
- properties: { $exception_list: { length: 1 } as unknown as unknown[] },
- })
- expect(() => preCymbalGroupKey(event)).not.toThrow()
- expect(preCymbalGroupKey(event)).toBeNull()
- })
-
- it('does not throw when stacktrace.frames is a non-array object with a numeric length', () => {
- const event = createTestPluginEvent({
- properties: {
- $exception_list: [
- {
- type: 'TypeError',
- value: 'boom',
- stacktrace: { frames: { length: 1 } as unknown as unknown[] },
- },
- ],
- },
- })
- expect(() => preCymbalGroupKey(event)).not.toThrow()
- expect(preCymbalGroupKey(event)).toMatch(/^[0-9a-f]{16}$/)
- })
-
- it('returns null when there is no message and no frames', () => {
- expect(preCymbalGroupKey(exceptionEvent({ type: 'Error' }))).toBeNull()
- })
-
- it('returns a 16-char hex digest', () => {
- const key = preCymbalGroupKey(exceptionEvent({ type: 'Error', value: 'boom' }))
- expect(key).toMatch(/^[0-9a-f]{16}$/)
- })
-
- describe('message-only exceptions', () => {
- it('groups by type and value', () => {
- const a = preCymbalGroupKey(exceptionEvent({ type: 'TypeError', value: 'same' }))
- const b = preCymbalGroupKey(exceptionEvent({ type: 'TypeError', value: 'same' }))
- const c = preCymbalGroupKey(exceptionEvent({ type: 'TypeError', value: 'other' }))
-
- expect(a).toBe(b)
- expect(a).not.toBe(c)
- })
-
- it('does not collide when separator-like chars appear in type or value', () => {
- // A naive `${type}|${value}` join would hash both of these to "A|B|C".
- const typeShifted = preCymbalGroupKey(exceptionEvent({ type: 'A|B', value: 'C' }))
- const valueShifted = preCymbalGroupKey(exceptionEvent({ type: 'A', value: 'B|C' }))
- expect(typeShifted).not.toBe(valueShifted)
- })
- })
-
- describe('stack exceptions', () => {
- const stackEvent = (fn: string, value: string = 'msg') =>
- exceptionEvent({
- type: 'TypeError',
- value,
- stacktrace: {
- frames: [{ function: fn, filename: `${fn}.js`, lineno: 1 }],
- },
- })
-
- it('groups by stack and ignores message when frames exist', () => {
- const a = preCymbalGroupKey(stackEvent('foo'))
- const b = preCymbalGroupKey(stackEvent('foo', 'different'))
-
- expect(a).toBe(b)
- })
-
- it('separates different stacks', () => {
- expect(preCymbalGroupKey(stackEvent('foo'))).not.toBe(preCymbalGroupKey(stackEvent('bar')))
- })
-
- it('does not conflate adjacent empty fields across frame boundaries', () => {
- const split = preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: {
- frames: [
- { function: 'a', filename: 'bc' },
- { function: '', filename: '' },
- ],
- },
- })
- )
- const merged = preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: {
- frames: [{ function: 'a', filename: 'bc' }],
- },
- })
- )
-
- expect(split).not.toBe(merged)
- })
-
- it('uses abs_path, line, and column aliases', () => {
- const withAliases = preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: {
- frames: [{ function: 'fn', abs_path: '/app/x.js', line: 10, column: 2 }],
- },
- })
- )
- const withCanonical = preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: {
- frames: [{ function: 'fn', filename: '/app/x.js', lineno: 10, colno: 2 }],
- },
- })
- )
-
- expect(withAliases).toBe(withCanonical)
- })
-
- it('does not throw when a frame is null', () => {
- expect(() =>
- preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: { frames: [{ function: 'a' }, null] },
- })
- )
- ).not.toThrow()
- })
-
- it('treats an invalid frame as empty fields without conflating it with the next valid frame', () => {
- const withNull = preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: { frames: [null, { function: 'a' }] },
- })
- )
- const onlyValid = preCymbalGroupKey(
- exceptionEvent({
- type: 'Error',
- stacktrace: { frames: [{ function: 'a' }] },
- })
- )
- expect(withNull).not.toBe(onlyValid)
- })
-
- it('ignores extra frame properties', () => {
- const minimal = preCymbalGroupKey(stackEvent('fn'))
- const verbose = preCymbalGroupKey(
- exceptionEvent({
- type: 'TypeError',
- value: 'msg',
- stacktrace: {
- frames: [
- {
- function: 'fn',
- filename: 'fn.js',
- lineno: 1,
- context_line: 'const x = 1',
- vars: { x: 1 },
- },
- ],
- },
- })
- )
-
- expect(minimal).toBe(verbose)
- })
- })
-
- describe('chained exceptions', () => {
- const chainedEvent = (excs: unknown[]) => createTestPluginEvent({ properties: { $exception_list: excs } })
-
- it('separates chains that share a wrapper but have different root causes', () => {
- const sameCause = chainedEvent([
- { type: 'WrapperError', value: 'wrap' },
- { type: 'TypeError', value: 'cause-A' },
- ])
- const differentCause = chainedEvent([
- { type: 'WrapperError', value: 'wrap' },
- { type: 'TypeError', value: 'cause-B' },
- ])
-
- expect(preCymbalGroupKey(sameCause)).not.toBe(preCymbalGroupKey(differentCause))
- })
-
- it('groups chains whose every exception matches', () => {
- const make = () =>
- chainedEvent([
- { type: 'WrapperError', value: 'wrap' },
- { type: 'TypeError', value: 'cause' },
- ])
- expect(preCymbalGroupKey(make())).toBe(preCymbalGroupKey(make()))
- })
-
- it('skips null entries in the chain without throwing', () => {
- const key = preCymbalGroupKey(chainedEvent([{ type: 'TypeError', value: 'real' }, null]))
- expect(key).toMatch(/^[0-9a-f]{16}$/)
- })
- })
-})
diff --git a/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.ts b/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.ts
deleted file mode 100644
index ccde0fa2f07b..000000000000
--- a/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { createHash } from 'crypto'
-
-import { PluginEvent } from '~/plugin-scaffold'
-
-const PRE_CYMBAL_FRAME_FIELD_SEP = '\0'
-const PRE_CYMBAL_FRAME_SEP = '\x1e'
-const PRE_CYMBAL_EXC_SEP = '\x1d'
-
-function updatePreCymbalFrameHash(hash: ReturnType<typeof createHash>, frame: Record<string, unknown>): void {
- hash.update(String(frame.function ?? ''))
- hash.update(PRE_CYMBAL_FRAME_FIELD_SEP)
- hash.update(String(frame.filename ?? frame.abs_path ?? ''))
- hash.update(PRE_CYMBAL_FRAME_FIELD_SEP)
- hash.update(String(frame.lineno ?? frame.line ?? ''))
- hash.update(PRE_CYMBAL_FRAME_FIELD_SEP)
- hash.update(String(frame.colno ?? frame.column ?? ''))
- hash.update(PRE_CYMBAL_FRAME_FIELD_SEP)
-}
-
-export function preCymbalGroupKey(event: PluginEvent): string | null {
- const excList = event.properties?.$exception_list
- if (!Array.isArray(excList) || excList.length === 0) {
- return null
- }
-
- const hash = createHash('sha1')
- let hasContent = false
-
- for (const exc of excList) {
- if (!exc || typeof exc !== 'object') {
- continue
- }
- const rawFrames = exc.stacktrace?.frames
- const frames = Array.isArray(rawFrames) ? rawFrames : null
- const value = exc.value ?? ''
- if (!frames?.length && !value) {
- continue
- }
-
- hasContent = true
- hash.update(String(exc.type ?? ''))
- hash.update(PRE_CYMBAL_FRAME_FIELD_SEP)
-
- if (frames?.length) {
- for (const frame of frames) {
- const safeFrame = frame && typeof frame === 'object' ? (frame as Record<string, unknown>) : {}
- updatePreCymbalFrameHash(hash, safeFrame)
- hash.update(PRE_CYMBAL_FRAME_SEP)
- }
- } else {
- hash.update(String(value))
- }
- hash.update(PRE_CYMBAL_EXC_SEP)
- }
-
- if (!hasContent) {
- return null
- }
- return hash.digest('hex').slice(0, 16)
-}