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.

feat(node): V2 kafka consumer (#57142)

Ben Whitea55c4de2370c
diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts
index 538bc2ac45af..94022bbc9416 100644
--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts
@@ -7,7 +7,7 @@ import { HogFlow } from '~/schema/hogflow'
import { parseJSON } from '~/utils/json-parse'
import { captureException } from '~/utils/posthog'
-import { KafkaConsumer } from '../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
import { HealthCheckResult, PluginsServerConfig, Team } from '../../types'
import { logger } from '../../utils/logger'
import { UUIDT } from '../../utils/utils'
@@ -36,7 +36,7 @@ export interface BatchHogFlowRequestMessage {
export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServerConfig> {
protected name = 'CdpBatchHogFlowRequestsConsumer'
private cyclotronJobQueue: CyclotronJobQueue
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
private hogFlowBatchPersonQueryService: HogFlowBatchPersonQueryService
constructor(
@@ -47,7 +47,7 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServ
) {
super(config, deps)
this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)
- this.kafkaConsumer = new KafkaConsumer({ groupId, topic })
+ this.kafkaConsumer = createKafkaConsumer({ groupId, topic })
this.hogFlowBatchPersonQueryService = new HogFlowBatchPersonQueryService(
new InternalFetchService(config.INTERNAL_API_BASE_URL, config.INTERNAL_API_SECRET)
)
diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts
index 4331885c725e..aa837fce8186 100644
--- a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts
@@ -4,7 +4,7 @@ import { z } from 'zod'
import { instrumentFn } from '~/common/tracing/tracing-utils'
import { KAFKA_COHORT_MEMBERSHIP_CHANGED } from '../../config/kafka-topics'
-import { KafkaConsumer } from '../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
import { HealthCheckResult } from '../../types'
import { PostgresUse } from '../../utils/db/postgres'
import { parseJSON } from '../../utils/json-parse'
@@ -24,11 +24,11 @@ export type CohortMembershipChange = z.infer<typeof CohortMembershipChangeSchema
export class CdpCohortMembershipConsumer extends CdpConsumerBase {
protected name = 'CdpCohortMembershipConsumer'
- private kafkaConsumer: KafkaConsumer
+ private kafkaConsumer: KafkaConsumerInterface
constructor(config: CdpConsumerBaseConfig, deps: CdpConsumerBaseDeps) {
super(config, deps)
- this.kafkaConsumer = new KafkaConsumer({
+ this.kafkaConsumer = createKafkaConsumer({
groupId: 'cdp-cohort-membership-consumer',
topic: KAFKA_COHORT_MEMBERSHIP_CHANGED,
})
diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
index 9016b3406213..259a997a0cae 100644
--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
@@ -5,7 +5,7 @@ import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'
import { convertToHogFunctionInvocationGlobals } from '../../cdp/utils'
import { KAFKA_EVENTS_JSON } from '../../config/kafka-topics'
-import { KafkaConsumer } from '../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'
import { parseJSON } from '../../utils/json-parse'
import { logger } from '../../utils/logger'
@@ -33,7 +33,7 @@ export class CdpEventsConsumer<
protected name = 'CdpEventsConsumer'
protected hogTypes: HogFunctionTypeType[] = ['destination']
private cyclotronJobQueue: CyclotronJobQueue
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
private hogRateLimiter: HogRateLimiterService
@@ -45,7 +45,7 @@ export class CdpEventsConsumer<
) {
super(config, deps)
this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)
- this.kafkaConsumer = new KafkaConsumer({ groupId, topic })
+ this.kafkaConsumer = createKafkaConsumer({ groupId, topic })
this.hogRateLimiter = new HogRateLimiterService(
{
bucketSize: config.CDP_RATE_LIMITER_BUCKET_SIZE,
diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts
index ecd064e8d53f..c396448b26f6 100644
--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts
@@ -3,7 +3,7 @@ import { Counter } from 'prom-client'
import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'
-import { KafkaConsumer } from '../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
import {
HealthCheckResult,
ISOTimestamp,
@@ -71,7 +71,7 @@ export interface CdpLegacyEventsConsumerDeps extends CdpConsumerBaseDeps {
export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsConsumerConfig> {
protected name = 'CdpLegacyEventsConsumer'
protected promiseScheduler = new PromiseScheduler()
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
private pluginConfigsLoader: LazyLoader<PluginConfigHogFunction[]>
private legacyPluginExecutor: LegacyPluginExecutorService
@@ -83,7 +83,7 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons
) {
super(config, deps)
- this.kafkaConsumer = new KafkaConsumer({
+ this.kafkaConsumer = createKafkaConsumer({
groupId: config.CDP_LEGACY_EVENT_CONSUMER_GROUP_ID,
topic: config.CDP_LEGACY_EVENT_CONSUMER_TOPIC,
})
diff --git a/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.ts b/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.ts
index 042154ce3af0..eee91cd64045 100644
--- a/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.ts
@@ -8,7 +8,7 @@ import {
} from '~/utils/realtime-supported-filter-manager-cdp'
import { KAFKA_EVENTS_JSON } from '../../config/kafka-topics'
-import { KafkaConsumer } from '../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
import { HealthCheckResult, RawClickHouseEvent } from '../../types'
import { yieldEach } from '../../utils/event-loop-yield'
import { parseJSON } from '../../utils/json-parse'
@@ -52,12 +52,12 @@ export const histogramBatchProcessingSteps = new Histogram({
export class CdpPrecalculatedFiltersConsumer extends CdpConsumerBase {
protected name = 'CdpPrecalculatedFiltersConsumer'
- private eventKafkaConsumer: KafkaConsumer
+ private eventKafkaConsumer: KafkaConsumerInterface
private realtimeSupportedFilterManager: RealtimeSupportedFilterManagerCDP
constructor(config: CdpConsumerBaseConfig, deps: CdpConsumerBaseDeps) {
super(config, deps)
- this.eventKafkaConsumer = new KafkaConsumer({
+ this.eventKafkaConsumer = createKafkaConsumer({
groupId: 'cdp-precalculated-filters-consumer',
topic: KAFKA_EVENTS_JSON,
})
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts b/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts
index a3e3947f1139..f0492a282e1e 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts
@@ -6,7 +6,7 @@
import { Message } from 'node-rdkafka'
import { compress, uncompress } from 'snappy'
-import { KafkaConsumer } from '../../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../../kafka/consumer'
import { KafkaProducerWrapper } from '../../../kafka/producer'
import { HealthCheckResult, HealthCheckResultError } from '../../../types'
import { parseJSON } from '../../../utils/json-parse'
@@ -16,7 +16,7 @@ import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueue
import { cdpJobSizeCompressedKb, cdpJobSizeKb } from './shared'
export class CyclotronJobQueueKafka {
- private kafkaConsumer?: KafkaConsumer
+ private kafkaConsumer?: KafkaConsumerInterface
private kafkaProducer?: KafkaProducerWrapper
private queue?: CyclotronJobQueueKind
private consumeBatch?: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>
@@ -45,7 +45,7 @@ export class CyclotronJobQueueKafka {
const topic = `cdp_cyclotron_${this.queue}`
// NOTE: As there is only ever one consumer per process we use the KAFKA_CONSUMER_ vars as with any other consumer
- this.kafkaConsumer = new KafkaConsumer({ groupId, topic, callEachBatchWhenEmpty: true })
+ this.kafkaConsumer = createKafkaConsumer({ groupId, topic, callEachBatchWhenEmpty: true })
logger.info('🔄', 'Connecting kafka consumer', { groupId, topic })
await this.kafkaConsumer.connect(async (messages) => {
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index ff9fd514ef86..8c23e3955fb8 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -114,6 +114,12 @@ export type CommonConfig = BaseServerConfig & {
CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE: boolean
CONSUMER_REBALANCE_TIMEOUT_MS: number
CONSUMER_AUTO_CREATE_TOPICS: boolean
+ /**
+ * When true, every Kafka consumer in this service uses KafkaConsumerV2; otherwise the
+ * legacy KafkaConsumer (v1) is used. Used by `createKafkaConsumer()` in
+ * `src/kafka/consumer/index.ts`. Will be removed once v1 is deleted.
+ */
+ CONSUMER_USE_V2: boolean
// Kafka
KAFKA_HOSTS: string
@@ -274,6 +280,7 @@ export function getDefaultCommonConfig(): CommonConfig {
CONSUMER_WAIT_FOR_BACKGROUND_TASKS_ON_REBALANCE: false,
CONSUMER_REBALANCE_TIMEOUT_MS: 20_000,
CONSUMER_AUTO_CREATE_TOPICS: true,
+ CONSUMER_USE_V2: false,
// Kafka
KAFKA_HOSTS: 'kafka:9092',
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
index 5ba1b94b3f15..e165fcd976ef 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
@@ -11,7 +11,7 @@ import { Counter } from 'prom-client'
import { execHog } from '../cdp/utils/hog-exec'
import { KAFKA_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
-import { KafkaConsumer } from '../kafka/consumer'
+import { createKafkaConsumer } from '../kafka/consumer'
import { EvaluationManagerService } from '../llm-analytics/services/evaluation-manager.service'
import { TaggerManagerService } from '../llm-analytics/services/tagger-manager.service'
import { TemporalService, TemporalServiceConfig } from '../llm-analytics/services/temporal.service'
@@ -234,7 +234,7 @@ export const startEvaluationScheduler = async (
const evaluationManager = new EvaluationManagerService(deps.postgres, deps.pubSub)
const taggerManager = new TaggerManagerService(deps.postgres, deps.pubSub)
- const kafkaConsumer = new KafkaConsumer({
+ const kafkaConsumer = createKafkaConsumer({
groupId: `${KAFKA_PREFIX}evaluation-scheduler`,
topic: KAFKA_EVENTS_JSON,
})
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
index 709a4ddc5472..7313ef6c4d1c 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.test.ts
@@ -3,7 +3,7 @@ import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/produc
import { DateTime } from 'luxon'
import { Message } from 'node-rdkafka'
-import { KafkaConsumer } from '~/kafka/consumer'
+import { KafkaConsumer } from '~/kafka/consumer/consumer-v1'
import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub, PipelineEvent, Team } from '~/types'
import { closeHub, createHub } from '~/utils/db/hub'
diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
index 56e5bf0f0b9f..4eabb6fe60de 100644
--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts
@@ -7,7 +7,7 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'
import { PluginEvent } from '~/plugin-scaffold'
import { TransformationResult } from '../../cdp/hog-transformations/hog-transformer.service'
-import { KafkaConsumer } from '../../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
import { HealthCheckResult, IngestionLane, PluginServerService } from '../../types'
import { EventIngestionRestrictionManager } from '../../utils/event-ingestion-restrictions'
import { logger } from '../../utils/logger'
@@ -91,7 +91,7 @@ const latestOffsetTimestampGauge = new Gauge({
export class ErrorTrackingConsumer {
protected name = 'error-tracking-consumer'
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
protected pipeline!: BatchPipelineUnwrapper<
{ message: Message },
ErrorTrackingPipelineOutput,
@@ -109,7 +109,7 @@ export class ErrorTrackingConsumer {
private config: ErrorTrackingConsumerOptions,
private deps: ErrorTrackingConsumerDeps
) {
- this.kafkaConsumer = new KafkaConsumer({
+ this.kafkaConsumer = createKafkaConsumer({
groupId: config.groupId,
topic: config.topic,
})
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index b08a9eb736a1..7625464ae08e 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -5,7 +5,7 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'
import { HogTransformerService } from '../cdp/hog-transformations/hog-transformer.service'
import { CommonConfig } from '../common/config'
-import { KafkaConsumer } from '../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../kafka/consumer'
import {
HealthCheckResult,
HealthCheckResultError,
@@ -115,7 +115,7 @@ export class IngestionConsumer {
protected name = 'ingestion-consumer'
protected groupId: string
protected topic: string
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
isStopping = false
public hogTransformer: HogTransformerService
private overflowRedirectService?: OverflowRedirectService
@@ -215,7 +215,7 @@ export class IngestionConsumer {
}
)
- this.kafkaConsumer = new KafkaConsumer({
+ this.kafkaConsumer = createKafkaConsumer({
groupId: this.groupId,
topic: this.topic,
})
diff --git a/nodejs/src/ingestion/ingestion-testing-consumer.ts b/nodejs/src/ingestion/ingestion-testing-consumer.ts
index bcf967a19d5a..4c0c3c5d9c9c 100644
--- a/nodejs/src/ingestion/ingestion-testing-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-testing-consumer.ts
@@ -3,7 +3,7 @@ import { Message } from 'node-rdkafka'
import { instrumentFn } from '~/common/tracing/tracing-utils'
import { KAFKA_INGESTION_WARNINGS } from '../config/kafka-topics'
-import { KafkaConsumer } from '../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../kafka/consumer'
import { KafkaProducerWrapper } from '../kafka/producer'
import { HealthCheckResult, HealthCheckResultError, PluginServerService, PluginsServerConfig } from '../types'
import { logger } from '../utils/logger'
@@ -47,7 +47,7 @@ export class IngestionTestingConsumer {
protected groupId: string
protected topic: string
protected dlqTopic: string
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
isStopping = false
protected kafkaProducer?: KafkaProducerWrapper
public readonly promiseScheduler = new PromiseScheduler()
@@ -75,7 +75,7 @@ export class IngestionTestingConsumer {
this.name = `ingestion-testing-consumer-${this.topic}`
- this.kafkaConsumer = new KafkaConsumer({
+ this.kafkaConsumer = createKafkaConsumer({
groupId: this.groupId,
topic: this.topic,
})
diff --git a/nodejs/src/kafka/consumer.test.ts b/nodejs/src/kafka/consumer/consumer-v1.test.ts
similarity index 99%
rename from nodejs/src/kafka/consumer.test.ts
rename to nodejs/src/kafka/consumer/consumer-v1.test.ts
index 8163f91f08e2..e86e09437459 100644
--- a/nodejs/src/kafka/consumer.test.ts
+++ b/nodejs/src/kafka/consumer/consumer-v1.test.ts
@@ -3,10 +3,10 @@ import { CODES, Message, MessageHeader, KafkaConsumer as RdKafkaConsumer } from
import { defaultConfig } from '~/config/config'
import { createTestEventHeaders } from '~/tests/helpers/event-headers'
-import { delay } from '../utils/utils'
-import { KafkaConsumer, parseEventHeaders, parseKafkaHeaders } from './consumer'
+import { delay } from '../../utils/utils'
+import { KafkaConsumer, parseEventHeaders, parseKafkaHeaders } from './consumer-v1'
-jest.mock('./admin', () => ({
+jest.mock('../admin', () => ({
ensureTopicExists: jest.fn().mockResolvedValue(undefined),
}))
diff --git a/nodejs/src/kafka/consumer.ts b/nodejs/src/kafka/consumer/consumer-v1.ts
similarity index 95%
rename from nodejs/src/kafka/consumer.ts
rename to nodejs/src/kafka/consumer/consumer-v1.ts
index 35a9d6ec10f3..8bbea05acbbf 100644
--- a/nodejs/src/kafka/consumer.ts
+++ b/nodejs/src/kafka/consumer/consumer-v1.ts
@@ -13,7 +13,7 @@ import {
WatermarkOffsets,
} from 'node-rdkafka'
import { hostname } from 'os'
-import { Counter, Gauge, Histogram } from 'prom-client'
+import { Counter, Histogram } from 'prom-client'
import {
EventHeaders,
@@ -28,69 +28,37 @@ import { isTestEnv } from '~/utils/env-utils'
import { parseJSON } from '~/utils/json-parse'
import { normalizeSessionId } from '~/utils/utils'
-import { instrumentFn } from '../common/tracing/tracing-utils'
-import { defaultConfig } from '../config/config'
-import { logger } from '../utils/logger'
-import { captureException } from '../utils/posthog'
-import { retryIfRetriable } from '../utils/retries'
-import { promisifyCallback } from '../utils/utils'
-import { ensureTopicExists } from './admin'
-import { getKafkaConfigFromEnv } from './config'
-import { parseBrokerStatistics, trackBrokerMetrics } from './kafka-client-metrics'
+import { instrumentFn } from '../../common/tracing/tracing-utils'
+import { defaultConfig } from '../../config/config'
+import { logger } from '../../utils/logger'
+import { captureException } from '../../utils/posthog'
+import { retryIfRetriable } from '../../utils/retries'
+import { promisifyCallback } from '../../utils/utils'
+import { ensureTopicExists } from '../admin'
+import { getKafkaConfigFromEnv } from '../config'
+import { parseBrokerStatistics, trackBrokerMetrics } from '../kafka-client-metrics'
+import {
+ consumedBatchBackgroundDuration,
+ consumedBatchBackpressureDuration,
+ consumedBatchDuration,
+ consumerBatchUtilization as gaugeBatchUtilization,
+ consumerBatchSize as histogramKafkaBatchSize,
+ consumerBatchSizeKb as histogramKafkaBatchSizeKb,
+ kafkaConsumerAssignment,
+} from './metrics'
const DEFAULT_BATCH_TIMEOUT_MS = 500
const SLOW_BATCH_PROCESSING_LOG_THRESHOLD_MS = 10000
const MAX_HEALTH_HEARTBEAT_INTERVAL_MS = 60_000
const STATISTICS_INTERVAL_MS = 5000 // Emit internal metrics every 5 seconds
-const kafkaConsumerAssignment = new Gauge({
- name: 'kafka_consumer_assignment',
- help: 'Kafka consumer partition assignment status',
- labelNames: ['topic_name', 'partition_id', 'pod', 'group_id'],
-})
-
const kafkaHeaderStatusCounter = new Counter({
name: 'kafka_header_status_total',
help: 'Count of events by header name and presence status',
labelNames: ['header', 'status'],
})
-const consumedBatchDuration = new Histogram({
- name: 'consumed_batch_duration_ms',
- help: 'Main loop consumer batch processing duration in ms',
- labelNames: ['topic', 'groupId'],
-})
-
-const consumedBatchBackgroundDuration = new Histogram({
- name: 'consumed_batch_background_duration_ms',
- help: 'Background task processing duration in ms',
- labelNames: ['topic', 'groupId'],
-})
-
-const consumedBatchBackpressureDuration = new Histogram({
- name: 'consumed_batch_backpressure_duration_ms',
- help: 'Time spent waiting for background work to finish due to backpressure',
- labelNames: ['topic', 'groupId'],
-})
-
-const gaugeBatchUtilization = new Gauge({
- name: 'consumer_batch_utilization',
- help: 'Indicates how big batches are we are processing compared to the max batch size. Useful as a scaling metric',
- labelNames: ['groupId'],
-})
-
-const histogramKafkaBatchSize = new Histogram({
- name: 'consumer_batch_size',
- help: 'The size of the batches we are receiving from Kafka',
- buckets: [0, 50, 100, 250, 500, 750, 1000, 1500, 2000, 3000, Infinity],
-})
-
-const histogramKafkaBatchSizeKb = new Histogram({
- name: 'consumer_batch_size_kb',
- help: 'The size in kb of the batches we are receiving from Kafka',
- buckets: [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity],
-})
-
+// v1-only metrics — v2 doesn't surface these. Kept here until v1 is deleted.
const histogramKafkaConsumeInterval = new Histogram({
name: 'kafka_consume_interval_ms',
help: 'Time elapsed between Kafka consume calls',
diff --git a/nodejs/src/kafka/consumer/consumer-v2.integration.test.ts b/nodejs/src/kafka/consumer/consumer-v2.integration.test.ts
new file mode 100644
index 000000000000..110c2bf4d075
--- /dev/null
+++ b/nodejs/src/kafka/consumer/consumer-v2.integration.test.ts
@@ -0,0 +1,425 @@
+import { AdminClient, LibrdKafkaError, Message } from 'node-rdkafka'
+import { randomUUID } from 'node:crypto'
+
+import { delay } from '../../utils/utils'
+import { KafkaProducerWrapper } from '../producer'
+import { KafkaConsumerV2 } from './consumer-v2'
+
+/**
+ * Multi-consumer integration tests for KafkaConsumerV2.
+ *
+ * Requires a running Kafka/Redpanda broker reachable at KAFKA_HOSTS (default: kafka:9092).
+ * Each test creates a unique topic, runs consumers, asserts on a shared "ledger" of every
+ * (offset, partition, consumerId, batchSeenAt) seen, then deletes the topic.
+ *
+ * The tests are deliberately tolerant of bounded duplicates during rebalance — the property
+ * we're validating is "no message is lost AND no partition is stuck", not "exactly once".
+ */
+
+jest.setTimeout(30_000)
+// Real-world per-step timings (from consumer-v2.profile.test.ts):
+// createTopic ~250ms consumerConnect ~15ms connect→ASSIGN ~15ms
+// producerConnect ~5ms timeToFirstMsg ~50ms disconnect ~65ms
+// Tests size their waits off these numbers — generous but not absurd.
+
+const KAFKA_HOSTS = process.env.KAFKA_HOSTS ?? 'kafka:9092'
+const KAFKA_CONFIG = { 'metadata.broker.list': KAFKA_HOSTS }
+
+type LedgerEntry = {
+ consumerId: string
+ topic: string
+ partition: number
+ offset: number
+ seenAt: number
+}
+
+class Ledger {
+ public entries: LedgerEntry[] = []
+
+ record(consumerId: string, m: Message): void {
+ this.entries.push({
+ consumerId,
+ topic: m.topic,
+ partition: m.partition,
+ offset: m.offset,
+ seenAt: Date.now(),
+ })
+ }
+
+ /** Total unique (partition, offset) pairs seen. */
+ uniqueCount(): number {
+ const seen = new Set<string>()
+ for (const e of this.entries) {
+ seen.add(`${e.partition}:${e.offset}`)
+ }
+ return seen.size
+ }
+
+ /** Number of entries that are duplicates (same (partition, offset) seen more than once). */
+ duplicateCount(): number {
+ const counts = new Map<string, number>()
+ for (const e of this.entries) {
+ const k = `${e.partition}:${e.offset}`
+ counts.set(k, (counts.get(k) ?? 0) + 1)
+ }
+ let dupes = 0
+ for (const c of counts.values()) {
+ if (c > 1) {
+ dupes += c - 1
+ }
+ }
+ return dupes
+ }
+
+ /** Highest offset seen per partition. */
+ maxOffsetByPartition(): Map<number, number> {
+ const max = new Map<number, number>()
+ for (const e of this.entries) {
+ const cur = max.get(e.partition)
+ if (cur === undefined || e.offset > cur) {
+ max.set(e.partition, e.offset)
+ }
+ }
+ return max
+ }
+
+ /** Snapshot of the consumer that owned each (partition, offset). */
+ ownership(): Map<string, string> {
+ const o = new Map<string, string>()
+ for (const e of this.entries) {
+ o.set(`${e.partition}:${e.offset}`, e.consumerId)
+ }
+ return o
+ }
+}
+
+async function createTopic(topic: string, numPartitions: number): Promise<void> {
+ const client = AdminClient.create(KAFKA_CONFIG)
+ await new Promise<void>((resolve, reject) => {
+ client.createTopic(
+ { topic, num_partitions: numPartitions, replication_factor: 1 },
+ 10_000,
+ (err: LibrdKafkaError) => {
+ if (err && err.message && !/already exists/i.test(err.message)) {
+ reject(err)
+ } else {
+ resolve()
+ }
+ }
+ )
+ })
+ client.disconnect()
+}
+
+async function deleteTopic(topic: string): Promise<void> {
+ const client = AdminClient.create(KAFKA_CONFIG)
+ await new Promise<void>((resolve) => {
+ client.deleteTopic(topic, 10_000, () => resolve())
+ })
+ client.disconnect()
+}
+
+async function produceMessages(producer: KafkaProducerWrapper, topic: string, count: number): Promise<void> {
+ const promises: Promise<void>[] = []
+ for (let i = 0; i < count; i++) {
+ promises.push(
+ producer.produce({
+ topic,
+ key: `k${i}`,
+ value: Buffer.from(`v${i}`),
+ })
+ )
+ }
+ await Promise.all(promises)
+}
+
+function makeConsumer(
+ consumerId: string,
+ groupId: string,
+ topic: string,
+ eachBatch: (consumerId: string, msgs: Message[]) => Promise<void>
+): KafkaConsumerV2 {
+ const consumer = new KafkaConsumerV2({ groupId, topic, batchTimeoutMs: 50 }, {
+ 'metadata.broker.list': KAFKA_HOSTS,
+ 'session.timeout.ms': 10_000,
+ } as Record<string, unknown>)
+ void consumer
+ .connect(async (msgs: Message[]) => eachBatch(consumerId, msgs))
+ .catch((err: unknown) => {
+ // Surface the real cause instead of letting waitForAssignments time out generically.
+ throw new Error(`Consumer ${consumerId} failed to connect: ${String(err)}`)
+ })
+ return consumer
+}
+
+/**
+ * Wait until each consumer has at least one partition assigned. This is the actual signal
+ * that the group has stabilized — not a fixed delay.
+ */
+async function waitForAssignments(consumers: KafkaConsumerV2[], timeoutMs = 10_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ if (consumers.every((c) => c.assignments().length > 0)) {
+ return
+ }
+ await delay(20)
+ }
+ throw new Error(`waitForAssignments timed out after ${timeoutMs}ms`)
+}
+
+async function waitFor(predicate: () => boolean, timeoutMs: number, pollMs = 20): Promise<void> {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ if (predicate()) {
+ return
+ }
+ await delay(pollMs)
+ }
+ throw new Error(`waitFor timed out after ${timeoutMs}ms`)
+}
+
+describe('KafkaConsumerV2 (integration)', () => {
+ let producer: KafkaProducerWrapper
+
+ beforeAll(async () => {
+ producer = await KafkaProducerWrapper.createWithConfig(undefined, {
+ 'metadata.broker.list': KAFKA_HOSTS,
+ } as Record<string, unknown>)
+ })
+
+ afterAll(async () => {
+ await producer.disconnect()
+ })
+
+ it('single consumer, single partition: all messages consumed exactly once', async () => {
+ const topic = `v2_int_single_${randomUUID()}`
+ const groupId = `v2-int-single-${randomUUID()}`
+ await createTopic(topic, 1)
+
+ try {
+ const ledger = new Ledger()
+ const consumer = makeConsumer('c1', groupId, topic, async (id, msgs) => {
+ for (const m of msgs) {
+ ledger.record(id, m)
+ }
+ await delay(1)
+ })
+
+ await waitForAssignments([consumer])
+ await produceMessages(producer, topic, 100)
+
+ await waitFor(() => ledger.uniqueCount() >= 100, 8_000)
+ await consumer.disconnect()
+
+ expect(ledger.uniqueCount()).toBe(100)
+ expect(ledger.duplicateCount()).toBe(0)
+ } finally {
+ await deleteTopic(topic)
+ }
+ })
+
+ it('three consumers, six partitions: messages spread across consumers, no duplicates in steady state', async () => {
+ const topic = `v2_int_three_${randomUUID()}`
+ const groupId = `v2-int-three-${randomUUID()}`
+ await createTopic(topic, 6)
+
+ try {
+ const ledger = new Ledger()
+ const each = async (id: string, msgs: Message[]) => {
+ for (const m of msgs) {
+ ledger.record(id, m)
+ }
+ await delay(1)
+ }
+ const c1 = makeConsumer('c1', groupId, topic, each)
+ const c2 = makeConsumer('c2', groupId, topic, each)
+ const c3 = makeConsumer('c3', groupId, topic, each)
+
+ // Wait for all 3 to actually have partitions assigned, not a fixed delay.
+ await waitForAssignments([c1, c2, c3])
+ await produceMessages(producer, topic, 1000)
+
+ await waitFor(() => ledger.uniqueCount() >= 1000, 15_000)
+
+ await Promise.all([c1.disconnect(), c2.disconnect(), c3.disconnect()])
+
+ expect(ledger.uniqueCount()).toBe(1000)
+ // In steady state with no rebalance during processing, duplicates should be zero or tiny.
+ expect(ledger.duplicateCount()).toBeLessThan(20)
+
+ // Every consumer should have processed something (load was actually distributed).
+ const consumerIds = new Set(ledger.entries.map((e) => e.consumerId))
+ expect(consumerIds.size).toBeGreaterThanOrEqual(2) // at least 2 of 3 saw messages
+ } finally {
+ await deleteTopic(topic)
+ }
+ })
+
+ it('graceful rebalance mid-flight: surviving consumer takes over with bounded duplicates', async () => {
+ const topic = `v2_int_graceful_${randomUUID()}`
+ const groupId = `v2-int-graceful-${randomUUID()}`
+ await createTopic(topic, 4)
+
+ try {
+ const ledger = new Ledger()
+ const each = async (id: string, msgs: Message[]) => {
+ for (const m of msgs) {
+ ledger.record(id, m)
+ }
+ await delay(1)
+ }
+ const c1 = makeConsumer('c1', groupId, topic, each)
+ const c2 = makeConsumer('c2', groupId, topic, each)
+
+ await waitForAssignments([c1, c2])
+ await produceMessages(producer, topic, 500)
+
+ // Wait until c1 has seen some messages, then disconnect it gracefully.
+ await waitFor(() => ledger.entries.filter((e) => e.consumerId === 'c1').length >= 50, 8_000)
+ await c1.disconnect()
+
+ // c2 should pick up everything that's left.
+ await waitFor(() => ledger.uniqueCount() >= 500, 15_000)
+ await c2.disconnect()
+
+ expect(ledger.uniqueCount()).toBe(500)
+ // Bounded duplicates: only messages whose offsets weren't stored before c1 drained.
+ // With proper drain semantics this should be very small.
+ expect(ledger.duplicateCount()).toBeLessThan(50)
+ } finally {
+ await deleteTopic(topic)
+ }
+ })
+
+ it('add consumer mid-flight (H1 scenario): cooperative rebalance, no message lost', async () => {
+ const topic = `v2_int_h1_${randomUUID()}`
+ const groupId = `v2-int-h1-${randomUUID()}`
+ await createTopic(topic, 4)
+
+ try {
+ const ledger = new Ledger()
+ const each = async (id: string, msgs: Message[]) => {
+ for (const m of msgs) {
+ ledger.record(id, m)
+ }
+ await delay(1)
+ }
+ const c1 = makeConsumer('c1', groupId, topic, each)
+ await waitForAssignments([c1])
+
+ // Produce in two waves so c2 has work to do after the rebalance — without this
+ // c1 would consume everything in <100ms before c2 finishes joining.
+ await produceMessages(producer, topic, 200)
+ await waitFor(() => ledger.entries.filter((e) => e.consumerId === 'c1').length >= 100, 8_000)
+
+ // Add a second consumer mid-flight → triggers a rebalance.
+ const c2 = makeConsumer('c2', groupId, topic, each)
+ await waitForAssignments([c1, c2])
+
+ await produceMessages(producer, topic, 600)
+ await waitFor(() => ledger.uniqueCount() >= 800, 15_000)
+ await Promise.all([c1.disconnect(), c2.disconnect()])
+
+ expect(ledger.uniqueCount()).toBe(800)
+ expect(ledger.duplicateCount()).toBeLessThan(50)
+ // c2 should have processed at least some of the second wave.
+ expect(ledger.entries.some((e) => e.consumerId === 'c2')).toBe(true)
+ } finally {
+ await deleteTopic(topic)
+ }
+ })
+
+ it('slow background task during rebalance (H3 scenario): drain awaits completion before unassign', async () => {
+ const topic = `v2_int_h3_${randomUUID()}`
+ const groupId = `v2-int-h3-${randomUUID()}`
+ await createTopic(topic, 4)
+
+ try {
+ const ledger = new Ledger()
+ // eachBatch returns a backgroundTask that takes 200ms.
+ const each = (id: string, msgs: Message[]): Promise<{ backgroundTask: Promise<void> }> => {
+ for (const m of msgs) {
+ ledger.record(id, m)
+ }
+ return Promise.resolve({ backgroundTask: delay(200) })
+ }
+
+ // Wrapper to satisfy the eachBatch signature
+ const wrap = (id: string) => async (msgs: Message[]) => each(id, msgs)
+ const c1 = new KafkaConsumerV2({ groupId, topic, batchTimeoutMs: 100 }, {
+ 'metadata.broker.list': KAFKA_HOSTS,
+ 'session.timeout.ms': 10_000,
+ } as Record<string, unknown>)
+ void c1.connect(wrap('c1')).catch((err: unknown) => {
+ throw new Error(`Consumer c1 failed to connect: ${String(err)}`)
+ })
+
+ const c2 = new KafkaConsumerV2({ groupId, topic, batchTimeoutMs: 100 }, {
+ 'metadata.broker.list': KAFKA_HOSTS,
+ 'session.timeout.ms': 10_000,
+ } as Record<string, unknown>)
+ void c2.connect(wrap('c2')).catch((err: unknown) => {
+ throw new Error(`Consumer c2 failed to connect: ${String(err)}`)
+ })
+
+ await waitForAssignments([c1, c2])
+ await produceMessages(producer, topic, 300)
+ await waitFor(() => ledger.entries.filter((e) => e.consumerId === 'c1').length >= 50, 8_000)
+
+ // Disconnect c1 gracefully — should drain its in-flight 200ms task before unassigning.
+ await c1.disconnect()
+
+ await waitFor(() => ledger.uniqueCount() >= 300, 15_000)
+ await c2.disconnect()
+
+ expect(ledger.uniqueCount()).toBe(300)
+ // Without the H3 race, duplicates should be small (only messages whose offsets the
+ // graceful disconnect couldn't commit because partitions were already revoked).
+ expect(ledger.duplicateCount()).toBeLessThan(30)
+ } finally {
+ await deleteTopic(topic)
+ }
+ })
+
+ it('disconnect with in-flight task: disconnect awaits the task, offsets are committed', async () => {
+ const topic = `v2_int_disconnect_${randomUUID()}`
+ const groupId = `v2-int-disconnect-${randomUUID()}`
+ await createTopic(topic, 1)
+
+ try {
+ const ledger = new Ledger()
+ let taskStartedAt = 0
+ let taskFinishedAt = 0
+ const consumer = new KafkaConsumerV2({ groupId, topic, batchTimeoutMs: 100 }, {
+ 'metadata.broker.list': KAFKA_HOSTS,
+ 'session.timeout.ms': 10_000,
+ } as Record<string, unknown>)
+ await consumer.connect((msgs) => {
+ for (const m of msgs) {
+ ledger.record('c1', m)
+ }
+ taskStartedAt = Date.now()
+ return Promise.resolve({
+ backgroundTask: delay(800).then(() => {
+ taskFinishedAt = Date.now()
+ }),
+ })
+ })
+
+ await waitForAssignments([consumer])
+ await produceMessages(producer, topic, 5)
+ await waitFor(() => ledger.uniqueCount() >= 5, 5_000)
+
+ const disconnectStart = Date.now()
+ await consumer.disconnect()
+ const disconnectDuration = Date.now() - disconnectStart
+
+ // disconnect must have awaited the in-flight task.
+ expect(taskFinishedAt).toBeGreaterThan(0)
+ // disconnect should not be instantaneous if there was work to drain.
+ expect(disconnectDuration).toBeGreaterThan(taskFinishedAt - taskStartedAt - 100)
+ } finally {
+ await deleteTopic(topic)
+ }
+ })
+})
diff --git a/nodejs/src/kafka/consumer/consumer-v2.test.ts b/nodejs/src/kafka/consumer/consumer-v2.test.ts
new file mode 100644
index 000000000000..0655ae0d3760
--- /dev/null
+++ b/nodejs/src/kafka/consumer/consumer-v2.test.ts
@@ -0,0 +1,625 @@
+import { CODES, Message, KafkaConsumer as RdKafkaConsumer } from 'node-rdkafka'
+
+import { captureException } from '../../utils/posthog'
+import { delay } from '../../utils/utils'
+import { KafkaConsumerV2 } from './consumer-v2'
+
+jest.mock('../admin', () => ({ ensureTopicExists: jest.fn().mockResolvedValue(undefined) }))
+
+// Spy on captureException to assert that the IDLE-keepalive invariant fires when violated.
+jest.mock('../../utils/posthog', () => ({
+ captureException: jest.fn(),
+}))
+
+jest.mock('node-rdkafka', () => ({
+ KafkaConsumer: jest.fn(),
+ CODES: {
+ ERRORS: {
+ ERR__REVOKE_PARTITIONS: 'ERR__REVOKE_PARTITIONS',
+ ERR__ASSIGN_PARTITIONS: 'ERR__ASSIGN_PARTITIONS',
+ },
+ },
+}))
+
+const createMessage = (m: Partial<Message> = {}): Message => ({
+ value: Buffer.from('test-value'),
+ key: Buffer.from('test-key'),
+ offset: 1,
+ partition: 0,
+ topic: 'test-topic',
+ size: 10,
+ ...m,
+})
+
+jest.setTimeout(15000)
+
+const activePromiseResolvers: Array<() => void> = []
+
+const triggerablePromise = <T = unknown>(): {
+ promise: Promise<T>
+ resolve: (value?: T) => void
+ reject: (reason?: unknown) => void
+} => {
+ const result = {
+ promise: null as unknown as Promise<T>,
+ resolve: () => {},
+ reject: () => {},
+ } as {
+ promise: Promise<T>
+ resolve: (value?: T) => void
+ reject: (reason?: unknown) => void
+ }
+
+ result.promise = new Promise((resolve, reject) => {
+ const wrappedResolve = (value?: T) => {
+ const i = activePromiseResolvers.indexOf(wrappedResolve)
+ if (i > -1) {
+ activePromiseResolvers.splice(i, 1)
+ }
+ resolve(value as T)
+ }
+ result.resolve = wrappedResolve
+ result.reject = (reason?: unknown) => {
+ const i = activePromiseResolvers.indexOf(wrappedResolve)
+ if (i > -1) {
+ activePromiseResolvers.splice(i, 1)
+ }
+ reject(reason)
+ }
+ activePromiseResolvers.push(wrappedResolve)
+ })
+ return result
+}
+
+describe('KafkaConsumerV2', () => {
+ let consumer: KafkaConsumerV2
+ let mockRdKafka: jest.Mocked<RdKafkaConsumer>
+ let consumeCallback: ((error: Error | null, messages: Message[]) => void) | undefined
+ let registeredRebalanceCb: ((err: any, partitions: any[]) => void) | undefined
+
+ beforeEach(() => {
+ consumeCallback = undefined
+ registeredRebalanceCb = undefined
+ ;(captureException as jest.Mock).mockClear()
+
+ const mockInstance: any = {
+ connect: jest.fn().mockImplementation((_: unknown, cb: (err: Error | null) => void) => cb(null)),
+ subscribe: jest.fn(),
+ consume: jest.fn().mockImplementation((_: unknown, cb: any) => {
+ consumeCallback = cb
+ }),
+ disconnect: jest.fn().mockImplementation((cb: (err: Error | null) => void) => cb(null)),
+ isConnected: jest.fn().mockReturnValue(true),
+ on: jest.fn(),
+ assignments: jest.fn().mockReturnValue([]),
+ offsetsStore: jest.fn(),
+ setDefaultConsumeTimeout: jest.fn(),
+ incrementalUnassign: jest.fn(),
+ incrementalAssign: jest.fn(),
+ assign: jest.fn(),
+ unassign: jest.fn(),
+ rebalanceProtocol: jest.fn().mockReturnValue('COOPERATIVE'),
+ }
+
+ // Capture the rebalance callback the consumer registers via rdKafkaConfig
+ const RdKafkaCtor = jest.mocked(require('node-rdkafka').KafkaConsumer)
+ RdKafkaCtor.mockImplementation((config: any) => {
+ registeredRebalanceCb = config.rebalance_cb
+ return mockInstance
+ })
+
+ consumer = new KafkaConsumerV2({ groupId: 'test-group', topic: 'test-topic' })
+ mockRdKafka = mockInstance
+ })
+
+ afterEach(async () => {
+ // Drop any in-flight tasks before disconnect to avoid 60s timeout waits.
+ if (consumer && (consumer as any).inFlight) {
+ ;(consumer as any).inFlight = []
+ }
+ while (activePromiseResolvers.length > 0) {
+ activePromiseResolvers[0]()
+ }
+ if (consumer) {
+ const p = consumer.disconnect()
+ // Release any pending consume callback so the loop can exit.
+ if (consumeCallback) {
+ consumeCallback(null, [])
+ }
+ await p
+ }
+ })
+
+ /** Drive the consumer through ASSIGN so it transitions to CONSUMING. */
+ const startConsuming = async (eachBatch: jest.Mock, partitions = [{ topic: 'test-topic', partition: 0 }]) => {
+ await consumer.connect(eachBatch)
+ registeredRebalanceCb!({ code: CODES.ERRORS.ERR__ASSIGN_PARTITIONS } as any, partitions)
+ // The loop is currently inside the IDLE keepalive consume(1, cb). Release it with
+ // an empty batch so the loop processes ASSIGN and arms a fresh consume() in CONSUMING.
+ if (consumeCallback) {
+ const cb = consumeCallback
+ consumeCallback = undefined
+ cb(null, [])
+ }
+ await delay(5)
+ }
+
+ /** Release the in-flight consume(), if any, with empty messages so the loop can iterate. */
+ const releaseConsume = () => {
+ if (consumeCallback) {
+ const cb = consumeCallback
+ consumeCallback = undefined
+ cb(null, [])
+ }
+ }
+
+ const fireRevoke = (partitions = [{ topic: 'test-topic', partition: 0 }]) => {
+ registeredRebalanceCb!({ code: CODES.ERRORS.ERR__REVOKE_PARTITIONS } as any, partitions)
+ // librdkafka delivers REVOKE on the same thread as consume() returns; simulate that.
+ releaseConsume()
+ }
+
+ const fireAssign = (partitions = [{ topic: 'test-topic', partition: 0 }]) => {
+ registeredRebalanceCb!({ code: CODES.ERRORS.ERR__ASSIGN_PARTITIONS } as any, partitions)
+ releaseConsume()
+ }
+
+ /** Deliver a batch + a controllable backgroundTask. Resolves when the task is in-flight. */
+ const dispatchBatch = async (
+ eachBatch: jest.Mock,
+ messages: Message[],
+ backgroundTask?: Promise<unknown>
+ ): Promise<void> => {
+ eachBatch.mockImplementationOnce(() =>
+ backgroundTask !== undefined ? Promise.resolve({ backgroundTask }) : Promise.resolve({})
+ )
+ consumeCallback!(null, messages)
+ await delay(2)
+ }
+
+ it('Smoke: connect → consume → eachBatch → offsets stored', async () => {
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ consumeCallback!(null, [createMessage({ offset: 1, partition: 0 })])
+ await delay(5)
+
+ expect(eachBatch).toHaveBeenCalledWith([createMessage({ offset: 1, partition: 0 })])
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0, offset: 2 }])
+ })
+
+ it('Backpressure: pushing > maxBackgroundTasks blocks until oldest settles', async () => {
+ ;(consumer as any).maxBackgroundTasks = 2
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const p1 = triggerablePromise()
+ const p2 = triggerablePromise()
+ const p3 = triggerablePromise()
+
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], p1.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], p2.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 3, partition: 0 })], p3.promise)
+ await delay(2)
+
+ // Loop is blocked on backpressure; consume() should NOT have been called for batch 4.
+ const callsBefore = mockRdKafka.consume.mock.calls.length
+ p1.resolve()
+ await delay(5)
+ expect(mockRdKafka.consume.mock.calls.length).toBeGreaterThan(callsBefore)
+ })
+
+ it('REVOKE drain: incrementalUnassign called only after every settled completes', async () => {
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const p1 = triggerablePromise()
+ const p2 = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], p1.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], p2.promise)
+
+ fireRevoke()
+ await delay(5)
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+
+ p1.resolve()
+ await delay(5)
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+
+ p2.resolve()
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+ })
+
+ it('H1 regression: task pushed during the rebalance window is awaited before unassign', async () => {
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const p1 = triggerablePromise()
+ const p2 = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], p1.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], p2.promise)
+
+ // Set up a third batch where eachBatch is in flight when the rebalance fires.
+ const p3 = triggerablePromise()
+ const eachBatchGate = triggerablePromise()
+ eachBatch.mockImplementationOnce(async () => {
+ await eachBatchGate.promise
+ return { backgroundTask: p3.promise }
+ })
+ consumeCallback!(null, [createMessage({ offset: 3, partition: 0 })])
+ await delay(2)
+
+ // Fire revoke while eachBatch is still awaiting the gate.
+ fireRevoke()
+ await delay(2)
+
+ // Release eachBatch — even though we're now DRAINING, the task is tracked and drainAll
+ // awaits its settled promise. (This is the H1 fix: tasks pushed during the rebalance
+ // window are NOT excluded from drain.)
+ eachBatchGate.resolve()
+ await delay(5)
+
+ // Validate the fix mechanism, not just the outcome: all 3 tasks are tracked in inFlight,
+ // including t3 which was dispatched AFTER REVOKE arrived.
+ expect((consumer as any).inFlight.length).toBe(3)
+
+ // Resolve t1 + t2 only. t3 still pending.
+ p1.resolve()
+ p2.resolve()
+ await delay(10)
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+
+ // Resolving t3 unblocks drain.
+ p3.resolve()
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+ })
+
+ it('H2 regression: stale tasks across generations skip storeOffsets and never trigger unassign', async () => {
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const slow = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], slow.promise)
+
+ // Fire revoke; drain begins.
+ fireRevoke()
+ await delay(2)
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+
+ // Resolve slow. Drain completes, unassign fires synchronously inside the loop.
+ slow.resolve()
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledTimes(1)
+ // The slow task crossed the rebalance generation — its storeOffsets MUST have been
+ // skipped (generation-tag mechanism). Validates the H2 protection directly.
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+
+ // Snapshot offsetsStore + unassign call counts before the reassign so we can assert
+ // nothing further happens once we re-acquire the partition.
+ const offsetCallsBeforeReassign = mockRdKafka.offsetsStore.mock.calls.length
+ mockRdKafka.incrementalUnassign.mockClear()
+
+ // Now simulate cooperative-sticky reassign of the same partition.
+ fireAssign()
+ await delay(5)
+ expect(mockRdKafka.incrementalAssign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+
+ // No deferred .then armed — no bogus unassign and no surprise offset writes against
+ // the just-reassigned partition.
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+ expect(mockRdKafka.offsetsStore.mock.calls.length).toBe(offsetCallsBeforeReassign)
+ })
+
+ it('H3 regression: out-of-order task completion — drain awaits ALL settled before unassign', async () => {
+ // The v1 H3 race was: drain awaited t.promise (raw), so the late task's storeOffsets
+ // could fire AFTER incrementalUnassign. v2 fixes this two ways:
+ // (a) drain awaits the post-storeOffsets `settled` chain, not the raw task; and
+ // (b) the generation tag in trackTask makes any storeOffsets call during DRAINING
+ // a no-op (see the "Generation tag" test).
+ //
+ // (b) means we can't meaningfully assert offsetsStore-vs-unassign ordering during a
+ // REVOKE — storeOffsets simply never runs in that path. So this test verifies the
+ // (a) property directly: with two tasks resolving out of order, drainAll awaits both
+ // settled callbacks before incrementalUnassign fires. If drain awaited only `raw`,
+ // it could fire before the second task settled.
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const p1 = triggerablePromise()
+ const p2 = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], p1.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], p2.promise)
+
+ fireRevoke()
+ await delay(2)
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+
+ // Resolve out of order — t2 finishes first.
+ p2.resolve()
+ await delay(10)
+ // Drain still awaits t1's settled — unassign must NOT have fired yet.
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+
+ // Now t1 settles → drain completes → unassign fires.
+ p1.resolve()
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+ })
+
+ it('Drain timeout: never-settling task is force-released after drainTimeoutMs', async () => {
+ ;(consumer as any).drainTimeoutMs = 50
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const stuck = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], stuck.promise)
+
+ fireRevoke()
+ await delay(120)
+
+ // Drain timed out; loop proceeded with unassign.
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()
+ })
+
+ it('ASSIGN after REVOKE: state transitions back to CONSUMING and resumes fetching', async () => {
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ fireRevoke()
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()
+
+ const callsBeforeAssign = mockRdKafka.consume.mock.calls.length
+ fireAssign([{ topic: 'test-topic', partition: 1 }])
+ await delay(10)
+ expect(mockRdKafka.incrementalAssign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 1 }])
+ // After ASSIGN, the loop transitions back to CONSUMING and immediately calls consume().
+ expect(mockRdKafka.consume.mock.calls.length).toBeGreaterThan(callsBeforeAssign)
+ })
+
+ it('REVOKE without follow-up ASSIGN: loop stays alive and keeps polling', async () => {
+ // Validates that if librdkafka revokes our partitions and never re-assigns (e.g. the
+ // group went down to one consumer), the loop doesn't wedge — it keeps calling
+ // consume() to drive heartbeats and the next rebalance.
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ fireRevoke()
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()
+
+ // No fireAssign() — drive several polls.
+ const callsBefore = mockRdKafka.consume.mock.calls.length
+ for (let i = 0; i < 5; i++) {
+ if (consumeCallback) {
+ const cb = consumeCallback
+ consumeCallback = undefined
+ cb(null, [])
+ }
+ await delay(5)
+ }
+ expect(mockRdKafka.consume.mock.calls.length).toBeGreaterThan(callsBefore)
+ // Loop still running — not crashed.
+ expect((consumer as any).running).toBe(true)
+ })
+
+ it('Sticky reassign roundtrip: REVOKE [P0] → ASSIGN [P0] back, no stuck or duplicate work', async () => {
+ // Validates the cooperative-sticky case where the broker takes our partition then
+ // gives it right back. v1's H2 bug fired here because of a stale deferred .then;
+ // v2's drain-inside-loop design must handle this cleanly.
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ fireRevoke([{ topic: 'test-topic', partition: 0 }])
+ await delay(20)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+
+ const unassignCallsBeforeReassign = mockRdKafka.incrementalUnassign.mock.calls.length
+
+ fireAssign([{ topic: 'test-topic', partition: 0 }])
+ await delay(20)
+ expect(mockRdKafka.incrementalAssign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+
+ // Critical: no spurious unassign of the just-reassigned partition.
+ expect(mockRdKafka.incrementalUnassign.mock.calls.length).toBe(unassignCallsBeforeReassign)
+ })
+
+ it('Incremental ASSIGN: a second ASSIGN with new partitions extends the assignment', async () => {
+ // With cooperative-sticky, a rebalance can deliver an ASSIGN for new partitions
+ // without first revoking the existing ones. The handler must call
+ // incrementalAssign() so existing partitions stay assigned.
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch, [{ topic: 'test-topic', partition: 0 }])
+
+ // Now a second ASSIGN comes in for partition 1 (cooperative add).
+ fireAssign([{ topic: 'test-topic', partition: 1 }])
+ await delay(10)
+
+ // incrementalAssign was called twice — once per ASSIGN event — never assign().
+ expect(mockRdKafka.incrementalAssign).toHaveBeenNthCalledWith(1, [{ topic: 'test-topic', partition: 0 }])
+ expect(mockRdKafka.incrementalAssign).toHaveBeenNthCalledWith(2, [{ topic: 'test-topic', partition: 1 }])
+ expect(mockRdKafka.assign).not.toHaveBeenCalled()
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+ })
+
+ it('Partial REVOKE: only the revoked partition is unassigned, drain awaits in-flight task', async () => {
+ // Cooperative-sticky drops a subset; we await the in-flight task before
+ // unassigning, and only call incrementalUnassign for the revoked partition.
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch, [
+ { topic: 'test-topic', partition: 0 },
+ { topic: 'test-topic', partition: 1 },
+ ])
+
+ const p1 = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], p1.promise)
+
+ fireRevoke([{ topic: 'test-topic', partition: 1 }])
+ await delay(5)
+
+ // Drain blocks unassign until the in-flight task settles.
+ expect(mockRdKafka.incrementalUnassign).not.toHaveBeenCalled()
+ p1.resolve()
+ await delay(20)
+
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 1 }])
+ expect((consumer as any).running).toBe(true)
+ })
+
+ it('Disconnect drains in-flight tasks before tearing down', async () => {
+ ;(consumer as any).maxBackgroundTasks = 5
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const slow = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], slow.promise)
+
+ const disconnectPromise = consumer.disconnect()
+
+ // Force the in-flight consume to release so the loop can observe state=STOPPED.
+ if (consumeCallback) {
+ consumeCallback(null, [])
+ }
+
+ // disconnect should be pending until slow resolves.
+ await delay(20)
+ expect(mockRdKafka.disconnect).not.toHaveBeenCalled()
+
+ slow.resolve()
+ await disconnectPromise
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0, offset: 2 }])
+ expect(mockRdKafka.disconnect).toHaveBeenCalled()
+ // Avoid double-disconnect in afterEach.
+ consumer = undefined as unknown as KafkaConsumerV2
+ })
+
+ it('eachBatch returning void: offsets still stored', async () => {
+ const eachBatch = jest.fn(() => Promise.resolve())
+ await startConsuming(eachBatch)
+
+ consumeCallback!(null, [createMessage({ offset: 5, partition: 0 })])
+ await delay(5)
+
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0, offset: 6 }])
+ })
+
+ it('eachBatch throwing: propagates the error and kills the loop (matches v1)', async () => {
+ // v2 deliberately does NOT catch eachBatch errors. The loop crashes, connect()'s
+ // .catch() re-throws to the orchestrator, the pod restarts, and the batch is
+ // re-read from the last committed offset (at-least-once preserved).
+ const error = new Error('boom')
+ const eachBatch = jest.fn().mockRejectedValue(error)
+
+ // Capture the loop promise so we can assert it rejects with our error.
+ await consumer.connect(eachBatch)
+ const loopDone = (consumer as any).loopDone as Promise<void>
+
+ registeredRebalanceCb!({ code: CODES.ERRORS.ERR__ASSIGN_PARTITIONS } as any, [
+ { topic: 'test-topic', partition: 0 },
+ ])
+ if (consumeCallback) {
+ const cb = consumeCallback
+ consumeCallback = undefined
+ cb(null, [])
+ }
+ await delay(5)
+
+ consumeCallback!(null, [createMessage({ offset: 7, partition: 0 })])
+ await expect(loopDone).rejects.toBe(error)
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0, offset: 8 }])
+ // afterEach calls disconnect() — the loopDone has already settled, so it's a no-op.
+ })
+
+ it('callEachBatchWhenEmpty: empty batches still call eachBatch', async () => {
+ consumer = (() => {
+ jest.mocked(require('node-rdkafka').KafkaConsumer)
+ return new KafkaConsumerV2({
+ groupId: 'test-group-empty',
+ topic: 'test-topic',
+ callEachBatchWhenEmpty: true,
+ })
+ })()
+ mockRdKafka = jest.mocked((consumer as any).rdKafkaConsumer)
+
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ consumeCallback!(null, [])
+ await delay(5)
+
+ expect(eachBatch).toHaveBeenCalledWith([])
+ })
+
+ it('autoOffsetStore=false: storeOffsets never called automatically', async () => {
+ consumer = (() => {
+ return new KafkaConsumerV2({
+ groupId: 'test-group-manual',
+ topic: 'test-topic',
+ autoOffsetStore: false,
+ })
+ })()
+ mockRdKafka = jest.mocked((consumer as any).rdKafkaConsumer)
+
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ consumeCallback!(null, [createMessage({ offset: 9, partition: 0 })])
+ await delay(5)
+
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+
+ // Manual path still works.
+ consumer.offsetsStore([{ topic: 'test-topic', partition: 0, offset: 10 }])
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0, offset: 10 }])
+ })
+
+ it('Generation tag: a settle that fires after a generation bump skips storeOffsets', async () => {
+ ;(consumer as any).maxBackgroundTasks = 5
+ ;(consumer as any).drainTimeoutMs = 30 // force drain timeout so generation bump precedes resolve
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const slow = triggerablePromise()
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], slow.promise)
+
+ fireRevoke()
+ // Drain times out → loop calls incrementalUnassign → state goes IDLE; generation bumped.
+ await delay(60)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()
+
+ // Resolve the slow task AFTER generation bump.
+ slow.resolve()
+ await delay(20)
+
+ // storeOffsets should NOT be called for this stale task.
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+ })
+
+ it('Health: not connected → error', () => {
+ ;(mockRdKafka.isConnected as jest.Mock).mockReturnValue(false)
+ const result = consumer.isHealthy()
+ expect(result.isError()).toBe(true)
+ })
+
+ it('Health: connected and recently ticked → ok', async () => {
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+ expect(consumer.isHealthy().isError()).toBe(false)
+ })
+})
+
+afterAll(() => {
+ // Belt and braces — make sure no tracked promises leak between files.
+ while (activePromiseResolvers.length > 0) {
+ activePromiseResolvers[0]()
+ }
+})
diff --git a/nodejs/src/kafka/consumer/consumer-v2.ts b/nodejs/src/kafka/consumer/consumer-v2.ts
new file mode 100644
index 000000000000..ef22037a6f7e
--- /dev/null
+++ b/nodejs/src/kafka/consumer/consumer-v2.ts
@@ -0,0 +1,599 @@
+import {
+ Assignment,
+ CODES,
+ ClientMetrics,
+ ConsumerGlobalConfig,
+ LibrdKafkaError,
+ Message,
+ Metadata,
+ KafkaConsumer as RdKafkaConsumer,
+ TopicPartitionOffset,
+} from 'node-rdkafka'
+import { hostname } from 'os'
+
+import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, LogLevel } from '~/types'
+import { parseJSON } from '~/utils/json-parse'
+
+import { defaultConfig } from '../../config/config'
+import { logger } from '../../utils/logger'
+import { captureException } from '../../utils/posthog'
+import { retryIfRetriable } from '../../utils/retries'
+import { promisifyCallback } from '../../utils/utils'
+import { ensureTopicExists } from '../admin'
+import { getKafkaConfigFromEnv } from '../config'
+import { parseBrokerStatistics, trackBrokerMetrics } from '../kafka-client-metrics'
+import {
+ consumedBatchBackgroundDuration,
+ consumedBatchBackpressureDuration,
+ consumedBatchDuration,
+ consumerBatchSize,
+ consumerBatchSizeKb,
+ consumerBatchUtilization,
+ consumerDrainDuration,
+ consumerDrainTimeouts,
+ consumerStaleStoreOffsetsSkipped,
+ kafkaConsumerAssignment,
+} from './metrics'
+
+const DEFAULT_BATCH_TIMEOUT_MS = 500
+const STATISTICS_INTERVAL_MS = 5000
+const LOOP_STALL_THRESHOLD_MS_DEFAULT = 60_000
+
+export type KafkaConsumerV2Config = {
+ groupId: string
+ topic: string
+ batchTimeoutMs?: number
+ callEachBatchWhenEmpty?: boolean
+ autoOffsetStore?: boolean
+ autoCommit?: boolean
+ enablePartitionEof?: boolean
+}
+
+export type RdKafkaConsumerOverrides = Omit<
+ ConsumerGlobalConfig,
+ 'group.id' | 'enable.auto.offset.store' | 'enable.auto.commit'
+>
+
+export type EachBatchResult = { backgroundTask?: Promise<unknown> } | void
+export type EachBatch = (messages: Message[]) => Promise<EachBatchResult>
+
+type RebalanceEvent =
+ | { type: 'ASSIGN'; partitions: Assignment[] }
+ | { type: 'REVOKE'; partitions: Assignment[] }
+ | { type: 'ERROR'; err: LibrdKafkaError }
+
+type TaskEntry = {
+ settled: Promise<void>
+ generation: number
+}
+
+/**
+ * Single-coroutine Kafka consumer. The loop is the only mutator; the rebalance callback
+ * just enqueues events. On REVOKE the loop synchronously drains in-flight settle promises
+ * (post-storeOffsets, not raw user tasks), bumps `generation` so any laggard task skips
+ * its now-invalid storeOffsets, then calls incrementalUnassign.
+ */
+export class KafkaConsumerV2 {
+ private rdKafkaConsumer: RdKafkaConsumer
+ private rdKafkaConfig: ConsumerGlobalConfig
+ private podName: string
+ private consumerId: string
+
+ // Loop iterates while running; disconnect() flips it false.
+ private running = true
+ private generation = 0
+ private rebalanceQueue: RebalanceEvent[] = []
+ private inFlight: TaskEntry[] = []
+ private loopDone: Promise<void> | undefined
+
+ // Tunables (resolved at construction)
+ private fetchBatchSize: number
+ private batchTimeoutMs: number
+ private maxBackgroundTasks: number
+ private backgroundTaskTimeoutMs: number
+ private drainTimeoutMs: number
+ private loopStallThresholdMs: number
+ private logStatsLevel: LogLevel
+
+ // Health tracking
+ private lastLoopTickAt = 0
+
+ constructor(
+ private config: KafkaConsumerV2Config,
+ rdKafkaOverrides: RdKafkaConsumerOverrides = {}
+ ) {
+ this.config.autoCommit ??= true
+ this.config.autoOffsetStore ??= true
+ this.config.callEachBatchWhenEmpty ??= false
+
+ this.podName = process.env.HOSTNAME || hostname()
+ this.consumerId = `${this.podName}-${this.config.groupId}-${Date.now()}-${Math.random()
+ .toString(36)
+ .substring(2, 8)}`
+
+ this.fetchBatchSize = defaultConfig.CONSUMER_BATCH_SIZE
+ this.batchTimeoutMs = this.config.batchTimeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS
+ this.maxBackgroundTasks = defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS
+ this.backgroundTaskTimeoutMs = defaultConfig.CONSUMER_BACKGROUND_TASK_TIMEOUT_MS
+ this.drainTimeoutMs = defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS
+ this.loopStallThresholdMs = defaultConfig.CONSUMER_LOOP_STALL_THRESHOLD_MS || LOOP_STALL_THRESHOLD_MS_DEFAULT
+ this.logStatsLevel = defaultConfig.CONSUMER_LOG_STATS_LEVEL
+
+ this.rdKafkaConfig = {
+ 'client.id': hostname(),
+ 'security.protocol': 'plaintext',
+ 'metadata.broker.list': 'kafka:9092',
+ log_level: 4,
+ 'group.id': this.config.groupId,
+ 'session.timeout.ms': 30_000,
+ 'max.poll.interval.ms': 300_000,
+ 'max.partition.fetch.bytes': 1_048_576,
+ 'fetch.error.backoff.ms': 100,
+ 'fetch.message.max.bytes': 10_485_760,
+ 'fetch.wait.max.ms': 50,
+ 'queued.min.messages': 100_000,
+ 'queued.max.messages.kbytes': 102_400,
+ 'client.rack': defaultConfig.KAFKA_CLIENT_RACK,
+ 'metadata.max.age.ms': 30_000,
+ 'socket.timeout.ms': 30_000,
+ 'enable.partition.eof': this.config.enablePartitionEof ?? true,
+ 'statistics.interval.ms': STATISTICS_INTERVAL_MS,
+ // Newer librdkafka versions require this in the global config (the topic-config
+ // form passed to RdKafkaConsumer's second arg is silently ignored for assign-based
+ // consumers in some versions). See node-rdkafka issue #984.
+ ['auto.offset.reset' as keyof ConsumerGlobalConfig]: 'earliest' as never,
+ ...getKafkaConfigFromEnv('CONSUMER'),
+ ...rdKafkaOverrides,
+ // Settings we don't allow callers to override.
+ 'partition.assignment.strategy': 'cooperative-sticky',
+ 'enable.auto.offset.store': false,
+ 'enable.auto.commit': this.config.autoCommit,
+ rebalance_cb: this.rebalanceCallback.bind(this),
+ offset_commit_cb: true,
+ }
+
+ this.rdKafkaConsumer = this.createConsumer()
+ }
+
+ public isHealthy(): HealthCheckResult {
+ if (!this.rdKafkaConsumer.isConnected()) {
+ return new HealthCheckResultError('Consumer not connected to Kafka broker', {
+ topic: this.config.topic,
+ groupId: this.config.groupId,
+ })
+ }
+
+ const timeSinceLastTick = this.lastLoopTickAt > 0 ? Date.now() - this.lastLoopTickAt : 0
+ if (this.lastLoopTickAt > 0 && timeSinceLastTick > this.loopStallThresholdMs) {
+ return new HealthCheckResultError(
+ `Consumer loop stalled (no tick for ${Math.round(timeSinceLastTick / 1000)}s)`,
+ {
+ topic: this.config.topic,
+ groupId: this.config.groupId,
+ running: this.running,
+ timeSinceLastTick,
+ threshold: this.loopStallThresholdMs,
+ }
+ )
+ }
+
+ return new HealthCheckResultOk()
+ }
+
+ public assignments(): Assignment[] {
+ return this.rdKafkaConsumer.isConnected() ? this.rdKafkaConsumer.assignments() : []
+ }
+
+ public offsetsStore(offsets: TopicPartitionOffset[]): void {
+ // Manual offset path used by SessionRecording. Storing offsets after the consumer
+ // has revoked the partitions is harmless — librdkafka will reject the store internally.
+ this.rdKafkaConsumer.offsetsStore(offsets)
+ }
+
+ public async connect(eachBatch: EachBatch): Promise<void> {
+ try {
+ await promisifyCallback<Metadata>((cb) => this.rdKafkaConsumer.connect({}, cb))
+ logger.info('📝', 'kafka_consumer_v2_connected', { groupId: this.config.groupId, topic: this.config.topic })
+ } catch (error) {
+ logger.error('⚠️', 'kafka_consumer_v2_connect_error', { error })
+ throw error
+ }
+
+ if (defaultConfig.CONSUMER_AUTO_CREATE_TOPICS) {
+ await ensureTopicExists(this.rdKafkaConfig, this.config.topic)
+ }
+
+ this.rdKafkaConsumer.setDefaultConsumeTimeout(this.batchTimeoutMs)
+ this.rdKafkaConsumer.subscribe([this.config.topic])
+
+ this.lastLoopTickAt = Date.now()
+ this.loopDone = this.runLoop(eachBatch).catch((error) => {
+ logger.error('🔁', 'kafka_consumer_v2_loop_error', {
+ error: String(error),
+ groupId: this.config.groupId,
+ topic: this.config.topic,
+ })
+ throw error
+ })
+ }
+
+ public async disconnect(): Promise<void> {
+ if (!this.running) {
+ return
+ }
+ // Flip running so the loop exits and so the final REVOKE during disconnect goes
+ // through rebalanceCallback's special-case path.
+ this.running = false
+ if (this.loopDone) {
+ await this.loopDone.catch((error) => {
+ logger.error('🔁', 'kafka_consumer_v2_loop_failed_during_disconnect', { error: String(error) })
+ })
+ }
+ if (this.rdKafkaConsumer.isConnected()) {
+ await new Promise<void>((res, rej) => this.rdKafkaConsumer.disconnect((e) => (e ? rej(e) : res())))
+ }
+ }
+
+ // === Main loop ===
+
+ private async runLoop(eachBatch: EachBatch): Promise<void> {
+ try {
+ while (this.running) {
+ this.lastLoopTickAt = Date.now()
+
+ // 1. Drain rebalance events. handleRebalanceEvent on REVOKE awaits drainAll
+ // and calls incrementalUnassign before returning.
+ while (this.rebalanceQueue.length > 0) {
+ const event = this.rebalanceQueue.shift()!
+ await this.handleRebalanceEvent(event)
+ if (!this.running) {
+ break
+ }
+ }
+ if (!this.running) {
+ break
+ }
+
+ // 2. Poll. consume() also drives heartbeats / rebalance delivery; with no
+ // assignments it returns empty within fetch.wait.max.ms.
+ await this.fetchAndDispatch(eachBatch)
+ }
+ } finally {
+ // Drain whatever is left before letting the caller's disconnect() return.
+ await this.drainAll('shutdown')
+ }
+ }
+
+ private async fetchAndDispatch(eachBatch: EachBatch): Promise<void> {
+ const messages = await retryIfRetriable(() =>
+ promisifyCallback<Message[]>((cb) => this.rdKafkaConsumer.consume(this.fetchBatchSize, cb))
+ )
+
+ consumerBatchSize.observe(messages.length)
+ consumerBatchSizeKb.observe(messages.reduce((acc, m) => (m.value?.length ?? 0) + acc, 0) / 1024)
+ consumerBatchUtilization.labels({ groupId: this.config.groupId }).set(messages.length / this.fetchBatchSize)
+
+ if (messages.length === 0 && !this.config.callEachBatchWhenEmpty) {
+ return
+ }
+
+ // disconnect() may have flipped `running` while we were awaiting consume().
+ if (!this.running) {
+ return
+ }
+
+ const startMs = Date.now()
+ // eachBatch errors are intentionally NOT caught — they propagate to the loop and
+ // crash the process. At-least-once is preserved (uncommitted offsets get re-read
+ // on restart) and any logic bug surfaces loudly rather than silently dropping.
+ const result: EachBatchResult = await eachBatch(messages)
+ consumedBatchDuration.labels(this.config.topic, this.config.groupId).observe(Date.now() - startMs)
+
+ // We always track. If a REVOKE arrived while eachBatch ran, the generation tag in
+ // trackTask makes the storeOffsets a no-op, but inFlight still holds the entry so
+ // drainAll waits for it.
+ const offsets = findOffsetsToCommit(messages)
+ this.trackTask(result, offsets, this.generation)
+ await this.applyBackpressure()
+ }
+
+ private trackTask(result: EachBatchResult, offsets: TopicPartitionOffset[], gen: number): void {
+ const raw = result?.backgroundTask ?? Promise.resolve()
+ const stopBackgroundTimer = result?.backgroundTask
+ ? consumedBatchBackgroundDuration.startTimer({
+ topic: this.config.topic,
+ groupId: this.config.groupId,
+ })
+ : undefined
+
+ const settled: Promise<void> = (async () => {
+ try {
+ const { timedOut } = await raceWithTimeout(Promise.resolve(raw), this.backgroundTaskTimeoutMs)
+ if (timedOut) {
+ throw new Error(`background_task_timeout_after_${this.backgroundTaskTimeoutMs}ms`)
+ }
+ } catch (error) {
+ logger.error('🔥', 'kafka_consumer_v2_background_task_failed', { error: String(error) })
+ captureException(error)
+ // Do not store offsets when the task failed.
+ return
+ } finally {
+ stopBackgroundTimer?.()
+ }
+
+ if (this.config.autoCommit && this.config.autoOffsetStore) {
+ if (gen !== this.generation) {
+ // The partitions backing these offsets were revoked between dispatch and now.
+ // Skip the store — librdkafka would reject it anyway after unassign.
+ consumerStaleStoreOffsetsSkipped.labels(this.config.topic, this.config.groupId).inc(offsets.length)
+ return
+ }
+ this.storeOffsetsInternal(offsets)
+ }
+ })()
+
+ const entry: TaskEntry = { settled, generation: gen }
+ this.inFlight.push(entry)
+ // Self-cleanup so steady-state inFlight doesn't grow unbounded.
+ void settled.finally(() => {
+ const idx = this.inFlight.indexOf(entry)
+ if (idx >= 0) {
+ this.inFlight.splice(idx, 1)
+ }
+ })
+ }
+
+ private async applyBackpressure(): Promise<void> {
+ if (this.inFlight.length < this.maxBackgroundTasks) {
+ return
+ }
+ const stop = consumedBatchBackpressureDuration.startTimer({
+ topic: this.config.topic,
+ groupId: this.config.groupId,
+ })
+ try {
+ // Wait for the OLDEST task's settled chain. Using settled (not raw) means we don't
+ // release backpressure until storeOffsets has been attempted.
+ await this.inFlight[0].settled
+ } finally {
+ stop()
+ }
+ }
+
+ private async handleRebalanceEvent(event: RebalanceEvent): Promise<void> {
+ if (event.type === 'ASSIGN') {
+ try {
+ if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
+ this.rdKafkaConsumer.incrementalAssign(event.partitions)
+ } else {
+ this.rdKafkaConsumer.assign(event.partitions)
+ }
+ } catch (error) {
+ logger.error('🔁', 'kafka_consumer_v2_assign_failed', { error: String(error) })
+ captureException(error)
+ return
+ }
+ for (const tp of event.partitions) {
+ kafkaConsumerAssignment
+ .labels({
+ topic_name: tp.topic,
+ partition_id: tp.partition.toString(),
+ pod: this.podName,
+ group_id: this.config.groupId,
+ })
+ .set(1)
+ }
+ logger.info('🔁', 'kafka_consumer_v2_assigned', {
+ partitions: event.partitions.map((p) => `${p.topic}/${p.partition}`),
+ })
+ return
+ }
+
+ if (event.type === 'REVOKE') {
+ this.generation++
+ logger.info('🔁', 'kafka_consumer_v2_revoke_starting', {
+ inFlight: this.inFlight.length,
+ generation: this.generation,
+ partitions: event.partitions.map((p) => `${p.topic}/${p.partition}`),
+ })
+ await this.drainAll('revoke')
+
+ try {
+ if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
+ this.rdKafkaConsumer.incrementalUnassign(event.partitions)
+ } else {
+ this.rdKafkaConsumer.unassign()
+ }
+ } catch (error) {
+ logger.error('🔁', 'kafka_consumer_v2_unassign_failed', { error: String(error) })
+ captureException(error)
+ }
+
+ for (const tp of event.partitions) {
+ kafkaConsumerAssignment
+ .labels({
+ topic_name: tp.topic,
+ partition_id: tp.partition.toString(),
+ pod: this.podName,
+ group_id: this.config.groupId,
+ })
+ .set(0)
+ }
+ const remaining = this.rdKafkaConsumer.isConnected() ? this.rdKafkaConsumer.assignments() : []
+ logger.info('🔁', 'kafka_consumer_v2_revoke_complete', {
+ generation: this.generation,
+ remainingAssignments: remaining.length,
+ })
+ return
+ }
+
+ // ERROR
+ if (this.rdKafkaConsumer.isConnected()) {
+ logger.error('🔥', 'kafka_consumer_v2_rebalance_error', { err: event.err })
+ captureException(event.err)
+ } else {
+ logger.warn('🔥', 'kafka_consumer_v2_rebalance_error_while_disconnected', { err: event.err })
+ }
+ }
+
+ private async drainAll(cause: 'revoke' | 'shutdown'): Promise<void> {
+ if (this.inFlight.length === 0) {
+ return
+ }
+ const stop = consumerDrainDuration.labels(this.config.topic, this.config.groupId, cause).startTimer()
+ // Snapshot at drain time — entries added AFTER this point are excluded by design;
+ // they were created in the next generation and have nothing to drain for THIS rebalance.
+ const promises = this.inFlight.map((t) => t.settled)
+ let timedOut = false
+ try {
+ const result = await raceWithTimeout(Promise.all(promises), this.drainTimeoutMs)
+ timedOut = result.timedOut
+ } finally {
+ stop()
+ }
+ if (timedOut) {
+ consumerDrainTimeouts.labels(this.config.topic, this.config.groupId, cause).inc()
+ logger.error('🔁', 'kafka_consumer_v2_drain_timeout', {
+ cause,
+ drainTimeoutMs: this.drainTimeoutMs,
+ inFlight: this.inFlight.length,
+ })
+ }
+ }
+
+ private storeOffsetsInternal(offsets: TopicPartitionOffset[]): void {
+ if (offsets.length === 0) {
+ return
+ }
+ try {
+ this.rdKafkaConsumer.offsetsStore(offsets)
+ } catch (error) {
+ // Expected when partitions were revoked between batch dispatch and offset store.
+ logger.warn('📝', 'kafka_consumer_v2_store_offsets_failed', {
+ error: String(error),
+ offsets,
+ })
+ }
+ }
+
+ // === Rebalance callback — pure event source, mutates nothing except the queue ===
+
+ private rebalanceCallback(err: LibrdKafkaError, partitions: Assignment[]): void {
+ // Special case: during disconnect, librdkafka delivers a final REVOKE and waits
+ // for the application to call unassign() synchronously. The loop has already
+ // exited at this point, so we have to handle it inline rather than enqueue.
+ if (!this.running) {
+ if (err.code === CODES.ERRORS.ERR__REVOKE_PARTITIONS) {
+ try {
+ if (this.rdKafkaConsumer.rebalanceProtocol() === 'COOPERATIVE') {
+ this.rdKafkaConsumer.incrementalUnassign(partitions)
+ } else {
+ this.rdKafkaConsumer.unassign()
+ }
+ } catch (error) {
+ logger.warn('🔁', 'kafka_consumer_v2_unassign_during_shutdown_failed', {
+ error: String(error),
+ })
+ }
+ }
+ return
+ }
+
+ if (err.code === CODES.ERRORS.ERR__ASSIGN_PARTITIONS) {
+ this.rebalanceQueue.push({ type: 'ASSIGN', partitions })
+ } else if (err.code === CODES.ERRORS.ERR__REVOKE_PARTITIONS) {
+ this.rebalanceQueue.push({ type: 'REVOKE', partitions })
+ } else {
+ this.rebalanceQueue.push({ type: 'ERROR', err })
+ }
+ }
+
+ // === RdKafkaConsumer construction + event wiring ===
+
+ private createConsumer(): RdKafkaConsumer {
+ const consumer = new RdKafkaConsumer(this.rdKafkaConfig, { 'auto.offset.reset': 'earliest' })
+
+ consumer.on('event.log', (log) => logger.info('📝', 'kafka_consumer_v2_librdkafka_log', { log }))
+ consumer.on('event.error', (error: LibrdKafkaError) => {
+ // librdkafka emits transient errors (local timeouts during pod churn, broker
+ // disconnects, metadata refresh failures) on the same channel as fatal errors.
+ // Only escalate when it's actually fatal — otherwise this is informational noise
+ // that floods on every deployment restart.
+ const level = error.isFatal ? 'error' : 'warn'
+ logger[level]('📝', 'kafka_consumer_v2_librdkafka_error', { error })
+ })
+ consumer.on('event.stats', (stats: { message: string }) => {
+ try {
+ const parsed = parseJSON(stats.message) as Record<string, any>
+ const brokerStats = parseBrokerStatistics(parsed)
+ trackBrokerMetrics(brokerStats, this.config.groupId, this.consumerId)
+ logger[this.logStatsLevel]('📊', 'kafka_consumer_v2_stats', {
+ rx_msgs: parsed.rxmsgs,
+ rx_bytes: parsed.rx_bytes ?? parsed.rxbytes,
+ consumer_group_state: parsed.cgrp?.state,
+ rebalance_state: parsed.cgrp?.join_state,
+ rebalance_cnt: parsed.cgrp?.rebalance_cnt,
+ assignment_size: parsed.cgrp?.assignment_size,
+ })
+ } catch (error) {
+ logger.error('📊', 'kafka_consumer_v2_stats_parse_failed', { error: String(error) })
+ }
+ })
+ consumer.on('subscribed', (topics) => logger.info('📝', 'kafka_consumer_v2_subscribed', { topics }))
+ consumer.on('connection.failure', (error: LibrdKafkaError, metrics: ClientMetrics) =>
+ logger.error('📝', 'kafka_consumer_v2_connection_failure', { error, metrics })
+ )
+ consumer.on('offset.commit', (error: LibrdKafkaError, offsets: TopicPartitionOffset[]) => {
+ if (error) {
+ logger.warn('📝', 'kafka_consumer_v2_offset_commit_error', { error, offsets })
+ } else {
+ logger.debug('📝', 'kafka_consumer_v2_offset_commit', { offsets })
+ }
+ })
+
+ return consumer
+ }
+}
+
+/**
+ * Race `p` against a timeout. Unlike `Promise.race([p, sleep(ms).then(...)])`, this clears
+ * the timer when `p` settles first so we don't leak a pending setTimeout into the event loop.
+ */
+function raceWithTimeout<T>(p: Promise<T>, ms: number): Promise<{ value?: T; timedOut: boolean }> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve({ timedOut: true }), ms)
+ p.then(
+ (v) => {
+ clearTimeout(timer)
+ resolve({ value: v, timedOut: false })
+ },
+ (e) => {
+ clearTimeout(timer)
+ reject(e)
+ }
+ )
+ })
+}
+
+/** For each (topic, partition) in `messages`, return the next offset to commit (highest seen + 1). */
+function findOffsetsToCommit(messages: TopicPartitionOffset[]): TopicPartitionOffset[] {
+ const grouped = new Map<string, Map<number, number>>()
+ for (const m of messages) {
+ let byPartition = grouped.get(m.topic)
+ if (!byPartition) {
+ byPartition = new Map<number, number>()
+ grouped.set(m.topic, byPartition)
+ }
+ const current = byPartition.get(m.partition)
+ if (current === undefined || m.offset > current) {
+ byPartition.set(m.partition, m.offset)
+ }
+ }
+ const result: TopicPartitionOffset[] = []
+ for (const [topic, byPartition] of grouped) {
+ for (const [partition, highest] of byPartition) {
+ result.push({ topic, partition, offset: highest + 1 })
+ }
+ }
+ return result
+}
diff --git a/nodejs/src/kafka/consumer/index.test.ts b/nodejs/src/kafka/consumer/index.test.ts
new file mode 100644
index 000000000000..d4372d11b7f7
--- /dev/null
+++ b/nodejs/src/kafka/consumer/index.test.ts
@@ -0,0 +1,40 @@
+import { createKafkaConsumer } from '.'
+
+import { defaultConfig } from '~/config/config'
+
+import { KafkaConsumer } from './consumer-v1'
+import { KafkaConsumerV2 } from './consumer-v2'
+
+jest.mock('../admin', () => ({ ensureTopicExists: jest.fn().mockResolvedValue(undefined) }))
+jest.mock('node-rdkafka', () => ({
+ KafkaConsumer: jest.fn().mockImplementation(() => ({
+ connect: jest.fn(),
+ subscribe: jest.fn(),
+ on: jest.fn(),
+ isConnected: jest.fn().mockReturnValue(false),
+ disconnect: jest.fn().mockImplementation((cb) => cb && cb(null)),
+ setDefaultConsumeTimeout: jest.fn(),
+ assignments: jest.fn().mockReturnValue([]),
+ })),
+ CODES: { ERRORS: { ERR__REVOKE_PARTITIONS: -174, ERR__ASSIGN_PARTITIONS: -175 } },
+}))
+
+describe('createKafkaConsumer', () => {
+ const original = defaultConfig.CONSUMER_USE_V2
+
+ afterEach(() => {
+ defaultConfig.CONSUMER_USE_V2 = original
+ })
+
+ it('returns v1 when CONSUMER_USE_V2 is false', () => {
+ defaultConfig.CONSUMER_USE_V2 = false
+ const c = createKafkaConsumer({ groupId: 'my-group', topic: 'my-topic' })
+ expect(c).toBeInstanceOf(KafkaConsumer)
+ })
+
+ it('returns v2 when CONSUMER_USE_V2 is true', () => {
+ defaultConfig.CONSUMER_USE_V2 = true
+ const c = createKafkaConsumer({ groupId: 'my-group', topic: 'my-topic' })
+ expect(c).toBeInstanceOf(KafkaConsumerV2)
+ })
+})
diff --git a/nodejs/src/kafka/consumer/index.ts b/nodejs/src/kafka/consumer/index.ts
new file mode 100644
index 000000000000..68bbae1cfe0a
--- /dev/null
+++ b/nodejs/src/kafka/consumer/index.ts
@@ -0,0 +1,40 @@
+import { Message, TopicPartitionOffset } from 'node-rdkafka'
+
+import { defaultConfig } from '../../config/config'
+import { HealthCheckResult } from '../../types'
+import { logger } from '../../utils/logger'
+import { KafkaConsumer, KafkaConsumerConfig, RdKafkaConsumerConfig } from './consumer-v1'
+import { KafkaConsumerV2 } from './consumer-v2'
+
+// Re-exports for back-compat with code that imports header parsers from `kafka/consumer`.
+// These utilities are not really part of the consumer class and could move out later.
+export { parseEventHeaders, parseKafkaHeaders } from './consumer-v1'
+export type { KafkaConsumerConfig, RdKafkaConsumerConfig } from './consumer-v1'
+
+/**
+ * The shared surface that both KafkaConsumer (v1) and KafkaConsumerV2 expose to call sites.
+ * Keep this small — every method here pins the migration. Adding a method here forces both
+ * implementations to support it.
+ */
+export interface KafkaConsumerInterface {
+ connect(eachBatch: (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>): Promise<void>
+ disconnect(): Promise<void>
+ isHealthy(): HealthCheckResult
+ offsetsStore(offsets: TopicPartitionOffset[]): void
+}
+
+/**
+ * Single entry-point for instantiating a Kafka consumer. v1/v2 selection is driven by the
+ * `CONSUMER_USE_V2` env var (boolean, applies to the entire service). Call sites should
+ * never `new KafkaConsumer(...)` directly during the rollout — go through this factory.
+ */
+export function createKafkaConsumer(
+ config: KafkaConsumerConfig,
+ rdKafkaConfig: RdKafkaConsumerConfig = {}
+): KafkaConsumerInterface {
+ if (defaultConfig.CONSUMER_USE_V2) {
+ logger.info('🔁', 'kafka_consumer_factory_using_v2', { groupId: config.groupId, topic: config.topic })
+ return new KafkaConsumerV2(config, rdKafkaConfig)
+ }
+ return new KafkaConsumer(config, rdKafkaConfig)
+}
diff --git a/nodejs/src/kafka/consumer/metrics.ts b/nodejs/src/kafka/consumer/metrics.ts
new file mode 100644
index 000000000000..403ec1dcc448
--- /dev/null
+++ b/nodejs/src/kafka/consumer/metrics.ts
@@ -0,0 +1,73 @@
+import { Counter, Gauge, Histogram } from 'prom-client'
+
+/**
+ * Prom-client metrics shared between KafkaConsumer (v1) and KafkaConsumerV2.
+ *
+ * Both implementations import these singletons so they can coexist in the same Node.js
+ * process during the v2 rollout without registry collisions ("metric X has already been
+ * registered"). When v1 is finally deleted, only v2 will reference them — names stay
+ * stable so dashboards survive the cutover.
+ */
+
+export const kafkaConsumerAssignment = new Gauge({
+ name: 'kafka_consumer_assignment',
+ help: 'Kafka consumer partition assignment status',
+ labelNames: ['topic_name', 'partition_id', 'pod', 'group_id'],
+})
+
+export const consumedBatchDuration = new Histogram({
+ name: 'consumed_batch_duration_ms',
+ help: 'Main loop consumer batch processing duration in ms',
+ labelNames: ['topic', 'groupId'],
+})
+
+export const consumedBatchBackgroundDuration = new Histogram({
+ name: 'consumed_batch_background_duration_ms',
+ help: 'Background task processing duration in ms',
+ labelNames: ['topic', 'groupId'],
+})
+
+export const consumedBatchBackpressureDuration = new Histogram({
+ name: 'consumed_batch_backpressure_duration_ms',
+ help: 'Time spent waiting for background work to finish due to backpressure',
+ labelNames: ['topic', 'groupId'],
+})
+
+export const consumerBatchUtilization = new Gauge({
+ name: 'consumer_batch_utilization',
+ help: 'Indicates how big batches are we are processing compared to the max batch size. Useful as a scaling metric',
+ labelNames: ['groupId'],
+})
+
+export const consumerBatchSize = new Histogram({
+ name: 'consumer_batch_size',
+ help: 'The size of the batches we are receiving from Kafka',
+ buckets: [0, 50, 100, 250, 500, 750, 1000, 1500, 2000, 3000, Infinity],
+})
+
+export const consumerBatchSizeKb = new Histogram({
+ name: 'consumer_batch_size_kb',
+ help: 'The size in kb of the batches we are receiving from Kafka',
+ buckets: [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity],
+})
+
+// v2-only metrics — kept here for symmetry. v1 doesn't reference these.
+
+export const consumerDrainDuration = new Histogram({
+ name: 'kafka_consumer_drain_duration_ms',
+ help: 'Time spent draining in-flight tasks during a rebalance or shutdown',
+ labelNames: ['topic', 'groupId', 'cause'],
+ buckets: [10, 50, 100, 500, 1000, 5000, 10000, 30000, 60000, 120000, Infinity],
+})
+
+export const consumerDrainTimeouts = new Counter({
+ name: 'kafka_consumer_drain_timeouts_total',
+ help: 'Number of times a drain hit its timeout before all tasks settled',
+ labelNames: ['topic', 'groupId', 'cause'],
+})
+
+export const consumerStaleStoreOffsetsSkipped = new Counter({
+ name: 'kafka_consumer_stale_store_offsets_skipped_total',
+ help: 'Number of times an offset store was skipped because the task spanned a rebalance generation',
+ labelNames: ['topic', 'groupId'],
+})
diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
index 5346993b02fc..d4107cd11718 100644
--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
@@ -11,7 +11,7 @@ import { AppMetricsOutput } from '~/ingestion/common/outputs'
import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'
import type { LogsSettings } from '~/types'
-import { KafkaConsumer, parseKafkaHeaders } from '../kafka/consumer'
+import { KafkaConsumerInterface, createKafkaConsumer, parseKafkaHeaders } from '../kafka/consumer'
import { HealthCheckResult, PluginServerService } from '../types'
import { isDevEnv } from '../utils/env-utils'
import { logger } from '../utils/logger'
@@ -120,7 +120,7 @@ export const logsSamplingRecordsDroppedCounter = new Counter({
export class LogsIngestionConsumer {
protected name = 'LogsIngestionConsumer'
- protected kafkaConsumer: KafkaConsumer
+ protected kafkaConsumer: KafkaConsumerInterface
private appMetricsAggregator: AppMetricsAggregator
private redis: RedisV2
private rateLimiter: LogsRateLimiterService
@@ -142,7 +142,7 @@ export class LogsIngestionConsumer {
this.appMetricsAggregator = new AppMetricsAggregator(deps.outputs)
- this.kafkaConsumer = new KafkaConsumer({ groupId: this.groupId, topic: this.topic })
+ this.kafkaConsumer = createKafkaConsumer({ groupId: this.groupId, topic: this.topic })
// Logs ingestion uses its own Redis instance with TLS support
this.redis = createRedisV2PoolFromConfig({
connection:
diff --git a/nodejs/src/session-recording/consumer.ts b/nodejs/src/session-recording/consumer.ts
index ab46c9edaa91..18255f3b0119 100644
--- a/nodejs/src/session-recording/consumer.ts
+++ b/nodejs/src/session-recording/consumer.ts
@@ -21,7 +21,7 @@ import {
runSessionReplayPipeline,
} from '../ingestion/session_replay'
import { TopHog } from '../ingestion/tophog/tophog'
-import { KafkaConsumer } from '../kafka/consumer'
+import { KafkaConsumer } from '../kafka/consumer/consumer-v1'
import { getBlockEncryptor } from '../session-replay/shared/crypto'
import { SessionFeatureStore } from '../session-replay/shared/features/session-feature-store'
import { getKeyStore } from '../session-replay/shared/keystore'