:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion): add keep-first dedup for $feature_flag_called events (#62793)
Phil Haack40173f83bd91
diff --git a/nodejs/src/config/redis-pools.test.ts b/nodejs/src/config/redis-pools.test.tsnew file mode 100644index 000000000000..0383311f551b--- /dev/null+++ b/nodejs/src/config/redis-pools.test.ts@@ -0,0 +1,43 @@+import { createFeatureFlagCalledDedupRedisConnectionConfig } from './redis-pools'++describe('createFeatureFlagCalledDedupRedisConnectionConfig', () => {+ const base = {+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST: '',+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT: 6379,+ INGESTION_REDIS_HOST: '',+ INGESTION_REDIS_PORT: 6379,+ POSTHOG_REDIS_HOST: '',+ POSTHOG_REDIS_PORT: 6379,+ POSTHOG_REDIS_PASSWORD: '',+ // nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport+ REDIS_URL: 'redis://localhost:6379',+ }++ it('uses the dedicated host and port when set', () => {+ expect(+ createFeatureFlagCalledDedupRedisConnectionConfig({+ ...base,+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST: 'ff-called-dedup-prod-redis',+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT: 6380,+ })+ ).toEqual({ url: 'ff-called-dedup-prod-redis', options: { port: 6380 }, name: 'ff-called-dedup-redis' })+ })++ it('falls back to the ingestion connection (not REDIS_URL) when no host is set', () => {+ expect(+ createFeatureFlagCalledDedupRedisConnectionConfig({+ ...base,+ INGESTION_REDIS_HOST: 'ingestion-prod-redis',+ INGESTION_REDIS_PORT: 6379,+ })+ ).toEqual({ url: 'ingestion-prod-redis', options: { port: 6379 }, name: 'ff-called-dedup-redis' })+ })++ it('falls back to REDIS_URL only when neither dedup nor ingestion hosts are set', () => {+ expect(createFeatureFlagCalledDedupRedisConnectionConfig(base)).toEqual({+ // nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport+ url: 'redis://localhost:6379',+ name: 'ff-called-dedup-redis',+ })+ })+})diff --git a/nodejs/src/config/redis-pools.ts b/nodejs/src/config/redis-pools.tsindex 923ad716df0e..a9e5cbab9171 100644--- a/nodejs/src/config/redis-pools.ts+++ b/nodejs/src/config/redis-pools.ts@@ -51,6 +51,38 @@ export function createPosthogRedisConnectionConfig(return { url: config.REDIS_URL, name: 'posthog-redis' }}+/**+ * Build the connection config for the $feature_flag_called dedup Redis pool.+ *+ * Falls back to the ingestion Redis connection (not REDIS_URL) when no dedicated+ * host is set, so dedup claims keep landing on the instance they use today until+ * INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST points at the dedicated instance.+ */+export function createFeatureFlagCalledDedupRedisConnectionConfig(+ config: Pick<+ IngestionConsumerConfig,+ 'INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST' | 'INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT'+ > &+ Pick<+ CommonConfig,+ | 'INGESTION_REDIS_HOST'+ | 'INGESTION_REDIS_PORT'+ | 'POSTHOG_REDIS_HOST'+ | 'POSTHOG_REDIS_PORT'+ | 'POSTHOG_REDIS_PASSWORD'+ | 'REDIS_URL'+ >+): RedisConnectionConfig {+ if (config.INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST) {+ return {+ url: config.INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST,+ options: { port: config.INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT ?? 6379 },+ name: 'ff-called-dedup-redis',+ }+ }+ return { ...createIngestionRedisConnectionConfig(config), name: 'ff-called-dedup-redis' }+}+/*** Build the connection config for the cookieless Redis pool.* Fallback chain: COOKIELESS_REDIS_HOST → REDIS_URLdiff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/dedupe-feature-flag-called.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/dedupe-feature-flag-called.test.tsnew file mode 100644index 000000000000..cc597f5ff932--- /dev/null+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/dedupe-feature-flag-called.test.ts@@ -0,0 +1,224 @@+import { isDropResult, isOkResult } from '~/ingestion/framework/results'+import {+ FeatureFlagCalledDedupMode,+ FeatureFlagCalledDedupService,+ featureFlagCalledDedupKey,+} from '~/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service'+import { getMetricValues, resetMetrics } from '~/tests/helpers/metrics'+import { createTestPluginEvent } from '~/tests/helpers/plugin-event'+import { createTestTeam } from '~/tests/helpers/team'++import { DedupeFeatureFlagCalledStepInput, createDedupeFeatureFlagCalledStep } from './dedupe-feature-flag-called'++const createMockService = (+ mode: FeatureFlagCalledDedupMode = 'drop',+ enabledForTeam = true+): jest.Mocked<FeatureFlagCalledDedupService> => ({+ mode,+ isEnabledForTeam: jest.fn().mockReturnValue(enabledForTeam),+ claimKeys: jest.fn(),+})++// Callers pass an explicit `undefined` for `properties` to reach `overrides`;+// a defaulted parameter accepts `undefined` (and applies the default) even+// under strict mode.+const createInput = (+ properties: Record<string, unknown> = { $feature_flag: 'my-flag', $feature_flag_response: true },+ overrides: { event?: string; distinctId?: string; teamId?: number; uuid?: string } = {}+): DedupeFeatureFlagCalledStepInput => ({+ event: createTestPluginEvent({+ event: overrides.event ?? '$feature_flag_called',+ distinct_id: overrides.distinctId ?? 'user-1',+ uuid: overrides.uuid ?? '123e4567-e89b-12d3-a456-426614174000',+ properties,+ }),+ team: createTestTeam({ id: overrides.teamId ?? 1 }),+})++describe('createDedupeFeatureFlagCalledStep', () => {+ beforeEach(() => {+ resetMetrics()+ })++ it('passes everything through when no service is provided', async () => {+ const step = createDedupeFeatureFlagCalledStep(undefined)++ const results = await step([createInput(), createInput()])++ expect(results).toHaveLength(2)+ results.forEach((result) => expect(isOkResult(result)).toBe(true))+ })++ it('handles empty batch', async () => {+ const service = createMockService()+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([])++ expect(results).toHaveLength(0)+ expect(service.claimKeys).not.toHaveBeenCalled()+ })++ it('ignores events that are not $feature_flag_called', async () => {+ const service = createMockService()+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([createInput({}, { event: '$pageview' })])++ expect(isOkResult(results[0])).toBe(true)+ expect(service.claimKeys).not.toHaveBeenCalled()+ })++ it('ignores teams the dedup is not enabled for', async () => {+ const service = createMockService('drop', false)+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([createInput()])++ expect(isOkResult(results[0])).toBe(true)+ expect(service.claimKeys).not.toHaveBeenCalled()+ })++ it('ignores events without a string $feature_flag property', async () => {+ const service = createMockService()+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([+ createInput({ $feature_flag_response: true }),+ createInput({ $feature_flag: 42, $feature_flag_response: true }),+ ])++ expect(results).toHaveLength(2)+ results.forEach((result) => expect(isOkResult(result)).toBe(true))+ expect(service.claimKeys).not.toHaveBeenCalled()+ })++ it('ignores events without a uuid', async () => {+ const service = createMockService()+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([createInput(undefined, { uuid: '' })])++ expect(isOkResult(results[0])).toBe(true)+ expect(service.claimKeys).not.toHaveBeenCalled()+ })++ it('passes first-seen events and drops in-batch duplicates in drop mode', async () => {+ const service = createMockService('drop')+ service.claimKeys.mockResolvedValue([true, false])+ const step = createDedupeFeatureFlagCalledStep(service)++ const inputs = [createInput(undefined, { uuid: 'uuid-1' }), createInput(undefined, { uuid: 'uuid-2' })]+ const results = await step(inputs)++ expect(results).toHaveLength(2)+ // Two identical tuples produce the same claim key in one claimKeys+ // call, each tagged with its own event uuid.+ const expectedKey = featureFlagCalledDedupKey(1, 'user-1', 'my-flag', true, undefined)+ expect(service.claimKeys).toHaveBeenCalledWith([+ { key: expectedKey, claimId: 'uuid-1' },+ { key: expectedKey, claimId: 'uuid-2' },+ ])+ expect(isOkResult(results[0])).toBe(true)+ expect(isDropResult(results[1])).toBe(true)+ if (isDropResult(results[1])) {+ expect(results[1].reason).toBe('feature_flag_called_duplicate')+ }+ expect(await getMetricValues('ingestion_feature_flag_called_dedup_events_total')).toEqual(+ expect.arrayContaining([+ { labels: { outcome: 'first_seen' }, value: 1 },+ { labels: { outcome: 'duplicate_dropped' }, value: 1 },+ ])+ )+ })++ it('passes duplicates through in shadow mode', async () => {+ const service = createMockService('shadow')+ service.claimKeys.mockResolvedValue([true, false])+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([+ createInput(undefined, { uuid: 'uuid-1' }),+ createInput(undefined, { uuid: 'uuid-2' }),+ ])++ expect(results).toHaveLength(2)+ results.forEach((result) => expect(isOkResult(result)).toBe(true))+ expect(service.claimKeys).toHaveBeenCalledTimes(1)+ expect(await getMetricValues('ingestion_feature_flag_called_dedup_events_total')).toEqual(+ expect.arrayContaining([+ { labels: { outcome: 'first_seen' }, value: 1 },+ { labels: { outcome: 'duplicate_shadow' }, value: 1 },+ ])+ )+ })++ it('maps claim results back when the batch interleaves deduped and ignored events', async () => {+ const service = createMockService('drop')+ service.claimKeys.mockResolvedValue([true, false])+ const step = createDedupeFeatureFlagCalledStep(service)++ const inputs = [+ createInput({}, { event: '$pageview' }),+ createInput(undefined, { uuid: 'uuid-1' }),+ createInput({ $feature_flag_response: true }),+ createInput(undefined, { uuid: 'uuid-2' }),+ ]+ const results = await step(inputs)++ expect(results).toHaveLength(4)+ expect(isOkResult(results[0])).toBe(true)+ expect(isOkResult(results[1])).toBe(true)+ expect(isOkResult(results[2])).toBe(true)+ expect(isDropResult(results[3])).toBe(true)+ const expectedKey = featureFlagCalledDedupKey(1, 'user-1', 'my-flag', true, undefined)+ expect(service.claimKeys).toHaveBeenCalledWith([+ { key: expectedKey, claimId: 'uuid-1' },+ { key: expectedKey, claimId: 'uuid-2' },+ ])+ })++ it('fails open when the service returns fewer results than claims', async () => {+ const service = createMockService('drop')+ service.claimKeys.mockResolvedValue([true])+ const step = createDedupeFeatureFlagCalledStep(service)++ const results = await step([+ createInput(undefined, { uuid: 'uuid-1' }),+ createInput(undefined, { uuid: 'uuid-2' }),+ ])++ expect(results).toHaveLength(2)+ results.forEach((result) => expect(isOkResult(result)).toBe(true))+ })++ it('builds different claim keys for different flag tuples', async () => {+ const service = createMockService('drop')+ service.claimKeys.mockResolvedValue([true, true, true, true])+ const step = createDedupeFeatureFlagCalledStep(service)++ await step([+ createInput({ $feature_flag: 'flag-a', $feature_flag_response: true }),+ createInput({ $feature_flag: 'flag-a', $feature_flag_response: false }),+ createInput({ $feature_flag: 'flag-b', $feature_flag_response: true }),+ createInput({ $feature_flag: 'flag-a', $feature_flag_response: true }, { distinctId: 'user-2' }),+ ])++ const claims = service.claimKeys.mock.calls[0][0]+ expect(new Set(claims.map((claim) => claim.key)).size).toBe(4)+ })++ it('builds identical claim keys for identical tuples', async () => {+ const service = createMockService('drop')+ service.claimKeys.mockResolvedValue([true, false])+ const step = createDedupeFeatureFlagCalledStep(service)++ await step([+ createInput({ $feature_flag: 'flag-a', $feature_flag_response: 'variant-1', $groups: { org: 'o1' } }),+ createInput({ $feature_flag: 'flag-a', $feature_flag_response: 'variant-1', $groups: { org: 'o1' } }),+ ])++ const claims = service.claimKeys.mock.calls[0][0]+ expect(claims[0].key).toBe(claims[1].key)+ })+})diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/dedupe-feature-flag-called.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/dedupe-feature-flag-called.tsnew file mode 100644index 000000000000..c90edfd88754--- /dev/null+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/dedupe-feature-flag-called.ts@@ -0,0 +1,94 @@+import { PipelineResult, drop, ok } from '~/ingestion/framework/results'+import {+ FeatureFlagCalledDedupClaim,+ FeatureFlagCalledDedupService,+ featureFlagCalledDedupKey,+} from '~/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service'+import { featureFlagCalledDedupEventsTotal } from '~/ingestion/utils/feature-flag-called-dedup/metrics'+import { PluginEvent } from '~/plugin-scaffold'+import { Team } from '~/types'++export interface DedupeFeatureFlagCalledStepInput {+ event: PluginEvent+ team: Team+}++/**+ * Drops redundant $feature_flag_called events using a keep-first Redis claim+ * keyed on (team, distinct_id, flag, response, groups). Server-side SDKs on+ * multi-process fleets re-emit the same exposure from every worker; only the+ * first copy carries signal, so the survivors preserve experiment exposure+ * semantics while the bulk of the volume is dropped. Note that "last called"+ * timestamps become TTL-granular: within a dedup window they reflect the+ * first call, not the most recent one.+ *+ * Claims are tagged with the event uuid, so a batch replayed by at-least-once+ * Kafka delivery recognizes its own claims from a failed prior attempt+ * instead of dropping events that were never written.+ *+ * Must run after cookieless processing (which rewrites event.distinct_id) and+ * before person processing, so dropped events skip the person and ClickHouse+ * writes entirely.+ *+ * In 'shadow' mode the claim is made and counted but nothing is dropped. If no+ * service is provided, this step is a passthrough. Redis failures fail open+ * inside the service: every event passes.+ */+export function createDedupeFeatureFlagCalledStep<T extends DedupeFeatureFlagCalledStepInput>(+ dedupService?: FeatureFlagCalledDedupService+) {+ return async function dedupeFeatureFlagCalledStep(inputs: T[]): Promise<PipelineResult<T>[]> {+ if (!dedupService || inputs.length === 0) {+ return inputs.map((input) => ok(input))+ }++ const claimPerInput: (FeatureFlagCalledDedupClaim | null)[] = inputs.map((input) => {+ if (input.event.event !== '$feature_flag_called' || !dedupService.isEnabledForTeam(input.team.id)) {+ return null+ }+ const properties = input.event.properties ?? {}+ const flagKey = properties['$feature_flag']+ // Without a uuid there is no stable claim identity, so pass the event through.+ if (typeof flagKey !== 'string' || !input.event.uuid) {+ return null+ }+ return {+ key: featureFlagCalledDedupKey(+ input.team.id,+ input.event.distinct_id,+ flagKey,+ properties['$feature_flag_response'],+ properties['$groups']+ ),+ claimId: input.event.uuid,+ }+ })++ const claims = claimPerInput.filter((claim): claim is FeatureFlagCalledDedupClaim => claim !== null)+ if (claims.length === 0) {+ return inputs.map((input) => ok(input))+ }++ const claimed = await dedupService.claimKeys(claims)++ // `claimed` has exactly one entry per non-null claim, in input order.+ // A missing entry fails open: a short result must never drop events.+ let claimIndex = 0+ return inputs.map((input, index) => {+ if (claimPerInput[index] === null) {+ return ok(input)+ }+ const isFirst = claimed[claimIndex++] ?? true+ if (isFirst) {+ featureFlagCalledDedupEventsTotal.labels('first_seen').inc()+ return ok(input)+ }+ if (dedupService.mode === 'drop') {+ featureFlagCalledDedupEventsTotal.labels('duplicate_dropped').inc()+ return drop('feature_flag_called_duplicate')+ }+ featureFlagCalledDedupEventsTotal.labels('duplicate_shadow').inc()+ return ok(input)+ })+ }+}diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/index.tsindex 0b44d6a7a5c1..d9ffe6de0c90 100644--- a/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts@@ -1,6 +1,7 @@export { createApplyCookielessProcessingStep } from './apply-cookieless-processing'export { createApplyEventRestrictionsStep } from './apply-event-restrictions'export { createApplyPersonProcessingRestrictionsStep } from './apply-person-processing-restrictions'+export { createDedupeFeatureFlagCalledStep } from './dedupe-feature-flag-called'export { createEnrichSurveyPersonPropertiesStep } from './enrich-survey-person-properties'export { createParseHeadersStep } from './parse-headers'export { createParseKafkaMessageStep } from './parse-kafka-message'diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex cb1964730568..c13e4b51e866 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -166,6 +166,19 @@ export type IngestionConsumerConfig = {/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: string+ // $feature_flag_called keep-first dedup config+ /** 'disabled' | 'shadow' (claim + count, never drop) | 'drop' */+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE: string+ /** '*' for all teams, or comma-separated team IDs */+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_TEAMS: string+ /** Comma-separated team IDs never deduped, even when TEAMS is '*' */+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS: string+ /** Claim TTL: the keep-first dedup window */+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_TTL_SECONDS: number+ /** Dedicated Redis host for dedup claims; empty reuses the ingestion Redis */+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST: string+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT: number+// AI event splitting configINGESTION_AI_EVENT_SPLITTING_ENABLED: boolean/** '*' for all teams, or comma-separated team IDs always routed to ai_events */@@ -278,6 +291,16 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {KAFKA_BATCH_START_LOGGING_ENABLED: false,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,+ // $feature_flag_called keep-first dedup config+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE: 'disabled',++ INGESTION_FEATURE_FLAG_CALLED_DEDUP_TEAMS: '',++ INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS: '',+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_TTL_SECONDS: 60 * 60,+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST: '',+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT: 6379,+// AI event splitting configINGESTION_AI_EVENT_SPLITTING_ENABLED: false,INGESTION_AI_EVENT_SPLITTING_TEAMS: '*',diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 99bdd6e8b47b..fd5d036443d6 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -47,6 +47,10 @@ import { TeamManager } from '~/utils/team-manager'import { AiEventSubpipelineFactory } from './common/ai-subpipeline.contract'import { EventFilterManager, EventFilterManagerComponent } from './common/event-filters'import { IngestionConsumerConfig } from './config'+import {+ FeatureFlagCalledDedupService,+ createFeatureFlagCalledDedupService,+} from './utils/feature-flag-called-dedup/feature-flag-called-dedup-service'import { MainLaneOverflowRedirect } from './utils/overflow-redirect/main-lane-overflow-redirect'import { OverflowLaneOverflowRedirect } from './utils/overflow-redirect/overflow-lane-overflow-redirect'import { OverflowRedirectService } from './utils/overflow-redirect/overflow-redirect-service'@@ -58,6 +62,8 @@ export type IngestionConsumerFullConfig = IngestionConsumerConfig &export interface IngestionConsumerDeps {postgres: PostgresRouterredisPool: RedisPool+ /** Dedicated pool for $feature_flag_called dedup claims; reuses redisPool when unset */+ featureFlagCalledDedupRedisPool?: RedisPooloutputs: IngestionOutputs<| EventOutput| AiEventOutput@@ -111,6 +117,7 @@ export class IngestionConsumer {public hogTransformer: HogTransformerprivate overflowRedirectService?: OverflowRedirectServiceprivate overflowLaneTTLRefreshService?: OverflowRedirectService+ private featureFlagCalledDedupService?: FeatureFlagCalledDedupServiceprivate tokenDistinctIdsToDrop: string[] = []private tokenDistinctIdsToSkipPersons: string[] = []private tokenDistinctIdsToForceOverflow: string[] = []@@ -188,6 +195,11 @@ export class IngestionConsumer {})}+ this.featureFlagCalledDedupService = createFeatureFlagCalledDedupService(+ this.deps.featureFlagCalledDedupRedisPool ?? this.deps.redisPool,+ this.config+ )+this.hogTransformer = deps.hogTransformerthis.personsStore = new BatchWritingPersonsStore(this.deps.personRepository, this.deps.outputs, {@@ -286,6 +298,7 @@ export class IngestionConsumer {promiseScheduler: this.promiseScheduler,overflowRedirectService: this.overflowRedirectService,overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,+ featureFlagCalledDedupService: this.featureFlagCalledDedupService,teamManager: this.deps.teamManager,cookielessManager: this.deps.cookielessManager,groupTypeManager: this.deps.groupTypeManager,diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex 8e5d87b0d093..a4b0f6bbb08a 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -41,6 +41,7 @@ import { newBatchingPipeline } from '~/ingestion/framework/builders'import { TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'import { OkResultWithContext } from '~/ingestion/framework/pipeline.interface'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'+import { FeatureFlagCalledDedupService } from '~/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service'import { OverflowRedirectService } from '~/ingestion/utils/overflow-redirect/overflow-redirect-service'import { Team } from '~/types'import { EventIngestionRestrictionManager } from '~/utils/event-ingestion-restrictions'@@ -100,6 +101,7 @@ export interface JoinedIngestionPipelineDeps {promiseScheduler: PromiseScheduleroverflowRedirectService?: OverflowRedirectServiceoverflowLaneTTLRefreshService?: OverflowRedirectService+ featureFlagCalledDedupService?: FeatureFlagCalledDedupServiceteamManager: TeamManagercookielessManager: CookielessManagergroupTypeManager: GroupTypeManager@@ -160,6 +162,7 @@ export function createJoinedIngestionPipeline<promiseScheduler,overflowRedirectService,overflowLaneTTLRefreshService,+ featureFlagCalledDedupService,teamManager,cookielessManager,groupTypeManager,@@ -183,6 +186,7 @@ export function createJoinedIngestionPipeline<preservePartitionLocality,overflowRedirectService,overflowLaneTTLRefreshService,+ featureFlagCalledDedupService,personsPrefetchEnabled,hogTransformer,cdpHogWatcherSampleRate,diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.tsindex 9339e5f445ed..45b9b39bcd1f 100644--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts@@ -9,6 +9,7 @@ import { createApplyEventFiltersStep } from '~/ingestion/common/steps/event-filtimport {createApplyCookielessProcessingStep,createApplyPersonProcessingRestrictionsStep,+ createDedupeFeatureFlagCalledStep,createOnlyCookielessRateLimitToOverflowStep,createOverflowLaneTTLRefreshStep,createValidateEventMetadataStep,@@ -20,6 +21,7 @@ import { createPrefetchHogFunctionsStep } from '~/ingestion/common/steps/event-pimport { BatchPipelineBuilder } from '~/ingestion/framework/builders/batch-pipeline-builders'import { prefetchPersonsStep } from '~/ingestion/pipelines/analytics/steps/prefetchPersonsStep'import { processPersonlessDistinctIdsBatchStep } from '~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep'+import { FeatureFlagCalledDedupService } from '~/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service'import { OverflowRedirectService } from '~/ingestion/utils/overflow-redirect/overflow-redirect-service'import { PluginEvent } from '~/plugin-scaffold'import { EventHeaders, Team } from '~/types'@@ -44,6 +46,7 @@ export interface PostTeamPreprocessingSubpipelineConfig {preservePartitionLocality: booleanoverflowRedirectService?: OverflowRedirectServiceoverflowLaneTTLRefreshService?: OverflowRedirectService+ featureFlagCalledDedupService?: FeatureFlagCalledDedupServicepersonsPrefetchEnabled: booleanhogTransformer: HogTransformercdpHogWatcherSampleRate: number@@ -62,6 +65,7 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPrpreservePartitionLocality,overflowRedirectService,overflowLaneTTLRefreshService,+ featureFlagCalledDedupService,personsPrefetchEnabled,hogTransformer,cdpHogWatcherSampleRate,@@ -94,6 +98,10 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr.pipeBatch(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Refresh TTLs for overflow lane events (keeps Redis flags alive).pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))+ // Drop redundant $feature_flag_called events (keep-first Redis claim).+ // Must run after cookieless (keys on the final distinct_id) and before+ // person prefetch so duplicates skip person processing and the CH write.+ .pipeBatch(createDedupeFeatureFlagCalledStep(featureFlagCalledDedupService))// Prefetch must run after cookieless, as cookieless changes distinct IDs.// Prefetch is fire-and-forget (best-effort cache warming), so retry here would be a// no-op — transient persons-Postgres failures are swallowed inside prefetchPersons sodiff --git a/nodejs/src/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service.test.ts b/nodejs/src/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service.test.tsnew file mode 100644index 000000000000..e06eb737b884--- /dev/null+++ b/nodejs/src/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service.test.ts@@ -0,0 +1,330 @@+import { IngestionLane } from '~/ingestion/config'+import { RedisPool } from '~/types'++import {+ RedisFeatureFlagCalledDedupService,+ createFeatureFlagCalledDedupService,+ featureFlagCalledDedupKey,+ parseFeatureFlagCalledDedupConfig,+} from './feature-flag-called-dedup-service'++interface MockRedis {+ pipeline: jest.Mock+ exec: jest.Mock+ set: jest.Mock+ get: jest.Mock+}++const createMockRedisPool = (+ execResults: [Error | null, unknown][] | null | Error+): { pool: RedisPool; redis: MockRedis } => {+ const pipeline = {+ set: jest.fn().mockReturnThis(),+ get: jest.fn().mockReturnThis(),+ exec:+ execResults instanceof Error+ ? jest.fn().mockRejectedValue(execResults)+ : jest.fn().mockResolvedValue(execResults),+ }+ const redis = {+ pipeline: jest.fn().mockReturnValue(pipeline),+ exec: pipeline.exec,+ set: pipeline.set,+ get: pipeline.get,+ }+ const pool = {+ acquire: jest.fn().mockResolvedValue(redis),+ release: jest.fn().mockResolvedValue(undefined),+ } as unknown as RedisPool+ return { pool, redis }+}++const createService = (execResults: [Error | null, unknown][] | null | Error) => {+ const { pool, redis } = createMockRedisPool(execResults)+ const service = new RedisFeatureFlagCalledDedupService({+ redisPool: pool,+ config: parseFeatureFlagCalledDedupConfig('drop', '*', '', 3600),+ })+ return { service, redis }+}++describe('RedisFeatureFlagCalledDedupService', () => {+ describe('parseFeatureFlagCalledDedupConfig', () => {+ it('parses a full config', () => {+ const config = parseFeatureFlagCalledDedupConfig('shadow', '1,2,3', '4', 600)++ expect(config).toEqual({ mode: 'shadow', teams: [1, 2, 3], excludedTeams: [4], ttlSeconds: 600 })+ })++ it('parses wildcard teams', () => {+ const config = parseFeatureFlagCalledDedupConfig('drop', '*', '', 600)++ expect(config.teams).toBe('*')+ expect(config.excludedTeams).toEqual([])+ })++ it('falls back to disabled on an invalid mode', () => {+ const config = parseFeatureFlagCalledDedupConfig('garbage', '*', '', 600)++ expect(config.mode).toBe('disabled')+ })++ it('treats wildcard excluded teams as disabled', () => {+ const config = parseFeatureFlagCalledDedupConfig('drop', '*', '*', 600)++ expect(config.mode).toBe('disabled')+ expect(config.excludedTeams).toEqual([])+ })++ it('recognizes whitespace-padded wildcards', () => {+ const config = parseFeatureFlagCalledDedupConfig('drop', ' * ', ' * ', 600)++ expect(config.mode).toBe('disabled')+ expect(config.teams).toBe('*')+ })++ it.each([[0], [-5], [NaN]])('falls back to disabled on invalid ttl %p', (ttlSeconds) => {+ const config = parseFeatureFlagCalledDedupConfig('drop', '*', '', ttlSeconds)++ expect(config.mode).toBe('disabled')+ })+ })++ describe('createFeatureFlagCalledDedupService', () => {+ const envConfig = (mode: string, lane: IngestionLane | null = null) => ({+ INGESTION_LANE: lane,+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE: mode,+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_TEAMS: '*',+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS: '',+ INGESTION_FEATURE_FLAG_CALLED_DEDUP_TTL_SECONDS: 3600,+ })++ it('returns undefined when disabled', () => {+ const { pool } = createMockRedisPool([])++ expect(createFeatureFlagCalledDedupService(pool, envConfig('disabled'))).toBeUndefined()+ })++ it('returns a service with the configured mode otherwise', () => {+ const { pool } = createMockRedisPool([])++ const service = createFeatureFlagCalledDedupService(pool, envConfig('drop'))++ expect(service).toBeInstanceOf(RedisFeatureFlagCalledDedupService)+ expect(service?.mode).toBe('drop')+ })++ it.each<[IngestionLane | null, boolean]>([+ ['main', true],+ ['overflow', true],+ [null, true],+ ['historical', false],+ ['async', false],+ ])('lane %s yields a service: %s', (lane, expectService) => {+ const { pool } = createMockRedisPool([])++ const service = createFeatureFlagCalledDedupService(pool, envConfig('drop', lane))++ if (expectService) {+ expect(service).toBeInstanceOf(RedisFeatureFlagCalledDedupService)+ } else {+ expect(service).toBeUndefined()+ }+ })+ })++ describe('isEnabledForTeam', () => {+ it.each([+ ['*', '', 5, true],+ ['*', '5', 5, false],+ ['1,2', '', 2, true],+ ['1,2', '', 3, false],+ ['1,2', '2', 2, false],+ ['', '', 1, false],+ ])('teams=%s excluded=%s team=%i -> %s', (teams, excluded, teamId, expected) => {+ const { pool } = createMockRedisPool([])+ const service = new RedisFeatureFlagCalledDedupService({+ redisPool: pool,+ config: parseFeatureFlagCalledDedupConfig('drop', teams, excluded, 3600),+ })++ expect(service.isEnabledForTeam(teamId)).toBe(expected)+ })+ })++ describe('featureFlagCalledDedupKey', () => {+ it('has a compact, team-scannable shape', () => {+ // Key bytes are paid per live key at prod cardinality, so the+ // shape (short prefix, truncated digest) is a memory contract.+ expect(featureFlagCalledDedupKey(42, 'user-1', 'flag-a', 'variant-1', { org: 'o1' })).toMatch(+ /^ffcd:42:[A-Za-z0-9_-]{22}$/+ )+ })++ it('is stable for the same tuple', () => {+ expect(featureFlagCalledDedupKey(1, 'user-1', 'flag-a', 'variant-1', { org: 'o1' })).toBe(+ featureFlagCalledDedupKey(1, 'user-1', 'flag-a', 'variant-1', { org: 'o1' })+ )+ })++ it('is independent of $groups property ordering', () => {+ expect(featureFlagCalledDedupKey(1, 'user-1', 'flag-a', true, { a: '1', b: '2' })).toBe(+ featureFlagCalledDedupKey(1, 'user-1', 'flag-a', true, { b: '2', a: '1' })+ )+ })++ it.each([+ ['team', [1, 'user-1', 'flag-a', true, null], [2, 'user-1', 'flag-a', true, null]],+ ['distinct_id', [1, 'user-1', 'flag-a', true, null], [1, 'user-2', 'flag-a', true, null]],+ ['flag', [1, 'user-1', 'flag-a', true, null], [1, 'user-1', 'flag-b', true, null]],+ ['response', [1, 'user-1', 'flag-a', true, null], [1, 'user-1', 'flag-a', false, null]],+ ['response null vs "null"', [1, 'user-1', 'flag-a', null, null], [1, 'user-1', 'flag-a', 'null', null]],+ ['groups', [1, 'user-1', 'flag-a', true, { org: 'o1' }], [1, 'user-1', 'flag-a', true, { org: 'o2' }]],+ ['groups vs none', [1, 'user-1', 'flag-a', true, { org: 'o1' }], [1, 'user-1', 'flag-a', true, undefined]],+ // The delimiter-injection collision class: components must not concatenate+ ['component boundary', [1, 'user:1', 'flag', true, null], [1, 'user', ':1flag', true, null]],+ ])('differs by %s', (_label, a, b) => {+ const [teamA, distinctA, flagA, responseA, groupsA] = a+ const [teamB, distinctB, flagB, responseB, groupsB] = b++ expect(+ featureFlagCalledDedupKey(teamA as number, distinctA as string, flagA as string, responseA, groupsA)+ ).not.toBe(+ featureFlagCalledDedupKey(teamB as number, distinctB as string, flagB as string, responseB, groupsB)+ )+ })+ })++ describe('claimKeys', () => {+ it('returns empty for no claims', async () => {+ const { service, redis } = createService([])++ expect(await service.claimKeys([])).toEqual([])+ expect(redis.pipeline).not.toHaveBeenCalled()+ })++ it('maps fresh claims to true and foreign claims to false', async () => {+ const { service, redis } = createService([+ [null, 'OK'],+ [null, 'uuid-1'],+ [null, null],+ [null, 'other-uuid'],+ ])++ expect(+ await service.claimKeys([+ { key: 'key-1', claimId: 'uuid-1' },+ { key: 'key-2', claimId: 'uuid-2' },+ ])+ ).toEqual([true, false])+ expect(redis.set).toHaveBeenCalledWith('key-1', 'uuid-1', 'EX', 3600, 'NX')+ expect(redis.set).toHaveBeenCalledWith('key-2', 'uuid-2', 'EX', 3600, 'NX')+ expect(redis.get).toHaveBeenCalledWith('key-1')+ expect(redis.get).toHaveBeenCalledWith('key-2')+ })++ it('recognizes its own prior claim on redelivery', async () => {+ // SET NX loses to the claim made by a previous delivery of the same+ // event, but the stored claim id matches, so the event still passes.+ const { service } = createService([+ [null, null],+ [null, 'uuid-1'],+ ])++ expect(await service.claimKeys([{ key: 'key-1', claimId: 'uuid-1' }])).toEqual([true])+ })++ it('resolves duplicate keys within one call in order', async () => {+ // Redis executes pipelined commands sequentially, so the first+ // occurrence of a repeated key claims it and later ones read the+ // first occurrence's claim id.+ const { service, redis } = createService([+ [null, 'OK'],+ [null, 'uuid-a'],+ [null, null],+ [null, 'uuid-a'],+ ])++ expect(+ await service.claimKeys([+ { key: 'key-1', claimId: 'uuid-a' },+ { key: 'key-1', claimId: 'uuid-b' },+ ])+ ).toEqual([true, false])+ expect(redis.set).toHaveBeenCalledTimes(2)+ })++ it('fails open when the pipeline throws', async () => {+ const { service } = createService(new Error('redis down'))++ expect(+ await service.claimKeys([+ { key: 'key-1', claimId: 'uuid-1' },+ { key: 'key-2', claimId: 'uuid-2' },+ ])+ ).toEqual([true, true])+ })++ it('fails open when the pipeline returns no results', async () => {+ const { service } = createService(null)++ expect(await service.claimKeys([{ key: 'key-1', claimId: 'uuid-1' }])).toEqual([true])+ })++ it('fails open when the pipeline returns the wrong number of results', async () => {+ const { service } = createService([[null, 'OK']])++ expect(await service.claimKeys([{ key: 'key-1', claimId: 'uuid-1' }])).toEqual([true])+ })++ it('fails open per claim on SET command errors', async () => {+ const { service } = createService([+ [new Error('boom'), null],+ [null, 'other-uuid'],+ [null, null],+ [null, 'other-uuid'],+ ])++ expect(+ await service.claimKeys([+ { key: 'key-1', claimId: 'uuid-1' },+ { key: 'key-2', claimId: 'uuid-2' },+ ])+ ).toEqual([true, false])+ })++ it('fails open per claim on GET command errors', async () => {+ const { service } = createService([+ [null, null],+ [new Error('boom'), null],+ ])++ expect(await service.claimKeys([{ key: 'key-1', claimId: 'uuid-1' }])).toEqual([true])+ })++ it('fails open when the key disappears between SET and GET', async () => {+ // The pipeline is not atomic: the key existed at SET time (NX+ // lost) but expired or was evicted before the GET. No claim+ // present means no evidence of a duplicate.+ const { service } = createService([+ [null, null],+ [null, null],+ ])++ expect(await service.claimKeys([{ key: 'key-1', claimId: 'uuid-1' }])).toEqual([true])+ })++ it('fails open when acquiring a client fails', async () => {+ const pool = {+ acquire: jest.fn().mockRejectedValue(new Error('pool exhausted')),+ release: jest.fn(),+ } as unknown as RedisPool+ const service = new RedisFeatureFlagCalledDedupService({+ redisPool: pool,+ config: parseFeatureFlagCalledDedupConfig('drop', '*', '', 3600),+ })++ expect(await service.claimKeys([{ key: 'key-1', claimId: 'uuid-1' }])).toEqual([true])+ })+ })+})diff --git a/nodejs/src/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service.ts b/nodejs/src/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service.tsnew file mode 100644index 000000000000..20a0496338f7--- /dev/null+++ b/nodejs/src/ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service.ts@@ -0,0 +1,276 @@+import { createHash } from 'crypto'+import { Redis } from 'ioredis'++import { IngestionConsumerConfig, IngestionLane } from '~/ingestion/config'+import { RedisPool } from '~/types'+import { timeoutGuard } from '~/utils/db/utils'+import { parseTeamsList } from '~/utils/env-utils'+import { logger } from '~/utils/logger'++import { featureFlagCalledDedupRedisLatency, featureFlagCalledDedupRedisOpsTotal } from './metrics'++// Deliberately terse: at full rollout every key byte costs ~13 MB of shared+// Redis memory (one byte per ~13M live keys).+const REDIS_KEY_PREFIX = 'ffcd:'++// 22 base64url chars = 132 bits. Birthday-bound collision probability across+// ~13M live keys is ~2^-86 — far below the rate of any failure mode we handle.+const HASH_LENGTH = 22++const FEATURE_FLAG_CALLED_DEDUP_MODES = ['disabled', 'shadow', 'drop'] as const++export type FeatureFlagCalledDedupMode = (typeof FEATURE_FLAG_CALLED_DEDUP_MODES)[number]++function isFeatureFlagCalledDedupMode(mode: string): mode is FeatureFlagCalledDedupMode {+ return (FEATURE_FLAG_CALLED_DEDUP_MODES as readonly string[]).includes(mode)+}++export interface FeatureFlagCalledDedupConfig {+ mode: FeatureFlagCalledDedupMode+ /** '*' for all teams, or an explicit allowlist of team IDs. */+ teams: number[] | '*'+ /** Escape hatch: teams never deduped, even when `teams` is '*'. */+ excludedTeams: number[]+ ttlSeconds: number+}++export function parseFeatureFlagCalledDedupConfig(+ mode: string,+ teams: string,+ excludedTeams: string,+ ttlSeconds: number+): FeatureFlagCalledDedupConfig {+ let parsedMode: FeatureFlagCalledDedupMode = 'disabled'+ if (isFeatureFlagCalledDedupMode(mode)) {+ parsedMode = mode+ } else {+ logger.warn('Invalid INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE, falling back to disabled', { mode })+ }+ const excluded = parseTeamsList(excludedTeams)+ if (excluded === '*') {+ // An operator reaching for '*' as an exclude-everyone switch means "off";+ // the escape hatch on a data-dropping feature must not fail toward dropping.+ logger.warn('INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS is "*", disabling dedup')+ parsedMode = 'disabled'+ }+ if (parsedMode !== 'disabled' && (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0)) {+ // An invalid TTL would make every SET ... EX command error, silently+ // disabling dedup behind a stream of Redis errors.+ logger.warn('Invalid INGESTION_FEATURE_FLAG_CALLED_DEDUP_TTL_SECONDS, falling back to disabled', {+ ttlSeconds,+ })+ parsedMode = 'disabled'+ }+ return {+ mode: parsedMode,+ teams: parseTeamsList(teams),+ excludedTeams: excluded === '*' ? [] : excluded,+ ttlSeconds,+ }+}++/**+ * Builds the Redis claim key for one $feature_flag_called exposure.+ *+ * The variable-length components are JSON-encoded as an array before hashing,+ * so a delimiter appearing inside a value (e.g. a distinct_id containing ':')+ * can never collide with another tuple. `$groups` entries are sorted to make+ * the key independent of property ordering.+ */+export function featureFlagCalledDedupKey(+ teamId: number,+ distinctId: string,+ flagKey: string,+ response: unknown,+ groups: unknown+): string {+ const normalizedGroups =+ groups && typeof groups === 'object' && !Array.isArray(groups)+ ? Object.entries(groups as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))+ : null+ // teamId is also in the hash so the digest alone is tenant-scoped, even if+ // a future code path assembles a key without the prefix. The plaintext+ // teamId stays in the key so operators can SCAN or purge one team's claims.+ const hash = createHash('sha256')+ .update(JSON.stringify([teamId, distinctId, flagKey, response ?? null, normalizedGroups]))+ .digest('base64url')+ .slice(0, HASH_LENGTH)+ return `${REDIS_KEY_PREFIX}${teamId}:${hash}`+}++/** One keep-first claim for a $feature_flag_called exposure. */+export interface FeatureFlagCalledDedupClaim {+ key: string+ /**+ * Stable identity of the claiming event (its uuid). At-least-once Kafka+ * delivery can replay a batch whose claims already succeeded but whose+ * events were never written; the claim id lets the replay recognize its+ * own claims instead of dropping those events as duplicates.+ */+ claimId: string+}++/**+ * Keep-first dedup claims for $feature_flag_called events.+ */+export interface FeatureFlagCalledDedupService {+ mode: FeatureFlagCalledDedupMode+ isEnabledForTeam(teamId: number): boolean+ /**+ * Claims each key, returning one boolean per claim: true if the event+ * should pass (first to claim the key, or the key holds this event's own+ * claim id from a prior delivery), false if another event already claimed+ * it (duplicate). Duplicate keys within one call resolve in order — the+ * first occurrence claims, later ones are duplicates.+ */+ claimKeys(claims: FeatureFlagCalledDedupClaim[]): Promise<boolean[]>+}++export interface RedisFeatureFlagCalledDedupServiceOptions {+ redisPool: RedisPool+ config: FeatureFlagCalledDedupConfig+}++export type FeatureFlagCalledDedupEnvConfig = Pick<+ IngestionConsumerConfig,+ | 'INGESTION_LANE'+ | 'INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE'+ | 'INGESTION_FEATURE_FLAG_CALLED_DEDUP_TEAMS'+ | 'INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS'+ | 'INGESTION_FEATURE_FLAG_CALLED_DEDUP_TTL_SECONDS'+>++/** Lanes that may dedup. `null` covers local dev, where no lane is set. */+const DEDUP_ALLOWED_LANES: readonly (IngestionLane | null)[] = ['main', 'overflow', null]++/**+ * Builds the dedup service from ingestion config, or undefined when the dedup+ * is disabled (the pipeline step treats an absent service as a passthrough).+ *+ * The dedup window is processing-time, not event-time, so lanes that process+ * delayed events (historical, async) must never dedup: a backfilled event is+ * not a duplicate of the live event that claimed its tuple an hour ago. The+ * lane gate holds even if the dedup env vars leak into a shared config.+ */+export function createFeatureFlagCalledDedupService(+ redisPool: RedisPool,+ envConfig: FeatureFlagCalledDedupEnvConfig+): FeatureFlagCalledDedupService | undefined {+ const config = parseFeatureFlagCalledDedupConfig(+ envConfig.INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE,+ envConfig.INGESTION_FEATURE_FLAG_CALLED_DEDUP_TEAMS,+ envConfig.INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS,+ envConfig.INGESTION_FEATURE_FLAG_CALLED_DEDUP_TTL_SECONDS+ )+ if (config.mode === 'disabled') {+ return undefined+ }+ if (!DEDUP_ALLOWED_LANES.includes(envConfig.INGESTION_LANE)) {+ logger.warn('Feature flag called dedup is not supported on this ingestion lane, disabling', {+ lane: envConfig.INGESTION_LANE,+ })+ return undefined+ }+ return new RedisFeatureFlagCalledDedupService({ redisPool, config })+}++/**+ * Redis-backed keep-first claims: `SET key <claimId> NX EX ttl` paired with a+ * `GET`. The first event for a tuple wins the claim; a later event passes only+ * when the stored claim id is its own (the same event redelivered by Kafka),+ * otherwise it loses the claim for the TTL window.+ *+ * Redis failures that reject fail open (everything is treated as claimed) — a+ * dedup outage must never suppress events. Connectivity loss does not reject:+ * pool clients use `maxRetriesPerRequest: -1`, so commands queue until the+ * shared client error watchdog kills the process; the 30s timeoutGuard below+ * logs and captures an exception but does not abort the command.+ */+export class RedisFeatureFlagCalledDedupService implements FeatureFlagCalledDedupService {+ private redisPool: RedisPool+ private config: FeatureFlagCalledDedupConfig+ private teams: Set<number> | '*'+ private excludedTeams: Set<number>++ constructor(options: RedisFeatureFlagCalledDedupServiceOptions) {+ this.redisPool = options.redisPool+ this.config = options.config+ this.teams = options.config.teams === '*' ? '*' : new Set(options.config.teams)+ this.excludedTeams = new Set(options.config.excludedTeams)+ }++ get mode(): FeatureFlagCalledDedupMode {+ return this.config.mode+ }++ isEnabledForTeam(teamId: number): boolean {+ if (this.excludedTeams.has(teamId)) {+ return false+ }+ return this.teams === '*' || this.teams.has(teamId)+ }++ async claimKeys(claims: FeatureFlagCalledDedupClaim[]): Promise<boolean[]> {+ if (claims.length === 0) {+ return []+ }++ const failOpen = claims.map(() => true)+ const startTime = performance.now()+ const timeout = timeoutGuard('Feature flag called dedup claim delayed. Waiting over 30 sec.', {+ count: claims.length,+ })+ let client: Redis | undefined+ try {+ client = await this.redisPool.acquire()+ const pipeline = client.pipeline()+ for (const claim of claims) {+ pipeline.set(claim.key, claim.claimId, 'EX', this.config.ttlSeconds, 'NX')+ pipeline.get(claim.key)+ }+ const results = await pipeline.exec()+ if (!results || results.length !== claims.length * 2) {+ featureFlagCalledDedupRedisOpsTotal.labels('error').inc()+ return failOpen+ }+ // SET ... NX replies 'OK' when the key was set (claimed) and null+ // when it already existed; the paired GET then tells us whether+ // the existing claim is this event's own (a redelivery). Any+ // per-command error fails open.+ let hadCommandError = false+ const passes = claims.map((claim, index) => {+ const [setError, setValue] = results[index * 2]+ const [getError, getValue] = results[index * 2 + 1]+ if (setError !== null || getError !== null) {+ hadCommandError = true+ }+ if (setError !== null || setValue === 'OK') {+ return true+ }+ if (getError !== null) {+ return true+ }+ // A pipeline is not atomic: the key can expire or be evicted+ // between the SET and the GET. No claim present means no+ // evidence of a duplicate, so fail open.+ return getValue === null || getValue === claim.claimId+ })+ featureFlagCalledDedupRedisOpsTotal.labels(hadCommandError ? 'partial_error' : 'success').inc()+ return passes+ } catch (error) {+ logger.warn('Redis error in feature flag called dedup claim, failing open', { error })+ featureFlagCalledDedupRedisOpsTotal.labels('error').inc()+ return failOpen+ } finally {+ clearTimeout(timeout)+ featureFlagCalledDedupRedisLatency.observe((performance.now() - startTime) / 1000)+ if (client) {+ try {+ await this.redisPool.release(client)+ } catch (releaseError) {+ logger.warn('Failed to release Redis client', { error: releaseError })+ }+ }+ }+ }+}diff --git a/nodejs/src/ingestion/utils/feature-flag-called-dedup/metrics.ts b/nodejs/src/ingestion/utils/feature-flag-called-dedup/metrics.tsnew file mode 100644index 000000000000..31ec5ce22df4--- /dev/null+++ b/nodejs/src/ingestion/utils/feature-flag-called-dedup/metrics.ts@@ -0,0 +1,19 @@+import { Counter, Histogram } from 'prom-client'++export const featureFlagCalledDedupEventsTotal = new Counter({+ name: 'ingestion_feature_flag_called_dedup_events_total',+ help: 'Outcomes of $feature_flag_called dedup claims',+ labelNames: ['outcome'], // 'first_seen' | 'duplicate_dropped' | 'duplicate_shadow'+})++export const featureFlagCalledDedupRedisOpsTotal = new Counter({+ name: 'ingestion_feature_flag_called_dedup_redis_ops_total',+ help: 'Redis operations by the feature flag called dedup service',+ labelNames: ['result'], // 'success' | 'partial_error' | 'error'+})++export const featureFlagCalledDedupRedisLatency = new Histogram({+ name: 'ingestion_feature_flag_called_dedup_redis_latency_seconds',+ help: 'Latency of feature flag called dedup Redis claims in seconds',+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],+})diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex be2eeb066cf4..76603c88052e 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -37,7 +37,11 @@ import {import { EncryptedFields } from '../cdp/utils/encryption-utils'import { CommonConfig } from '../common/config'import { defaultConfig, overrideConfigWithEnv } from '../config/config'-import { createCookielessRedisConnectionConfig, createIngestionRedisConnectionConfig } from '../config/redis-pools'+import {+ createCookielessRedisConnectionConfig,+ createFeatureFlagCalledDedupRedisConnectionConfig,+ createIngestionRedisConnectionConfig,+} from '../config/redis-pools'import { deserializeKafkaMessage } from '../ingestion/api/kafka-message-converter'import { IngestBatchRequest, IngestBatchResponse } from '../ingestion/api/types'import {@@ -57,6 +61,7 @@ import {RedisConnectionsConfig,getDefaultIngestionOutputsConfig,} from '../ingestion/config'+import { createFeatureFlagCalledDedupService } from '../ingestion/utils/feature-flag-called-dedup/feature-flag-called-dedup-service'import { MainLaneOverflowRedirect } from '../ingestion/utils/overflow-redirect/main-lane-overflow-redirect'import { OverflowLaneOverflowRedirect } from '../ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect'import { OverflowRedirectService } from '../ingestion/utils/overflow-redirect/overflow-redirect-service'@@ -155,6 +160,7 @@ export class IngestionApiServer implements NodeServer {private ingestionProducerRegistry?: KafkaProducerRegistry<ProducerName>private redisPool?: RedisPoolprivate cookielessRedisPool?: RedisPool+ private featureFlagCalledDedupRedisPool?: RedisPoolprivate cookielessManager?: CookielessManagerprivate pubsub?: PubSubprivate personsStore?: BatchWritingPersonsStore@@ -258,6 +264,14 @@ export class IngestionApiServer implements NodeServer {logger.info('👍', 'Cookieless Redis ready')this.cookielessManager = new CookielessManager(this.config, this.cookielessRedisPool)++ // Dedicated $feature_flag_called dedup Redis; falls back to ingestion until the host is set.+ this.featureFlagCalledDedupRedisPool = createRedisPoolFromConfig({+ connection: createFeatureFlagCalledDedupRedisConnectionConfig(this.config),+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,+ })+const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)// 4. Kafka producers for pipeline outputs (not consuming from Kafka)@@ -369,6 +383,11 @@ export class IngestionApiServer implements NodeServer {concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,}const eventFilterManagerStarted = await new EventFilterManagerComponent(this.postgres).start()+ const featureFlagCalledDedupService = createFeatureFlagCalledDedupService(+ this.featureFlagCalledDedupRedisPool,+ this.config+ )+const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore,groupStore,@@ -380,6 +399,7 @@ export class IngestionApiServer implements NodeServer {promiseScheduler: this.promiseScheduler,overflowRedirectService,overflowLaneTTLRefreshService,+ featureFlagCalledDedupService,teamManager,cookielessManager: this.cookielessManager,groupTypeManager,@@ -519,7 +539,9 @@ export class IngestionApiServer implements NodeServer {private getCleanupResources(): CleanupResources {return {kafkaProducers: [],- redisPools: [this.redisPool, this.cookielessRedisPool].filter(Boolean) as RedisPool[],+ redisPools: [this.redisPool, this.cookielessRedisPool, this.featureFlagCalledDedupRedisPool].filter(+ Boolean+ ) as RedisPool[],postgres: this.postgres,pubsub: this.pubsub,additionalCleanup: async () => {diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.tsindex cd8fd979f173..0468ce3c71a9 100644--- a/nodejs/src/servers/ingestion-general-server.ts+++ b/nodejs/src/servers/ingestion-general-server.ts@@ -25,7 +25,11 @@ import {KAFKA_EVENTS_PLUGIN_INGESTION_HISTORICAL,KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW,} from '../config/kafka-topics'-import { createCookielessRedisConnectionConfig, createIngestionRedisConnectionConfig } from '../config/redis-pools'+import {+ createCookielessRedisConnectionConfig,+ createFeatureFlagCalledDedupRedisConnectionConfig,+ createIngestionRedisConnectionConfig,+} from '../config/redis-pools'import {KafkaDownstreamProducerEnvConfig,KafkaUpstreamProducerEnvConfig,@@ -155,6 +159,17 @@ export class IngestionGeneralServer implements NodeServer {poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,}))+ // Dedicated $feature_flag_called dedup Redis, so its claim keys don't compete+ // with ingestion's overflow-redirect keys under eviction. Falls back to the+ // ingestion connection until the dedup host is configured.+ .add(+ 'featureFlagCalledDedupRedisPool',+ new RedisPoolComponent({+ connection: createFeatureFlagCalledDedupRedisConnectionConfig(this.config),+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,+ })+ ).add('producerRegistry', new KafkaProducerRegistryComponent(this.config.KAFKA_CLIENT_RACK, this.config)))@@ -245,6 +260,7 @@ export class IngestionGeneralServer implements NodeServer {const ingestionDeps: IngestionConsumerDeps = {postgres: this.postgres,redisPool: this.redisPool,+ featureFlagCalledDedupRedisPool: sharedServices.container.featureFlagCalledDedupRedisPool,outputs: ingestionOutputs,teamManager,groupTypeManager,diff --git a/nodejs/src/utils/env-utils.ts b/nodejs/src/utils/env-utils.tsindex 05813efd2110..8a0edea8d68c 100644--- a/nodejs/src/utils/env-utils.ts+++ b/nodejs/src/utils/env-utils.ts@@ -52,7 +52,9 @@ export function isOverflowBatchByDistinctId(): boolean {// Parse a comma-separated env var of team ids into a list, or '*' for "all teams".export function parseTeamsList(teamsStr: string): number[] | '*' {- if (teamsStr === '*') {+ // Trim so a whitespace-padded '*' (easy to produce in Helm/YAML) is still+ // recognized as the wildcard rather than silently parsing as an empty list.+ if (teamsStr.trim() === '*') {return '*'}return teamsStr