: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
fix(cdp): Route hog watcher reads to redis reader endpoint (#57517)
Daniel Marchuk02bb895e544b
diff --git a/nodejs/src/cdp/cdp-services.test.ts b/nodejs/src/cdp/cdp-services.test.tsnew file mode 100644index 000000000000..f92bba365813--- /dev/null+++ b/nodejs/src/cdp/cdp-services.test.ts@@ -0,0 +1,109 @@+import { RedisV2 } from '~/common/redis/redis-v2'++import { createCdpReaderRedisPool } from './cdp-services'++const mockReaderPool: RedisV2 = {+ useClient: jest.fn((_opts, cb) => cb({ ping: () => Promise.resolve('PONG') } as any)),+ usePipeline: jest.fn(),+}++jest.mock('~/common/redis/redis-v2', () => ({+ createRedisV2PoolFromConfig: jest.fn(() => mockReaderPool),+}))++const { createRedisV2PoolFromConfig } = require('~/common/redis/redis-v2') as {+ createRedisV2PoolFromConfig: jest.Mock+}++const mockWriterPool = { useClient: jest.fn(), usePipeline: jest.fn() } as unknown as RedisV2++const baseConfig = {+ CDP_REDIS_HOST: 'cdp-writer.internal',+ CDP_REDIS_PORT: 6379,+ CDP_REDIS_PASSWORD: 'secret',+ CDP_REDIS_READER_HOST: '',+ CDP_REDIS_READER_PORT: 6379,+ REDIS_URL: 'rediss://:password@fallback-host:6379',+ REDIS_POOL_MIN_SIZE: 1,+ REDIS_POOL_MAX_SIZE: 4,+}++describe('createCdpReaderRedisPool', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ it('creates a dedicated reader pool when CDP_REDIS_READER_HOST is set', () => {+ const config = { ...baseConfig, CDP_REDIS_READER_HOST: 'cdp-reader.internal', CDP_REDIS_READER_PORT: 6380 }++ const result = createCdpReaderRedisPool(config, mockWriterPool, 'test-redis')++ expect(result).toBe(mockReaderPool)+ expect(createRedisV2PoolFromConfig).toHaveBeenCalledWith({+ connection: {+ url: 'cdp-reader.internal',+ options: { port: 6380, password: 'secret' },+ name: 'test-redis-reader',+ },+ poolMinSize: 1,+ poolMaxSize: 4,+ })+ })++ it('runs a startup health check ping on the reader pool', async () => {+ const config = { ...baseConfig, CDP_REDIS_READER_HOST: 'cdp-reader.internal', CDP_REDIS_READER_PORT: 6380 }++ createCdpReaderRedisPool(config, mockWriterPool, 'test-redis')++ // Let the non-blocking ping resolve+ await Promise.resolve()++ expect(mockReaderPool.useClient).toHaveBeenCalledWith(+ { name: 'startup-ping', timeout: 5000 },+ expect.any(Function)+ )+ })++ it('logs an error if the reader health check fails', async () => {+ const pingError = new Error('connection refused')+ ;(mockReaderPool.useClient as jest.Mock).mockRejectedValueOnce(pingError)+ const logSpy = jest.spyOn(require('~/utils/logger').logger, 'error')+ const config = { ...baseConfig, CDP_REDIS_READER_HOST: 'bad-host.internal', CDP_REDIS_READER_PORT: 6380 }++ createCdpReaderRedisPool(config, mockWriterPool, 'test-redis')++ // Let the rejected promise and .catch handler run+ await new Promise((r) => setImmediate(r))++ expect(logSpy).toHaveBeenCalledWith(+ '🔌',+ expect.stringContaining('failed startup health check'),+ expect.objectContaining({ err: pingError })+ )+ })++ it('falls back to writer pool when CDP_REDIS_READER_HOST is not set', () => {+ const config = { ...baseConfig, CDP_REDIS_READER_HOST: '' }++ const result = createCdpReaderRedisPool(config, mockWriterPool, 'test-redis')++ expect(result).toBe(mockWriterPool)+ expect(createRedisV2PoolFromConfig).not.toHaveBeenCalled()+ })++ it('does not leak credentials from REDIS_URL in fallback log', () => {+ const logSpy = jest.spyOn(require('~/utils/logger').logger, 'info')+ const config = {+ ...baseConfig,+ CDP_REDIS_HOST: '',+ CDP_REDIS_READER_HOST: '',+ REDIS_URL: 'rediss://:[email protected]:6379',+ }++ createCdpReaderRedisPool(config, mockWriterPool, 'test-redis')++ const logMessage = logSpy.mock.calls[0]?.[1] as string+ expect(logMessage).not.toContain('supersecret')+ expect(logMessage).toContain('prod-redis.internal')+ })+})diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 58f71963a868..4004b79f1c81 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -1,4 +1,5 @@import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { getRedisHost } from '~/utils/db/redis'import type { CommonConfig } from '../common/config'import { InternalCaptureService } from '../common/services/internal-capture'@@ -6,6 +7,7 @@ import { AppMetricsOutput, LogEntriesOutput } from '../ingestion/common/outputs'import { IngestionOutputs } from '../ingestion/outputs/ingestion-outputs'import { KafkaProducerRegistry } from '../ingestion/outputs/kafka-producer-registry'import { PostgresRouter } from '../utils/db/postgres'+import { logger } from '../utils/logger'import { PubSub } from '../utils/pubsub'import { TeamManager } from '../utils/team-manager'import type { CdpConfig } from './config'@@ -79,6 +81,8 @@ export type CdpCoreServicesConfig = Pick<| 'CDP_REDIS_HOST'| 'CDP_REDIS_PORT'| 'CDP_REDIS_PASSWORD'+ | 'CDP_REDIS_READER_HOST'+ | 'CDP_REDIS_READER_PORT'| 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'| 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'| 'CDP_WATCHER_HOG_COST_TIMING'@@ -127,6 +131,59 @@ export interface CdpCoreServicesDeps {internalCaptureService: InternalCaptureService}+/**+ * Creates a Redis reader pool, using a dedicated reader host if configured,+ * otherwise falling back to the writer pool.+ */+export function createCdpReaderRedisPool(+ config: Pick<+ CdpCoreServicesConfig,+ | 'CDP_REDIS_HOST'+ | 'CDP_REDIS_PORT'+ | 'CDP_REDIS_PASSWORD'+ | 'CDP_REDIS_READER_HOST'+ | 'CDP_REDIS_READER_PORT'+ | 'REDIS_URL'+ | 'REDIS_POOL_MIN_SIZE'+ | 'REDIS_POOL_MAX_SIZE'+ >,+ writerPool: RedisV2,+ name: string+): RedisV2 {+ if (config.CDP_REDIS_READER_HOST) {+ logger.info(+ '🔌',+ `[${name}] writer=${config.CDP_REDIS_HOST}:${config.CDP_REDIS_PORT} reader=${config.CDP_REDIS_READER_HOST}:${config.CDP_REDIS_READER_PORT}`+ )+ const readerPool = createRedisV2PoolFromConfig({+ connection: {+ url: config.CDP_REDIS_READER_HOST,+ options: { port: config.CDP_REDIS_READER_PORT, password: config.CDP_REDIS_PASSWORD },+ name: `${name}-reader`,+ },+ poolMinSize: config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,+ })++ // Non-blocking startup health check — surfaces misconfig immediately in logs+ void readerPool+ .useClient({ name: 'startup-ping', timeout: 5000 }, (client) => client.ping())+ .catch((err) => {+ logger.error(+ '🔌',+ `[${name}] reader at ${config.CDP_REDIS_READER_HOST}:${config.CDP_REDIS_READER_PORT} failed startup health check — reads will fall back to writer`,+ { err }+ )+ })++ return readerPool+ }++ const sanitizedWriter = config.CDP_REDIS_HOST || getRedisHost(config.REDIS_URL)+ logger.info('🔌', `[${name}] writer=${sanitizedWriter}:${config.CDP_REDIS_PORT} reader=<falling back to writer>`)+ return writerPool+}+export function createCdpCoreServices(config: CdpCoreServicesConfig,deps: CdpCoreServicesDeps,@@ -144,6 +201,8 @@ export function createCdpCoreServices(poolMaxSize: config.REDIS_POOL_MAX_SIZE,})+ const redisReader = createCdpReaderRedisPool(config, redis, redisName)+const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)const hogFlowManager = new HogFlowManagerService(deps.postgres, deps.pubSub)@@ -166,7 +225,8 @@ export function createCdpCoreServices(observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,},- redis+ redis,+ redisReader)const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 75b964cb34ca..62f471480a36 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -61,6 +61,9 @@ export type CdpConfig = {CDP_REDIS_HOST: stringCDP_REDIS_PORT: numberCDP_REDIS_PASSWORD: string+ // Reuses CDP_REDIS_PASSWORD; falls back to the writer when host is unset.+ CDP_REDIS_READER_HOST: string+ CDP_REDIS_READER_PORT: numberCDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: booleanCDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: string@@ -154,6 +157,8 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_REDIS_HOST: '127.0.0.1',CDP_REDIS_PORT: 6379,CDP_REDIS_PASSWORD: '',+ CDP_REDIS_READER_HOST: '',+ CDP_REDIS_READER_PORT: 6379,CDP_EVENT_PROCESSOR_EXECUTE_FIRST_STEP: true,CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN: '',diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.tsindex c5c1944f5616..12e359ab36ad 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 } from '../cdp-services'+import { CdpCoreServicesConfig, createCdpReaderRedisPool } 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'@@ -455,6 +455,8 @@ export function createHogTransformerService(poolMinSize: config.REDIS_POOL_MIN_SIZE,poolMaxSize: config.REDIS_POOL_MAX_SIZE,})+ const redisReader = createCdpReaderRedisPool(config, redis, '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)const emailService = new EmailService(@@ -503,7 +505,8 @@ export function createHogTransformerService(observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,},- redis+ redis,+ redisReader)return new HogTransformerService(diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.tsindex 9fddf1bf87d6..48d76b7f003f 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts@@ -1,4 +1,5 @@import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { logger } from '~/utils/logger'import { Hub, ProjectId, Team } from '../../../types'import { closeHub, createHub } from '../../../utils/db/hub'@@ -552,4 +553,70 @@ describe('HogWatcher', () => {expect(observeResultsSpy).toHaveBeenCalledWith([results[3]])})})++ describe('reader fallback', () => {+ let loggerWarnSpy: jest.SpyInstance++ const makeFailingReader = (err: Error): RedisV2 => ({+ useClient: jest.fn(() => Promise.reject(err)),+ usePipeline: jest.fn(() => Promise.reject(err)),+ })++ beforeEach(() => {+ loggerWarnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined)+ })++ afterEach(() => {+ loggerWarnSpy.mockRestore()+ })++ it('should fall back to the writer when the reader throws on getPersistedStates', async () => {+ const failingReader = makeFailingReader(new Error('reader unavailable'))+ const watcherWithFailingReader = new HogWatcherService(hub.teamManager, watcherConfig, redis, failingReader)++ // Seed state on the writer so a successful fallback returns real data+ await watcherWithFailingReader.observeResults([createResult({ duration: 1000, kind: 'hog' })])++ const state = await watcherWithFailingReader.getPersistedState(hogFunctionId)++ expect(failingReader.usePipeline).toHaveBeenCalledTimes(1)+ expect(state.tokens).toBeLessThan(watcherConfig.bucketSize)+ expect(loggerWarnSpy).toHaveBeenCalledWith(+ '🔀',+ expect.stringContaining('reader getStates failed'),+ expect.any(Object)+ )+ })++ it('should fall back to the writer when the reader throws on getAllFunctionStates', async () => {+ // Seed enough cost to trigger a state transition - that's what writes the+ // state key that getAllFunctionStates SCANs for.+ await watcher.observeResults(Array(10000).fill(createResult({ duration: 25000, kind: 'async_function' })))++ const failingReader = makeFailingReader(new Error('reader unavailable'))+ const watcherWithFailingReader = new HogWatcherService(hub.teamManager, watcherConfig, redis, failingReader)++ const states = await watcherWithFailingReader.getAllFunctionStates()++ expect(failingReader.useClient).toHaveBeenCalledTimes(1)+ expect(Object.keys(states)).toContain(hogFunctionId)+ expect(loggerWarnSpy).toHaveBeenCalledWith(+ '🔀',+ expect.stringContaining('reader scanStates failed'),+ expect.any(Object)+ )+ })++ it('should not log a fallback when the reader is healthy', async () => {+ const healthyWatcher = new HogWatcherService(hub.teamManager, watcherConfig, redis, redis)++ await healthyWatcher.getPersistedState(hogFunctionId)++ expect(loggerWarnSpy).not.toHaveBeenCalledWith(+ '🔀',+ expect.stringContaining('reader getStates failed'),+ expect.any(Object)+ )+ })+ })})diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.tsindex 6c5a8583a4b0..329834f80763 100644--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts@@ -1,6 +1,6 @@import { Counter } from 'prom-client'-import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'+import { RedisClientPipeline, RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'import { LazyLoader } from '~/utils/lazy-loader'import { logger } from '~/utils/logger'import { captureTeamEvent } from '~/utils/posthog'@@ -95,11 +95,15 @@ export class HogWatcherService {complete: () => void} | null = null+ private redisReader: RedisV2+constructor(private teamManager: TeamManager,private config: HogWatcherConfig,- private redis: RedisV2+ private redis: RedisV2,+ redisReader?: RedisV2) {+ this.redisReader = redisReader ?? redisthis.costsMapping = {hog: {lowerBound: this.config.hogCostTimingLowerMs,@@ -201,12 +205,20 @@ export class HogWatcherService {const idsSet = new Set(ids)const nowSeconds = Math.round(Date.now() / 1000)- const res = await this.redis.usePipeline({ name: 'getStates' }, (pipeline) => {+ const buildGetStatesPipeline = (pipeline: RedisClientPipeline) => {for (const id of idsSet) {pipeline.hmget(`${REDIS_KEY_TOKENS}/${id}`, 'pool', 'ts')pipeline.get(`${REDIS_KEY_STATE}/${id}`)}- })+ }++ let res+ try {+ res = await this.redisReader.usePipeline({ name: 'getStates' }, buildGetStatesPipeline)+ } catch (err) {+ logger.warn('🔀', '[HogWatcher] reader getStates failed, falling back to writer', { err })+ res = await this.redis.usePipeline({ name: 'getStates' }, buildGetStatesPipeline)+ }return Array.from(idsSet).reduce((acc, id, index) => {@@ -280,19 +292,27 @@ export class HogWatcherService {}public async getAllFunctionStates(): Promise<Record<HogFunctionType['id'], HogWatcherFunctionState>> {- // Scan all state keys in Redis- const stateKeys = await this.redis.useClient({ name: 'scanStates' }, async (client) => {- const keys: string[] = []- let cursor = '0'-- do {- const [newCursor, batch] = await client.scan(cursor, 'MATCH', `${REDIS_KEY_STATE}/*`, 'COUNT', 500)- cursor = newCursor- keys.push(...batch)- } while (cursor !== '0')-- return keys- })+ const scan = (pool: RedisV2): Promise<string[] | null> =>+ pool.useClient({ name: 'scanStates' }, async (client) => {+ const keys: string[] = []+ let cursor = '0'++ do {+ const [newCursor, batch] = await client.scan(cursor, 'MATCH', `${REDIS_KEY_STATE}/*`, 'COUNT', 500)+ cursor = newCursor+ keys.push(...batch)+ } while (cursor !== '0')++ return keys+ })++ let stateKeys: string[] | null+ try {+ stateKeys = await scan(this.redisReader)+ } catch (err) {+ logger.warn('🔀', '[HogWatcher] reader scanStates failed, falling back to writer', { err })+ stateKeys = await scan(this.redis)+ }if (!stateKeys || stateKeys.length === 0) {return {}diff --git a/nodejs/src/utils/db/redis.test.ts b/nodejs/src/utils/db/redis.test.tsnew file mode 100644index 000000000000..55a610c5b277--- /dev/null+++ b/nodejs/src/utils/db/redis.test.ts@@ -0,0 +1,34 @@+import { getRedisHost } from './redis'++describe('getRedisHost', () => {+ it('extracts host from a standard rediss:// URL', () => {+ expect(getRedisHost('rediss://prod-host:6379')).toBe('prod-host:6379')+ })++ it('strips credentials from a URL with embedded password', () => {+ expect(getRedisHost('rediss://:secret@prod-host:6379')).toBe('prod-host:6379')+ })++ it('strips username and password from URL', () => {+ expect(getRedisHost('rediss://user:pass@my-host:6380/0')).toBe('my-host:6380')+ })++ it('handles a plain hostname that is not a valid URL', () => {+ expect(getRedisHost('my-redis-host')).toBe('my-redis-host')+ })++ it('strips credentials from a non-URL string containing @', () => {+ expect(getRedisHost(':password@hostname')).toBe('hostname')+ })++ it('appends port from options when hostname has no port', () => {+ expect(getRedisHost('hostname', { port: 6380 })).toBe('hostname:6380')+ })++ it('does not double-append port if hostname already has one', () => {+ // 'hostname:6379' parses as a URL with protocol 'hostname:' and pathname '6379'+ // so host is empty — falls through to sanitized placeholder+ // Use a non-URL format with @ to test the catch branch properly+ expect(getRedisHost(':pass@host:6379', { port: 6380 })).toBe('host:6379')+ })+})diff --git a/nodejs/src/utils/db/redis.ts b/nodejs/src/utils/db/redis.tsindex 8ba8f8a1c585..b61ebb28e3fd 100644--- a/nodejs/src/utils/db/redis.ts+++ b/nodejs/src/utils/db/redis.ts@@ -53,7 +53,7 @@ export function createRedisPoolFromConfig(config: RedisPoolConfig): RedisPool {* Sanitizes a Redis URL for safe logging by extracting only the host portion.* This prevents leaking credentials that may be embedded in the URL.*/-function getRedisHost(url: string, options?: RedisOptions): string {+export function getRedisHost(url: string, options?: RedisOptions): string {try {const parsed = new URL(url)return parsed.host || '[sanitized-redis-host]'