:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ingestion): rate limit to overflow by the kafka message key (#95565)
José Sequeira977946ac7a1c
diff --git a/nodejs/src/common/kafka/consumer/consumer-v1.ts b/nodejs/src/common/kafka/consumer/consumer-v1.tsindex 9c7f810a88bc..ca401cc6aa04 100644--- a/nodejs/src/common/kafka/consumer/consumer-v1.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v1.ts@@ -940,6 +940,8 @@ export const parseEventHeaders = (headers?: MessageHeader[]): EventHeaders => {result.historical_migration = value === 'true'} else if (key === 'skip_heatmap_processing') {result.skip_heatmap_processing = value === 'true'+ } else if (key === 'redirect-original-key') {+ result.redirect_original_key = value}})})diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snapindex 90f6878315bb..ad2e17caba50 100644--- a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap+++ b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap@@ -137,7 +137,8 @@ exports[`IngestionConsumer general overflow should emit to overflow if token and"distinct_id": "overflow-distinct-id","event": "$pageview","now": "2025-01-01T00:00:00.000Z",- "redirect-step": "skipCookielessRateLimitToOverflowStep",+ "redirect-original-key": "THIS IS NOT A TOKEN FOR TEAM 2:overflow-distinct-id",+ "redirect-step": "rateLimitToOverflowStep","redirect-timestamp": "2025-01-01T00:00:00.000Z","token": "THIS IS NOT A TOKEN FOR TEAM 2","uuid": "<REPLACED-UUID-0>",diff --git a/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.test.ts b/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.test.tsindex 08830bf06c19..62b4c78e0d8a 100644--- a/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.test.ts+++ b/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.test.ts@@ -19,7 +19,7 @@ const createGroup = (eventCount: number = 1,firstTimestamp: number = Date.now()): OverflowEventGroup => ({- key: { token, distinctId },+ key: `${token}:${distinctId}`,headersPerEvent: Array.from({ length: eventCount }, () =>createTestEventHeaders({ token, distinct_id: distinctId })),@@ -69,7 +69,7 @@ describe('MainLaneOverflowRedirect', () => {await service.handleEventBatch(batch)- expect(mockRepository.batchFlag).toHaveBeenCalledWith('events', [{ token: 'token1', distinctId: 'user1' }])+ expect(mockRepository.batchFlag).toHaveBeenCalledWith('events', ['token1:user1'])})it('checks Redis for keys not in local cache', async () => {@@ -77,7 +77,7 @@ describe('MainLaneOverflowRedirect', () => {await service.handleEventBatch(batch)- expect(mockRepository.batchCheck).toHaveBeenCalledWith('events', [{ token: 'token1', distinctId: 'user1' }])+ expect(mockRepository.batchCheck).toHaveBeenCalledWith('events', ['token1:user1'])})it('returns keys that are already flagged in Redis', async () => {@@ -159,9 +159,9 @@ describe('MainLaneOverflowRedirect', () => {expect(mockRepository.batchCheck).toHaveBeenCalledTimes(1)expect(mockRepository.batchCheck).toHaveBeenCalledWith('events', [- { token: 'token1', distinctId: 'user1' },- { token: 'token1', distinctId: 'user2' },- { token: 'token2', distinctId: 'user1' },+ 'token1:user1',+ 'token1:user2',+ 'token2:user1',])})})@@ -232,7 +232,7 @@ describe('MainLaneOverflowRedirect', () => {distinctId: string,eventNames: (string | undefined)[]): OverflowEventGroup => ({- key: { token, distinctId },+ key: `${token}:${distinctId}`,headersPerEvent: eventNames.map((event) =>createTestEventHeaders({ token, distinct_id: distinctId, event })),diff --git a/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.ts b/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.tsindex 29fde1487b75..4bb30e7911b9 100644--- a/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.ts+++ b/nodejs/src/ingestion/common/overflow-redirect/main-lane-overflow-redirect.ts@@ -13,7 +13,7 @@ import {overflowRedirectSourceEventsTotal,} from './metrics'import { OverflowEventGroup, OverflowRedirectService } from './overflow-redirect-service'-import { OverflowRedisRepository, OverflowType, memberKey } from './overflow-redis-repository'+import { OverflowRedisRepository, OverflowType } from './overflow-redis-repository'import { OverflowStrategyEntry } from './overflow-strategy'export interface MainLaneOverflowRedirectConfig {@@ -27,7 +27,7 @@ export interface MainLaneOverflowRedirectConfig {overflowType: OverflowType}-// Bounds the in-memory cache so a flood of unique token:distinct_id keys cannot+// Bounds the in-memory cache so a flood of unique partition keys cannot// grow it without limit; evicted keys simply re-check Redis on the next lookup.const DEFAULT_LOCAL_CACHE_MAX_SIZE = 1_000_000@@ -67,8 +67,8 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {this.overflowType = config.overflowType}- private localCacheKey(type: OverflowType, token: string, distinctId: string): string {- return `${type}:${token}:${distinctId}`+ private localCacheKey(type: OverflowType, key: string): string {+ return `${type}:${key}`}// true = flagged in Redis, false = known not in Redis, undefined = cache miss.@@ -91,14 +91,13 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {const needsRedisCheck: OverflowEventGroup[] = []for (const group of batch) {- const cacheKey = this.localCacheKey(type, group.key.token, group.key.distinctId)+ const cacheKey = this.localCacheKey(type, group.key)const cached = this.getCachedValue(cacheKey)if (cached === true) {// Already flagged (cached from previous Redis lookup) - redirect- const mKey = memberKey(group.key.token, group.key.distinctId)- toRedirect.add(mKey)- redirectSource.set(mKey, 'redis')+ toRedirect.add(group.key)+ redirectSource.set(group.key, 'redis')overflowRedirectCacheHitsTotal.labels(type, 'hit_flagged').inc()} else if (cached === false) {// Known not in Redis - check rate limit only@@ -119,13 +118,12 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {)for (const group of needsRedisCheck) {- const mKey = memberKey(group.key.token, group.key.distinctId)- const cacheKey = this.localCacheKey(type, group.key.token, group.key.distinctId)+ const cacheKey = this.localCacheKey(type, group.key)- if (redisResults.get(mKey)) {+ if (redisResults.get(group.key)) {// Flagged in Redis - redirect- toRedirect.add(mKey)- redirectSource.set(mKey, 'redis')+ toRedirect.add(group.key)+ redirectSource.set(group.key, 'redis')this.setCachedValue(cacheKey, true)} else {// Not in Redis - cache false and check rate limit@@ -142,8 +140,6 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {const newlyFlagged: OverflowEventGroup[] = []for (const group of needsRateLimitCheck) {- const rateLimitKey = memberKey(group.key.token, group.key.distinctId)-// Consume from every strategy (no short-circuit) so buckets drain// consistently; any exhausted bucket flags the key.let allowed = true@@ -156,7 +152,7 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {continue}- if (limiter.consume(rateLimitKey, tokens, group.firstTimestamp)) {+ if (limiter.consume(group.key, tokens, group.firstTimestamp)) {overflowRedirectRateLimitDecisions.labels(type, label, 'allowed').inc()} else {allowed = false@@ -167,8 +163,8 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {if (!allowed) {// Rate limit exceeded - needs to be flaggednewlyFlagged.push(group)- toRedirect.add(rateLimitKey)- redirectSource.set(rateLimitKey, 'rate_limiter')+ toRedirect.add(group.key)+ redirectSource.set(group.key, 'rate_limiter')}}@@ -177,8 +173,7 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {// Update local cache BEFORE Redis write to prevent race condition where// a subsequent batch could check the rate limiter again before Redis completesfor (const group of newlyFlagged) {- const cacheKey = this.localCacheKey(type, group.key.token, group.key.distinctId)- this.setCachedValue(cacheKey, true)+ this.setCachedValue(this.localCacheKey(type, group.key), true)}overflowRedirectCacheSize.set(this.localCache.size)@@ -198,10 +193,9 @@ export class MainLaneOverflowRedirect implements OverflowRedirectService {let passedEvents = 0const eventsBySource = new Map<'redis' | 'rate_limiter', number>()for (const group of batch) {- const mKey = memberKey(group.key.token, group.key.distinctId)- if (toRedirect.has(mKey)) {+ if (toRedirect.has(group.key)) {redirectedEvents += group.headersPerEvent.length- const source = redirectSource.get(mKey)+ const source = redirectSource.get(group.key)if (source) {eventsBySource.set(source, (eventsBySource.get(source) ?? 0) + group.headersPerEvent.length)}diff --git a/nodejs/src/ingestion/common/overflow-redirect/overflow-lane-overflow-redirect.test.ts b/nodejs/src/ingestion/common/overflow-redirect/overflow-lane-overflow-redirect.test.tsindex 792823faeb1a..c044e5fb0db9 100644--- a/nodejs/src/ingestion/common/overflow-redirect/overflow-lane-overflow-redirect.test.ts+++ b/nodejs/src/ingestion/common/overflow-redirect/overflow-lane-overflow-redirect.test.ts@@ -18,7 +18,7 @@ const createGroup = (eventCount: number = 1,firstTimestamp: number = Date.now()): OverflowEventGroup => ({- key: { token, distinctId },+ key: `${token}:${distinctId}`,headersPerEvent: Array.from({ length: eventCount }, () =>createTestEventHeaders({ token, distinct_id: distinctId })),@@ -51,10 +51,7 @@ describe('OverflowLaneOverflowRedirect', () => {await service.handleEventBatch(batch)- expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('events', [- { token: 'token1', distinctId: 'user1' },- { token: 'token1', distinctId: 'user2' },- ])+ expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('events', ['token1:user1', 'token1:user2'])})it('uses correct overflow type', async () => {@@ -65,9 +62,7 @@ describe('OverflowLaneOverflowRedirect', () => {await recordingsService.handleEventBatch([createGroup('token1', 'session1')])- expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('recordings', [- { token: 'token1', distinctId: 'session1' },- ])+ expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('recordings', ['token1:session1'])})it('handles empty batch gracefully', async () => {@@ -88,9 +83,9 @@ describe('OverflowLaneOverflowRedirect', () => {expect(mockRepository.batchRefreshTTL).toHaveBeenCalledTimes(1)expect(mockRepository.batchRefreshTTL).toHaveBeenCalledWith('events', [- { token: 'token1', distinctId: 'user1' },- { token: 'token1', distinctId: 'user2' },- { token: 'token2', distinctId: 'user1' },+ 'token1:user1',+ 'token1:user2',+ 'token2:user1',])})})diff --git a/nodejs/src/ingestion/common/overflow-redirect/overflow-redirect-service.ts b/nodejs/src/ingestion/common/overflow-redirect/overflow-redirect-service.tsindex bdc3c02c5113..640fb5891eb3 100644--- a/nodejs/src/ingestion/common/overflow-redirect/overflow-redirect-service.ts+++ b/nodejs/src/ingestion/common/overflow-redirect/overflow-redirect-service.ts@@ -4,13 +4,9 @@ import { EventHeaders, HealthCheckResult } from '~/types'// don't need to know about the repository layerexport type { OverflowType } from './overflow-redis-repository'-export interface OverflowEventKey {- token: string- distinctId: string-}-export interface OverflowEventGroup {- key: OverflowEventKey+ /** The Kafka partition key capture computed, e.g. `token:distinct_id` or `token:client_ip`. */+ key: string/** Headers of each event for this key in the batch; strategies count their tokens from these. */headersPerEvent: EventHeaders[]firstTimestamp: number@@ -22,7 +18,7 @@ export interface OverflowEventGroup {*/export interface OverflowRedirectService {/**- * Handle a batch of events grouped by token:distinct_id.+ * Handle a batch of events grouped by partition key.** - Main lane: Check if flagged, flag if rate limited, return set of keys to redirect* - Overflow lane: Refresh TTL for all keys, return empty set (no redirects)@@ -30,7 +26,7 @@ export interface OverflowRedirectService {* The overflow keyspace (`OverflowType`) is fixed per service instance and* supplied at construction — a given service belongs to exactly one pipeline.*- * @returns Set of keys (token:distinctId) that should be redirected to overflow+ * @returns Set of partition keys that should be redirected to overflow*/handleEventBatch(batch: OverflowEventGroup[]): Promise<Set<string>>diff --git a/nodejs/src/ingestion/common/overflow-redirect/overflow-redis-repository.ts b/nodejs/src/ingestion/common/overflow-redirect/overflow-redis-repository.tsindex 1e76bd33760a..3c25b086559a 100644--- a/nodejs/src/ingestion/common/overflow-redirect/overflow-redis-repository.ts+++ b/nodejs/src/ingestion/common/overflow-redirect/overflow-redis-repository.ts@@ -13,17 +13,13 @@ export type OverflowType = 'events' | 'recordings' | 'ai' | 'errortracking'const REDIS_KEY_PREFIX = '@posthog/stateful-overflow/'/**- * Generates a Redis key for a given type, token, and distinctId.+ * Generates a Redis key for a given type and partition key. Capture builds+ * partition keys as `token:suffix`, so the stored key stays byte-identical to+ * the old `type:token:distinctId` format and other flag writers (billing+ * limits, session overflow) remain compatible.*/-export function redisKey(type: OverflowType, token: string, distinctId: string): string {- return `${REDIS_KEY_PREFIX}${type}:${token}:${distinctId}`-}--/**- * Generates a member key (token:distinctId) used in result sets.- */-export function memberKey(token: string, distinctId: string): string {- return `${token}:${distinctId}`+export function redisKey(type: OverflowType, key: string): string {+ return `${REDIS_KEY_PREFIX}${type}:${key}`}/**@@ -35,20 +31,20 @@ export function memberKey(token: string, distinctId: string): string {export interface OverflowRedisRepository {/*** Batch check which keys exist in Redis using MGET.- * Returns a Map of memberKey -> isFlagged.+ * Returns a Map of key -> isFlagged.*/- batchCheck(type: OverflowType, keys: { token: string; distinctId: string }[]): Promise<Map<string, boolean>>+ batchCheck(type: OverflowType, keys: string[]): Promise<Map<string, boolean>>/*** Batch flag keys in Redis using pipeline SET with EX (TTL).*/- batchFlag(type: OverflowType, keys: { token: string; distinctId: string }[]): Promise<void>+ batchFlag(type: OverflowType, keys: string[]): Promise<void>/*** Batch refresh TTL for keys using pipeline GETEX.* Only refreshes existing keys, does not create new ones.*/- batchRefreshTTL(type: OverflowType, keys: { token: string; distinctId: string }[]): Promise<void>+ batchRefreshTTL(type: OverflowType, keys: string[]): Promise<void>/*** Health check: PING Redis.@@ -70,10 +66,10 @@ export class RedisOverflowRepository implements OverflowRedisRepository {this.redisTTLSeconds = config.redisTTLSeconds}- async batchCheck(type: OverflowType, keys: { token: string; distinctId: string }[]): Promise<Map<string, boolean>> {+ async batchCheck(type: OverflowType, keys: string[]): Promise<Map<string, boolean>> {const defaultResult = new Map<string, boolean>()for (const key of keys) {- defaultResult.set(memberKey(key.token, key.distinctId), false)+ defaultResult.set(key, false)}if (keys.length === 0) {@@ -86,11 +82,11 @@ export class RedisOverflowRepository implements OverflowRedisRepository {{ type, count: keys.length },async (client: Redis) => {const results = new Map<string, boolean>()- const redisKeys = keys.map((key) => redisKey(type, key.token, key.distinctId))+ const redisKeys = keys.map((key) => redisKey(type, key))const values = await client.mget(...redisKeys)for (let i = 0; i < keys.length; i++) {- results.set(memberKey(keys[i].token, keys[i].distinctId), values[i] !== null)+ results.set(keys[i], values[i] !== null)}overflowRedirectRedisOpsTotal.labels('mget', 'success').inc()@@ -109,7 +105,7 @@ export class RedisOverflowRepository implements OverflowRedisRepository {return result}- async batchFlag(type: OverflowType, keys: { token: string; distinctId: string }[]): Promise<void> {+ async batchFlag(type: OverflowType, keys: string[]): Promise<void> {if (keys.length === 0) {return}@@ -124,7 +120,7 @@ export class RedisOverflowRepository implements OverflowRedisRepository {const pipeline = client.pipeline()for (const key of keys) {- pipeline.set(redisKey(type, key.token, key.distinctId), '1', 'EX', this.redisTTLSeconds)+ pipeline.set(redisKey(type, key), '1', 'EX', this.redisTTLSeconds)}await pipeline.exec()@@ -142,7 +138,7 @@ export class RedisOverflowRepository implements OverflowRedisRepository {}}- async batchRefreshTTL(type: OverflowType, keys: { token: string; distinctId: string }[]): Promise<void> {+ async batchRefreshTTL(type: OverflowType, keys: string[]): Promise<void> {if (keys.length === 0) {return}@@ -157,7 +153,7 @@ export class RedisOverflowRepository implements OverflowRedisRepository {const pipeline = client.pipeline()for (const key of keys) {- pipeline.getex(redisKey(type, key.token, key.distinctId), 'EX', this.redisTTLSeconds)+ pipeline.getex(redisKey(type, key), 'EX', this.redisTTLSeconds)}await pipeline.exec()diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/index.tsindex 43ad2a62d667..9b4b348487fb 100644--- a/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/index.ts@@ -6,11 +6,7 @@ export { createEnrichSurveyPersonPropertiesStep } from './enrich-survey-person-pexport { createParseHeadersStep } from './parse-headers'export { createParseKafkaMessageStep, parseMessageTopHogMetrics } from './parse-kafka-message'export { createOverflowLaneTTLRefreshStep } from './overflow-lane-ttl-refresh-step'-export {- createOnlyCookielessRateLimitToOverflowStep,- createRateLimitToOverflowStep,- createSkipCookielessRateLimitToOverflowStep,-} from './rate-limit-to-overflow-step'+export { createRateLimitToOverflowStep } from './rate-limit-to-overflow-step'export { createResolveTeamStep } from './resolve-team'export { createValidateEventMetadataStep } from './validate-event-metadata'export { createValidateEventPropertiesStep } from './validate-event-properties'diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.tsindex ce66e24ce0dc..fe427d932223 100644--- a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.test.ts@@ -1,14 +1,18 @@import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'import { PipelineResultType } from '~/ingestion/framework/results'import { createTestEventHeaders } from '~/tests/helpers/event-headers'-import { createTestPipelineEvent } from '~/tests/helpers/pipeline-event'-import { createOverflowLaneTTLRefreshStep } from './overflow-lane-ttl-refresh-step'-import { RateLimitToOverflowStepInput } from './rate-limit-to-overflow-step'+import { OverflowLaneTTLRefreshStepInput, createOverflowLaneTTLRefreshStep } from './overflow-lane-ttl-refresh-step'-const createMockEvent = (token: string, distinctId: string, now?: Date): RateLimitToOverflowStepInput => ({- headers: createTestEventHeaders({ token, distinct_id: distinctId, now: now ?? new Date() }),- event: createTestPipelineEvent({ distinct_id: distinctId }),+const createMockEvent = (+ token: string,+ distinctId: string,+ options: { kafkaKey?: string | null; now?: Date } = {}+): OverflowLaneTTLRefreshStepInput => ({+ message: {+ key: options.kafkaKey === null || options.kafkaKey === undefined ? null : Buffer.from(options.kafkaKey),+ },+ headers: createTestEventHeaders({ token, distinct_id: distinctId, now: options.now ?? new Date() }),})const createMockService = (): jest.Mocked<OverflowRedirectService> => ({@@ -33,28 +37,45 @@ describe('createOverflowLaneTTLRefreshStep', () => {})})- it('calls service with deduplicated keys', async () => {+ it('refreshes the message key, the redirect-original-key header, or the headers fallback', async () => {const service = createMockService()const step = createOverflowLaneTTLRefreshStep(service)const baseTime = new Date()const events = [- createMockEvent('token1', 'user1', baseTime),- createMockEvent('token1', 'user1', baseTime), // Duplicate key- createMockEvent('token1', 'user2', baseTime),+ // Redirect with partition locality: the cookieless IP key survives.+ createMockEvent('token1', '$posthog_cookieless', { kafkaKey: 'token1:1.2.3.4', now: baseTime }),+ // Redirect without locality nulls the key but stamps the original into a header.+ {+ message: { key: null },+ headers: createTestEventHeaders({+ token: 'token1',+ distinct_id: '$posthog_cookieless',+ redirect_original_key: 'token1:5.6.7.8',+ now: baseTime,+ }),+ },+ // Routed to overflow at capture (no redirect): fall back to token:headers.distinct_id.+ createMockEvent('token1', 'user1', { kafkaKey: null, now: baseTime }),+ createMockEvent('token1', 'user1', { kafkaKey: null, now: baseTime }), // Duplicate key]await step(events)expect(service.handleEventBatch).toHaveBeenCalledWith([{- key: { token: 'token1', distinctId: 'user1' },- headersPerEvent: [events[0].headers, events[1].headers],+ key: 'token1:1.2.3.4',+ headersPerEvent: [events[0].headers],+ firstTimestamp: baseTime.getTime(),+ },+ {+ key: 'token1:5.6.7.8',+ headersPerEvent: [events[1].headers],firstTimestamp: baseTime.getTime(),},{- key: { token: 'token1', distinctId: 'user2' },- headersPerEvent: [events[2].headers],+ key: 'token1:user1',+ headersPerEvent: [events[2].headers, events[3].headers],firstTimestamp: baseTime.getTime(),},])diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.tsindex 8bb21b2fb418..451c75d4968a 100644--- a/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/overflow-lane-ttl-refresh-step.ts@@ -1,13 +1,17 @@+import { Message } from 'node-rdkafka'+import {OverflowEventGroup,OverflowRedirectService,} from '~/ingestion/common/overflow-redirect/overflow-redirect-service'import { PipelineResult, ok } from '~/ingestion/framework/results'-import { EventHeaders, PipelineEvent } from '~/types'+import { EventHeaders } from '~/types'++import { deriveOverflowKey } from './rate-limit-to-overflow-step'export interface OverflowLaneTTLRefreshStepInput {+ message: Pick<Message, 'key'>headers: EventHeaders- event: PipelineEvent}/**@@ -15,6 +19,9 @@ export interface OverflowLaneTTLRefreshStepInput {* Used in the overflow lane to keep Redis flags alive while events are being processed.* Once events stop coming, the flags expire and future events return to the main lane.*+ * Refreshes the key the main lane flagged, using the same key derivation as the+ * rate limit step (`deriveOverflowKey`) so flag and refresh always agree.+ ** If no service is provided, this step is a no-op (passthrough).*/export function createOverflowLaneTTLRefreshStep<T extends OverflowLaneTTLRefreshStepInput>(@@ -25,29 +32,24 @@ export function createOverflowLaneTTLRefreshStep<T extends OverflowLaneTTLRefresreturn Promise.resolve(inputs.map((input) => ok(input)))}- // Group events by token:distinct_id for batch TTL refresh- const keyStats = new Map<- string,- { token: string; distinctId: string; headersPerEvent: EventHeaders[]; firstTimestamp: number }- >()+ // Group events by partition key for batch TTL refresh+ const keyStats = new Map<string, { headersPerEvent: EventHeaders[]; firstTimestamp: number }>()- for (const { headers, event } of inputs) {- const token = headers.token ?? ''- const distinctId = event.distinct_id ?? ''- const eventKey = `${token}:${distinctId}`+ for (const { message, headers } of inputs) {+ const eventKey = deriveOverflowKey(message, headers)const timestamp = headers.now?.getTime() ?? Date.now()const existing = keyStats.get(eventKey)if (existing) {existing.headersPerEvent.push(headers)} else {- keyStats.set(eventKey, { token, distinctId, headersPerEvent: [headers], firstTimestamp: timestamp })+ keyStats.set(eventKey, { headersPerEvent: [headers], firstTimestamp: timestamp })}}- const groups: OverflowEventGroup[] = Array.from(keyStats.values()).map(- ({ token, distinctId, headersPerEvent, firstTimestamp }) => ({- key: { token, distinctId },+ const groups: OverflowEventGroup[] = Array.from(keyStats.entries()).map(+ ([key, { headersPerEvent, firstTimestamp }]) => ({+ key,headersPerEvent,firstTimestamp,})diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.tsindex bae54138da42..d2a4d440aa8e 100644--- a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.test.ts@@ -3,21 +3,22 @@ import { COOKIELESS_SENTINEL_VALUE } from '~/ingestion/common/cookieless/cookielimport { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'import { PipelineResultType } from '~/ingestion/framework/results'import { createTestEventHeaders } from '~/tests/helpers/event-headers'-import { createTestPipelineEvent } from '~/tests/helpers/pipeline-event'-import {- OnlyCookielessRateLimitToOverflowStepInput,- RateLimitToOverflowStepInput,- SkipCookielessRateLimitToOverflowStepInput,- createOnlyCookielessRateLimitToOverflowStep,- createRateLimitToOverflowStep,- createSkipCookielessRateLimitToOverflowStep,-} from './rate-limit-to-overflow-step'--const createMockEvent = (token: string, distinctId: string, now?: Date): RateLimitToOverflowStepInput => ({- headers: createTestEventHeaders({ token, distinct_id: distinctId, now: now ?? new Date() }),- event: createTestPipelineEvent({ distinct_id: distinctId }),-})+import { RateLimitToOverflowStepInput, createRateLimitToOverflowStep } from './rate-limit-to-overflow-step'++// Mirrors capture: the message key is `token:distinct_id` for regular events and+// `token:client_ip` for cookieless events; spread events have no key.+const createMockEvent = (+ token: string,+ distinctId: string,+ options: { kafkaKeySuffix?: string | null; now?: Date } = {}+): RateLimitToOverflowStepInput => {+ const suffix = options.kafkaKeySuffix === undefined ? distinctId : options.kafkaKeySuffix+ return {+ message: { key: suffix === null ? null : Buffer.from(`${token}:${suffix}`) },+ headers: createTestEventHeaders({ token, distinct_id: distinctId, now: options.now ?? new Date() }),+ }+}const createMockOverflowRedirectService = (keysToRedirect: Set<string> = new Set()@@ -28,439 +29,133 @@ const createMockOverflowRedirectService = (})describe('createRateLimitToOverflowStep', () => {- describe('when service is not provided (overflow disabled)', () => {- it('returns all events as ok', async () => {- const step = createRateLimitToOverflowStep(true, undefined)+ it('returns all events as ok when service is not provided (overflow disabled)', async () => {+ const step = createRateLimitToOverflowStep(true, undefined)- const events = [- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user2'),- createMockEvent('token2', 'user1'),- ]+ const events = [createMockEvent('token1', 'user1'), createMockEvent('token2', 'user2')]- const results = await step(events)+ const results = await step(events)- expect(results).toHaveLength(3)- results.forEach((result) => {- expect(result.type).toBe(PipelineResultType.OK)- })+ expect(results).toHaveLength(2)+ results.forEach((result) => {+ expect(result.type).toBe(PipelineResultType.OK)})})- describe('when service is provided (overflow enabled)', () => {- it('returns ok for events not flagged by service', async () => {- const service = createMockOverflowRedirectService()- const step = createRateLimitToOverflowStep(true, service)-- const events = [createMockEvent('token1', 'user1'), createMockEvent('token1', 'user2')]-- const results = await step(events)-- expect(results).toHaveLength(2)- results.forEach((result) => {- expect(result.type).toBe(PipelineResultType.OK)- })- })-- it('redirects events flagged by service', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createRateLimitToOverflowStep(true, service)-- const events = [createMockEvent('token1', 'user1'), createMockEvent('token1', 'user2')]-- const results = await step(events)-- expect(results).toHaveLength(2)- expect(results[0].type).toBe(PipelineResultType.REDIRECT)- if (results[0].type === PipelineResultType.REDIRECT) {- expect(results[0].reason).toBe('rate_limit_exceeded')- expect(results[0].output).toBe(OVERFLOW_OUTPUT)- }- expect(results[1].type).toBe(PipelineResultType.OK)- })-- it('redirects all events for flagged key', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createRateLimitToOverflowStep(true, service)-- // Create 10 events for the same flagged key- const events = Array.from({ length: 10 }, () => createMockEvent('token1', 'user1'))-- const results = await step(events)-- expect(results).toHaveLength(10)- results.forEach((result) => {- expect(result.type).toBe(PipelineResultType.REDIRECT)- if (result.type === PipelineResultType.REDIRECT) {- expect(result.reason).toBe('rate_limit_exceeded')- expect(result.output).toBe(OVERFLOW_OUTPUT)- }- })- })-- it('calls service with correct batch format', async () => {- const service = createMockOverflowRedirectService()- const step = createRateLimitToOverflowStep(true, service)-- const baseTime = new Date()- const events = [- createMockEvent('token1', 'user1', baseTime),- createMockEvent('token1', 'user1', baseTime),- createMockEvent('token2', 'user2', baseTime),- ]-- await step(events)-- expect(service.handleEventBatch).toHaveBeenCalledWith([- {- key: { token: 'token1', distinctId: 'user1' },- headersPerEvent: [events[0].headers, events[1].headers],- firstTimestamp: baseTime.getTime(),- },- {- key: { token: 'token2', distinctId: 'user2' },- headersPerEvent: [events[2].headers],- firstTimestamp: baseTime.getTime(),- },- ])- })-- it('groups events by token:distinct_id key', async () => {- const service = createMockOverflowRedirectService()- const step = createRateLimitToOverflowStep(true, service)-- const events = [- // 3 events for token1:user1- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user1'),- // 3 events for token1:user2- createMockEvent('token1', 'user2'),- createMockEvent('token1', 'user2'),- createMockEvent('token1', 'user2'),- // 3 events for token2:user1- createMockEvent('token2', 'user1'),- createMockEvent('token2', 'user1'),- createMockEvent('token2', 'user1'),- ]-- const results = await step(events)-- expect(results).toHaveLength(9)- // All should be ok since service returns empty set- results.forEach((result) => {- expect(result.type).toBe(PipelineResultType.OK)- })-- // Service should be called with 3 unique keys- expect(service.handleEventBatch).toHaveBeenCalledTimes(1)- const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]- expect(batches).toHaveLength(3)- })-- it('redirects only keys flagged by service, not others', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createRateLimitToOverflowStep(true, service)-- const events = [- // 5 events for token1:user1 (flagged)- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user1'),- createMockEvent('token1', 'user1'),- // 2 events for token1:user2 (not flagged)- createMockEvent('token1', 'user2'),- createMockEvent('token1', 'user2'),- ]-- const results = await step(events)-- expect(results).toHaveLength(7)-- // First 5 should be redirected (token1:user1 flagged)- for (let i = 0; i < 5; i++) {- expect(results[i].type).toBe(PipelineResultType.REDIRECT)- }-- // Last 2 should be ok (token1:user2 not flagged)- expect(results[5].type).toBe(PipelineResultType.OK)- expect(results[6].type).toBe(PipelineResultType.OK)- })-- it('handles empty token or distinct_id', async () => {- const service = createMockOverflowRedirectService()- const step = createRateLimitToOverflowStep(true, service)-- const events = [createMockEvent('', 'user1'), createMockEvent('token1', ''), createMockEvent('', '')]-- const results = await step(events)-- expect(results).toHaveLength(3)- results.forEach((result) => {- expect(result.type).toBe(PipelineResultType.OK)- })- })-- it('preserves input structure in results', async () => {- const service = createMockOverflowRedirectService()- const step = createRateLimitToOverflowStep(true, service)-- const events = [- {- ...createMockEvent('token1', 'user1'),- additionalField: 'test',- },- ]-- const results = await step(events)-- expect(results).toHaveLength(1)- expect(results[0].type).toBe(PipelineResultType.OK)- if (results[0].type === PipelineResultType.OK) {- expect(results[0].value).toHaveProperty('additionalField', 'test')- }- })-- it('maintains ordering of events in results', async () => {- const service = createMockOverflowRedirectService()- const step = createRateLimitToOverflowStep(true, service)-- const events = [- createMockEvent('token1', 'user1'),- createMockEvent('token2', 'user2'),- createMockEvent('token3', 'user3'),- createMockEvent('token1', 'user1'),- ]-- const results = await step(events)-- expect(results).toHaveLength(4)-- for (let i = 0; i < results.length; i++) {- const result = results[i]- if (result.type === PipelineResultType.OK) {- expect(result.value.headers.token).toBe(events[i].headers.token)- expect(result.value.headers.distinct_id).toBe(events[i].headers.distinct_id)- }- }- })-- it('preserves partition key when preservePartitionLocality is true', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createRateLimitToOverflowStep(true, service)-- const events = [createMockEvent('token1', 'user1')]-- const results = await step(events)-- expect(results).toHaveLength(1)- expect(results[0].type).toBe(PipelineResultType.REDIRECT)- if (results[0].type === PipelineResultType.REDIRECT) {- expect(results[0].preserveKey).toBe(true)- }- })-- it('does not preserve partition key when preservePartitionLocality is false', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createRateLimitToOverflowStep(false, service)-- const events = [createMockEvent('token1', 'user1')]-- const results = await step(events)-- expect(results).toHaveLength(1)- expect(results[0].type).toBe(PipelineResultType.REDIRECT)- if (results[0].type === PipelineResultType.REDIRECT) {- expect(results[0].preserveKey).toBe(false)- }- })-- it('handles distinct_id with colons correctly', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:user:with:colons']))- const step = createRateLimitToOverflowStep(true, service)+ it('calls service with events grouped by the message key split on the token prefix', async () => {+ const service = createMockOverflowRedirectService()+ const step = createRateLimitToOverflowStep(true, service)- const events = [createMockEvent('token1', 'user:with:colons')]+ const baseTime = new Date()+ const events = [+ createMockEvent('token1', 'user1', { now: baseTime }),+ createMockEvent('token1', 'user1', { now: baseTime }),+ createMockEvent('token2', 'user2', { now: baseTime }),+ ]- const results = await step(events)+ await step(events)- expect(results).toHaveLength(1)- expect(results[0].type).toBe(PipelineResultType.REDIRECT)- })+ expect(service.handleEventBatch).toHaveBeenCalledWith([+ {+ key: 'token1:user1',+ headersPerEvent: [events[0].headers, events[1].headers],+ firstTimestamp: baseTime.getTime(),+ },+ {+ key: 'token2:user2',+ headersPerEvent: [events[2].headers],+ firstTimestamp: baseTime.getTime(),+ },+ ])})-})--const createCookielessVariantInput = (- headerDistinctId: string,- eventDistinctId: string,- token: string = 'token1',- now?: Date-): OnlyCookielessRateLimitToOverflowStepInput => ({- headers: createTestEventHeaders({ token, distinct_id: headerDistinctId, now: now ?? new Date() }),- event: createTestPipelineEvent({ distinct_id: eventDistinctId }),-})-// Properties that should hold for both cookieless variants. Each variant defines what-// "out of scope" means (events it ignores), but the resulting behavior is the same:-// pass through as OK, and don't bother calling the service.-describe.each([- {- name: 'createSkipCookielessRateLimitToOverflowStep',- createStep: createSkipCookielessRateLimitToOverflowStep,- outOfScopeInputs: (): OnlyCookielessRateLimitToOverflowStepInput[] => [- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed1'),- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed2', 'token2'),- ],- },- {- name: 'createOnlyCookielessRateLimitToOverflowStep',- createStep: createOnlyCookielessRateLimitToOverflowStep,- outOfScopeInputs: (): OnlyCookielessRateLimitToOverflowStepInput[] => [- createCookielessVariantInput('user1', 'user1'),- createCookielessVariantInput('user2', 'user2', 'token2'),- ],- },-])('$name (shared behavior)', ({ createStep, outOfScopeInputs }) => {- it('returns ok for all events when service is not provided', async () => {- const step = createStep(true, undefined)+ it('redirects events for flagged keys and passes the rest, preserving order', async () => {+ const service = createMockOverflowRedirectService(new Set(['token1:user1']))+ const step = createRateLimitToOverflowStep(true, service)const events = [- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed1'),- createCookielessVariantInput('user1', 'user1'),+ createMockEvent('token1', 'user1'),+ createMockEvent('token1', 'user2'),+ createMockEvent('token1', 'user1'),]const results = await step(events)- results.forEach((result) => expect(result.type).toBe(PipelineResultType.OK))+ expect(results).toHaveLength(3)+ expect(results[0].type).toBe(PipelineResultType.REDIRECT)+ if (results[0].type === PipelineResultType.REDIRECT) {+ expect(results[0].reason).toBe('rate_limit_exceeded')+ expect(results[0].output).toBe(OVERFLOW_OUTPUT)+ }+ expect(results[1].type).toBe(PipelineResultType.OK)+ if (results[1].type === PipelineResultType.OK) {+ expect(results[1].value).toBe(events[1])+ }+ expect(results[2].type).toBe(PipelineResultType.REDIRECT)})- it('does not call service when batch has nothing in scope', async () => {- const service = createMockOverflowRedirectService()- const step = createStep(true, service)-- const results = await step(outOfScopeInputs())+ it('uses the message key verbatim, including colons in the distinct id', async () => {+ const service = createMockOverflowRedirectService(new Set(['token1:user:with:colons']))+ const step = createRateLimitToOverflowStep(true, service)- results.forEach((result) => expect(result.type).toBe(PipelineResultType.OK))- expect(service.handleEventBatch).not.toHaveBeenCalled()- })-})+ const results = await step([createMockEvent('token1', 'user:with:colons')])-describe('createSkipCookielessRateLimitToOverflowStep', () => {- const createHeaderOnlyInput = (- token: string,- distinctId: string,- now?: Date- ): SkipCookielessRateLimitToOverflowStepInput => ({- headers: createTestEventHeaders({ token, distinct_id: distinctId, now: now ?? new Date() }),+ expect(results[0].type).toBe(PipelineResultType.REDIRECT)+ const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]+ expect(batches[0].key).toBe('token1:user:with:colons')})- it('skips cookieless events and keys non-cookieless on headers.distinct_id', async () => {- const service = createMockOverflowRedirectService()- const step = createSkipCookielessRateLimitToOverflowStep(true, service)+ it('aggregates cookieless events by client IP from the message key, not the hashed distinct_id', async () => {+ // Capture keys a cookieless event on token:client_ip while the header stays+ // the sentinel. One IP's stream must share a bucket even though every event+ // gets a fresh hashed distinct_id later, so a flag on the IP key redirects+ // all of that IP's events.+ const service = createMockOverflowRedirectService(new Set(['token1:1.2.3.4']))+ const step = createRateLimitToOverflowStep(true, service)const events = [- createHeaderOnlyInput('token1', 'user1'),- createHeaderOnlyInput('token1', COOKIELESS_SENTINEL_VALUE),- createHeaderOnlyInput('token1', 'user2'),+ createMockEvent('token1', COOKIELESS_SENTINEL_VALUE, { kafkaKeySuffix: '1.2.3.4' }),+ createMockEvent('token1', COOKIELESS_SENTINEL_VALUE, { kafkaKeySuffix: '1.2.3.4' }),+ createMockEvent('token1', COOKIELESS_SENTINEL_VALUE, { kafkaKeySuffix: '5.6.7.8' }),]- await step(events)+ const results = await step(events)- expect(service.handleEventBatch).toHaveBeenCalledWith(- expect.arrayContaining([- expect.objectContaining({- key: { token: 'token1', distinctId: 'user1' },- headersPerEvent: [events[0].headers],- }),- expect.objectContaining({- key: { token: 'token1', distinctId: 'user2' },- headersPerEvent: [events[2].headers],- }),- ])- )const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]expect(batches).toHaveLength(2)- })-- it('passes cookieless events through as ok regardless of redirect set', async () => {- const service = createMockOverflowRedirectService(new Set([`token1:${COOKIELESS_SENTINEL_VALUE}`]))- const step = createSkipCookielessRateLimitToOverflowStep(true, service)-- const events = [createHeaderOnlyInput('token1', COOKIELESS_SENTINEL_VALUE)]-- const results = await step(events)+ expect(batches[0].key).toBe('token1:1.2.3.4')+ expect(batches[0].headersPerEvent).toHaveLength(2)- expect(results).toHaveLength(1)- expect(results[0].type).toBe(PipelineResultType.OK)+ expect(results[0].type).toBe(PipelineResultType.REDIRECT)+ expect(results[1].type).toBe(PipelineResultType.REDIRECT)+ expect(results[2].type).toBe(PipelineResultType.OK)})- it('redirects flagged non-cookieless events while leaving cookieless ok', async () => {+ it('falls back to token:distinct_id from headers for events without a message key', async () => {const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createSkipCookielessRateLimitToOverflowStep(true, service)+ const step = createRateLimitToOverflowStep(true, service)- const events = [- createHeaderOnlyInput('token1', 'user1'),- createHeaderOnlyInput('token1', COOKIELESS_SENTINEL_VALUE),- createHeaderOnlyInput('token1', 'user2'),- ]+ const events = [createMockEvent('token1', 'user1', { kafkaKeySuffix: null })]const results = await step(events)expect(results[0].type).toBe(PipelineResultType.REDIRECT)- expect(results[1].type).toBe(PipelineResultType.OK)- expect(results[2].type).toBe(PipelineResultType.OK)- })-})--describe('createOnlyCookielessRateLimitToOverflowStep', () => {- it('keys cookieless events on event.distinct_id (post-rewrite hashed id)', async () => {- const service = createMockOverflowRedirectService()- const step = createOnlyCookielessRateLimitToOverflowStep(true, service)-- const events = [- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed-a'),- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed-b'),- createCookielessVariantInput('user1', 'user1'),- ]-- await step(events)-const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][0]- expect(batches).toHaveLength(2)- expect(batches).toEqual(- expect.arrayContaining([- expect.objectContaining({ key: { token: 'token1', distinctId: 'hashed-a' } }),- expect.objectContaining({ key: { token: 'token1', distinctId: 'hashed-b' } }),- ])- )+ expect(batches[0].key).toBe('token1:user1')})- it('passes non-cookieless events through as ok regardless of redirect set', async () => {+ it.each([+ [true, true],+ [false, false],+ ])('propagates preservePartitionLocality=%s to the redirect result', async (locality, expected) => {const service = createMockOverflowRedirectService(new Set(['token1:user1']))- const step = createOnlyCookielessRateLimitToOverflowStep(true, service)-- const events = [createCookielessVariantInput('user1', 'user1')]-- const results = await step(events)-- expect(results).toHaveLength(1)- expect(results[0].type).toBe(PipelineResultType.OK)- })+ const step = createRateLimitToOverflowStep(locality, service)- it('redirects flagged cookieless events while leaving non-cookieless ok', async () => {- const service = createMockOverflowRedirectService(new Set(['token1:hashed-a']))- const step = createOnlyCookielessRateLimitToOverflowStep(true, service)-- const events = [- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed-a'),- createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed-b'),- createCookielessVariantInput('user1', 'user1'),- ]-- const results = await step(events)+ const results = await step([createMockEvent('token1', 'user1')])expect(results[0].type).toBe(PipelineResultType.REDIRECT)- expect(results[1].type).toBe(PipelineResultType.OK)- expect(results[2].type).toBe(PipelineResultType.OK)+ if (results[0].type === PipelineResultType.REDIRECT) {+ expect(results[0].preserveKey).toBe(expected)+ }})})diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.tsindex 25bf58a1fe22..7256df4a3e65 100644--- a/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/rate-limit-to-overflow-step.ts@@ -1,156 +1,91 @@+import { Message } from 'node-rdkafka'+import { OVERFLOW_OUTPUT, OverflowOutput } from '~/common/outputs'-import { COOKIELESS_SENTINEL_VALUE } from '~/ingestion/common/cookieless/cookieless-manager'import {OverflowEventGroup,OverflowRedirectService,} from '~/ingestion/common/overflow-redirect/overflow-redirect-service'import { PipelineResult, ok, redirect } from '~/ingestion/framework/results'-import { EventHeaders, PipelineEvent } from '~/types'--// `headers.distinct_id` is set by capture from Kafka headers and is never mutated by the-// pipeline. For cookieless events it stays equal to COOKIELESS_SENTINEL_VALUE even after the-// cookieless step has rewritten `event.distinct_id` to a hashed value — so it's the reliable-// indicator of "this is a cookieless event" at any point in the pipeline.+import { EventHeaders } from '~/types'-interface KeyDerivation {- token: string- distinctId: string+export interface RateLimitToOverflowStepInput {+ message: Pick<Message, 'key'>+ headers: EventHeaders}-async function applyOverflowRedirect<T extends { headers: EventHeaders }>(- inputs: T[],- overflowRedirectService: OverflowRedirectService | undefined,- preservePartitionLocality: boolean,- deriveKey: (input: T) => KeyDerivation | null-): Promise<PipelineResult<T, OverflowOutput>[]> {- if (!overflowRedirectService) {- return inputs.map((input) => ok(input))+function messageKeyString(message: Pick<Message, 'key'>): string | null {+ const rawKey = message.key+ if (rawKey === null || rawKey === undefined) {+ return null}-- const perInputKeys: (string | null)[] = []- const keyStats = new Map<- string,- { token: string; distinctId: string; headersPerEvent: EventHeaders[]; firstTimestamp: number }- >()-- for (const input of inputs) {- const derived = deriveKey(input)- if (!derived) {- perInputKeys.push(null)- continue- }-- const eventKey = `${derived.token}:${derived.distinctId}`- perInputKeys.push(eventKey)-- const timestamp = input.headers.now?.getTime() ?? Date.now()- const existing = keyStats.get(eventKey)- if (existing) {- existing.headersPerEvent.push(input.headers)- } else {- keyStats.set(eventKey, { ...derived, headersPerEvent: [input.headers], firstTimestamp: timestamp })- }- }-- if (keyStats.size === 0) {- return inputs.map((input) => ok(input))- }-- const groups: OverflowEventGroup[] = Array.from(keyStats.values()).map(- ({ token, distinctId, headersPerEvent, firstTimestamp }) => ({- key: { token, distinctId },- headersPerEvent,- firstTimestamp,- })- )- const keysToRedirect = await overflowRedirectService.handleEventBatch(groups)-- return inputs.map((input, index) => {- const eventKey = perInputKeys[index]- if (eventKey !== null && keysToRedirect.has(eventKey)) {- return redirect('rate_limit_exceeded', OVERFLOW_OUTPUT, preservePartitionLocality)- }- return ok(input)- })+ const kafkaKey = typeof rawKey === 'string' ? rawKey : rawKey.toString('utf8')+ return kafkaKey.length === 0 ? null : kafkaKey}/**- * Rate-limits every input regardless of cookieless mode. Keys on `event.distinct_id`.- * Use when there is no cookieless step in the pipeline (e.g. error tracking).+ * The partition key a message concentrates on, shared by the rate limit and+ * TTL refresh steps so both sides of an overflow flag agree on its key: the+ * Kafka message key, or the `redirect-original-key` header a redirect stamps+ * when it drops the key, or `token:distinct_id` from headers — the key capture+ * builds for regular events.*/-export interface RateLimitToOverflowStepInput {- headers: EventHeaders- event: PipelineEvent+export function deriveOverflowKey(message: Pick<Message, 'key'>, headers: EventHeaders): string {+ return (+ messageKeyString(message) ??+ headers.redirect_original_key ??+ `${headers.token ?? ''}:${headers.distinct_id ?? ''}`+ )}+/**+ * Rate-limits events to overflow, keyed on the Kafka message key — the partition+ * key capture computed. Runs before the body is parsed.+ *+ * The message key is the only correct unit for this limit: it is what+ * concentrates traffic on a partition. For regular events it is+ * `token:distinct_id`; for cookieless events it is `token:client_ip`, so one+ * IP's cookieless stream is budgeted as a single key even though every event+ * gets a fresh hashed distinct_id later in the pipeline.+ */export function createRateLimitToOverflowStep<T extends RateLimitToOverflowStepInput>(preservePartitionLocality: boolean,overflowRedirectService?: OverflowRedirectService) {return async function rateLimitToOverflowStep(inputs: T[]): Promise<PipelineResult<T, OverflowOutput>[]> {- return applyOverflowRedirect(inputs, overflowRedirectService, preservePartitionLocality, (input) => ({- token: input.headers.token ?? '',- distinctId: input.event.distinct_id ?? '',- }))- }-}--/**- * Rate-limits only non-cookieless events using `headers.distinct_id`. Designed to run- * before the body is parsed — it does not require `event`. Cookieless events- * (`headers.distinct_id === COOKIELESS_SENTINEL_VALUE`) pass through untouched, to be- * handled by `createOnlyCookielessRateLimitToOverflowStep` after the cookieless step- * has assigned them a real hashed distinct_id.- */-export interface SkipCookielessRateLimitToOverflowStepInput {- headers: EventHeaders-}+ if (!overflowRedirectService || inputs.length === 0) {+ return inputs.map((input) => ok(input))+ }-export function createSkipCookielessRateLimitToOverflowStep<T extends SkipCookielessRateLimitToOverflowStepInput>(- preservePartitionLocality: boolean,- overflowRedirectService?: OverflowRedirectService-) {- return async function skipCookielessRateLimitToOverflowStep(- inputs: T[]- ): Promise<PipelineResult<T, OverflowOutput>[]> {- return applyOverflowRedirect(inputs, overflowRedirectService, preservePartitionLocality, (input) => {- if (input.headers.distinct_id === COOKIELESS_SENTINEL_VALUE) {- return null- }- return {- token: input.headers.token ?? '',- distinctId: input.headers.distinct_id ?? '',- }- })- }-}+ const perInputKeys: string[] = []+ const keyStats = new Map<string, { headersPerEvent: EventHeaders[]; firstTimestamp: number }>()-/**- * Rate-limits only cookieless events using `event.distinct_id` (the hashed value- * assigned by the cookieless step). Must run after `createApplyCookielessProcessingStep`,- * not before. Pairs with `createSkipCookielessRateLimitToOverflowStep` to cover the full- * traffic without parsing the body for non-cookieless events that are about to be redirected.- */-export interface OnlyCookielessRateLimitToOverflowStepInput {- headers: EventHeaders- event: PipelineEvent-}+ for (const input of inputs) {+ const eventKey = deriveOverflowKey(input.message, input.headers)+ perInputKeys.push(eventKey)-export function createOnlyCookielessRateLimitToOverflowStep<T extends OnlyCookielessRateLimitToOverflowStepInput>(- preservePartitionLocality: boolean,- overflowRedirectService?: OverflowRedirectService-) {- return async function onlyCookielessRateLimitToOverflowStep(- inputs: T[]- ): Promise<PipelineResult<T, OverflowOutput>[]> {- return applyOverflowRedirect(inputs, overflowRedirectService, preservePartitionLocality, (input) => {- if (input.headers.distinct_id !== COOKIELESS_SENTINEL_VALUE) {- return null+ const timestamp = input.headers.now?.getTime() ?? Date.now()+ const existing = keyStats.get(eventKey)+ if (existing) {+ existing.headersPerEvent.push(input.headers)+ } else {+ keyStats.set(eventKey, { headersPerEvent: [input.headers], firstTimestamp: timestamp })}- return {- token: input.headers.token ?? '',- distinctId: input.event.distinct_id ?? '',+ }++ const groups: OverflowEventGroup[] = Array.from(keyStats.entries()).map(+ ([key, { headersPerEvent, firstTimestamp }]) => ({+ key,+ headersPerEvent,+ firstTimestamp,+ })+ )+ const keysToRedirect = await overflowRedirectService.handleEventBatch(groups)++ return inputs.map((input, index) => {+ if (keysToRedirect.has(perInputKeys[index])) {+ return redirect('rate_limit_exceeded', OVERFLOW_OUTPUT, preservePartitionLocality)}+ return ok(input)})}}diff --git a/nodejs/src/ingestion/framework/result-handling-helpers.test.ts b/nodejs/src/ingestion/framework/result-handling-helpers.test.tsindex 47d3145b041b..78bcb152e9b0 100644--- a/nodejs/src/ingestion/framework/result-handling-helpers.test.ts+++ b/nodejs/src/ingestion/framework/result-handling-helpers.test.ts@@ -221,7 +221,9 @@ describe('redirectMessageToOutput', () => {expect(mockOutputs.produce).toHaveBeenCalledWith(TEST_REDIRECT, {value: mockMessage.value,key: null,- headers: expect.any(Object),+ // The dropped partition key rides along in a header so the overflow+ // lane can still refresh the flag that routed the event there.+ headers: expect.objectContaining({ 'redirect-original-key': 'test-key' }),})})diff --git a/nodejs/src/ingestion/framework/result-handling-helpers.ts b/nodejs/src/ingestion/framework/result-handling-helpers.tsindex 7750d49280db..e603b22319d2 100644--- a/nodejs/src/ingestion/framework/result-handling-helpers.ts+++ b/nodejs/src/ingestion/framework/result-handling-helpers.ts@@ -133,10 +133,16 @@ export async function redirectMessageToOutput<O extends string>(const step = stepName || 'unknown'try {- const headers = copyAndExtendHeaders(originalMessage, {+ const extraHeaders: Record<string, string> = {'redirect-step': step,'redirect-timestamp': new Date().toISOString(),- })+ }+ // Dropping the key spreads the redirected stream across partitions;+ // keep the original key recoverable for consumers of the stream.+ if (!preserveKey && originalMessage.key) {+ extraHeaders['redirect-original-key'] = originalMessage.key.toString()+ }+ const headers = copyAndExtendHeaders(originalMessage, extraHeaders)const key = preserveKey ? (originalMessage.key ?? null) : nullconst producePromise = outputs.produce(output, {diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.tsindex 60824c61277a..5b44f30a4778 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts@@ -25,9 +25,8 @@ import {createApplyCookielessProcessingStep,createApplyEventRestrictionsStep,createApplyPersonProcessingRestrictionsStep,- createOnlyCookielessRateLimitToOverflowStep,createOverflowLaneTTLRefreshStep,- createSkipCookielessRateLimitToOverflowStep,+ createRateLimitToOverflowStep,createValidateEventMetadataStep,createValidateEventPropertiesStep,createValidateEventSchemaStep,@@ -167,9 +166,10 @@ export function createAiIngestionPipeline<pipelineWritesPersons: false,}))- // Rate-limit non-cookieless events to overflow before parsing the body.- // Cookieless events pass through and are handled post-cookieless below.- .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))+ // Rate-limit events to overflow before parsing the body, keyed on the+ // Kafka message key — the partition key capture computed. Cookieless+ // events count under token:client_ip.+ .pipeChunk(createRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService)).parseMessage().resolveTeam().pipe(createValidateHistoricalMigrationStep())@@ -186,7 +186,6 @@ export function createAiIngestionPipeline<// final distinct_id, so it must run after this batch step..gather().pipeChunk(createApplyCookielessProcessingStep(cookielessManager))- .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService)).pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))// Read-only batch person fetch (no person writes). The personhog// client retries transient gRPC errors for ~150ms; this outerdiff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex c00026e23d1f..598fa56ec9bb 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -26,7 +26,7 @@ import {import {createApplyEventRestrictionsStep,createEnrichSurveyPersonPropertiesStep,- createSkipCookielessRateLimitToOverflowStep,+ createRateLimitToOverflowStep,createValidateHistoricalMigrationStep,} from '~/ingestion/common/steps/event-preprocessing'import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'@@ -167,8 +167,6 @@ export function createJoinedIngestionPipeline<eventSchemaEnforcementManager,eventSchemaEnforcementEnabled,cookielessManager,- preservePartitionLocality,- overflowRedirectService,overflowLaneTTLRefreshService,featureFlagCalledDedupService,personsPrefetchEnabled,@@ -222,11 +220,11 @@ export function createJoinedIngestionPipeline<pipelineWritesPersons: true,}))- // Rate-limit non-cookieless events to overflow before parsing the body.- // Cookieless events (headers.distinct_id === sentinel) pass through and are- // handled by the matching only-cookieless step in post-team, which keys on- // the hashed distinct_id assigned by the cookieless step.- .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))+ // Rate-limit events to overflow before parsing the body, keyed on the+ // Kafka message key — the partition key capture computed. Cookieless+ // events count under token:client_ip, so one IP's cookieless stream+ // is budgeted as a single partition key.+ .pipeChunk(createRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Warm the team cache for the chunk's tokens in one batched load while message// bodies parse, so the per-event lookups in resolveTeam hit cache or coalesce// onto the in-flight load instead of paying a serial load per token.diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.tsindex 7bf3892bdaa3..02fe4439f74e 100644--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts@@ -16,7 +16,6 @@ import {createApplyCookielessProcessingStep,createApplyPersonProcessingRestrictionsStep,createDedupeFeatureFlagCalledStep,- createOnlyCookielessRateLimitToOverflowStep,createOverflowLaneTTLRefreshStep,createValidateEventMetadataStep,createValidateEventPropertiesStep,@@ -47,8 +46,6 @@ export interface PostTeamPreprocessingSubpipelineConfig {eventSchemaEnforcementManager: EventSchemaEnforcementManagereventSchemaEnforcementEnabled: booleancookielessManager: CookielessManager- preservePartitionLocality: boolean- overflowRedirectService?: OverflowRedirectServiceoverflowLaneTTLRefreshService?: OverflowRedirectServicefeatureFlagCalledDedupService?: FeatureFlagCalledDedupServicepersonsPrefetchEnabled: boolean@@ -75,8 +72,6 @@ export function createPostTeamPreprocessingSubpipeline<eventSchemaEnforcementManager,eventSchemaEnforcementEnabled,cookielessManager,- preservePartitionLocality,- overflowRedirectService,overflowLaneTTLRefreshService,featureFlagCalledDedupService,personsPrefetchEnabled,@@ -115,10 +110,6 @@ export function createPostTeamPreprocessingSubpipeline<// Any steps that depend on the final distinct ID must run after this step..gather().pipeChunk(createApplyCookielessProcessingStep(cookielessManager))- // Rate-limit only cookieless events using the hashed distinct_id assigned by the- // cookieless step. Non-cookieless events were rate-limited pre-parse in the joined- // pipeline via createSkipCookielessRateLimitToOverflowStep.- .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Refresh TTLs for overflow lane events (keeps Redis flags alive).pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))// Drop redundant $feature_flag_called events (keep-first Redis claim).diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.tsindex 632117c3bc71..f11e4810684e 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts@@ -143,7 +143,7 @@ describe('ErrorTrackingPipeline', () => {partition: 0,offset: 0,size: 0,- key: Buffer.from(distinctId),+ key: Buffer.from(`${token}:${distinctId}`),} as Message}@@ -988,21 +988,9 @@ describe('ErrorTrackingPipeline', () => {expect(producedEvents[0].distinct_id).toBe('hashed-distinct-id')})- it('passes cookieless events through skip-cookieless rate limit even when service flags the sentinel', async () => {- // The skip-cookieless step keys on headers.distinct_id. For cookieless events- // the header is the sentinel, and the step explicitly passes them through —- // they are handled by the only-cookieless step post-rewrite. This test proves- // the sentinel-keyed flag does not redirect.- const person = createTestPerson({ distinct_id: 'hashed-distinct-id' })- mockPersonRepository.fetchPersonsByDistinctIds.mockResolvedValue([person])- mockCymbalClient.processExceptions.mockResolvedValue([createCymbalResponse()])-- mockCookielessManager.doBatch.mockImplementationOnce((events: any[]) =>- Promise.resolve(- events.map((e) => ok({ ...e, event: { ...e.event, distinct_id: 'hashed-distinct-id' } }))- )- )-+ it('redirects cookieless events to overflow when their message key is flagged', async () => {+ // The rate limit step keys on the Kafka message key, so a flagged+ // cookieless event goes to overflow before Cymbal runs.const flagging = createMockOverflowRedirectService(new Set([`test-token-123:${COOKIELESS_SENTINEL_VALUE}`]))const configWithOverflow: ErrorTrackingPipelineConfig = {...pipelineConfig,@@ -1014,34 +1002,6 @@ describe('ErrorTrackingPipeline', () => {const pipeline = createErrorTrackingPipeline(configWithOverflow)await runErrorTrackingPipeline(pipeline, [message])- expect(getOverflowMessages()).toHaveLength(0)- expect(mockCymbalClient.processExceptions).toHaveBeenCalledTimes(1)- const producedEvents = getProducedEvents()- expect(producedEvents).toHaveLength(1)- expect(producedEvents[0].distinct_id).toBe('hashed-distinct-id')- })-- it('redirects cookieless events to overflow via only-cookieless rate limit on the hashed distinct_id', async () => {- // The only-cookieless step keys on event.distinct_id (the value after the- // cookieless step rewrites it). This test proves a flag on the hashed key- // sends the cookieless event to overflow rather than Cymbal.- mockCookielessManager.doBatch.mockImplementationOnce((events: any[]) =>- Promise.resolve(- events.map((e) => ok({ ...e, event: { ...e.event, distinct_id: 'hashed-distinct-id' } }))- )- )-- const flagging = createMockOverflowRedirectService(new Set(['test-token-123:hashed-distinct-id']))- const configWithOverflow: ErrorTrackingPipelineConfig = {- ...pipelineConfig,- overflowMode: 'redirect',- overflowRedirectService: flagging,- }-- const message = createKafkaMessage({ distinctId: COOKIELESS_SENTINEL_VALUE })- const pipeline = createErrorTrackingPipeline(configWithOverflow)- await runErrorTrackingPipeline(pipeline, [message])-expect(mockCymbalClient.processExceptions).not.toHaveBeenCalled()expect(getProducedEvents()).toHaveLength(0)expect(getOverflowMessages()).toHaveLength(1)diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.tsindex faa04bc8f9a7..3c1565db4a8a 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts@@ -22,9 +22,8 @@ import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/ovimport {createApplyCookielessProcessingStep,createApplyEventRestrictionsStep,- createOnlyCookielessRateLimitToOverflowStep,createOverflowLaneTTLRefreshStep,- createSkipCookielessRateLimitToOverflowStep,+ createRateLimitToOverflowStep,} from '~/ingestion/common/steps/event-preprocessing'import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'@@ -168,11 +167,10 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)pipelineWritesPersons: false,}))- // Rate-limit non-cookieless events to overflow before parsing the body.- // Cookieless events (headers.distinct_id === sentinel) pass through and are- // handled post-cookieless by createOnlyCookielessRateLimitToOverflowStep, which- // keys on the hashed distinct_id assigned by the cookieless step.- .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))+ // Rate-limit events to overflow before parsing the body, keyed on the+ // Kafka message key — the partition key capture computed. Cookieless+ // events count under token:client_ip.+ .pipeChunk(createRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService)).parseMessage().resolveTeam()// Carry the Kafka message byte size through for Cymbal batch chunking.@@ -182,10 +180,6 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)// the final distinct ID..gather().pipeChunk(createApplyCookielessProcessingStep(cookielessManager))- // Rate-limit only cookieless events to overflow now that they- // have a real hashed distinct_id. Non-cookieless events were- // rate-limited pre-parse above.- .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Refresh TTLs for overflow lane events (keeps Redis flags alive).pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex d52978494f16..bdd7dc4a1062 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -875,6 +875,8 @@ export interface EventHeaders {force_disable_person_processing: booleanhistorical_migration: booleanskip_heatmap_processing: boolean+ /** The Kafka partition key a redirect dropped, so the overflow lane can refresh its overflow flag. */+ redirect_original_key?: string}export interface IncomingEvent {diff --git a/nodejs/tests/ingestion/common/overflow-redirect/overflow-redis-repository.integration.test.ts b/nodejs/tests/ingestion/common/overflow-redirect/overflow-redis-repository.integration.test.tsindex 2d1c432ccdf1..6a8645dfb74b 100644--- a/nodejs/tests/ingestion/common/overflow-redirect/overflow-redis-repository.integration.test.ts+++ b/nodejs/tests/ingestion/common/overflow-redirect/overflow-redis-repository.integration.test.ts@@ -8,8 +8,7 @@ describe('RedisOverflowRepository (integration)', () => {let repository: RedisOverflowRepositorylet testToken: string- const key = (distinctId: string) => ({ token: testToken, distinctId })- const memberKey = (distinctId: string) => `${testToken}:${distinctId}`+ const key = (distinctId: string) => `${testToken}:${distinctId}`beforeEach(async () => {infra = await createIngestionTestInfra()@@ -23,7 +22,7 @@ describe('RedisOverflowRepository (integration)', () => {afterEach(async () => {const redis = await infra.redisPool.acquire()- const prefix = redisKey('events', testToken, '').replace('events:', '')+ const prefix = redisKey('events', `${testToken}:`).replace('events:', '')const keys = await redis.keys(`${prefix}*`)if (keys.length) {await redis.del(...keys)@@ -36,29 +35,29 @@ describe('RedisOverflowRepository (integration)', () => {it('returns false for keys that do not exist', async () => {const result = await repository.batchCheck('events', [key('user1')])- expect(result.get(memberKey('user1'))).toBe(false)+ expect(result.get(key('user1'))).toBe(false)})it('returns true for keys that exist', async () => {const redis = await infra.redisPool.acquire()- await redis.set(redisKey('events', testToken, 'user1'), '1')+ await redis.set(redisKey('events', key('user1')), '1')await infra.redisPool.release(redis)const result = await repository.batchCheck('events', [key('user1')])- expect(result.get(memberKey('user1'))).toBe(true)+ expect(result.get(key('user1'))).toBe(true)})it('handles mixed existing and non-existing keys', async () => {const redis = await infra.redisPool.acquire()- await redis.set(redisKey('events', testToken, 'user2'), '1')+ await redis.set(redisKey('events', key('user2')), '1')await infra.redisPool.release(redis)const result = await repository.batchCheck('events', [key('user1'), key('user2'), key('user3')])- expect(result.get(memberKey('user1'))).toBe(false)- expect(result.get(memberKey('user2'))).toBe(true)- expect(result.get(memberKey('user3'))).toBe(false)+ expect(result.get(key('user1'))).toBe(false)+ expect(result.get(key('user2'))).toBe(true)+ expect(result.get(key('user3'))).toBe(false)})it('returns empty map for empty input', async () => {@@ -73,8 +72,8 @@ describe('RedisOverflowRepository (integration)', () => {await repository.batchFlag('events', [key('user1')])const redis = await infra.redisPool.acquire()- const value = await redis.get(redisKey('events', testToken, 'user1'))- const ttl = await redis.ttl(redisKey('events', testToken, 'user1'))+ const value = await redis.get(redisKey('events', key('user1')))+ const ttl = await redis.ttl(redisKey('events', key('user1')))await infra.redisPool.release(redis)expect(value).toBe('1')@@ -86,8 +85,8 @@ describe('RedisOverflowRepository (integration)', () => {await repository.batchFlag('events', [key('user1'), key('user2')])const redis = await infra.redisPool.acquire()- const val1 = await redis.get(redisKey('events', testToken, 'user1'))- const val2 = await redis.get(redisKey('events', testToken, 'user2'))+ const val1 = await redis.get(redisKey('events', key('user1')))+ const val2 = await redis.get(redisKey('events', key('user2')))await infra.redisPool.release(redis)expect(val1).toBe('1')@@ -104,14 +103,14 @@ describe('RedisOverflowRepository (integration)', () => {it('refreshes TTL for existing keys', async () => {const redis = await infra.redisPool.acquire()// Set key with short TTL- await redis.set(redisKey('events', testToken, 'user1'), '1', 'EX', 10)+ await redis.set(redisKey('events', key('user1')), '1', 'EX', 10)await infra.redisPool.release(redis)// Refresh TTL to 300await repository.batchRefreshTTL('events', [key('user1')])const redis2 = await infra.redisPool.acquire()- const ttl = await redis2.ttl(redisKey('events', testToken, 'user1'))+ const ttl = await redis2.ttl(redisKey('events', key('user1')))await infra.redisPool.release(redis2)// TTL should now be close to 300 (the configured value)@@ -123,7 +122,7 @@ describe('RedisOverflowRepository (integration)', () => {await repository.batchRefreshTTL('events', [key('nonexistent')])const redis = await infra.redisPool.acquire()- const exists = await redis.exists(redisKey('events', testToken, 'nonexistent'))+ const exists = await redis.exists(redisKey('events', key('nonexistent')))await infra.redisPool.release(redis)expect(exists).toBe(0)@@ -131,14 +130,14 @@ describe('RedisOverflowRepository (integration)', () => {it('handles mixed existing and non-existing keys', async () => {const redis = await infra.redisPool.acquire()- await redis.set(redisKey('events', testToken, 'existing'), '1', 'EX', 10)+ await redis.set(redisKey('events', key('existing')), '1', 'EX', 10)await infra.redisPool.release(redis)await repository.batchRefreshTTL('events', [key('existing'), key('nonexistent')])const redis2 = await infra.redisPool.acquire()- const existingTTL = await redis2.ttl(redisKey('events', testToken, 'existing'))- const nonexistentExists = await redis2.exists(redisKey('events', testToken, 'nonexistent'))+ const existingTTL = await redis2.ttl(redisKey('events', key('existing')))+ const nonexistentExists = await redis2.exists(redisKey('events', key('nonexistent')))await infra.redisPool.release(redis2)expect(existingTTL).toBeGreaterThan(200)@@ -157,9 +156,9 @@ describe('RedisOverflowRepository (integration)', () => {const result = await repository.batchCheck('events', [key('user1'), key('user2'), key('user3')])- expect(result.get(memberKey('user1'))).toBe(true)- expect(result.get(memberKey('user2'))).toBe(true)- expect(result.get(memberKey('user3'))).toBe(false)+ expect(result.get(key('user1'))).toBe(true)+ expect(result.get(key('user2'))).toBe(true)+ expect(result.get(key('user3'))).toBe(false)})})@@ -170,8 +169,8 @@ describe('RedisOverflowRepository (integration)', () => {const eventsResult = await repository.batchCheck('events', [key('user1')])const recordingsResult = await repository.batchCheck('recordings', [key('user1')])- expect(eventsResult.get(memberKey('user1'))).toBe(true)- expect(recordingsResult.get(memberKey('user1'))).toBe(false)+ expect(eventsResult.get(key('user1'))).toBe(true)+ expect(recordingsResult.get(key('user1'))).toBe(false)})})