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.

fix: v3 lua script sub2 refill rate (#59829)

Aleksander Błaszkiewicz0b0d80e0cf58
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts
index 655ca4f56515..9e286d224890 100644
--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts
@@ -224,13 +224,13 @@ describe('HogWatcher', () => {
await watcher.observeResults(lotsOfResults)
- // V3 lua deducts past the bucket on overshoot, so the persisted pool sentinel is -1.
- // The state machine is driven by the rate-limiter return (-1 on denial), so
- // `state: 3` (disabled) is correct.
+ // V3 lua floor-drains on overdraft, so the persisted pool lands at 0.
+ // The state machine is driven by the rate-limiter return (tokens=-1 on the
+ // denied per-input results inside observeResults), so `state: 3` (disabled).
expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`
{
"state": 3,
- "tokens": -1,
+ "tokens": 0,
}
`)
@@ -300,12 +300,13 @@ describe('HogWatcher', () => {
await watcher.clearLock(hogFunctionId) // For testing the logic
await watcher.observeResults(Array(100).fill(createResult({ duration: 1000, kind: 'hog' })))
- // Final batch denies (cost > available); V3 lua deducts past the bucket, so pool
- // lands at -1 and the state transition fires from the rate limiter return.
+ // Final batch overdraws; V3 lua floor-drains the available tokens, so the
+ // stored pool lands at 0. State transition fires from the rate limiter
+ // return (tokens=-1 on the denied per-input tail).
expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`
{
"state": 3,
- "tokens": -1,
+ "tokens": 0,
}
`)
expect(onStateChangeSpy).toHaveBeenCalledTimes(2) // New state change
@@ -321,12 +322,12 @@ describe('HogWatcher', () => {
watcher = new HogWatcherService(hub.teamManager, watcherConfig, redis)
onStateChangeSpy = jest.spyOn(watcher as any, 'onStateChange') as jest.SpyInstance
await watcher.observeResults(Array(1000).fill(createResult({ duration: 1000, kind: 'hog' })))
- // Cold-start denial: V3 lua deducts past the bucket, leaving the pool at -1.
- // The state transition fires from the rate-limiter return.
+ // Cold-start denial: V3 lua floor-drains to 0. State transition fires
+ // from the rate-limiter return (tokens=-1 on denied per-input results).
expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`
{
"state": 2,
- "tokens": -1,
+ "tokens": 0,
}
`)
expect(onStateChangeSpy).toHaveBeenCalledTimes(1)
@@ -342,20 +343,20 @@ describe('HogWatcher', () => {
it('should not automatically transition out of disabled', async () => {
await watcher.observeResults(Array(1000).fill(createResult({ duration: 1000, kind: 'hog' })))
- // V3 lua deducts past the bucket on denied overshoot, leaving the pool at -1.
- // State persists at 3 (disabled) because state writes are independent of pool writes.
+ // V3 lua floor-drains on overdraft → pool=0. State persists at 3
+ // (disabled) because state writes are independent of pool writes.
expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`
{
"state": 3,
- "tokens": -1,
+ "tokens": 0,
}
`)
advanceTime(1000)
- // Refill from -1 at refillRate=10 over 1s.
+ // Refill from 0 at refillRate=10 over 1s.
expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`
{
"state": 3,
- "tokens": 9,
+ "tokens": 10,
}
`)
@@ -364,7 +365,7 @@ describe('HogWatcher', () => {
expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`
{
"state": 3,
- "tokens": 19,
+ "tokens": 20,
}
`)
expect(onStateChangeSpy).toHaveBeenCalledTimes(1)
diff --git a/nodejs/src/common/redis/redis-token-bucket-v3.lua.ts b/nodejs/src/common/redis/redis-token-bucket-v3.lua.ts
index fbe7e61f9957..2fdf0977973f 100644
--- a/nodejs/src/common/redis/redis-token-bucket-v3.lua.ts
+++ b/nodejs/src/common/redis/redis-token-bucket-v3.lua.ts
@@ -13,8 +13,9 @@ import { Redis } from 'ioredis'
// per call; we save ~95% of EXPIRE dispatches. Stale keys live 2x
// longer in exchange.
//
-// Public output (tokensBefore, tokensAfter) and stored-field semantics are
-// identical to V2; only the TTL ceiling and refresh cadence differ.
+// Public return matches V2 (tokensAfter=-1 on denial). Stored-pool on overdraft
+// differs: V3 floor-drains the available tokens and keeps the fractional remainder
+// so refill accumulates cross-batch (V2 preserved the full pre-overdraft balance).
const LUA_TOKEN_BUCKET_V3 = `
local key = KEYS[1]
local now = tonumber(ARGV[1])
@@ -50,11 +51,19 @@ else
tokensBefore = currentTokens + (timeDiffSeconds * fillRate)
end
+-- On overdraft, drain floor(max(0, tokensBefore)) and keep the fractional remainder
+-- in the pool. Assumes per-input cost is an integer (≥1) — the fraction can never
+-- satisfy one input, so we let it accumulate cross-batch instead of getting wiped
+-- each call (which would starve everything under sustained overload).
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
-- Don't regress ts when now < before; otherwise advance to now.
@@ -65,7 +74,7 @@ else
tsToWrite = now
end
-redis.call('hset', key, 'ts', tsToWrite, 'pool', tokensAfter)
+redis.call('hset', key, 'ts', tsToWrite, 'pool', poolToStore)
-- Set TTL ceiling at (expiry * 2) on creation, then refresh when remaining
-- TTL drops below expiry/2. PTTL returns -1 (no TTL) and -2 (missing key)
diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts
index f3b172e9424e..feacfdcdc280 100644
--- a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts
+++ b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts
@@ -259,7 +259,7 @@ describe('KeyedRateLimiterService', () => {
const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])
lastAfterRecovery = res[0][1].tokens
}
- expect(lastAfterRecovery).toBeGreaterThanOrEqual(0)
+ expect(lastAfterRecovery).toBeGreaterThanOrEqual(4)
})
it('refreshes the V2 TTL on every call', async () => {
@@ -296,10 +296,10 @@ describe('KeyedRateLimiterService', () => {
})
it('allows the first N inputs of an over-budget batch and denies the rest', async () => {
- // The user case: 10 cost-1 requests against a bucket of 4. Per the
- // V2/V3 contract, `isRateLimited = tokens <= 0`, so the 4th request
- // (which brings tokens to exactly 0) is flagged as rate-limited
- // even though its cost was paid. The remaining 6 hit tokens=-1.
+ // 10 cost-1 requests against a bucket of 4. JS fan-out walks tokensBefore=4,
+ // allowing the first 4 (last one lands at next=0, which is allowed under the
+ // < 0 boundary so the lua's floor-drained token actually passes an input).
+ // Remaining 6 see budget=0 < 1 and deny.
const limiter = buildLimiter('grouped-fanout', { bucketSize: 4, refillRate: 0 })
await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
@@ -311,7 +311,7 @@ describe('KeyedRateLimiterService', () => {
false,
false,
false,
- true, // tokens=0 — boundary, flagged as rate-limited
+ false,
true,
true,
true,
@@ -321,36 +321,13 @@ describe('KeyedRateLimiterService', () => {
])
})
- it('per-input decisions match rateLimitMany for uniform-cost batches', async () => {
- const ungrouped = buildLimiter('grouped-vs-many-a')
- const grouped = buildLimiter('grouped-vs-many-b')
- await deleteKeysWithPrefix(redis, ungrouped.getKeyPrefix())
- await deleteKeysWithPrefix(redis, grouped.getKeyPrefix())
-
- // 200 events for 50 ids — realistic CDP shape.
- const ids = Array.from({ length: 50 }, (_, i) => `fn-${i}`)
- const requests = Array.from({ length: 200 }, () => ({
- id: ids[Math.floor(Math.random() * ids.length)],
- cost: 1,
- }))
-
- const manyRes = await ungrouped.rateLimitMany(requests)
- const groupedRes = await grouped.rateLimitGrouped(requests)
-
- // Same length, same id ordering, same isRateLimited flags.
- expect(groupedRes.map(([id]) => id)).toEqual(manyRes.map(([id]) => id))
- expect(groupedRes.map(([, r]) => r.isRateLimited)).toEqual(manyRes.map(([, r]) => r.isRateLimited))
- })
-
it('keeps independent budgets per id', async () => {
const limiter = buildLimiter('grouped-multi-id', { bucketSize: 2, refillRate: 0 })
await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
- // Two ids interleaved with 3 cost-1 requests each. Each id's budget
- // of 2 fits its 1st request cleanly (tokens=1), depletes on the 2nd
- // (tokens=0 → rate-limited boundary), and denies the 3rd (tokens=-1).
- // If the budgets were shared, t2's first call would already be
- // rate-limited because t1 would have drained the shared bucket.
+ // Two ids interleaved with 3 cost-1 requests each. Each id's budget of 2
+ // fits the first two cost-1 requests (allowed) and denies the third. If
+ // budgets were shared, team-2's first call would already be denied.
const res = await limiter.rateLimitGrouped([
{ id: 'team-1', cost: 1 },
{ id: 'team-2', cost: 1 },
@@ -361,7 +338,7 @@ describe('KeyedRateLimiterService', () => {
])
expect(res.map(([, r]) => r.tokens)).toEqual([1, 1, 0, 0, -1, -1])
- expect(res.map(([, r]) => r.isRateLimited)).toEqual([false, false, true, true, true, true])
+ expect(res.map(([, r]) => r.isRateLimited)).toEqual([false, false, false, false, true, true])
})
it('issues exactly one Redis dispatch per unique id (call-count win)', async () => {
@@ -496,5 +473,38 @@ describe('KeyedRateLimiterService', () => {
expect(stored.ts).toBe(String(Math.round(now / 1000)))
expect(stored.pool).toBe('95')
})
+
+ it('recovers from overdraft under sustained sub-2 fillRate (V3 wedge regression)', async () => {
+ const limiter = buildLimiter('grouped-v3-wedge', { bucketSize: 10, refillRate: 1.5 })
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ let lastDuringDrain = 0
+ for (let i = 0; i < 100; i++) {
+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])
+ lastDuringDrain = res[0][1].tokens
+ }
+ expect(lastDuringDrain).toBe(-1)
+
+ let lastAfterRecovery = -1
+ for (let i = 0; i < 10; i++) {
+ advanceTime(1000)
+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])
+ lastAfterRecovery = res[0][1].tokens
+ }
+ expect(lastAfterRecovery).toBeGreaterThanOrEqual(4)
+ })
+
+ it('drains the bucket on overdraft so the next batch sees an empty pool', async () => {
+ const limiter = buildLimiter('grouped-drain', { bucketSize: 100, refillRate: 0 })
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+ const key = `${limiter.getKeyPrefix()}/team-1`
+
+ const requests = Array.from({ length: 200 }, () => ({ id: 'team-1', cost: 1 }))
+ await limiter.rateLimitGrouped(requests)
+ expect((await readBucket(key)).pool).toBe('0')
+
+ const next = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])
+ expect(next[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
index 0468efa86d1a..be816ee0de2e 100644
--- a/nodejs/src/common/services/keyed-rate-limiter.service.ts
+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts
@@ -137,13 +137,12 @@ export class KeyedRateLimiterService {
}
/**
- * Coalesced variant of rateLimitMany. Same input/output shape, but N inputs
- * across M unique ids dispatch only M Redis calls — per-input decisions are
- * fanned out client-side from each id's `tokensBefore`. For uniform-cost
- * batches the per-input decisions match rateLimitMany exactly.
+ * Coalesced variant of rateLimitMany — N inputs across M unique ids → M Redis calls.
+ * Per-input decisions fan out client-side from each id's `tokensBefore`.
*
- * Uses the V3 lua script (HMGET + multi-field HSET + conditional EXPIRE).
- * Per-id bucket params come from the first request seen for that id.
+ * Boundary differs from rateLimitMany: an input whose cost lands exactly on
+ * the local budget (`next === 0`) is allowed here, rate-limited there. Per-id
+ * bucket params come from the first request seen for that id.
*/
public async rateLimitGrouped(requests: KeyedRateLimitRequest[]): Promise<[string, KeyedRateLimit][]> {
if (requests.length === 0) {
@@ -209,16 +208,13 @@ export class KeyedRateLimiterService {
let limited = 0
const out: [string, KeyedRateLimit][] = requests.map((req) => {
const tokensBefore = budgetById.get(req.id) ?? 0
+ // Boundary is `next < 0`, not `<= 0` — needed so the lua's floor-drain of
+ // one token under sustained overload actually lets that input through.
if (tokensBefore >= req.cost) {
const next = tokensBefore - req.cost
budgetById.set(req.id, next)
- const isRateLimited = next <= 0
- if (isRateLimited) {
- limited++
- } else {
- allowed++
- }
- return [req.id, { tokensBefore, tokens: next, isRateLimited }]
+ allowed++
+ return [req.id, { tokensBefore, tokens: next, isRateLimited: false }]
}
limited++
return [req.id, { tokensBefore, tokens: -1, isRateLimited: true }]
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
index e3fb12c74344..ff6cb677d7f6 100644
--- a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.test.ts
+++ b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.test.ts
@@ -10,13 +10,14 @@ 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] ? 0 : 99, isRateLimited: !!decisions[id] },
+ { tokensBefore: 100, tokens: decisions[id] ? -1 : 99, isRateLimited: !!decisions[id] },
])
)
}),
@@ -77,6 +78,41 @@ describe('createKeyedRateLimiterStep', () => {
}
})
+ 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({
@@ -106,23 +142,7 @@ describe('createKeyedRateLimiterStep', () => {
expect(limiter.rateLimitGrouped).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.rateLimitGrouped).toHaveBeenCalledTimes(1)
- const calledWith = (limiter.rateLimitGrouped 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 () => {
+ it('forwards per-input bucket config overrides snapshotted from first input per key', async () => {
const limiter = mkLimiter({})
const step = createKeyedRateLimiterStep<Input>(
baseOpts({
@@ -135,14 +155,14 @@ describe('createKeyedRateLimiterStep', () => {
await step([
{ teamId: 1, key: 'k1', bucketOverride: 5 },
{ teamId: 1, key: 'k1', bucketOverride: 999 }, // ignored — first wins
- { teamId: 2, key: 'k2' }, // no override
+ { teamId: 2, key: 'k2' },
])
const requests = (limiter.rateLimitGrouped 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()
+ 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 () => {
@@ -189,7 +209,6 @@ describe('createKeyedRateLimiterStep', () => {
await step([{ teamId: 1, key: 'a' }])
- // No throws and limiter was still called.
expect(limiter.rateLimitGrouped).toHaveBeenCalled()
})
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 12c5e638f476..1485cfc3015f 100644
--- a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
+++ b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts
@@ -64,12 +64,14 @@ export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<
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>()
+ 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])
@@ -77,28 +79,28 @@ export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<
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 })
+ if (!bucketConfigByKey.has(key)) {
+ bucketConfigByKey.set(key, opts.getBucketConfig?.(inputs[i]) ?? {})
}
+ requestIndexForInput[i] = perInputRequests.length
+ perInputRequests.push({
+ id: key,
+ cost: costFn(inputs[i]),
+ ...bucketConfigByKey.get(key),
+ })
}
- const limitedKeys = new Set<string>()
- if (requestByKey.size > 0) {
- const rateLimitResults = await opts.rateLimiter.rateLimitGrouped(Array.from(requestByKey.values()))
- for (const [key, result] of rateLimitResults) {
- if (result.isRateLimited) {
- limitedKeys.add(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
}
}
- // 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 }
@@ -108,7 +110,7 @@ export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<
if (key === null) {
continue
}
- const outcome: RateLimitOutcome = limitedKeys.has(key) ? 'rate_limited' : 'allowed'
+ const outcome: RateLimitOutcome = limitedForInput[i] ? 'rate_limited' : 'allowed'
outcomeCounter.inc({ app_source: opts.appSource, outcome, reporting_mode: reportingModeLabel })
if (opts.appMetricsAggregator) {
@@ -138,7 +140,7 @@ export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<
return inputs.map((input, i) => {
const key = keyForInput[i]
- if (key === null || !limitedKeys.has(key) || opts.reportingMode) {
+ if (key === null || !limitedForInput[i] || opts.reportingMode) {
return ok(input)
}
return drop<T>(dropReason)
diff --git a/nodejs/src/ingestion/error-tracking/rate-limiter-e2e.test.ts b/nodejs/src/ingestion/error-tracking/rate-limiter-e2e.test.ts
new file mode 100644
index 000000000000..78fd2c1bec50
--- /dev/null
+++ b/nodejs/src/ingestion/error-tracking/rate-limiter-e2e.test.ts
@@ -0,0 +1,94 @@
+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
+import { KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'
+import { Hub } from '~/types'
+import { closeHub, createHub } from '~/utils/db/hub'
+
+import { deleteKeysWithPrefix } from '../../cdp/_tests/redis'
+
+const mockNow: jest.SpyInstance = jest.spyOn(Date, 'now')
+
+// E2E for the ET team-global rate limit: 100 events per 15 minutes, sustained 10 ev/sec.
+// Real Redis, real V3 lua (post floor-drain fix), real per-input fan-out — proves that:
+// - the initial burst of 100 passes,
+// - sustained overload drains the bucket to ~0 and starves new events,
+// - refill accumulates cross-batch (V3 lua's floor-drain preserves the fractional remainder),
+// - over the 15-minute window we admit roughly bucketSize burst + bucketSize refill (~2x bucketSize).
+describe('error tracking — sustained traffic e2e', () => {
+ jest.retryTimes(2)
+
+ let now: number
+ let hub: Hub
+ let redis: RedisV2
+
+ const advanceTime = (ms: number) => {
+ now += ms
+ mockNow.mockReturnValue(now)
+ }
+
+ beforeEach(async () => {
+ hub = await createHub()
+ now = 1720000000000
+ mockNow.mockReturnValue(now)
+ redis = createRedisV2PoolFromConfig({
+ connection: hub.CDP_REDIS_HOST
+ ? {
+ url: hub.CDP_REDIS_HOST,
+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },
+ }
+ : { url: hub.REDIS_URL },
+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,
+ })
+ })
+
+ afterEach(async () => {
+ await closeHub(hub)
+ jest.clearAllMocks()
+ })
+
+ it('100 per 15min: bursts 100 immediately, then admits ~bucketSize more across the window', async () => {
+ const bucketSize = 100
+ const minutes = 15
+ const refillRate = bucketSize / (minutes * 60) // ~0.111 / sec
+ const limiter = new KeyedRateLimiterService(
+ { name: 'et-e2e-sustained', bucketSize, refillRate, ttlSeconds: 60 * 60 },
+ redis
+ )
+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())
+
+ // Sustained 10 ev/sec as one batch of 10 per second — same fan-out as 10
+ // singleton calls but 10× fewer Redis round-trips.
+ const eventsPerBatch = 10
+ const totalSeconds = minutes * 60
+ const batchIntervalMs = 1000
+
+ let totalAllowed = 0
+ let firstBurstAllowed = 0
+ let seenFirstStarve = false
+
+ for (let s = 0; s < totalSeconds; s++) {
+ const res = await limiter.rateLimitGrouped(
+ Array.from({ length: eventsPerBatch }, () => ({ id: 'team-1', cost: 1 }))
+ )
+ const allowed = res.filter(([, r]) => !r.isRateLimited).length
+ totalAllowed += allowed
+ // The first ten seconds carry the burst (bucketSize=100 / eventsPerBatch=10).
+ if (s < bucketSize / eventsPerBatch) {
+ firstBurstAllowed += allowed
+ }
+ if (s >= bucketSize / eventsPerBatch && allowed === 0 && !seenFirstStarve) {
+ seenFirstStarve = true
+ }
+ advanceTime(batchIntervalMs)
+ }
+
+ // The first bucketSize events all pass (initial burst).
+ expect(firstBurstAllowed).toBe(bucketSize)
+ // After the burst, the bucket drains and we hit the starvation window.
+ expect(seenFirstStarve).toBe(true)
+ // Over 15 minutes: bucketSize burst + bucketSize refill = 2 × bucketSize total.
+ // Allow ±5 slack for fractional boundary edge cases.
+ expect(totalAllowed).toBeGreaterThanOrEqual(2 * bucketSize - 5)
+ expect(totalAllowed).toBeLessThanOrEqual(2 * bucketSize + 5)
+ }, 30000)
+})