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(kafka): keep committed progress across a rebalance (#80897)

Daniel Marchuk4a6d3e69429b
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.ts b/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.ts
index 7807b3a1d1ab..235977b5d0c0 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v2.rebalance.integration.test.ts
@@ -21,9 +21,11 @@ import { KafkaConsumerV2 } from './consumer-v2'
* the new owner resumes with zero redelivery,
* - cooperative-sticky revokes are incremental: the surviving consumer never drops to zero
* assignments while a partition moves,
- * - the generation guard: a batch in flight when the revoke arrives skips its offset store,
- * so its messages are redelivered on the moved partition (exactly once more) while the
- * retained partition never re-reads them and the group commit stays at the pre-batch mark,
+ * - the generation guard fences by the drain budget, not by the revoke: a batch still in flight
+ * when the revoke arrives but settling inside the drain budget stores and commits its offsets
+ * (no redelivery, because its side effects already ran), while a batch that outlives the budget
+ * is fenced and its messages are redelivered on the moved partition rather than committed as
+ * done,
* - the onPartitionsRevoked hook (the session replay flush-on-revoke contract): it runs
* after the drain while the partitions are still assigned, offsets it stores are committed
* exactly as the partitions are given up — including from an already-committed baseline
@@ -338,7 +340,7 @@ describe('KafkaConsumerV2 rebalance semantics (integration)', () => {
}
})
- it('a batch in flight at revoke skips its offset store (generation guard): moved partition redelivers it, retained partition does not', async () => {
+ it('a batch in flight at revoke that settles inside the drain budget commits its offsets: no redelivery on either partition', async () => {
const topic = `v2_int_reb_gen_${randomUUID()}`
const groupId = `v2-int-reb-gen-${randomUUID()}`
await createTopic(topic, 2)
@@ -401,10 +403,8 @@ describe('KafkaConsumerV2 rebalance semantics (integration)', () => {
])
await waitFor(() => ledger.length >= wave1.length, 8_000)
- const preGateCommit = new Map<number, number>()
for (const partition of [0, 1]) {
const highest = Math.max(...wave1.filter((r) => r.partition === partition).map((r) => r.offset))
- preGateCommit.set(partition, highest + 1)
await waitForAsync(
async () => (await fetchCommittedOffset(groupId, topic, partition)) === highest + 1,
10_000
@@ -420,9 +420,10 @@ describe('KafkaConsumerV2 rebalance semantics (integration)', () => {
])
await waitFor(() => gated.every((g) => ledger.some((e) => e.value === g.value)), 8_000)
- // B joins while the gated batch is still in flight. The revoke bumps the
- // generation and drains — the drain blocks on our gate. Hold it long enough
- // for the revoke to be firmly in progress, then release.
+ // B joins while the gated batch is still in flight. The revoke drains first — the
+ // drain blocks on our gate. Hold it long enough for the revoke to be firmly in
+ // progress, then release well inside the drain budget
+ // (CONSUMER_REBALANCE_TIMEOUT_MS, 20s by default).
consumerB = makeConsumer(groupId, topic, (msgs) => Promise.resolve(recordB(msgs)), {
autoOffsetStore: true,
})
@@ -434,33 +435,129 @@ describe('KafkaConsumerV2 rebalance semantics (integration)', () => {
const movedPartition = b.assignments()[0].partition
const retainedPartition = movedPartition === 0 ? 1 : 0
- // The generation guard skipped the gated batch's store, so the moved partition's
- // gated message is redelivered to B from the pre-gate commit point: seen exactly
- // twice overall (once by A pre-revoke, once by B). The retained partition stays
- // with A, whose in-memory position is already past its gated message: exactly once.
+ // The gated batch settled inside the drain budget, so its offsets were stored while
+ // both partitions were still assigned and committed as the moved one was given up.
+ // Neither gated message is redelivered: A saw each exactly once and B re-reads
+ // nothing. This is the duplicate-send guarantee — replaying here would fire a
+ // destination's outbound request a second time.
const gatedMoved = gated.find((g) => g.partition === movedPartition)!
const gatedRetained = gated.find((g) => g.partition === retainedPartition)!
- await waitFor(() => ledger.filter((e) => e.value === gatedMoved.value).length >= 2, 15_000)
+ for (const partition of [movedPartition, retainedPartition]) {
+ const gatedForPartition = gated.find((g) => g.partition === partition)!
+ await waitForAsync(
+ async () =>
+ (await fetchCommittedOffset(groupId, topic, partition)) === gatedForPartition.offset + 1,
+ 15_000
+ )
+ }
+ expect(ledger.filter((e) => e.value === gatedMoved.value).map((e) => e.consumerId)).toEqual(['A'])
+ expect(ledger.filter((e) => e.value === gatedRetained.value).map((e) => e.consumerId)).toEqual(['A'])
+
+ // Nothing else was re-read either: every (partition, offset) appears exactly once.
+ expect([...countByPartitionOffset(ledger).values()].filter((n) => n > 1)).toEqual([])
+ } finally {
+ defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS = savedMaxBackgroundTasks
+ await consumerA.disconnect()
+ await consumerB?.disconnect()
+ await deleteTopic(topic)
+ }
+ })
+
+ it('a batch outliving the drain budget is fenced: its offsets never commit and the moved partition redelivers it', async () => {
+ const topic = `v2_int_reb_fence_${randomUUID()}`
+ const groupId = `v2-int-reb-fence-${randomUUID()}`
+ await createTopic(topic, 2)
+
+ // Free background slots so the loop can take the revoke while the gated task is
+ // pending, and a drain budget short enough that the gate outlives it — the task then
+ // settles after the fence, which is what must block its offset store.
+ const savedMaxBackgroundTasks = defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS
+ const savedRebalanceTimeout = defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS
+ defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS = 4
+ defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS = 2_000
+
+ const ledger: LedgerEntry[] = []
+ let gateArmed = false
+ let releaseGate: () => void = () => {}
+ const gate = new Promise<void>((resolve) => {
+ releaseGate = resolve
+ })
+
+ const record =
+ (consumerId: string, gated: boolean) =>
+ (messages: Message[]): { backgroundTask?: Promise<unknown> } => {
+ for (const m of messages) {
+ ledger.push({
+ consumerId,
+ partition: m.partition,
+ offset: m.offset,
+ key: m.key?.toString() ?? '',
+ value: m.value?.toString() ?? '',
+ seenAt: Date.now(),
+ })
+ }
+ return gated && gateArmed ? { backgroundTask: gate } : {}
+ }
+
+ const consumerA = makeConsumer(groupId, topic, (msgs) => Promise.resolve(record('A', true)(msgs)), {
+ autoOffsetStore: true,
+ })
+ let consumerB: KafkaConsumerV2 | undefined
+
+ try {
+ await waitFor(() => consumerA.assignments().length === 2, 10_000)
+
+ const wave1 = await produceTracked(producer, topic, [
+ { key: 'a0', partition: 0 },
+ { key: 'b0', partition: 1 },
+ ])
+ await waitFor(() => ledger.length >= wave1.length, 8_000)
+ const preGateCommit = new Map<number, number>()
+ for (const produced of wave1) {
+ preGateCommit.set(produced.partition, produced.offset + 1)
+ await waitForAsync(
+ async () =>
+ (await fetchCommittedOffset(groupId, topic, produced.partition)) === produced.offset + 1,
+ 10_000
+ )
+ }
+
+ gateArmed = true
+ const gated = await produceTracked(producer, topic, [
+ { key: 'gated-p0', partition: 0 },
+ { key: 'gated-p1', partition: 1 },
+ ])
+ await waitFor(() => gated.every((g) => ledger.some((e) => e.value === g.value)), 8_000)
+
+ // B joins. The drain gives up after 2s with the gate still closed, so the fence
+ // engages before the task settles.
+ consumerB = makeConsumer(groupId, topic, (msgs) => Promise.resolve(record('B', false)(msgs)), {
+ autoOffsetStore: true,
+ })
+ const b = consumerB
+ await waitFor(() => consumerA.assignments().length === 1 && b.assignments().length === 1, 20_000)
+ releaseGate()
+
+ const movedPartition = b.assignments()[0].partition
+ const retainedPartition = movedPartition === 0 ? 1 : 0
+ const gatedMoved = gated.find((g) => g.partition === movedPartition)!
+
+ // Fenced: the gated batch's store was skipped, so the moved partition redelivers
+ // its message to B from the pre-gate commit. At-least-once is preserved — an
+ // unfinished batch must never be committed as done.
+ await waitFor(() => ledger.filter((e) => e.value === gatedMoved.value).length >= 2, 20_000)
expect(
ledger
.filter((e) => e.value === gatedMoved.value)
.map((e) => e.consumerId)
.sort()
).toEqual(['A', 'B'])
- expect(ledger.filter((e) => e.value === gatedRetained.value).map((e) => e.consumerId)).toEqual(['A'])
-
- // Commits reflect the guard exactly: the retained partition's commit is still the
- // pre-gate mark (its gated store was skipped and nothing re-stored it), while the
- // moved partition advances past the gated message once B's redelivery settles.
- await waitForAsync(
- async () => (await fetchCommittedOffset(groupId, topic, movedPartition)) === gatedMoved.offset + 1,
- 15_000
- )
expect(await fetchCommittedOffset(groupId, topic, retainedPartition)).toBe(
preGateCommit.get(retainedPartition)
)
} finally {
defaultConfig.CONSUMER_MAX_BACKGROUND_TASKS = savedMaxBackgroundTasks
+ defaultConfig.CONSUMER_REBALANCE_TIMEOUT_MS = savedRebalanceTimeout
await consumerA.disconnect()
await consumerB?.disconnect()
await deleteTopic(topic)
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts b/nodejs/src/common/kafka/consumer/consumer-v2.test.ts
index 9e3753941428..48088713f320 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v2.test.ts
@@ -298,7 +298,7 @@ describe('KafkaConsumerV2', () => {
expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
})
- it('H2 regression: stale tasks across generations skip storeOffsets and never trigger unassign', async () => {
+ it('H2 regression: a task settling inside the drain stores its offsets, and a sticky reassign arms nothing extra', async () => {
;(consumer as any).maxBackgroundTasks = 5
const eachBatch = jest.fn(() => Promise.resolve({}))
await startConsuming(eachBatch)
@@ -315,9 +315,11 @@ describe('KafkaConsumerV2', () => {
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()
+ // The task finished inside the drain budget, while the partition was still assigned, so
+ // its offsets are stored (and committed on the unassign below) rather than discarded —
+ // discarding them is what made the next owner replay completed work. A task that misses
+ // the budget is fenced instead: see the "Partition fence" test.
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ offset: 2, partition: 0, topic: 'test-topic' }])
// Snapshot offsetsStore + unassign call counts before the reassign so we can assert
// nothing further happens once we re-acquire the partition.
@@ -336,17 +338,103 @@ describe('KafkaConsumerV2', () => {
expect(mockRdKafka.offsetsStore.mock.calls.length).toBe(offsetCallsBeforeReassign)
})
+ it('store order survives an empty batch that lingers in inFlight: a later batch waits for the earlier storing one', async () => {
+ // Empty batches no longer chain, which is what stops them holding a backpressure slot.
+ // But an empty batch still enters inFlight when it carries a backgroundTask, and the CDP
+ // cyclotron worker returns one for an empty poll. Chaining a storing batch on the tail of
+ // inFlight would then let it inherit the empty batch's settle and store ahead of the
+ // earlier storing batch — the exact reordering the chain exists to prevent.
+ ;(consumer as any).maxBackgroundTasks = 10
+ ;(consumer as any).config.callEachBatchWhenEmpty = true
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const slowFirst = triggerablePromise()
+ const emptyBatchTask = triggerablePromise()
+
+ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], slowFirst.promise)
+ await dispatchBatch(eachBatch, [], emptyBatchTask.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], undefined)
+
+ // The empty batch finishes first. The later batch must still be waiting on the first one.
+ emptyBatchTask.resolve()
+ await delay(20)
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+
+ slowFirst.resolve()
+ await delay(20)
+ expect(mockRdKafka.offsetsStore.mock.calls.map((call) => call[0])).toEqual([
+ [{ topic: 'test-topic', partition: 0, offset: 2 }],
+ [{ topic: 'test-topic', partition: 0, offset: 3 }],
+ ])
+ })
+
+ it('a failed batch blocks a later store even when an empty batch sits between them', async () => {
+ // The store chain is what keeps a later batch from advancing the committed offset past an
+ // earlier batch that failed. An empty poll (callEachBatchWhenEmpty, as the CDP cyclotron
+ // worker sets) still enters inFlight when it carries a backgroundTask, so excluding empty
+ // batches from the chain reopens that gap and offsets advance past failed work.
+ ;(consumer as any).maxBackgroundTasks = 10
+ ;(consumer as any).config.callEachBatchWhenEmpty = true
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch)
+
+ const failing = triggerablePromise()
+ await dispatchBatch(eachBatch, [], failing.promise)
+ await dispatchBatch(eachBatch, [createMessage({ offset: 7, partition: 0 })], Promise.resolve())
+ await delay(10)
+
+ // The later batch must not have stored yet: the empty batch ahead of it has not settled.
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+
+ failing.reject(new Error('empty batch work failed'))
+ await delay(30)
+
+ // And once that batch fails, the store is abandoned rather than committed.
+ expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()
+ })
+
+ it('the fence is per partition: a laggard task still stores the partition it kept, never the one it lost', async () => {
+ ;(consumer as any).maxBackgroundTasks = 5
+ ;(consumer as any).drainTimeoutMs = 30 // the task settles after the drain gives up
+ const eachBatch = jest.fn(() => Promise.resolve({}))
+ await startConsuming(eachBatch, [
+ { topic: 'test-topic', partition: 0 },
+ { topic: 'test-topic', partition: 1 },
+ ])
+
+ const slow = triggerablePromise()
+ await dispatchBatch(
+ eachBatch,
+ [createMessage({ offset: 5, partition: 0 }), createMessage({ offset: 9, partition: 1 })],
+ slow.promise
+ )
+
+ // Only partition 0 is revoked; we keep partition 1.
+ fireRevoke([{ topic: 'test-topic', partition: 0 }])
+ await delay(60)
+ expect(mockRdKafka.incrementalUnassign).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 0 }])
+
+ slow.resolve()
+ await delay(20)
+
+ // Partition 1's progress is ours to commit — it never left. Partition 0's is not, because
+ // another member may own it now. A global fence would have dropped both, stalling
+ // partition 1's commit until some later revoke replayed everything since.
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledTimes(1)
+ expect(mockRdKafka.offsetsStore).toHaveBeenCalledWith([{ topic: 'test-topic', partition: 1, offset: 10 }])
+ })
+
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) the epoch bump after the drain fences anything that settles later, so a task
+ // that missed the budget can't store against a partition we gave up (see the
+ // "Partition fence" 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`,
+ // This test verifies (a) 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({}))
@@ -643,9 +731,9 @@ describe('KafkaConsumerV2', () => {
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 () => {
+ it('Partition fence: a settle that fires after the partition is given up skips storeOffsets', async () => {
;(consumer as any).maxBackgroundTasks = 5
- ;(consumer as any).drainTimeoutMs = 30 // force drain timeout so generation bump precedes resolve
+ ;(consumer as any).drainTimeoutMs = 30 // force drain timeout so the epoch bump precedes resolve
const eachBatch = jest.fn(() => Promise.resolve({}))
await startConsuming(eachBatch)
@@ -653,11 +741,11 @@ describe('KafkaConsumerV2', () => {
await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], slow.promise)
fireRevoke()
- // Drain times out → loop calls incrementalUnassign → state goes IDLE; generation bumped.
+ // Drain times out → loop calls incrementalUnassign → state goes IDLE; the epoch is bumped.
await delay(60)
expect(mockRdKafka.incrementalUnassign).toHaveBeenCalled()
- // Resolve the slow task AFTER generation bump.
+ // Resolve the slow task AFTER the epoch bump.
slow.resolve()
await delay(20)
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.ts b/nodejs/src/common/kafka/consumer/consumer-v2.ts
index c803e8565dc8..caade8f990f3 100644
--- a/nodejs/src/common/kafka/consumer/consumer-v2.ts
+++ b/nodejs/src/common/kafka/consumer/consumer-v2.ts
@@ -68,16 +68,17 @@ type RebalanceEvent =
type TaskEntry = {
settled: Promise<void>
- generation: number
}
+const partitionKey = (tp: { topic: string; partition: number }): string => `${tp.topic}/${tp.partition}`
+
/**
* 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, runs the optional onPartitionsRevoked hook while the
- * partitions are still assigned (so a flush there can store offsets that get committed
- * on the unassign), then calls incrementalUnassign.
+ * (post-storeOffsets, not raw user tasks), bumps the epoch of each partition it is giving up so
+ * any laggard task skips its now-invalid storeOffsets for those partitions, runs the optional
+ * onPartitionsRevoked hook while the partitions are still assigned (so a flush there can store
+ * offsets that get committed on the unassign), then calls incrementalUnassign.
*/
export class KafkaConsumerV2 {
private rdKafkaConsumer: RdKafkaConsumer
@@ -87,6 +88,10 @@ export class KafkaConsumerV2 {
// Loop iterates while running; disconnect() flips it false.
private running = true
+ // Bumped for a partition each time we give it up, so a task that settles after that point
+ // cannot store an offset for it. Keyed by `topic/partition`; absent means never revoked.
+ private partitionEpochs = new Map<string, number>()
+ // Rebalance counter, kept for log continuity only — the fence reads partitionEpochs.
private generation = 0
private rebalanceQueue: RebalanceEvent[] = []
private inFlight: TaskEntry[] = []
@@ -322,15 +327,15 @@ export class KafkaConsumerV2 {
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.
+ // We always track. If a partition backing this batch is revoked while eachBatch runs, the
+ // epoch captured in trackTask makes that partition's 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)
+ this.trackTask(result, offsets)
await this.applyBackpressure()
}
- private trackTask(result: EachBatchResult, offsets: TopicPartitionOffset[], gen: number): void {
+ private trackTask(result: EachBatchResult, offsets: TopicPartitionOffset[]): void {
const raw = result?.backgroundTask ?? Promise.resolve()
const stopBackgroundTimer = result?.backgroundTask
? consumedBatchBackgroundDuration.startTimer({
@@ -339,6 +344,11 @@ export class KafkaConsumerV2 {
})
: undefined
+ // The epoch each partition held when this batch was dispatched. At store time an unchanged
+ // epoch means we have held the partition continuously since, so the offset is still ours
+ // to advance.
+ const dispatchEpochs = new Map(offsets.map((o) => [partitionKey(o), this.epochOf(o)]))
+
// Serialize store decisions in batch order: without this a faster later batch
// could store its (higher) offset before an earlier failed batch latches fatalError.
const predecessorSettled =
@@ -367,17 +377,22 @@ export class KafkaConsumerV2 {
}
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
+ // Fence per partition, not per rebalance. A partition we still hold is safe to
+ // advance even if a sibling partition was revoked in the meantime; one that was
+ // revoked is not, because it may have passed through another member since — and
+ // storing our older offset would rewind the group and redeliver.
+ const storable = offsets.filter((o) => this.epochOf(o) === dispatchEpochs.get(partitionKey(o)))
+ const fenced = offsets.length - storable.length
+ if (fenced > 0) {
+ consumerStaleStoreOffsetsSkipped.labels(this.config.topic, this.config.groupId).inc(fenced)
+ }
+ if (storable.length > 0) {
+ this.storeOffsetsInternal(storable)
}
- this.storeOffsetsInternal(offsets)
}
})()
- const entry: TaskEntry = { settled, generation: gen }
+ const entry: TaskEntry = { settled }
this.inFlight.push(entry)
// Self-cleanup so steady-state inFlight doesn't grow unbounded.
void settled.finally(() => {
@@ -435,6 +450,9 @@ export class KafkaConsumerV2 {
}
if (event.type === 'REVOKE') {
+ // Ticks as the rebalance starts so both log lines below carry the same number. This
+ // counter is only ever read by those two lines — the fence is the partitionEpochs bump
+ // after the drain, and it deliberately does not happen this early.
this.generation++
logger.info('🔁', 'kafka_consumer_v2_revoke_starting', {
inFlight: this.inFlight.length,
@@ -445,7 +463,18 @@ export class KafkaConsumerV2 {
// hook gets the remainder, so CONSUMER_REBALANCE_TIMEOUT_MS bounds the total hold
// on the rebalance — not each phase separately.
const revokeDeadline = Date.now() + this.drainTimeoutMs
+ // Drain before fencing. A batch that settles inside the budget has already run its
+ // side effects and still holds its partitions, so its offset store is valid and
+ // librdkafka commits it on the unassign below. Fencing first discarded those offsets,
+ // so the next owner replayed work that was already done — for a CDP destination that
+ // is a second outbound request (duplicate Slack message, webhook, CRM write).
await this.drainAll('revoke')
+ // Whatever is still unsettled missed the budget: fence the partitions we are giving up
+ // so a late settle can't store offsets for them. Partitions we keep are untouched, so
+ // a laggard task can still commit the progress it made on those.
+ for (const tp of event.partitions) {
+ this.partitionEpochs.set(partitionKey(tp), this.epochOf(tp) + 1)
+ }
if (this.onPartitionsRevoked) {
const hookBudgetMs = Math.max(revokeDeadline - Date.now(), 0)
@@ -510,6 +539,10 @@ export class KafkaConsumerV2 {
}
}
+ private epochOf(tp: { topic: string; partition: number }): number {
+ return this.partitionEpochs.get(partitionKey(tp)) ?? 0
+ }
+
private async drainAll(cause: 'revoke' | 'shutdown'): Promise<void> {
if (this.inFlight.length === 0) {
return