: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 per-issue pre-cymbal rate limit (#59611)
Aleksander Błaszkiewicz3c3d43be7b6c
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.tsindex 201037ac7a5e..afdf8daadd31 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts@@ -7,6 +7,7 @@ import { KafkaConsumer } from '~/kafka/consumer/consumer-v1'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub, PipelineEvent, Team } from '~/types'import { closeHub, createHub } from '~/utils/db/hub'+import { PostgresUse } from '~/utils/db/postgres'import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'import { parseJSON } from '~/utils/json-parse'import { UUIDT } from '~/utils/utils'@@ -427,4 +428,218 @@ describe('ErrorTrackingConsumer', () => {expect(producedMessages[0].value.person_mode).toBe('full')})})++ describe('rate limiting', () => {+ const upsertSettings = async (args: {+ projectRateLimit?: number | null+ perIssueRateLimit?: number | null+ }): Promise<void> => {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_errortrackingsettings+ (team_id, project_rate_limit_value, project_rate_limit_bucket_size_minutes,+ per_issue_rate_limit_value, per_issue_rate_limit_bucket_size_minutes)+ VALUES ($1, $2, 60, $3, 60)+ ON CONFLICT (team_id) DO UPDATE SET+ project_rate_limit_value = EXCLUDED.project_rate_limit_value,+ project_rate_limit_bucket_size_minutes = EXCLUDED.project_rate_limit_bucket_size_minutes,+ per_issue_rate_limit_value = EXCLUDED.per_issue_rate_limit_value,+ per_issue_rate_limit_bucket_size_minutes = EXCLUDED.per_issue_rate_limit_bucket_size_minutes`,+ [team.id, args.projectRateLimit ?? null, args.perIssueRateLimit ?? null],+ 'test-upsert-error-tracking-settings'+ )+ }++ const enableRateLimiter = async (): Promise<void> => {+ await consumer.stop()+ hub.ERROR_TRACKING_RATE_LIMITER_ENABLED = true+ hub.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE = false+ consumer = await createConsumer(hub)++ await consumer['rateLimiterRedis']!.useClient({ name: 'test-flush' }, async (client) => {+ const keys = await client.keys(+ `@posthog-test/error-tracking-rate-limiter/tokens/${team.id}:exceptions:*`+ )+ if (keys.length > 0) {+ await client.del(...keys)+ }+ })+ }++ const exceptionEvent = (fn: string, value: string = 'msg'): PipelineEvent =>+ createEvent({+ properties: {+ $exception_list: [+ {+ type: 'TypeError',+ value,+ stacktrace: { frames: [{ function: fn, filename: `${fn}.js`, lineno: 1 }] },+ mechanism: { type: 'generic', handled: true },+ },+ ],+ },+ })++ const drainProduces = () => consumer['promiseScheduler'].waitForAll()++ const producedCount = (): number =>+ mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test').length++ // The Lua script reads time via `Date.now()`. `beforeEach` mocks it to a+ // fixed value; bumping the same spy advances "now" so the bucket refills.+ const advanceTime = (seconds: number): void => {+ jest.spyOn(Date, 'now').mockReturnValue(Date.now() + seconds * 1000)+ }++ describe('project rate limit', () => {+ it('lets early batches through and partially passes through once the budget is exhausted', async () => {+ await upsertSettings({ projectRateLimit: 15 })+ await enableRateLimiter()++ const sendBatch = (size: number) => {+ const events = Array.from({ length: size }, (_, i) => exceptionEvent(`fn-${i}`))+ return consumer.handleKafkaBatch(createKafkaMessages(events))+ }++ // tokens 15 → 5 (10 allowed)+ await sendBatch(10)+ // budget 5, batch of 30 → partial pass-through: 5 allowed, 25 dropped.+ await sendBatch(30)+ // bucket drained — entire batch dropped.+ await sendBatch(20)+ await drainProduces()++ expect(producedCount()).toBe(15)+ })++ it('refills tokens over time once the bucket window has elapsed', async () => {+ await upsertSettings({ projectRateLimit: 4 })+ await enableRateLimiter()++ const send = (fn: string) => consumer.handleKafkaBatch(createKafkaMessages([exceptionEvent(fn)]))++ // Team-keyed bucket drains regardless of signature.+ // tokens 4 → 3+ await send('foo')+ // 3 → 2+ await send('bar')+ // 2 → 1+ await send('baz')+ // 1 → 0 — last token spent, request served+ await send('qux')+ await drainProduces()+ expect(producedCount()).toBe(4)++ // Advance one full bucket window (60 min); refillRate = 4 / 3600s → bucket back to full.+ advanceTime(60 * 60)++ // tokens 4 → 3+ await send('foo')+ await drainProduces()+ expect(producedCount()).toBe(5)+ })+ })++ describe('per-issue rate limit', () => {+ it('partially passes through a batch that overflows multiple per-issue buckets', async () => {+ await upsertSettings({ perIssueRateLimit: 3 })+ await enableRateLimiter()++ // Single batch carrying two interleaved signatures, each with its own+ // bucket of 3. Per-input fan-out should allow 3 from each and drop the+ // overflow within each key group independently.+ const events = [+ ...Array.from({ length: 12 }, () => exceptionEvent('foo')),+ ...Array.from({ length: 12 }, () => exceptionEvent('bar')),+ ]+ await consumer.handleKafkaBatch(createKafkaMessages(events))+ await drainProduces()++ // 3 allowed per signature × 2 signatures = 6.+ expect(producedCount()).toBe(6)+ })++ it('applies independently to each stack signature', async () => {+ await upsertSettings({ perIssueRateLimit: 4 })+ await enableRateLimiter()++ const send = (fn: string) => consumer.handleKafkaBatch(createKafkaMessages([exceptionEvent(fn)]))++ // issue A: tokens 4 → 3+ await send('A')+ // 3 → 2+ await send('A')+ // 2 → 1+ await send('A')+ // 1 → 0 — last token spent, request served+ await send('A')+ // bucket empty — next A is dropped+ await send('A')++ expect(producedCount()).toBe(4)++ // issue B has its own fresh bucket: 4 → 3+ await send('B')+ await drainProduces()++ expect(producedCount()).toBe(5) // 4 from A + 1 from B+ })++ it('groups by stack and ignores message interpolation', async () => {+ await upsertSettings({ perIssueRateLimit: 4 })+ await enableRateLimiter()++ const send = (fn: string, value: string = 'msg') =>+ consumer.handleKafkaBatch(createKafkaMessages([exceptionEvent(fn, value)]))++ // foo: tokens 4 → 3+ await send('foo')+ // 3 → 2+ await send('foo')+ // 2 → 1+ await send('foo')+ // 1 → 0 — last token spent, request served+ await send('foo')++ // bar has its own bucket: 4 → 3+ await send('bar')++ 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,+ // request denied.+ await send('foo', 'different')+ await drainProduces()++ expect(producedCount()).toBe(5)+ })++ it('refills tokens over time once the bucket window has elapsed', async () => {+ await upsertSettings({ perIssueRateLimit: 4 })+ await enableRateLimiter()++ const send = (fn: string) => consumer.handleKafkaBatch(createKafkaMessages([exceptionEvent(fn)]))++ // tokens 4 → 3+ await send('foo')+ // 3 → 2+ await send('foo')+ // 2 → 1+ await send('foo')+ // 1 → 0 — last token spent, request served+ await send('foo')+ await drainProduces()+ expect(producedCount()).toBe(4)++ // Advance one full bucket window (60 min); refillRate = 4 / 3600s → bucket back to full.+ advanceTime(60 * 60)++ // tokens 4 → 3+ await send('foo')+ await drainProduces()+ expect(producedCount()).toBe(5)+ })+ })+ })})diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.tsindex cc329ea6f418..cec67bd45ff9 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts@@ -35,6 +35,7 @@ import {runErrorTrackingPipeline,} from './error-tracking-pipeline'import { KeyedRateLimiterStepOptions } from './keyed-rate-limiter-step'+import { preCymbalGroupKey } from './pre-cymbal-group-key'/*** Configuration values for ErrorTrackingConsumer.@@ -286,6 +287,33 @@ export class ErrorTrackingConsumer {}const specs: KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[] = [+ // Per-issue cap runs before the team-global cap so a runaway issue+ // gets dropped against its own bucket instead of draining the+ // team-global budget on its way out.+ {+ rateLimiter: this.rateLimiter,+ appMetricsAggregator: this.rateLimiterAppMetricsAggregator,+ appSource: 'exceptions',+ getKey: (input) => {+ if (input.errorTrackingSettings?.perIssueRateLimitValue == null) {+ return null+ }+ const sig = preCymbalGroupKey(input.event)+ return sig ? `${input.team.id}:exceptions:issue:${sig}` : null+ },+ getTeamId: (input) => input.team.id,+ reportingMode: this.config.rateLimiterReportingMode,+ dropReason: 'rate_limited:per_issue',+ getBucketConfig: (input) => {+ const settings = input.errorTrackingSettings!+ const value = settings.perIssueRateLimitValue!+ const minutes = settings.perIssueRateLimitBucketSizeMinutes ?? 60+ return {+ bucketSize: value,+ refillRate: value / (minutes * 60),+ }+ },+ },// Team-global cap: every $exception event for a team consumes one token// from a per-team bucket.{@@ -314,27 +342,6 @@ export class ErrorTrackingConsumer {}},},- // TODO: Per-exception-hash limit using a coarse pre-Cymbal fingerprint- // (Cymbal's proper fingerprint is post-symbolication, so we accept a- // weaker-but-cheaper bucket here). Wiring would look like:- // {- // rateLimiter: this.rateLimiter,- // appMetricsAggregator: this.rateLimiterAppMetricsAggregator,- // appSource: 'exceptions',- // getKey: (input) => {- // const first = input.event.properties?.$exception_list?.[0]- // if (!first?.type && !first?.value) return null- // const hash = createHash('sha1')- // .update(`${first?.type ?? ''}|${first?.value ?? ''}`)- // .digest('hex')- // .slice(0, 16)- // return `${input.team.id}:exceptions:hash:${hash}`- // },- // getTeamId: (input) => input.team.id,- // reportingMode: this.config.rateLimiterReportingMode,- // dropReason: 'rate_limited:per_hash',- // // getBucketConfig: ... (see TODO above)- // },]return specsdiff --git a/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.ts b/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.tsindex 9d242fa1311f..e98d1c0e1cfc 100644--- a/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.ts+++ b/nodejs/src/ingestion/error-tracking/load-error-tracking-settings-step.test.ts@@ -1,14 +1,11 @@-import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'+import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-manager'import { isOkResult } from '../pipelines/results'import { createLoadErrorTrackingSettingsStep } from './load-error-tracking-settings-step'describe('createLoadErrorTrackingSettingsStep', () => {const buildManager = (- settingsByTeam: Record<- string,- { projectRateLimitValue: number | null; projectRateLimitBucketSizeMinutes: number | null } | null- >+ settingsByTeam: Record<string, ErrorTrackingSettings | null>): jest.Mocked<Pick<ErrorTrackingSettingsManager, 'getSettings'>> => ({getSettings: jest.fn((teamId: number) => Promise.resolve(settingsByTeam[String(teamId)] ?? null)),})@@ -27,7 +24,12 @@ describe('createLoadErrorTrackingSettingsStep', () => {it('attaches the loaded settings', async () => {const manager = buildManager({- '1': { projectRateLimitValue: 100, projectRateLimitBucketSizeMinutes: 5 },+ '1': {+ projectRateLimitValue: 100,+ projectRateLimitBucketSizeMinutes: 5,+ perIssueRateLimitValue: 20,+ perIssueRateLimitBucketSizeMinutes: 15,+ },})const step = createLoadErrorTrackingSettingsStep(manager as unknown as ErrorTrackingSettingsManager)@@ -38,6 +40,8 @@ describe('createLoadErrorTrackingSettingsStep', () => {expect(result.value.errorTrackingSettings).toEqual({projectRateLimitValue: 100,projectRateLimitBucketSizeMinutes: 5,+ perIssueRateLimitValue: 20,+ perIssueRateLimitBucketSizeMinutes: 15,})}})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.tsnew file mode 100644index 000000000000..159a6231c82a--- /dev/null+++ b/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.test.ts@@ -0,0 +1,211 @@+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.tsnew file mode 100644index 000000000000..ccde0fa2f07b--- /dev/null+++ b/nodejs/src/ingestion/error-tracking/pre-cymbal-group-key.ts@@ -0,0 +1,60 @@+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)+}diff --git a/nodejs/src/ingestion/error-tracking/rate-limiter-e2e.test.ts b/nodejs/src/ingestion/error-tracking/rate-limiter-e2e.test.tsdeleted file mode 100644index 78fd2c1bec50..000000000000--- a/nodejs/src/ingestion/error-tracking/rate-limiter-e2e.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'-import { KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'-import { Hub } from '~/types'-import { closeHub, createHub } from '~/utils/db/hub'--import { deleteKeysWithPrefix } from '../../cdp/_tests/redis'--const mockNow: jest.SpyInstance = jest.spyOn(Date, 'now')--// E2E for the ET team-global rate limit: 100 events per 15 minutes, sustained 10 ev/sec.-// Real Redis, real V3 lua (post floor-drain fix), real per-input fan-out — proves that:-// - the initial burst of 100 passes,-// - sustained overload drains the bucket to ~0 and starves new events,-// - refill accumulates cross-batch (V3 lua's floor-drain preserves the fractional remainder),-// - over the 15-minute window we admit roughly bucketSize burst + bucketSize refill (~2x bucketSize).-describe('error tracking — sustained traffic e2e', () => {- jest.retryTimes(2)-- let now: number- let hub: Hub- let redis: RedisV2-- const advanceTime = (ms: number) => {- now += ms- mockNow.mockReturnValue(now)- }-- beforeEach(async () => {- hub = await createHub()- now = 1720000000000- mockNow.mockReturnValue(now)- redis = createRedisV2PoolFromConfig({- connection: hub.CDP_REDIS_HOST- ? {- url: hub.CDP_REDIS_HOST,- options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },- }- : { url: hub.REDIS_URL },- poolMinSize: hub.REDIS_POOL_MIN_SIZE,- poolMaxSize: hub.REDIS_POOL_MAX_SIZE,- })- })-- afterEach(async () => {- await closeHub(hub)- jest.clearAllMocks()- })-- it('100 per 15min: bursts 100 immediately, then admits ~bucketSize more across the window', async () => {- const bucketSize = 100- const minutes = 15- const refillRate = bucketSize / (minutes * 60) // ~0.111 / sec- const limiter = new KeyedRateLimiterService(- { name: 'et-e2e-sustained', bucketSize, refillRate, ttlSeconds: 60 * 60 },- redis- )- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())-- // Sustained 10 ev/sec as one batch of 10 per second — same fan-out as 10- // singleton calls but 10× fewer Redis round-trips.- const eventsPerBatch = 10- const totalSeconds = minutes * 60- const batchIntervalMs = 1000-- let totalAllowed = 0- let firstBurstAllowed = 0- let seenFirstStarve = false-- for (let s = 0; s < totalSeconds; s++) {- const res = await limiter.rateLimitGrouped(- Array.from({ length: eventsPerBatch }, () => ({ id: 'team-1', cost: 1 }))- )- const allowed = res.filter(([, r]) => !r.isRateLimited).length- totalAllowed += allowed- // The first ten seconds carry the burst (bucketSize=100 / eventsPerBatch=10).- if (s < bucketSize / eventsPerBatch) {- firstBurstAllowed += allowed- }- if (s >= bucketSize / eventsPerBatch && allowed === 0 && !seenFirstStarve) {- seenFirstStarve = true- }- advanceTime(batchIntervalMs)- }-- // The first bucketSize events all pass (initial burst).- expect(firstBurstAllowed).toBe(bucketSize)- // After the burst, the bucket drains and we hit the starvation window.- expect(seenFirstStarve).toBe(true)- // Over 15 minutes: bucketSize burst + bucketSize refill = 2 × bucketSize total.- // Allow ±5 slack for fractional boundary edge cases.- expect(totalAllowed).toBeGreaterThanOrEqual(2 * bucketSize - 5)- expect(totalAllowed).toBeLessThanOrEqual(2 * bucketSize + 5)- }, 30000)-})diff --git a/nodejs/src/utils/error-tracking-settings-manager.test.ts b/nodejs/src/utils/error-tracking-settings-manager.test.tsindex 31c152eb0380..47d0027d2b96 100644--- a/nodejs/src/utils/error-tracking-settings-manager.test.ts+++ b/nodejs/src/utils/error-tracking-settings-manager.test.ts@@ -35,18 +35,28 @@ describe('ErrorTrackingSettingsManager', () => {const upsertSettings = async (targetTeamId: number,projectRateLimitValue: number | null,- projectRateLimitBucketSizeMinutes: number | null+ projectRateLimitBucketSizeMinutes: number | null,+ perIssueRateLimitValue: number | null = null,+ perIssueRateLimitBucketSizeMinutes: number | null = null): Promise<void> => {await postgres.query(PostgresUse.COMMON_WRITE,`INSERT INTO posthog_errortrackingsettings(team_id, project_rate_limit_value, project_rate_limit_bucket_size_minutes,per_issue_rate_limit_value, per_issue_rate_limit_bucket_size_minutes)- VALUES ($1, $2, $3, NULL, NULL)+ VALUES ($1, $2, $3, $4, $5)ON CONFLICT (team_id) DO UPDATE SETproject_rate_limit_value = EXCLUDED.project_rate_limit_value,- project_rate_limit_bucket_size_minutes = EXCLUDED.project_rate_limit_bucket_size_minutes`,- [targetTeamId, projectRateLimitValue, projectRateLimitBucketSizeMinutes],+ project_rate_limit_bucket_size_minutes = EXCLUDED.project_rate_limit_bucket_size_minutes,+ per_issue_rate_limit_value = EXCLUDED.per_issue_rate_limit_value,+ per_issue_rate_limit_bucket_size_minutes = EXCLUDED.per_issue_rate_limit_bucket_size_minutes`,+ [+ targetTeamId,+ projectRateLimitValue,+ projectRateLimitBucketSizeMinutes,+ perIssueRateLimitValue,+ perIssueRateLimitBucketSizeMinutes,+ ],'upsert-test-error-tracking-settings')}@@ -57,12 +67,14 @@ describe('ErrorTrackingSettingsManager', () => {})it('returns settings when the team has a row', async () => {- await upsertSettings(teamId, 100, 5)+ await upsertSettings(teamId, 100, 5, 20, 15)const result = await manager.getSettings(teamId)expect(result).toEqual({projectRateLimitValue: 100,projectRateLimitBucketSizeMinutes: 5,+ perIssueRateLimitValue: 20,+ perIssueRateLimitBucketSizeMinutes: 15,})})@@ -73,6 +85,8 @@ describe('ErrorTrackingSettingsManager', () => {expect(result).toEqual({projectRateLimitValue: null,projectRateLimitBucketSizeMinutes: null,+ perIssueRateLimitValue: null,+ perIssueRateLimitBucketSizeMinutes: null,})})diff --git a/nodejs/src/utils/error-tracking-settings-manager.ts b/nodejs/src/utils/error-tracking-settings-manager.tsindex 99115cff2bfa..5a0a87e6472f 100644--- a/nodejs/src/utils/error-tracking-settings-manager.ts+++ b/nodejs/src/utils/error-tracking-settings-manager.ts@@ -4,12 +4,16 @@ import { LazyLoader } from './lazy-loader'export interface ErrorTrackingSettings {projectRateLimitValue: number | nullprojectRateLimitBucketSizeMinutes: number | null+ perIssueRateLimitValue: number | null+ perIssueRateLimitBucketSizeMinutes: number | null}interface RawSettingsRow {team_id: numberproject_rate_limit_value: number | nullproject_rate_limit_bucket_size_minutes: number | null+ per_issue_rate_limit_value: number | null+ per_issue_rate_limit_bucket_size_minutes: number | null}export class ErrorTrackingSettingsManager {@@ -47,7 +51,9 @@ export class ErrorTrackingSettingsManager {`SELECTteam_id,project_rate_limit_value,- project_rate_limit_bucket_size_minutes+ project_rate_limit_bucket_size_minutes,+ per_issue_rate_limit_value,+ per_issue_rate_limit_bucket_size_minutesFROM posthog_errortrackingsettingsWHERE team_id = ANY($1)`,[numericTeamIds],@@ -58,6 +64,8 @@ export class ErrorTrackingSettingsManager {result[String(row.team_id)] = {projectRateLimitValue: row.project_rate_limit_value,projectRateLimitBucketSizeMinutes: row.project_rate_limit_bucket_size_minutes,+ perIssueRateLimitValue: row.per_issue_rate_limit_value,+ perIssueRateLimitBucketSizeMinutes: row.per_issue_rate_limit_bucket_size_minutes,}}