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.

feat(cdp): switch valkey reads per feature via env var (#79468)

Ben White5f272953ac1b
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index b16fce0c17d4..ea564f5fa992 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -53,7 +53,12 @@ import { HogFunctionManagerService } from './services/managers/hog-function-mana
import { EmailTrackingService } from './services/messaging/email-tracking.service'
import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'
import { RecipientTokensService } from './services/messaging/recipient-tokens.service'
-import { HogWatcherService, HogWatcherState } from './services/monitoring/hog-watcher.service'
+import {
+ HogWatcherService,
+ HogWatcherState,
+ sameWatcherState,
+ sameWatcherStates,
+} from './services/monitoring/hog-watcher.service'
import { NativeDestinationExecutorService } from './services/native-destination-executor.service'
import { SegmentDestinationExecutorService } from './services/segment-destination-executor.service'
import { HOG_FUNCTION_TEMPLATES } from './templates'
@@ -64,10 +69,10 @@ import {
isSegmentPluginHogFunction,
sanitizeLogMessage,
} from './utils'
+import { dualRead, dualWrite } from './utils/dual-store'
import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'
import { buildHogFunctionInvocations } from './utils/invocation-utils'
import { JWT, PosthogJwtAudience } from './utils/jwt-utils'
-import { mirrorCall, mirrorCompare } from './utils/mirror-call'
// Allowlist of safe content types for webhook responses to prevent XSS
const SAFE_CONTENT_TYPES = new Set([
@@ -309,10 +314,11 @@ export class CdpApi {
() =>
async (req: ModifiedRequest, res: express.Response): Promise<void> => {
const { id } = req.params
- const summary = await mirrorCompare(
+ const summary = await dualRead(
'hog-watcher.getPersistedState',
() => this.hogWatcher.getPersistedState(id),
- () => this.hogWatcherMirror.getPersistedState(id)
+ () => this.hogWatcherMirror.getPersistedState(id),
+ sameWatcherState
)
res.json(summary)
@@ -330,10 +336,11 @@ export class CdpApi {
return
}
- const summary = await mirrorCompare(
+ const summary = await dualRead(
'hog-watcher.getPersistedState',
() => this.hogWatcher.getPersistedState(id),
- () => this.hogWatcherMirror.getPersistedState(id)
+ () => this.hogWatcherMirror.getPersistedState(id),
+ sameWatcherState
)
const hogFunction = await this.hogFunctionManager.fetchHogFunction(id)
@@ -345,22 +352,22 @@ export class CdpApi {
// Only allow patching the status if it is different from the current status
if (summary.state !== state) {
- await Promise.all([
- this.hogWatcher.forceStateChange(hogFunction, state),
- mirrorCall('hog-watcher.forceStateChange', () =>
- this.hogWatcherMirror.forceStateChange(hogFunction, state)
- ),
- ])
+ await dualWrite(
+ 'hog-watcher.forceStateChange',
+ () => this.hogWatcher.forceStateChange(hogFunction, state),
+ () => this.hogWatcherMirror.forceStateChange(hogFunction, state)
+ )
}
// Hacky - wait for a little to give a chance for the state to change
await delay(100)
res.json(
- await mirrorCompare(
+ await dualRead(
'hog-watcher.getPersistedState',
() => this.hogWatcher.getPersistedState(id),
- () => this.hogWatcherMirror.getPersistedState(id)
+ () => this.hogWatcherMirror.getPersistedState(id),
+ sameWatcherState
)
)
}
@@ -369,10 +376,11 @@ export class CdpApi {
() =>
async (req: ModifiedRequest, res: express.Response): Promise<void> => {
try {
- const allStates = await mirrorCompare(
+ const allStates = await dualRead(
'hog-watcher.getAllFunctionStates',
() => this.hogWatcher.getAllFunctionStates(),
- () => this.hogWatcherMirror.getAllFunctionStates()
+ () => this.hogWatcherMirror.getAllFunctionStates(),
+ sameWatcherStates
)
// Transform the data for better consumption by Grafana and sort by tokens ascending
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 5b4cbf66da25..3e4d2fcbd093 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -43,6 +43,7 @@ import { NativeDestinationExecutorService } from './services/native-destination-
import { SegmentDestinationExecutorService } from './services/segment-destination-executor.service'
import { WarehouseWebhooksService } from './services/warehouse/warehouse-webhooks.service'
import { MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './utils/cdp-fetch'
+import { configureValkeyReads } from './utils/dual-store'
import { EncryptedFields } from './utils/encryption-utils'
/** Union of every output name resolved by `createCdpOutputsRegistry()`. */
@@ -58,17 +59,17 @@ export interface CdpValkeyShadowPools {
export interface CdpCoreServices {
redis: RedisV2
/**
- * Shadow Valkey pools used for dual-write/read. Consumers that build their own
+ * Valkey pools used for dual-write/read. Consumers that build their own
* redis-backed services (e.g. CdpEventsConsumer's HogRateLimiterService) read this
- * to construct mirror instances bound to the shadow Valkey.
+ * to construct the Valkey-bound twin.
*/
valkeyShadow: CdpValkeyShadowPools
hogFunctionManager: HogFunctionManagerService
hogFlowManager: HogFlowManagerService
hogWatcher: HogWatcherService
/**
- * Mirror HogWatcherService bound to the shadow Valkey pool. Use at call sites
- * alongside `hogWatcher` (via `mirrorCall`) to load-test the new infrastructure.
+ * Valkey-bound twin of `hogWatcher`. Use at call sites alongside `hogWatcher` via
+ * `dualRead` / `dualWrite`, which decide which of the two results the caller sees.
* Constructed with `sendEvents: false` so it never emits duplicate billable team events.
*/
hogWatcherMirror: HogWatcherService
@@ -116,6 +117,7 @@ export type CdpCoreServicesConfig = Pick<
| 'CDP_VALKEY_READER_HOST'
| 'CDP_VALKEY_READER_PORT'
| 'CDP_VALKEY_TLS'
+ | 'CDP_VALKEY_READ_FEATURES'
| 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'
| 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'
| 'CDP_WATCHER_HOG_COST_TIMING'
@@ -261,9 +263,10 @@ export function createCdpValkeyShadowPools(
`[${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.
+ // commandTimeout aborts in-flight commands at the ioredis protocol level, so a slow Valkey
+ // doesn't tie up a pool client until the kernel TCP timeout. Pair this with the race-timeout
+ // in dual-store's secondary path (which only stops awaiting); together they prevent leaks
+ // on bad Valkey health.
const shadowCommandTimeoutMs = 1000
const tls = config.CDP_VALKEY_TLS ? {} : undefined
@@ -283,15 +286,15 @@ export function createCdpValkeyShadowPools(
poolMaxSize: config.REDIS_POOL_MAX_SIZE,
})
- // The config is required, but reachability is not fatal: reads still come from the
- // primary Redis, so an unreachable Valkey must not take CDP down. It stays a
- // non-blocking check until reads move over.
+ // The config is required, but reachability is not fatal: features not named in
+ // CDP_VALKEY_READ_FEATURES still read from Redis, so an unreachable Valkey must not take
+ // CDP down at boot. Features that have moved over surface it as failing reads instead.
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()`,
+ `[${name}] shadow writer at ${config.CDP_VALKEY_HOST}:${config.CDP_VALKEY_PORT} failed startup health check — valkey ops will surface as "[mirror:*] failed" warn logs from dual-store`,
{ err }
)
})
@@ -347,6 +350,10 @@ export function createCdpCoreServices(
const redisReader = createCdpReaderRedisPool(config, redis, redisName)
const valkeyShadow = createCdpValkeyShadowPools(config, redisName)
+ // Every CDP process funnels through here, so this is the one place the per-feature read
+ // source has to be applied for `dualRead` / `dualWrite` to see it.
+ configureValkeyReads(config.CDP_VALKEY_READ_FEATURES)
+
const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)
const hogFlowManager = new HogFlowManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)
@@ -370,10 +377,10 @@ export function createCdpCoreServices(
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.
+ // Valkey-bound twin of the watcher. `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.
const hogWatcherMirror = new HogWatcherService(
deps.teamManager,
{ ...hogWatcherConfig, sendEvents: false },
@@ -423,7 +430,7 @@ export function createCdpCoreServices(
backoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
backoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
},
- redis,
+ // Valkey-only: push is pre-release, so it moved over whole rather than dual-writing.
valkeyShadow.writer,
messageAssetsService
)
@@ -459,7 +466,7 @@ export function createCdpCoreServices(
// whose capabilities execute email actions; everywhere else this is null
// and EmailValidationService degrades to the local cache + DNS.
const emailValidationService = new EmailValidationService(deps.emailValidationValkey)
- // Observer mirrors writes to Valkey (load-only); only the primary path drives metrics.
+ // Observer writes to both stores; the read source decides which verdict drives the metric.
const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow.writer)
const hogFlowExecutor = new HogFlowExecutorService(
hogFlowFunctionsService,
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index b7eca1915f64..bb1f8841856d 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -66,10 +66,9 @@ export type CdpConfig = ClickhouseConfig & {
CDP_REDIS_READER_HOST: string
CDP_REDIS_READER_PORT: number
- // Shadow Valkey pool for dual-write/read. CDP_VALKEY_HOST is required: every CDP
- // Redis call also runs against this pool, and a process without it is misconfigured
- // rather than degraded. Shadow results are discarded, and errors/timeouts are logged
- // and counted but never affect the primary code path.
+ // Valkey pool for dual-write/read. CDP_VALKEY_HOST is required: every CDP Redis call
+ // also runs against this pool, and a process without it is misconfigured rather than
+ // degraded.
CDP_VALKEY_HOST: string
CDP_VALKEY_PORT: number
CDP_VALKEY_PASSWORD: string
@@ -77,6 +76,12 @@ export type CdpConfig = ClickhouseConfig & {
CDP_VALKEY_READER_PORT: number
// AWS ElastiCache Valkey Serverless requires TLS; toggle off only for local non-TLS test setups.
CDP_VALKEY_TLS: boolean
+ // Comma-separated list of features (see MIRROR_FEATURES in utils/dual-store.ts) whose reads
+ // are served from Valkey rather than Redis. `*` selects every feature. Writes always go to
+ // both stores regardless, so a feature can be flipped back by removing it from this list.
+ // Check the cdp_valkey_mirror_operations_total mismatch/failed counts for a feature before
+ // flipping it: hog-watcher reads a missing key as healthy with a full token bucket.
+ CDP_VALKEY_READ_FEATURES: string
SES_RATE_LIMITER_VALKEY_HOST: string
SES_RATE_LIMITER_VALKEY_PORT: number
@@ -237,6 +242,7 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_VALKEY_READER_HOST: '',
CDP_VALKEY_READER_PORT: 6379,
CDP_VALKEY_TLS: false,
+ CDP_VALKEY_READ_FEATURES: '',
SES_RATE_LIMITER_VALKEY_HOST: '',
SES_RATE_LIMITER_VALKEY_PORT: 6379,
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
index 66b555ea7a2f..60755e174837 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
@@ -12,7 +12,7 @@ import {
CyclotronJobQueueKind,
} from '../types'
import { isLegacyPluginHogFunction, isNativeHogFunction, isSegmentPluginHogFunction } from '../utils'
-import { mirrorCall } from '../utils/mirror-call'
+import { dualWrite } from '../utils/dual-store'
import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'
/**
@@ -203,10 +203,11 @@ export class CdpCyclotronWorker<
@instrumented({ key: 'cdpConsumer.backgroundTask.hogWatcherObserve', timeoutMs: 10_000, sendException: false })
private async observeResults(invocationResults: CyclotronJobInvocationResult[]): Promise<void> {
try {
- await Promise.all([
- this.hogWatcher.observeResults(invocationResults),
- mirrorCall('hog-watcher.observeResults', () => this.hogWatcherMirror.observeResults(invocationResults)),
- ])
+ await dualWrite(
+ 'hog-watcher.observeResults',
+ () => this.hogWatcher.observeResults(invocationResults),
+ () => this.hogWatcherMirror.observeResults(invocationResults)
+ )
} catch (err: any) {
captureException(err)
logger.error('Error observing results', { err })
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
index 8a50218f5cf2..babf5fe07c94 100644
--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
@@ -11,7 +11,7 @@ import { HealthCheckResult, HealthCheckResultOk, PluginsServerConfig } from '../
import { createHogFlowInvocation } from '../services/hogflows/hogflow-executor.service'
import { actionIdForLogging } from '../services/hogflows/hogflow-utils'
import { JobQueue } from '../services/job-queue/job-queue.interface'
-import { HogWatcherFunctionState, HogWatcherState } from '../services/monitoring/hog-watcher.service'
+import { HogWatcherFunctionState, HogWatcherState, sameWatcherState } from '../services/monitoring/hog-watcher.service'
import {
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
@@ -22,8 +22,8 @@ import {
MinimalAppMetric,
} from '../types'
import { logEntry } from '../utils'
+import { dualRead, dualWrite } from '../utils/dual-store'
import { createInvocation, createInvocationResult } from '../utils/invocation-utils'
-import { mirrorCall, mirrorCompare } from '../utils/mirror-call'
import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'
const DISALLOWED_HEADERS = [
@@ -439,10 +439,11 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
const [webhook, hogFunctionState] = await Promise.all([
this.getWebhook(webhookId),
- mirrorCompare(
+ dualRead(
'hog-watcher.getCachedEffectiveState',
() => this.hogWatcher.getCachedEffectiveState(webhookId),
- () => this.hogWatcherMirror.getCachedEffectiveState(webhookId)
+ () => this.hogWatcherMirror.getCachedEffectiveState(webhookId),
+ sameWatcherState
),
])
@@ -472,8 +473,11 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
void this.promiseScheduler.schedule(
this.invocationResultsService.flush(),
- this.hogWatcher.observeResultsBuffered(result),
- mirrorCall('hog-watcher.observeResultsBuffered', () => this.hogWatcherMirror.observeResultsBuffered(result))
+ dualWrite(
+ 'hog-watcher.observeResultsBuffered',
+ () => this.hogWatcher.observeResultsBuffered(result),
+ () => this.hogWatcherMirror.observeResultsBuffered(result)
+ )
)
return result
diff --git a/nodejs/src/cdp/services/batch-export-hog-function.service.ts b/nodejs/src/cdp/services/batch-export-hog-function.service.ts
index 2c5a6ed27d47..376c64479589 100644
--- a/nodejs/src/cdp/services/batch-export-hog-function.service.ts
+++ b/nodejs/src/cdp/services/batch-export-hog-function.service.ts
@@ -12,8 +12,8 @@ import {
HogFunctionType,
} from '../types'
import { convertToHogFunctionInvocationGlobals } from '../utils'
+import { dualWrite } from '../utils/dual-store'
import { createInvocation } from '../utils/invocation-utils'
-import { mirrorCall } from '../utils/mirror-call'
import { HogExecutorAsyncService } from './hog-executor-async.service'
import { InvocationResultsService } from './invocation-results.service'
import { GroupsManagerService } from './managers/groups-manager.service'
@@ -99,9 +99,10 @@ export class BatchExportHogFunctionService {
void this.promiseScheduler.schedule(
Promise.all([
this.invocationResultsService.queueInvocationResultsAndFlush([result]),
- this.hogWatcher.observeResultsBuffered(result),
- mirrorCall('hog-watcher.observeResultsBuffered', () =>
- this.hogWatcherMirror.observeResultsBuffered(result)
+ dualWrite(
+ 'hog-watcher.observeResultsBuffered',
+ () => this.hogWatcher.observeResultsBuffered(result),
+ () => this.hogWatcherMirror.observeResultsBuffered(result)
),
])
)
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
index 95e7c186d125..ab169cd31354 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
@@ -17,13 +17,13 @@ import {
LogEntry,
MinimalAppMetric,
} from '../types'
-import { mirrorCompare } from '../utils/mirror-call'
+import { dualRead } from '../utils/dual-store'
import { HogFlowExecutorService } from './hogflows/hogflow-executor.service'
import { HogFlowManagerService } from './hogflows/hogflow-manager.service'
import { shouldBlockHogFlowDueToQuota } from './hogflows/hogflow-quota-limiting'
import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'
import { HogMaskerService } from './monitoring/hog-masker.service'
-import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'
+import { HogWatcherService, HogWatcherState, sameWatcherStates } from './monitoring/hog-watcher.service'
export interface HogFlowInvocationPipelineConfig {
CDP_RATE_LIMITER_BUCKET_SIZE: number
@@ -105,28 +105,29 @@ export class HogFlowInvocationPipeline {
).flat()
const hogFlowIds = possibleInvocations.map((x) => x.hogFlow.id)
- const states = await mirrorCompare(
+ const states = await dualRead(
'hog-watcher.getEffectiveStates',
() =>
instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {
return await this.deps.hogWatcher.getEffectiveStates(hogFlowIds)
}),
- () => this.deps.hogWatcherMirror.getEffectiveStates(hogFlowIds)
+ () => this.deps.hogWatcherMirror.getEffectiveStates(hogFlowIds),
+ sameWatcherStates
)
const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({
id: x.hogFlow.id,
cost: 1,
}))
- const rateLimits = await mirrorCompare(
- 'hog-rate-limiter.rateLimitGrouped',
+ const rateLimits = await dualRead(
+ 'hog-flow-rate-limiter.rateLimitGrouped',
() =>
instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {
return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)
}),
() => this.hogRateLimiterMirror.rateLimitGrouped(rateLimitInputs),
- (primary, mirror) =>
- primary.every(([, result], index) => result.isRateLimited === mirror[index]?.[1].isRateLimited)
+ (primary, secondary) =>
+ primary.every(([, result], index) => result.isRateLimited === secondary[index]?.[1].isRateLimited)
)
const validInvocations: CyclotronJobInvocationHogFlow[] = []
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
index 848263d9ab81..73ba8e097c1e 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
@@ -15,13 +15,13 @@ import {
HogFunctionTypeType,
MinimalAppMetric,
} from '../types'
+import { dualRead } from '../utils/dual-store'
import { buildHogFunctionInvocations } from '../utils/invocation-utils'
-import { mirrorCompare } from '../utils/mirror-call'
import { HogInputsService } from './hog-inputs.service'
import { HogFunctionManagerService } from './managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'
import { HogMaskerService } from './monitoring/hog-masker.service'
-import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'
+import { HogWatcherService, HogWatcherState, sameWatcherStates } from './monitoring/hog-watcher.service'
export interface HogFunctionInvocationPipelineConfig {
CDP_RATE_LIMITER_BUCKET_SIZE: number
@@ -103,28 +103,29 @@ export class HogFunctionInvocationPipeline {
).flat()
const hogFunctionIds = possibleInvocations.map((x) => x.hogFunction.id)
- const states = await mirrorCompare(
+ const states = await dualRead(
'hog-watcher.getEffectiveStates',
() =>
instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {
return await this.deps.hogWatcher.getEffectiveStates(hogFunctionIds)
}),
- () => this.deps.hogWatcherMirror.getEffectiveStates(hogFunctionIds)
+ () => this.deps.hogWatcherMirror.getEffectiveStates(hogFunctionIds),
+ sameWatcherStates
)
const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({
id: x.hogFunction.id,
cost: 1,
}))
- const rateLimits = await mirrorCompare(
- 'hog-rate-limiter.rateLimitGrouped',
+ const rateLimits = await dualRead(
+ 'hog-function-rate-limiter.rateLimitGrouped',
() =>
instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {
return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)
}),
() => this.hogRateLimiterMirror.rateLimitGrouped(rateLimitInputs),
- (primary, mirror) =>
- primary.every(([, result], index) => result.isRateLimited === mirror[index]?.[1].isRateLimited)
+ (primary, secondary) =>
+ primary.every(([, result], index) => result.isRateLimited === secondary[index]?.[1].isRateLimited)
)
const validInvocations: CyclotronJobInvocationHogFunction[] = []
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.ts
index 74f9d570ba3f..d59a5d449380 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.test.ts
@@ -62,12 +62,6 @@ describe('HogFlowDuplicateObserverService', () => {
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, valkey)
- 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, valkey)
await observer.observe(buildInvocation({ eventUuid: null }), buildAction('action-1'))
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts
index c0087cb0f28d..e9c0627b7d18 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-duplicate-observer.service.ts
@@ -5,7 +5,7 @@ import { RedisClient, RedisV2 } from '~/common/redis/redis-v2'
import { logger } from '~/common/utils/logger'
import { CyclotronJobInvocationHogFlow } from '../../types'
-import { mirrorCompare } from '../../utils/mirror-call'
+import { dualRead } from '../../utils/dual-store'
const DUPLICATE_OBSERVATION_TTL_SECONDS = 15 * 60
@@ -16,14 +16,13 @@ const hogflowDuplicateInvocationDetectedTotal = new Counter({
})
/**
- * Detects duplicate workflow invocations via a Redis SET-NX key per
- * (workflow, event, action). Every observation also fires against the Valkey mirror
- * in parallel — load is realised on the mirror; only the primary drives the
- * duplicate-detected metric.
+ * Detects duplicate workflow invocations via a SET-NX key per (workflow, event, action).
+ * Every observation fires against both Redis and Valkey in parallel; the store this feature
+ * currently reads from is the one whose verdict drives the duplicate-detected metric.
*/
export class HogFlowDuplicateObserverService {
constructor(
- private readonly redis: RedisV2 | null,
+ private readonly redis: RedisV2,
private readonly redisMirror: RedisV2
) {}
@@ -32,7 +31,7 @@ export class HogFlowDuplicateObserverService {
currentAction: HogFlowAction
): Promise<{ duplicate: boolean }> {
const eventUuid = invocation.state?.event?.uuid
- if (!this.redis || !eventUuid) {
+ if (!eventUuid) {
return { duplicate: false }
}
const key = `hogflow:observe:${invocation.functionId}:${eventUuid}:${currentAction.id}`
@@ -47,11 +46,11 @@ export class HogFlowDuplicateObserverService {
let duplicate = false
try {
- const existingId = await mirrorCompare(
+ const existingId = await dualRead(
'hog-flow-duplicate-observer.observe',
- () => this.redis!.useClient({ name: 'hogflow-observe', failOpen: true }, setNxGet),
+ () => this.redis.useClient({ name: 'hogflow-observe', failOpen: true }, setNxGet),
() => this.redisMirror.useClient({ name: 'hogflow-observe-mirror', failOpen: true }, setNxGet),
- (primary, mirror) => Boolean(primary) === Boolean(mirror)
+ (primary, secondary) => Boolean(primary) === Boolean(secondary)
)
if (existingId && existingId !== invocation.id) {
duplicate = true
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
index de62b765b0ef..1e797e47be81 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -64,9 +64,8 @@ describe('PushNotificationService', () => {
let service: PushNotificationService
let integrationManager: IntegrationManagerService
let fetchUtils: PushNotificationFetchUtils
- let redisStore: Map<string, string>
- let mockRedisSet: jest.Mock
- let mockRedis: any
+ let valkeyStore: Map<string, string>
+ let mockValkeySet: jest.Mock
let mockValkey: any
const mockTrackedFetch = jest.fn()
@@ -92,35 +91,21 @@ describe('PushNotificationService', () => {
backoffMaxMs: 30000,
}
- redisStore = new Map<string, string>()
- mockRedisSet = jest.fn((key: string, value: string) => {
- redisStore.set(key, value)
+ valkeyStore = new Map<string, string>()
+ mockValkeySet = jest.fn((key: string, value: string) => {
+ valkeyStore.set(key, value)
return 'OK'
})
- mockRedis = {
- useClient: jest.fn((_opts: any, fn: any) =>
- fn({
- get: (key: string) => redisStore.get(key) ?? null,
- set: mockRedisSet,
- })
- ),
- } as any
-
- // Backed by its own store so mirror writes never show up in `mockRedisSet` assertions.
- const valkeyStore = new Map<string, string>()
mockValkey = {
useClient: jest.fn((_opts: any, fn: any) =>
fn({
get: (key: string) => valkeyStore.get(key) ?? null,
- set: (key: string, value: string) => {
- valkeyStore.set(key, value)
- return 'OK'
- },
+ set: mockValkeySet,
})
),
} as any
- service = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockRedis, mockValkey)
+ service = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockValkey)
})
afterEach(() => {
@@ -307,7 +292,6 @@ describe('PushNotificationService', () => {
integrationManager,
encryptedFields,
fetchUtils,
- mockRedis,
mockValkey,
new MessageAssetsService({ produce: jest.fn() } as any)
)
@@ -369,7 +353,6 @@ describe('PushNotificationService', () => {
integrationManager,
encryptedFields,
fetchUtils,
- mockRedis,
mockValkey,
{
buildRowForPush: () => {
@@ -665,54 +648,52 @@ describe('PushNotificationService', () => {
await send()
await send()
- // The JWT is written to Redis once and read back on the second send. Minting a new token per
+ // The JWT is written to Valkey once and read back on the second send. Minting a new token per
// send is what makes Apple return 429 TooManyProviderTokenUpdates.
- expect(mockRedisSet).toHaveBeenCalledTimes(1)
+ expect(mockValkeySet).toHaveBeenCalledTimes(1)
+ // Apple accepts a provider token for up to an hour, so the TTL has to stay under that.
+ expect(mockValkeySet).toHaveBeenCalledWith(
+ expect.stringContaining('@posthog/apns-provider-jwt/'),
+ expect.any(String),
+ 'EX',
+ 2700
+ )
})
- it('mirrors APNS provider token reads and writes to Valkey', async () => {
- const mirrorStore = new Map<string, string>()
- const mirrorSet = jest.fn((key: string, value: string) => {
- mirrorStore.set(key, value)
- return 'OK'
- })
- const mirrorRedis = {
- useClient: jest.fn((_opts: any, fn: any) =>
- fn({
- get: (key: string) => mirrorStore.get(key) ?? null,
- set: mirrorSet,
- })
- ),
+ it('reuses the pod-local APNS token when Valkey is unavailable', async () => {
+ // Both Valkey calls are failOpen, so an outage makes the read return null. Without the
+ // pod-local fallback every send mints a token and Apple answers 429 TooManyProviderTokenUpdates.
+ const failingValkey = {
+ useClient: jest.fn().mockResolvedValue(null),
} as any
- const mirroredService = new PushNotificationService(
+ const offlineService = new PushNotificationService(
integrationManager,
encryptedFields,
fetchUtils,
- mockRedis,
- mirrorRedis
+ failingValkey
)
mockTrackedFetch.mockResolvedValue({
fetchError: null,
fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },
fetchDuration: 15,
})
- const invocation = createSendPushNotificationInvocation({
- '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
- })
+ const send = (): Promise<any> =>
+ offlineService.executeSendPushNotification(
+ createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ )
- await mirroredService.executeSendPushNotification(invocation)
+ mockTrackedFetch.mockClear()
+ await send()
+ await send()
- expect(mirrorRedis.useClient).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'apns-jwt-read' }),
- expect.any(Function)
- )
- expect(mirrorSet).toHaveBeenCalledWith(
- expect.stringContaining('@posthog/apns-provider-jwt/'),
- expect.any(String),
- 'EX',
- 2700
+ const authHeaders = mockTrackedFetch.mock.calls.map(
+ (call: any) => call[0].fetchParams.headers.Authorization
)
- expect([...mirrorStore.values()]).toEqual([...redisStore.values()])
+ expect(authHeaders).toHaveLength(2)
+ expect(authHeaders[0]).toEqual(expect.stringContaining('bearer '))
+ expect(authHeaders[0]).toBe(authHeaders[1])
})
it('sets apns-priority to 5 for passive interruption level', async () => {
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index 5f4a7f02fc33..d45bfb41ff48 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -6,7 +6,6 @@ import {
CyclotronInvocationQueueParametersSendPushNotificationType,
PushNotificationPayloadType,
} from '~/cdp/schema/cyclotron'
-import { mirrorCall, mirrorCompare } from '~/cdp/utils/mirror-call'
import { RedisV2 } from '~/common/redis/redis-v2'
import { instrumented } from '~/common/tracing/tracing-utils'
import { parseJSON } from '~/common/utils/json-parse'
@@ -66,11 +65,15 @@ const pushNotificationRescheduledCounter = new Counter({
})
// Apple rate-limits new APNs provider tokens (returns 429 TooManyProviderTokenUpdates if refreshed more
-// than once every ~20 min per key) and accepts a token for up to 1 hour. Cache the signed JWT in Redis
+// than once every ~20 min per key) and accepts a token for up to 1 hour. Cache the signed JWT in Valkey
// keyed by the auth key id so the whole fleet reuses one token per key rather than minting one per send.
const APNS_JWT_CACHE_PREFIX = '@posthog/apns-provider-jwt/'
const APNS_JWT_TTL_SECONDS = 45 * 60
+// One entry per signing key, so the ceiling is the number of APNs integrations routed through this pod.
+// Pruned on write rather than on a timer.
+const APNS_JWT_LOCAL_CACHE_MAX = 500
+
// A push action fans out to its selected channels within one invocation. Cap the count so a workflow
// crafted with a huge channel list can't tie up a worker with an unbounded outbound-request loop; a real
// push targets a handful of provider integrations, not thousands.
@@ -163,11 +166,16 @@ export class PushNotificationService {
private integrationManager: IntegrationManagerService,
private encryptedFields: EncryptedFields,
private fetchUtils: PushNotificationFetchUtils,
- private redis: RedisV2 | null,
- private redisMirror: RedisV2,
+ private valkey: RedisV2,
private messageAssetsService?: MessageAssetsService
) {}
+ // Both Valkey calls for the APNs token are failOpen, so an outage turns every send into a fresh mint —
+ // the exact pattern Apple answers with 429 TooManyProviderTokenUpdates. This per-pod copy bounds that
+ // to one token per pod per TTL. It is a fallback, not the cache: Valkey is still read first, so the
+ // fleet normally shares one token per key.
+ private apnsJwtLocalCache = new Map<string, { jwt: string; expiresAtMs: number }>()
+
@instrumented('push-notification.executeSendPushNotification')
async executeSendPushNotification(
invocation: CyclotronJobInvocationHogFunction,
@@ -563,19 +571,18 @@ export class PushNotificationService {
const keyFingerprint = createHash('sha256').update(`${teamId}:${keyId}:${signingKey}`).digest('hex')
const cacheKey = `${APNS_JWT_CACHE_PREFIX}${keyFingerprint}`
- const read = (pool: RedisV2) =>
- pool.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) => client.get(cacheKey))
- const cached = this.redis
- ? await mirrorCompare(
- 'push-notification.apns-jwt-read',
- () => read(this.redis!),
- () => read(this.redisMirror)
- )
- : null
+ const cached = await this.valkey.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) =>
+ client.get(cacheKey)
+ )
if (cached) {
return cached
}
+ const local = this.apnsJwtLocalCache.get(cacheKey)
+ if (local && local.expiresAtMs > Date.now()) {
+ return local.jwt
+ }
+
const header = Buffer.from(JSON.stringify({ alg: 'ES256', kid: keyId })).toString('base64url')
const now = Math.floor(Date.now() / 1000)
const claims = Buffer.from(JSON.stringify({ iss: teamId, iat: now })).toString('base64url')
@@ -585,17 +592,35 @@ export class PushNotificationService {
const signature = sign.sign({ key: signingKey, dsaEncoding: 'ieee-p1363' }, 'base64url')
const jwt = `${signingInput}.${signature}`
- const write = (pool: RedisV2) =>
- pool.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>
- client.set(cacheKey, jwt, 'EX', APNS_JWT_TTL_SECONDS)
- )
- await Promise.all([
- this.redis ? write(this.redis) : undefined,
- mirrorCall('push-notification.apns-jwt-write', () => write(this.redisMirror)),
- ])
+ this.rememberApnsJwtLocally(cacheKey, jwt)
+ await this.valkey.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>
+ client.set(cacheKey, jwt, 'EX', APNS_JWT_TTL_SECONDS)
+ )
return jwt
}
+ private rememberApnsJwtLocally(cacheKey: string, jwt: string): void {
+ const nowMs = Date.now()
+ this.apnsJwtLocalCache.set(cacheKey, { jwt, expiresAtMs: nowMs + APNS_JWT_TTL_SECONDS * 1000 })
+
+ if (this.apnsJwtLocalCache.size <= APNS_JWT_LOCAL_CACHE_MAX) {
+ return
+ }
+ for (const [key, entry] of this.apnsJwtLocalCache) {
+ if (entry.expiresAtMs <= nowMs) {
+ this.apnsJwtLocalCache.delete(key)
+ }
+ }
+ // Map iterates in insertion order, so this drops the least recently minted. Safe because Valkey
+ // is the real cache — a dropped entry only costs a signature during an outage.
+ for (const key of this.apnsJwtLocalCache.keys()) {
+ if (this.apnsJwtLocalCache.size <= APNS_JWT_LOCAL_CACHE_MAX) {
+ break
+ }
+ this.apnsJwtLocalCache.delete(key)
+ }
+ }
+
private buildApnsPayload(payload: PushNotificationPayloadType): Record<string, unknown> {
const alert: Record<string, unknown> = { title: payload.title }
if (payload.body) {
diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts
index be11cf12eaac..411acec75f54 100644
--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts
@@ -8,8 +8,8 @@ import {
CyclotronJobInvocationHogFunction,
HogFunctionMasking,
} from '../../types'
+import { dualRead } from '../../utils/dual-store'
import { execHog } from '../../utils/hog-exec'
-import { mirrorCompare } 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`
@@ -170,15 +170,15 @@ export class HogMaskerService {
}
const maskContexts = Object.values(masks)
- const result = await mirrorCompare(
+ const result = await dualRead(
'hog-masker.filterByMasking',
() => this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline),
() => this.redisMirror.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline),
- (primary, mirror) =>
+ (primary, secondary) =>
maskContexts.every(
(masker, index) =>
allowedExecutionsForResult(primary, index, masker) ===
- allowedExecutionsForResult(mirror, index, masker)
+ allowedExecutionsForResult(secondary, index, masker)
)
)
diff --git a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts
index 04ec8505d83c..f6ebd24768da 100644
--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.ts
@@ -53,6 +53,33 @@ export type HogWatcherFunctionState = {
state: HogWatcherState
}
+/**
+ * Compares a watcher read across Redis and Valkey on `state` alone, for `dualRead`.
+ *
+ * `tokens` is refilled from the wall clock at read time (see `getPersistedStates`), so the two
+ * stores disagree on it whenever their reads land on different seconds. Comparing it would leave
+ * the mismatch metric permanently saturated, and that metric is the signal we need to trust
+ * before moving watcher reads to Valkey. `state` is what decides whether an invocation runs.
+ */
+export function sameWatcherState(
+ primary: HogWatcherFunctionState | null,
+ secondary: HogWatcherFunctionState | null
+): boolean {
+ return primary?.state === secondary?.state
+}
+
+/** `sameWatcherState` over a keyed batch — the id set has to agree as well as each state. */
+export function sameWatcherStates(
+ primary: Record<string, HogWatcherFunctionState>,
+ secondary: Record<string, HogWatcherFunctionState>
+): boolean {
+ const ids = Object.keys(primary ?? {})
+ return (
+ ids.length === Object.keys(secondary ?? {}).length &&
+ ids.every((id) => primary[id]?.state === secondary[id]?.state)
+ )
+}
+
type FunctionCostEntry = {
hogFunction?: HogFunctionType
functionId: string
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
index 81035e2964b3..161349555947 100644
--- a/nodejs/src/cdp/services/monitoring/hog-watcher.service.unit.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-watcher.service.unit.test.ts
@@ -3,7 +3,13 @@ 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'
+import {
+ HogWatcherConfig,
+ HogWatcherService,
+ HogWatcherState,
+ sameWatcherState,
+ sameWatcherStates,
+} from './hog-watcher.service'
const WATCHER_CONFIG: HogWatcherConfig = {
hogCostTimingLowerMs: 50,
@@ -94,4 +100,35 @@ describe('HogWatcherService unit behavior', () => {
await rejections
})
+
+ // The Redis/Valkey cutover gate is the dualRead mismatch metric on these calls. Comparing
+ // `tokens`, which is refilled from the wall clock per read, would saturate it and make the
+ // gate useless — so token drift must not read as a mismatch, and a state change must.
+ describe('cutover comparators', () => {
+ it.each([
+ ['token drift alone is equivalent', 10, HogWatcherState.healthy, 9, HogWatcherState.healthy, true],
+ ['a differing state is not', 10, HogWatcherState.healthy, 10, HogWatcherState.disabled, false],
+ ])('%s', (_name, aTokens, aState, bTokens, bState, expected) => {
+ expect(sameWatcherState({ tokens: aTokens, state: aState }, { tokens: bTokens, state: bState })).toBe(
+ expected
+ )
+ expect(
+ sameWatcherStates(
+ { fn: { tokens: aTokens, state: aState } },
+ { fn: { tokens: bTokens, state: bState } }
+ )
+ ).toBe(expected)
+ })
+
+ it.each([
+ ['a missing id', { a: { tokens: 1, state: HogWatcherState.healthy } }, {}],
+ ['an extra id', {}, { a: { tokens: 1, state: HogWatcherState.healthy } }],
+ ])('reports %s as a mismatch', (_name, primary, secondary) => {
+ expect(sameWatcherStates(primary, secondary)).toBe(false)
+ })
+
+ it('treats one side missing entirely as a mismatch', () => {
+ expect(sameWatcherState({ tokens: 1, state: HogWatcherState.healthy }, null)).toBe(false)
+ })
+ })
})
diff --git a/nodejs/src/cdp/utils/dual-store.test.ts b/nodejs/src/cdp/utils/dual-store.test.ts
new file mode 100644
index 000000000000..26a383a1f9dd
--- /dev/null
+++ b/nodejs/src/cdp/utils/dual-store.test.ts
@@ -0,0 +1,138 @@
+import { logger } from '~/common/utils/logger'
+
+import { configureValkeyReads, dualRead, dualWrite, parseValkeyReadFeatures, readSourceFor } from './dual-store'
+
+jest.mock('~/common/utils/logger', () => ({ logger: { warn: jest.fn(), info: jest.fn() } }))
+
+describe('dual-store', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ configureValkeyReads('')
+ })
+
+ describe('parseValkeyReadFeatures', () => {
+ it('throws on an unknown feature name rather than silently leaving reads on redis', () => {
+ expect(() => parseValkeyReadFeatures('hog-masker,hog-waatcher')).toThrow(
+ /unknown feature\(s\): hog-waatcher/
+ )
+ })
+
+ it('selects every feature for *', () => {
+ expect(parseValkeyReadFeatures('*').size).toBeGreaterThan(1)
+ })
+
+ it('reads only the named features from valkey', () => {
+ configureValkeyReads(' hog-masker , hog-flow-duplicate-observer ')
+ expect(readSourceFor('hog-masker.filterByMasking')).toBe('valkey')
+ expect(readSourceFor('hog-flow-duplicate-observer.observe')).toBe('valkey')
+ expect(readSourceFor('hog-watcher.getEffectiveStates')).toBe('redis')
+ })
+ })
+
+ describe('dualRead', () => {
+ it.each([
+ ['', 'redis-value'],
+ ['hog-masker', 'valkey-value'],
+ ])('with CDP_VALKEY_READ_FEATURES=%p returns %p', async (features, expected) => {
+ configureValkeyReads(features)
+ await expect(
+ dualRead(
+ 'hog-masker.filterByMasking',
+ () => Promise.resolve('redis-value'),
+ () => Promise.resolve('valkey-value')
+ )
+ ).resolves.toBe(expected)
+ })
+
+ it.each([
+ ['', 'valkey'],
+ ['hog-masker', 'redis'],
+ ])('with CDP_VALKEY_READ_FEATURES=%p a failing %s read never reaches the caller', async (features, failing) => {
+ configureValkeyReads(features)
+ const boom = () => Promise.reject(new Error('boom'))
+ const ok = () => Promise.resolve('ok')
+ await expect(
+ dualRead(
+ 'hog-masker.filterByMasking',
+ failing === 'redis' ? boom : ok,
+ failing === 'valkey' ? boom : ok
+ )
+ ).resolves.toBe('ok')
+ })
+
+ it('stops awaiting the non-read store after timeoutMs', async () => {
+ const start = Date.now()
+ await expect(
+ dualRead(
+ 'hog-masker.filterByMasking',
+ () => Promise.resolve('redis-value'),
+ () => new Promise(() => {}), // never settles
+ undefined,
+ 20
+ )
+ ).resolves.toBe('redis-value')
+ expect(Date.now() - start).toBeLessThan(200)
+ })
+
+ it('logs a mismatch once without changing the returned result', async () => {
+ await expect(
+ dualRead(
+ 'hog-watcher.getPersistedState',
+ () => Promise.resolve({ state: 'healthy' }),
+ () => Promise.resolve({ state: 'degraded' })
+ )
+ ).resolves.toEqual({ state: 'healthy' })
+ expect(logger.warn).toHaveBeenCalledWith('🪞', '[mirror:hog-watcher.getPersistedState] result mismatch')
+ })
+
+ it('returns the read-store result when the comparator throws on an unexpected shape', async () => {
+ await expect(
+ dualRead<{ isRateLimited: boolean }[]>(
+ 'hog-function-rate-limiter.rateLimitGrouped',
+ () => Promise.resolve([{ isRateLimited: false }]),
+ () => Promise.resolve(undefined as any),
+ (primary, secondary) =>
+ primary.every((entry, i) => entry.isRateLimited === secondary[i].isRateLimited)
+ )
+ ).resolves.toEqual([{ isRateLimited: false }])
+ })
+ })
+
+ describe('dualWrite', () => {
+ it.each([
+ ['', 'redis'],
+ ['hog-watcher', 'valkey'],
+ ])(
+ 'with CDP_VALKEY_READ_FEATURES=%p only a failing %s write reaches the caller',
+ async (features, propagating) => {
+ configureValkeyReads(features)
+ const boom = () => Promise.reject(new Error('boom'))
+ const ok = () => Promise.resolve()
+
+ await expect(
+ dualWrite(
+ 'hog-watcher.observeResults',
+ propagating === 'redis' ? boom : ok,
+ propagating === 'valkey' ? boom : ok
+ )
+ ).rejects.toThrow('boom')
+
+ await expect(
+ dualWrite(
+ 'hog-watcher.observeResults',
+ propagating === 'redis' ? ok : boom,
+ propagating === 'valkey' ? ok : boom
+ )
+ ).resolves.toBeUndefined()
+ }
+ )
+
+ it('writes to both stores', async () => {
+ const redis = jest.fn().mockResolvedValue(undefined)
+ const valkey = jest.fn().mockResolvedValue(undefined)
+ await dualWrite('hog-watcher.observeResults', redis, valkey)
+ expect(redis).toHaveBeenCalledTimes(1)
+ expect(valkey).toHaveBeenCalledTimes(1)
+ })
+ })
+})
diff --git a/nodejs/src/cdp/utils/dual-store.ts b/nodejs/src/cdp/utils/dual-store.ts
new file mode 100644
index 000000000000..85c204609f24
--- /dev/null
+++ b/nodejs/src/cdp/utils/dual-store.ts
@@ -0,0 +1,200 @@
+import { isDeepStrictEqual } from 'node:util'
+import { Counter } from 'prom-client'
+
+import { logger } from '~/common/utils/logger'
+
+import { instrumentFn } from '../../common/tracing/tracing-utils'
+
+const DEFAULT_TIMEOUT_MS = 2000
+const mismatchWarningLogged = new Set<string>()
+
+/**
+ * CDP features whose Redis calls also run against Valkey.
+ *
+ * Writes always go to both stores. Reads come from Redis until a feature is named in
+ * `CDP_VALKEY_READ_FEATURES`, which flips that feature — and only that feature — over to
+ * Valkey. Listed roughly in the order they are safe to flip: the entries near the top
+ * back caches and metrics, the ones near the bottom decide whether an invocation runs.
+ */
+export const MIRROR_FEATURES = [
+ 'hog-flow-duplicate-observer',
+ 'hog-function-rate-limiter',
+ 'hog-masker',
+ 'hog-flow-rate-limiter',
+ 'hog-watcher',
+] as const
+
+export type MirrorFeature = (typeof MIRROR_FEATURES)[number]
+
+/** `<feature>.<operation>`; the operation half is free-form and only feeds metrics and logs. */
+export type MirrorLabel = `${MirrorFeature}.${string}`
+
+type Store = 'redis' | 'valkey'
+
+const mirrorOperationsTotal = new Counter({
+ name: 'cdp_valkey_mirror_operations_total',
+ // `source` is the store the feature reads from, so `failed` means the *other* store's call failed.
+ help: 'CDP Redis/Valkey dual-store operations by operation, read source and outcome.',
+ labelNames: ['operation', 'source', 'outcome'],
+})
+
+// Process-wide because the helpers below are free functions called from a dozen services that
+// have no other reason to carry config. Set once per process from `createCdpCoreServices`.
+let valkeyReadFeatures: ReadonlySet<MirrorFeature> = new Set()
+
+/**
+ * Parses the comma-separated `CDP_VALKEY_READ_FEATURES` value. `*` selects every feature.
+ *
+ * Throws on an unrecognised name: a typo would otherwise leave reads quietly on Redis while
+ * the deploy looks like it migrated the feature.
+ */
+export function parseValkeyReadFeatures(raw: string): Set<MirrorFeature> {
+ const names = raw
+ .split(',')
+ .map((name) => name.trim())
+ .filter(Boolean)
+
+ if (names.includes('*')) {
+ return new Set(MIRROR_FEATURES)
+ }
+
+ const unknown = names.filter((name) => !(MIRROR_FEATURES as readonly string[]).includes(name))
+ if (unknown.length > 0) {
+ throw new Error(
+ `CDP_VALKEY_READ_FEATURES contains unknown feature(s): ${unknown.join(', ')}. Known features: ${MIRROR_FEATURES.join(', ')}`
+ )
+ }
+
+ return new Set(names as MirrorFeature[])
+}
+
+export function configureValkeyReads(raw: string): void {
+ valkeyReadFeatures = parseValkeyReadFeatures(raw)
+ logger.info(
+ '🪞',
+ `[dual-store] reading from valkey: ${valkeyReadFeatures.size > 0 ? [...valkeyReadFeatures].join(', ') : '<none, all reads from redis>'}`
+ )
+}
+
+export function readSourceFor(label: MirrorLabel): Store {
+ const feature = label.split('.')[0] as MirrorFeature
+ return valkeyReadFeatures.has(feature) ? 'valkey' : 'redis'
+}
+
+type SecondaryOutcome<T> = { status: 'completed'; value: T } | { status: 'failed' }
+
+/**
+ * Runs the non-read store's 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, so it never rejects.
+ * - Wrapped in `instrumentFn` so latency / errors surface in tracing under
+ * the `cdp.mirror.<label>` key.
+ */
+async function runSecondary<T>(
+ label: MirrorLabel,
+ source: Store,
+ call: () => Promise<T>,
+ timeoutMs: number
+): Promise<SecondaryOutcome<T>> {
+ return instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, async () => {
+ let timeoutId: NodeJS.Timeout | undefined
+ try {
+ const value = await Promise.race([
+ call(),
+ new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(
+ () => reject(new Error(`secondary call timed out after ${timeoutMs}ms`)),
+ timeoutMs
+ )
+ }),
+ ])
+ return { status: 'completed', value } as const
+ } catch (err) {
+ mirrorOperationsTotal.labels({ operation: label, source, outcome: 'failed' }).inc()
+ logger.warn('🪞', `[mirror:${label}] secondary store failed`, { err: String(err) })
+ return { status: 'failed' } as const
+ } finally {
+ if (timeoutId) {
+ clearTimeout(timeoutId)
+ }
+ }
+ })
+}
+
+/** Splits the two calls into the one whose result we use and the one we only observe. */
+function order<T>(
+ label: MirrorLabel,
+ redisCall: () => Promise<T>,
+ valkeyCall: () => Promise<T>
+): { source: Store; primary: () => Promise<T>; secondary: () => Promise<T> } {
+ const source = readSourceFor(label)
+ return source === 'valkey'
+ ? { source, primary: valkeyCall, secondary: redisCall }
+ : { source, primary: redisCall, secondary: valkeyCall }
+}
+
+/**
+ * Runs a read against both stores in parallel, returning the result from whichever store this
+ * feature currently reads from and recording whether the other returned equivalent data.
+ *
+ * The read source's errors propagate to the caller; the other store's are swallowed.
+ */
+export async function dualRead<T>(
+ label: MirrorLabel,
+ redisCall: () => Promise<T>,
+ valkeyCall: () => Promise<T>,
+ isEquivalent: (primary: T, secondary: T) => boolean = isDeepStrictEqual,
+ timeoutMs: number = DEFAULT_TIMEOUT_MS
+): Promise<T> {
+ const { source, primary, secondary } = order(label, redisCall, valkeyCall)
+
+ const primaryPromise = primary()
+ const secondaryPromise = runSecondary(label, source, secondary, timeoutMs)
+ const [primaryResult, secondaryResult] = await Promise.all([primaryPromise, secondaryPromise])
+
+ if (secondaryResult.status === 'completed') {
+ // `isEquivalent` is caller-supplied and indexes into the secondary payload, so a shape
+ // the comparator does not expect throws here — outside runSecondary's guard. Treat
+ // that as a mismatch rather than letting it reject the primary result.
+ let outcome: 'matched' | 'mismatched'
+ try {
+ outcome = isEquivalent(primaryResult, secondaryResult.value) ? 'matched' : 'mismatched'
+ } catch (err) {
+ outcome = 'mismatched'
+ logger.warn('🪞', `[mirror:${label}] comparison threw`, { err: String(err) })
+ }
+ mirrorOperationsTotal.labels({ operation: label, source, outcome }).inc()
+ if (outcome === 'mismatched' && !mismatchWarningLogged.has(label)) {
+ mismatchWarningLogged.add(label)
+ logger.warn('🪞', `[mirror:${label}] result mismatch`)
+ }
+ }
+
+ return primaryResult
+}
+
+/**
+ * Writes to both stores in parallel.
+ *
+ * Failures on the store this feature reads from propagate to the caller, because they change
+ * what the next read decides. Failures on the other store are logged and counted only — that
+ * data is not being read, so a gap in it cannot affect behaviour.
+ */
+export async function dualWrite(
+ label: MirrorLabel,
+ redisCall: () => Promise<unknown>,
+ valkeyCall: () => Promise<unknown>,
+ timeoutMs: number = DEFAULT_TIMEOUT_MS
+): Promise<void> {
+ const { source, primary, secondary } = order(label, redisCall, valkeyCall)
+
+ const [, secondaryResult] = await Promise.all([primary(), runSecondary(label, source, secondary, timeoutMs)])
+
+ if (secondaryResult.status === 'completed') {
+ mirrorOperationsTotal.labels({ operation: label, source, outcome: 'completed' }).inc()
+ }
+}
diff --git a/nodejs/src/cdp/utils/mirror-call.test.ts b/nodejs/src/cdp/utils/mirror-call.test.ts
deleted file mode 100644
index 8c626b95d49d..000000000000
--- a/nodejs/src/cdp/utils/mirror-call.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { logger } from '~/common/utils/logger'
-
-import { mirrorCall, mirrorCompare } from './mirror-call'
-
-jest.mock('~/common/utils/logger', () => ({ logger: { warn: jest.fn() } }))
-
-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('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)
- })
-
- it('returns the primary result when mirror results match', async () => {
- await expect(
- mirrorCompare(
- 'test.compare',
- () => Promise.resolve({ state: 'healthy' }),
- () => Promise.resolve({ state: 'healthy' })
- )
- ).resolves.toEqual({ state: 'healthy' })
- expect(logger.warn).not.toHaveBeenCalledWith('🪞', '[mirror:test.compare] result mismatch')
- })
-
- it('reports a mismatch without changing the primary result', async () => {
- await expect(
- mirrorCompare(
- 'test.compare',
- () => Promise.resolve({ state: 'healthy' }),
- () => Promise.resolve({ state: 'degraded' })
- )
- ).resolves.toEqual({ state: 'healthy' })
- expect(logger.warn).toHaveBeenCalledWith('🪞', '[mirror:test.compare] result mismatch')
- })
-
- it('returns the primary result when the comparator throws on an unexpected mirror shape', async () => {
- await expect(
- mirrorCompare<{ isRateLimited: boolean }[]>(
- 'test.compare',
- () => Promise.resolve([{ isRateLimited: false }]),
- () => Promise.resolve(undefined as any),
- (primary, mirror) => primary.every((entry, i) => entry.isRateLimited === mirror[i].isRateLimited)
- )
- ).resolves.toEqual([{ isRateLimited: false }])
- })
-
- it('returns the primary result when the mirror fails', async () => {
- await expect(
- mirrorCompare(
- 'test.compare',
- () => Promise.resolve('primary'),
- () => Promise.reject(new Error('boom'))
- )
- ).resolves.toBe('primary')
- })
-})
diff --git a/nodejs/src/cdp/utils/mirror-call.ts b/nodejs/src/cdp/utils/mirror-call.ts
deleted file mode 100644
index 94ac69c40400..000000000000
--- a/nodejs/src/cdp/utils/mirror-call.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { isDeepStrictEqual } from 'node:util'
-import { Counter } from 'prom-client'
-
-import { logger } from '~/common/utils/logger'
-
-import { instrumentFn } from '../../common/tracing/tracing-utils'
-
-const DEFAULT_TIMEOUT_MS = 2000
-const mismatchWarningLogged = new Set<string>()
-
-const mirrorOperationsTotal = new Counter({
- name: 'cdp_valkey_mirror_operations_total',
- help: 'CDP Redis-to-Valkey mirror operations by operation and outcome.',
- labelNames: ['operation', 'outcome'],
-})
-
-type MirrorOutcome<T> = { status: 'completed'; value: T } | { status: 'failed' }
-
-async function runMirrorCall<T>(label: string, call: () => Promise<T>, timeoutMs: number): Promise<MirrorOutcome<T>> {
- let timeoutId: NodeJS.Timeout | undefined
- try {
- const value = await Promise.race([
- call(),
- new Promise<never>((_, reject) => {
- timeoutId = setTimeout(() => reject(new Error(`mirror call timed out after ${timeoutMs}ms`)), timeoutMs)
- }),
- ])
- return { status: 'completed', value }
- } catch (err) {
- mirrorOperationsTotal.labels({ operation: label, outcome: 'failed' }).inc()
- logger.warn('🪞', `[mirror:${label}] failed`, { err: String(err) })
- return { status: 'failed' }
- } finally {
- if (timeoutId) {
- clearTimeout(timeoutId)
- }
- }
-}
-
-/**
- * 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.
- */
-export async function mirrorCall(
- label: string,
- call: () => Promise<unknown>,
- timeoutMs: number = DEFAULT_TIMEOUT_MS
-): Promise<void> {
- return instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, async () => {
- const outcome = await runMirrorCall(label, call, timeoutMs)
- if (outcome.status === 'completed') {
- mirrorOperationsTotal.labels({ operation: label, outcome: 'completed' }).inc()
- }
- })
-}
-
-/**
- * Runs an authoritative Redis read and its Valkey mirror in parallel, returning
- * the Redis result while recording whether Valkey returned equivalent data.
- */
-export async function mirrorCompare<T>(
- label: string,
- primaryCall: () => Promise<T>,
- mirrorCallFactory: () => Promise<T>,
- isEquivalent: (primary: T, mirror: T) => boolean = isDeepStrictEqual,
- timeoutMs: number = DEFAULT_TIMEOUT_MS
-): Promise<T> {
- const primaryPromise = primaryCall()
- const mirrorPromise = instrumentFn({ key: `cdp.mirror.${label}`, sendException: false }, () =>
- runMirrorCall(label, mirrorCallFactory, timeoutMs)
- )
- const [primary, mirror] = await Promise.all([primaryPromise, mirrorPromise])
-
- if (mirror.status === 'completed') {
- // `isEquivalent` is caller-supplied and indexes into the mirror payload, so a shape
- // the comparator does not expect throws here — outside runMirrorCall's guard. Treat
- // that as a mismatch rather than letting it reject the primary result.
- let outcome: 'matched' | 'mismatched'
- try {
- outcome = isEquivalent(primary, mirror.value) ? 'matched' : 'mismatched'
- } catch (err) {
- outcome = 'mismatched'
- logger.warn('🪞', `[mirror:${label}] comparison threw`, { err: String(err) })
- }
- mirrorOperationsTotal.labels({ operation: label, outcome }).inc()
- if (outcome === 'mismatched' && !mismatchWarningLogged.has(label)) {
- mismatchWarningLogged.add(label)
- logger.warn('🪞', `[mirror:${label}] result mismatch`)
- }
- }
-
- return primary
-}