:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(cdp): remove rateLimitMany from keyed rate limiter (#58760)
posthog[bot]3d0f68d4d790
diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex d3a393cc49ef..7dc1f64e5751 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -147,7 +147,7 @@ export class CdpEventsConsumer<cost: 1,}))const [rateLimits] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)}),mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>@@ -317,7 +317,7 @@ export class CdpEventsConsumer<cost: 1,}))const [rateLimits] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)}),mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>diff --git a/nodejs/src/common/services/keyed-rate-limiter.bench.test.ts b/nodejs/src/common/services/keyed-rate-limiter.bench.test.tsdeleted file mode 100644index 32123e175317..000000000000--- a/nodejs/src/common/services/keyed-rate-limiter.bench.test.ts+++ /dev/null@@ -1,190 +0,0 @@-/**- * Benchmark — `rateLimitMany` (V2 pipelined per-call) vs `rateLimitGrouped`- * (V3 pipelined + coalesced) on `KeyedRateLimiterService`. Mirrors what the- * production primary (rateLimitMany) and mirror (rateLimitGrouped) paths- * actually do.- *- * Runs against the local docker-compose Redis (or wherever `createHub`'s- * Redis points). Skipped by default — set `RUN_BENCHMARKS=1` to opt in.- *- * RUN_BENCHMARKS=1 hogli test nodejs/src/common/services/keyed-rate-limiter.bench.test.ts --forceExit- *- * Knobs via env vars:- * BENCH_BATCHES default 100 batch invocations per run- * BENCH_EVENTS_PER_BATCH default 200 events per batch (per call)- * BENCH_UNIQUE_FUNCTIONS default 50 unique ids in the batch- *- * What it measures:- * - Wall-clock time + ops/sec for each path.- * - Redis-side `INFO commandstats` delta per command (calls, total μs, μs/call).- * - Reduction percentages in the summary.- *- * What it asserts (light — perf varies by host):- * - rateLimitGrouped fires strictly fewer Redis commands than rateLimitMany.- * - rateLimitGrouped spends strictly fewer total Redis-side μs.- */-import { Hub } from '~/types'-import { closeHub, createHub } from '~/utils/db/hub'--import { deleteKeysWithPrefix } from '../../cdp/_tests/redis'-import { RedisV2, createRedisV2PoolFromConfig } from '../redis/redis-v2'-import { KeyedRateLimitRequest, KeyedRateLimiterService } from './keyed-rate-limiter.service'--const BATCHES = Number(process.env.BENCH_BATCHES ?? 100)-const EVENTS_PER_BATCH = Number(process.env.BENCH_EVENTS_PER_BATCH ?? 200)-const UNIQUE_FUNCTIONS = Number(process.env.BENCH_UNIQUE_FUNCTIONS ?? 50)-const TRACKED = ['evalsha', 'hget', 'hmget', 'hset', 'expire', 'pexpire', 'pttl', 'ttl']--type CommandStats = Map<string, { calls: number; usec: number; rejected: number }>--const benchDescribe = process.env.RUN_BENCHMARKS ? describe : describe.skip--benchDescribe('benchmark: KeyedRateLimiterService rateLimitMany vs rateLimitGrouped', () => {- let hub: Hub- let redis: RedisV2- let limiter: KeyedRateLimiterService-- beforeAll(async () => {- hub = await createHub()- 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: 1,- poolMaxSize: 4,- })- limiter = new KeyedRateLimiterService(- { name: 'bench', bucketSize: 10000, refillRate: 10, ttlSeconds: 60 * 60 * 24 },- redis- )- })-- afterAll(async () => {- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- await closeHub(hub)- })-- const buildWorkload = (): KeyedRateLimitRequest[][] => {- const ids = Array.from({ length: UNIQUE_FUNCTIONS }, (_, i) => `bench-${i.toString().padStart(4, '0')}`)- return Array.from({ length: BATCHES }, () =>- Array.from({ length: EVENTS_PER_BATCH }, () => ({- id: ids[Math.floor(Math.random() * ids.length)],- cost: 1,- }))- )- }-- const readCommandStats = async (): Promise<CommandStats> => {- const stats: CommandStats = new Map()- const raw = await redis.useClient({ name: 'info' }, async (client) => client.info('commandstats'))- if (!raw) {- return stats- }- for (const line of raw.split('\n')) {- const m = /^cmdstat_([a-z|]+):calls=(\d+),usec=(\d+).*?rejected_calls=(\d+)/.exec(line.trim())- if (!m) {- continue- }- const [, cmd, calls, usec, rejected] = m- stats.set(cmd, { calls: Number(calls), usec: Number(usec), rejected: Number(rejected) })- }- return stats- }-- const diffStats = (before: CommandStats, after: CommandStats): CommandStats => {- const out: CommandStats = new Map()- for (const cmd of TRACKED) {- const a = after.get(cmd) ?? { calls: 0, usec: 0, rejected: 0 }- const b = before.get(cmd) ?? { calls: 0, usec: 0, rejected: 0 }- out.set(cmd, { calls: a.calls - b.calls, usec: a.usec - b.usec, rejected: a.rejected - b.rejected })- }- return out- }-- const printRun = (label: string, wallMs: number, stats: CommandStats) => {- const totalCalls = TRACKED.reduce((s, c) => s + (stats.get(c)?.calls ?? 0), 0)- const totalUsec = TRACKED.reduce((s, c) => s + (stats.get(c)?.usec ?? 0), 0)- const opsPerSec = ((BATCHES * EVENTS_PER_BATCH) / wallMs) * 1000-- console.log(`\n=== ${label} ===`)- console.log(`wall: ${wallMs.toFixed(1)} ms (${opsPerSec.toFixed(0)} events/s)`)- console.log(`redis-side: ${totalCalls.toLocaleString()} commands, ${totalUsec.toLocaleString()} μs`)- console.log(`per-command:`)- for (const cmd of TRACKED) {- const s = stats.get(cmd)- if (!s || s.calls === 0) {- continue- }- const usecPerCall = s.calls > 0 ? (s.usec / s.calls).toFixed(2) : '-'- console.log(- ` ${cmd.padEnd(8)} ${s.calls.toLocaleString().padStart(10)} calls, ${s.usec- .toLocaleString()- .padStart(10)} μs (${usecPerCall} μs/call)`- )- }- }-- const runOne = async (- label: string,- method: 'rateLimitMany' | 'rateLimitGrouped',- workload: KeyedRateLimitRequest[][]- ): Promise<{ wallMs: number; stats: CommandStats }> => {- // Warm-up so script load + connection establish aren't part of the measurement.- await limiter[method]([{ id: 'warmup', cost: 1 }])- await redis.useClient({ name: 'reset' }, async (client) => client.config('RESETSTAT'))-- const before = await readCommandStats()- const start = process.hrtime.bigint()- for (const batch of workload) {- await limiter[method](batch)- }- const end = process.hrtime.bigint()- const after = await readCommandStats()-- const wallMs = Number(end - start) / 1e6- const stats = diffStats(before, after)- printRun(label, wallMs, stats)- return { wallMs, stats }- }-- it('rateLimitGrouped reduces Redis commands and CPU vs rateLimitMany', async () => {- console.log(`Workload: ${BATCHES} batches × ${EVENTS_PER_BATCH} events × ${UNIQUE_FUNCTIONS} unique fns`)-- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const workload = buildWorkload()-- const many = await runOne('rateLimitMany (V2 pipelined per-call)', 'rateLimitMany', workload)- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const grouped = await runOne('rateLimitGrouped (V3 + coalesced)', 'rateLimitGrouped', workload)-- const totalManyCalls = TRACKED.reduce((s, c) => s + (many.stats.get(c)?.calls ?? 0), 0)- const totalGroupedCalls = TRACKED.reduce((s, c) => s + (grouped.stats.get(c)?.calls ?? 0), 0)- const totalManyUsec = TRACKED.reduce((s, c) => s + (many.stats.get(c)?.usec ?? 0), 0)- const totalGroupedUsec = TRACKED.reduce((s, c) => s + (grouped.stats.get(c)?.usec ?? 0), 0)-- console.log(`\n=== Summary ===`)- console.log(- `Wall time: Many ${many.wallMs.toFixed(1)} ms → Grouped ${grouped.wallMs.toFixed(1)} ms (${(- many.wallMs / grouped.wallMs- ).toFixed(2)}× faster)`- )- console.log(- `Redis cmds: Many ${totalManyCalls.toLocaleString()} → Grouped ${totalGroupedCalls.toLocaleString()} (${(- (1 - totalGroupedCalls / totalManyCalls) *- 100- ).toFixed(1)}% reduction)`- )- console.log(- `Redis CPU (μs): Many ${totalManyUsec.toLocaleString()} → Grouped ${totalGroupedUsec.toLocaleString()} (${(- (1 - totalGroupedUsec / totalManyUsec) *- 100- ).toFixed(1)}% reduction)`- )-- expect(totalGroupedCalls).toBeLessThan(totalManyCalls)- expect(totalGroupedUsec).toBeLessThan(totalManyUsec)- }, 120_000)-})diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts b/nodejs/src/common/services/keyed-rate-limiter.service.test.tsindex 1a2e97eda30d..e60b675e872c 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts@@ -63,12 +63,12 @@ describe('KeyedRateLimiterService', () => {return result ?? { ts: null, pool: null }}- describe('rateLimitMany (V2 pipelined per-call)', () => {+ describe('rateLimitGrouped', () => {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 }])+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])expect(res).toEqual([['team-1', { tokens: 99, isRateLimited: false }]])})@@ -77,13 +77,13 @@ describe('KeyedRateLimiterService', () => {const limiter = buildLimiter('test-exceed')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 99 }])+ let res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 99 }])expect(res[0][1]).toEqual({ tokens: 1, isRateLimited: false })- res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])+ res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])expect(res[0][1]).toEqual({ tokens: 0, isRateLimited: true })- res = await limiter.rateLimitMany([{ id: 'team-1', cost: 20 }])+ res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 20 }])expect(res[0][1].isRateLimited).toBe(true)})@@ -91,11 +91,11 @@ describe('KeyedRateLimiterService', () => {const limiter = buildLimiter('test-refill')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 50 }])+ let res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 50 }])expect(res[0][1].tokens).toBe(50)advanceTime(1000)- res = await limiter.rateLimitMany([{ id: 'team-1', cost: 0 }])+ res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 0 }])expect(res[0][1].tokens).toBe(60)})@@ -103,7 +103,7 @@ describe('KeyedRateLimiterService', () => {const limiter = buildLimiter('test-multi')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const res = await limiter.rateLimitMany([+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 },{ id: 'team-2', cost: 5 },])@@ -120,12 +120,12 @@ describe('KeyedRateLimiterService', () => {await deleteKeysWithPrefix(redis, limiterA.getKeyPrefix())await deleteKeysWithPrefix(redis, limiterB.getKeyPrefix())- await limiterA.rateLimitMany([{ id: 'shared-id', cost: 100 }])- const drainedA = await limiterA.rateLimitMany([{ id: 'shared-id', cost: 1 }])+ await limiterA.rateLimitGrouped([{ id: 'shared-id', cost: 100 }])+ const drainedA = await limiterA.rateLimitGrouped([{ 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 }])+ const freshB = await limiterB.rateLimitGrouped([{ id: 'shared-id', cost: 1 }])expect(freshB[0][1]).toEqual({ tokens: 99, isRateLimited: false })})@@ -134,50 +134,21 @@ describe('KeyedRateLimiterService', () => {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(),- 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')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 }])+ const res = await limiter.rateLimitGrouped([{ id: 'tiny-team', cost: 6, bucketSize: 5, refillRate: 1 }])expect(res[0][1].isRateLimited).toBe(true)})- // The following tests are migrated from redis-token-bucket-v2.lua.test.ts —- // they exercise the V2 lua via the keyed service rather than the raw client.-it('returns -1 when first cost exceeds pool size', async () => {const limiter = buildLimiter('test-first-exceed')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 150 }])+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 150 }])expect(res[0][1].tokens).toBe(-1)expect(res[0][1].isRateLimited).toBe(true)})@@ -186,99 +157,21 @@ describe('KeyedRateLimiterService', () => {const limiter = buildLimiter('test-cost-zero')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- await limiter.rateLimitMany([{ id: 'team-1', cost: 30 }])- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 0 }])+ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 30 }])+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 0 }])expect(res[0][1].tokens).toBe(70)})- it('allows a single catch-up call to spend more than poolMax (PR 57920)', async () => {- const limiter = buildLimiter('test-catchup')- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())-- await limiter.rateLimitMany([{ id: 'team-1', cost: 100 }]) // pool=0- advanceTime(20_000) // 20s × 10/s = 200 accrued credit- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 199 }])- // Spent 199 of the accrued 200; stored pool capped at poolMax (=100).- expect(res[0][1]).toEqual({ tokens: 1, isRateLimited: false })- })-it('still rate-limits when a catch-up cost exceeds accrued credit', async () => {const limiter = buildLimiter('test-catchup-exceeds')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- await limiter.rateLimitMany([{ id: 'team-1', cost: 100 }]) // pool=0+ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 100 }]) // pool=0advanceTime(5_000) // 5s × 10/s = 50 accrued- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 60 }])+ const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 60 }])expect(res[0][1].isRateLimited).toBe(true)})- it('threads state through pipelined repeats of the same id', async () => {- const limiter = buildLimiter('test-thread')- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())-- // After call 3 (cost=2) is denied with pool=1, the bucket retains its 1- // token — leftover budget shouldn't be discarded just because a request- // overshot. So call 4 (cost=1) can spend it and lands at tokens=0.- const res = await limiter.rateLimitMany([- { id: 'team-1', cost: 90 },- { id: 'team-1', cost: 9 },- { id: 'team-1', cost: 2 },- { id: 'team-1', cost: 1 },- ])-- expect(res).toEqual([- ['team-1', { tokens: 10, isRateLimited: false }],- ['team-1', { tokens: 1, isRateLimited: false }],- ['team-1', { tokens: -1, isRateLimited: true }],- ['team-1', { tokens: 0, isRateLimited: true }],- ])- })-- // Regression for the V2 lua wedge: with sub-2 fractional fillRates, V2 used to- // store -1 in `pool` on every denial, which threw away the fractional refill- // that had just accrued. Subsequent 1 req/s calls would re-read -1, accrue the- // fillRate, fail to afford cost=1, and re-clamp to -1 — wedged forever. The fix- // keeps the public return contract (`tokensAfter = -1` on denial) but stores the- // un-clamped balance so partial refills accumulate across calls.- it('recovers from overdraft under sustained sub-2 fillRate (V2 wedge regression)', async () => {- const limiter = buildLimiter('test-v2-wedge', { bucketSize: 10, refillRate: 1.5 })- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())-- // Drain into denial: 100 cost-1 calls against a 10-token bucket.- let lastDuringDrain = 0- for (let i = 0; i < 100; i++) {- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- lastDuringDrain = res[0][1].tokens- }- expect(lastDuringDrain).toBe(-1)-- // 1 req/s with refillRate=1.5 should recover within ~10s.- let lastAfterRecovery = -1- for (let i = 0; i < 10; i++) {- advanceTime(1000)- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- lastAfterRecovery = res[0][1].tokens- }- expect(lastAfterRecovery).toBeGreaterThanOrEqual(0)- })-- it('refreshes the V2 TTL on every call', async () => {- const limiter = buildLimiter('test-v2-ttl', { ttlSeconds: 60 })- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const key = `${limiter.getKeyPrefix()}/team-1`-- await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- // Bump the TTL way down; the next call should refresh it back to ttlSeconds.- await redis.useClient({ name: 'pexpire' }, async (client) => await client.pexpire(key, 5_000))-- await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- const ttl = await redis.useClient({ name: 'ttl-check' }, async (client) => await client.ttl(key))- expect(ttl).toBeGreaterThan(5)- expect(ttl).toBeLessThanOrEqual(60)- })- })-- describe('rateLimitGrouped (V3 + coalesced + per-input fan-out)', () => {it('returns one decision per input request (parallel to input order)', async () => {const limiter = buildLimiter('grouped-shape')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())@@ -296,10 +189,9 @@ 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. `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.const limiter = buildLimiter('grouped-fanout', { bucketSize: 4, refillRate: 0 })await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())@@ -321,27 +213,6 @@ 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())@@ -365,7 +236,7 @@ describe('KeyedRateLimiterService', () => {})it('issues exactly one Redis dispatch per unique id (call-count win)', async () => {- // 10 cost-1 requests for the same id → 1 evalsha (vs 10 with rateLimitMany).+ // 10 cost-1 requests for the same id → 1 evalsha.const limiter = buildLimiter('grouped-dispatch-count')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.ts b/nodejs/src/common/services/keyed-rate-limiter.service.tsindex f12420e605b9..cea6c5697712 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts@@ -71,66 +71,13 @@ export class KeyedRateLimiterService {return [`${this.keyPrefix}/${req.id}`, nowSeconds, req.cost, bucketSize, refillRate, ttlSeconds]}- public async rateLimitMany(requests: KeyedRateLimitRequest[]): Promise<[string, KeyedRateLimit][]> {- if (requests.length === 0) {- return []- }-- const bucketSizes = requests.map((req) => {- const bucketSize = req.bucketSize ?? this.config.bucketSize- if (bucketSize == null) {- throw new Error(`KeyedRateLimiterService(${this.config.name}): missing bucketSize for ${req.id}`)- }- return bucketSize- })-- const res = await this.redis.usePipeline(- { name: `keyed-rate-limiter:${this.config.name}`, failOpen: true },- (pipeline) => {- requests.forEach((req) => {- pipeline.checkRateLimitV2(...this.rateLimitArgs(req))- })- }- )-- redisCallsTotal.inc({ name: this.config.name, method: 'rateLimitMany' }, requests.length)-- if (!res) {- // failOpen — Redis blipped; allow everything rather than dropping ingestion.- requestsTotal.inc({ name: this.config.name, method: 'rateLimitMany', outcome: 'allowed' }, requests.length)- return requests.map((req, i) => [req.id, { tokens: bucketSizes[i], isRateLimited: false }])- }-- let allowed = 0- let limited = 0- const out: [string, KeyedRateLimit][] = requests.map((req, index) => {- const [tokenRes] = getRedisPipelineResults(res, index, 1)- const tokensAfter = tokenRes[1]?.[1] ?? bucketSizes[index]- const isRateLimited = Number(tokensAfter) <= 0- if (isRateLimited) {- limited++- } else {- allowed++- }- return [req.id, { tokens: Number(tokensAfter), isRateLimited }]- })- if (allowed > 0) {- requestsTotal.inc({ name: this.config.name, method: 'rateLimitMany', outcome: 'allowed' }, allowed)- }- if (limited > 0) {- requestsTotal.inc({ name: this.config.name, method: 'rateLimitMany', outcome: 'limited' }, limited)- }- return out- }-/**- * 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.+ * Token-bucket rate limit decision for a batch of requests. N inputs across+ * M unique ids dispatch only M Redis calls — per-input decisions are fanned+ * out client-side from each id's `tokensBefore`. Per-id bucket params come+ * from the first request seen for that id.** Uses the V3 lua script (HMGET + multi-field HSET + conditional EXPIRE).- * 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) {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.tsindex 883ff343ab40..8ad0c668028e 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@@ -12,7 +12,7 @@ type Input = { teamId: number; key: string | null; cost?: number; bucketOverrideconst mkLimiter = (decisions: Record<string, boolean>): KeyedRateLimiterService =>({- rateLimitMany: jest.fn((requests: KeyedRateLimitRequest[]) => {+ rateLimitGrouped: jest.fn((requests: KeyedRateLimitRequest[]) => {return Promise.resolve(requests.map(({ id }): [string, KeyedRateLimit] => [id,@@ -103,7 +103,7 @@ describe('createKeyedRateLimiterStep', () => {])expect(results.every(isOkResult)).toBe(true)- expect(limiter.rateLimitMany).not.toHaveBeenCalled()+ expect(limiter.rateLimitGrouped).not.toHaveBeenCalled()})it('aggregates cost per unique key in a single Redis call', async () => {@@ -116,8 +116,8 @@ describe('createKeyedRateLimiterStep', () => {{ teamId: 2, key: 'k2', cost: 5 },])- expect(limiter.rateLimitMany).toHaveBeenCalledTimes(1)- const calledWith = (limiter.rateLimitMany as jest.Mock).mock.calls[0][0] as KeyedRateLimitRequest[]+ 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 })})@@ -138,7 +138,7 @@ describe('createKeyedRateLimiterStep', () => {{ teamId: 2, key: 'k2' }, // no override])- const requests = (limiter.rateLimitMany as jest.Mock).mock.calls[0][0] as KeyedRateLimitRequest[]+ 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()@@ -190,7 +190,7 @@ describe('createKeyedRateLimiterStep', () => {await step([{ teamId: 1, key: 'a' }])// No throws and limiter was still called.- expect(limiter.rateLimitMany).toHaveBeenCalled()+ expect(limiter.rateLimitGrouped).toHaveBeenCalled()})it('uses the configured dropReason', async () => {diff --git a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.tsindex f70a3a769cc8..12c5e638f476 100644--- a/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts+++ b/nodejs/src/ingestion/error-tracking/keyed-rate-limiter-step.ts@@ -89,7 +89,7 @@ export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<const limitedKeys = new Set<string>()if (requestByKey.size > 0) {- const rateLimitResults = await opts.rateLimiter.rateLimitMany(Array.from(requestByKey.values()))+ const rateLimitResults = await opts.rateLimiter.rateLimitGrouped(Array.from(requestByKey.values()))for (const [key, result] of rateLimitResults) {if (result.isRateLimited) {limitedKeys.add(key)