-
Notifications
You must be signed in to change notification settings - Fork 0
KAFKA-19160: Improve performance of fetching stable offsets #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: trunk
Are you sure you want to change the base?
Conversation
When fetching stable offsets in the group coordinator, we iterate over all requested partitions. For each partition, we iterate over the group's ongoing transactions to check if there is a pending transactional offset commit for that partition. This can get slow when there are a large number of partitions and a large number of pending transactions. Instead, maintain a list of pending transactions per partition to speed up lookups.
@squah-confluent Thanks for the patch. Could we write a micro benchmark to demonstrate the gain? |
WalkthroughAdded a nested timeline map in OffsetMetadataManager to track open transactional producerIds by group → topic → partition, and updated offset deletion, pending-offset checks, replay, and transaction-completion logic to maintain and prune this structure alongside existing group-level tracking. (47 words) Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant OffsetMetadataManager
participant Storage
Client->>OffsetMetadataManager: Commit transactional offset (group,topic,partition,producerId)
Note right of OffsetMetadataManager: record producerId in\nopenTransactionsByGroup and\nopenTransactionsByGroupTopicAndPartition
OffsetMetadataManager->>Storage: append transactional offset record
Client->>OffsetMetadataManager: DeleteAllOffsets (group)
OffsetMetadataManager->>OffsetMetadataManager: iterate nested map for group\n( topic -> partition -> producerIds )
OffsetMetadataManager->>Storage: emit tombstone if no committed offset
Client->>OffsetMetadataManager: Replay offset commit / tombstone
OffsetMetadataManager->>OffsetMetadataManager: update nested maps or remove producerId\nand prune empty maps
Client->>OffsetMetadataManager: EndTransaction (producerId)
OffsetMetadataManager->>OffsetMetadataManager: remove producerId from group set\nand group→topic→partition nested map, prune empties
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (3)
290-292
: Consider initial capacity hintWhile the new map is created with default capacity, we already know the upper bound equals the number of groups in the shard.
Passing an estimated initial capacity (e.g.new TimelineHashMap<>(snapshotRegistry, expectedGroupCount)
) would avoid internal re‑hashing during warm‑up and complement the performance goal.
690-699
: Minor micro‑optimisation opportunity
hasPendingTransactionalOffsets
currently performs two nested look‑ups even when the group isn’t present.
Inlining the fast‑fail path keeps the common case cheap:TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> topics = openTransactionsByGroupTopicAndPartition.get(groupId); if (topics == null) return false; TimelineHashMap<Integer, TimelineHashSet<Long>> partitions = topics.get(topic); return partitions != null && !partitions.getOrDefault(partition, TimelineHashSet.empty()).isEmpty();Not critical, but consistent with the goal of shaving latency off hot paths.
1008-1012
: Helper method could improve readability & symmetryThe three‑level
computeIfAbsent
chain is repeated in multiple places (here, plus future writes).
Encapsulating it in a privateaddOpenTransaction(groupId, topic, partition, producerId)
helper removes duplication and lowers the cognitive load for future maintainers.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java
(7 hunks)
🔇 Additional comments (2)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (2)
201-205
: 👍 Valuable fine‑grained tracking addedIntroducing
openTransactionsByGroupTopicAndPartition
is a solid design choice that avoids repeatedly scanning every producer of a group when we only care about a single partition.
This lays the groundwork for the performance win described in the PR objective.
1067-1100
: Edge‑case: staleopenTransactionsByGroup
entry
replayEndTransactionMarker
correctly removes a producer‑id from both structures, butreplay
’s tombstone path (lines 1020‑1041) updates only the partition‑level map.
If that tombstone happens to clear the last pending offset for the producer, the group‑level set will still contain an orphaned producer id until the transaction eventually ends.
This can postpone group cleanup viacleanupExpiredOffsets
.If intentional, a comment explaining the lifecycle would help; otherwise consider synchronising removals in both places.
TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic = | ||
openTransactionsByGroupTopicAndPartition.get(groupId); | ||
if (openTransactionsByTopic != null) { | ||
openTransactionsByTopic.forEach((topic, openTransactionsByPartition) -> { | ||
openTransactionsByPartition.forEach((partition, producerIds) -> { | ||
producerIds.forEach(producerId -> { | ||
if (!hasCommittedOffset(groupId, topic, partition)) { | ||
records.add(GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord(groupId, topic, partition)); | ||
numDeletedOffsets.getAndIncrement(); | ||
} | ||
}); | ||
}); | ||
}); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Duplicate tombstones may be emitted for the same partition
producerIds.forEach(...)
iterates once per producer id, potentially adding the same tombstone several times when multiple producers have pending offsets for the identical <group, topic, partition>
.
This inflates records
and over‑counts numDeletedOffsets
, causing needless log traffic and skewed metrics.
- openTransactionsByPartition.forEach((partition, producerIds) -> {
- producerIds.forEach(producerId -> {
- if (!hasCommittedOffset(groupId, topic, partition)) {
- records.add(GroupCoordinatorRecordHelpers
- .newOffsetCommitTombstoneRecord(groupId, topic, partition));
- numDeletedOffsets.getAndIncrement();
- }
- });
- });
+ openTransactionsByPartition.keySet().forEach(partition -> {
+ if (!hasCommittedOffset(groupId, topic, partition)) {
+ records.add(GroupCoordinatorRecordHelpers
+ .newOffsetCommitTombstoneRecord(groupId, topic, partition));
+ numDeletedOffsets.getAndIncrement();
+ }
+ });
This preserves the original semantics while guaranteeing a single tombstone per partition.
/gemini review |
Warning Gemini encountered an error creating the review. You can try again by commenting |
/gemini review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a performance improvement for fetching stable offsets by maintaining a list of pending transactions per partition. The changes seem well-structured and address the identified bottleneck. However, some areas could benefit from further clarification and potential optimization.
Summary of Findings
- Missing null check: In
replayEndTransactionMarker
, there's a potential null pointer exception ifopenTransactionsByTopic
is null after removing a topic. A null check before proceeding with further operations would enhance robustness. - Potential memory leak: In
replay
, when removing pending offset commits, the code removes partitions and topics fromopenTransactionsByGroupTopicAndPartition
. However, it's crucial to ensure that theOffsets
object associated withpendingTransactionalOffsets
is also cleaned up to prevent a potential memory leak.
Merge Readiness
The pull request introduces a significant performance improvement and appears to be well-structured. However, the potential null pointer exception and memory leak should be addressed before merging. I am unable to approve this pull request, and recommend that others review and approve this code before merging. At a minimum, the high severity issues should be addressed before merging.
testing |
/refacto-test |
Refacto is reviewing this PR. Please wait for the review comments to be posted. |
@coderabbitai full review |
✅ Actions performedFull review triggered. |
Code Review: Offset Tracking Implementation👍 Well Done
📌 Files Processed
📝 Additional Comments
|
|
||
openTransactionsByPartition.remove(partition); | ||
if (openTransactionsByPartition.isEmpty()) { | ||
openTransactionsByTopic.remove(topic); | ||
} | ||
if (openTransactionsByTopic.isEmpty()) { | ||
openTransactionsByGroupTopicAndPartition.remove(groupId); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Incomplete Resource Cleanup
Nested resource cleanup doesn't check if openTransactionsByPartition exists before removing. If null, NullPointerException could occur during transaction completion, potentially causing transaction processing failures.
Standards
- ISO-IEC-25010-Reliability-Fault-Tolerance
- ISO-IEC-25010-Functional-Correctness-Appropriateness
- DbC-Resource-Mgmt
openTransactionsByPartition.remove(partition); | ||
if (openTransactionsByPartition.isEmpty()) { | ||
openTransactionsByTopic.remove(topic); | ||
} | ||
if (openTransactionsByTopic.isEmpty()) { | ||
openTransactionsByGroupTopicAndPartition.remove(groupId); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Incomplete Transaction Cleanup
The cleanup logic removes entries from openTransactionsByGroupTopicAndPartition but fails to check if the producer still has other pending offsets before removing it from openTransactionsByGroup. This can leave stale entries in openTransactionsByGroup causing memory leaks.
Standards
- Logic-Verification-Completeness
- Algorithm-Correctness-Resource-Management
- Business-Rule-Consistency
TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic = | ||
openTransactionsByGroupTopicAndPartition.get(groupId); | ||
if (openTransactionsByTopic != null) { | ||
TimelineHashMap<Integer, TimelineHashSet<Long>> openTransactionsByPartition = openTransactionsByTopic.get(topic); | ||
if (openTransactionsByPartition != null) { | ||
TimelineHashSet<Long> openTransactions = openTransactionsByPartition.get(partition); | ||
if (openTransactions != null) { | ||
openTransactions.forEach(openProducerId -> { | ||
Offsets pendingOffsets = pendingTransactionalOffsets.get(openProducerId); | ||
if (pendingOffsets != null) { | ||
pendingOffsets.remove(groupId, topic, partition); | ||
} | ||
}); | ||
|
||
openTransactionsByPartition.remove(partition); | ||
if (openTransactionsByPartition.isEmpty()) { | ||
openTransactionsByTopic.remove(topic); | ||
} | ||
if (openTransactionsByTopic.isEmpty()) { | ||
openTransactionsByGroupTopicAndPartition.remove(groupId); | ||
} | ||
} | ||
}); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Duplicate Code Paths
Similar nested map traversal and cleanup logic appears multiple times in the code. This duplication increases maintenance burden as any change to the cleanup logic must be applied consistently across all occurrences.
Standards
- Clean-Code-DRY
- Design-Pattern-Extract-Method
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (1)
661-674
: Duplicate tombstones may be emitted for the same partition.
producerIds.forEach(...)
iterates once per producer id, potentially adding the same tombstone several times when multiple producers have pending offsets for the identical<group, topic, partition>
.
This inflatesrecords
and over‑countsnumDeletedOffsets
, causing needless log traffic and skewed metrics.Apply this diff to ensure a single tombstone per partition:
- openTransactionsByPartition.forEach((partition, producerIds) -> { - producerIds.forEach(producerId -> { - if (!hasCommittedOffset(groupId, topic, partition)) { - records.add(GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord(groupId, topic, partition)); - numDeletedOffsets.getAndIncrement(); - } - }); - }); + openTransactionsByPartition.keySet().forEach(partition -> { + if (!hasCommittedOffset(groupId, topic, partition)) { + records.add(GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord(groupId, topic, partition)); + numDeletedOffsets.getAndIncrement(); + } + });
🧹 Nitpick comments (3)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (3)
197-197
: Improve documentation clarity.Consider making the comment more explicit about what "whether groups have any open transactions" means in this context.
- * Tracks whether groups have any open transactions. + * Tracks groups that have pending transactional offsets.
1020-1043
: Consider refactoring for better readability.The nested conditionals for pruning empty maps can be simplified using a helper method.
Consider extracting the pruning logic to a helper method:
+ private void pruneEmptyPartitionMaps(String groupId, String topic, int partition) { + TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic = + openTransactionsByGroupTopicAndPartition.get(groupId); + if (openTransactionsByTopic == null) return; + + TimelineHashMap<Integer, TimelineHashSet<Long>> openTransactionsByPartition = openTransactionsByTopic.get(topic); + if (openTransactionsByPartition == null) return; + + openTransactionsByPartition.remove(partition); + if (openTransactionsByPartition.isEmpty()) { + openTransactionsByTopic.remove(topic); + } + if (openTransactionsByTopic.isEmpty()) { + openTransactionsByGroupTopicAndPartition.remove(groupId); + } + } // Remove all the pending offset commits related to the tombstone. TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic = openTransactionsByGroupTopicAndPartition.get(groupId); if (openTransactionsByTopic != null) { TimelineHashMap<Integer, TimelineHashSet<Long>> openTransactionsByPartition = openTransactionsByTopic.get(topic); if (openTransactionsByPartition != null) { TimelineHashSet<Long> openTransactions = openTransactionsByPartition.get(partition); if (openTransactions != null) { openTransactions.forEach(openProducerId -> { Offsets pendingOffsets = pendingTransactionalOffsets.get(openProducerId); if (pendingOffsets != null) { pendingOffsets.remove(groupId, topic, partition); } }); - - openTransactionsByPartition.remove(partition); - if (openTransactionsByPartition.isEmpty()) { - openTransactionsByTopic.remove(topic); - } - if (openTransactionsByTopic.isEmpty()) { - openTransactionsByGroupTopicAndPartition.remove(groupId); - } + pruneEmptyPartitionMaps(groupId, topic, partition); } } }
1067-1099
: Good implementation, but consider extracting complexity.The logic correctly maintains consistency between both tracking structures, but the deeply nested loops make the code hard to follow.
Consider extracting the partition-level cleanup into a helper method:
+ private void removeProducerFromPartitionTracking(String groupId, Long producerId, + TimelineHashMap<String, TimelineHashMap<Integer, OffsetAndMetadata>> topicOffsets) { + TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic = + openTransactionsByGroupTopicAndPartition.get(groupId); + if (openTransactionsByTopic == null) return; + + topicOffsets.forEach((topic, partitionOffsets) -> { + TimelineHashMap<Integer, TimelineHashSet<Long>> openTransactionsByPartition = openTransactionsByTopic.get(topic); + if (openTransactionsByPartition == null) return; + + partitionOffsets.keySet().forEach(partitionId -> { + TimelineHashSet<Long> partitionTransactions = openTransactionsByPartition.get(partitionId); + if (partitionTransactions != null) { + partitionTransactions.remove(producerId); + if (partitionTransactions.isEmpty()) { + openTransactionsByPartition.remove(partitionId); + } + if (openTransactionsByPartition.isEmpty()) { + openTransactionsByTopic.remove(topic); + } + if (openTransactionsByTopic.isEmpty()) { + openTransactionsByGroupTopicAndPartition.remove(groupId); + } + } + }); + }); + } pendingOffsets.offsetsByGroup.forEach((groupId, topicOffsets) -> { TimelineHashSet<Long> groupTransactions = openTransactionsByGroup.get(groupId); if (groupTransactions != null) { groupTransactions.remove(producerId); if (groupTransactions.isEmpty()) { openTransactionsByGroup.remove(groupId); } } - TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic = - openTransactionsByGroupTopicAndPartition.get(groupId); - if (openTransactionsByTopic == null) return; - - topicOffsets.forEach((topic, partitionOffsets) -> { - TimelineHashMap<Integer, TimelineHashSet<Long>> openTransactionsByPartition = openTransactionsByTopic.get(topic); - if (openTransactionsByPartition == null) return; - - partitionOffsets.keySet().forEach(partitionId -> { - TimelineHashSet<Long> partitionTransactions = openTransactionsByPartition.get(partitionId); - if (partitionTransactions != null) { - partitionTransactions.remove(producerId); - if (partitionTransactions.isEmpty()) { - openTransactionsByPartition.remove(partitionId); - } - if (openTransactionsByPartition.isEmpty()) { - openTransactionsByTopic.remove(topic); - } - if (openTransactionsByTopic.isEmpty()) { - openTransactionsByGroupTopicAndPartition.remove(groupId); - } - } - }); - }); + removeProducerFromPartitionTracking(groupId, producerId, topicOffsets); });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java
(8 hunks)
🔇 Additional comments (5)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (5)
9-9
: LGTM!The URL fix is correct.
201-206
: LGTM!Good implementation. The nested map structure efficiently tracks open transactions at the partition level, which directly addresses the performance issue described in the PR.
685-699
: LGTM!Good implementation using the new nested map for efficient partition-level lookups. This is the key improvement that resolves the performance issue by avoiding iteration over all group transactions.
1008-1012
: LGTM!Correct implementation of updating both the group-level and partition-level tracking structures when replaying transactional offset commits.
1054-1054
: LGTM!Appropriate use of the suppression annotation for a complex method that maintains consistency across multiple nested data structures. The comment explains it well.
When fetching stable offsets in the group coordinator, we iterate over
all requested partitions. For each partition, we iterate over the
group's ongoing transactions to check if there is a pending
transactional offset commit for that partition.
This can get slow when there are a large number of partitions and a
large number of pending transactions. Instead, maintain a list of
pending transactions per partition to speed up lookups.
Summary by CodeRabbit
New Features
Bug Fixes
Performance