: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: Setup dual writing for cdp services to valkey (#57674)
Ben White9e129c1bc52f
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 4004b79f1c81..33f6c851fd90 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -22,6 +22,7 @@ import { createCdpOutputsRegistry } from './outputs/registry'import { CapturedEventsService } from './services/captured-events/captured-events.service'import { HogExecutorService } from './services/hog-executor.service'import { HogInputsService } from './services/hog-inputs.service'+import { HogFlowDuplicateObserverService } from './services/hogflows/hogflow-duplicate-observer.service'import { HogFlowExecutorService } from './services/hogflows/hogflow-executor.service'import { HogFlowFunctionsService } from './services/hogflows/hogflow-functions.service'import { HogFlowManagerService } from './services/hogflows/hogflow-manager.service'@@ -51,11 +52,31 @@ export type CdpOutput =export type CdpOutputs = IngestionOutputs<CdpOutput>+export interface CdpValkeyShadowPools {+ writer: RedisV2+ reader: RedisV2+}+export interface CdpCoreServices {redis: RedisV2+ /**+ * Shadow Valkey pools used for dual-write/read load testing. Null when+ * CDP_VALKEY_DUAL_ENABLED is false or CDP_VALKEY_HOST is unset. Consumers+ * that build their own redis-backed services (e.g. CdpEventsConsumer's+ * HogRateLimiterService) read this to construct mirror instances bound+ * to the shadow Valkey.+ */+ valkeyShadow: CdpValkeyShadowPools | nullhogFunctionManager: HogFunctionManagerServicehogFlowManager: HogFlowManagerServicehogWatcher: HogWatcherService+ /**+ * Mirror HogWatcherService bound to the shadow Valkey pool. Null when+ * shadow mode is disabled. Use at call sites alongside `hogWatcher` (via+ * `mirrorCall`) to load-test the new infrastructure. Constructed with+ * `sendEvents: false` so it never emits duplicate billable team events.+ */+ hogWatcherMirror: HogWatcherService | nullhogExecutor: HogExecutorServicehogFunctionTemplateManager: HogFunctionTemplateManagerServicehogFlowFunctionsService: HogFlowFunctionsService@@ -83,6 +104,13 @@ export type CdpCoreServicesConfig = Pick<| 'CDP_REDIS_PASSWORD'| 'CDP_REDIS_READER_HOST'| 'CDP_REDIS_READER_PORT'+ | 'CDP_VALKEY_HOST'+ | 'CDP_VALKEY_PORT'+ | 'CDP_VALKEY_PASSWORD'+ | 'CDP_VALKEY_READER_HOST'+ | 'CDP_VALKEY_READER_PORT'+ | 'CDP_VALKEY_DUAL_ENABLED'+ | 'CDP_VALKEY_TLS'| 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'| 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'| 'CDP_WATCHER_HOG_COST_TIMING'@@ -184,6 +212,101 @@ export function createCdpReaderRedisPool(return writerPool}+/**+ * Creates writer + reader pools for the shadow Valkey instance used in dual-write/read mode.+ * Returns null when CDP_VALKEY_DUAL_ENABLED is false or CDP_VALKEY_HOST is unset, in which+ * case the shadow path is disabled and behavior is identical to today.+ *+ * The reader falls back to the writer pool when CDP_VALKEY_READER_HOST is unset.+ */+export function createCdpValkeyShadowPools(+ config: Pick<+ CdpCoreServicesConfig,+ | 'CDP_VALKEY_HOST'+ | 'CDP_VALKEY_PORT'+ | 'CDP_VALKEY_PASSWORD'+ | 'CDP_VALKEY_READER_HOST'+ | 'CDP_VALKEY_READER_PORT'+ | 'CDP_VALKEY_DUAL_ENABLED'+ | 'CDP_VALKEY_TLS'+ | 'REDIS_POOL_MIN_SIZE'+ | 'REDIS_POOL_MAX_SIZE'+ >,+ name: string+): CdpValkeyShadowPools | null {+ if (!config.CDP_VALKEY_DUAL_ENABLED || !config.CDP_VALKEY_HOST) {+ return null+ }++ logger.info(+ '🪞',+ `[${name}] shadow valkey writer=${config.CDP_VALKEY_HOST}:${config.CDP_VALKEY_PORT} reader=${config.CDP_VALKEY_READER_HOST || '<falling back to writer>'}`+ )++ // commandTimeout aborts in-flight commands at the ioredis protocol level, so a slow shadow+ // doesn't tie up a pool client until the kernel TCP timeout. Pair this with mirrorCall()'s+ // race-timeout (which only stops awaiting); together they prevent leaks on bad shadow health.+ const shadowCommandTimeoutMs = 1000++ const tls = config.CDP_VALKEY_TLS ? {} : undefined++ const writer = createRedisV2PoolFromConfig({+ connection: {+ url: config.CDP_VALKEY_HOST,+ options: {+ port: config.CDP_VALKEY_PORT,+ password: config.CDP_VALKEY_PASSWORD,+ commandTimeout: shadowCommandTimeoutMs,+ tls,+ },+ name: `${name}-shadow`,+ },+ poolMinSize: config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,+ })++ // Non-blocking startup health check — shadow misconfig must not block startup.+ void writer+ .useClient({ name: 'startup-ping', timeout: 5000 }, (client) => client.ping())+ .catch((err) => {+ logger.error(+ '🪞',+ `[${name}] shadow writer at ${config.CDP_VALKEY_HOST}:${config.CDP_VALKEY_PORT} failed startup health check — shadow ops will surface as "[mirror:*] failed" warn logs from mirrorCall()`,+ { err }+ )+ })++ let reader: RedisV2 = writer+ if (config.CDP_VALKEY_READER_HOST) {+ reader = createRedisV2PoolFromConfig({+ connection: {+ url: config.CDP_VALKEY_READER_HOST,+ options: {+ port: config.CDP_VALKEY_READER_PORT,+ password: config.CDP_VALKEY_PASSWORD,+ commandTimeout: shadowCommandTimeoutMs,+ tls,+ },+ name: `${name}-shadow-reader`,+ },+ poolMinSize: config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,+ })++ void reader+ .useClient({ name: 'startup-ping', timeout: 5000 }, (client) => client.ping())+ .catch((err) => {+ logger.error(+ '🪞',+ `[${name}] shadow reader at ${config.CDP_VALKEY_READER_HOST}:${config.CDP_VALKEY_READER_PORT} failed startup health check`,+ { err }+ )+ })+ }++ return { writer, reader }+}+export function createCdpCoreServices(config: CdpCoreServicesConfig,deps: CdpCoreServicesDeps,@@ -202,32 +325,45 @@ export function createCdpCoreServices(})const redisReader = createCdpReaderRedisPool(config, redis, redisName)+ const valkeyShadow = createCdpValkeyShadowPools(config, redisName)const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)const hogFlowManager = new HogFlowManagerService(deps.postgres, deps.pubSub)- const hogWatcher = new HogWatcherService(- deps.teamManager,- {- hogCostTimingLowerMs: config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,- hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,- hogCostTiming: config.CDP_WATCHER_HOG_COST_TIMING,- asyncCostTimingLowerMs: config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,- asyncCostTimingUpperMs: config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,- asyncCostTiming: config.CDP_WATCHER_ASYNC_COST_TIMING,- sendEvents: config.CDP_WATCHER_SEND_EVENTS,- bucketSize: config.CDP_WATCHER_BUCKET_SIZE,- refillRate: config.CDP_WATCHER_REFILL_RATE,- ttl: config.CDP_WATCHER_TTL,- automaticallyDisableFunctions: config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,- thresholdDegraded: config.CDP_WATCHER_THRESHOLD_DEGRADED,- stateLockTtl: config.CDP_WATCHER_STATE_LOCK_TTL,- observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,- observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,- },- redis,- redisReader- )+ const hogWatcherConfig = {+ hogCostTimingLowerMs: config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,+ hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,+ hogCostTiming: config.CDP_WATCHER_HOG_COST_TIMING,+ asyncCostTimingLowerMs: config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,+ asyncCostTimingUpperMs: config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,+ asyncCostTiming: config.CDP_WATCHER_ASYNC_COST_TIMING,+ sendEvents: config.CDP_WATCHER_SEND_EVENTS,+ bucketSize: config.CDP_WATCHER_BUCKET_SIZE,+ refillRate: config.CDP_WATCHER_REFILL_RATE,+ ttl: config.CDP_WATCHER_TTL,+ automaticallyDisableFunctions: config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,+ thresholdDegraded: config.CDP_WATCHER_THRESHOLD_DEGRADED,+ stateLockTtl: config.CDP_WATCHER_STATE_LOCK_TTL,+ observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,+ observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,+ }++ const hogWatcher = new HogWatcherService(deps.teamManager, hogWatcherConfig, redis, redisReader)++ // 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.+ const hogWatcherMirror: HogWatcherService | null = valkeyShadow+ ? new HogWatcherService(+ deps.teamManager,+ { ...hogWatcherConfig, sendEvents: false, useV3: true },+ valkeyShadow.writer,+ valkeyShadow.reader+ )+ : nullconst hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)const emailService = new EmailService(@@ -266,7 +402,13 @@ export function createCdpCoreServices(const recipientsManager = new RecipientsManagerService(deps.postgres)const recipientPreferencesService = new RecipientPreferencesService(recipientsManager)- const hogFlowExecutor = new HogFlowExecutorService(hogFlowFunctionsService, recipientPreferencesService, redis)+ // Observer mirrors writes to Valkey (load-only); only the primary path drives metrics.+ const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow?.writer ?? null)+ const hogFlowExecutor = new HogFlowExecutorService(+ hogFlowFunctionsService,+ recipientPreferencesService,+ hogFlowDuplicateObserver+ )const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)@@ -284,9 +426,11 @@ export function createCdpCoreServices(return {redis,+ valkeyShadow,hogFunctionManager,hogFlowManager,hogWatcher,+ hogWatcherMirror,hogExecutor,hogFunctionTemplateManager,hogFlowFunctionsService,diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 62f471480a36..580845190a68 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -65,6 +65,19 @@ export type CdpConfig = {CDP_REDIS_READER_HOST: stringCDP_REDIS_READER_PORT: number+ // Shadow Valkey pool for dual-write/read load testing. When CDP_VALKEY_DUAL_ENABLED+ // is true and CDP_VALKEY_HOST is set, every Redis call also runs against this pool;+ // shadow results are discarded, errors/timeouts logged + counted but never affect+ // the primary code path.+ CDP_VALKEY_HOST: string+ CDP_VALKEY_PORT: number+ CDP_VALKEY_PASSWORD: string+ CDP_VALKEY_READER_HOST: string+ CDP_VALKEY_READER_PORT: number+ CDP_VALKEY_DUAL_ENABLED: boolean+ // AWS ElastiCache Valkey Serverless requires TLS; toggle off only for local non-TLS test setups.+ CDP_VALKEY_TLS: boolean+CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: booleanCDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: stringCDP_FETCH_RETRIES: number@@ -160,6 +173,14 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_REDIS_READER_HOST: '',CDP_REDIS_READER_PORT: 6379,+ CDP_VALKEY_HOST: '',+ CDP_VALKEY_PORT: 6379,+ CDP_VALKEY_PASSWORD: '',+ CDP_VALKEY_READER_HOST: '',+ CDP_VALKEY_READER_PORT: 6379,+ CDP_VALKEY_DUAL_ENABLED: false,+ CDP_VALKEY_TLS: false,+CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: true,CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: '',CDP_FETCH_RETRIES: 3,diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex 1964d9b6452c..5c92a27f5ea1 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -7,7 +7,13 @@ import { GeoIPService } from '../../utils/geoip'import { logger } from '../../utils/logger'import { GroupRepository } from '../../worker/ingestion/groups/repositories/group-repository.interface'import { PersonRepository } from '../../worker/ingestion/persons/repositories/person-repository'-import { CdpCoreServicesConfig, CdpCoreServicesDeps, CdpOutputs, createCdpCoreServices } from '../cdp-services'+import {+ CdpCoreServicesConfig,+ CdpCoreServicesDeps,+ CdpOutputs,+ CdpValkeyShadowPools,+ createCdpCoreServices,+} from '../cdp-services'import type { CdpConfig } from '../config'import { HogExecutorService } from '../services/hog-executor.service'import { HogFlowExecutorService } from '../services/hogflows/hogflow-executor.service'@@ -45,12 +51,14 @@ export interface TeamIDWithConfig {export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = CdpConsumerBaseConfig> {redis: RedisV2+ valkeyShadow: CdpValkeyShadowPools | nullisStopping = falsehogExecutor: HogExecutorServicehogFlowExecutor: HogFlowExecutorServicehogMasker: HogMaskerServicehogWatcher: HogWatcherService+ hogWatcherMirror: HogWatcherService | nullgroupsManager: GroupsManagerServicehogFlowManager: HogFlowManagerService@@ -77,9 +85,11 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdconst services = createCdpCoreServices(config, deps)this.redis = services.redis+ this.valkeyShadow = services.valkeyShadowthis.hogFunctionManager = services.hogFunctionManagerthis.hogFlowManager = services.hogFlowManagerthis.hogWatcher = services.hogWatcher+ this.hogWatcherMirror = services.hogWatcherMirrorthis.hogExecutor = services.hogExecutorthis.hogFunctionTemplateManager = services.hogFunctionTemplateManagerthis.hogFlowFunctionsService = services.hogFlowFunctionsService@@ -93,7 +103,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdthis.outputs = services.outputs// Base-only services- this.hogMasker = new HogMaskerService(services.redis)+ this.hogMasker = new HogMaskerService(services.redis, services.valkeyShadow?.writer ?? null)this.personsManager = new PersonsManagerService(deps.teamManager, deps.personRepository, config.SITE_URL)this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)this.pluginDestinationExecutorService = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.tsindex 0a56c38b4c08..9121d47690c5 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts@@ -12,6 +12,7 @@ import {CyclotronJobQueueKind,} from '../types'import { isLegacyPluginHogFunction, isNativeHogFunction, isSegmentPluginHogFunction } from '../utils'+import { mirrorCall } from '../utils/mirror-call'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'/**@@ -153,7 +154,12 @@ export class CdpCyclotronWorker<@instrumented({ key: 'cdpConsumer.backgroundTask.hogWatcherObserve', timeoutMs: 10_000, sendException: false })private async observeResults(invocationResults: CyclotronJobInvocationResult[]): Promise<void> {try {- await this.hogWatcher.observeResults(invocationResults)+ await Promise.all([+ this.hogWatcher.observeResults(invocationResults),+ mirrorCall('hog-watcher.observeResults', () =>+ this.hogWatcherMirror?.observeResults(invocationResults)+ ),+ ])} catch (err: any) {captureException(err)logger.error('Error observing results', { err })diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 259a997a0cae..7f8a4f3df774 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -4,6 +4,7 @@ import { Message } from 'node-rdkafka'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'import { convertToHogFunctionInvocationGlobals } from '../../cdp/utils'+import { KeyedRateLimitRequest, KeyedRateLimiterService } from '../../common/services/keyed-rate-limiter.service'import { KAFKA_EVENTS_JSON } from '../../config/kafka-topics'import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'@@ -12,7 +13,6 @@ import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { shouldBlockHogFlowDueToQuota } from '../services/hogflows/hogflow-quota-limiting'import { CyclotronJobQueue } from '../services/job-queue/job-queue'-import { HogRateLimiterService } from '../services/monitoring/hog-rate-limiter.service'import { HogWatcherState } from '../services/monitoring/hog-watcher.service'import {CyclotronJobInvocation,@@ -23,6 +23,7 @@ import {LogEntry,MinimalAppMetric,} from '../types'+import { mirrorCall } from '../utils/mirror-call'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterHogFunctionStateOnEvent, counterParseError, counterRateLimited } from './metrics'import { shouldBlockInvocationDueToQuota } from './quota-limiting-helper'@@ -35,7 +36,8 @@ export class CdpEventsConsumer<private cyclotronJobQueue: CyclotronJobQueueprotected kafkaConsumer: KafkaConsumerInterface- private hogRateLimiter: HogRateLimiterService+ private hogRateLimiter: KeyedRateLimiterService+ private hogRateLimiterMirror: KeyedRateLimiterService | nullconstructor(config: TConfig,@@ -46,14 +48,16 @@ export class CdpEventsConsumer<super(config, deps)this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)this.kafkaConsumer = createKafkaConsumer({ groupId, topic })- this.hogRateLimiter = new HogRateLimiterService(- {- bucketSize: config.CDP_RATE_LIMITER_BUCKET_SIZE,- refillRate: config.CDP_RATE_LIMITER_REFILL_RATE,- ttl: config.CDP_RATE_LIMITER_TTL,- },- this.redis- )+ const rateLimiterConfig = {+ name: 'hog-rate-limiter',+ bucketSize: config.CDP_RATE_LIMITER_BUCKET_SIZE,+ refillRate: config.CDP_RATE_LIMITER_REFILL_RATE,+ ttlSeconds: config.CDP_RATE_LIMITER_TTL,+ }+ this.hogRateLimiter = new KeyedRateLimiterService(rateLimiterConfig, this.redis)+ this.hogRateLimiterMirror = this.valkeyShadow+ ? new KeyedRateLimiterService(rateLimiterConfig, this.valkeyShadow.writer)+ : null}public async processBatch(@@ -128,12 +132,28 @@ export class CdpEventsConsumer<)).flat()- const states = await instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {- return await this.hogWatcher.getEffectiveStates(possibleInvocations.map((x) => x.hogFunction.id))- })- const rateLimits = await instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {- return await this.hogRateLimiter.rateLimitMany(possibleInvocations.map((x) => [x.hogFunction.id, 1]))- })+ const hogFunctionIds = possibleInvocations.map((x) => x.hogFunction.id)+ const [states] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {+ return await this.hogWatcher.getEffectiveStates(hogFunctionIds)+ }),+ mirrorCall('hog-watcher.getEffectiveStates', () =>+ this.hogWatcherMirror?.getEffectiveStates(hogFunctionIds)+ ),+ ])++ const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({+ id: x.hogFunction.id,+ cost: 1,+ }))+ const [rateLimits] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {+ return await this.hogRateLimiter.rateLimitMany(rateLimitInputs)+ }),+ mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>+ this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)+ ),+ ])const validInvocations: CyclotronJobInvocationHogFunction[] = []@@ -284,12 +304,26 @@ export class CdpEventsConsumer<)).flat()- const states = await instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {- return await this.hogWatcher.getEffectiveStates(possibleInvocations.map((x) => x.hogFlow.id))- })- const rateLimits = await instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {- return await this.hogRateLimiter.rateLimitMany(possibleInvocations.map((x) => [x.hogFlow.id, 1]))- })+ const hogFlowIds = possibleInvocations.map((x) => x.hogFlow.id)+ const [states] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {+ return await this.hogWatcher.getEffectiveStates(hogFlowIds)+ }),+ mirrorCall('hog-watcher.getEffectiveStates', () => this.hogWatcherMirror?.getEffectiveStates(hogFlowIds)),+ ])++ const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({+ id: x.hogFlow.id,+ cost: 1,+ }))+ const [rateLimits] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitMany', async () => {+ return await this.hogRateLimiter.rateLimitMany(rateLimitInputs)+ }),+ mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>+ this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)+ ),+ ])const validInvocations: CyclotronJobInvocation[] = []// Iterate over adding them to the list and updating their prioritydiff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.tsindex 12e359ab36ad..fb06cdc1f8e4 100644--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts@@ -13,7 +13,7 @@ import { GeoIPService, GeoIp } from '../../utils/geoip'import { logger } from '../../utils/logger'import { PubSub } from '../../utils/pubsub'import { TeamManager } from '../../utils/team-manager'-import { CdpCoreServicesConfig, createCdpReaderRedisPool } from '../cdp-services'+import { CdpCoreServicesConfig, createCdpReaderRedisPool, createCdpValkeyShadowPools } from '../cdp-services'import { HogExecutorService } from '../services/hog-executor.service'import { HogInputsService } from '../services/hog-inputs.service'import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'@@ -26,6 +26,7 @@ import { HogWatcherService, HogWatcherState } from '../services/monitoring/hog-wimport { EncryptedFields } from '../utils/encryption-utils'import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'import { createInvocation } from '../utils/invocation-utils'+import { mirrorCall } from '../utils/mirror-call'import { getTransformationFunctions } from './transformation-functions'export interface HogTransformerConfig {@@ -86,6 +87,7 @@ export class HogTransformerService {private hogFunctionManager: HogFunctionManagerService,private hogExecutor: HogExecutorService,private hogWatcher: HogWatcherService,+ private hogWatcherMirror: HogWatcherService | null,private hogFunctionMonitoringService: HogFunctionMonitoringService,private pluginExecutor: LegacyPluginExecutorService,private geoipService: GeoIPService,@@ -119,6 +121,10 @@ export class HogTransformerService {logger.warn('⚠️', 'HogWatcher observeResults failed', { error })}): Promise.resolve(),++ shouldRunHogWatcher+ ? mirrorCall('hog-watcher.observeResults', () => this.hogWatcherMirror?.observeResults(results))+ : Promise.resolve(),])}@@ -401,7 +407,10 @@ export class HogTransformerService {public async fetchAndCacheHogFunctionStates(functionIds: string[]): Promise<void> {const timer = hogWatcherLatency.startTimer({ operation: 'getStates' })- const states = await this.hogWatcher.getEffectiveStates(functionIds)+ const [states] = await Promise.all([+ this.hogWatcher.getEffectiveStates(functionIds),+ mirrorCall('hog-watcher.getEffectiveStates', () => this.hogWatcherMirror?.getEffectiveStates(functionIds)),+ ])timer()// Save only the state enum value to cache@@ -456,6 +465,7 @@ export function createHogTransformerService(poolMaxSize: config.REDIS_POOL_MAX_SIZE,})const redisReader = createCdpReaderRedisPool(config, redis, 'hog-transformer-redis')+ const valkeyShadow = createCdpValkeyShadowPools(config, 'hog-transformer-redis')const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)@@ -486,33 +496,39 @@ export function createHogTransformerService()const pluginExecutor = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)const hogFunctionMonitoringService = new HogFunctionMonitoringService(deps.monitoringOutputs)- const hogWatcher = new HogWatcherService(- deps.teamManager,- {- hogCostTimingLowerMs: config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,- hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,- hogCostTiming: config.CDP_WATCHER_HOG_COST_TIMING,- asyncCostTimingLowerMs: config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,- asyncCostTimingUpperMs: config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,- asyncCostTiming: config.CDP_WATCHER_ASYNC_COST_TIMING,- sendEvents: config.CDP_WATCHER_SEND_EVENTS,- bucketSize: config.CDP_WATCHER_BUCKET_SIZE,- refillRate: config.CDP_WATCHER_REFILL_RATE,- ttl: config.CDP_WATCHER_TTL,- automaticallyDisableFunctions: config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,- thresholdDegraded: config.CDP_WATCHER_THRESHOLD_DEGRADED,- stateLockTtl: config.CDP_WATCHER_STATE_LOCK_TTL,- observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,- observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,- },- redis,- redisReader- )+ const hogWatcherConfig = {+ hogCostTimingLowerMs: config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,+ hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,+ hogCostTiming: config.CDP_WATCHER_HOG_COST_TIMING,+ asyncCostTimingLowerMs: config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,+ asyncCostTimingUpperMs: config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,+ asyncCostTiming: config.CDP_WATCHER_ASYNC_COST_TIMING,+ sendEvents: config.CDP_WATCHER_SEND_EVENTS,+ bucketSize: config.CDP_WATCHER_BUCKET_SIZE,+ refillRate: config.CDP_WATCHER_REFILL_RATE,+ ttl: config.CDP_WATCHER_TTL,+ automaticallyDisableFunctions: config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,+ thresholdDegraded: config.CDP_WATCHER_THRESHOLD_DEGRADED,+ stateLockTtl: config.CDP_WATCHER_STATE_LOCK_TTL,+ observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,+ observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,+ }+ const hogWatcher = new HogWatcherService(deps.teamManager, hogWatcherConfig, redis, redisReader)+ // sendEvents:false on the mirror so we don't double-emit billable team events.+ const hogWatcherMirror: HogWatcherService | null = valkeyShadow+ ? new HogWatcherService(+ deps.teamManager,+ { ...hogWatcherConfig, sendEvents: false, useV3: true },+ valkeyShadow.writer,+ valkeyShadow.reader+ )+ : nullreturn new HogTransformerService(hogFunctionManager,hogExecutor,hogWatcher,+ hogWatcherMirror,hogFunctionMonitoringService,pluginExecutor,deps.geoipService,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.tsnew file mode 100644index 000000000000..b19f5b91908f--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts@@ -0,0 +1,127 @@+import { register } from 'prom-client'++import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { Hub } from '~/types'+import { closeHub, createHub } from '~/utils/db/hub'++import { deleteKeysWithPrefix } from '../../_tests/redis'+import { CyclotronJobInvocationHogFlow } from '../../types'+import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'++const KEY_PREFIX = 'hogflow:observe:'++const buildInvocation = (overrides: { id?: string; functionId?: string; eventUuid?: string | null } = {}) =>+ ({+ id: overrides.id ?? 'invocation-1',+ functionId: overrides.functionId ?? 'workflow-1',+ state: { event: overrides.eventUuid === null ? undefined : { uuid: overrides.eventUuid ?? 'event-1' } },+ }) as unknown as CyclotronJobInvocationHogFlow++const buildAction = (id: string) => ({ id, type: 'function' }) as any++const dupCounterValue = async (workflowId: string): Promise<number> => {+ const metric = register.getSingleMetric('hogflow_duplicate_invocation_detected_total') as any+ const data = await metric.get()+ const found = data.values.find((v: any) => v.labels.workflow_id === workflowId)+ return found?.value ?? 0+}++describe('HogFlowDuplicateObserverService', () => {+ jest.retryTimes(3)++ let hub: Hub+ let redis: RedisV2++ 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: hub.REDIS_POOL_MIN_SIZE,+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,+ })+ })++ afterAll(async () => {+ await closeHub(hub)+ })++ beforeEach(async () => {+ await deleteKeysWithPrefix(redis, KEY_PREFIX)+ register.resetMetrics()+ })++ const readKey = async (key: string): Promise<string | null> =>+ (await redis.useClient({ name: 'read' }, (client) => client.get(key))) ?? null++ it('is a no-op when redis is null', async () => {+ const observer = new HogFlowDuplicateObserverService(null)+ await observer.observe(buildInvocation(), buildAction('action-1'))+ // Nothing to assert beyond not throwing — verifies the early return.+ })++ it('is a no-op when invocation has no eventUuid', async () => {+ const observer = new HogFlowDuplicateObserverService(redis)+ await observer.observe(buildInvocation({ eventUuid: null }), buildAction('action-1'))+ const keys = await redis.useClient({ name: 'keys' }, (client) => client.keys(`${KEY_PREFIX}*`))+ expect(keys ?? []).toHaveLength(0)+ })++ it('writes the key on first observation and does not flag a duplicate', async () => {+ const observer = new HogFlowDuplicateObserverService(redis)+ await observer.observe(buildInvocation({ id: 'inv-A' }), buildAction('action-1'))++ const stored = await readKey('hogflow:observe:workflow-1:event-1:action-1')+ expect(stored).toBe('inv-A')+ expect(await dupCounterValue('workflow-1')).toBe(0)+ })++ it('does not flag a duplicate when the same invocation re-observes', async () => {+ const observer = new HogFlowDuplicateObserverService(redis)+ const inv = buildInvocation({ id: 'inv-A' })+ await observer.observe(inv, buildAction('action-1'))+ await observer.observe(inv, buildAction('action-1'))++ expect(await dupCounterValue('workflow-1')).toBe(0)+ })++ it('flags a duplicate when a different invocation hits the same key', async () => {+ const observer = new HogFlowDuplicateObserverService(redis)+ await observer.observe(buildInvocation({ id: 'inv-A' }), buildAction('action-1'))+ await observer.observe(buildInvocation({ id: 'inv-B' }), buildAction('action-1'))++ // The second observation must NOT overwrite the first (NX) — verifies single-call atomicity.+ expect(await readKey('hogflow:observe:workflow-1:event-1:action-1')).toBe('inv-A')+ expect(await dupCounterValue('workflow-1')).toBe(1)+ })++ it('writes to the mirror in parallel with the primary', async () => {+ const mirror = {+ useClient: jest.fn().mockResolvedValue('OK'),+ } as unknown as RedisV2++ const observer = new HogFlowDuplicateObserverService(redis, mirror)+ await observer.observe(buildInvocation({ id: 'inv-A' }), buildAction('action-1'))++ expect(mirror.useClient).toHaveBeenCalledTimes(1)+ expect((mirror.useClient as jest.Mock).mock.calls[0][0]).toMatchObject({+ name: 'hogflow-observe-mirror',+ failOpen: true,+ })+ })++ it('does not break the primary when the mirror throws', async () => {+ const mirror = {+ useClient: jest.fn().mockRejectedValue(new Error('mirror exploded')),+ } as unknown as RedisV2++ const observer = new HogFlowDuplicateObserverService(redis, mirror)+ await observer.observe(buildInvocation({ id: 'inv-A' }), buildAction('action-1'))++ expect(await readKey('hogflow:observe:workflow-1:event-1:action-1')).toBe('inv-A')+ })+})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.tsnew file mode 100644index 000000000000..0081198f1b00--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts@@ -0,0 +1,65 @@+import { Counter } from 'prom-client'++import { RedisClient, RedisV2 } from '~/common/redis/redis-v2'++import { HogFlowAction } from '../../../schema/hogflow'+import { logger } from '../../../utils/logger'+import { CyclotronJobInvocationHogFlow } from '../../types'+import { mirrorCall } from '../../utils/mirror-call'++const DUPLICATE_OBSERVATION_TTL_SECONDS = 15 * 60++const hogflowDuplicateInvocationDetectedTotal = new Counter({+ name: 'hogflow_duplicate_invocation_detected_total',+ help: 'Fired once per action reached by a duplicate invocation of the same (workflow, event). Inflated by N actions per duplicate pair - treat as trend signal, not exact count.',+ labelNames: ['workflow_id'],+})++/**+ * Detects duplicate workflow invocations via a Redis SET-NX key per+ * (workflow, event, action). When `redisMirror` is set, every observation also+ * fires against the mirror in parallel — load is realised on the mirror; only+ * the primary drives the duplicate-detected metric.+ */+export class HogFlowDuplicateObserverService {+ constructor(+ private readonly redis: RedisV2 | null,+ private readonly redisMirror: RedisV2 | null = null+ ) {}++ public async observe(+ invocation: CyclotronJobInvocationHogFlow,+ currentAction: HogFlowAction+ ): Promise<{ duplicate: boolean }> {+ const eventUuid = invocation.state?.event?.uuid+ if (!this.redis || !eventUuid) {+ return { duplicate: false }+ }+ const key = `hogflow:observe:${invocation.functionId}:${eventUuid}:${currentAction.id}`++ // SET ... NX GET (Redis 7+ / Valkey 7.2+) sets the key when absent and returns the+ // existing value when present — one round-trip instead of GET-then-SETNX. ioredis 4.x+ // types only describe 'OK' | null for the return, so we cast to the actual GET payload.+ const setNxGet = (client: RedisClient): Promise<string | null> =>+ client.set(key, invocation.id, ['EX', String(DUPLICATE_OBSERVATION_TTL_SECONDS), 'NX', 'GET']) as Promise<+ string | null+ >++ let duplicate = false+ try {+ const [existingId] = await Promise.all([+ this.redis.useClient({ name: 'hogflow-observe', failOpen: true }, setNxGet),+ mirrorCall('hog-flow-duplicate-observer.observe', () =>+ this.redisMirror?.useClient({ name: 'hogflow-observe-mirror', failOpen: true }, setNxGet)+ ),+ ])+ if (existingId && existingId !== invocation.id) {+ duplicate = true+ hogflowDuplicateInvocationDetectedTotal.inc({ workflow_id: invocation.functionId })+ }+ } catch (error) {+ logger.debug('🦔', '[HogFlowDuplicateObserver] failed', { error: String(error) })+ }+ return { duplicate }+ }+}diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 3970905f3233..53b15f1f162c 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -1,8 +1,5 @@import { get } from 'lodash'import { DateTime } from 'luxon'-import { Counter } from 'prom-client'--import { RedisV2 } from '~/common/redis/redis-v2'import { HogFlow, HogFlowAction } from '../../../schema/hogflow'import { logger } from '../../../utils/logger'@@ -31,6 +28,7 @@ import { HogFunctionHandler } from './actions/hog_function'import { RandomCohortBranchHandler } from './actions/random_cohort_branch'import { TriggerHandler } from './actions/trigger.handler'import { WaitUntilTimeWindowHandler } from './actions/wait_until_time_window'+import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'import { HogFlowFunctionsService } from './hogflow-functions.service'import {actionIdForLogging,@@ -42,14 +40,6 @@ import {export const MAX_ACTION_STEPS_HARD_LIMIT = 1000-const DUPLICATE_OBSERVATION_TTL_SECONDS = 15 * 60--const hogflowDuplicateInvocationDetectedTotal = new Counter({- name: 'hogflow_duplicate_invocation_detected_total',- help: 'Fired once per action reached by a duplicate invocation of the same (workflow, event). Inflated by N actions per duplicate pair - treat as trend signal, not exact count.',- labelNames: ['workflow_id'],-})-export function createHogFlowInvocation(globals: HogFunctionInvocationGlobals,hogFlow: HogFlow,@@ -89,14 +79,14 @@ export function createHogFlowInvocation(export class HogFlowExecutorService {private readonly actionHandlers: Record<HogFlowAction['type'], ActionHandler>- private readonly redis: RedisV2 | null+ private readonly duplicateObserver: HogFlowDuplicateObserverService | nullconstructor(hogFlowFunctionsService: HogFlowFunctionsService,recipientPreferencesService: RecipientPreferencesService,- redis?: RedisV2+ duplicateObserver?: HogFlowDuplicateObserverService) {- this.redis = redis ?? null+ this.duplicateObserver = duplicateObserver ?? nullconst hogFunctionHandler = new HogFunctionHandler(hogFlowFunctionsService, recipientPreferencesService, 'fetch')const hogFunctionEmailHandler = new HogFunctionHandler(hogFlowFunctionsService,@@ -166,25 +156,7 @@ export class HogFlowExecutorService {invocation: CyclotronJobInvocationHogFlow,currentAction: HogFlowAction): Promise<void> {- const eventUuid = invocation.state?.event?.uuid- if (!this.redis || !eventUuid) {- return- }- const key = `hogflow:observe:${invocation.functionId}:${eventUuid}:${currentAction.id}`- try {- await this.redis.useClient({ name: 'hogflow-observe', failOpen: true }, async (client) => {- const wasSet = await client.set(key, invocation.id, 'EX', DUPLICATE_OBSERVATION_TTL_SECONDS, 'NX')- if (wasSet) {- return- }- const existingId = await client.get(key)- if (existingId && existingId !== invocation.id) {- hogflowDuplicateInvocationDetectedTotal.inc({ workflow_id: invocation.functionId })- }- })- } catch (error) {- logger.debug('🦔', '[HogFlowExecutor] Duplicate observer failed', { error: String(error) })- }+ await this.duplicateObserver?.observe(invocation, currentAction)}async execute(diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.tsindex c737ee982ddd..b1a0f44bc24b 100644--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts@@ -1,6 +1,6 @@import { createHash } from 'crypto'-import { RedisV2 } from '~/common/redis/redis-v2'+import { RedisClientPipeline, RedisV2 } from '~/common/redis/redis-v2'import {CyclotronJobInvocation,@@ -9,6 +9,7 @@ import {HogFunctionMasking,} from '../../types'import { execHog } from '../../utils/hog-exec'+import { mirrorCall } from '../../utils/mirror-call'export const BASE_REDIS_KEY = process.env.NODE_ENV == 'test' ? '@posthog-test/hog-masker' : '@posthog/hog-masker'const REDIS_KEY_TOKENS = `${BASE_REDIS_KEY}/mask`@@ -91,7 +92,10 @@ function getTtl(invocation: CyclotronJobInvocation, maskingConfig: HogFunctionMa// Hog masker is meant to be done per batchexport class HogMaskerService {- constructor(private redis: RedisV2) {}+ constructor(+ private redis: RedisV2,+ private redisMirror: RedisV2 | null = null+ ) {}public async filterByMasking<T extends CyclotronJobInvocation>(invocations: T[]@@ -142,13 +146,20 @@ export class HogMaskerService {return { masked: [], notMasked: invocations }}- const result = await this.redis.usePipeline({ name: 'masker', failOpen: true }, (pipeline) => {+ const buildPipeline = (pipeline: RedisClientPipeline): void => {Object.values(masks).forEach(({ hogFunctionId, hash, increment, ttl }) => {pipeline.incrby(`${REDIS_KEY_TOKENS}/${hogFunctionId}/${hash}`, increment)// @ts-expect-error - NX is not typed in ioredispipeline.expire(`${REDIS_KEY_TOKENS}/${hogFunctionId}/${hash}`, ttl, 'NX')})- })+ }++ const [result] = await Promise.all([+ this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline),+ mirrorCall('hog-masker.filterByMasking', () =>+ this.redisMirror?.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline)+ ),+ ])Object.values(masks).forEach((masker, index) => {const newValue: number | null = result ? result[index * 2][1] : nulldiff --git a/nodejs/src/cdp/services/monitoring/hog-rate-limiter.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-rate-limiter.service.test.tsdeleted file mode 100644index 5ed3947ea86a..000000000000--- a/nodejs/src/cdp/services/monitoring/hog-rate-limiter.service.test.ts+++ /dev/null@@ -1,132 +0,0 @@-import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'-import { Hub } from '~/types'-import { closeHub, createHub } from '~/utils/db/hub'--import { deleteKeysWithPrefix } from '../../_tests/redis'-import { BASE_REDIS_KEY, HogRateLimiterService } from './hog-rate-limiter.service'--const mockNow: jest.SpyInstance = jest.spyOn(Date, 'now')--describe('HogRateLimiter', () => {- jest.retryTimes(3)-- describe('integration', () => {- let now: number- let hub: Hub- let rateLimiter: HogRateLimiterService- let redis: RedisV2- const id1 = 'hog-function-id-1'- const id2 = 'hog-function-id-2'-- 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,- })- await deleteKeysWithPrefix(redis, BASE_REDIS_KEY)-- rateLimiter = new HogRateLimiterService({ bucketSize: 100, refillRate: 10, ttl: 60 * 60 * 24 }, redis)- })-- const advanceTime = (ms: number) => {- now += ms- mockNow.mockReturnValue(now)- }-- afterEach(async () => {- await closeHub(hub)- jest.clearAllMocks()- })-- it('should use tokens for an ID', async () => {- const res = await rateLimiter.rateLimitMany([[id1, 1]])-- expect(res).toEqual([[id1, { tokens: 99, isRateLimited: false }]])- })-- it('should rate limit an ID', async () => {- let res = await rateLimiter.rateLimitMany([[id1, 99]])-- expect(res[0][1].tokens).toBe(1)- expect(res[0][1].isRateLimited).toBe(false)-- res = await rateLimiter.rateLimitMany([[id1, 1]])-- expect(res[0][1].tokens).toBe(0)- expect(res[0][1].isRateLimited).toBe(true)-- res = await rateLimiter.rateLimitMany([[id1, 20]])-- expect(res[0][1].tokens).toBe(-1) // It never goes below -1- expect(res[0][1].isRateLimited).toBe(true)- })-- it('should use tokens for many IDs', async () => {- const res = await rateLimiter.rateLimitMany([- [id1, 1],- [id2, 5],- ])-- expect(res).toEqual([- [id1, { tokens: 99, isRateLimited: false }],- [id2, { tokens: 95, isRateLimited: false }],- ])-- const res2 = await rateLimiter.rateLimitMany([- [id1, 1],- [id2, 0],- ])-- expect(res2).toEqual([- [id1, { tokens: 98, isRateLimited: false }],- [id2, { tokens: 95, isRateLimited: false }],- ])- })-- it('should refill over time', async () => {- const res = await rateLimiter.rateLimitMany([[id1, 50]])-- expect(res[0][1].tokens).toBe(50)-- advanceTime(1000) // 1 second = 10 tokens-- const res2 = await rateLimiter.rateLimitMany([[id1, 5]])-- expect(res2[0][1].tokens).toBe(55) // cost 5 but added 10 tokens- expect(res2[0][1].isRateLimited).toBe(false)-- advanceTime(4000) // 4 seconds = 40 tokens-- const res3 = await rateLimiter.rateLimitMany([[id1, 0]])-- expect(res3[0][1].tokens).toBe(95)- expect(res3[0][1].isRateLimited).toBe(false)- })-- it('should allow rate usage for multiple of the same ID', async () => {- const res = await rateLimiter.rateLimitMany([- [id1, 90],- [id1, 9],- [id1, 1],- [id1, 2],- ])-- expect(res).toEqual([- [id1, { tokens: 10, isRateLimited: false }],- [id1, { tokens: 1, isRateLimited: false }],- [id1, { tokens: 0, isRateLimited: true }],- [id1, { tokens: -1, isRateLimited: true }],- ])- })- })-})diff --git a/nodejs/src/cdp/services/monitoring/hog-rate-limiter.service.ts b/nodejs/src/cdp/services/monitoring/hog-rate-limiter.service.tsdeleted file mode 100644index cb795b6b1cb5..000000000000--- a/nodejs/src/cdp/services/monitoring/hog-rate-limiter.service.ts+++ /dev/null@@ -1,61 +0,0 @@-import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'--export interface HogRateLimiterConfig {- bucketSize: number- refillRate: number- ttl: number-}--export const BASE_REDIS_KEY =- process.env.NODE_ENV == 'test' ? '@posthog-test/hog-rate-limiter' : '@posthog/hog-rate-limiter'-const REDIS_KEY_TOKENS = `${BASE_REDIS_KEY}/tokens`--export type HogRateLimit = {- tokens: number- isRateLimited: boolean-}--export class HogRateLimiterService {- constructor(- private config: HogRateLimiterConfig,- private redis: RedisV2- ) {}-- private rateLimitArgs(id: string, cost: number): [string, number, number, number, number, number] {- const nowSeconds = Math.round(Date.now() / 1000)-- return [- `${REDIS_KEY_TOKENS}/${id}`,- nowSeconds,- cost,- this.config.bucketSize,- this.config.refillRate,- this.config.ttl,- ]- }-- public async rateLimitMany(idCosts: [string, number][]): Promise<[string, HogRateLimit][]> {- const res = await this.redis.usePipeline({ name: 'hog-rate-limiter', failOpen: true }, (pipeline) => {- idCosts.forEach(([id, cost]) => {- pipeline.checkRateLimitV2(...this.rateLimitArgs(id, cost))- })- })-- if (!res) {- throw new Error('Failed to rate limit')- }-- return idCosts.map(([id], index) => {- const [tokenRes] = getRedisPipelineResults(res, index, 1)- // V2 returns [tokensBefore, tokensAfter], we use tokensAfter for backward compatibility- const tokensAfter = tokenRes[1]?.[1] ?? this.config.bucketSize- return [- id,- {- tokens: Number(tokensAfter),- isRateLimited: Number(tokensAfter) <= 0,- },- ]- })- }-}diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.tsindex 98a113ca4dd4..a3c08ef91dea 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts@@ -224,10 +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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": -1,+ "tokens": 10000,}`)@@ -297,10 +300,13 @@ 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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": -1,+ "tokens": 4300,}`)expect(onStateChangeSpy).toHaveBeenCalledTimes(2) // New state change@@ -316,10 +322,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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 2,- "tokens": -1,+ "tokens": 10000,}`)expect(onStateChangeSpy).toHaveBeenCalledTimes(1)@@ -335,17 +343,21 @@ 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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": -1,+ "tokens": 10000,}`)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.expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 9,+ "tokens": 10000,}`)@@ -354,7 +366,7 @@ describe('HogWatcher', () => {expect(await watcher.getPersistedState(hogFunctionId)).toMatchInlineSnapshot(`{"state": 3,- "tokens": 19,+ "tokens": 10000,}`)expect(onStateChangeSpy).toHaveBeenCalledTimes(1)@@ -621,4 +633,53 @@ 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 d5e78876eeb9..fd1f9fc14714 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts@@ -1,6 +1,7 @@import { Counter } from 'prom-client'import { RedisClientPipeline, RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'+import { KeyedRateLimiterService } from '~/common/services/keyed-rate-limiter.service'import { LazyLoader } from '~/utils/lazy-loader'import { logger } from '~/utils/logger'import { captureTeamEvent } from '~/utils/posthog'@@ -30,6 +31,10 @@ 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'@@ -96,6 +101,7 @@ export class HogWatcherService {} | null = nullprivate redisReader: RedisV2+ private rateLimiter: KeyedRateLimiterServiceconstructor(private teamManager: TeamManager,@@ -104,6 +110,17 @@ export class HogWatcherService {redisReader?: RedisV2) {this.redisReader = redisReader ?? redis+ // Token-bucket rate limiter — `name: 'hog-watcher-2'` produces the same+ // Redis key prefix this service has used historically (matches BASE_REDIS_KEY).+ this.rateLimiter = new KeyedRateLimiterService(+ {+ name: 'hog-watcher-2',+ bucketSize: this.config.bucketSize,+ refillRate: this.config.refillRate,+ ttlSeconds: this.config.ttl,+ },+ this.redis+ )this.costsMapping = {hog: {lowerBound: this.config.hogCostTimingLowerMs,@@ -163,19 +180,6 @@ export class HogWatcherService {}}- private rateLimitArgs(id: HogFunctionType['id'], cost: number) {- const nowSeconds = Math.round(Date.now() / 1000)-- return [- `${REDIS_KEY_TOKENS}/${id}`,- nowSeconds,- cost,- this.config.bucketSize,- this.config.refillRate,- this.config.ttl,- ] as const- }-public calculateNewState(tokens: number): HogWatcherState {const rating = tokens / this.config.bucketSize@@ -441,19 +445,21 @@ export class HogWatcherService {return { states, locks }})- const [stateRes, tokenRes] = await Promise.all([+ const useV3 = this.config.useV3 ?? false+ const 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)}),- this.redis.usePipeline({ name: 'updateRateLimits' }, (pipeline) => {- for (const functionCost of functionCostEntries) {- pipeline.checkRateLimitV2(...this.rateLimitArgs(functionCost.functionId, functionCost.cost))- }- }),+ // 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),])- if (!stateRes || !tokenRes) {+ if (!stateRes) {return}@@ -461,11 +467,9 @@ export class HogWatcherService {// Calculate all those that have changed statefunctionCostEntries.map((functionCost, index) => {- const tokenResult = tokenRes[index]-+ const limit = rateLimitRes[index]?.[1]const currentState: HogWatcherState = Number(stateRes.states[index] ?? HogWatcherState.healthy)- // V2 returns [tokensBefore, tokensAfter], we use tokensAfter- const tokens = Number(tokenResult?.[1]?.[1] ?? this.config.bucketSize)+ const tokens = Number(limit?.tokens ?? this.config.bucketSize)const newState = this.calculateNewState(tokens)if (currentState !== newState) {diff --git a/nodejs/src/cdp/utils/mirror-call.test.ts b/nodejs/src/cdp/utils/mirror-call.test.tsnew file mode 100644index 000000000000..faac190a3814--- /dev/null+++ b/nodejs/src/cdp/utils/mirror-call.test.ts@@ -0,0 +1,29 @@+import { mirrorCall } from './mirror-call'++describe('mirrorCall', () => {+ it('resolves when the call resolves in time', async () => {+ const call = jest.fn().mockResolvedValue('ok')+ await mirrorCall('test.op', call, 50)+ expect(call).toHaveBeenCalledTimes(1)+ })++ it('short-circuits when the call factory returns undefined (mirror unconfigured)', async () => {+ const call = jest.fn().mockReturnValue(undefined)+ await mirrorCall('test.op', call, 50)+ expect(call).toHaveBeenCalledTimes(1)+ // Resolving with no work — verified by virtue of the test not hanging.+ })++ it('catches and logs errors instead of throwing', async () => {+ const call = jest.fn().mockRejectedValue(new Error('boom'))+ await expect(mirrorCall('test.op', call, 50)).resolves.toBeUndefined()+ })++ it('stops awaiting after timeoutMs and never throws', async () => {+ const call = jest.fn().mockImplementation(() => new Promise(() => {})) // never settles+ const start = Date.now()+ await mirrorCall('test.op', call, 20)+ const elapsed = Date.now() - start+ expect(elapsed).toBeLessThan(200)+ })+})diff --git a/nodejs/src/cdp/utils/mirror-call.ts b/nodejs/src/cdp/utils/mirror-call.tsnew file mode 100644index 000000000000..26e03f3646b7--- /dev/null+++ b/nodejs/src/cdp/utils/mirror-call.ts@@ -0,0 +1,53 @@+import { instrumentFn } from '../../common/tracing/tracing-utils'+import { logger } from '../../utils/logger'++const DEFAULT_TIMEOUT_MS = 2000++/**+ * Wraps a Valkey mirror call so it can never affect the primary code path.+ *+ * - Real cancellation comes from `commandTimeout` on the shadow ioredis client+ * (set in `createCdpValkeyShadowPools`), which aborts at the protocol level.+ * The race below is a backstop — it stops the helper from awaiting beyond+ * `timeoutMs` even if the underlying client misbehaves.+ * - Catches any error or timeout and logs it.+ * - Always resolves to `undefined`, so the result can be dropped into+ * `Promise.all([...])` or `promiseScheduler.schedule(...)` alongside the+ * primary call.+ * - Wrapped in `instrumentFn` so latency / errors surface in tracing under+ * the `cdp.mirror.<label>` key.+ *+ * The `call` arg returns `Promise<unknown> | undefined` so the common pattern+ * of `() => this.fooMirror?.bar(args)` works directly: when the mirror is null+ * the inner expression evaluates to undefined and the helper short-circuits.+ */+export async function mirrorCall(+ label: string,+ call: () => Promise<unknown> | undefined,+ timeoutMs: number = DEFAULT_TIMEOUT_MS+): Promise<void> {+ return instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, async () => {+ let timeoutId: NodeJS.Timeout | undefined+ try {+ const promise = call()+ if (!promise) {+ return+ }+ await Promise.race([+ promise,+ new Promise<never>((_, reject) => {+ timeoutId = setTimeout(+ () => reject(new Error(`mirror call timed out after ${timeoutMs}ms`)),+ timeoutMs+ )+ }),+ ])+ } catch (err) {+ logger.warn('🪞', `[mirror:${label}] failed`, { err: String(err) })+ } finally {+ if (timeoutId) {+ clearTimeout(timeoutId)+ }+ }+ })+}diff --git a/nodejs/src/common/redis/redis-token-bucket.lua.ts b/nodejs/src/common/redis/redis-token-bucket-v2.lua.tssimilarity index 65%rename from nodejs/src/common/redis/redis-token-bucket.lua.tsrename to nodejs/src/common/redis/redis-token-bucket-v2.lua.tsindex 917afd70de8f..fd79d6869367 100644--- a/nodejs/src/common/redis/redis-token-bucket.lua.ts+++ b/nodejs/src/common/redis/redis-token-bucket-v2.lua.ts@@ -1,6 +1,6 @@import { Redis } from 'ioredis'-const LUA_TOKEN_BUCKET = `+const LUA_TOKEN_BUCKET_V2 = `local key = KEYS[1]local now = tonumber(ARGV[1])local cost = tonumber(ARGV[2])@@ -13,13 +13,19 @@ local before = redis.call('hget', key, 'ts')if before == false thenlocal tokensBefore = poolMaxlocal tokensAfter+ local poolToStoreif poolMax - cost >= 0 thentokensAfter = poolMax - cost+ poolToStore = tokensAfterelse+ -- Don't deduct cost we couldn't afford. Public return stays -1 so+ -- callers' tokensAfter <= 0 denial check is unchanged, but we store the+ -- full bucket so an impossible-cost first call doesn't burn the credit.tokensAfter = -1+ poolToStore = poolMaxendredis.call('hset', key, 'ts', now)- redis.call('hset', key, 'pool', tokensAfter)+ redis.call('hset', key, 'pool', poolToStore)redis.call('expire', key, expiry)return {tokensBefore, tokensAfter}end@@ -47,31 +53,30 @@ currentTokens = currentTokens + owedTokenslocal tokensBefore = currentTokens-- Remove the cost and calculate tokens after; cap stored pool at poolMax so silent--- periods do not let saved credit grow unbounded across many calls.+-- periods do not let saved credit grow unbounded across many calls. On denial we+-- still return -1 (preserves caller-side tokensAfter <= 0 contract) but persist the+-- un-deducted balance so partial refills accumulate across calls — without this,+-- sub-2 fractional fillRates wedge at -1 forever under sustained 1 req/s traffic.local tokensAfter+local poolToStoreif currentTokens - cost >= 0 thentokensAfter = math.min(currentTokens - cost, poolMax)+ poolToStore = tokensAfterelsetokensAfter = -1+ poolToStore = math.min(currentTokens, poolMax)end-redis.call('hset', key, 'pool', tokensAfter)+redis.call('hset', key, 'pool', poolToStore)redis.call('expire', key, expiry)-- Return both values for partial allowance calculationreturn {tokensBefore, tokensAfter}`-export const defineLuaTokenBucket = (client: Redis) => {- // NOTE: We removed the original command and both checks point at the new one- // Once deployed, we can follow up to use the non-v2 caller- client.defineCommand('checkRateLimit', {- numberOfKeys: 1,- lua: LUA_TOKEN_BUCKET,- })-+export const defineLuaTokenBucketV2 = (client: Redis) => {client.defineCommand('checkRateLimitV2', {numberOfKeys: 1,- lua: LUA_TOKEN_BUCKET,+ lua: LUA_TOKEN_BUCKET_V2,})}diff --git a/nodejs/src/common/redis/redis-token-bucket-v3.lua.ts b/nodejs/src/common/redis/redis-token-bucket-v3.lua.tsnew file mode 100644index 000000000000..fbe7e61f9957--- /dev/null+++ b/nodejs/src/common/redis/redis-token-bucket-v3.lua.ts@@ -0,0 +1,86 @@+import { Redis } from 'ioredis'++// V3 single-key token-bucket script.+//+// Optimizations vs V2 (script CPU was ~95% of Redis cost in prod):+// 1. ts + pool fetched in one HMGET (was two HGETs).+// 2. ts + pool written in one multi-field HSET (was two HSETs).+// 3. EXPIRE writes (expiry * 2) instead of expiry, and only on creation or+// when the remaining TTL drops below expiry/2 (was unconditional on+// every call). Cap is one EXPIRE per (expiry * 1.5) window per key.+// The 2x ceiling gives a 2x safety margin over V2: a key only expires+// after 2 * expiry of no calls (vs 1 * expiry in V2). PTTL adds ~0.2 μs+// 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.+const LUA_TOKEN_BUCKET_V3 = `+local key = KEYS[1]+local now = tonumber(ARGV[1])+local cost = tonumber(ARGV[2])+local poolMax = tonumber(ARGV[3])+local fillRate = tonumber(ARGV[4])+local expiry = tonumber(ARGV[5])++local existing = redis.call('hmget', key, 'ts', 'pool')+local rawBefore = existing[1]+local rawPool = existing[2]++local tokensBefore+local before+if rawBefore == false then+ before = false+ tokensBefore = poolMax+else+ before = tonumber(rawBefore)+ local timeDiffSeconds = now - before+ if timeDiffSeconds < 0 then+ timeDiffSeconds = 0+ end+ local currentTokens+ if rawPool == false then+ currentTokens = poolMax+ else+ currentTokens = tonumber(rawPool)+ end+ -- tokensBefore is the uncapped accrued credit. A catch-up call after a long+ -- silent period can therefore spend more than poolMax in one go. The cap is+ -- applied below on tokensAfter so the *stored* pool can never exceed poolMax.+ tokensBefore = currentTokens + (timeDiffSeconds * fillRate)+end++local tokensAfter+if tokensBefore - cost >= 0 then+ tokensAfter = math.min(tokensBefore - cost, poolMax)+else+ tokensAfter = -1+end++-- Don't regress ts when now < before; otherwise advance to now.+local tsToWrite+if before ~= false and now < before then+ tsToWrite = before+else+ tsToWrite = now+end++redis.call('hset', key, 'ts', tsToWrite, 'pool', tokensAfter)++-- 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)+-- which are both < any positive threshold, so the refresh fires defensively+-- if the TTL is ever lost.+if before == false or redis.call('pttl', key) < (expiry * 500) then+ redis.call('expire', key, expiry * 2)+end++return {tokensBefore, tokensAfter}+`++export const defineLuaTokenBucketV3 = (client: Redis) => {+ client.defineCommand('checkRateLimitV3', {+ numberOfKeys: 1,+ lua: LUA_TOKEN_BUCKET_V3,+ })+}diff --git a/nodejs/src/common/redis/redis-v2.ts b/nodejs/src/common/redis/redis-v2.tsindex 76b70b0a28f5..0051667edad6 100644--- a/nodejs/src/common/redis/redis-v2.ts+++ b/nodejs/src/common/redis/redis-v2.ts@@ -5,17 +5,18 @@ import { RedisPoolConfig, createRedisFromConfig } from '../../utils/db/redis'import { timeoutGuard } from '../../utils/db/utils'import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'-import { defineLuaTokenBucket } from './redis-token-bucket.lua'+import { defineLuaTokenBucketV2 } from './redis-token-bucket-v2.lua'+import { defineLuaTokenBucketV3 } from './redis-token-bucket-v3.lua'-type WithCheckRateLimit<T, TV2> = {- checkRateLimit: (key: string, now: number, cost: number, poolMax: number, fillRate: number, expiry: number) => T+type WithCheckRateLimit<TV2, TV3> = {checkRateLimitV2: (key: string, now: number, cost: number, poolMax: number, fillRate: number, expiry: number) => TV2+ checkRateLimitV3: (key: string, now: number, cost: number, poolMax: number, fillRate: number, expiry: number) => TV3}-export type RedisClientPipeline = Pipeline & WithCheckRateLimit<number, [number, number]>+export type RedisClientPipeline = Pipeline & WithCheckRateLimit<[number, number], [number, number]>export type RedisClient = Omit<Redis, 'pipeline'> &- WithCheckRateLimit<Promise<number>, Promise<[number, number]>> & {+ WithCheckRateLimit<Promise<[number, number]>, Promise<[number, number]>> & {pipeline: () => RedisClientPipeline}@@ -39,7 +40,8 @@ export const createRedisV2PoolFromConfig = (config: RedisPoolConfig): RedisV2 =>create: async () => {const client = await createRedisFromConfig(config.connection)- defineLuaTokenBucket(client)+ defineLuaTokenBucketV2(client)+ defineLuaTokenBucketV3(client)return client as RedisClient},diff --git a/nodejs/src/common/services/keyed-rate-limiter.bench.test.ts b/nodejs/src/common/services/keyed-rate-limiter.bench.test.tsnew file mode 100644index 000000000000..32123e175317--- /dev/null+++ b/nodejs/src/common/services/keyed-rate-limiter.bench.test.ts@@ -0,0 +1,190 @@+/**+ * 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 51bb19c0accb..1a2e97eda30d 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.test.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.test.ts@@ -41,122 +41,440 @@ describe('KeyedRateLimiterService', () => {jest.clearAllMocks()})- const buildLimiter = (name: string, overrides: Partial<{ bucketSize: number; refillRate: number }> = {}) =>+ const buildLimiter = (+ name: string,+ overrides: Partial<{ bucketSize: number; refillRate: number; ttlSeconds: number }> = {}+ ) =>new KeyedRateLimiterService({name,bucketSize: overrides.bucketSize ?? 100,refillRate: overrides.refillRate ?? 10,- ttlSeconds: 60 * 60 * 24,+ ttlSeconds: overrides.ttlSeconds ?? 60 * 60 * 24,},redis)- it('uses tokens for an id', async () => {- const limiter = buildLimiter('test-basic')- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ const readBucket = async (key: string): Promise<{ ts: string | null; pool: string | null }> => {+ const result = await redis.useClient({ name: 'read-bucket' }, async (client) => {+ const [ts, pool] = await Promise.all([client.hget(key, 'ts'), client.hget(key, 'pool')])+ return { ts, pool }+ })+ return result ?? { ts: null, pool: null }+ }- const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])+ describe('rateLimitMany (V2 pipelined per-call)', () => {+ it('uses tokens for an id', async () => {+ const limiter = buildLimiter('test-basic')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- expect(res).toEqual([['team-1', { tokens: 99, isRateLimited: false }]])- })+ const res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- it('rate limits when exceeding the bucket', async () => {- const limiter = buildLimiter('test-exceed')- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ expect(res).toEqual([['team-1', { tokens: 99, isRateLimited: false }]])+ })- let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 99 }])- expect(res[0][1]).toEqual({ tokens: 1, isRateLimited: false })+ it('rate limits when exceeding the bucket', async () => {+ const limiter = buildLimiter('test-exceed')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])- expect(res[0][1]).toEqual({ tokens: 0, isRateLimited: true })+ let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 99 }])+ expect(res[0][1]).toEqual({ tokens: 1, isRateLimited: false })- res = await limiter.rateLimitMany([{ id: 'team-1', cost: 20 }])- expect(res[0][1].isRateLimited).toBe(true)- })+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 1 }])+ expect(res[0][1]).toEqual({ tokens: 0, isRateLimited: true })- it('refills over time according to refillRate', async () => {- const limiter = buildLimiter('test-refill')- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 20 }])+ expect(res[0][1].isRateLimited).toBe(true)+ })- let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 50 }])- expect(res[0][1].tokens).toBe(50)+ it('refills over time according to refillRate', async () => {+ const limiter = buildLimiter('test-refill')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- advanceTime(1000)- res = await limiter.rateLimitMany([{ id: 'team-1', cost: 0 }])- expect(res[0][1].tokens).toBe(60)- })+ let res = await limiter.rateLimitMany([{ id: 'team-1', cost: 50 }])+ expect(res[0][1].tokens).toBe(50)- it('isolates ids that share a limiter via different keys', async () => {- const limiter = buildLimiter('test-multi')- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ advanceTime(1000)+ res = await limiter.rateLimitMany([{ id: 'team-1', cost: 0 }])+ expect(res[0][1].tokens).toBe(60)+ })- const res = await limiter.rateLimitMany([- { id: 'team-1', cost: 1 },- { id: 'team-2', cost: 5 },- ])+ it('isolates ids that share a limiter via different keys', async () => {+ const limiter = buildLimiter('test-multi')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- expect(res).toEqual([- ['team-1', { tokens: 99, isRateLimited: false }],- ['team-2', { tokens: 95, isRateLimited: false }],- ])- })+ 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 }],+ ])+ })- it('isolates two limiters that share a Redis via different prefixes', async () => {- const limiterA = buildLimiter('test-prefix-a')- const limiterB = buildLimiter('test-prefix-b')- await deleteKeysWithPrefix(redis, limiterA.getKeyPrefix())- await deleteKeysWithPrefix(redis, limiterB.getKeyPrefix())+ it('isolates two limiters that share a Redis via different prefixes', async () => {+ const limiterA = buildLimiter('test-prefix-a')+ const limiterB = buildLimiter('test-prefix-b')+ await deleteKeysWithPrefix(redis, limiterA.getKeyPrefix())+ await deleteKeysWithPrefix(redis, limiterB.getKeyPrefix())- // Drain limiter A entirely.- 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)+ 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.rateLimitMany([{ id: 'shared-id', cost: 1 }])- expect(freshB[0][1]).toEqual({ tokens: 99, isRateLimited: false })- })+ // Same id under limiter B is untouched — confirms prefix isolation.+ const freshB = await limiterB.rateLimitMany([{ id: 'shared-id', cost: 1 }])+ expect(freshB[0][1]).toEqual({ tokens: 99, isRateLimited: false })+ })- it('uses test-prefixed redis keys when NODE_ENV=test', () => {- const limiter = buildLimiter('node-env-check')- expect(limiter.getKeyPrefix().startsWith('@posthog-test/')).toBe(true)- })+ it('uses test-prefixed redis keys when NODE_ENV=test', () => {+ const limiter = buildLimiter('node-env-check')+ 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('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(),- // Simulate the failOpen path inside RedisV2: usePipeline returns null on error.- usePipeline: jest.fn().mockResolvedValue(null),- } as unknown as RedisV2- )+ 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 }],+ ])+ })- const res = await limiter.rateLimitMany([- { id: 'a', cost: 1 },- { id: 'b', cost: 2 },- ])+ it('honours per-call bucketSize and refillRate overrides', async () => {+ const limiter = buildLimiter('test-per-call')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())- expect(res).toEqual([- ['a', { tokens: 50, isRateLimited: false }],- ['b', { tokens: 50, isRateLimited: false }],- ])+ // 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 }])++ 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 }])+ expect(res[0][1].tokens).toBe(-1)+ expect(res[0][1].isRateLimited).toBe(true)+ })++ it('treats cost=0 as a peek without changing tokens', async () => {+ 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 }])+ 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+ advanceTime(5_000) // 5s × 10/s = 50 accrued+ 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 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)+ })})- it('honours per-call bucketSize and refillRate overrides', async () => {- const limiter = buildLimiter('test-per-call', { bucketSize: 100, refillRate: 10 })- await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ 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())++ const res = await limiter.rateLimitGrouped([+ { id: 'team-1', cost: 1 },+ { id: 'team-2', cost: 1 },+ { id: 'team-1', cost: 1 },+ ])++ expect(res).toHaveLength(3)+ expect(res[0][0]).toBe('team-1')+ expect(res[1][0]).toBe('team-2')+ expect(res[2][0]).toBe('team-1')+ })++ 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.+ const limiter = buildLimiter('grouped-fanout', { bucketSize: 4, refillRate: 0 })+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())++ const requests = Array.from({ length: 10 }, () => ({ id: 'team-1', cost: 1 }))+ const res = await limiter.rateLimitGrouped(requests)++ expect(res.map(([, r]) => r.tokens)).toEqual([3, 2, 1, 0, -1, -1, -1, -1, -1, -1])+ expect(res.map(([, r]) => r.isRateLimited)).toEqual([+ false,+ false,+ false,+ true, // tokens=0 — boundary, flagged as rate-limited+ true,+ true,+ true,+ true,+ true,+ true,+ ])+ })++ 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.+ const res = await limiter.rateLimitGrouped([+ { id: 'team-1', cost: 1 },+ { id: 'team-2', cost: 1 },+ { id: 'team-1', cost: 1 },+ { id: 'team-2', cost: 1 },+ { id: 'team-1', cost: 1 },+ { id: 'team-2', cost: 1 },+ ])++ 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])+ })++ 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).+ const limiter = buildLimiter('grouped-dispatch-count')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())++ const before = await redis.useClient({ name: 'before' }, async (client) => client.info('commandstats'))+ await redis.useClient({ name: 'reset' }, async (client) => client.config('RESETSTAT'))++ const requests = Array.from({ length: 10 }, () => ({ id: 'team-1', cost: 1 }))+ await limiter.rateLimitGrouped(requests)++ const after = await redis.useClient({ name: 'after' }, async (client) => client.info('commandstats'))+ const evalshaMatch = /cmdstat_evalsha:calls=(\d+)/.exec(after ?? '')+ const evalshaCount = evalshaMatch ? Number(evalshaMatch[1]) : 0+ expect(evalshaCount).toBe(1)++ // Sanity: at least proves we read INFO before/after, not testing those.+ expect(typeof before).toBe('string')+ })++ it('returns empty array for empty input without touching Redis', async () => {+ const limiter = buildLimiter('grouped-empty')+ const res = await limiter.rateLimitGrouped([])+ expect(res).toEqual([])+ })++ it('fails open when the Redis pipeline fails', async () => {+ const limiter = new KeyedRateLimiterService(+ { name: 'grouped-fail-open', bucketSize: 50, refillRate: 1, ttlSeconds: 60 },+ {+ useClient: jest.fn(),+ usePipeline: jest.fn().mockResolvedValue(null),+ } as unknown as RedisV2+ )++ const res = await limiter.rateLimitGrouped([+ { id: 'a', cost: 1 },+ { id: 'b', cost: 2 },+ { id: 'a', cost: 1 },+ ])++ expect(res.map(([id]) => id)).toEqual(['a', 'b', 'a'])+ // All three allowed — fail-open assumes full bucket.+ 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 () => {+ const limiter = buildLimiter('grouped-accrued')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())++ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 100 }]) // pool=0+ advanceTime(20_000) // 20s × 10/s = 200 accrued+ const 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 }]])+ })++ it('sets TTL to 2x ttlSeconds on creation (V3 ceiling)', async () => {+ const limiter = buildLimiter('grouped-ttl-create', { ttlSeconds: 60 })+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ const key = `${limiter.getKeyPrefix()}/team-1`++ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 5 }])++ const ttl = await redis.useClient({ name: 'ttl-check' }, async (client) => await client.ttl(key))+ expect(ttl).toBeGreaterThan(60)+ expect(ttl).toBeLessThanOrEqual(120)+ })- // 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 }])+ it('does NOT refresh TTL while remaining is above ttlSeconds/2', async () => {+ const limiter = buildLimiter('grouped-ttl-stable', { ttlSeconds: 60 })+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ const key = `${limiter.getKeyPrefix()}/team-1`- expect(res[0][1].isRateLimited).toBe(true)+ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])+ // Force PTTL to ~50s — well above the 30s threshold (ttlSeconds/2).+ await redis.useClient({ name: 'pexpire' }, async (client) => await client.pexpire(key, 50_000))+ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])++ const ttlMs = await redis.useClient({ name: 'pttl-check' }, async (client) => await client.pttl(key))+ expect(ttlMs).toBeGreaterThan(0)+ expect(ttlMs).toBeLessThanOrEqual(50_000)+ })++ it('refreshes TTL once remaining drops below ttlSeconds/2', async () => {+ const limiter = buildLimiter('grouped-ttl-refresh', { ttlSeconds: 60 })+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ const key = `${limiter.getKeyPrefix()}/team-1`++ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])+ // Force PTTL to ~10s — well below the 30s threshold.+ await redis.useClient({ name: 'pexpire' }, async (client) => await client.pexpire(key, 10_000))+ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 1 }])++ const ttlMs = await redis.useClient({ name: 'pttl-check' }, async (client) => await client.pttl(key))+ // Refresh fired — TTL bounces back near 2 × ttlSeconds (= 120s).+ expect(ttlMs).toBeGreaterThan(60_000)+ expect(ttlMs).toBeLessThanOrEqual(120_000)+ })++ it('persists ts + pool to redis (storage shape unchanged from V2)', async () => {+ const limiter = buildLimiter('grouped-persist')+ await deleteKeysWithPrefix(redis, limiter.getKeyPrefix())+ const key = `${limiter.getKeyPrefix()}/team-1`++ await limiter.rateLimitGrouped([{ id: 'team-1', cost: 5 }])+ const stored = await readBucket(key)+ expect(stored.ts).toBe(String(Math.round(now / 1000)))+ expect(stored.pool).toBe('95')+ })})})diff --git a/nodejs/src/common/services/keyed-rate-limiter.service.ts b/nodejs/src/common/services/keyed-rate-limiter.service.tsindex ab8af3d5f81b..f12420e605b9 100644--- a/nodejs/src/common/services/keyed-rate-limiter.service.ts+++ b/nodejs/src/common/services/keyed-rate-limiter.service.ts@@ -1,30 +1,26 @@+import { Counter } from 'prom-client'+import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'+const requestsTotal = new Counter({+ name: 'keyed_rate_limiter_requests_total',+ help: 'Per-input rate-limit decisions, labelled by outcome.',+ labelNames: ['name', 'method', 'outcome'],+})+const redisCallsTotal = new Counter({+ name: 'keyed_rate_limiter_redis_calls_total',+ help: 'Lua script dispatches. requests/redis_calls = grouping ratio.',+ labelNames: ['name', 'method'],+})+/*** Token-bucket rate limiter keyed by an arbitrary string id, backed by Redis.- *- * The Redis key prefix is configurable so multiple independent limiters- * (e.g. error tracking, future per-event-name limits) can share a Redis- * without colliding. Built on the same `checkRateLimitV2` Lua command that- * powers `HogRateLimiterService`.- *- * Per-call bucket params (bucketSize / refillRate / ttlSeconds on the request)- * are supported so the same service instance can run different limits for- * different ids — e.g. per-team overrides without rebuilding the service.+ * Multiple limiters can share a Redis via different `name` prefixes.*/export interface KeyedRateLimiterConfig {- /**- * Logical name for this limiter — used to build the Redis key prefix- * (`@posthog/<name>/tokens/<id>`). In `NODE_ENV=test` the prefix is- * `@posthog-test/<name>/tokens/<id>` so test runs don't collide with- * production keys when sharing a Redis.- */+ /** Logical name; produces `@posthog/<name>/tokens/<id>` keys (`@posthog-test/...` under NODE_ENV=test). */name: string- /**- * Default bucket params used when a request doesn't specify its own.- * Optional — callers that always supply per-request overrides can omit them.- * `rateLimitArgs` throws if a request reaches Redis without either source.- */+ /** Default bucket params; per-request overrides take precedence. */bucketSize?: numberrefillRate?: numberttlSeconds?: number@@ -33,11 +29,8 @@ export interface KeyedRateLimiterConfig {export interface KeyedRateLimitRequest {id: stringcost: number- /** Override the service's default bucket capacity for this request. */bucketSize?: number- /** Override the service's default replenish rate for this request. */refillRate?: number- /** Override the service's default Redis key TTL for this request. */ttlSeconds?: number}@@ -100,23 +93,115 @@ export class KeyedRateLimiterService {})+ redisCallsTotal.inc({ name: this.config.name, method: 'rateLimitMany' }, requests.length)+if (!res) {- // failOpen swallowed an error — treat all as not rate limited so we- // don't drop ingestion just because Redis blipped. Reflect each- // request's own (potentially overridden) bucketSize in the response.+ // 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 }])}- return requests.map((req, index) => {+ 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]- return [- req.id,- {- tokens: Number(tokensAfter),- isRateLimited: Number(tokensAfter) <= 0,- },- ]+ 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.+ *+ * 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) {+ return []+ }++ const grouped = new Map<string, KeyedRateLimitRequest>()+ for (const req of requests) {+ const existing = grouped.get(req.id)+ if (existing) {+ existing.cost += req.cost+ } else {+ grouped.set(req.id, { ...req })+ }+ }++ const items = [...grouped.values()]+ const bucketSizes = items.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-grouped:${this.config.name}`, failOpen: true },+ (pipeline) => {+ items.forEach((req) => {+ pipeline.checkRateLimitV3(...this.rateLimitArgs(req))+ })+ }+ )++ redisCallsTotal.inc({ name: this.config.name, method: 'rateLimitGrouped' }, items.length)++ 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])+ }+ })++ let allowed = 0+ let limited = 0+ const out: [string, KeyedRateLimit][] = requests.map((req) => {+ const remaining = budgetById.get(req.id) ?? 0+ if (remaining >= req.cost) {+ const next = remaining - req.cost+ budgetById.set(req.id, next)+ const isRateLimited = next <= 0+ if (isRateLimited) {+ limited+++ } else {+ allowed+++ }+ return [req.id, { tokens: next, isRateLimited }]+ }+ limited+++ return [req.id, { tokens: -1, isRateLimited: true }]+ })+ if (allowed > 0) {+ requestsTotal.inc({ name: this.config.name, method: 'rateLimitGrouped', outcome: 'allowed' }, allowed)+ }+ if (limited > 0) {+ requestsTotal.inc({ name: this.config.name, method: 'rateLimitGrouped', outcome: 'limited' }, limited)+ }+ return out}}diff --git a/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.test.ts b/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.test.tsindex f0f851eeb8da..de472a2281ba 100644--- a/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.test.ts+++ b/nodejs/src/logs-ingestion/services/logs-rate-limiter.service.test.ts@@ -202,7 +202,7 @@ describe('LogsRateLimiterService', () => {expect(res).toEqual([[teamId1, { tokensBefore: 100, tokensAfter: 100, isRateLimited: false }]])})- it('should recover from negative pool over time', async () => {+ it('should recover from empty pool over time', async () => {// Exhaust the bucket completelyawait rateLimiter.rateLimitMany([[teamId1, 100, Math.round(now / 1000)]])const res = await rateLimiter.rateLimitMany([[teamId1, 50, Math.round(now / 1000)]])@@ -211,14 +211,15 @@ describe('LogsRateLimiterService', () => {expect(res[0][1].tokensAfter).toBe(-1)expect(res[0][1].isRateLimited).toBe(true)- // Wait for refill (2 seconds = 20KB)+ // Wait for refill (2 seconds = 20KB). The cost=50 denial above didn't+ // drain the bucket below 0 — denied requests don't deduct — so refill+ // starts from 0, not -1.advanceTime(2000)const res2 = await rateLimiter.rateLimitMany([[teamId1, 0, Math.round(now / 1000)]])- // Pool was -1, refills by 20, so now 19- expect(res2[0][1].tokensBefore).toBe(19)- expect(res2[0][1].tokensAfter).toBe(19)+ expect(res2[0][1].tokensBefore).toBe(20)+ expect(res2[0][1].tokensAfter).toBe(20)expect(res2[0][1].isRateLimited).toBe(false)})