: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
perf(ingestion): rate-limit non-cookieless events to overflow before parse (#60052)
Paweł Ledwoń29eb9a504890
diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snapindex 544e56ac0eda..44258abd69c9 100644--- a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap+++ b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap@@ -137,7 +137,7 @@ 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": "rateLimitToOverflowStep",+ "redirect-step": "skipCookielessRateLimitToOverflowStep","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/analytics/index.ts b/nodejs/src/ingestion/analytics/index.tsindex 1528ba3fc391..f52591eb9c52 100644--- a/nodejs/src/ingestion/analytics/index.ts+++ b/nodejs/src/ingestion/analytics/index.ts@@ -24,11 +24,6 @@ export {type PostTeamPreprocessingSubpipelineInput,} from './post-team-preprocessing-subpipeline'-export {- createPreTeamPreprocessingSubpipeline,- type PreTeamPreprocessingSubpipelineConfig,-} from './pre-team-preprocessing-subpipeline'-export {createJoinedIngestionPipeline,type JoinedIngestionPipelineConfig,diff --git a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.tsindex f3b3a3355ccb..05af847cf0b5 100644--- a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts@@ -17,6 +17,17 @@ import {createFlushEventFiltersBatchAppMetricsStep,} from '../common/steps/event-filters-steps'import { CookielessManager } from '../cookieless/cookieless-manager'+import {+ createApplyEventRestrictionsStep,+ createDropExceptionEventsStep,+ createEnrichSurveyPersonPropertiesStep,+ createParseHeadersStep,+ createParseKafkaMessageStep,+ createResolveTeamStep,+ createSkipCookielessRateLimitToOverflowStep,+ createValidateAiEventTokensStep,+ createValidateHistoricalMigrationStep,+} from '../event-preprocessing'import { EventPipelineRunnerOptions } from '../event-processing/event-pipeline-options'import { createFlushBatchStoresStep } from '../event-processing/flush-batch-stores-step'import { SplitAiEventsStepConfig } from '../event-processing/split-ai-events-step'@@ -43,7 +54,6 @@ import {PostTeamPreprocessingSubpipelineConfig,createPostTeamPreprocessingSubpipeline,} from './post-team-preprocessing-subpipeline'-import { createPreTeamPreprocessingSubpipeline } from './pre-team-preprocessing-subpipeline'export interface JoinedIngestionPipelineConfig {eventSchemaEnforcementEnabled: boolean@@ -200,13 +210,35 @@ export function createJoinedIngestionPipeline<batch.messageAware((b) =>b+ // Header-only steps: parse Kafka headers and apply token-level restrictions.+ // Cheap; runs per-event before we touch the body..sequentially((b) =>- createPreTeamPreprocessingSubpipeline(b, {- teamManager,- eventIngestionRestrictionManager,- overflowEnabled,+ b.pipe(createParseHeadersStep()).pipe(+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {+ overflowEnabled,+ preservePartitionLocality,+ })+ )+ )+ // 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.+ .pipeBatch(+ createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality,- })+ overflowRedirectService+ )+ )+ // Body parse and team resolution. Anything that needs the parsed event lives here.+ .sequentially((b) =>+ b+ .pipe(createParseKafkaMessageStep())+ .pipe(createDropExceptionEventsStep())+ .pipe(createResolveTeamStep(teamManager))+ .pipe(createValidateHistoricalMigrationStep())+ .pipe(createValidateAiEventTokensStep())+ .pipe(createEnrichSurveyPersonPropertiesStep())).filterMap(addTeamToContext, (b) =>bdiff --git a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.tsindex 41b991aac37d..2dd43fe157a6 100644--- a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts@@ -16,8 +16,8 @@ import { CookielessManager } from '../cookieless/cookieless-manager'import {createApplyCookielessProcessingStep,createApplyPersonProcessingRestrictionsStep,+ createOnlyCookielessRateLimitToOverflowStep,createOverflowLaneTTLRefreshStep,- createRateLimitToOverflowStep,createValidateEventMetadataStep,createValidateEventPropertiesStep,createValidateEventSchemaStep,@@ -90,8 +90,10 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr// Any steps that depend on the final distinct ID must run after this step..gather().pipeBatch(createApplyCookielessProcessingStep(cookielessManager))- // Rate limit to overflow must run after cookieless, as it uses the final distinct ID- .pipeBatch(createRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))+ // 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.+ .pipeBatch(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Refresh TTLs for overflow lane events (keeps Redis flags alive).pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))// Prefetch must run after cookieless, as cookieless changes distinct IDsdiff --git a/nodejs/src/ingestion/analytics/pre-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/pre-team-preprocessing-subpipeline.tsdeleted file mode 100644index 77a53d938823..000000000000--- a/nodejs/src/ingestion/analytics/pre-team-preprocessing-subpipeline.ts+++ /dev/null@@ -1,58 +0,0 @@-import { Message } from 'node-rdkafka'--import { PluginEvent } from '~/plugin-scaffold'-import { TeamManager } from '~/utils/team-manager'--import { EventHeaders, Team } from '../../types'-import { EventIngestionRestrictionManager } from '../../utils/event-ingestion-restrictions'-import {- createApplyEventRestrictionsStep,- createDropExceptionEventsStep,- createEnrichSurveyPersonPropertiesStep,- createParseHeadersStep,- createParseKafkaMessageStep,- createResolveTeamStep,- createValidateAiEventTokensStep,- createValidateHistoricalMigrationStep,-} from '../event-preprocessing'-import { StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'--export interface PreTeamPreprocessingSubpipelineInput {- message: Message-}--export interface PreTeamPreprocessingSubpipelineOutput {- message: Message- headers: EventHeaders- event: PluginEvent- team: Team-}--export interface PreTeamPreprocessingSubpipelineConfig {- teamManager: TeamManager- eventIngestionRestrictionManager: EventIngestionRestrictionManager- overflowEnabled: boolean- preservePartitionLocality: boolean-}--export function createPreTeamPreprocessingSubpipeline<TInput extends PreTeamPreprocessingSubpipelineInput, TContext>(- builder: StartPipelineBuilder<TInput, TContext>,- config: PreTeamPreprocessingSubpipelineConfig-) {- const { teamManager, eventIngestionRestrictionManager, overflowEnabled, preservePartitionLocality } = config-- return builder- .pipe(createParseHeadersStep())- .pipe(- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {- overflowEnabled,- preservePartitionLocality,- })- )- .pipe(createParseKafkaMessageStep())- .pipe(createDropExceptionEventsStep())- .pipe(createResolveTeamStep(teamManager))- .pipe(createValidateHistoricalMigrationStep())- .pipe(createValidateAiEventTokensStep())- .pipe(createEnrichSurveyPersonPropertiesStep())-}diff --git a/nodejs/src/ingestion/event-preprocessing/index.ts b/nodejs/src/ingestion/event-preprocessing/index.tsindex cc79901b2daf..8b5c29b0aeac 100644--- a/nodejs/src/ingestion/event-preprocessing/index.ts+++ b/nodejs/src/ingestion/event-preprocessing/index.ts@@ -6,7 +6,11 @@ export { createEnrichSurveyPersonPropertiesStep } from './enrich-survey-person-pexport { createParseHeadersStep } from './parse-headers'export { createParseKafkaMessageStep } from './parse-kafka-message'export { createOverflowLaneTTLRefreshStep } from './overflow-lane-ttl-refresh-step'-export { createRateLimitToOverflowStep } from './rate-limit-to-overflow-step'+export {+ createOnlyCookielessRateLimitToOverflowStep,+ createRateLimitToOverflowStep,+ createSkipCookielessRateLimitToOverflowStep,+} from './rate-limit-to-overflow-step'export { createResolveTeamStep } from './resolve-team'export { createValidateAiEventTokensStep } from './validate-ai-event-tokens'export { createValidateEventMetadataStep } from './validate-event-metadata'diff --git a/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.test.ts b/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.test.tsindex c5d9b6cd2d23..894f8ab2e71c 100644--- a/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.test.ts+++ b/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.test.ts@@ -1,9 +1,17 @@import { createTestEventHeaders } from '../../../tests/helpers/event-headers'import { createTestPipelineEvent } from '../../../tests/helpers/pipeline-event'import { OVERFLOW_OUTPUT } from '../common/outputs'+import { COOKIELESS_SENTINEL_VALUE } from '../cookieless/cookieless-manager'import { PipelineResultType } from '../pipelines/results'import { OverflowRedirectService } from '../utils/overflow-redirect/overflow-redirect-service'-import { RateLimitToOverflowStepInput, createRateLimitToOverflowStep } from './rate-limit-to-overflow-step'+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() }),@@ -272,3 +280,173 @@ describe('createRateLimitToOverflowStep', () => {})})})++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)++ const events = [+ createCookielessVariantInput(COOKIELESS_SENTINEL_VALUE, 'hashed1'),+ createCookielessVariantInput('user1', 'user1'),+ ]++ const results = await step(events)++ results.forEach((result) => expect(result.type).toBe(PipelineResultType.OK))+ })++ 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())++ results.forEach((result) => expect(result.type).toBe(PipelineResultType.OK))+ expect(service.handleEventBatch).not.toHaveBeenCalled()+ })+})++describe('createSkipCookielessRateLimitToOverflowStep', () => {+ const createHeaderOnlyInput = (+ token: string,+ distinctId: string,+ now?: Date+ ): SkipCookielessRateLimitToOverflowStepInput => ({+ headers: createTestEventHeaders({ token, distinct_id: distinctId, now: now ?? new Date() }),+ })++ it('skips cookieless events and keys non-cookieless on headers.distinct_id', async () => {+ const service = createMockOverflowRedirectService()+ const step = createSkipCookielessRateLimitToOverflowStep(true, service)++ const events = [+ createHeaderOnlyInput('token1', 'user1'),+ createHeaderOnlyInput('token1', COOKIELESS_SENTINEL_VALUE),+ createHeaderOnlyInput('token1', 'user2'),+ ]++ await step(events)++ expect(service.handleEventBatch).toHaveBeenCalledWith(+ 'events',+ expect.arrayContaining([+ expect.objectContaining({ key: { token: 'token1', distinctId: 'user1' }, eventCount: 1 }),+ expect.objectContaining({ key: { token: 'token1', distinctId: 'user2' }, eventCount: 1 }),+ ])+ )+ const batches = (service.handleEventBatch as jest.Mock).mock.calls[0][1]+ 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(results).toHaveLength(1)+ expect(results[0].type).toBe(PipelineResultType.OK)+ })++ it('redirects flagged non-cookieless events while leaving cookieless ok', async () => {+ const service = createMockOverflowRedirectService(new Set(['token1:user1']))+ const step = createSkipCookielessRateLimitToOverflowStep(true, service)++ const events = [+ createHeaderOnlyInput('token1', 'user1'),+ createHeaderOnlyInput('token1', COOKIELESS_SENTINEL_VALUE),+ createHeaderOnlyInput('token1', 'user2'),+ ]++ 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][1]+ 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' } }),+ ])+ )+ })++ it('passes non-cookieless events through as ok regardless of redirect set', async () => {+ 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)+ })++ 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)++ expect(results[0].type).toBe(PipelineResultType.REDIRECT)+ expect(results[1].type).toBe(PipelineResultType.OK)+ expect(results[2].type).toBe(PipelineResultType.OK)+ })+})diff --git a/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.ts b/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.tsindex 433f77be11a1..9782fca7c9c1 100644--- a/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.ts+++ b/nodejs/src/ingestion/event-preprocessing/rate-limit-to-overflow-step.ts@@ -1,8 +1,77 @@import { EventHeaders, PipelineEvent } from '../../types'import { OVERFLOW_OUTPUT, OverflowOutput } from '../common/outputs'+import { COOKIELESS_SENTINEL_VALUE } from '../cookieless/cookieless-manager'import { PipelineResult, ok, redirect } from '../pipelines/results'import { OverflowEventBatch, OverflowRedirectService } from '../utils/overflow-redirect/overflow-redirect-service'+// `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.++interface KeyDerivation {+ token: string+ distinctId: string+}++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))+ }++ const perInputKeys: (string | null)[] = []+ const keyStats = new Map<string, { token: string; distinctId: string; count: number; 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.count+++ } else {+ keyStats.set(eventKey, { ...derived, count: 1, firstTimestamp: timestamp })+ }+ }++ if (keyStats.size === 0) {+ return inputs.map((input) => ok(input))+ }++ const batches: OverflowEventBatch[] = Array.from(keyStats.values()).map(+ ({ token, distinctId, count, firstTimestamp }) => ({+ key: { token, distinctId },+ eventCount: count,+ firstTimestamp,+ })+ )+ const keysToRedirect = await overflowRedirectService.handleEventBatch('events', batches)++ 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)+ })+}++/**+ * 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).+ */export interface RateLimitToOverflowStepInput {headers: EventHeadersevent: PipelineEvent@@ -13,51 +82,68 @@ export function createRateLimitToOverflowStep<T extends RateLimitToOverflowStepIoverflowRedirectService?: OverflowRedirectService) {return async function rateLimitToOverflowStep(inputs: T[]): Promise<PipelineResult<T, OverflowOutput>[]> {- if (!overflowRedirectService) {- return inputs.map((input) => ok(input))- }+ 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+}- // Count events by token:distinct_id and track first timestamp- // NOTE: headers.token and headers.now are safe to use as they don't change during processing.- // However, headers.distinct_id is NOT safe because cookieless processing may change the- // distinct_id from the sentinel value - use event.distinct_id instead.- const keyStats = new Map<string, { token: string; distinctId: string; count: number; firstTimestamp: number }>()-- for (const { headers, event } of inputs) {- const token = headers.token ?? ''- const distinctId = event.distinct_id ?? ''- const eventKey = `${token}:${distinctId}`- const timestamp = headers.now?.getTime() ?? Date.now()-- const existing = keyStats.get(eventKey)- if (existing) {- existing.count++- } else {- keyStats.set(eventKey, { token, distinctId, count: 1, firstTimestamp: timestamp })+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 ?? '',+ }+ })+ }+}++/**+ * 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+}- // Service handles all overflow logic (rate limiting + optional Redis coordination)- const batches: OverflowEventBatch[] = Array.from(keyStats.values()).map(- ({ token, distinctId, count, firstTimestamp }) => ({- key: { token, distinctId },- eventCount: count,- firstTimestamp,- })- )- const keysToRedirect = await overflowRedirectService.handleEventBatch('events', batches)-- // Build results in original order- return inputs.map((input) => {- const { headers, event } = input- const token = headers.token ?? ''- const distinctId = event.distinct_id ?? ''- const eventKey = `${token}:${distinctId}`-- if (keysToRedirect.has(eventKey)) {- return redirect('rate_limit_exceeded', OVERFLOW_OUTPUT, preservePartitionLocality)- } else {- return ok(input)+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+ }+ return {+ token: input.headers.token ?? '',+ distinctId: input.event.distinct_id ?? '',}})}