Skip to content

: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.

fix(cdp): make watcher reads cluster safe (#76819)

Ben Whitefab08ec7880c
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 8eefb9ded9bf..f5875d17408b 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -167,6 +167,9 @@ services:
CLICKHOUSE_DATABASE: ${CLICKHOUSE_DATABASE:-posthog}
# CDP Redis defaults to 127.0.0.1 — must point to the Docker service
CDP_REDIS_HOST: redis7
+ CDP_VALKEY_HOST: valkey-cluster
+ CDP_VALKEY_PORT: 6379
+ CDP_VALKEY_DUAL_ENABLED: 'true'
# Encryption keys default is only set when NODE_ENV=dev, but the image uses production
ENCRYPTION_SALT_KEYS: '00beef0000beef0000beef0000beef00'
# PersonHog is required for CDP — point at the local gRPC router
@@ -177,6 +180,8 @@ services:
condition: service_started
redis7:
condition: service_healthy
+ valkey-cluster:
+ condition: service_healthy
db:
condition: service_healthy
personhog-router:
@@ -381,6 +386,31 @@ services:
ports:
- '6379:6379'
+ valkey-cluster:
+ image: valkey/valkey:8.1-alpine
+ restart: on-failure
+ ports:
+ - '127.0.0.1:6390:6379'
+ command:
+ - /bin/sh
+ - -ec
+ - |
+ valkey-server --cluster-enabled yes --cluster-config-file /tmp/nodes.conf --cluster-node-timeout 5000 &
+ pid=$$!
+ until valkey-cli ping >/dev/null 2>&1; do sleep 0.1; done
+ valkey-cli cluster addslots $$(seq 0 16383)
+ wait $$pid
+ healthcheck:
+ test:
+ [
+ 'CMD-SHELL',
+ 'valkey-cli cluster info | grep -q cluster_state:ok && test "$$(valkey-cli cluster info | sed -n "s/cluster_slots_assigned://p" | tr -d "\r")" = 16384',
+ ]
+ interval: 2s
+ timeout: 3s
+ retries: 15
+ start_period: 5s
+
redis-cluster:
image: redis:7.2
restart: on-failure
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts
index 2642e8084140..e51a0a97c17b 100644
--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.test.ts
@@ -582,16 +582,13 @@ describe('HogWatcher', () => {
})
it('should fall back to the writer when the reader throws on getPersistedStates', async () => {
+ await watcher.observeResults([createResult({ duration: 1000, kind: 'hog' })])
+
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)
- // observeResults uses useClient (mget), getPersistedState uses usePipeline
- expect(failingReader.useClient).toHaveBeenCalledTimes(1)
expect(failingReader.usePipeline).toHaveBeenCalledTimes(1)
expect(state.tokens).toBeLessThan(watcherConfig.bucketSize)
expect(loggerWarnSpy).toHaveBeenCalledWith(
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts
index 81cc3e896a40..04ec8505d83c 100644
--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts
@@ -99,7 +99,8 @@ export class HogWatcherService {
results: CyclotronJobInvocationResult[]
promise: Promise<void>
timeout: NodeJS.Timeout
- complete: () => void
+ resolve: () => void
+ reject: (error: unknown) => void
} | null = null
private redisReader: RedisV2
@@ -466,15 +467,27 @@ export class HogWatcherService {
// Split reads (state/lock) to the reader and writes (token bucket) to the writer.
// These can run concurrently since the reads don't depend on the write results.
- // Uses mget to batch all state keys and lock keys into 2 commands instead of 2N individual gets.
const stateKeys = functionCostEntries.map((fc) => `${REDIS_KEY_STATE}/${fc.functionId}`)
const lockKeys = functionCostEntries.map((fc) => `${REDIS_KEY_STATE_LOCK}/${fc.functionId}`)
- const readStates = (pool: RedisV2) =>
- pool.useClient({ name: 'readStatesForObserve' }, async (client) => {
- const [states, locks] = await Promise.all([client.mget(...stateKeys), client.mget(...lockKeys)])
- return { states, locks }
+ const readStates = async (pool: RedisV2) => {
+ // Single-key pipeline commands avoid CROSSSLOT errors when function IDs map to different cluster slots.
+ const results = await pool.usePipeline({ name: 'readStatesForObserve' }, (pipeline) => {
+ stateKeys.forEach((key) => pipeline.get(key))
+ lockKeys.forEach((key) => pipeline.get(key))
})
+ if (!results) {
+ return null
+ }
+ const commandError = results.find(([error]) => error)?.[0]
+ if (commandError) {
+ throw commandError
+ }
+ return {
+ states: stateKeys.map((_, index) => results[index]?.[1]),
+ locks: lockKeys.map((_, index) => results[stateKeys.length + index]?.[1]),
+ }
+ }
const requests = functionCostEntries.map((fc) => ({ id: fc.functionId, cost: fc.cost }))
const [stateRes, rateLimitRes] = await Promise.all([
@@ -525,36 +538,43 @@ export class HogWatcherService {
// We need to make sure that we only process the results once
if (!this.queuedResults) {
let resolvePromise: () => void
- const promise = new Promise<void>((resolve) => {
+ let rejectPromise: (error: unknown) => void
+ const promise = new Promise<void>((resolve, reject) => {
resolvePromise = resolve
+ rejectPromise = reject
})
this.queuedResults = {
results: [],
promise,
- complete: resolvePromise!,
- timeout: setTimeout(() => this.flushBufferedResults(), this.config.observeResultsBufferTimeMs),
+ resolve: resolvePromise!,
+ reject: rejectPromise!,
+ timeout: setTimeout(() => void this.flushBufferedResults(), this.config.observeResultsBufferTimeMs),
}
}
this.queuedResults.results.push(result)
+ const bufferedPromise = this.queuedResults.promise
if (this.queuedResults.results.length >= this.config.observeResultsBufferMaxResults) {
- await this.flushBufferedResults()
- } else {
- await this.queuedResults.promise
+ void this.flushBufferedResults()
}
+ await bufferedPromise
}
- private async flushBufferedResults() {
+ private async flushBufferedResults(): Promise<void> {
if (!this.queuedResults) {
return
}
- const { results, timeout, complete } = this.queuedResults
+ const { results, timeout, resolve, reject } = this.queuedResults
clearTimeout(timeout)
this.queuedResults = null
- await this.observeResults(results)
- complete()
+ try {
+ await this.observeResults(results)
+ resolve()
+ } catch (error) {
+ reject(error)
+ }
}
}
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.unit.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.unit.test.ts
new file mode 100644
index 000000000000..81035e2964b3
--- /dev/null
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.unit.test.ts
@@ -0,0 +1,97 @@
+import { RedisClientPipeline, RedisV2 } from '~/common/redis/redis-v2'
+
+import { createExampleInvocation } from '../../_tests/fixtures'
+import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../../types'
+import { createInvocationResult } from '../../utils/invocation-utils'
+import { HogWatcherConfig, HogWatcherService } from './hog-watcher.service'
+
+const WATCHER_CONFIG: HogWatcherConfig = {
+ hogCostTimingLowerMs: 50,
+ hogCostTimingUpperMs: 550,
+ hogCostTiming: 100,
+ asyncCostTimingLowerMs: 100,
+ asyncCostTimingUpperMs: 5000,
+ asyncCostTiming: 20,
+ sendEvents: false,
+ bucketSize: 10000,
+ refillRate: 10,
+ ttl: 86400,
+ automaticallyDisableFunctions: true,
+ thresholdDegraded: 0.8,
+ stateLockTtl: 60,
+ observeResultsBufferTimeMs: 500,
+ observeResultsBufferMaxResults: 500,
+}
+
+const createResult = (id: string): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> => {
+ const invocation = createExampleInvocation({ id, team_id: 2 })
+ invocation.state.timings = [{ kind: 'hog', duration_ms: 100 }]
+ return createInvocationResult(invocation, {}, { finished: true })
+}
+
+const createClusterRedisStub = (): RedisV2 => ({
+ useClient: jest.fn(async (_options, callback) =>
+ callback({
+ mget: () => Promise.reject(new Error("CROSSSLOT Keys in request don't hash to the same slot")),
+ } as any)
+ ),
+ usePipeline: jest.fn((_options, callback) => {
+ const results: [null, unknown][] = []
+ const pipeline = {
+ get: () => {
+ results.push([null, null])
+ return pipeline
+ },
+ checkRateLimitV3: () => {
+ results.push([null, [9900, 0]])
+ return pipeline
+ },
+ } as unknown as RedisClientPipeline
+ callback(pipeline)
+ return Promise.resolve(results)
+ }),
+})
+
+describe('HogWatcherService unit behavior', () => {
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('observes multiple functions without issuing cross-slot commands', async () => {
+ const watcher = new HogWatcherService({} as any, WATCHER_CONFIG, createClusterRedisStub())
+
+ await expect(watcher.observeResults([createResult('first'), createResult('second')])).resolves.toBeUndefined()
+ })
+
+ it('falls back to the writer when a reader pipeline command fails', async () => {
+ const writer = createClusterRedisStub()
+ const commandError = new Error('reader command failed')
+ const reader: RedisV2 = {
+ useClient: jest.fn(),
+ usePipeline: jest.fn().mockResolvedValue([[commandError, undefined]]),
+ }
+ const watcher = new HogWatcherService({} as any, WATCHER_CONFIG, writer, reader)
+
+ await expect(watcher.observeResults([createResult('first'), createResult('second')])).resolves.toBeUndefined()
+ expect(writer.usePipeline).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'readStatesForObserve' }),
+ expect.any(Function)
+ )
+ })
+
+ it('rejects buffered callers when a timer-triggered flush fails', async () => {
+ jest.useFakeTimers()
+ const watcher = new HogWatcherService({} as any, WATCHER_CONFIG, createClusterRedisStub())
+ const error = new Error("CROSSSLOT Keys in request don't hash to the same slot")
+ jest.spyOn(watcher, 'observeResults').mockRejectedValue(error)
+
+ const bufferedResults = [
+ watcher.observeResultsBuffered(createResult('first')),
+ watcher.observeResultsBuffered(createResult('second')),
+ ]
+ const rejections = Promise.all(bufferedResults.map((result) => expect(result).rejects.toBe(error)))
+ await jest.advanceTimersByTimeAsync(WATCHER_CONFIG.observeResultsBufferTimeMs)
+
+ await rejections
+ })
+})
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.valkey.integration.test.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.valkey.integration.test.ts
new file mode 100644
index 000000000000..f3b97ba1c5f6
--- /dev/null
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.valkey.integration.test.ts
@@ -0,0 +1,82 @@
+import Redis from 'ioredis'
+
+import { defineLuaTokenBucketV2 } from '~/common/redis/redis-token-bucket-v2.lua'
+import { defineLuaTokenBucketV3 } from '~/common/redis/redis-token-bucket-v3.lua'
+import { RedisClient, RedisClientPipeline, RedisV2 } from '~/common/redis/redis-v2'
+import { TeamManager } from '~/common/utils/team-manager'
+
+import { createExampleInvocation } from '../../_tests/fixtures'
+import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../../types'
+import { createInvocationResult } from '../../utils/invocation-utils'
+import { BASE_REDIS_KEY, HogWatcherConfig, HogWatcherService } from './hog-watcher.service'
+
+const host = process.env.CDP_VALKEY_HOST ?? '127.0.0.1'
+const port = Number(process.env.CDP_VALKEY_PORT ?? 6390)
+
+const WATCHER_CONFIG: HogWatcherConfig = {
+ hogCostTimingLowerMs: 50,
+ hogCostTimingUpperMs: 550,
+ hogCostTiming: 100,
+ asyncCostTimingLowerMs: 100,
+ asyncCostTimingUpperMs: 5000,
+ asyncCostTiming: 20,
+ sendEvents: false,
+ bucketSize: 10000,
+ refillRate: 10,
+ ttl: 86400,
+ automaticallyDisableFunctions: true,
+ thresholdDegraded: 0.8,
+ stateLockTtl: 60,
+ observeResultsBufferTimeMs: 500,
+ observeResultsBufferMaxResults: 500,
+}
+
+const createResult = (id: string): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> => {
+ const invocation = createExampleInvocation({ id, team_id: 2 })
+ invocation.state.timings = [{ kind: 'hog', duration_ms: 100 }]
+ return createInvocationResult(invocation, {}, { finished: true })
+}
+
+describe('HogWatcher on Valkey Cluster', () => {
+ let valkey: Redis.Redis
+ let valkeyPool: RedisV2
+
+ const functionIds = ['valkey-integration-first', 'valkey-integration-second']
+ const stateKeys = functionIds.map((id) => `${BASE_REDIS_KEY}/state/${id}`)
+
+ beforeAll(async () => {
+ valkey = new Redis(port, host, { maxRetriesPerRequest: 1 })
+ defineLuaTokenBucketV2(valkey)
+ defineLuaTokenBucketV3(valkey)
+ await valkey.ping()
+ valkeyPool = {
+ useClient: async (_options, callback) => callback(valkey as unknown as RedisClient),
+ usePipeline: async (_options, callback) => {
+ const pipeline = valkey.pipeline() as RedisClientPipeline
+ callback(pipeline)
+ return pipeline.exec()
+ },
+ }
+ })
+
+ afterAll(async () => {
+ await valkey.quit()
+ })
+
+ it('reproduces CROSSSLOT, then observes the same functions without a multi-key command', async () => {
+ const slots = await Promise.all(stateKeys.map((key) => valkey.cluster('keyslot', key)))
+ expect(slots[0]).not.toEqual(slots[1])
+ await expect(valkey.mget(...stateKeys)).rejects.toThrow('CROSSSLOT')
+
+ const watcher = new HogWatcherService({} as TeamManager, WATCHER_CONFIG, valkeyPool)
+ await expect(watcher.observeResults(functionIds.map(createResult))).resolves.toBeUndefined()
+ })
+
+ it('allows MGET when keys share a hash tag', async () => {
+ await valkey.mset('valkey-test:{same}:first', 'first', 'valkey-test:{same}:second', 'second')
+ await expect(valkey.mget('valkey-test:{same}:first', 'valkey-test:{same}:second')).resolves.toEqual([
+ 'first',
+ 'second',
+ ])
+ })
+})