: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
chore(error-tracking): support cookieless (#60145)
Zach Browndf8777d5db40
diff --git a/nodejs/src/ingestion/cookieless/cookieless-manager.ts b/nodejs/src/ingestion/cookieless/cookieless-manager.tsindex 5adf46510958..1b699cb77bfb 100644--- a/nodejs/src/ingestion/cookieless/cookieless-manager.ts+++ b/nodejs/src/ingestion/cookieless/cookieless-manager.ts@@ -91,6 +91,29 @@ interface CookielessConfig {sessionInactivityMs: number}+/**+ * The cookieless-related keys a CookielessManager needs from the consumer config.+ */+export type CookielessManagerConfig = Pick<+ IngestionConsumerConfig,+ | 'COOKIELESS_DISABLED'+ | 'COOKIELESS_FORCE_STATELESS_MODE'+ | 'COOKIELESS_DELETE_EXPIRED_LOCAL_SALTS_INTERVAL_MS'+ | 'COOKIELESS_SESSION_TTL_SECONDS'+ | 'COOKIELESS_SALT_TTL_SECONDS'+ | 'COOKIELESS_SESSION_INACTIVITY_MS'+ | 'COOKIELESS_IDENTIFIES_TTL_SECONDS'+>++/**+ * Everything a server needs to instantiate a CookielessManager and its Redis pool —+ * the manager's own config plus the Redis connection knobs read by+ * `createCookielessRedisConnectionConfig`. Use this in service config slices instead+ * of redeclaring the cookieless keys inline.+ */+export type CookielessServerConfig = CookielessManagerConfig &+ Pick<IngestionConsumerConfig, 'COOKIELESS_REDIS_HOST' | 'COOKIELESS_REDIS_PORT'>+export class CookielessManager {public readonly redisHelpers: RedisHelperspublic readonly config: CookielessConfig@@ -99,19 +122,7 @@ export class CookielessManager {private readonly mutex = new ConcurrencyController(1)private cleanupInterval: NodeJS.Timeout | null = null- constructor(- config: Pick<- IngestionConsumerConfig,- | 'COOKIELESS_DISABLED'- | 'COOKIELESS_FORCE_STATELESS_MODE'- | 'COOKIELESS_DELETE_EXPIRED_LOCAL_SALTS_INTERVAL_MS'- | 'COOKIELESS_SESSION_TTL_SECONDS'- | 'COOKIELESS_SALT_TTL_SECONDS'- | 'COOKIELESS_SESSION_INACTIVITY_MS'- | 'COOKIELESS_IDENTIFIES_TTL_SECONDS'- >,- redis: GenericPool<Redis.Redis>- ) {+ constructor(config: CookielessManagerConfig, redis: GenericPool<Redis.Redis>) {this.config = {disabled: config.COOKIELESS_DISABLED,forceStatelessMode: config.COOKIELESS_FORCE_STATELESS_MODE,diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.tsindex afdf8daadd31..69390c36f846 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts@@ -204,6 +204,7 @@ describe('ErrorTrackingConsumer', () => {errorTrackingSettingsManager: new ErrorTrackingSettingsManager(hub.postgres),hogTransformer: mockHogTransformer,groupTypeManager: hub.groupTypeManager,+ cookielessManager: hub.cookielessManager,redisPool: hub.redisPool,personRepository: hub.personRepository,}diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.tsindex cec67bd45ff9..12db3fcc982a 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts@@ -20,6 +20,7 @@ import { TeamManager } from '../../utils/team-manager'import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'import { PersonRepository } from '../../worker/ingestion/persons/repositories/person-repository'import { OverflowOutput } from '../common/outputs'+import { CookielessManager } from '../cookieless/cookieless-manager'import { BatchPipelineUnwrapper } from '../pipelines/batch-pipeline-unwrapper'import { TopHog } from '../tophog'import { MainLaneOverflowRedirect } from '../utils/overflow-redirect/main-lane-overflow-redirect'@@ -96,6 +97,7 @@ export interface ErrorTrackingConsumerDeps {errorTrackingSettingsManager?: ErrorTrackingSettingsManagerhogTransformer: ErrorTrackingHogTransformergroupTypeManager: GroupTypeManager+ cookielessManager: CookielessManagerredisPool: GenericPool<Redis>personRepository: PersonRepository}@@ -264,6 +266,7 @@ export class ErrorTrackingConsumer {hogTransformer: this.deps.hogTransformer,cymbalClient: this.cymbalClient,groupTypeManager: this.deps.groupTypeManager,+ cookielessManager: this.deps.cookielessManager,eventIngestionRestrictionManager: this.eventIngestionRestrictionManager,overflowEnabled: this.config.overflowEnabled,preservePartitionLocality: this.config.preservePartitionLocality,diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.tsindex aa7bec9c3fe4..4353ff16ac91 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.test.ts@@ -13,10 +13,13 @@ import { GroupTypeManager } from '~/worker/ingestion/group-type-manager'import { PersonRepository } from '~/worker/ingestion/persons/repositories/person-repository'import { TophogOutput } from '../common/outputs'+import { COOKIELESS_SENTINEL_VALUE, CookielessManager } from '../cookieless/cookieless-manager'import { IngestionOutputs } from '../outputs/ingestion-outputs'import { SingleIngestionOutput } from '../outputs/single-ingestion-output'import { TopHogRegistry } from '../pipelines/extensions/tophog'+import { ok } from '../pipelines/results'import { TopHog } from '../tophog'+import { OverflowRedirectService } from '../utils/overflow-redirect/overflow-redirect-service'import { CymbalClient } from './cymbal/client'import { CymbalResponse } from './cymbal/types'import { ErrorTrackingHogTransformer } from './error-tracking-consumer'@@ -50,6 +53,7 @@ describe('ErrorTrackingPipeline', () => {let mockCymbalClient: jest.Mocked<CymbalClient>let mockGroupTypeManager: jest.Mocked<GroupTypeManager>let mockEventIngestionRestrictionManager: jest.Mocked<EventIngestionRestrictionManager>+ let mockCookielessManager: jest.Mocked<CookielessManager>let promiseScheduler: PromiseSchedulerlet pipelineConfig: ErrorTrackingPipelineConfig@@ -270,6 +274,14 @@ describe('ErrorTrackingPipeline', () => {forceRefresh: jest.fn(),} as unknown as jest.Mocked<EventIngestionRestrictionManager>+ // Passthrough: non-cookieless events round-trip unchanged. The apply step+ // extracts `.value.event` from each result and reuses the original input+ // wrapper, so returning `ok(input)` is enough to leave events untouched.+ mockCookielessManager = {+ doBatch: jest.fn().mockImplementation((events: any[]) => Promise.resolve(events.map((e) => ok(e)))),+ shutdown: jest.fn(),+ } as unknown as jest.Mocked<CookielessManager>+promiseScheduler = new PromiseScheduler()// Mock TopHog registry that returns no-op recorders@@ -306,6 +318,7 @@ describe('ErrorTrackingPipeline', () => {hogTransformer: mockHogTransformer,cymbalClient: mockCymbalClient,groupTypeManager: mockGroupTypeManager,+ cookielessManager: mockCookielessManager,eventIngestionRestrictionManager: mockEventIngestionRestrictionManager,overflowEnabled: false,preservePartitionLocality: false,@@ -926,6 +939,116 @@ describe('ErrorTrackingPipeline', () => {})})+ describe('cookieless processing', () => {+ const createMockOverflowRedirectService = (+ keysToRedirect: Set<string> = new Set()+ ): jest.Mocked<OverflowRedirectService> =>+ ({+ handleEventBatch: jest.fn().mockResolvedValue(keysToRedirect),+ healthCheck: jest.fn().mockResolvedValue({ status: 'ok' }),+ shutdown: jest.fn().mockResolvedValue(undefined),+ }) as unknown as jest.Mocked<OverflowRedirectService>++ it('invokes the cookieless manager once per batch', async () => {+ const person = createTestPerson()+ mockPersonRepository.fetchPersonsByDistinctIds.mockResolvedValue([person])+ mockCymbalClient.processExceptions.mockResolvedValue([createCymbalResponse(), createCymbalResponse()])++ const messages = [createKafkaMessage({ distinctId: 'a' }), createKafkaMessage({ distinctId: 'b' })]+ const pipeline = createErrorTrackingPipeline(pipelineConfig)+ await runErrorTrackingPipeline(pipeline, messages)++ expect(mockCookielessManager.doBatch).toHaveBeenCalledTimes(1)+ const passedEvents = mockCookielessManager.doBatch.mock.calls[0][0]+ expect(passedEvents).toHaveLength(2)+ expect(passedEvents.map((e: any) => e.event.distinct_id)).toEqual(['a', 'b'])+ })++ it('uses the rewritten distinct_id from the cookieless manager downstream', async () => {+ 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' },+ })+ )+ )+ )++ const message = createKafkaMessage({ distinctId: '$posthog_cookieless' })+ const pipeline = createErrorTrackingPipeline(pipelineConfig)+ await runErrorTrackingPipeline(pipeline, [message])++ const producedEvents = getProducedEvents()+ expect(producedEvents).toHaveLength(1)+ 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' } }))+ )+ )++ const flagging = createMockOverflowRedirectService(new Set([`test-token-123:${COOKIELESS_SENTINEL_VALUE}`]))+ const configWithOverflow: ErrorTrackingPipelineConfig = {+ ...pipelineConfig,+ overflowEnabled: true,+ overflowRedirectService: flagging,+ }++ const message = createKafkaMessage({ distinctId: COOKIELESS_SENTINEL_VALUE })+ 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,+ overflowEnabled: true,+ 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)+ })+ })+describe('TopHog metrics', () => {let mockTophogQueueMessages: jest.Mocklet topHog: TopHogdiff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.tsindex 145ffe2a2783..e0cf203ecc03 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts@@ -17,13 +17,16 @@ import {OverflowOutput,TophogOutput,} from '../common/outputs'+import { CookielessManager } from '../cookieless/cookieless-manager'import {+ createApplyCookielessProcessingStep,createApplyEventRestrictionsStep,+ createOnlyCookielessRateLimitToOverflowStep,createOverflowLaneTTLRefreshStep,createParseHeadersStep,createParseKafkaMessageStep,- createRateLimitToOverflowStep,createResolveTeamStep,+ createSkipCookielessRateLimitToOverflowStep,} from '../event-preprocessing'import { createCreateEventStep } from '../event-processing/create-event-step'import { createEmitEventStep } from '../event-processing/emit-event-step'@@ -70,6 +73,7 @@ export interface ErrorTrackingPipelineConfig {hogTransformer: ErrorTrackingHogTransformer | nullcymbalClient: CymbalClientgroupTypeManager: GroupTypeManager+ cookielessManager: CookielessManagereventIngestionRestrictionManager: EventIngestionRestrictionManageroverflowEnabled: boolean/**@@ -130,17 +134,23 @@ function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends stri* Creates the error tracking pipeline.** The pipeline processes exception events through these phases:- * 1. Parse headers - Extract token, timestamps from Kafka message headers- * 2. Apply event restrictions - Billing limits, drop/overflow- * 3. Parse Kafka message - Parse message body into event- * 4. Resolve team - Look up team by token- * 5. Cymbal processing - Symbolicate, fingerprint, and link issues- * 6. Person properties - Fetch person by distinct_id (read-only)- * 7. Hog transformations - Run team transformations (including GeoIP if enabled)- * 8. Prepare event - Convert to PreIngestionEvent format, track if person found- * 9. Group type mapping - Map group types to indexes (read-only)- * 10. Create event - Build ErrorTrackingKafkaEvent (matches Cymbal's output format)- * 11. Emit event - Produce to output topic+ * 1. Parse headers - Extract token, timestamps from Kafka message headers+ * 2. Apply event restrictions - Billing limits, drop/overflow+ * 3. Skip-cookieless rate limit - Redirect non-cookieless rate-limited events to overflow+ * pre-parse (cookieless events pass through to step 6)+ * 4. Parse Kafka message - Parse message body into event+ * 5. Resolve team - Look up team by token+ * 6. Apply cookieless processing - Rewrite distinct_id for cookieless events+ * 7. Only-cookieless rate limit - Redirect cookieless rate-limited events to overflow+ * using the hashed distinct_id from step 6+ * 8. Team-global rate limit - Drop events that exceed per-team caps (optional)+ * 9. Cymbal processing - Symbolicate, fingerprint, and link issues+ * 10. Person properties - Fetch person by distinct_id (read-only)+ * 11. Hog transformations - Run team transformations (including GeoIP if enabled)+ * 12. Prepare event - Convert to PreIngestionEvent format, track if person found+ * 13. Group type mapping - Map group types to indexes (read-only)+ * 14. Create event - Build ErrorTrackingKafkaEvent (matches Cymbal's output format)+ * 15. Emit event - Produce to output topic** Note: Cymbal runs before enrichment because it only needs the raw exception data* for symbolication and fingerprinting. This reduces payload size and avoids@@ -163,6 +173,7 @@ export function createErrorTrackingPipeline(hogTransformer,cymbalClient,groupTypeManager,+ cookielessManager,eventIngestionRestrictionManager,overflowEnabled,preservePartitionLocality,@@ -183,20 +194,27 @@ export function createErrorTrackingPipeline(const pipeline = newBatchPipelineBuilder<ErrorTrackingPipelineInput, { message: Message }>().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) =>+ 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 post-cookieless by createOnlyCookielessRateLimitToOverflowStep, 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- // Parse headers from Kafka message [REUSE]- .pipe(createParseHeadersStep())- // Apply event restrictions (billing limits, drop/overflow) [REUSE]- .pipe(- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {- overflowEnabled,- preservePartitionLocality,- })- )- // Parse Kafka message body [REUSE].pipe(createParseKafkaMessageStep())- // Resolve team from token [REUSE].pipe(topHogWrapper(createResolveTeamStep(teamManager), [countOk('resolved_teams', (output) => ({@@ -224,19 +242,29 @@ export function createErrorTrackingPipeline((b) =>b.teamAware((b) => {- // Pre-Cymbal rate limit chain runs FIRST so that events we'd drop- // never consume overflow-redirect cycles or symbolication budget.- // Each spec becomes its own batch step, applied in array order.- // Empty / undefined → no-op.- const afterRateLimit = applyKeyedRateLimiters(b.gather(), preCymbalRateLimiters ?? [])- const preCymbal = afterRateLimit- // Rate limit high-volume token:distinct_id pairs to overflow+ // Cookieless processing: rewrites event.distinct_id for cookieless+ // events. Must run as a batch and before any step that depends on+ // the final distinct ID.+ const afterCookieless = b+ .gather()+ .pipeBatch(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..pipeBatch(- createRateLimitToOverflowStep(+ createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality,overflowRedirectService))+ // Pre-Cymbal team-global rate-limit chain. Drops events the team+ // has explicitly capped, so they never consume symbolication+ // budget. Empty / undefined → no-op.+ const afterRateLimit = applyKeyedRateLimiters(+ afterCookieless,+ preCymbalRateLimiters ?? []+ )+ const preCymbal = afterRateLimit// Refresh TTLs for overflow lane events (keeps Redis flags alive).pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))return (diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.tsindex de5a6c4210fa..f154bab74b7e 100644--- a/nodejs/src/servers/error-tracking-server.ts+++ b/nodejs/src/servers/error-tracking-server.ts@@ -9,7 +9,7 @@ import {import { EncryptedFields } from '../cdp/utils/encryption-utils'import { CommonConfig } from '../common/config'import { defaultConfig, overrideConfigWithEnv } from '../config/config'-import { createIngestionRedisConnectionConfig } from '../config/redis-pools'+import { createCookielessRedisConnectionConfig, createIngestionRedisConnectionConfig } from '../config/redis-pools'import {KafkaIngestionProducerEnvConfig,KafkaProducerEnvConfig,@@ -27,6 +27,7 @@ import {PersonHogConfig,RedisConnectionsConfig,} from '../ingestion/config'+import { CookielessManager, CookielessServerConfig } from '../ingestion/cookieless/cookieless-manager'import {ErrorTrackingConsumerConfig,ErrorTrackingOutputsConfig,@@ -72,6 +73,7 @@ export type ErrorTrackingServerConfig = BaseServerConfig &RedisConnectionsConfig &KafkaConsumerBaseConfig &PersonHogConfig &+ CookielessServerConfig &Pick<CommonConfig,| 'LOG_LEVEL'@@ -90,6 +92,8 @@ export class ErrorTrackingServer implements NodeServer {private postgres?: PostgresRouterprivate producerRegistry?: KafkaProducerRegistry<ProducerName>private redisPool?: RedisPool+ private cookielessRedisPool?: RedisPool+ private cookielessManager?: CookielessManagerprivate pubsub?: PubSubconstructor(config: Partial<ErrorTrackingServerConfig> = {}) {@@ -140,6 +144,16 @@ export class ErrorTrackingServer implements NodeServer {})logger.info('👍', 'Ingestion Redis ready')+ logger.info('🤔', 'Connecting to cookieless Redis...')+ this.cookielessRedisPool = createRedisPoolFromConfig({+ connection: createCookielessRedisConnectionConfig(this.config),+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,+ })+ logger.info('👍', 'Cookieless Redis ready')++ this.cookielessManager = new CookielessManager(this.config, this.cookielessRedisPool)+this.pubsub = new PubSub(this.redisPool)await this.pubsub.start()@@ -224,6 +238,7 @@ export class ErrorTrackingServer implements NodeServer {errorTrackingSettingsManager,hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),groupTypeManager: new GroupTypeManager(groupRepository, teamManager),+ cookielessManager: this.cookielessManager!,redisPool: this.redisPool!,personRepository,}@@ -245,11 +260,12 @@ export class ErrorTrackingServer implements NodeServer {private getCleanupResources(): CleanupResources {return {kafkaProducers: [],- redisPools: [this.redisPool].filter(Boolean) as RedisPool[],+ redisPools: [this.redisPool, this.cookielessRedisPool].filter(Boolean) as RedisPool[],postgres: this.postgres,pubsub: this.pubsub,additionalCleanup: async () => {await this.producerRegistry?.disconnectAll()+ this.cookielessManager?.shutdown()},}}