Skip to content

: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.

fix(ingestion): unstall v1 consumer after revokes, drop wait flag (#105238)

Paweł Ledwoń0758e69510a6
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 456bf4151754..e33d93554ef1 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -166,7 +166,6 @@ export type CommonConfig = BaseServerConfig & {
CONSUMER_LOOP_BASED_HEALTH_CHECK: boolean
CONSUMER_MAX_BACKGROUND_TASKS: number
CONSUMER_BACKGROUND_TASK_TIMEOUT_MS: number
- CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE: boolean
CONSUMER_REBALANCE_TIMEOUT_MS: number
CONSUMER_AUTO_CREATE_TOPICS: boolean
/**
@@ -383,7 +382,6 @@ export function getDefaultCommonConfig(): CommonConfig {
CONSUMER_LOOP_BASED_HEALTH_CHECK: false,
CONSUMER_MAX_BACKGROUND_TASKS: 1,
CONSUMER_BACKGROUND_TASK_TIMEOUT_MS: 60_000,
- CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE: false,
CONSUMER_REBALANCE_TIMEOUT_MS: 20_000,
CONSUMER_AUTO_CREATE_TOPICS: true,
CONSUMER_USE_V2: false,
diff --git a/nodejs/src/common/kafka/consumer/consumer-v1.test.ts b/nodejs/src/common/kafka/consumer/consumer-v1.test.ts
index 4d93e5d73263..2eb8985fa5b6 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v1.test.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v1.test.ts
@@ -1,6 +1,5 @@
import { CODES, Message, MessageHeader, KafkaConsumer as RdKafkaConsumer } from 'node-rdkafka'
-import { defaultConfig } from '~/common/config/config'
import { createTestEventHeaders } from '~/tests/helpers/event-headers'
import { delay } from '../../utils/utils'
@@ -116,7 +115,6 @@ describe('consumer', () => {
incrementalAssign: jest.fn(),
rebalanceProtocol: jest.fn().mockReturnValue('COOPERATIVE'),
}
- defaultConfig.CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE = true
// Mock the RdKafkaConsumer constructor to return our configured mock
jest.mocked(require('node-rdkafka').KafkaConsumer).mockImplementation(() => mockRdKafkaConsumerInstance)
@@ -371,16 +369,6 @@ describe('consumer', () => {
})
describe('rebalancing', () => {
- it('should set rebalancing state during partition revocation', () => {
- expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)
-
- consumer.rebalanceCallback({ code: CODES.ERRORS.ERR__REVOKE_PARTITIONS } as any, [
- { topic: 'test-topic', partition: 1 },
- ])
-
- expect(consumer['rebalanceCoordination'].isRebalancing).toBe(true)
- })
-
it('should clear rebalancing state during partition assignment', () => {
consumer['rebalanceCoordination'].isRebalancing = true
@@ -391,8 +379,9 @@ describe('consumer', () => {
expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)
})
- it('should call incrementalUnassign when no background tasks exist', async () => {
+ it('should unassign and resume consuming when no background tasks exist', async () => {
consumer['backgroundTask'] = []
+ mockRdKafkaConsumer.assignments.mockReturnValue([{ topic: 'test-topic', partition: 2 }])
consumer.rebalanceCallback({ code: CODES.ERRORS.ERR__REVOKE_PARTITIONS } as any, [
{ topic: 'test-topic', partition: 1 },
@@ -402,9 +391,25 @@ describe('consumer', () => {
expect(mockRdKafkaConsumer.incrementalUnassign).toHaveBeenCalledWith([
{ topic: 'test-topic', partition: 1 },
])
+ expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)
+ })
+
+ it('should resume consuming when unassigning revoked partitions throws', () => {
+ consumer['backgroundTask'] = []
+ mockRdKafkaConsumer.incrementalUnassign.mockImplementation(() => {
+ throw new Error('KafkaConsumer is not connected')
+ })
+
+ expect(() =>
+ consumer.rebalanceCallback({ code: CODES.ERRORS.ERR__REVOKE_PARTITIONS } as any, [
+ { topic: 'test-topic', partition: 1 },
+ ])
+ ).toThrow('KafkaConsumer is not connected')
+ expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)
})
it('should wait for background tasks before calling incrementalUnassign', async () => {
+ mockRdKafkaConsumer.assignments.mockReturnValue([{ topic: 'test-topic', partition: 2 }])
// Create controllable promises to test actual waiting behavior
const task1 = triggerablePromise()
const task2 = triggerablePromise()
@@ -438,33 +443,7 @@ describe('consumer', () => {
expect(mockRdKafkaConsumer.incrementalUnassign).toHaveBeenCalledWith([
{ topic: 'test-topic', partition: 1 },
])
- })
-
- it('should not wait when waitForBackgroundTasksOnRebalance is disabled', async () => {
- defaultConfig.CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE = false
- // Create a consumer with feature disabled
- const consumerDisabled = new KafkaConsumer({
- groupId: 'test-group',
- topic: 'test-topic',
- })
-
- const mockConsumerDisabled = jest.mocked(consumerDisabled['rdKafkaConsumer'])
-
- // Add background tasks with metadata
- // Explicitly assign promise array (handled in cleanup)
- void (consumerDisabled['backgroundTask'] = [{ promise: Promise.resolve(), createdAt: Date.now() }])
-
- consumerDisabled.rebalanceCallback({ code: CODES.ERRORS.ERR__REVOKE_PARTITIONS } as any, [
- { topic: 'test-topic', partition: 1 },
- ])
-
- // Should proceed immediately without waiting
- await delay(1)
- expect(mockConsumerDisabled.incrementalUnassign).toHaveBeenCalledWith([
- { topic: 'test-topic', partition: 1 },
- ])
-
- await consumerDisabled.disconnect()
+ expect(consumer['rebalanceCoordination'].isRebalancing).toBe(false)
})
})
})
diff --git a/nodejs/src/common/kafka/consumer/consumer-v1.ts b/nodejs/src/common/kafka/consumer/consumer-v1.ts
index ca401cc6aa04..d07d7930b531 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v1.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v1.ts
@@ -110,7 +110,6 @@ export type KafkaConsumerConfig = {
autoOffsetStore?: boolean
autoCommit?: boolean
enablePartitionEof?: boolean
- waitForBackgroundTasksOnRebalance?: boolean
/**
* Messages pulled per poll, overriding CONSUMER_BATCH_SIZE for this consumer only.
*
@@ -126,8 +125,6 @@ export type RdKafkaConsumerConfig = Omit<
'group.id' | 'enable.auto.offset.store' | 'enable.auto.commit'
>
-type RebalanceCallback = boolean | ((err: LibrdKafkaError, assignments: Assignment[]) => void)
-
interface RebalanceCoordination {
isRebalancing: boolean
rebalanceTimeoutMs: number
@@ -172,7 +169,6 @@ export class KafkaConsumer {
this.config.autoCommit ??= true
this.config.autoOffsetStore ??= true
this.config.callEachBatchWhenEmpty ??= false
- this.config.waitForBackgroundTasksOnRebalance = defaultConfig.CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE
this.maxBackgroundTasks = defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS
this.fetchBatchSize = config.fetchBatchSize ?? defaultConfig.CONSUMER_BATCH_SIZE
this.maxHealthHeartbeatIntervalMs =
@@ -180,10 +176,6 @@ export class KafkaConsumer {
this.consumerLoopStallThresholdMs = defaultConfig.CONSUMER_LOOP_STALL_THRESHOLD_MS
this.consumerLogStatsLevel = defaultConfig.CONSUMER_LOG_STATS_LEVEL
- const rebalancecb: RebalanceCallback = this.config.waitForBackgroundTasksOnRebalance
- ? this.rebalanceCallback.bind(this)
- : true
-
this.consumerConfig = stripClassicProtocolConfig({
'client.id': hostname(),
'security.protocol': 'plaintext',
@@ -215,7 +207,7 @@ export class KafkaConsumer {
'partition.assignment.strategy': isTestEnv() ? 'roundrobin' : 'cooperative-sticky', // Roundrobin is used for testing to avoid flakiness caused by running librdkafka v2.2.0
'enable.auto.offset.store': false, // NOTE: This is always false - we handle it using a custom function
'enable.auto.commit': this.config.autoCommit,
- rebalance_cb: rebalancecb,
+ rebalance_cb: this.rebalanceCallback.bind(this),
offset_commit_cb: true,
})
@@ -407,9 +399,7 @@ export class KafkaConsumer {
if (err.code === CODES.ERRORS.ERR__ASSIGN_PARTITIONS) {
// Mark rebalancing as complete when partitions are assigned
- if (this.config.waitForBackgroundTasksOnRebalance) {
- this.resetRebalanceCoordination()
- }
+ this.resetRebalanceCoordination()
assignments.forEach((tp) => {
kafkaConsumerAssignment.set(
{
@@ -428,10 +418,8 @@ export class KafkaConsumer {
}
} else if (err.code === CODES.ERRORS.ERR__REVOKE_PARTITIONS) {
// Mark rebalancing as starting when partitions are revoked
- if (this.config.waitForBackgroundTasksOnRebalance) {
- this.rebalanceCoordination.isRebalancing = true
- this.rebalanceCoordination.rebalanceStartTime = Date.now()
- }
+ this.rebalanceCoordination.isRebalancing = true
+ this.rebalanceCoordination.rebalanceStartTime = Date.now()
logger.info('🔁', 'partition_revocation_starting', {
backgroundTaskCount: this.backgroundTask.length,
revokedPartitions: assignments.map((tp) => ({
@@ -441,58 +429,21 @@ export class KafkaConsumer {
})
// Handle background task coordination asynchronously
- if (this.config.waitForBackgroundTasksOnRebalance && this.backgroundTask.length > 0) {
+ if (this.backgroundTask.length > 0) {
// Don't block the rebalance callback, but coordinate in the background
Promise.all(this.backgroundTask.map((t) => t.promise))
.then(() => {
logger.info('🔁', 'background_tasks_completed_before_partition_revocation')
- if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
- this.rdKafkaConsumer.incrementalUnassign(assignments)
- } else {
- this.rdKafkaConsumer.unassign()
- }
- this.updateMetricsAfterRevocation(assignments)
- try {
- if (this.assignments().length === 0) {
- this.resetRebalanceCoordination()
- }
- } catch (error) {
- // Consumer might be in an erroneous state, reset anyway to be safe
- logger.debug('🔁', 'assignments_check_failed_resetting_rebalance_coordination', {
- error: String(error),
- })
- this.resetRebalanceCoordination()
- }
+ this.completeRevocation(assignments)
})
.catch((error) => {
logger.error('🔁', 'background_task_error_during_revocation', { error })
// Still proceed with revocation even if background tasks fail
- if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
- this.rdKafkaConsumer.incrementalUnassign(assignments)
- } else {
- this.rdKafkaConsumer.unassign()
- }
- this.updateMetricsAfterRevocation(assignments)
- try {
- if (this.assignments().length === 0) {
- this.resetRebalanceCoordination()
- }
- } catch (error) {
- // Consumer might be in an erroneous state, reset anyway to be safe
- logger.debug('🔁', 'assignments_check_failed_resetting_rebalance_coordination', {
- error: String(error),
- })
- this.resetRebalanceCoordination()
- }
+ this.completeRevocation(assignments)
})
} else {
- // No background tasks or feature disabled, proceed immediately
- if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
- this.rdKafkaConsumer.incrementalUnassign(assignments)
- } else {
- this.rdKafkaConsumer.unassign()
- }
- this.updateMetricsAfterRevocation(assignments)
+ // No background tasks, proceed immediately
+ this.completeRevocation(assignments)
}
} else {
// Ignore exceptions if we are not connected
@@ -505,6 +456,19 @@ export class KafkaConsumer {
}
}
+ private completeRevocation(assignments: Assignment[]): void {
+ try {
+ if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
+ this.rdKafkaConsumer.incrementalUnassign(assignments)
+ } else {
+ this.rdKafkaConsumer.unassign()
+ }
+ this.updateMetricsAfterRevocation(assignments)
+ } finally {
+ this.resetRebalanceCoordination()
+ }
+ }
+
private updateMetricsAfterRevocation(assignments: Assignment[]): void {
assignments.forEach((tp) => {
kafkaConsumerAssignment.set(
@@ -673,9 +637,9 @@ export class KafkaConsumer {
this.lastConsumerLoopTime = Date.now()
logger.debug('🔁', 'main_loop_consuming')
- // If we're rebalancing and feature flag is enabled, skip consuming to avoid processing messages
+ // If we're rebalancing, skip consuming to avoid processing messages
// during rebalancing when background tasks might be running
- if (this.rebalanceCoordination.isRebalancing && this.config.waitForBackgroundTasksOnRebalance) {
+ if (this.rebalanceCoordination.isRebalancing) {
if (
Date.now() - this.rebalanceCoordination.rebalanceStartTime >
this.rebalanceCoordination.rebalanceTimeoutMs
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 3dcaaa371bdb..4609b09e8af6 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -74,7 +74,6 @@ export type KafkaConsumerBaseConfig = Pick<
| 'CONSUMER_LOG_STATS_LEVEL'
| 'CONSUMER_LOOP_BASED_HEALTH_CHECK'
| 'CONSUMER_MAX_BACKGROUND_TASKS'
- | 'CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE'
| 'CONSUMER_AUTO_CREATE_TOPICS'
>