:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(error-tracking): flush batch side effects as a consumer background task (#96300)
José Sequeiraa25764da692e
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.tsindex a233456c2d87..a77750d9e849 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts@@ -230,6 +230,14 @@ describe('ErrorTrackingConsumer', () => {return events.map((event) => createKafkaMessage(event, token ?? team.api_token))}+ // A batch is fully processed once the returned background task (the+ // scheduled side-effect flush) has settled, matching the consumer loop.+ const handleBatch = async (messages: Message[]): Promise<void> => {+ const result = await consumer.handleKafkaBatch(messages)+ expect(result.backgroundTask).toBeDefined()+ await result.backgroundTask+ }+beforeEach(async () => {fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())@@ -263,7 +271,7 @@ describe('ErrorTrackingConsumer', () => {describe('event processing', () => {it('should process a basic exception event', async () => {const messages = createKafkaMessages([createEvent()])- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)const producedMessages =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')@@ -282,7 +290,7 @@ describe('ErrorTrackingConsumer', () => {createEvent({ distinct_id: 'user-3' }),]const messages = createKafkaMessages(events)- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)const producedMessages =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')@@ -294,7 +302,7 @@ describe('ErrorTrackingConsumer', () => {it('should include exception fingerprint and issue id from Cymbal', async () => {const messages = createKafkaMessages([createEvent()])- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)const producedMessages =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')@@ -317,7 +325,7 @@ describe('ErrorTrackingConsumer', () => {},}),])- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)const producedMessages =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')@@ -349,7 +357,7 @@ describe('ErrorTrackingConsumer', () => {ip: '89.160.20.129',}),])- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)const producedMessages =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')@@ -364,7 +372,7 @@ describe('ErrorTrackingConsumer', () => {it('should flush invocation results after batch processing', async () => {const messages = createKafkaMessages([createEvent()])- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)expect(mockHogTransformer.processInvocationResults).toHaveBeenCalledTimes(1)})@@ -384,7 +392,7 @@ describe('ErrorTrackingConsumer', () => {describe('error handling', () => {it('should reject events with invalid token', async () => {const messages = createKafkaMessages([createEvent()], 'invalid-token-that-does-not-exist')- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)// Event should not be produced to output topic (team not found = dropped)const producedMessages =@@ -396,7 +404,7 @@ describe('ErrorTrackingConsumer', () => {})it('should handle empty batch', async () => {- await consumer.handleKafkaBatch([])+ await handleBatch([])const producedMessages = mockProducerObserver.getProducedKafkaMessages()expect(producedMessages).toHaveLength(0)@@ -407,7 +415,7 @@ describe('ErrorTrackingConsumer', () => {it('should always use full person_mode', async () => {// Error tracking always uses full person_mode to preserve group propertiesconst messages = createKafkaMessages([createEvent()])- await consumer.handleKafkaBatch(messages)+ await handleBatch(messages)const producedMessages =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.tsindex e47f4ca2929b..2392e2c215f1 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts@@ -192,7 +192,7 @@ export class ErrorTrackingConsumer {await this.kafkaConsumer.connect(async (messages) => {return await instrumentFn('errorTrackingConsumer.handleEachBatch', async () => {- await this.handleKafkaBatch(messages)+ return await this.handleKafkaBatch(messages)})})@@ -259,7 +259,7 @@ export class ErrorTrackingConsumer {return this.kafkaConsumer.isHealthy()}- public async handleKafkaBatch(messages: Message[]): Promise<void> {+ public async handleKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<unknown> }> {// Update offset timestamps for lag metricsfor (const message of messages) {if (message.timestamp) {@@ -278,10 +278,23 @@ export class ErrorTrackingConsumer {error: error instanceof Error ? error.message : String(error),size: messages.length,})+ // Flush scheduled work before the error propagates and crashes the loop+ await this.flushScheduledWork()throw error- } finally {- // Flush scheduled work and invocation results to prevent memory accumulation- await Promise.all([this.promiseScheduler.waitForAll(), this.deps.hogTransformer.processInvocationResults()])}++ // Flushing scheduled produces is the slow tail of a batch (broker acks),+ // so hand it to the consumer as a background task: the consumer fetches+ // and processes the next batch while this settles, and only stores this+ // batch's offsets once it has. CONSUMER_MAX_BACKGROUND_TASKS caps how+ // many batches may overlap this way.+ return {+ backgroundTask: instrumentFn('errorTrackingConsumer.awaitScheduledWork', () => this.flushScheduledWork()),+ }+ }++ private async flushScheduledWork(): Promise<void> {+ // Flush scheduled work and invocation results to prevent memory accumulation+ await Promise.all([this.promiseScheduler.waitForAll(), this.deps.hogTransformer.processInvocationResults()])}}