: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
feat(logs): Moved logs rate limiter over to the shared one (#58000)
Ben Whited50efae64eab
diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts b/nodejs/src/common/services/keyed-rate-limiter.service.test.tsindex e60b675e872c..f3b172e9424e 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts@@ -63,27 +63,27 @@ describe('KeyedRateLimiterService', () => {return result ?? { ts: null, pool: null }}- describe('rateLimitGrouped', () => {+ describe('rateLimitMany (V2 pipelined per-call)', () => {it('uses tokens for an id', async () => {const limiter = buildLimiter('test-basic')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])+ const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- expect(res).toEqual([['team-1', { tokens: 99, isRateLimited: false }]])+ expect(res).toEqual([['team-1', { tokensBefore: 100, 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.rateLimitGrouped([{ id: 'team-1', cost: 99 }])- expect(res[0][1]).toEqual({ tokens: 1, isRateLimited: false })+ let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 99 }])+ expect(res[0][1]).toEqual({ tokensBefore: 100, tokens: 1, isRateLimited: false })- 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: 1 }])+ expect(res[0][1]).toEqual({ tokensBefore: 1, tokens: 0, isRateLimited: true })- res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 20 }])+ res = await limiter.rateLimitMany([{ 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.rateLimitGrouped([{ id: 'team-1', cost: 50 }])+ let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 50 }])expect(res[0][1].tokens).toBe(50)advanceTime(1000)- res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 0 }])+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 0 }])expect(res[0][1].tokens).toBe(60)})@@ -103,14 +103,14 @@ describe('KeyedRateLimiterService', () => {const limiter = buildLimiter('test-multi')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- const res = await limiter.rateLimitGrouped([+ 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 }],+ ['team-1', { tokensBefore: 100, tokens: 99, isRateLimited: false }],+ ['team-2', { tokensBefore: 100, tokens: 95, isRateLimited: false }],])})@@ -120,13 +120,13 @@ describe('KeyedRateLimiterService', () => {await deleteKeysWithPrefix(redis, limiterA.getKeyPrefix())await deleteKeysWithPrefix(redis, limiterB.getKeyPrefix())- await limiterA.rateLimitGrouped([{ id: 'shared-id', cost: 100 }])- const drainedA = await limiterA.rateLimitGrouped([{ id: 'shared-id', cost: 1 }])+ 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.rateLimitGrouped([{ id: 'shared-id', cost: 1 }])- expect(freshB[0][1]).toEqual({ tokens: 99, isRateLimited: false })+ const freshB = await limiterB.rateLimitMany([{ id: 'shared-id', cost: 1 }])+ expect(freshB[0][1]).toEqual({ tokensBefore: 100, tokens: 99, isRateLimited: false })})it('uses test-prefixed redis keys when NODE_ENV=test', () => {@@ -134,21 +134,50 @@ 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', { tokensBefore: 50, tokens: 50, isRateLimited: false }],+ ['b', { tokensBefore: 50, 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.rateLimitGrouped([{ id: 'tiny-team', cost: 6, bucketSize: 5, refillRate: 1 }])+ const res = await limiter.rateLimitMany([{ 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.rateLimitGrouped([{ id: 'team-1', cost: 150 }])+ const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 150 }])expect(res[0][1].tokens).toBe(-1)expect(res[0][1].isRateLimited).toBe(true)})@@ -157,21 +186,99 @@ describe('KeyedRateLimiterService', () => {const limiter = buildLimiter('test-cost-zero')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- await limiter.rateLimitGrouped([{ id: 'team-1', cost: 30 }])- const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 0 }])+ await limiter.rateLimitMany([{ id: 'team-1', cost: 30 }])+ const res = await limiter.rateLimitMany([{ 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({ tokensBefore: 200, 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.rateLimitGrouped([{ id: 'team-1', cost: 100 }]) // pool=0+ await limiter.rateLimitMany([{ id: 'team-1', cost: 100 }]) // pool=0advanceTime(5_000) // 5s × 10/s = 50 accrued- const res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 60 }])+ const res = await limiter.rateLimitMany([{ 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 V2 wedge fix means the+ // bucket retains its 1 token — leftover budget isn't discarded on denial. 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', { tokensBefore: 100, tokens: 10, isRateLimited: false }],+ ['team-1', { tokensBefore: 10, tokens: 1, isRateLimited: false }],+ ['team-1', { tokensBefore: 1, tokens: -1, isRateLimited: true }],+ ['team-1', { tokensBefore: 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 (`tokens = -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())@@ -189,9 +296,10 @@ describe('KeyedRateLimiterService', () => {})it('allows the first N inputs of an over-budget batch and denies the rest', async () => {- // 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.+ // 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.const limiter = buildLimiter('grouped-fanout', { bucketSize: 4, refillRate: 0 })await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())@@ -213,6 +321,27 @@ 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())@@ -236,7 +365,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.+ // 10 cost-1 requests for the same id → 1 evalsha (vs 10 with rateLimitMany).const limiter = buildLimiter('grouped-dispatch-count')await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())@@ -281,6 +410,26 @@ describe('KeyedRateLimiterService', () => {expect(res.every(([, r]) => !r.isRateLimited)).toBe(true)})+ // Earlier shape seeded budgetById = bucketSize and then ran the fan-out, so+ // any id whose total request count exceeded bucketSize was rate-limited under+ // fail-open. This regression locks in the all-allowed behavior even when the+ // batch dwarfs the bucket.+ it('allows every request under fail-open even when batch size exceeds bucketSize', async () => {+ const limiter = new KeyedRateLimiterService(+ { name: 'grouped-fail-open-overflow', bucketSize: 100, refillRate: 1, ttlSeconds: 60 },+ {+ useClient: jest.fn(),+ usePipeline: jest.fn().mockResolvedValue(null),+ } as unknown as RedisV2+ )++ const requests = Array.from({ length: 200 }, () => ({ id: 'team-1', cost: 1 }))+ const res = await limiter.rateLimitGrouped(requests)++ expect(res).toHaveLength(200)+ expect(res.every(([, r]) => !r.isRateLimited)).toBe(true)+ })+// V3-specific behavior — migrated from redis-token-bucket-v3.lua.test.ts.it('exposes uncapped accrued credit (PR 57920 contract)', async () => {@@ -291,7 +440,7 @@ describe('KeyedRateLimiterService', () => {advanceTime(20_000) // 20s × 10/s = 200 accruedconst res = await limiter.rateLimitGrouped([{ id: 'team-1', cost: 199 }])// Catch-up call redeems 199 of the 200 accrued credit.- expect(res).toEqual([['team-1', { tokens: 1, isRateLimited: false }]])+ expect(res).toEqual([['team-1', { tokensBefore: 200, tokens: 1, isRateLimited: false }]])})it('sets TTL to 2x ttlSeconds on creation (V3 ceiling)', async () => {diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.ts b/nodejs/src/common/services/keyed-rate-limiter.service.tsindex cea6c5697712..0468efa86d1a 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts@@ -24,6 +24,8 @@ export interface KeyedRateLimiterConfig {bucketSize?: numberrefillRate?: numberttlSeconds?: number+ /** When false, throw if the Redis pipeline returns null instead of fail-open allowing all. Default: true (fail open). */+ failOpen?: boolean}export interface KeyedRateLimitRequest {@@ -32,9 +34,14 @@ export interface KeyedRateLimitRequest {bucketSize?: numberrefillRate?: numberttlSeconds?: number+ /** Override the request timestamp (seconds). Default: `Math.round(Date.now() / 1000)`. Used for lag-aware rate limiting where the timestamp comes from message headers. */+ now?: number}export type KeyedRateLimit = {+ /** Pre-deduction token count — uncapped accrued credit (PR 57920 contract). */+ tokensBefore: number+ /** Post-deduction token count. -1 when the cost exceeded the available budget. */tokens: numberisRateLimited: boolean}@@ -59,7 +66,7 @@ export class KeyedRateLimiterService {}private rateLimitArgs(req: KeyedRateLimitRequest): [string, number, number, number, number, number] {- const nowSeconds = Math.round(Date.now() / 1000)+ const nowSeconds = req.now ?? Math.round(Date.now() / 1000)const bucketSize = req.bucketSize ?? this.config.bucketSizeconst refillRate = req.refillRate ?? this.config.refillRateconst ttlSeconds = req.ttlSeconds ?? this.config.ttlSeconds@@ -71,13 +78,72 @@ 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) {+ if (this.config.failOpen === false) {+ throw new Error(`KeyedRateLimiterService(${this.config.name}): rate-limit pipeline failed`)+ }+ requestsTotal.inc({ name: this.config.name, method: 'rateLimitMany', outcome: 'allowed' }, requests.length)+ return requests.map((req, i) => [+ req.id,+ { tokensBefore: bucketSizes[i], 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 tokensBefore = Number(tokenRes[1]?.[0] ?? bucketSizes[index])+ const tokensAfter = Number(tokenRes[1]?.[1] ?? bucketSizes[index])+ const isRateLimited = tokensAfter <= 0+ if (isRateLimited) {+ limited+++ } else {+ allowed+++ }+ return [req.id, { tokensBefore, tokens: 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+ }+/**- * 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.+ * 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.** 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) {@@ -114,23 +180,37 @@ export class KeyedRateLimiterService {redisCallsTotal.inc({ name: this.config.name, method: 'rateLimitGrouped' }, items.length)+ if (!res) {+ if (this.config.failOpen === false) {+ throw new Error(`KeyedRateLimiterService(${this.config.name}): rate-limit pipeline failed`)+ }+ // Fail-open: allow every request, no fan-out deduction. The earlier shape+ // here seeded `budgetById` with bucketSize and then ran the fan-out, which+ // wrongly rate-limited any id whose total cost exceeded bucketSize.+ const bucketSizeById = new Map(items.map((req, i) => [req.id, bucketSizes[i]]))+ requestsTotal.inc(+ { name: this.config.name, method: 'rateLimitGrouped', outcome: 'allowed' },+ requests.length+ )+ 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>()items.forEach((req, index) => {- if (res) {- const [tokenRes] = getRedisPipelineResults(res, index, 1)- const tokensBefore = tokenRes[1]?.[0]- budgetById.set(req.id, tokensBefore != null ? Number(tokensBefore) : bucketSizes[index])- } else {- budgetById.set(req.id, bucketSizes[index])- }+ const [tokenRes] = getRedisPipelineResults(res, index, 1)+ const tokensBefore = tokenRes[1]?.[0]+ budgetById.set(req.id, tokensBefore != null ? Number(tokensBefore) : bucketSizes[index])})let allowed = 0let limited = 0const out: [string, KeyedRateLimit][] = requests.map((req) => {- const remaining = budgetById.get(req.id) ?? 0- if (remaining >= req.cost) {- const next = remaining - req.cost+ const tokensBefore = budgetById.get(req.id) ?? 0+ if (tokensBefore >= req.cost) {+ const next = tokensBefore - req.costbudgetById.set(req.id, next)const isRateLimited = next <= 0if (isRateLimited) {@@ -138,10 +218,10 @@ export class KeyedRateLimiterService {} else {allowed++}- return [req.id, { tokens: next, isRateLimited }]+ return [req.id, { tokensBefore, tokens: next, isRateLimited }]}limited++- return [req.id, { tokens: -1, isRateLimited: true }]+ return [req.id, { tokensBefore, tokens: -1, isRateLimited: true }]})if (allowed > 0) {requestsTotal.inc({ name: this.config.name, method: 'rateLimitGrouped', outcome: 'allowed' }, allowed)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 8ad0c668028e..e3fb12c74344 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@@ -16,7 +16,7 @@ const mkLimiter = (decisions: Record<string, boolean>): KeyedRateLimiterServicereturn Promise.resolve(requests.map(({ id }): [string, KeyedRateLimit] => [id,- { tokens: decisions[id] ? 0 : 99, isRateLimited: !!decisions[id] },+ { tokensBefore: 100, tokens: decisions[id] ? 0 : 99, isRateLimited: !!decisions[id] },]))}),diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.tsindex d4107cd11718..9d07ac1cb99e 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts@@ -21,7 +21,7 @@ import { type PiiScrubStats } from './log-pii-scrub'import { processLogMessageBuffer } from './log-record-avro'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'import type { CompiledRuleSet } from './sampling/evaluate'-import { type SamplingRateContext, processBufferWithSampling } from './sampling/process-buffer-with-sampling'+import { LogsSamplingService } from './sampling/logs-sampling.service'import { SamplingRulesCache } from './sampling/sampling-rules-cache'import { LogsRateLimiterService } from './services/logs-rate-limiter.service'import { LogsIngestionMessage } from './types'@@ -124,7 +124,7 @@ export class LogsIngestionConsumer {private appMetricsAggregator: AppMetricsAggregatorprivate redis: RedisV2private rateLimiter: LogsRateLimiterService- private readonly logsSamplingRateLimitTtlSeconds: number+ private samplingService: LogsSamplingServiceprivate readonly samplingEnabledTeamsRaw: stringprivate readonly samplingKillswitch: boolean@@ -160,7 +160,7 @@ export class LogsIngestionConsumer {poolMaxSize: config.REDIS_POOL_MAX_SIZE,})this.rateLimiter = new LogsRateLimiterService(config, this.redis)- this.logsSamplingRateLimitTtlSeconds = config.LOGS_LIMITER_TTL_SECONDS+ this.samplingService = new LogsSamplingService(this.redis, config.LOGS_LIMITER_TTL_SECONDS)this.samplingEnabledTeamsRaw = overrides.LOGS_SAMPLING_ENABLED_TEAMS ?? config.LOGS_SAMPLING_ENABLED_TEAMSthis.samplingKillswitch = overrides.LOGS_SAMPLING_KILLSWITCH ?? config.LOGS_SAMPLING_KILLSWITCH}@@ -226,14 +226,12 @@ export class LogsIngestionConsumer {})if (useSamplingPipeline && ruleSet) {- const rateCtx: SamplingRateContext | null = ruleSet.hasRateLimitRules- ? {- teamId: message.teamId,- redis: this.redis,- ttlSeconds: this.logsSamplingRateLimitTtlSeconds,- }- : null- const sampled = await processBufferWithSampling(message.message.value!, logsSettings, ruleSet, rateCtx)+ const sampled = await this.samplingService.processBuffer(+ message.message.value!,+ logsSettings,+ ruleSet,+ message.teamId+ )if (sampled.recordsDropped > 0) {logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)}diff --git a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.test.ts b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.tssimilarity index 88%rename from nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.test.tsrename to nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.tsindex 30f2622d4b5f..6a8ac7961d22 100644--- a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.test.ts+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts@@ -5,7 +5,7 @@ import type { LogsSettings } from '~/types'import { type LogRecord, decodeLogRecords, encodeLogRecords } from '../log-record-avro'import { compileRuleSet } from './compile-rules'-import { type SamplingRateContext, processBufferWithSampling } from './process-buffer-with-sampling'+import { LogsSamplingService } from './logs-sampling.service'const LOG_RECORD_AVRO = avro.Type.forSchema({type: 'record',@@ -49,7 +49,7 @@ function baseLog(uuid: string, serviceName: string): LogRecord {}}-describe('processBufferWithSampling', () => {+describe('LogsSamplingService', () => {it('batches rate_limit lines and drops when tokensBefore is below pending count', async () => {const ruleSet = compileRuleSet([{@@ -77,8 +77,8 @@ describe('processBufferWithSampling', () => {}),}- const rateCtx: SamplingRateContext = { teamId: 99, redis: mockRedis, ttlSeconds: 60 }- const result = await processBufferWithSampling(buffer, logsSettings, ruleSet, rateCtx)+ const service = new LogsSamplingService(mockRedis, 60)+ const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99)expect(result.recordsDropped).toBe(1)expect(result.recordsDroppedByRuleId.get('rl-1')).toBe(1)@@ -106,8 +106,8 @@ describe('processBufferWithSampling', () => {usePipeline: jest.fn(() => Promise.resolve(null)),}- const rateCtx: SamplingRateContext = { teamId: 1, redis: mockRedis, ttlSeconds: 60 }- const result = await processBufferWithSampling(buffer, logsSettings, ruleSet, rateCtx)+ const service = new LogsSamplingService(mockRedis, 60)+ const result = await service.processBuffer(buffer, logsSettings, ruleSet, 1)expect(result.recordsDropped).toBe(0)expect(result.recordsDroppedByRuleId.size).toBe(0)diff --git a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.tsnew file mode 100644index 000000000000..cde7de2cd8fa--- /dev/null+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts@@ -0,0 +1,184 @@+import { trace } from '@opentelemetry/api'++import { type RedisV2 } from '~/common/redis/redis-v2'+import { KeyedRateLimitRequest, KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'+import { instrumented } from '~/common/tracing/tracing-utils'+import type { LogsSettings } from '~/types'++import { type PiiScrubStats } from '../log-pii-scrub'+import {+ type LogRecord,+ decodeLogRecords,+ encodeLogRecords,+ transformDecodedLogRecordsInPlace,+} from '../log-record-avro'+import type { CompiledRuleSet, RateLimitPendingByRule } from './evaluate'+import {+ SAMPLING_DECISION_DROP,+ SAMPLING_DECISION_SAMPLE_DROPPED,+ classifySamplingRecord,+ evaluateLogRecord,+} from './evaluate'++export type ProcessBufferWithSamplingResult = {+ value: Buffer+ pii: PiiScrubStats+ recordsDropped: number+ /** Counts dropped lines (drop / sample_dropped) attributed to the first matching rule UUID. */+ recordsDroppedByRuleId: Map<string, number>+ /** When true, the caller must not produce this message to downstream Kafka (all lines sampled out). */+ allDropped: boolean+}++export class LogsSamplingService {+ private rateLimiter: KeyedRateLimiterService++ constructor(redis: RedisV2, ttlSeconds: number) {+ this.rateLimiter = new KeyedRateLimiterService({ name: 'logs-sampling-rate', ttlSeconds }, redis)+ }++ @instrumented({+ key: 'logsIngestion.sampling.processBufferWithSampling',+ measureTime: false,+ sendException: false,+ })+ public async processBuffer(+ buffer: Buffer,+ settings: LogsSettings,+ ruleSet: CompiledRuleSet,+ teamId?: number+ ): Promise<ProcessBufferWithSamplingResult> {+ const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)+ if (!logRecordType) {+ throw new Error('avro schema metadata not found')+ }+ const pii = await transformDecodedLogRecordsInPlace(records, settings)+ const kept: LogRecord[] = []+ let recordsDropped = 0+ const recordsDroppedByRuleId = new Map<string, number>()++ const useRate = Boolean(ruleSet.hasRateLimitRules && teamId != null)++ if (useRate && teamId != null) {+ const classifications = records.map((r) => classifySamplingRecord(ruleSet, r))+ const pendingByRule: RateLimitPendingByRule = new Map()+ for (let i = 0; i < records.length; i++) {+ const c = classifications[i]!+ if (c.kind === 'rate_limit') {+ const list = pendingByRule.get(c.ruleId) ?? []+ list.push(i)+ pendingByRule.set(c.ruleId, list)+ }+ }+ const rateKeep = await this.applyRateLimits(teamId, ruleSet, pendingByRule)++ for (let i = 0; i < records.length; i++) {+ const record = records[i]!+ const c = classifications[i]!+ if (c.kind === 'rate_limit') {+ if (rateKeep.get(i) === false) {+ recordsDropped+++ recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)+ continue+ }+ kept.push(record)+ continue+ }+ if (c.decision === SAMPLING_DECISION_DROP || c.decision === SAMPLING_DECISION_SAMPLE_DROPPED) {+ recordsDropped+++ if (c.ruleId != null) {+ recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)+ }+ continue+ }+ kept.push(record)+ }+ } else {+ for (const record of records) {+ const { decision, ruleId } = evaluateLogRecord(ruleSet, record)+ if (decision === SAMPLING_DECISION_DROP || decision === SAMPLING_DECISION_SAMPLE_DROPPED) {+ recordsDropped+++ if (ruleId != null) {+ recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)+ }+ continue+ }+ kept.push(record)+ }+ }++ trace.getActiveSpan()?.setAttributes({+ 'logs.sampling.input_record_count': records.length,+ 'logs.sampling.kept_record_count': kept.length,+ 'logs.sampling.dropped_record_count': recordsDropped,+ 'logs.sampling.all_dropped': kept.length === 0,+ 'logs.sampling.json_parse_logs': Boolean(settings.json_parse_logs),+ 'logs.sampling.pii_scrub_logs': Boolean(settings.pii_scrub_logs),+ })++ if (kept.length === 0) {+ return { value: Buffer.alloc(0), pii, recordsDropped, recordsDroppedByRuleId, allDropped: true }+ }+ const value = await encodeLogRecords(logRecordType, compressionCodec, kept)+ return { value, pii, recordsDropped, recordsDroppedByRuleId, allDropped: false }+ }++ /**+ * Maps a recordIndex -> keep (true) or drop (false) decision per rate_limit rule.+ * Each rule's pending lines share one Lua call; lines are admitted up to the+ * pre-batch token budget.+ */+ private async applyRateLimits(+ teamId: number,+ ruleSet: CompiledRuleSet,+ pendingByRule: RateLimitPendingByRule+ ): Promise<Map<number, boolean>> {+ const keepByIndex = new Map<number, boolean>()+ if (pendingByRule.size === 0) {+ return keepByIndex+ }++ const ruleById = new Map(ruleSet.rules.map((r) => [r.id, r]))+ type Entry = { indices: number[]; req: KeyedRateLimitRequest }+ const entries: Entry[] = []++ for (const [ruleId, indices] of pendingByRule) {+ const rl = ruleById.get(ruleId)?.rateLimit+ if (!rl || indices.length === 0) {+ continue+ }+ entries.push({+ indices,+ req: {+ id: `${teamId}/${ruleId}`,+ cost: indices.length,+ bucketSize: rl.poolMax,+ refillRate: rl.refillPerSecond,+ },+ })+ }++ if (entries.length === 0) {+ for (const [, indices] of pendingByRule) {+ for (const idx of indices) {+ keepByIndex.set(idx, true)+ }+ }+ return keepByIndex+ }++ const results = await this.rateLimiter.rateLimitMany(entries.map((e) => e.req))++ for (let i = 0; i < entries.length; i++) {+ const { indices } = entries[i]!+ const tokensBefore = results[i]?.[1].tokensBefore ?? 0+ const budget = Math.max(0, Math.floor(tokensBefore))+ const toAdmit = Math.min(indices.length, budget)+ for (let j = 0; j < indices.length; j++) {+ keepByIndex.set(indices[j]!, j < toAdmit)+ }+ }++ return keepByIndex+ }+}diff --git a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.ts b/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.tsdeleted file mode 100644index 730e33cb6bf9..000000000000--- a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.ts+++ /dev/null@@ -1,211 +0,0 @@-import { trace } from '@opentelemetry/api'--import { type RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'-import { instrumented } from '~/common/tracing/tracing-utils'-import type { LogsSettings } from '~/types'--import { type PiiScrubStats } from '../log-pii-scrub'-import {- type LogRecord,- decodeLogRecords,- encodeLogRecords,- transformDecodedLogRecordsInPlace,-} from '../log-record-avro'-import type { CompiledRuleSet, RateLimitPendingByRule, SamplingClassifyResult } from './evaluate'-import {- SAMPLING_DECISION_DROP,- SAMPLING_DECISION_SAMPLE_DROPPED,- classifySamplingRecord,- evaluateLogRecord,-} from './evaluate'--const samplingProcessInstrumentOpts = { measureTime: false, sendException: false } as const--const SAMPLING_RATE_LIMIT_REDIS_PREFIX =- process.env.NODE_ENV === 'test' ? '@posthog-test/logs-sampling-rate' : '@posthog/logs-sampling-rate'--export type SamplingRateContext = {- teamId: number- redis: RedisV2- ttlSeconds: number-}--export type ProcessBufferWithSamplingResult = {- value: Buffer- pii: PiiScrubStats- recordsDropped: number- /** Counts dropped lines (drop / sample_dropped) attributed to the first matching rule UUID. */- recordsDroppedByRuleId: Map<string, number>- /** When true, the caller must not produce this message to downstream Kafka (all lines sampled out). */- allDropped: boolean-}--async function applySamplingRateLimits(- teamId: number,- redis: RedisV2,- ttlSeconds: number,- ruleSet: CompiledRuleSet,- pendingByRule: RateLimitPendingByRule,- nowSeconds: number-): Promise<Map<number, boolean>> {- /** recordIndex -> keep (true) or drop (false) when classification was rate_limit */- const keepByIndex = new Map<number, boolean>()-- if (pendingByRule.size === 0) {- return keepByIndex- }-- const ruleById = new Map(ruleSet.rules.map((r) => [r.id, r]))- const pipelineArgs: { ruleId: string; cost: number; poolMax: number; fillRate: number; key: string }[] = []-- for (const [ruleId, indices] of pendingByRule) {- const rule = ruleById.get(ruleId)- const rl = rule?.rateLimit- if (!rl || indices.length === 0) {- continue- }- pipelineArgs.push({- ruleId,- cost: indices.length,- poolMax: rl.poolMax,- fillRate: rl.refillPerSecond,- key: `${SAMPLING_RATE_LIMIT_REDIS_PREFIX}/${teamId}/${ruleId}`,- })- }-- if (pipelineArgs.length === 0) {- for (const [, indices] of pendingByRule) {- for (const idx of indices) {- keepByIndex.set(idx, true)- }- }- return keepByIndex- }-- const res = await redis.usePipeline({ name: 'logs-sampling-rate-limit', failOpen: true }, (pipeline) => {- for (const a of pipelineArgs) {- pipeline.checkRateLimitV2(a.key, nowSeconds, a.cost, a.poolMax, a.fillRate, ttlSeconds)- }- })-- if (!res) {- for (const [, indices] of pendingByRule) {- for (const idx of indices) {- keepByIndex.set(idx, true)- }- }- return keepByIndex- }-- for (let pi = 0; pi < pipelineArgs.length; pi++) {- const arg = pipelineArgs[pi]!- const { ruleId, poolMax: argPoolMax } = arg- const rule = ruleById.get(ruleId)- const poolMax = rule?.rateLimit?.poolMax ?? argPoolMax- const [tokenRes] = getRedisPipelineResults(res, pi, 1)- const tokensBefore = Number(tokenRes[1]?.[0] ?? poolMax)- const indices = pendingByRule.get(ruleId) ?? []- const budget = Math.max(0, Math.floor(tokensBefore))- const toAdmit = Math.min(indices.length, budget)- for (let j = 0; j < indices.length; j++) {- keepByIndex.set(indices[j]!, j < toAdmit)- }- }-- return keepByIndex-}--async function processBufferWithSamplingImpl(- buffer: Buffer,- settings: LogsSettings,- ruleSet: CompiledRuleSet,- rateCtx?: SamplingRateContext | null-): Promise<ProcessBufferWithSamplingResult> {- const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)- if (!logRecordType) {- throw new Error('avro schema metadata not found')- }- const pii = await transformDecodedLogRecordsInPlace(records, settings)- const kept: LogRecord[] = []- let recordsDropped = 0- const recordsDroppedByRuleId = new Map<string, number>()-- const useRate = Boolean(ruleSet.hasRateLimitRules && rateCtx)-- if (useRate && rateCtx) {- const classifications: SamplingClassifyResult[] = records.map((r) => classifySamplingRecord(ruleSet, r))- const pendingByRule: RateLimitPendingByRule = new Map()- for (let i = 0; i < records.length; i++) {- const c = classifications[i]!- if (c.kind === 'rate_limit') {- const list = pendingByRule.get(c.ruleId) ?? []- list.push(i)- pendingByRule.set(c.ruleId, list)- }- }- const nowSeconds = Math.floor(Date.now() / 1000)- const rateKeep = await applySamplingRateLimits(- rateCtx.teamId,- rateCtx.redis,- rateCtx.ttlSeconds,- ruleSet,- pendingByRule,- nowSeconds- )-- for (let i = 0; i < records.length; i++) {- const record = records[i]!- const c = classifications[i]!- if (c.kind === 'rate_limit') {- const allow = rateKeep.get(i) !== false- if (!allow) {- recordsDropped++- recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)- continue- }- kept.push(record)- continue- }- if (c.decision === SAMPLING_DECISION_DROP || c.decision === SAMPLING_DECISION_SAMPLE_DROPPED) {- recordsDropped++- if (c.ruleId != null) {- recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)- }- continue- }- kept.push(record)- }- } else {- for (const record of records) {- const { decision, ruleId } = evaluateLogRecord(ruleSet, record)- if (decision === SAMPLING_DECISION_DROP || decision === SAMPLING_DECISION_SAMPLE_DROPPED) {- recordsDropped++- if (ruleId != null) {- recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)- }- continue- }- kept.push(record)- }- }-- trace.getActiveSpan()?.setAttributes({- 'logs.sampling.input_record_count': records.length,- 'logs.sampling.kept_record_count': kept.length,- 'logs.sampling.dropped_record_count': recordsDropped,- 'logs.sampling.all_dropped': kept.length === 0,- 'logs.sampling.json_parse_logs': Boolean(settings.json_parse_logs),- 'logs.sampling.pii_scrub_logs': Boolean(settings.pii_scrub_logs),- })-- if (kept.length === 0) {- return { value: Buffer.alloc(0), pii, recordsDropped, recordsDroppedByRuleId, allDropped: true }- }- const value = await encodeLogRecords(logRecordType, compressionCodec, kept)- return { value, pii, recordsDropped, recordsDroppedByRuleId, allDropped: false }-}--export const processBufferWithSampling = instrumented({- key: 'logsIngestion.sampling.processBufferWithSampling',- ...samplingProcessInstrumentOpts,-})(processBufferWithSamplingImpl)diff --git a/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.ts b/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.tsindex e4ee889b15bf..747707b0967a 100644--- a/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.ts+++ b/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.ts@@ -1,6 +1,7 @@import { Histogram } from 'prom-client'-import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'+import { RedisV2 } from '~/common/redis/redis-v2'+import { KeyedRateLimitRequest, KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'import { LogsIngestionConsumerConfig } from '../config'import { LogsIngestionMessage } from '../types'@@ -28,9 +29,11 @@ export type LogsRateLimiterConfig = Pick<| 'LOGS_LIMITER_TTL_SECONDS'>+const LIMITER_NAME = 'logs-rate-limiter'++/** Re-exported for the consumer test which needs to clean up keys between runs. */export const BASE_REDIS_KEY =- process.env.NODE_ENV == 'test' ? '@posthog-test/logs-rate-limiter' : '@posthog/logs-rate-limiter'-const REDIS_KEY_TOKENS = `${BASE_REDIS_KEY}/tokens`+ process.env.NODE_ENV == 'test' ? `@posthog-test/${LIMITER_NAME}` : `@posthog/${LIMITER_NAME}`export type LogsRateLimit = {tokensBefore: number@@ -53,15 +56,23 @@ export class LogsRateLimiterService {private teamRefillRates: Map<number, number>private disabledTeamIds: Set<number> | '*' | nullprivate enabledTeamIds: Set<number> | '*' | null+ private rateLimiter: KeyedRateLimiterServiceconstructor(private config: LogsRateLimiterConfig,- private redis: RedisV2+ redis: RedisV2) {this.teamBucketSizes = this.parseTeamConfig(config.LOGS_LIMITER_TEAM_BUCKET_SIZE_KB)this.teamRefillRates = this.parseTeamConfig(config.LOGS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND)this.disabledTeamIds = this.parseTeamIdList(config.LOGS_LIMITER_DISABLED_FOR_TEAMS)this.enabledTeamIds = this.parseTeamIdList(config.LOGS_LIMITER_ENABLED_TEAMS)+ this.rateLimiter = new KeyedRateLimiterService(+ // Bucket params are passed per-request so live `this.config` mutations+ // (used in tests) take effect. failOpen=false preserves the legacy+ // throw-on-Redis-outage behaviour.+ { name: LIMITER_NAME, failOpen: false },+ redis+ )}private parseTeamIdList(config: string): Set<number> | '*' | null {@@ -95,23 +106,6 @@ export class LogsRateLimiterService {return result}- private rateLimitArgs(- id: string,- cost: number,- nowSeconds: number- ): [string, number, number, number, number, number] {- const teamId = parseInt(id, 10)-- return [- `${REDIS_KEY_TOKENS}/${id}`,- nowSeconds,- cost,- this.teamBucketSizes.get(teamId) ?? this.config.LOGS_LIMITER_BUCKET_SIZE_KB,- this.teamRefillRates.get(teamId) ?? this.config.LOGS_LIMITER_REFILL_RATE_KB_PER_SECOND,- this.config.LOGS_LIMITER_TTL_SECONDS,- ]- }-private getHeaderValue(headers: any[] | undefined, key: string): string | undefined {if (!headers || !Array.isArray(headers)) {return undefined@@ -139,29 +133,22 @@ export class LogsRateLimiterService {}public async rateLimitMany(idCosts: [string, number, number][]): Promise<[string, LogsRateLimit][]> {- const res = await this.redis.usePipeline({ name: 'logs-rate-limiter', failOpen: true }, (pipeline) => {- idCosts.forEach(([id, cost, nowSeconds]) => {- pipeline.checkRateLimitV2(...this.rateLimitArgs(id, cost, nowSeconds))- })- })-- if (!res) {- throw new Error('Failed to rate limit')- }-- return idCosts.map(([id, ,], index) => {- const [tokenRes] = getRedisPipelineResults(res, index, 1)- const tokensBefore = Number(tokenRes[1]?.[0] ?? this.config.LOGS_LIMITER_BUCKET_SIZE_KB)- const tokensAfter = Number(tokenRes[1]?.[1] ?? this.config.LOGS_LIMITER_BUCKET_SIZE_KB)- return [+ const requests: KeyedRateLimitRequest[] = idCosts.map(([id, cost, nowSeconds]) => {+ const teamId = parseInt(id, 10)+ return {id,- {- tokensBefore,- tokensAfter,- isRateLimited: tokensAfter <= 0,- },- ]+ cost,+ now: nowSeconds,+ bucketSize: this.teamBucketSizes.get(teamId) ?? this.config.LOGS_LIMITER_BUCKET_SIZE_KB,+ refillRate: this.teamRefillRates.get(teamId) ?? this.config.LOGS_LIMITER_REFILL_RATE_KB_PER_SECOND,+ ttlSeconds: this.config.LOGS_LIMITER_TTL_SECONDS,+ }})+ const results = await this.rateLimiter.rateLimitMany(requests)+ return results.map(([id, r]) => [+ id,+ { tokensBefore: r.tokensBefore, tokensAfter: r.tokens, isRateLimited: r.isRateLimited },+ ])}private isRateLimitingEnabledForTeam(teamId: number): boolean {