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.

chore(error-tracking): remove nodejs rate limiting superseded by cymbal (#72163)

Aleksander Błaszkiewicz002c8006cfd0
diff --git a/nodejs/src/common/redis/redis-token-bucket-guarded.lua.ts b/nodejs/src/common/redis/redis-token-bucket-guarded.lua.ts
deleted file mode 100644
index ba7af287ece6..000000000000
--- a/nodejs/src/common/redis/redis-token-bucket-guarded.lua.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { Redis } from 'ioredis'
-
-// v3 token-bucket + per-team new-key counter + per-team cooldown flag.
-// Caps how many unique bucket keys a team can mint per window.
-//
-// KEYS: [1] cooldown_flag, [2] counter (per-window), [3] bucket
-// ARGV: now, cost, poolMax, fillRate, bucketExpiry, threshold, windowTtl, cooldownTtl
-// Returns: { tokensBefore, tokensAfter, statusCode } where statusCode is 0=allowed | 1=limited | 2=tripped | 3=cooldown.
-// On tripped/cooldown the bucket is not written.
-const LUA_TOKEN_BUCKET_GUARDED = `
-local cooldown_key = KEYS[1]
-local counter_key = KEYS[2]
-local key = KEYS[3]
-local now = tonumber(ARGV[1])
-local cost = tonumber(ARGV[2])
-local poolMax = tonumber(ARGV[3])
-local fillRate = tonumber(ARGV[4])
-local expiry = tonumber(ARGV[5])
-local threshold = tonumber(ARGV[6])
-local window_ttl = tonumber(ARGV[7])
-local cooldown_ttl = tonumber(ARGV[8])
-
-if redis.call('exists', cooldown_key) == 1 then
- return {0, 0, 3}
-end
-
-local is_new = (redis.call('exists', key) == 0)
-if is_new then
- local count = redis.call('incr', counter_key)
- if count == 1 then
- redis.call('expire', counter_key, window_ttl)
- end
- if count > threshold then
- redis.call('set', cooldown_key, '1', 'ex', cooldown_ttl)
- return {0, 0, 2}
- end
-end
-
-local existing = redis.call('hmget', key, 'ts', 'pool')
-local rawBefore = existing[1]
-local rawPool = existing[2]
-
-local tokensBefore
-local before
-if rawBefore == false then
- before = false
- tokensBefore = poolMax
-else
- before = tonumber(rawBefore)
- local timeDiffSeconds = now - before
- if timeDiffSeconds < 0 then
- timeDiffSeconds = 0
- end
- local currentTokens
- if rawPool == false then
- currentTokens = poolMax
- else
- currentTokens = tonumber(rawPool)
- end
- tokensBefore = currentTokens + (timeDiffSeconds * fillRate)
-end
-
-local tokensAfter
-local poolToStore
-if tokensBefore - cost >= 0 then
- tokensAfter = math.min(tokensBefore - cost, poolMax)
- poolToStore = tokensAfter
-else
- tokensAfter = -1
- local available = math.max(0, tokensBefore)
- poolToStore = math.min(tokensBefore - math.floor(available), poolMax)
-end
-
-local tsToWrite
-if before ~= false and now < before then
- tsToWrite = before
-else
- tsToWrite = now
-end
-
-redis.call('hset', key, 'ts', tsToWrite, 'pool', poolToStore)
-
-if before == false or redis.call('pttl', key) < (expiry * 500) then
- redis.call('expire', key, expiry * 2)
-end
-
-local status_code
-if tokensAfter == -1 then
- status_code = 1
-else
- status_code = 0
-end
-
-return {tokensBefore, tokensAfter, status_code}
-`
-
-export const defineLuaTokenBucketGuarded = (client: Redis): void => {
- client.defineCommand('checkGuardedRateLimit', {
- numberOfKeys: 3,
- lua: LUA_TOKEN_BUCKET_GUARDED,
- })
-}
diff --git a/nodejs/src/common/redis/redis-v2.ts b/nodejs/src/common/redis/redis-v2.ts
index 7cec6cb22379..4e4f7e91e4c0 100644
--- a/nodejs/src/common/redis/redis-v2.ts
+++ b/nodejs/src/common/redis/redis-v2.ts
@@ -6,33 +6,18 @@ import { timeoutGuard } from '~/common/utils/db/utils'
import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
-import { defineLuaTokenBucketGuarded } from './redis-token-bucket-guarded.lua'
import { defineLuaTokenBucketV2 } from './redis-token-bucket-v2.lua'
import { defineLuaTokenBucketV3 } from './redis-token-bucket-v3.lua'
-type WithCheckRateLimit<TV2, TV3, TGuarded> = {
+type WithCheckRateLimit<TV2, TV3> = {
checkRateLimitV2: (key: string, now: number, cost: number, poolMax: number, fillRate: number, expiry: number) => TV2
checkRateLimitV3: (key: string, now: number, cost: number, poolMax: number, fillRate: number, expiry: number) => TV3
- checkGuardedRateLimit: (
- cooldownKey: string,
- counterKey: string,
- bucketKey: string,
- now: number,
- cost: number,
- poolMax: number,
- fillRate: number,
- expiry: number,
- threshold: number,
- windowTtl: number,
- cooldownTtl: number
- ) => TGuarded
}
-export type RedisClientPipeline = Pipeline &
- WithCheckRateLimit<[number, number], [number, number], [number, number, number]>
+export type RedisClientPipeline = Pipeline & WithCheckRateLimit<[number, number], [number, number]>
export type RedisClient = Omit<Redis, 'pipeline'> &
- WithCheckRateLimit<Promise<[number, number]>, Promise<[number, number]>, Promise<[number, number, number]>> & {
+ WithCheckRateLimit<Promise<[number, number]>, Promise<[number, number]>> & {
pipeline: () => RedisClientPipeline
}
@@ -58,7 +43,6 @@ export const createRedisV2PoolFromConfig = (config: RedisPoolConfig): RedisV2 =>
defineLuaTokenBucketV2(client)
defineLuaTokenBucketV3(client)
- defineLuaTokenBucketGuarded(client)
return client as RedisClient
},
diff --git a/nodejs/src/common/utils/error-tracking-settings-manager.test.ts b/nodejs/src/common/utils/error-tracking-settings-manager.test.ts
deleted file mode 100644
index 0f925ef8d780..000000000000
--- a/nodejs/src/common/utils/error-tracking-settings-manager.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, Team } from '~/types'
-
-import { defaultConfig } from '../config/config'
-import { closeHub, createHub } from './db/hub'
-import { PostgresRouter, PostgresUse } from './db/postgres'
-import { ErrorTrackingSettingsManager } from './error-tracking-settings-manager'
-
-describe('ErrorTrackingSettingsManager', () => {
- let hub: Hub
- let manager: ErrorTrackingSettingsManager
- let postgres: PostgresRouter
- let teamId: Team['id']
- let fetchSpy: jest.SpyInstance
-
- beforeEach(async () => {
- const now = Date.now()
- jest.spyOn(Date, 'now').mockImplementation(() => now)
-
- await resetTestDatabase()
- hub = await createHub()
-
- postgres = new PostgresRouter(defaultConfig)
- manager = new ErrorTrackingSettingsManager(postgres)
- const team = await getFirstTeam(hub.postgres)
- teamId = team.id
- fetchSpy = jest.spyOn(manager as any, 'fetchSettings')
- })
-
- afterEach(async () => {
- jest.restoreAllMocks()
- await postgres.end()
- await closeHub(hub)
- })
-
- const upsertSettings = async (
- targetTeamId: number,
- projectRateLimitValue: 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, $4, $5)
- 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`,
- [
- targetTeamId,
- projectRateLimitValue,
- projectRateLimitBucketSizeMinutes,
- perIssueRateLimitValue,
- perIssueRateLimitBucketSizeMinutes,
- ],
- 'upsert-test-error-tracking-settings'
- )
- }
-
- it('returns null when the team has no row', async () => {
- const result = await manager.getSettings(teamId)
- expect(result).toBeNull()
- })
-
- it('returns settings when the team has a row', async () => {
- await upsertSettings(teamId, 100, 5, 20, 15)
-
- const result = await manager.getSettings(teamId)
- expect(result).toEqual({
- projectRateLimitValue: 100,
- projectRateLimitBucketSizeMinutes: 5,
- perIssueRateLimitValue: 20,
- perIssueRateLimitBucketSizeMinutes: 15,
- })
- })
-
- it('returns null fields when row exists but values are unset', async () => {
- await upsertSettings(teamId, null, null)
-
- const result = await manager.getSettings(teamId)
- expect(result).toEqual({
- projectRateLimitValue: null,
- projectRateLimitBucketSizeMinutes: null,
- perIssueRateLimitValue: null,
- perIssueRateLimitBucketSizeMinutes: null,
- })
- })
-
- it('caches results across calls within the refresh window', async () => {
- await upsertSettings(teamId, 50, 15)
-
- await manager.getSettings(teamId)
- await manager.getSettings(teamId)
- await manager.getSettings(teamId)
-
- expect(fetchSpy).toHaveBeenCalledTimes(1)
- })
-
- it('coalesces concurrent lookups into a single fetch', async () => {
- await upsertSettings(teamId, 100, 5)
-
- await Promise.all([manager.getSettings(teamId), manager.getSettings(teamId), manager.getSettings(teamId)])
-
- expect(fetchSpy).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/nodejs/src/common/utils/error-tracking-settings-manager.ts b/nodejs/src/common/utils/error-tracking-settings-manager.ts
deleted file mode 100644
index 5a0a87e6472f..000000000000
--- a/nodejs/src/common/utils/error-tracking-settings-manager.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { PostgresRouter, PostgresUse } from './db/postgres'
-import { LazyLoader } from './lazy-loader'
-
-export interface ErrorTrackingSettings {
- projectRateLimitValue: number | null
- projectRateLimitBucketSizeMinutes: number | null
- perIssueRateLimitValue: number | null
- perIssueRateLimitBucketSizeMinutes: number | null
-}
-
-interface RawSettingsRow {
- team_id: number
- project_rate_limit_value: number | null
- project_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 {
- private lazyLoader: LazyLoader<ErrorTrackingSettings>
-
- constructor(private postgres: PostgresRouter) {
- this.lazyLoader = new LazyLoader({
- name: 'ErrorTrackingSettingsManager',
- refreshAgeMs: 2 * 60 * 1000,
- refreshJitterMs: 30 * 1000,
- loader: async (teamIds: string[]) => {
- return await this.fetchSettings(teamIds)
- },
- })
- }
-
- public async getSettings(teamId: number): Promise<ErrorTrackingSettings | null> {
- return await this.lazyLoader.get(String(teamId))
- }
-
- private async fetchSettings(teamIds: string[]): Promise<Record<string, ErrorTrackingSettings | null>> {
- const numericTeamIds = teamIds.map(Number).filter((id) => !isNaN(id) && id > 0)
-
- const result: Record<string, ErrorTrackingSettings | null> = {}
- for (const id of teamIds) {
- result[id] = null
- }
-
- if (numericTeamIds.length === 0) {
- return result
- }
-
- const queryResult = await this.postgres.query<RawSettingsRow>(
- PostgresUse.COMMON_READ,
- `SELECT
- team_id,
- project_rate_limit_value,
- project_rate_limit_bucket_size_minutes,
- per_issue_rate_limit_value,
- per_issue_rate_limit_bucket_size_minutes
- FROM posthog_errortrackingsettings
- WHERE team_id = ANY($1)`,
- [numericTeamIds],
- 'fetch-error-tracking-settings'
- )
-
- for (const row of queryResult.rows) {
- 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,
- }
- }
-
- return result
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/config.ts b/nodejs/src/ingestion/pipelines/errortracking/config.ts
index 484935b238bb..b4f6cd90e0ed 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/config.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/config.ts
@@ -47,27 +47,6 @@ export type ErrorTrackingConsumerConfig = {
* split large batches before they hit Cymbal's body limit. */
ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES: number
- /** Master kill-switch for the keyed rate limiter. When false, no Redis pool
- * is created and the pipeline step is a no-op. */
- ERROR_TRACKING_RATE_LIMITER_ENABLED: boolean
- /** When true, decisions are computed and tracked but never enforced. Lets
- * us validate thresholds + Redis path before flipping to enforce. */
- ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE: boolean
- /** Dedicated Redis host. If empty, falls back to REDIS_URL. */
- ERROR_TRACKING_RATE_LIMITER_REDIS_HOST: string
- ERROR_TRACKING_RATE_LIMITER_REDIS_PORT: number
- ERROR_TRACKING_RATE_LIMITER_REDIS_TLS: boolean
- /** TTL in seconds for the Redis bucket key. */
- ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS: number
-
- /** Max new per-issue bucket keys a single team can create per window before
- * cooldown engages and per-issue limiting is bypassed for that team. */
- ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD: number
- /** Length of the new-key counter window (seconds). */
- ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS: number
- /** Cooldown duration once a team trips the guard (seconds). */
- ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS: number
-
/** Pipeline name for metrics labeling */
INGESTION_PIPELINE: string | null
/** Lane identifier (main, overflow) for metrics labeling */
@@ -91,15 +70,6 @@ export function getDefaultErrorTrackingConsumerConfig(): ErrorTrackingConsumerCo
ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS: 60, // 1 minute
ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY: true,
ERROR_TRACKING_CYMBAL_MAX_BODY_BYTES: 1_800_000,
- ERROR_TRACKING_RATE_LIMITER_ENABLED: false,
- ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE: true,
- ERROR_TRACKING_RATE_LIMITER_REDIS_HOST: '',
- ERROR_TRACKING_RATE_LIMITER_REDIS_PORT: 6379,
- ERROR_TRACKING_RATE_LIMITER_REDIS_TLS: false,
- ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS: 86_400,
- ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD: 1000,
- ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS: 3600,
- ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS: 300,
INGESTION_PIPELINE: null,
INGESTION_LANE: null,
INGESTION_OVERFLOW_MODE: 'disabled',
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 2f85e601b0b6..35bbb10cdc01 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts
@@ -8,8 +8,6 @@ import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
-import { PostgresUse } from '~/common/utils/db/postgres'
-import { ErrorTrackingSettingsManager } from '~/common/utils/error-tracking-settings-manager'
import { parseJSON } from '~/common/utils/json-parse'
import { UUIDT } from '~/common/utils/utils'
import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
@@ -151,18 +149,6 @@ describe('ErrorTrackingConsumer', () => {
statefulOverflowLocalCacheTTLSeconds: infra.config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
preservePartitionLocality: infra.config.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
pipeline: infra.config.INGESTION_PIPELINE ?? 'errortracking',
- rateLimiterEnabled: infra.config.ERROR_TRACKING_RATE_LIMITER_ENABLED,
- rateLimiterReportingMode: infra.config.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE,
- rateLimiterRedisHost: infra.config.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,
- rateLimiterRedisPort: infra.config.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,
- rateLimiterRedisTls: infra.config.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,
- rateLimiterTtlSeconds: infra.config.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
- perIssueGuardThreshold: infra.config.ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD,
- perIssueGuardWindowTtlSeconds: infra.config.ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS,
- perIssueGuardCooldownTtlSeconds: infra.config.ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS,
- fallbackRedisUrl: infra.config.REDIS_URL,
- rateLimiterRedisPoolMinSize: infra.config.REDIS_POOL_MIN_SIZE,
- rateLimiterRedisPoolMaxSize: infra.config.REDIS_POOL_MAX_SIZE,
}
// Create and store the mock so tests can configure it
mockHogTransformer = createMockHogTransformer()
@@ -201,7 +187,6 @@ describe('ErrorTrackingConsumer', () => {
),
}),
teamManager: infra.teamManager,
- errorTrackingSettingsManager: new ErrorTrackingSettingsManager(infra.postgres),
hogTransformer: mockHogTransformer,
groupTypeManager: new ReadOnlyGroupTypeManager({
fetchGroupsByKeys: jest.fn().mockResolvedValue([]),
@@ -429,259 +414,4 @@ 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 infra.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()
- infra.config.ERROR_TRACKING_RATE_LIMITER_ENABLED = true
- infra.config.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE = false
- consumer = await createConsumer(infra)
-
- await consumer['rateLimiterRedis']!.useClient({ name: 'test-flush' }, async (client) => {
- // Per-issue buckets are hash-tagged (`tokens/{teamId}/…`); the team-global
- // bucket is keyed straight off the id (`tokens/teamId:exceptions:global`).
- const tokens = `@posthog-test/error-tracking-rate-limiter/tokens`
- const keys = [
- ...(await client.keys(`${tokens}/{${team.id}}/*`)),
- ...(await client.keys(`${tokens}/${team.id}:*`)),
- ]
- 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 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()
-
- 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)
- })
-
- 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 251e97654629..ac42d36fe5fa 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
@@ -7,11 +7,7 @@ import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-ma
import { HogTransformationResult } from '~/common/hog-transformations/hog-transformer.interface'
import { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
-import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
-import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
-import { KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'
import { instrumentFn } from '~/common/tracing/tracing-utils'
-import { ErrorTrackingSettingsManager } from '~/common/utils/error-tracking-settings-manager'
import {
EventIngestionRestrictionManager,
EventIngestionRestrictionManagerComponent,
@@ -33,12 +29,9 @@ import { CymbalClient } from './cymbal'
import {
ErrorTrackingOutputs,
ErrorTrackingPipeline,
- PostCymbalRateLimiterInput,
createErrorTrackingPipeline,
runErrorTrackingPipeline,
} from './error-tracking-pipeline'
-import { KeyedRateLimiterStepOptions } from './keyed-rate-limiter-step'
-import { PerIssueGuardedRateLimiterService } from './per-issue-guarded-rate-limiter.service'
/**
* Configuration values for ErrorTrackingConsumer.
@@ -63,20 +56,6 @@ export interface ErrorTrackingConsumerOptions {
*/
preservePartitionLocality: boolean
pipeline: string
- rateLimiterEnabled: boolean
- rateLimiterReportingMode: boolean
- rateLimiterRedisHost: string
- rateLimiterRedisPort: number
- rateLimiterRedisTls: boolean
- rateLimiterTtlSeconds: number
- perIssueGuardThreshold: number
- perIssueGuardWindowTtlSeconds: number
- perIssueGuardCooldownTtlSeconds: number
- /** Fallback Redis URL when no dedicated host is configured. Required when rateLimiterEnabled. */
- fallbackRedisUrl?: string
- /** Pool sizing for the dedicated rate limiter Redis pool. */
- rateLimiterRedisPoolMinSize?: number
- rateLimiterRedisPoolMaxSize?: number
}
/**
@@ -97,8 +76,6 @@ export interface ErrorTrackingHogTransformer {
export interface ErrorTrackingConsumerDeps {
outputs: ErrorTrackingOutputs
teamManager: TeamManager
- /** Only required when the rate limiter is enabled; constructed alongside it. */
- errorTrackingSettingsManager?: ErrorTrackingSettingsManager
hogTransformer: ErrorTrackingHogTransformer
groupTypeManager: ReadOnlyGroupTypeManager
cookielessManager: CookielessManager
@@ -133,10 +110,6 @@ export class ErrorTrackingConsumer {
protected overflowRedirectService?: OverflowRedirectService
protected overflowLaneTTLRefreshService?: OverflowRedirectService
protected topHog?: TopHog
- protected rateLimiter?: KeyedRateLimiterService
- protected perIssueGuardedRateLimiter?: PerIssueGuardedRateLimiterService
- protected rateLimiterAppMetricsAggregator?: AppMetricsAggregator
- protected rateLimiterRedis?: RedisV2
constructor(
private config: ErrorTrackingConsumerOptions,
@@ -183,49 +156,6 @@ export class ErrorTrackingConsumer {
overflowType: 'errortracking',
})
}
-
- // Optional keyed rate limiter — dedicated Redis pool, only built when explicitly enabled.
- // When the master switch is off, no pool/service exists at all (the pipeline step is a no-op).
- if (config.rateLimiterEnabled) {
- const dedicatedHost = config.rateLimiterRedisHost
- this.rateLimiterRedis = createRedisV2PoolFromConfig({
- connection: dedicatedHost
- ? {
- url: dedicatedHost,
- options: {
- port: config.rateLimiterRedisPort,
- tls: config.rateLimiterRedisTls ? {} : undefined,
- },
- name: 'error-tracking-rate-limiter-redis',
- }
- : {
- url: config.fallbackRedisUrl ?? '',
- name: 'error-tracking-rate-limiter-redis-fallback',
- },
- poolMinSize: config.rateLimiterRedisPoolMinSize ?? 1,
- poolMaxSize: config.rateLimiterRedisPoolMaxSize ?? 3,
- })
- this.rateLimiter = new KeyedRateLimiterService(
- {
- name: 'error-tracking-rate-limiter',
- // bucketSize/refillRate are intentionally omitted — every request supplies
- // them via getBucketConfig (per-team), so service-level defaults are unused.
- ttlSeconds: config.rateLimiterTtlSeconds,
- },
- this.rateLimiterRedis
- )
- this.perIssueGuardedRateLimiter = new PerIssueGuardedRateLimiterService(
- {
- name: 'error-tracking-rate-limiter',
- threshold: config.perIssueGuardThreshold,
- windowTtlSeconds: config.perIssueGuardWindowTtlSeconds,
- cooldownTtlSeconds: config.perIssueGuardCooldownTtlSeconds,
- bucketTtlSeconds: config.rateLimiterTtlSeconds,
- },
- this.rateLimiterRedis
- )
- this.rateLimiterAppMetricsAggregator = new AppMetricsAggregator(deps.outputs)
- }
}
public get service(): PluginServerService {
@@ -286,103 +216,18 @@ export class ErrorTrackingConsumer {
preservePartitionLocality: this.config.preservePartitionLocality,
overflowRedirectService: this.overflowRedirectService,
overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,
- postCymbalRateLimiters: this.buildPostCymbalRateLimiterSpecs(),
- errorTrackingSettingsManager: this.rateLimiter ? this.deps.errorTrackingSettingsManager : undefined,
topHog: this.topHog,
})
logger.info('✅', `${this.name} - pipeline initialized`)
}
- /** Per-issue spec uses the guarded service; team-global spec uses the base service. */
- private buildPostCymbalRateLimiterSpecs(): KeyedRateLimiterStepOptions<PostCymbalRateLimiterInput>[] {
- if (!this.rateLimiter || !this.perIssueGuardedRateLimiter) {
- return []
- }
-
- return [
- // 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.perIssueGuardedRateLimiter,
- appMetricsAggregator: this.rateLimiterAppMetricsAggregator,
- appSource: 'exceptions',
- getKey: (input) => {
- if (input.errorTrackingSettings?.perIssueRateLimitValue == null) {
- return null
- }
- const issueId = input.event.properties?.$exception_issue_id
- return typeof issueId === 'string' && issueId
- ? `${input.team.id}:exceptions:issue:${issueId}`
- : null
- },
- // 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',
- 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.
- {
- rateLimiter: this.rateLimiter,
- appMetricsAggregator: this.rateLimiterAppMetricsAggregator,
- appSource: 'exceptions',
- // Skip rate limiting when the team hasn't opted in (no row or null value).
- // Returning null makes the rate-limiter step pass the input through as `ok()`.
- // The serializer enforces min_value=1, so a non-null value is always positive.
- getKey: (input) =>
- input.errorTrackingSettings?.projectRateLimitValue == null
- ? null
- : `${input.team.id}:exceptions:global`,
- getTeamId: (input) => input.team.id,
- reportingMode: this.config.rateLimiterReportingMode,
- dropReason: 'rate_limited:team_global',
- getBucketConfig: (input) => {
- // User model: "N events per M minutes".
- // Token bucket: bucketSize=N (max burst), refillRate=N/(M*60) per second.
- const settings = input.errorTrackingSettings!
- const value = settings.projectRateLimitValue!
- const minutes = settings.projectRateLimitBucketSizeMinutes ?? 60
- return {
- bucketSize: value,
- refillRate: value / (minutes * 60),
- }
- },
- },
- ]
- }
-
public async stop(): Promise<void> {
logger.info('🔁', `${this.name} - stopping`)
// Wait for any pending side effects
await this.promiseScheduler.waitForAll()
- // Drain any pending rate-limiter outcome metrics before output producers go away.
- if (this.rateLimiterAppMetricsAggregator) {
- try {
- await this.rateLimiterAppMetricsAggregator.flush()
- } catch (error) {
- logger.error('⚠️', `${this.name} - failed to flush rate limiter app metrics on stop`, {
- error: error instanceof Error ? error.message : String(error),
- })
- }
- }
-
// Shutdown overflow services
await this.overflowRedirectService?.shutdown()
await this.overflowLaneTTLRefreshService?.shutdown()
@@ -426,16 +271,7 @@ export class ErrorTrackingConsumer {
throw error
} finally {
// Flush scheduled work and invocation results to prevent memory accumulation
- await Promise.all([
- this.promiseScheduler.waitForAll(),
- this.deps.hogTransformer.processInvocationResults(),
- // Best-effort: failures here must not break ingestion.
- this.rateLimiterAppMetricsAggregator?.flush().catch((error) => {
- logger.error('⚠️', `${this.name} - failed to flush rate limiter app metrics`, {
- error: error instanceof Error ? error.message : String(error),
- })
- }),
- ])
+ await Promise.all([this.promiseScheduler.waitForAll(), this.deps.hogTransformer.processInvocationResults()])
}
}
}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
index f102f7add216..2eac1155d406 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
@@ -12,11 +12,10 @@ import {
} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
-import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/common/utils/error-tracking-settings-manager'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
-import { CommonTeamStage, newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
+import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import {
@@ -36,15 +35,11 @@ import { IngestionOverflowMode } from '~/ingestion/config'
import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
import { TopHogRegistry, count, countOk, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
import { createBatch } from '~/ingestion/framework/helpers'
-import { PluginEvent } from '~/plugin-scaffold'
-import { Team } from '~/types'
import { createAttachMessageBytesStep } from './attach-message-bytes-step'
import { createCymbalProcessingStep } from './cymbal-processing-step'
import { CymbalClient } from './cymbal/client'
import { ErrorTrackingHogTransformer } from './error-tracking-consumer'
-import { KeyedRateLimiterStepOptions, createKeyedRateLimiterStep } from './keyed-rate-limiter-step'
-import { createLoadErrorTrackingSettingsStep } from './load-error-tracking-settings-step'
import { createErrorTrackingPrepareEventStep } from './prepare-event-step'
export interface ErrorTrackingPipelineInput {
@@ -96,49 +91,10 @@ export interface ErrorTrackingPipelineConfig {
overflowRedirectService?: OverflowRedirectService
/** Service for refreshing TTLs on overflow lane events. */
overflowLaneTTLRefreshService?: OverflowRedirectService
- /**
- * 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.
- */
- 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.
- */
- errorTrackingSettingsManager?: ErrorTrackingSettingsManager
/** TopHog registry for metrics. */
topHog: TopHogRegistry
}
-/**
- * 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 PostCymbalRateLimiterInput {
- team: { id: number }
- event: PluginEvent
- errorTrackingSettings?: ErrorTrackingSettings | null
-}
-
-/**
- * Apply each rate limiter spec as its own post-Cymbal chunk step. The chain's TCurrent
- * 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.
- */
-function applyKeyedRateLimiters<
- TInput extends { message: Message },
- TContext extends { message: Message },
- ROut extends string,
- CBatch,
- TPost extends { team: Team },
- TCurrent,
->(
- stage: CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, TCurrent>,
- specs: KeyedRateLimiterStepOptions<TCurrent>[]
-): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, TCurrent> {
- return specs.reduce((s, spec) => s.pipeChunk(createKeyedRateLimiterStep(spec)), stage)
-}
-
/**
* Creates the error tracking pipeline.
*
@@ -153,13 +109,12 @@ function applyKeyedRateLimiters<
* 7. Only-cookieless rate limit - Redirect cookieless rate-limited events to overflow
* using the hashed distinct_id from step 6
* 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
- * 13. Group type mapping - Map group types to indexes (read-only)
- * 14. Create event - Build ErrorTrackingKafkaEvent (matches Cymbal's output format)
- * 15. Emit event - Produce to output topic
+ * 9. Person properties - Fetch person by distinct_id (read-only)
+ * 10. Hog transformations - Run team transformations (including GeoIP if enabled)
+ * 11. Prepare event - Convert to PreIngestionEvent format, track if person found
+ * 12. Group type mapping - Map group types to indexes (read-only)
+ * 13. Create event - Build ErrorTrackingKafkaEvent (matches Cymbal's output format)
+ * 14. Emit event - Produce to output topic
*
* Note: Cymbal runs before enrichment because it only needs the raw exception data
* for symbolication and fingerprinting. This reduces payload size and avoids
@@ -180,8 +135,6 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
preservePartitionLocality,
overflowRedirectService,
overflowLaneTTLRefreshService,
- postCymbalRateLimiters,
- errorTrackingSettingsManager,
topHog,
} = config
@@ -216,9 +169,6 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
})),
]),
})
- // Attach per-team error-tracking settings. No-op when the manager isn't wired
- // (rate limiter disabled) — keeps the type chain consistent regardless.
- .pipe(createLoadErrorTrackingSettingsStep(errorTrackingSettingsManager))
// Carry the Kafka message byte size through for Cymbal batch chunking.
.pipe(createAttachMessageBytesStep())
// Cookieless processing: rewrites event.distinct_id for cookieless
@@ -244,10 +194,8 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)
retry: { 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.
return (
- applyKeyedRateLimiters(afterCymbal, postCymbalRateLimiters ?? [])
+ afterCymbal
// Batch fetch person (read-only, no updates)
.pipeChunk(createFetchPersonChunkStep(personRepository))
// Run Hog transformations (including GeoIP if team has it enabled)
diff --git a/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.test.ts b/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.test.ts
deleted file mode 100644
index 436f4f372457..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.test.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
-import {
- KeyedRateLimit,
- KeyedRateLimitRequest,
- KeyedRateLimiterService,
-} from '~/common/services/keyed-rate-limiter.service'
-import { isDropResult, isOkResult } from '~/ingestion/framework/results'
-
-import { createKeyedRateLimiterStep } from './keyed-rate-limiter-step'
-
-type Input = { teamId: number; key: string | null; cost?: number; bucketOverride?: number }
-
-// `decisions[id] = true` means every per-input request for that id is rate-limited.
-const mkLimiter = (decisions: Record<string, boolean>): KeyedRateLimiterService =>
- ({
- rateLimitGrouped: jest.fn((requests: KeyedRateLimitRequest[]) => {
- return Promise.resolve(
- requests.map(({ id }): [string, KeyedRateLimit] => [
- id,
- { tokensBefore: 100, tokens: decisions[id] ? -1 : 99, isRateLimited: !!decisions[id] },
- ])
- )
- }),
- }) as unknown as KeyedRateLimiterService
-
-const mkAggregator = (): AppMetricsAggregator =>
- ({
- queue: jest.fn(),
- }) as unknown as AppMetricsAggregator
-
-const baseOpts = (overrides: Partial<Parameters<typeof createKeyedRateLimiterStep<Input>>[0]> = {}) => ({
- appSource: 'exceptions',
- getKey: (i: Input) => i.key,
- getCost: (i: Input) => i.cost ?? 1,
- getTeamId: (i: Input) => i.teamId,
- reportingMode: false,
- ...overrides,
-})
-
-describe('createKeyedRateLimiterStep', () => {
- it('is a no-op when rateLimiter is undefined', async () => {
- const step = createKeyedRateLimiterStep<Input>(baseOpts({ rateLimiter: undefined }))
-
- const results = await step([
- { teamId: 1, key: 'a' },
- { teamId: 1, key: 'b' },
- ])
-
- expect(results).toHaveLength(2)
- expect(results.every(isOkResult)).toBe(true)
- })
-
- it('returns empty array for empty input', async () => {
- const step = createKeyedRateLimiterStep<Input>(baseOpts({ rateLimiter: mkLimiter({}) }))
- const results = await step([])
- expect(results).toEqual([])
- })
-
- it('drops rate-limited inputs in enforcing mode', async () => {
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({
- rateLimiter: mkLimiter({ '1:exceptions:global': true }),
- reportingMode: false,
- })
- )
-
- const results = await step([
- { teamId: 1, key: '1:exceptions:global' },
- { teamId: 1, key: '1:exceptions:global' },
- { teamId: 2, key: '2:exceptions:global' },
- ])
-
- expect(isDropResult(results[0])).toBe(true)
- expect(isDropResult(results[1])).toBe(true)
- expect(isOkResult(results[2])).toBe(true)
- if (isDropResult(results[0])) {
- expect(results[0].reason).toBe('rate_limited')
- }
- })
-
- it('passes a prefix of inputs and drops the over-budget tail (partial passthrough)', async () => {
- // First 3 of 5 per-input requests for 'k' are allowed; rest denied.
- const seen = new Map<string, number>()
- const limiter = {
- rateLimitGrouped: jest.fn((requests: KeyedRateLimitRequest[]) => {
- return Promise.resolve(
- requests.map(({ id }): [string, KeyedRateLimit] => {
- const idx = seen.get(id) ?? 0
- seen.set(id, idx + 1)
- const isRateLimited = idx >= 3
- return [id, { tokensBefore: 3, tokens: isRateLimited ? -1 : 0, isRateLimited }]
- })
- )
- }),
- } as unknown as KeyedRateLimiterService
- const aggregator = mkAggregator()
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({ rateLimiter: limiter, appMetricsAggregator: aggregator })
- )
-
- const results = await step([
- { teamId: 1, key: 'k' },
- { teamId: 1, key: 'k' },
- { teamId: 1, key: 'k' },
- { teamId: 1, key: 'k' },
- { teamId: 1, key: 'k' },
- ])
-
- expect(results.map(isOkResult)).toEqual([true, true, true, false, false])
- expect(aggregator.queue).toHaveBeenCalledWith(expect.objectContaining({ metric_name: 'allowed', count: 3 }))
- expect(aggregator.queue).toHaveBeenCalledWith(
- expect.objectContaining({ metric_name: 'rate_limited', count: 2 })
- )
- })
-
- it('passes through all inputs in reporting mode even when rate limited', async () => {
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({
- rateLimiter: mkLimiter({ '1:exceptions:global': true }),
- reportingMode: true,
- })
- )
-
- const results = await step([
- { teamId: 1, key: '1:exceptions:global' },
- { teamId: 1, key: '1:exceptions:global' },
- ])
-
- expect(results.every(isOkResult)).toBe(true)
- })
-
- it('passes inputs whose getKey returns null without rate-limiting them', async () => {
- const limiter = mkLimiter({})
- const step = createKeyedRateLimiterStep<Input>(baseOpts({ rateLimiter: limiter }))
-
- const results = await step([
- { teamId: 1, key: null },
- { teamId: 1, key: null },
- ])
-
- expect(results.every(isOkResult)).toBe(true)
- expect(limiter.rateLimitGrouped).not.toHaveBeenCalled()
- })
-
- it('forwards per-input bucket config overrides snapshotted from first input per key', async () => {
- const limiter = mkLimiter({})
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({
- rateLimiter: limiter,
- getBucketConfig: (i: Input) =>
- i.bucketOverride !== undefined ? { bucketSize: i.bucketOverride, refillRate: 1 } : {},
- })
- )
-
- await step([
- { teamId: 1, key: 'k1', bucketOverride: 5 },
- { teamId: 1, key: 'k1', bucketOverride: 999 }, // ignored — first wins
- { teamId: 2, key: 'k2' },
- ])
-
- const requests = (limiter.rateLimitGrouped as jest.Mock).mock.calls[0][0] as KeyedRateLimitRequest[]
- expect(requests[0]).toMatchObject({ id: 'k1', bucketSize: 5, refillRate: 1 })
- expect(requests[1]).toMatchObject({ id: 'k1', bucketSize: 5, refillRate: 1 })
- expect(requests[2].bucketSize).toBeUndefined()
- expect(requests[2].refillRate).toBeUndefined()
- })
-
- it('emits one app_metrics2 row per (team, key, outcome) with summed counts', async () => {
- const aggregator = mkAggregator()
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({
- rateLimiter: mkLimiter({ '1:exceptions:global': true }),
- appMetricsAggregator: aggregator,
- reportingMode: true,
- })
- )
-
- await step([
- { teamId: 1, key: '1:exceptions:global' },
- { teamId: 1, key: '1:exceptions:global' },
- { teamId: 1, key: '1:exceptions:global' },
- { teamId: 2, key: '2:exceptions:global' },
- ])
-
- expect(aggregator.queue).toHaveBeenCalledTimes(2)
- expect(aggregator.queue).toHaveBeenCalledWith({
- team_id: 1,
- app_source: 'exceptions',
- app_source_id: '1:exceptions:global',
- metric_kind: 'rate_limiting',
- metric_name: 'rate_limited',
- count: 3,
- })
- expect(aggregator.queue).toHaveBeenCalledWith({
- team_id: 2,
- app_source: 'exceptions',
- app_source_id: '2:exceptions:global',
- metric_kind: 'rate_limiting',
- metric_name: 'allowed',
- count: 1,
- })
- })
-
- it.each([
- ['all allowed', {}, [{ metric_name: 'allowed', count: 3 }]],
- [
- 'mixed outcomes',
- { '1:exceptions:issue:aaa': true },
- [
- { metric_name: 'allowed', count: 2 },
- { metric_name: 'rate_limited', count: 1 },
- ],
- ],
- ] as const)(
- 'collapses high-cardinality keys under getAppSourceId for app_metrics2 (%s)',
- async (_label, decisions, expectedRows) => {
- const aggregator = mkAggregator()
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({
- rateLimiter: mkLimiter(decisions),
- appMetricsAggregator: aggregator,
- reportingMode: true,
- getAppSourceId: (i) => `${i.teamId}:exceptions:per_issue`,
- })
- )
-
- await step([
- { teamId: 1, key: '1:exceptions:issue:aaa' },
- { teamId: 1, key: '1:exceptions:issue:bbb' },
- { teamId: 1, key: '1:exceptions:issue:ccc' },
- ])
-
- expect(aggregator.queue).toHaveBeenCalledTimes(expectedRows.length)
- for (const { metric_name, count } of expectedRows) {
- expect(aggregator.queue).toHaveBeenCalledWith({
- team_id: 1,
- app_source: 'exceptions',
- app_source_id: '1:exceptions:per_issue',
- metric_kind: 'rate_limiting',
- metric_name,
- count,
- })
- }
- }
- )
-
- it('does not emit metrics when aggregator is undefined', async () => {
- const limiter = mkLimiter({ a: true })
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({ rateLimiter: limiter, appMetricsAggregator: undefined })
- )
-
- await step([{ teamId: 1, key: 'a' }])
-
- expect(limiter.rateLimitGrouped).toHaveBeenCalled()
- })
-
- it('uses the configured dropReason', async () => {
- const step = createKeyedRateLimiterStep<Input>(
- baseOpts({
- rateLimiter: mkLimiter({ k: true }),
- reportingMode: false,
- dropReason: 'custom_reason',
- })
- )
-
- const results = await step([{ teamId: 1, key: 'k' }])
- expect(isDropResult(results[0])).toBe(true)
- if (isDropResult(results[0])) {
- expect(results[0].reason).toBe('custom_reason')
- }
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.ts b/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.ts
deleted file mode 100644
index 551833963ba2..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { Counter } from 'prom-client'
-
-import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
-import { KeyedRateLimitRequest, KeyedRateLimiter } from '~/common/services/keyed-rate-limiter.service'
-import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
-import { drop, ok } from '~/ingestion/framework/results'
-
-const outcomeCounter = new Counter({
- name: 'keyed_rate_limiter_outcomes_total',
- help: 'Per-input rate limit outcomes for keyed rate limiters across pipelines.',
- labelNames: ['app_source', 'outcome', 'reporting_mode'],
-})
-
-export type RateLimitOutcome = 'allowed' | 'rate_limited'
-
-export interface KeyedRateLimiterStepOptions<T> {
- /** When undefined, the step is a no-op — every input passes through `ok()`. */
- rateLimiter?: KeyedRateLimiter
- /** When undefined, no `app_metrics2` rows are emitted; Prom counter still increments. */
- appMetricsAggregator?: AppMetricsAggregator
- /** Used as the `app_source` label on emitted metrics (e.g. 'exceptions'). */
- appSource: string
- /** Extract a stable rate-limit key from each input. Return null to skip rate-limiting that input. */
- getKey: (input: T) => string | null
- /**
- * Override the `app_source_id` written to `app_metrics2`. Defaults to the rate-limit key.
- * Use this when the key is high-cardinality (e.g. a per-issue key) and you want every row
- * collapsed under one stable id — `getKey` still drives the actual rate-limit bucket.
- */
- getAppSourceId?: (input: T) => string
- /** Cost per input. Defaults to 1 — override for byte-based limits etc. */
- getCost?: (input: T) => number
- /** Team id used when emitting `app_metrics2` rows. */
- getTeamId: (input: T) => number
- /**
- * Optional per-input override of bucketSize / refillRate / ttlSeconds. When provided,
- * the values from the first input in each key group win. All inputs sharing a key are
- * expected to agree (e.g. team-keyed limits where all inputs in a key share a team).
- */
- getBucketConfig?: (input: T) => Partial<Pick<KeyedRateLimitRequest, 'bucketSize' | 'refillRate' | 'ttlSeconds'>>
- /** When true, decisions are computed and tracked but never enforced — every input passes through `ok()`. */
- reportingMode: boolean
- /** Drop reason label when enforcing. Defaults to `rate_limited`. */
- dropReason?: string
-}
-
-/**
- * Generic batch pipeline step that applies a token-bucket rate limit keyed by
- * an arbitrary string. Reusable for the initial per-team exception limit and
- * for future per-hash / per-event-name limits — the only thing the caller
- * varies is `getKey`.
- *
- * Behaviour summary:
- * - rateLimiter undefined → no-op, all `ok()`.
- * - getKey returns null → that input bypasses rate limiting (still `ok()`).
- * - reportingMode true → decisions tracked but never enforced.
- * - reportingMode false → inputs in rate-limited groups become `drop(dropReason)`.
- *
- * Cost is summed per unique key within a batch so we make one Redis call per key
- * regardless of how many inputs share it.
- */
-export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<T>): ChunkProcessingStep<T, T> {
- const costFn = opts.getCost ?? (() => 1)
- const dropReason = opts.dropReason ?? 'rate_limited'
- const reportingModeLabel = opts.reportingMode ? 'true' : 'false'
-
- return async function keyedRateLimiterStep(inputs) {
- if (!opts.rateLimiter || inputs.length === 0) {
- return inputs.map((input) => ok(input))
- }
-
- const keyForInput: (string | null)[] = new Array(inputs.length)
- const limitedForInput: boolean[] = new Array(inputs.length).fill(false)
- const perInputRequests: KeyedRateLimitRequest[] = []
- const requestIndexForInput: number[] = new Array(inputs.length).fill(-1)
- const bucketConfigByKey = new Map<
- string,
- Partial<Pick<KeyedRateLimitRequest, 'bucketSize' | 'refillRate' | 'ttlSeconds'>>
- >()
-
- for (let i = 0; i < inputs.length; i++) {
- const key = opts.getKey(inputs[i])
- keyForInput[i] = key
- if (key === null) {
- continue
- }
- if (!bucketConfigByKey.has(key)) {
- bucketConfigByKey.set(key, opts.getBucketConfig?.(inputs[i]) ?? {})
- }
- requestIndexForInput[i] = perInputRequests.length
- perInputRequests.push({
- id: key,
- teamId: opts.getTeamId(inputs[i]),
- cost: costFn(inputs[i]),
- ...bucketConfigByKey.get(key),
- })
- }
-
- if (perInputRequests.length > 0) {
- const rateLimitResults = await opts.rateLimiter.rateLimitGrouped(perInputRequests)
- for (let i = 0; i < inputs.length; i++) {
- const reqIdx = requestIndexForInput[i]
- if (reqIdx === -1) {
- continue
- }
- limitedForInput[i] = rateLimitResults[reqIdx][1].isRateLimited
- }
- }
-
- const outcomeBuckets = new Map<
- string,
- { teamId: number; appSourceId: string; outcome: RateLimitOutcome; count: number }
- >()
- for (let i = 0; i < inputs.length; i++) {
- const key = keyForInput[i]
- if (key === null) {
- continue
- }
- const outcome: RateLimitOutcome = limitedForInput[i] ? 'rate_limited' : 'allowed'
- outcomeCounter.inc({ app_source: opts.appSource, outcome, reporting_mode: reportingModeLabel })
-
- if (opts.appMetricsAggregator) {
- const teamId = opts.getTeamId(inputs[i])
- const appSourceId = opts.getAppSourceId ? opts.getAppSourceId(inputs[i]) : key
- const bucketKey = `${teamId}|${appSourceId}|${outcome}`
- const existing = outcomeBuckets.get(bucketKey)
- if (existing) {
- existing.count++
- } else {
- outcomeBuckets.set(bucketKey, { teamId, appSourceId, outcome, count: 1 })
- }
- }
- }
-
- if (opts.appMetricsAggregator) {
- for (const { teamId, appSourceId, outcome, count } of outcomeBuckets.values()) {
- opts.appMetricsAggregator.queue({
- team_id: teamId,
- app_source: opts.appSource,
- app_source_id: appSourceId,
- metric_kind: 'rate_limiting',
- metric_name: outcome,
- count,
- })
- }
- }
-
- return inputs.map((input, i) => {
- const key = keyForInput[i]
- if (key === null || !limitedForInput[i] || opts.reportingMode) {
- return ok(input)
- }
- return drop<T>(dropReason)
- })
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/load-error-tracking-settings-step.test.ts b/nodejs/src/ingestion/pipelines/errortracking/load-error-tracking-settings-step.test.ts
deleted file mode 100644
index 21a8bd1d7b21..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/load-error-tracking-settings-step.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/common/utils/error-tracking-settings-manager'
-import { isOkResult } from '~/ingestion/framework/results'
-
-import { createLoadErrorTrackingSettingsStep } from './load-error-tracking-settings-step'
-
-describe('createLoadErrorTrackingSettingsStep', () => {
- const buildManager = (
- settingsByTeam: Record<string, ErrorTrackingSettings | null>
- ): jest.Mocked<Pick<ErrorTrackingSettingsManager, 'getSettings'>> => ({
- getSettings: jest.fn((teamId: number) => Promise.resolve(settingsByTeam[String(teamId)] ?? null)),
- })
-
- it('attaches null when the team has no settings row', async () => {
- const manager = buildManager({ '1': null })
- const step = createLoadErrorTrackingSettingsStep(manager as unknown as ErrorTrackingSettingsManager)
-
- const result = await step({ team: { id: 1 } })
-
- expect(isOkResult(result)).toBe(true)
- if (isOkResult(result)) {
- expect(result.value.errorTrackingSettings).toBeNull()
- }
- })
-
- it('attaches the loaded settings', async () => {
- const manager = buildManager({
- '1': {
- projectRateLimitValue: 100,
- projectRateLimitBucketSizeMinutes: 5,
- perIssueRateLimitValue: 20,
- perIssueRateLimitBucketSizeMinutes: 15,
- },
- })
- const step = createLoadErrorTrackingSettingsStep(manager as unknown as ErrorTrackingSettingsManager)
-
- const result = await step({ team: { id: 1 } })
-
- expect(isOkResult(result)).toBe(true)
- if (isOkResult(result)) {
- expect(result.value.errorTrackingSettings).toEqual({
- projectRateLimitValue: 100,
- projectRateLimitBucketSizeMinutes: 5,
- perIssueRateLimitValue: 20,
- perIssueRateLimitBucketSizeMinutes: 15,
- })
- }
- })
-
- it('attaches null without calling the manager when no manager is provided', async () => {
- const step = createLoadErrorTrackingSettingsStep<{ team: { id: number } }>(undefined)
-
- const result = await step({ team: { id: 1 } })
-
- expect(isOkResult(result)).toBe(true)
- if (isOkResult(result)) {
- expect(result.value.errorTrackingSettings).toBeNull()
- }
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/load-error-tracking-settings-step.ts b/nodejs/src/ingestion/pipelines/errortracking/load-error-tracking-settings-step.ts
deleted file mode 100644
index 9a02141ababb..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/load-error-tracking-settings-step.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/common/utils/error-tracking-settings-manager'
-import { ok } from '~/ingestion/framework/results'
-import { ProcessingStep } from '~/ingestion/framework/steps'
-
-export interface LoadErrorTrackingSettingsInput {
- team: { id: number }
-}
-
-export type WithErrorTrackingSettings<T> = T & {
- errorTrackingSettings: ErrorTrackingSettings | null
-}
-
-export function createLoadErrorTrackingSettingsStep<T extends LoadErrorTrackingSettingsInput>(
- manager: ErrorTrackingSettingsManager | undefined
-): ProcessingStep<T, WithErrorTrackingSettings<T>> {
- return async function loadErrorTrackingSettingsStep(input) {
- const errorTrackingSettings = manager ? await manager.getSettings(input.team.id) : null
- return ok({ ...input, errorTrackingSettings })
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts b/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts
deleted file mode 100644
index e2686e647e6d..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.test.ts
+++ /dev/null
@@ -1,354 +0,0 @@
-import { register } from 'prom-client'
-
-import { defaultConfig } from '~/common/config/config'
-import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
-import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
-import { KeyedRateLimitRequest } from '~/common/services/keyed-rate-limiter.service'
-import { logger } from '~/common/utils/logger'
-
-import { PerIssueGuardedRateLimiterService } from './per-issue-guarded-rate-limiter.service'
-
-const mockNow: jest.SpyInstance = jest.spyOn(Date, 'now')
-
-describe('PerIssueGuardedRateLimiterService', () => {
- jest.retryTimes(3)
-
- let now: number
- let redis: RedisV2
-
- const advanceTime = (ms: number) => {
- now += ms
- mockNow.mockReturnValue(now)
- }
-
- beforeEach(() => {
- now = 1720000000000
- mockNow.mockReturnValue(now)
-
- redis = createRedisV2PoolFromConfig({
- connection: defaultConfig.CDP_REDIS_HOST
- ? {
- url: defaultConfig.CDP_REDIS_HOST,
- options: { port: defaultConfig.CDP_REDIS_PORT, password: defaultConfig.CDP_REDIS_PASSWORD },
- }
- : { url: defaultConfig.REDIS_URL },
- poolMinSize: defaultConfig.REDIS_POOL_MIN_SIZE,
- poolMaxSize: defaultConfig.REDIS_POOL_MAX_SIZE,
- })
- })
-
- afterEach(() => {
- jest.clearAllMocks()
- })
-
- const build = (
- name: string,
- overrides: Partial<{
- threshold: number
- windowTtlSeconds: number
- cooldownTtlSeconds: number
- bucketTtlSeconds: number
- }> = {}
- ) =>
- new PerIssueGuardedRateLimiterService(
- {
- name,
- threshold: overrides.threshold ?? 3,
- windowTtlSeconds: overrides.windowTtlSeconds ?? 3600,
- cooldownTtlSeconds: overrides.cooldownTtlSeconds ?? 300,
- bucketTtlSeconds: overrides.bucketTtlSeconds ?? 60 * 60 * 24,
- },
- redis
- )
-
- const cleanLimiter = async (limiter: PerIssueGuardedRateLimiterService) => {
- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
- await deleteKeysWithPrefix(redis, limiter.getCounterKeyPrefix())
- await deleteKeysWithPrefix(redis, limiter.getCooldownKeyPrefix())
- }
-
- const readCounter = async (key: string): Promise<number | null> => {
- const res = await redis.useClient({ name: 'read-counter' }, async (client) => client.get(key))
- return res == null ? null : Number(res)
- }
-
- const cooldownIsSet = async (key: string): Promise<boolean> => {
- const res = await redis.useClient({ name: 'read-cooldown' }, async (client) => client.get(key))
- return res != null
- }
-
- const req = (
- teamId: number,
- scopeKey: string,
- cost = 1,
- overrides: Partial<{ bucketSize: number; refillRate: number }> = {}
- ): KeyedRateLimitRequest => ({
- id: `${teamId}:exceptions:issue:${scopeKey}`,
- teamId,
- cost,
- bucketSize: overrides.bucketSize ?? 100,
- refillRate: overrides.refillRate ?? 10,
- })
-
- const outcomeCount = async (outcome: string): Promise<number> => {
- const metrics = await register.getMetricsAsJSON()
- const metric = metrics.find((m) => m.name === 'error_tracking_per_issue_guard_outcome_total')
- return metric?.values.find((v) => v.labels.outcome === outcome)?.value ?? 0
- }
-
- const buildWithPipelineResult = (result: unknown): PerIssueGuardedRateLimiterService =>
- new PerIssueGuardedRateLimiterService(
- { name: 'lua-fail', threshold: 1, windowTtlSeconds: 3600, cooldownTtlSeconds: 60, bucketTtlSeconds: 60 },
- { useClient: jest.fn(), usePipeline: jest.fn().mockResolvedValue(result) } as unknown as RedisV2
- )
-
- it('allows the first event with a new scopeKey and bumps the per-team window counter', async () => {
- const limiter = build('first-event')
- await cleanLimiter(limiter)
-
- const res = await limiter.rateLimitGrouped([req(42, 'scope-a')])
-
- expect(res[0][1]).toEqual(expect.objectContaining({ isRateLimited: false }))
- const nowSeconds = Math.round(now / 1000)
- expect(await readCounter(limiter.counterKey(42, nowSeconds))).toBe(1)
- expect(await cooldownIsSet(limiter.cooldownKey(42))).toBe(false)
- })
-
- it('colocates cooldown, counter, and bucket keys on one Redis Cluster slot per team', () => {
- const limiter = build('slot-tag')
- const nowSeconds = Math.round(now / 1000)
- const keys = [
- limiter.cooldownKey(42),
- limiter.counterKey(42, nowSeconds),
- limiter.bucketKey(42, '42:exceptions:issue:abc'),
- ]
- // Redis hashes only the substring inside the first {…}; identical tags ⇒ same slot ⇒ no CROSSSLOT.
- const hashTag = (key: string) => key.slice(key.indexOf('{') + 1, key.indexOf('}'))
- expect(keys.map(hashTag)).toEqual(['42', '42', '42'])
- // Different teams must not collapse onto the same tag.
- expect(hashTag(limiter.cooldownKey(99))).toBe('99')
- })
-
- it('skips counter increment for an already-seen scopeKey', async () => {
- const limiter = build('repeat-scope')
- await cleanLimiter(limiter)
-
- await limiter.rateLimitGrouped([req(42, 'scope-a')])
- await limiter.rateLimitGrouped([req(42, 'scope-a')])
- await limiter.rateLimitGrouped([req(42, 'scope-a')])
-
- const nowSeconds = Math.round(now / 1000)
- expect(await readCounter(limiter.counterKey(42, nowSeconds))).toBe(1)
- })
-
- it('does not create the bucket key once tripped, and short-circuits subsequent events', async () => {
- const limiter = build('trip', { threshold: 1 })
- await cleanLimiter(limiter)
-
- const r1 = await limiter.rateLimitGrouped([req(42, 'a')]) // allowed (counter=1)
- const r2 = await limiter.rateLimitGrouped([req(42, 'b')]) // tripped (counter=2 > threshold 1)
- const r3 = await limiter.rateLimitGrouped([req(42, 'c')]) // cooldown (flag set)
-
- // r1 mints a bucket, r2/r3 do not (per-issue defers to team-global → isRateLimited=false).
- expect(r1[0][1].isRateLimited).toBe(false)
- expect(r2[0][1].isRateLimited).toBe(false)
- expect(r3[0][1].isRateLimited).toBe(false)
- expect(await cooldownIsSet(limiter.cooldownKey(42))).toBe(true)
-
- // Bucket for 'b' was never written.
- const bExists = await redis.useClient({ name: 'check' }, async (client) =>
- client.exists(limiter.bucketKey(42, '42:exceptions:issue:b'))
- )
- expect(bExists).toBe(0)
-
- // Counter stayed at 2 — no INCR during cooldown.
- const nowSeconds = Math.round(now / 1000)
- expect(await readCounter(limiter.counterKey(42, nowSeconds))).toBe(2)
- })
-
- it('isolates cooldown flags by team', async () => {
- const limiter = build('team-iso', { threshold: 1 })
- await cleanLimiter(limiter)
-
- await limiter.rateLimitGrouped([req(42, 'a')])
- await limiter.rateLimitGrouped([req(42, 'b')])
- expect(await cooldownIsSet(limiter.cooldownKey(42))).toBe(true)
-
- const r = await limiter.rateLimitGrouped([req(99, 'a')])
- expect(r[0][1].isRateLimited).toBe(false)
- expect(await cooldownIsSet(limiter.cooldownKey(99))).toBe(false)
- })
-
- it('rotates the counter on hour boundary', async () => {
- const limiter = build('hour-rotate', { threshold: 1, windowTtlSeconds: 3600 })
- await cleanLimiter(limiter)
-
- await limiter.rateLimitGrouped([req(42, 'a')])
-
- const nowSeconds = Math.round(now / 1000)
- const counterH = limiter.counterKey(42, nowSeconds)
- advanceTime(3600 * 1000)
- const counterHPlus1 = limiter.counterKey(42, Math.round(now / 1000))
- expect(counterHPlus1).not.toBe(counterH)
-
- // After the rollover, the new-hour counter starts fresh on the next new scopeKey.
- await limiter.rateLimitGrouped([req(42, 'b')])
- expect(await readCounter(counterHPlus1)).toBe(1)
- })
-
- it('returns to allowed once cooldown TTL expires and team stops creating new scopeKeys', async () => {
- const limiter = build('recover', { threshold: 1, cooldownTtlSeconds: 1 })
- await cleanLimiter(limiter)
-
- await limiter.rateLimitGrouped([req(42, 'a')])
- await limiter.rateLimitGrouped([req(42, 'b')])
- expect(await cooldownIsSet(limiter.cooldownKey(42))).toBe(true)
-
- await new Promise((resolve) => setTimeout(resolve, 1100))
- expect(await cooldownIsSet(limiter.cooldownKey(42))).toBe(false)
-
- const r = await limiter.rateLimitGrouped([req(42, 'a')])
- expect(r[0][1].isRateLimited).toBe(false)
- })
-
- it('rate-limits when a single scopeKey drains its own bucket', async () => {
- const limiter = build('bucket-limit')
- await cleanLimiter(limiter)
-
- await limiter.rateLimitGrouped([req(42, 'noisy', 4, { bucketSize: 5, refillRate: 0 })])
- const r = await limiter.rateLimitGrouped([req(42, 'noisy', 4, { bucketSize: 5, refillRate: 0 })])
- expect(r[0][1].isRateLimited).toBe(true)
- })
-
- it('allows the first N inputs of an over-budget single-scopeKey batch and denies the rest', async () => {
- const limiter = build('partial-passthrough')
- await cleanLimiter(limiter)
-
- // bucketSize 3, refillRate 0 — five inputs sharing one scopeKey: first 3 pass, last 2 limited.
- const requests = Array.from({ length: 5 }, () => req(42, 'shared', 1, { bucketSize: 3, refillRate: 0 }))
- const res = await limiter.rateLimitGrouped(requests)
-
- expect(res.map(([, r]) => r.isRateLimited)).toEqual([false, false, false, true, true])
- })
-
- it('handles a mixed batch: cooldown team, tripping team, partial pass-through, clean team', async () => {
- const limiter = build('big-mix', { threshold: 2 })
- await cleanLimiter(limiter)
-
- const bucketExists = async (key: string): Promise<number> =>
- (await redis.useClient({ name: 'check' }, async (client) => client.exists(key))) ?? 0
-
- // Pre-trip team 100: 3 new scopeKeys against threshold=2 → cooldown flag set.
- await limiter.rateLimitGrouped([req(100, 'pre1'), req(100, 'pre2'), req(100, 'pre3')])
- expect(await cooldownIsSet(limiter.cooldownKey(100))).toBe(true)
-
- // Single big batch covering every status at once:
- // team 100: already in cooldown → both events pass through, no buckets minted.
- // team 200: 3 distinct scopeKeys → first 2 allowed, third trips.
- // team 300: 4 inputs sharing one scopeKey, bucket=2 → first 2 allowed, last 2 limited.
- // team 400: 2 distinct scopeKeys → both clean pass, no trip (counter 2 == threshold).
- const batch = [
- req(100, 'cooldown-1'),
- req(100, 'cooldown-2'),
- req(200, 'tripA'),
- req(200, 'tripB'),
- req(200, 'tripC'),
- req(300, 'noisy', 1, { bucketSize: 2, refillRate: 0 }),
- req(300, 'noisy', 1, { bucketSize: 2, refillRate: 0 }),
- req(300, 'noisy', 1, { bucketSize: 2, refillRate: 0 }),
- req(300, 'noisy', 1, { bucketSize: 2, refillRate: 0 }),
- req(400, 'cleanA'),
- req(400, 'cleanB'),
- ]
- const res = await limiter.rateLimitGrouped(batch)
-
- expect(res.map(([, r]) => r.isRateLimited)).toEqual([
- false, // 100 cooldown
- false, // 100 cooldown
- false, // 200 allowed
- false, // 200 allowed
- false, // 200 tripped (passes through)
- false, // 300 allowed (budget 2 → 1)
- false, // 300 allowed (budget 1 → 0)
- true, // 300 limited
- true, // 300 limited
- false, // 400 allowed
- false, // 400 allowed
- ])
-
- // Team 100 was already in cooldown → new scopeKeys never minted buckets.
- expect(await bucketExists(limiter.bucketKey(100, '100:exceptions:issue:cooldown-1'))).toBe(0)
- expect(await bucketExists(limiter.bucketKey(100, '100:exceptions:issue:cooldown-2'))).toBe(0)
-
- // Team 200 tripped this batch — first two buckets minted, third (tripC) NOT.
- expect(await cooldownIsSet(limiter.cooldownKey(200))).toBe(true)
- expect(await bucketExists(limiter.bucketKey(200, '200:exceptions:issue:tripA'))).toBe(1)
- expect(await bucketExists(limiter.bucketKey(200, '200:exceptions:issue:tripB'))).toBe(1)
- expect(await bucketExists(limiter.bucketKey(200, '200:exceptions:issue:tripC'))).toBe(0)
-
- // Team 300 never tripped (only 1 distinct scopeKey).
- expect(await cooldownIsSet(limiter.cooldownKey(300))).toBe(false)
- // Team 400 stayed under threshold.
- expect(await cooldownIsSet(limiter.cooldownKey(400))).toBe(false)
- })
-
- it('throws when a request is missing teamId', async () => {
- const limiter = build('missing-team')
- await cleanLimiter(limiter)
-
- await expect(
- limiter.rateLimitGrouped([{ id: 'whatever', cost: 1, bucketSize: 100, refillRate: 1 }])
- ).rejects.toThrow(/missing teamId/)
- })
-
- it('fails open when the Redis pipeline fails', async () => {
- const limiter = new PerIssueGuardedRateLimiterService(
- {
- name: 'fail-open',
- threshold: 1,
- windowTtlSeconds: 3600,
- cooldownTtlSeconds: 60,
- bucketTtlSeconds: 60,
- },
- {
- useClient: jest.fn(),
- usePipeline: jest.fn().mockResolvedValue(null),
- } as unknown as RedisV2
- )
-
- const before = await outcomeCount('fail_open_redis')
- const res = await limiter.rateLimitGrouped([req(42, 'a'), req(42, 'b')])
- for (const [, r] of res) {
- expect(r).toEqual(expect.objectContaining({ isRateLimited: false }))
- }
- expect((await outcomeCount('fail_open_redis')) - before).toBe(2)
- })
-
- it('warns and records fail_open_lua when a single Lua call errored', async () => {
- const warnSpy = jest.spyOn(logger, 'warn')
- const before = await outcomeCount('fail_open_lua')
- const limiter = buildWithPipelineResult([[new Error('lua boom'), null]])
-
- const res = await limiter.rateLimitGrouped([req(42, 'a')])
-
- expect(res[0][1]).toEqual(expect.objectContaining({ isRateLimited: false }))
- expect(warnSpy).toHaveBeenCalledTimes(1)
- expect((await outcomeCount('fail_open_lua')) - before).toBe(1)
- })
-
- it.each([
- ['wrong tuple size', [10]],
- ['non-numeric values', ['x', 'y', 'z']],
- ['null reply', null],
- ])('warns and records fail_open_lua when the Lua reply is malformed (%s)', async (_label, value) => {
- const warnSpy = jest.spyOn(logger, 'warn')
- const before = await outcomeCount('fail_open_lua')
- const limiter = buildWithPipelineResult([[null, value]])
-
- const res = await limiter.rateLimitGrouped([req(42, 'a')])
-
- expect(res[0][1]).toEqual(expect.objectContaining({ isRateLimited: false }))
- expect(warnSpy).toHaveBeenCalledTimes(1)
- expect((await outcomeCount('fail_open_lua')) - before).toBe(1)
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.ts b/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.ts
deleted file mode 100644
index dc2b57314ee9..000000000000
--- a/nodejs/src/ingestion/pipelines/errortracking/per-issue-guarded-rate-limiter.service.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { Counter } from 'prom-client'
-
-import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'
-import { KeyedRateLimit, KeyedRateLimitRequest, KeyedRateLimiter } from '~/common/services/keyed-rate-limiter.service'
-import { logger } from '~/common/utils/logger'
-
-const guardOutcomeCounter = new Counter({
- name: 'error_tracking_per_issue_guard_outcome_total',
- help: 'Per-event outcome from the per-issue guarded rate limiter.',
- labelNames: ['outcome'],
-})
-
-export type GuardedStatus = 'allowed' | 'limited' | 'tripped' | 'cooldown'
-
-/** `fail_open_redis`/`fail_open_lua` mark events allowed only by virtue of an error, so they can be alerted on. */
-export type GuardOutcome = GuardedStatus | 'fail_open_redis' | 'fail_open_lua'
-
-const STATUS_BY_CODE: GuardedStatus[] = ['allowed', 'limited', 'tripped', 'cooldown']
-
-type ValidatedRequest = KeyedRateLimitRequest & { teamId: number; bucketSize: number; refillRate: number }
-
-export interface PerIssueGuardedRateLimiterConfig {
- /** Logical name; produces `@posthog/<name>/tokens|sigcount|sigcooldown/...` keys (`@posthog-test/...` under NODE_ENV=test). */
- name: string
- /** Max new bucket keys per team per window before tripping cooldown. */
- threshold: number
- /** Counter window TTL (seconds). Also drives the hourly counter key rotation. */
- windowTtlSeconds: number
- /** Cooldown flag TTL (seconds). How long a tripped team is quarantined from new-key creation. */
- cooldownTtlSeconds: number
- /** Token-bucket TTL (seconds). Mirrors the existing rate-limiter's bucket TTL. */
- bucketTtlSeconds: number
- /** When false, throw if the Redis pipeline returns null instead of fail-open allowing all. Default: true. */
- failOpen?: boolean
-}
-
-const buildPrefixes = (name: string): { bucket: string; counter: string; cooldown: string } => {
- const root = process.env.NODE_ENV === 'test' ? '@posthog-test' : '@posthog'
- return {
- bucket: `${root}/${name}/tokens`,
- counter: `${root}/${name}/sigcount`,
- cooldown: `${root}/${name}/sigcooldown`,
- }
-}
-
-export class PerIssueGuardedRateLimiterService implements KeyedRateLimiter {
- private readonly prefixes: { bucket: string; counter: string; cooldown: string }
-
- constructor(
- private readonly config: PerIssueGuardedRateLimiterConfig,
- private readonly redis: RedisV2
- ) {
- this.prefixes = buildPrefixes(config.name)
- }
-
- public getKeyPrefix(): string {
- return this.prefixes.bucket
- }
-
- public getCounterKeyPrefix(): string {
- return this.prefixes.counter
- }
-
- public getCooldownKeyPrefix(): string {
- return this.prefixes.cooldown
- }
-
- // All three keys of a single guarded call carry a `{teamId}` hash tag so Redis Cluster
- // colocates them on one slot — the Lua script touches all three at once and would otherwise
- // fail with CROSSSLOT. Tagging on teamId keeps different teams spread across slots.
- public cooldownKey(teamId: number): string {
- return `${this.prefixes.cooldown}/{${teamId}}`
- }
-
- public counterKey(teamId: number, nowSeconds: number): string {
- const window = Math.floor(nowSeconds / this.config.windowTtlSeconds)
- return `${this.prefixes.counter}/{${teamId}}/${window}`
- }
-
- public bucketKey(teamId: number, id: string): string {
- return `${this.prefixes.bucket}/{${teamId}}/${id}`
- }
-
- /** Tripped/cooldown pass through as `isRateLimited: false`; the 4-state status only surfaces via the Prom counter. */
- public async rateLimitGrouped(requests: KeyedRateLimitRequest[]): Promise<[string, KeyedRateLimit][]> {
- if (requests.length === 0) {
- return []
- }
-
- const grouped = new Map<string, KeyedRateLimitRequest>()
- for (const req of requests) {
- const existing = grouped.get(req.id)
- if (existing) {
- existing.cost += req.cost
- } else {
- grouped.set(req.id, { ...req })
- }
- }
-
- const items = [...grouped.values()].map((req): ValidatedRequest => {
- if (req.teamId == null) {
- throw new Error(
- `PerIssueGuardedRateLimiterService(${this.config.name}): request for id "${req.id}" is missing teamId — the step must populate it`
- )
- }
- if (req.bucketSize == null) {
- throw new Error(
- `PerIssueGuardedRateLimiterService(${this.config.name}): missing bucketSize for ${req.id}`
- )
- }
- if (req.refillRate == null) {
- throw new Error(
- `PerIssueGuardedRateLimiterService(${this.config.name}): missing refillRate for ${req.id}`
- )
- }
- return req as ValidatedRequest
- })
-
- const res = await this.redis.usePipeline(
- { name: `per-issue-guarded:${this.config.name}`, failOpen: true },
- (pipeline) => {
- items.forEach((req) => {
- const now = req.now ?? Math.round(Date.now() / 1000)
- pipeline.checkGuardedRateLimit(
- this.cooldownKey(req.teamId),
- this.counterKey(req.teamId, now),
- this.bucketKey(req.teamId, req.id),
- now,
- req.cost,
- req.bucketSize,
- req.refillRate,
- req.ttlSeconds ?? this.config.bucketTtlSeconds,
- this.config.threshold,
- this.config.windowTtlSeconds,
- this.config.cooldownTtlSeconds
- )
- })
- }
- )
-
- if (!res) {
- if (this.config.failOpen === false) {
- throw new Error(`PerIssueGuardedRateLimiterService(${this.config.name}): rate-limit pipeline failed`)
- }
- guardOutcomeCounter.inc({ outcome: 'fail_open_redis' }, requests.length)
- const bucketSizeById = new Map(items.map((req) => [req.id, req.bucketSize]))
- return requests.map((req) => {
- const bucketSize = bucketSizeById.get(req.id) ?? 0
- return [req.id, { tokensBefore: bucketSize, tokens: bucketSize, isRateLimited: false }]
- })
- }
-
- const budgetById = new Map<string, number>()
- const statusById = new Map<string, GuardedStatus>()
- const failOpenLuaIds = new Set<string>()
- items.forEach((req, index) => {
- const [tokenRes] = getRedisPipelineResults(res, index, 1)
- // Lua returns [tokensBefore, tokensAfter, statusCode]; we drop tokensAfter — it reflects
- // the summed cost, and we re-simulate per-input fan-out below.
- const callError = tokenRes?.[0]
- const raw = tokenRes?.[1] as [unknown, unknown, unknown] | undefined
- const tokensBefore = Number(raw?.[0])
- const statusCode = Number(raw?.[2])
-
- if (
- callError != null ||
- !Array.isArray(raw) ||
- raw.length < 3 ||
- Number.isNaN(tokensBefore) ||
- Number.isNaN(statusCode)
- ) {
- logger.warn('PerIssueGuardedRateLimiterService Lua call failed, failing open', {
- name: this.config.name,
- id: req.id,
- teamId: req.teamId,
- error: callError ?? undefined,
- raw,
- })
- failOpenLuaIds.add(req.id)
- budgetById.set(req.id, req.bucketSize)
- return
- }
-
- const status = STATUS_BY_CODE[statusCode] ?? 'allowed'
- budgetById.set(req.id, tokensBefore)
- statusById.set(req.id, status)
- })
-
- const out: [string, KeyedRateLimit][] = requests.map((req) => {
- if (failOpenLuaIds.has(req.id)) {
- guardOutcomeCounter.inc({ outcome: 'fail_open_lua' }, 1)
- const bucketSize = budgetById.get(req.id) ?? 0
- return [req.id, { tokensBefore: bucketSize, tokens: bucketSize, isRateLimited: false }]
- }
-
- const status = statusById.get(req.id) ?? 'allowed'
- const tokensBefore = budgetById.get(req.id) ?? 0
- guardOutcomeCounter.inc({ outcome: status }, 1)
-
- if (status === 'tripped' || status === 'cooldown') {
- // Skip client-side fan-out: per-issue defers to team-global limiter.
- return [req.id, { tokensBefore: 0, tokens: 0, isRateLimited: false }]
- }
- // Same fan-out shape as KeyedRateLimiterService.rateLimitGrouped.
- if (tokensBefore >= req.cost) {
- const next = tokensBefore - req.cost
- budgetById.set(req.id, next)
- return [req.id, { tokensBefore, tokens: next, isRateLimited: false }]
- }
- return [req.id, { tokensBefore, tokens: -1, isRateLimited: true }]
- })
-
- return out
- }
-}
diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.ts
index 26eb04ff0c84..64bd994c8c09 100644
--- a/nodejs/src/servers/error-tracking-server.ts
+++ b/nodejs/src/servers/error-tracking-server.ts
@@ -13,7 +13,6 @@ import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-pers
import { ServerCommands } from '~/common/utils/commands'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
-import { ErrorTrackingSettingsManager } from '~/common/utils/error-tracking-settings-manager'
import { GeoIPService } from '~/common/utils/geoip'
import { logger } from '~/common/utils/logger'
import { PubSub } from '~/common/utils/pubsub'
@@ -160,9 +159,6 @@ export class ErrorTrackingServer implements NodeServer {
await this.pubsub.start()
const teamManager = new TeamManager(this.postgres)
- const errorTrackingSettingsManager = this.config.ERROR_TRACKING_RATE_LIMITER_ENABLED
- ? new ErrorTrackingSettingsManager(this.postgres)
- : undefined
// 2. Services needed by ErrorTrackingConsumer and HogTransformer
const geoipService = new GeoIPService(this.config.MMDB_FILE_LOCATION)
@@ -212,23 +208,10 @@ export class ErrorTrackingServer implements NodeServer {
this.config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
preservePartitionLocality: this.config.ERROR_TRACKING_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
pipeline: this.config.INGESTION_PIPELINE ?? 'errortracking',
- rateLimiterEnabled: this.config.ERROR_TRACKING_RATE_LIMITER_ENABLED,
- rateLimiterReportingMode: this.config.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE,
- rateLimiterRedisHost: this.config.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,
- rateLimiterRedisPort: this.config.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,
- rateLimiterRedisTls: this.config.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,
- rateLimiterTtlSeconds: this.config.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
- perIssueGuardThreshold: this.config.ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD,
- perIssueGuardWindowTtlSeconds: this.config.ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS,
- perIssueGuardCooldownTtlSeconds: this.config.ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS,
- fallbackRedisUrl: this.config.REDIS_URL,
- rateLimiterRedisPoolMinSize: this.config.REDIS_POOL_MIN_SIZE,
- rateLimiterRedisPoolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
},
{
outputs,
teamManager,
- errorTrackingSettingsManager,
hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),
groupTypeManager: new ReadOnlyGroupTypeManager(groupRepository),
cookielessManager: this.cookielessManager!,