: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): always use v3 rate limiter (#58279)
Ben White1714915ea14c
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 33f6c851fd90..bd0c2bb0d689 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -353,13 +353,11 @@ export function createCdpCoreServices(// Mirror HogWatcherService bound to the shadow Valkey pool. `sendEvents: false`// so it never emits duplicate billable team events on state transitions; the// Prom counter `cdp_hog_function_state_change` may double-emit when both pools- // detect the same transition — rare, accepted during dual-write mode. The- // mirror dispatches to the optimized V3 lua so we get full-load comparison- // data on the optimized path.+ // detect the same transition — rare, accepted during dual-write mode.const hogWatcherMirror: HogWatcherService | null = valkeyShadow? new HogWatcherService(deps.teamManager,- { ...hogWatcherConfig, sendEvents: false, useV3: true },+ { ...hogWatcherConfig, sendEvents: false },valkeyShadow.writer,valkeyShadow.reader)diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 7f8a4f3df774..d3a393cc49ef 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -148,7 +148,7 @@ export class CdpEventsConsumer<}))const [rateLimits] = await Promise.all([instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {- return await this.hogRateLimiter.rateLimitMany(rateLimitInputs)+ return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)}),mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)@@ -318,7 +318,7 @@ export class CdpEventsConsumer<}))const [rateLimits] = await Promise.all([instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {- return await this.hogRateLimiter.rateLimitMany(rateLimitInputs)+ return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)}),mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.tsindex fb06cdc1f8e4..307f186900a3 100644--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts@@ -518,7 +518,7 @@ export function createHogTransformerService(const hogWatcherMirror: HogWatcherService | null = valkeyShadow? new HogWatcherService(deps.teamManager,- { ...hogWatcherConfig, sendEvents: false, useV3: true },+ { ...hogWatcherConfig, sendEvents: false },valkeyShadow.writer,valkeyShadow.reader)diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.tsindex a3c08ef91dea..655ca4f56515 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)- // V2 lua now leaves the pool at bucketSize on denied overshoot calls (no deduct).- // The state machine is still driven by the rate-limiter return (-1 on denial), so- // `state: 3` (disabled) is correct — it's just the storage value that differs.+ // 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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 10000,+ "tokens": -1,}`)@@ -300,13 +300,12 @@ describe('HogWatcher', () => {await watcher.clearLock(hogFunctionId) // For testing the logicawait watcher.observeResults(Array(100).fill(createResult({ duration: 1000, kind: 'hog' })))- // Final batch denies (cost > available); pool stays at the un-deducted value- // (4300 from the previous step), but the state transition still fires because- // the rate limiter returned -1.+ // 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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 4300,+ "tokens": -1,}`)expect(onStateChangeSpy).toHaveBeenCalledTimes(2) // New state change@@ -322,12 +321,12 @@ describe('HogWatcher', () => {watcher = new HogWatcherService(hub.teamManager, watcherConfig, redis)onStateChangeSpy = jest.spyOn(watcher as any, 'onStateChange') as jest.SpyInstanceawait watcher.observeResults(Array(1000).fill(createResult({ duration: 1000, kind: 'hog' })))- // Cold-start denial: cost > poolMax leaves the pool at bucketSize. The state- // transition still fires from the rate-limiter return.+ // Cold-start denial: V3 lua deducts past the bucket, leaving the pool at -1.+ // The state transition fires from the rate-limiter return.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 2,- "tokens": 10000,+ "tokens": -1,}`)expect(onStateChangeSpy).toHaveBeenCalledTimes(1)@@ -343,21 +342,20 @@ describe('HogWatcher', () => {it('should not automatically transition out of disabled', async () => {await watcher.observeResults(Array(1000).fill(createResult({ duration: 1000, kind: 'hog' })))- // Pool stays at bucketSize after the denied overshoot. State persists at 3- // (disabled) regardless because state writes are independent of pool writes.+ // 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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 10000,+ "tokens": -1,}`)advanceTime(1000)- // No actual deduction happened, so the pool is already at bucketSize and stays- // there even after the refill window — the cap kicks in.+ // Refill from -1 at refillRate=10 over 1s.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 10000,+ "tokens": 9,}`)@@ -366,7 +364,7 @@ describe('HogWatcher', () => {expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 10000,+ "tokens": 19,}`)expect(onStateChangeSpy).toHaveBeenCalledTimes(1)@@ -633,53 +631,4 @@ describe('HogWatcher', () => {)})})-- // The mirror Valkey path runs observeResults with useV3=true (V3 lua- // pipelined per-bucket). Behavior must match V2 — these tests exercise- // the same observe → token-deduct → state-transition flow to lock that- // contract in.- describe('useV3 equivalence (mirror path)', () => {- let v3Watcher: HogWatcherService-- beforeEach(() => {- v3Watcher = new HogWatcherService(hub.teamManager, { ...watcherConfig, useV3: true }, redis, redis)- })-- it('deducts tokens identically to the V2 pipelined path', async () => {- const results = Array(10).fill(createResult({ duration: 1000, kind: 'hog' }))-- await v3Watcher.observeResults(results)- const state = await v3Watcher.getPersistedState(hogFunctionId)-- // Reset and run the same input through the default (V2) watcher.- await deleteKeysWithPrefix(redis, BASE_REDIS_KEY)- await watcher.observeResults(results)- const v2State = await watcher.getPersistedState(hogFunctionId)-- expect(state).toEqual(v2State)- })-- it('triggers state changes via the same threshold logic', async () => {- await v3Watcher.observeResults(Array(1000).fill(createResult({ duration: 1000, kind: 'hog' })))- const state = await v3Watcher.getPersistedState(hogFunctionId)- // Heavy-cost flow should drive the bucket below the disabled threshold.- expect(state.state).toBe(HogWatcherState.disabled)- })-- it('handles batches with multiple distinct function ids', async () => {- const otherId = 'hog-function-id-2'- await v3Watcher.observeResults([- createResult({ id: hogFunctionId, duration: 1000, kind: 'hog' }),- createResult({ id: otherId, duration: 1000, kind: 'hog' }),- ])-- const stateA = await v3Watcher.getPersistedState(hogFunctionId)- const stateB = await v3Watcher.getPersistedState(otherId)-- expect(stateA.tokens).toBeLessThan(watcherConfig.bucketSize)- expect(stateB.tokens).toBeLessThan(watcherConfig.bucketSize)- // Each function's bucket is independent.- expect(stateA.tokens).toEqual(stateB.tokens)- })- })})diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.tsindex fd1f9fc14714..27becbc15228 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts@@ -31,10 +31,6 @@ export interface HogWatcherConfig {stateLockTtl: numberobserveResultsBufferTimeMs: numberobserveResultsBufferMaxResults: number- // When true, dispatches the token-bucket pipeline call to checkRateLimitV3- // (optimized lua: HMGET, multi-field HSET, conditional EXPIRE refresh).- // Default: V2.- useV3?: boolean}export const BASE_REDIS_KEY = process.env.NODE_ENV == 'test' ? '@posthog-test/hog-watcher-2' : '@posthog/hog-watcher-2'@@ -445,18 +441,13 @@ export class HogWatcherService {return { states, locks }})- const useV3 = this.config.useV3 ?? falseconst requests = functionCostEntries.map((fc) => ({ id: fc.functionId, cost: fc.cost }))const [stateRes, rateLimitRes] = await Promise.all([readStates(this.redisReader).catch((err) => {logger.warn('🔀', '[HogWatcher] reader readStatesForObserve failed, falling back to writer', { err })return readStates(this.redis)}),- // Mirror path uses rateLimitGrouped (V3 lua, optimized + coalesced if any- // dups slip through); primary keeps rateLimitMany (V2). Inputs are already- // unique per functionId so coalescing is a no-op shape-wise — V3 lua is- // the actual change here.- useV3 ? this.rateLimiter.rateLimitGrouped(requests) : this.rateLimiter.rateLimitMany(requests),+ this.rateLimiter.rateLimitGrouped(requests),])if (!stateRes) {