Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: idea for rate limiting exceptions (#56929)

Ben Whitede538247d3ba
diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts
new file mode 100644
index 000000000000..51bb19c0accb
--- /dev/null
+++ b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts
@@ -0,0 +1,162 @@
+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
+import { Hub } from '~/types'
+import { closeHub, createHub } from '~/utils/db/hub'
+
+import { deleteKeysWithPrefix } from '../../cdp/_tests/redis'
+import { KeyedRateLimiterService } from './keyed-rate-limiter.service'
+
+const mockNow: jest.SpyInstance = jest.spyOn(Date, 'now')
+
+describe('KeyedRateLimiterService', () => {
+ jest.retryTimes(3)
+
+ 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()
+ })
+
+ const buildLimiter = (name: string, overrides: Partial<{ bucketSize: number; refillRate: number }> = {}) =>
+ new KeyedRateLimiterService(
+ {
+ name,
+ bucketSize: overrides.bucketSize ?? 100,
+ refillRate: overrides.refillRate ?? 10,
+ ttlSeconds: 60 * 60 * 24,
+ },
+ redis
+ )
+
+ it('uses tokens for an id', async () => {
+ const limiter = buildLimiter('test-basic')
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])
+
+ expect(res).toEqual([['team-1', { tokens: 99, isRateLimited: false }]])
+ })
+
+ it('rate limits when exceeding the bucket', async () => {
+ const limiter = buildLimiter('test-exceed')
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 99 }])
+ expect(res[0][1]).toEqual({ tokens: 1, isRateLimited: false })
+
+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])
+ expect(res[0][1]).toEqual({ tokens: 0, isRateLimited: true })
+
+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 20 }])
+ expect(res[0][1].isRateLimited).toBe(true)
+ })
+
+ it('refills over time according to refillRate', async () => {
+ const limiter = buildLimiter('test-refill')
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 50 }])
+ expect(res[0][1].tokens).toBe(50)
+
+ advanceTime(1000)
+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 0 }])
+ expect(res[0][1].tokens).toBe(60)
+ })
+
+ it('isolates ids that share a limiter via different keys', async () => {
+ const limiter = buildLimiter('test-multi')
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ const res = await limiter.rateLimitMany([
+ { id: 'team-1', cost: 1 },
+ { id: 'team-2', cost: 5 },
+ ])
+
+ expect(res).toEqual([
+ ['team-1', { tokens: 99, isRateLimited: false }],
+ ['team-2', { tokens: 95, isRateLimited: false }],
+ ])
+ })
+
+ it('isolates two limiters that share a Redis via different prefixes', async () => {
+ const limiterA = buildLimiter('test-prefix-a')
+ const limiterB = buildLimiter('test-prefix-b')
+ await deleteKeysWithPrefix(redis, limiterA.getKeyPrefix())
+ await deleteKeysWithPrefix(redis, limiterB.getKeyPrefix())
+
+ // Drain limiter A entirely.
+ await limiterA.rateLimitMany([{ id: 'shared-id', cost: 100 }])
+ const drainedA = await limiterA.rateLimitMany([{ id: 'shared-id', cost: 1 }])
+ expect(drainedA[0][1].isRateLimited).toBe(true)
+
+ // Same id under limiter B is untouched — confirms prefix isolation.
+ const freshB = await limiterB.rateLimitMany([{ id: 'shared-id', cost: 1 }])
+ expect(freshB[0][1]).toEqual({ tokens: 99, isRateLimited: false })
+ })
+
+ it('uses test-prefixed redis keys when NODE_ENV=test', () => {
+ const limiter = buildLimiter('node-env-check')
+ expect(limiter.getKeyPrefix().startsWith('@posthog-test/')).toBe(true)
+ })
+
+ it('returns empty array for empty input without touching Redis', async () => {
+ const limiter = buildLimiter('test-empty')
+ const res = await limiter.rateLimitMany([])
+ expect(res).toEqual([])
+ })
+
+ it('fails open when the Redis pipeline fails', async () => {
+ const limiter = new KeyedRateLimiterService(
+ { name: 'test-fail-open', bucketSize: 50, refillRate: 1, ttlSeconds: 60 },
+ {
+ useClient: jest.fn(),
+ // Simulate the failOpen path inside RedisV2: usePipeline returns null on error.
+ usePipeline: jest.fn().mockResolvedValue(null),
+ } as unknown as RedisV2
+ )
+
+ const res = await limiter.rateLimitMany([
+ { id: 'a', cost: 1 },
+ { id: 'b', cost: 2 },
+ ])
+
+ expect(res).toEqual([
+ ['a', { tokens: 50, isRateLimited: false }],
+ ['b', { tokens: 50, isRateLimited: false }],
+ ])
+ })
+
+ it('honours per-call bucketSize and refillRate overrides', async () => {
+ const limiter = buildLimiter('test-per-call', { bucketSize: 100, refillRate: 10 })
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ // Per-call override: tiny bucket of 5, despite the service's default of 100.
+ const res = await limiter.rateLimitMany([{ id: 'tiny-team', cost: 6, bucketSize: 5, refillRate: 1 }])
+
+ expect(res[0][1].isRateLimited).toBe(true)
+ })
+})
diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.ts b/nodejs/src/common/services/keyed-rate-limiter.service.ts
new file mode 100644
index 000000000000..bc2889058dc3
--- /dev/null
+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts
@@ -0,0 +1,112 @@
+import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'
+
+/**
+ * Token-bucket rate limiter keyed by an arbitrary string id, backed by Redis.
+ *
+ * The Redis key prefix is configurable so multiple independent limiters
+ * (e.g. error tracking, future per-event-name limits) can share a Redis
+ * without colliding. Built on the same `checkRateLimitV2` Lua command that
+ * powers `HogRateLimiterService`.
+ *
+ * Per-call bucket params (bucketSize / refillRate / ttlSeconds on the request)
+ * are supported so the same service instance can run different limits for
+ * different ids — e.g. per-team overrides without rebuilding the service.
+ */
+export interface KeyedRateLimiterConfig {
+ /**
+ * Logical name for this limiter — used to build the Redis key prefix
+ * (`@posthog/<name>/tokens/<id>`). In `NODE_ENV=test` the prefix is
+ * `@posthog-test/<name>/tokens/<id>` so test runs don't collide with
+ * production keys when sharing a Redis.
+ */
+ name: string
+ /** Default bucket params used when a request doesn't specify its own. */
+ bucketSize: number
+ refillRate: number
+ ttlSeconds: number
+}
+
+export interface KeyedRateLimitRequest {
+ id: string
+ cost: number
+ /** Override the service's default bucket capacity for this request. */
+ bucketSize?: number
+ /** Override the service's default replenish rate for this request. */
+ refillRate?: number
+ /** Override the service's default Redis key TTL for this request. */
+ ttlSeconds?: number
+}
+
+export type KeyedRateLimit = {
+ tokens: number
+ isRateLimited: boolean
+}
+
+const buildKeyPrefix = (name: string): string => {
+ const root = process.env.NODE_ENV === 'test' ? '@posthog-test' : '@posthog'
+ return `${root}/${name}/tokens`
+}
+
+export class KeyedRateLimiterService {
+ private readonly keyPrefix: string
+
+ constructor(
+ private readonly config: KeyedRateLimiterConfig,
+ private readonly redis: RedisV2
+ ) {
+ this.keyPrefix = buildKeyPrefix(config.name)
+ }
+
+ public getKeyPrefix(): string {
+ return this.keyPrefix
+ }
+
+ private rateLimitArgs(req: KeyedRateLimitRequest): [string, number, number, number, number, number] {
+ const nowSeconds = Math.round(Date.now() / 1000)
+ return [
+ `${this.keyPrefix}/${req.id}`,
+ nowSeconds,
+ req.cost,
+ req.bucketSize ?? this.config.bucketSize,
+ req.refillRate ?? this.config.refillRate,
+ req.ttlSeconds ?? this.config.ttlSeconds,
+ ]
+ }
+
+ public async rateLimitMany(requests: KeyedRateLimitRequest[]): Promise<[string, KeyedRateLimit][]> {
+ if (requests.length === 0) {
+ return []
+ }
+
+ const res = await this.redis.usePipeline(
+ { name: `keyed-rate-limiter:${this.config.name}`, failOpen: true },
+ (pipeline) => {
+ requests.forEach((req) => {
+ pipeline.checkRateLimitV2(...this.rateLimitArgs(req))
+ })
+ }
+ )
+
+ if (!res) {
+ // failOpen swallowed an error — treat all as not rate limited so we
+ // don't drop ingestion just because Redis blipped. Reflect each
+ // request's own (potentially overridden) bucketSize in the response.
+ return requests.map((req) => [
+ req.id,
+ { tokens: req.bucketSize ?? this.config.bucketSize, isRateLimited: false },
+ ])
+ }
+
+ return requests.map((req, index) => {
+ const [tokenRes] = getRedisPipelineResults(res, index, 1)
+ const tokensAfter = tokenRes[1]?.[1] ?? req.bucketSize ?? this.config.bucketSize
+ return [
+ req.id,
+ {
+ tokens: Number(tokensAfter),
+ isRateLimited: Number(tokensAfter) <= 0,
+ },
+ ]
+ })
+ }
+}
diff --git a/nodejs/src/ingestion/error-tracking/config.ts b/nodejs/src/ingestion/error-tracking/config.ts
index a6d34f503c6e..8c209cfdcefa 100644
--- a/nodejs/src/ingestion/error-tracking/config.ts
+++ b/nodejs/src/ingestion/error-tracking/config.ts
@@ -35,6 +35,23 @@ 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
+ /** Token bucket capacity (events per key burst). */
+ ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE: number
+ /** Token bucket replenish rate (events per second). */
+ ERROR_TRACKING_RATE_LIMITER_REFILL_RATE: number
+ /** TTL in seconds for the Redis bucket key. */
+ ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS: number
+
/** Pipeline name for metrics labeling */
INGESTION_PIPELINE: string | null
/** Lane identifier (main, overflow) for metrics labeling */
@@ -56,6 +73,14 @@ export function getDefaultErrorTrackingConsumerConfig(): ErrorTrackingConsumerCo
ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS: 300, // 5 minutes
ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS: 60, // 1 minute
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_BUCKET_SIZE: 100_000,
+ ERROR_TRACKING_RATE_LIMITER_REFILL_RATE: 1_000,
+ ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS: 86_400,
INGESTION_PIPELINE: null,
INGESTION_LANE: null,
}
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
index 7313ef6c4d1c..dd9efac9e795 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
@@ -156,6 +156,17 @@ describe('ErrorTrackingConsumer', () => {
statefulOverflowRedisTTLSeconds: hub.ERROR_TRACKING_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS,
statefulOverflowLocalCacheTTLSeconds: hub.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
pipeline: hub.INGESTION_PIPELINE ?? 'error_tracking',
+ rateLimiterEnabled: hub.ERROR_TRACKING_RATE_LIMITER_ENABLED,
+ rateLimiterReportingMode: hub.ERROR_TRACKING_RATE_LIMITER_REPORTING_MODE,
+ rateLimiterRedisHost: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_HOST,
+ rateLimiterRedisPort: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,
+ rateLimiterRedisTls: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,
+ rateLimiterBucketSize: hub.ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE,
+ rateLimiterRefillRate: hub.ERROR_TRACKING_RATE_LIMITER_REFILL_RATE,
+ rateLimiterTtlSeconds: hub.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
+ fallbackRedisUrl: hub.REDIS_URL,
+ rateLimiterRedisPoolMinSize: hub.REDIS_POOL_MIN_SIZE,
+ rateLimiterRedisPoolMaxSize: hub.REDIS_POOL_MAX_SIZE,
}
// Create and store the mock so tests can configure it
mockHogTransformer = createMockHogTransformer()
@@ -181,6 +192,12 @@ describe('ErrorTrackingConsumer', () => {
'test'
),
tophog: new SingleIngestionOutput('tophog', 'clickhouse_tophog_test', mockProducer, 'test'),
+ app_metrics: new SingleIngestionOutput(
+ 'app_metrics',
+ 'clickhouse_app_metrics2_test',
+ mockProducer,
+ 'test'
+ ),
}),
teamManager: hub.teamManager,
hogTransformer: mockHogTransformer,
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
index 4eabb6fe60de..1f65ea71550a 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
@@ -3,6 +3,9 @@ import { Redis } from 'ioredis'
import { Message } from 'node-rdkafka'
import { Counter, Gauge } from 'prom-client'
+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 { PluginEvent } from '~/plugin-scaffold'
@@ -26,9 +29,11 @@ import { CymbalClient } from './cymbal'
import {
ErrorTrackingOutputs,
ErrorTrackingPipelineOutput,
+ PreCymbalRateLimiterInput,
createErrorTrackingPipeline,
runErrorTrackingPipeline,
} from './error-tracking-pipeline'
+import { KeyedRateLimiterStepOptions } from './keyed-rate-limiter-step'
/**
* Configuration values for ErrorTrackingConsumer.
@@ -48,6 +53,19 @@ export interface ErrorTrackingConsumerOptions {
statefulOverflowRedisTTLSeconds: number
statefulOverflowLocalCacheTTLSeconds: number
pipeline: string
+ rateLimiterEnabled: boolean
+ rateLimiterReportingMode: boolean
+ rateLimiterRedisHost: string
+ rateLimiterRedisPort: number
+ rateLimiterRedisTls: boolean
+ rateLimiterBucketSize: number
+ rateLimiterRefillRate: number
+ rateLimiterTtlSeconds: 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
}
/**
@@ -104,6 +122,9 @@ export class ErrorTrackingConsumer {
protected overflowRedirectService?: OverflowRedirectService
protected overflowLaneTTLRefreshService?: OverflowRedirectService
protected topHog?: TopHog
+ protected rateLimiter?: KeyedRateLimiterService
+ protected rateLimiterAppMetricsAggregator?: AppMetricsAggregator
+ protected rateLimiterRedis?: RedisV2
constructor(
private config: ErrorTrackingConsumerOptions,
@@ -149,6 +170,39 @@ export class ErrorTrackingConsumer {
redisRepository: overflowRedisRepository,
})
}
+
+ // 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: config.rateLimiterBucketSize,
+ refillRate: config.rateLimiterRefillRate,
+ ttlSeconds: config.rateLimiterTtlSeconds,
+ },
+ this.rateLimiterRedis
+ )
+ this.rateLimiterAppMetricsAggregator = new AppMetricsAggregator(deps.outputs)
+ }
}
public get service(): PluginServerService {
@@ -206,18 +260,90 @@ export class ErrorTrackingConsumer {
overflowEnabled: this.config.overflowEnabled,
overflowRedirectService: this.overflowRedirectService,
overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,
+ preCymbalRateLimiters: this.buildPreCymbalRateLimiterSpecs(),
topHog: this.topHog,
})
logger.info('✅', `${this.name} - pipeline initialized`)
}
+ /**
+ * Construct the pre-Cymbal rate limiter spec list. Add new specs here as
+ * we extend rate limiting beyond the team-global limit (per-hash, per-event-name etc).
+ */
+ private buildPreCymbalRateLimiterSpecs(): KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[] {
+ if (!this.rateLimiter) {
+ return []
+ }
+
+ const specs: KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[] = [
+ // 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',
+ getKey: (input) => `${input.team.id}:exceptions:global`,
+ getTeamId: (input) => input.team.id,
+ reportingMode: this.config.rateLimiterReportingMode,
+ dropReason: 'rate_limited:team_global',
+ // TODO: Read per-team bucket overrides from a Team Extension model
+ // (e.g. ErrorTrackingTeamSettings.rate_limit_bucket_size /
+ // .rate_limit_refill_rate). When those columns are nullable and unset,
+ // fall back to the env-configured defaults baked into `this.rateLimiter`.
+ // Wiring would look like:
+ // getBucketConfig: (input) => {
+ // const settings = (input as { team: TeamWithErrorTrackingSettings }).team
+ // .error_tracking_settings
+ // return {
+ // bucketSize: settings?.rate_limit_bucket_size ?? undefined,
+ // refillRate: settings?.rate_limit_refill_rate ?? undefined,
+ // }
+ // },
+ },
+ // 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 specs
+ }
+
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()
@@ -259,7 +385,16 @@ 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()])
+ 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),
+ })
+ }),
+ ])
}
}
}
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts
index 639db136006f..424eb215d6ce 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts
@@ -292,6 +292,12 @@ describe('ErrorTrackingPipeline', () => {
dlq: new SingleIngestionOutput('dlq', 'error_tracking_dlq', mockKafkaProducer, 'test'),
overflow: new SingleIngestionOutput('overflow', 'error_tracking_overflow', mockKafkaProducer, 'test'),
tophog: new SingleIngestionOutput('tophog', 'clickhouse_tophog_test', mockKafkaProducer, 'test'),
+ app_metrics: new SingleIngestionOutput(
+ 'app_metrics',
+ 'clickhouse_app_metrics2_test',
+ mockKafkaProducer,
+ 'test'
+ ),
}),
groupId: 'error-tracking-test',
promiseScheduler,
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts
index 9805de74b315..ef99f9df0ec8 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts
@@ -1,5 +1,6 @@
import { Message } from 'node-rdkafka'
+import { PluginEvent } from '~/plugin-scaffold'
import { EventIngestionRestrictionManager } from '~/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/utils/promise-scheduler'
import { TeamManager } from '~/utils/team-manager'
@@ -7,6 +8,7 @@ import { GroupTypeManager } from '~/worker/ingestion/group-type-manager'
import { PersonRepository } from '~/worker/ingestion/persons/repositories/person-repository'
import {
+ AppMetricsOutput,
DlqOutput,
EVENTS_OUTPUT,
EventOutput,
@@ -29,6 +31,7 @@ import { createReadOnlyProcessGroupsStep } from '../event-processing/readonly-pr
import { IngestionOutputs } from '../outputs/ingestion-outputs'
import { BatchPipelineUnwrapper } from '../pipelines/batch-pipeline-unwrapper'
import { newBatchPipelineBuilder } from '../pipelines/builders'
+import { BatchPipelineBuilder } from '../pipelines/builders/batch-pipeline-builders'
import { TopHogRegistry, count, countOk, createTopHogWrapper } from '../pipelines/extensions/tophog'
import { createBatch, createUnwrapper } from '../pipelines/helpers'
import { PipelineConfig } from '../pipelines/result-handling-pipeline'
@@ -37,6 +40,7 @@ import { OverflowRedirectService } from '../utils/overflow-redirect/overflow-red
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 { createFetchPersonBatchStep } from './person-properties-step'
import { createErrorTrackingPrepareEventStep } from './prepare-event-step'
@@ -52,7 +56,7 @@ export interface ErrorTrackingPipelineInput {
export type ErrorTrackingPipelineOutput = void
export type ErrorTrackingOutputs = IngestionOutputs<
- EventOutput | IngestionWarningsOutput | DlqOutput | OverflowOutput | TophogOutput
+ EventOutput | IngestionWarningsOutput | DlqOutput | OverflowOutput | TophogOutput | AppMetricsOutput
>
export interface ErrorTrackingPipelineConfig {
@@ -70,10 +74,40 @@ export interface ErrorTrackingPipelineConfig {
overflowRedirectService?: OverflowRedirectService
/** Service for refreshing TTLs on overflow lane events. */
overflowLaneTTLRefreshService?: OverflowRedirectService
+ /**
+ * Rate limiter step specs to apply pre-Cymbal. Each becomes its own batch step in
+ * the pipeline, run in array order. Empty / undefined → no rate limiting.
+ *
+ * Pre-Cymbal placement saves symbolication cost on dropped events. If a future
+ * limiter needs Cymbal-derived data (e.g. the proper exception fingerprint), add
+ * a `postCymbalRateLimiters` slot rather than reorder this one.
+ */
+ preCymbalRateLimiters?: KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[]
/** TopHog registry for metrics. */
topHog: TopHogRegistry
}
+/**
+ * Shape consumed by pre-Cymbal rate limiter step specs. The pipeline guarantees these
+ * fields are present at the insertion point (after team resolution, before Cymbal).
+ */
+export interface PreCymbalRateLimiterInput {
+ team: { id: number }
+ event: PluginEvent
+}
+
+/**
+ * Apply each rate limiter spec as its own pre-Cymbal batch step. The chain's TOutput
+ * is wider than the spec's input type, but `KeyedRateLimiterStepOptions<T>` is
+ * contravariant in T, so a narrower spec assigns into the wider chain context.
+ */
+function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends string>(
+ builder: BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R>,
+ specs: KeyedRateLimiterStepOptions<TOutput>[]
+): BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {
+ return specs.reduce((b, spec) => b.pipeBatch(createKeyedRateLimiterStep(spec)), builder)
+}
+
/**
* Creates the error tracking pipeline.
*
@@ -115,6 +149,7 @@ export function createErrorTrackingPipeline(
overflowEnabled,
overflowRedirectService,
overflowLaneTTLRefreshService,
+ preCymbalRateLimiters,
topHog,
} = config
@@ -165,9 +200,13 @@ export function createErrorTrackingPipeline(
}),
(b) =>
b
- .teamAware((b) =>
- b
- .gather()
+ .teamAware((b) => {
+ // Pre-Cymbal rate limit chain runs FIRST so that events we'd drop
+ // never consume overflow-redirect cycles or symbolication budget.
+ // Each spec becomes its own batch step, applied in array order.
+ // Empty / undefined → no-op.
+ const afterRateLimit = applyKeyedRateLimiters(b.gather(), preCymbalRateLimiters ?? [])
+ const preCymbal = afterRateLimit
// Rate limit high-volume token:distinct_id pairs to overflow
.pipeBatch(
createRateLimitToOverflowStep(
@@ -177,46 +216,50 @@ export function createErrorTrackingPipeline(
)
// Refresh TTLs for overflow lane events (keeps Redis flags alive)
.pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
- // Process through Cymbal as a batch (before enrichment - Cymbal only
- // needs raw exception data, not person/geoip/group data).
- // Retry on transient failures (5xx, timeout, network errors).
- // 10 tries with 100ms base sleep and 2x backoff (capped at 10s)
- // gives ~30s total budget to ride out a Cymbal restart.
- .pipeBatchWithRetry(createCymbalProcessingStep(cymbalClient), {
- tries: 10,
- sleepMs: 100,
- })
- // Enrich, prepare, create, and emit events
- // Batch fetch person (read-only, no updates)
- .pipeBatch(createFetchPersonBatchStep(personRepository))
- .sequentially((b) =>
- b
- // Run Hog transformations (including GeoIP if team has it enabled)
- .pipe(createHogTransformEventStep(hogTransformer))
- // Prepare event for emission
- .pipe(createErrorTrackingPrepareEventStep())
- // Map group types to indexes (read-only, no new group types created)
- .pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
- .pipe(createCreateEventStep(EVENTS_OUTPUT))
- .pipe(
- topHogWrapper(
- createEmitEventStep({
- outputs,
- groupId,
- }),
- [
- count('emitted_events', (input) => ({
- team_id: String(input.teamId),
- })),
- count('emitted_events_per_distinct_id', (input) => ({
- team_id: String(input.teamId),
- distinct_id: input.eventsToEmit[0]?.event.distinct_id ?? '',
- })),
- ]
+ return (
+ preCymbal
+ // Process through Cymbal as a batch (before enrichment - Cymbal only
+ // needs raw exception data, not person/geoip/group data).
+ // Retry on transient failures (5xx, timeout, network errors).
+ // 10 tries with 100ms base sleep and 2x backoff (capped at 10s)
+ // gives ~30s total budget to ride out a Cymbal restart.
+ .pipeBatchWithRetry(createCymbalProcessingStep(cymbalClient), {
+ tries: 10,
+ sleepMs: 100,
+ })
+ // Enrich, prepare, create, and emit events
+ // Batch fetch person (read-only, no updates)
+ .pipeBatch(createFetchPersonBatchStep(personRepository))
+ .sequentially((b) =>
+ b
+ // Run Hog transformations (including GeoIP if team has it enabled)
+ .pipe(createHogTransformEventStep(hogTransformer))
+ // Prepare event for emission
+ .pipe(createErrorTrackingPrepareEventStep())
+ // Map group types to indexes (read-only, no new group types created)
+ .pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
+ .pipe(createCreateEventStep(EVENTS_OUTPUT))
+ .pipe(
+ topHogWrapper(
+ createEmitEventStep({
+ outputs,
+ groupId,
+ }),
+ [
+ count('emitted_events', (input) => ({
+ team_id: String(input.teamId),
+ })),
+ count('emitted_events_per_distinct_id', (input) => ({
+ team_id: String(input.teamId),
+ distinct_id:
+ input.eventsToEmit[0]?.event.distinct_id ?? '',
+ })),
+ ]
+ )
)
- )
- )
- )
+ )
+ )
+ })
.handleIngestionWarnings(outputs)
)
)
diff --git a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.test.ts b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.test.ts
new file mode 100644
index 000000000000..883ff343ab40
--- /dev/null
+++ b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.test.ts
@@ -0,0 +1,211 @@
+import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
+import {
+ KeyedRateLimit,
+ KeyedRateLimitRequest,
+ KeyedRateLimiterService,
+} from '~/common/services/keyed-rate-limiter.service'
+
+import { isDropResult, isOkResult } from '../pipelines/results'
+import { createKeyedRateLimiterStep } from './keyed-rate-limiter-step'
+
+type Input = { teamId: number; key: string | null; cost?: number; bucketOverride?: number }
+
+const mkLimiter = (decisions: Record<string, boolean>): KeyedRateLimiterService =>
+ ({
+ rateLimitMany: jest.fn((requests: KeyedRateLimitRequest[]) => {
+ return Promise.resolve(
+ requests.map(({ id }): [string, KeyedRateLimit] => [
+ id,
+ { tokens: decisions[id] ? 0 : 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 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.rateLimitMany).not.toHaveBeenCalled()
+ })
+
+ it('aggregates cost per unique key in a single Redis call', async () => {
+ const limiter = mkLimiter({})
+ const step = createKeyedRateLimiterStep<Input>(baseOpts({ rateLimiter: limiter }))
+
+ await step([
+ { teamId: 1, key: 'k1', cost: 3 },
+ { teamId: 1, key: 'k1', cost: 4 },
+ { teamId: 2, key: 'k2', cost: 5 },
+ ])
+
+ expect(limiter.rateLimitMany).toHaveBeenCalledTimes(1)
+ const calledWith = (limiter.rateLimitMany as jest.Mock).mock.calls[0][0] as KeyedRateLimitRequest[]
+ const byId = Object.fromEntries(calledWith.map((req) => [req.id, req.cost]))
+ expect(byId).toEqual({ k1: 7, k2: 5 })
+ })
+
+ it('forwards per-input bucket config overrides to the limiter (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' }, // no override
+ ])
+
+ const requests = (limiter.rateLimitMany as jest.Mock).mock.calls[0][0] as KeyedRateLimitRequest[]
+ const byId = Object.fromEntries(requests.map((req) => [req.id, req]))
+ expect(byId.k1).toMatchObject({ id: 'k1', bucketSize: 5, refillRate: 1 })
+ expect(byId.k2.bucketSize).toBeUndefined()
+ expect(byId.k2.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('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' }])
+
+ // No throws and limiter was still called.
+ expect(limiter.rateLimitMany).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/error-tracking/keyed-rate-limiter-step.ts b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
new file mode 100644
index 000000000000..f70a3a769cc8
--- /dev/null
+++ b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
@@ -0,0 +1,147 @@
+import { Counter } from 'prom-client'
+
+import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
+import { KeyedRateLimitRequest, KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'
+
+import { BatchProcessingStep } from '../pipelines/base-batch-pipeline'
+import { drop, ok } from '../pipelines/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?: KeyedRateLimiterService
+ /** 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
+ /** 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>): BatchProcessingStep<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))
+ }
+
+ // Per-input key (null means "skip this input"). Cost summed per unique key
+ // so we issue exactly one Redis call per key — same pattern as logs-rate-limiter.
+ // Bucket config (if provided) snapshots the first input per key — all inputs in
+ // a key group are expected to agree (e.g. team-keyed limits all share a team).
+ const keyForInput: (string | null)[] = new Array(inputs.length)
+ const requestByKey = new Map<string, KeyedRateLimitRequest>()
+
+ for (let i = 0; i < inputs.length; i++) {
+ const key = opts.getKey(inputs[i])
+ keyForInput[i] = key
+ if (key === null) {
+ continue
+ }
+ const inputCost = costFn(inputs[i])
+ const existing = requestByKey.get(key)
+ if (existing) {
+ existing.cost += inputCost
+ } else {
+ const overrides = opts.getBucketConfig?.(inputs[i]) ?? {}
+ requestByKey.set(key, { id: key, cost: inputCost, ...overrides })
+ }
+ }
+
+ const limitedKeys = new Set<string>()
+ if (requestByKey.size > 0) {
+ const rateLimitResults = await opts.rateLimiter.rateLimitMany(Array.from(requestByKey.values()))
+ for (const [key, result] of rateLimitResults) {
+ if (result.isRateLimited) {
+ limitedKeys.add(key)
+ }
+ }
+ }
+
+ // Aggregate outcomes per (team, key, outcome) so we emit one app_metrics2
+ // row per unique tuple regardless of input volume in this batch.
+ const outcomeBuckets = new Map<
+ string,
+ { teamId: number; key: string; outcome: RateLimitOutcome; count: number }
+ >()
+ for (let i = 0; i < inputs.length; i++) {
+ const key = keyForInput[i]
+ if (key === null) {
+ continue
+ }
+ const outcome: RateLimitOutcome = limitedKeys.has(key) ? 'rate_limited' : 'allowed'
+ outcomeCounter.inc({ app_source: opts.appSource, outcome, reporting_mode: reportingModeLabel })
+
+ if (opts.appMetricsAggregator) {
+ const teamId = opts.getTeamId(inputs[i])
+ const bucketKey = `${teamId}|${key}|${outcome}`
+ const existing = outcomeBuckets.get(bucketKey)
+ if (existing) {
+ existing.count++
+ } else {
+ outcomeBuckets.set(bucketKey, { teamId, key, outcome, count: 1 })
+ }
+ }
+ }
+
+ if (opts.appMetricsAggregator) {
+ for (const { teamId, key, outcome, count } of outcomeBuckets.values()) {
+ opts.appMetricsAggregator.queue({
+ team_id: teamId,
+ app_source: opts.appSource,
+ app_source_id: key,
+ metric_kind: 'rate_limiting',
+ metric_name: outcome,
+ count,
+ })
+ }
+ }
+
+ return inputs.map((input, i) => {
+ const key = keyForInput[i]
+ if (key === null || !limitedKeys.has(key) || opts.reportingMode) {
+ return ok(input)
+ }
+ return drop<T>(dropReason)
+ })
+ }
+}
diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.ts
index 13065001ef5f..822ea4e6042a 100644
--- a/nodejs/src/servers/error-tracking-server.ts
+++ b/nodejs/src/servers/error-tracking-server.ts
@@ -203,6 +203,17 @@ export class ErrorTrackingServer implements NodeServer {
statefulOverflowLocalCacheTTLSeconds:
this.config.ERROR_TRACKING_STATEFUL_OVERFLOW_LOCAL_CACHE_TTL_SECONDS,
pipeline: this.config.INGESTION_PIPELINE ?? 'error_tracking',
+ 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,
+ rateLimiterBucketSize: this.config.ERROR_TRACKING_RATE_LIMITER_BUCKET_SIZE,
+ rateLimiterRefillRate: this.config.ERROR_TRACKING_RATE_LIMITER_REFILL_RATE,
+ rateLimiterTtlSeconds: this.config.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
+ fallbackRedisUrl: this.config.REDIS_URL,
+ rateLimiterRedisPoolMinSize: this.config.REDIS_POOL_MIN_SIZE,
+ rateLimiterRedisPoolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
},
{
outputs,