Skip to content

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

feat: error tracking per issue guard (#60325)

Aleksander Błaszkiewicza11699749252
diff --git a/nodejs/src/common/redis/redis-token-bucket-guarded.lua.ts b/nodejs/src/common/redis/redis-token-bucket-guarded.lua.ts
new file mode 100644
index 000000000000..ba7af287ece6
--- /dev/null
+++ b/nodejs/src/common/redis/redis-token-bucket-guarded.lua.ts
@@ -0,0 +1,102 @@
+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 0051667edad6..9a130b9ebe3d 100644
--- a/nodejs/src/common/redis/redis-v2.ts
+++ b/nodejs/src/common/redis/redis-v2.ts
@@ -5,18 +5,33 @@ import { RedisPoolConfig, createRedisFromConfig } from '../../utils/db/redis'
import { timeoutGuard } from '../../utils/db/utils'
import { logger } from '../../utils/logger'
import { captureException } from '../../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> = {
+type WithCheckRateLimit<TV2, TV3, TGuarded> = {
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]>
+export type RedisClientPipeline = Pipeline &
+ WithCheckRateLimit<[number, number], [number, number], [number, number, number]>
export type RedisClient = Omit<Redis, 'pipeline'> &
- WithCheckRateLimit<Promise<[number, number]>, Promise<[number, number]>> & {
+ WithCheckRateLimit<Promise<[number, number]>, Promise<[number, number]>, Promise<[number, number, number]>> & {
pipeline: () => RedisClientPipeline
}
@@ -42,6 +57,7 @@ export const createRedisV2PoolFromConfig = (config: RedisPoolConfig): RedisV2 =>
defineLuaTokenBucketV2(client)
defineLuaTokenBucketV3(client)
+ defineLuaTokenBucketGuarded(client)
return client as RedisClient
},
diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.ts b/nodejs/src/common/services/keyed-rate-limiter.service.ts
index be816ee0de2e..196c28eec56d 100644
--- a/nodejs/src/common/services/keyed-rate-limiter.service.ts
+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts
@@ -31,6 +31,8 @@ export interface KeyedRateLimiterConfig {
export interface KeyedRateLimitRequest {
id: string
cost: number
+ /** Used by guard-style limiters to scope per-team state. Ignored by the base service. */
+ teamId?: number
bucketSize?: number
refillRate?: number
ttlSeconds?: number
@@ -46,12 +48,24 @@ export type KeyedRateLimit = {
isRateLimited: boolean
}
+export interface KeyedRateLimiter {
+ /**
+ * Rate-limit a batch of requests.
+ *
+ * Contract: the resolved array is a 1:1 positional mapping to `requests` —
+ * same length, exactly one decision per input request, in input order.
+ * Callers (e.g. `createKeyedRateLimiterStep`) correlate results by index, so
+ * implementations must not deduplicate, group, or reorder the returned array.
+ */
+ rateLimitGrouped(requests: KeyedRateLimitRequest[]): Promise<[string, KeyedRateLimit][]>
+}
+
const buildKeyPrefix = (name: string): string => {
const root = process.env.NODE_ENV === 'test' ? '@posthog-test' : '@posthog'
return `${root}/${name}/tokens`
}
-export class KeyedRateLimiterService {
+export class KeyedRateLimiterService implements KeyedRateLimiter {
private readonly keyPrefix: string
constructor(
diff --git a/nodejs/src/ingestion/error-tracking/config.ts b/nodejs/src/ingestion/error-tracking/config.ts
index 78b97347a45b..badeed4a670d 100644
--- a/nodejs/src/ingestion/error-tracking/config.ts
+++ b/nodejs/src/ingestion/error-tracking/config.ts
@@ -58,6 +58,14 @@ export type ErrorTrackingConsumerConfig = {
/** 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 */
@@ -86,6 +94,9 @@ export function getDefaultErrorTrackingConsumerConfig(): ErrorTrackingConsumerCo
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,
}
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 e8617411baac..8db575f2f603 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
@@ -166,6 +166,9 @@ describe('ErrorTrackingConsumer', () => {
rateLimiterRedisPort: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_PORT,
rateLimiterRedisTls: hub.ERROR_TRACKING_RATE_LIMITER_REDIS_TLS,
rateLimiterTtlSeconds: hub.ERROR_TRACKING_RATE_LIMITER_TTL_SECONDS,
+ perIssueGuardThreshold: hub.ERROR_TRACKING_PER_ISSUE_GUARD_THRESHOLD,
+ perIssueGuardWindowTtlSeconds: hub.ERROR_TRACKING_PER_ISSUE_GUARD_WINDOW_TTL_SECONDS,
+ perIssueGuardCooldownTtlSeconds: hub.ERROR_TRACKING_PER_ISSUE_GUARD_COOLDOWN_TTL_SECONDS,
fallbackRedisUrl: hub.REDIS_URL,
rateLimiterRedisPoolMinSize: hub.REDIS_POOL_MIN_SIZE,
rateLimiterRedisPoolMaxSize: hub.REDIS_POOL_MAX_SIZE,
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
index 12db3fcc982a..9c4496475813 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
@@ -36,6 +36,7 @@ import {
runErrorTrackingPipeline,
} from './error-tracking-pipeline'
import { KeyedRateLimiterStepOptions } from './keyed-rate-limiter-step'
+import { PerIssueGuardedRateLimiterService } from './per-issue-guarded-rate-limiter.service'
import { preCymbalGroupKey } from './pre-cymbal-group-key'
/**
@@ -68,6 +69,9 @@ export interface ErrorTrackingConsumerOptions {
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. */
@@ -133,6 +137,7 @@ export class ErrorTrackingConsumer {
protected overflowLaneTTLRefreshService?: OverflowRedirectService
protected topHog?: TopHog
protected rateLimiter?: KeyedRateLimiterService
+ protected perIssueGuardedRateLimiter?: PerIssueGuardedRateLimiterService
protected rateLimiterAppMetricsAggregator?: AppMetricsAggregator
protected rateLimiterRedis?: RedisV2
@@ -211,6 +216,16 @@ export class ErrorTrackingConsumer {
},
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)
}
}
@@ -280,29 +295,26 @@ export class ErrorTrackingConsumer {
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).
- */
+ /** Per-issue spec uses the guarded service; team-global spec uses the base service. */
private buildPreCymbalRateLimiterSpecs(): KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[] {
- if (!this.rateLimiter) {
+ if (!this.rateLimiter || !this.perIssueGuardedRateLimiter) {
return []
}
- const specs: KeyedRateLimiterStepOptions<PreCymbalRateLimiterInput>[] = [
+ 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.rateLimiter,
+ rateLimiter: this.perIssueGuardedRateLimiter,
appMetricsAggregator: this.rateLimiterAppMetricsAggregator,
appSource: 'exceptions',
getKey: (input) => {
if (input.errorTrackingSettings?.perIssueRateLimitValue == null) {
return null
}
- const sig = preCymbalGroupKey(input.event)
- return sig ? `${input.team.id}:exceptions:issue:${sig}` : null
+ const scopeKey = preCymbalGroupKey(input.event)
+ return scopeKey ? `${input.team.id}:exceptions:issue:${scopeKey}` : null
},
getTeamId: (input) => input.team.id,
reportingMode: this.config.rateLimiterReportingMode,
@@ -346,8 +358,6 @@ export class ErrorTrackingConsumer {
},
},
]
-
- return specs
}
public async stop(): Promise<void> {
diff --git a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
index 1485cfc3015f..dbb56bc8a499 100644
--- a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
+++ b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
@@ -1,7 +1,7 @@
import { Counter } from 'prom-client'
import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
-import { KeyedRateLimitRequest, KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'
+import { KeyedRateLimitRequest, KeyedRateLimiter } from '~/common/services/keyed-rate-limiter.service'
import { BatchProcessingStep } from '../pipelines/base-batch-pipeline'
import { drop, ok } from '../pipelines/results'
@@ -16,7 +16,7 @@ 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
+ 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'). */
@@ -85,6 +85,7 @@ export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<
requestIndexForInput[i] = perInputRequests.length
perInputRequests.push({
id: key,
+ teamId: opts.getTeamId(inputs[i]),
cost: costFn(inputs[i]),
...bucketConfigByKey.get(key),
})
diff --git a/nodejs/src/ingestion/error-tracking/per-issue-guarded-rate-limiter.service.test.ts b/nodejs/src/ingestion/error-tracking/per-issue-guarded-rate-limiter.service.test.ts
new file mode 100644
index 000000000000..a1556d2ee6e0
--- /dev/null
+++ b/nodejs/src/ingestion/error-tracking/per-issue-guarded-rate-limiter.service.test.ts
@@ -0,0 +1,343 @@
+import { register } from 'prom-client'
+
+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
+import { KeyedRateLimitRequest } from '~/common/services/keyed-rate-limiter.service'
+import { Hub } from '~/types'
+import { closeHub, createHub } from '~/utils/db/hub'
+import { logger } from '~/utils/logger'
+
+import { deleteKeysWithPrefix } from '../../cdp/_tests/redis'
+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 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 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('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.getKeyPrefix()}/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.getKeyPrefix()}/100:exceptions:issue:cooldown-1`)).toBe(0)
+ expect(await bucketExists(`${limiter.getKeyPrefix()}/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.getKeyPrefix()}/200:exceptions:issue:tripA`)).toBe(1)
+ expect(await bucketExists(`${limiter.getKeyPrefix()}/200:exceptions:issue:tripB`)).toBe(1)
+ expect(await bucketExists(`${limiter.getKeyPrefix()}/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/error-tracking/per-issue-guarded-rate-limiter.service.ts b/nodejs/src/ingestion/error-tracking/per-issue-guarded-rate-limiter.service.ts
new file mode 100644
index 000000000000..974a315d8ee1
--- /dev/null
+++ b/nodejs/src/ingestion/error-tracking/per-issue-guarded-rate-limiter.service.ts
@@ -0,0 +1,208 @@
+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 '~/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
+ }
+
+ 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}`
+ }
+
+ /** 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.prefixes.bucket}/${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 f154bab74b7e..64b8666bb0de 100644
--- a/nodejs/src/servers/error-tracking-server.ts
+++ b/nodejs/src/servers/error-tracking-server.ts
@@ -228,6 +228,9 @@ export class ErrorTrackingServer implements NodeServer {
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,