GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [improve][broker] Add limits for Key_Shared Subscription look ahead in dispatching by lhotari · Pull Request #23231 · apache/pulsar

Conversation

@lhotari

@lhotari lhotari commented Aug 27, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

Fixes #23200

Motivation

This PR introduces enhancements to the Key_Shared subscription dispatching logic in the Pulsar broker. The changes aim to optimize message dispatching, improve the handling of slow consumers, and address several identified issues related to message replay and message "look ahead" when consumers are blocked in delivery due to key ordering restrictions.

This PR adds limits to the Key_Shared Subscription look-ahead feature, which was introduced in PR #7105. Additionally, there are several improvements to the previous logic.

Since there wasn't any named concept for the feature added in PR #7105, it has been named "key shared look ahead" in this PR. This references the feature added in PR #7105, where the dispatcher will skip replaying messages and read more messages from the backlog. The changes in PR #7105 didn't add a limit for reading more messages. The comments in the PR mention that it will be limited by the unacked message limits. However, this isn't the case since the read messages aren't considered unacked messages until they have been dispatched to consumers.

Reading ahead would be triggered in multiple cases:

  • When consumers are backpressured due to slow processing or message delivery
  • When consumers are blocked due to key ordering restrictions
    • The previous logic for blocking a hash was unoptimal. The impact is discussed in a Pulsar Q&A discussion. It seemed that a hash range got blocked, but that wasn't the case.
      • The replay queue had a head-of-line blocking issue, which caused many hashes being blocked unnecessarily
      • In reading more entries, all entries got dropped when any of the read entries was blocked by a hash.
        • This is unnecessary for retaining ordering. This is addressed in this PR.
          • It seems that addressing this issues depends on PIP-282 changes, [fix][broker] Introduce the last sent position to fix message ordering issues in Key_Shared (PIP-282) #21953.

Since consumers were blocked unnecessarily, reading ahead would often just continue reading the complete backlog into the replay queue. The impact is described in #23200

  • Reading the entries to the replay queue causes unnecessary network traffic, disk IO & CPU on bookies and CPU on brokers. The read entries will be dropped in most cases.
    • Issue [improve] [broker] Avoid repeated Read-and-discard when using Key_Shared mode #22245 has been a previous attempt to mitigate this symptom
  • Reading ahead would cause a lot of "ack holes".
    • PIP-299 [improve] [pip] PIP-299: Stop dispatch messages if the individual acks will be lost in the persistent storage #21118 has been a previous attempt to mitigate this symptom

In addition to fix the infinite key shared look ahead issue, this PR seems to fix a problem in the existing implementation where this code blocks progress of a consumer:

pulsar/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumers.java

Lines 453 to 458 in d7e8ea1

if (readType == ReadType.Normal && stickyKeyHashes != null
&& redeliveryMessages.containsStickyKeyHashes(stickyKeyHashes)) {
// If redeliveryMessages contains messages that correspond to the same hash as the messages
// that the dispatcher is trying to send, do not send those messages for order guarantee
return 0;
}

What this means is that when the dispatcher has read a batch, it will discard all messages in the read messages if any hash is present in the replay queue (redelivery messages). This is an unoptimal solution for ensuring that ordering is preserved. This PR addresses the issue while attempting to keep backwards compatibility from a single consumer's perspective.

The "look ahead" limit introduced in this PR will add backpressure to how the dispatcher works. Eventually consumers will be slower than the dispatcher sending messages to consumers and that's why it's necessary to have the limit, also in cases where the hashes wouldn't be blocked or "allowOutOfOrderDelivery" mode is used.

There's also another related problem that this change addresses. The head of the replay queue might get blocked in the release Pulsar versions.

pulsar/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java

Lines 348 to 350 in ed14f21

NavigableSet<Position> messagesToReplayNow = getMessagesToReplayNow(messagesToRead);
NavigableSet<Position> messagesToReplayFiltered = filterOutEntriesWillBeDiscarded(messagesToReplayNow);
if (!messagesToReplayFiltered.isEmpty()) {

In this PR, the solution to this is to take as many entries that match the criteria from the replay queue. This required changing the getMessagesToReplayNow to accept a Predicate for filtering:

    public NavigableSet<Position> getMessagesToReplayNow(int maxMessagesToRead, Predicate<Position> filter) {
        NavigableSet<Position> items = new TreeSet<>();
        messagesToRedeliver.processItems(PositionFactory::create, item -> {
            if (filter.test(item)) {
                items.add(item);
            }
            return items.size() < maxMessagesToRead;
        });
        return items;
    }

Modifications

  1. Configuration Properties:

    • Added new configuration properties to control the limits of Key_Shared subscriptions look ahead in dispatching:
      • keySharedLookAheadMsgInReplayThresholdPerConsumer
      • keySharedLookAheadMsgInReplayThresholdPerSubscription
      • keySharedLookAheadEnabledWhenRecentlyJoinedConsumersExist
  2. Broker Configuration:

    • Updated broker.conf to include descriptions and default values for the new configuration properties.
  3. Key_Shared Subscription Logic:

    • Implement the key shared look-ahead limits that are configured with the above configuration properties.
    • Enhance the dispatching to ensure efficient dispatching:
      • Instead of filtering the list of entries pulled from the message redelivery controller, refactor the solution to take a function that can filter the entries until there's a sufficient amount of messages for dispatching.
        • This refactoring eliminates the previous method filterOutEntriesWillBeDiscarded while preserving the previous logic of filtering.
      • Remove the unnecessary thread-local fields localGroupedEntries and the unused localGroupedPositions.
        • It is unnecessary to eliminate the creation of short-lived objects in modern JVMs. It just clutters the code without any performance benefit. "No garbage" style is relevant mainly for long-lived objects stored in caches or large array allocations.
    • Replace getMessagesToReplayNow(1) with getFirstPositionInReplay().
      • This check will no longer have the side effect of pulling messages from delayed delivery when it's called.
    • Add a new method canReplayMessages to make the look-ahead logic more explicit. The previous solution of returning an empty set from the getMessagesToReplayNow method made it hard to understand how the look-ahead behavior is implemented.
    • Rename the isDispatcherStuckOnReplays field to skipNextReplayToTriggerLookAhead to make the meaning of the field explicit and self-descriptive.
    • Fix issue where the !havePendingReplayRead status wasn't checked before starting a new read.
      • For shared subscription, it's fine to just check !havePendingPendingRead, but for Key_Shared it isn't.
      • extract doesntHavePendingRead for handling the logic
    • Rename the keyNumbers variable to remainingConsumersToFinishSending so that the meaning of the variable is explicit and self-descriptive.
    • Rename the groupedEntries variable to entriesByConsumerForDispatching so that the meaning of the variable is explicit and self-descriptive.
    • Rename the entriesWithSameKey variable to entriesForConsumer so that the variable is self-descriptive.
    • Fix calculations based on maxUnackedMessages and unackedMessages. The unit is in individual messages and permits are in entries. These 2 cannot be mixed.
    • Addressing the consumer blocked issue: the logic has been changed to evaluate each message hash one-by-one.

Documentation

  • doc
  • doc-required
  • doc-not-needed
  • doc-complete

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@lhotari
lhotari requested review from codelipenghui, equanz, merlimat and poorbarcode August 27, 2024 12:25
@github-actions github-actions Bot added the doc-required Your PR changes impact docs and you will update later. label Aug 27, 2024
@lhotari lhotari added ready-to-test and removed doc-required Your PR changes impact docs and you will update later. labels Aug 27, 2024
@github-actions github-actions Bot added the doc-required Your PR changes impact docs and you will update later. label Aug 27, 2024
@lhotari
lhotari marked this pull request as ready for review August 27, 2024 12:45
@lhotari
lhotari marked this pull request as draft August 27, 2024 12:51
@lhotari

lhotari commented Aug 27, 2024

Copy link
Copy Markdown
Member Author

This PR is ready for initial review feedback. I'm looking into ways of adding tests for the key_shared look ahead limits.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Aug 27, 2024
[improve] PIP-381: Handle PositionInfo that's too large to serialize as a single entry #22799
Closed
[improve][broker] Reschedule reads with increasing backoff when no messages are dispatched #23226
Merged
lhotari
lhotari commented Aug 28, 2024
View reviewed changes
Comment thread .../apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumers.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

lhotari added 10 commits August 29, 2024 22:28
@lhotari
Refactor dispatching filtering logic
d565b92
- take more messages until maximum amount of messages has been picked
@lhotari
Limit Key_Shared look ahead
a5bade9
@lhotari
Move KeySharedSubscriptionTest out of flaky test group
ff2db40
@lhotari
Simplify method
25e6858
@lhotari
More code comments
8e4328f
@lhotari
Fix handling of permits
b577134
@lhotari
Fix assertions
b9dad9f
@lhotari
Improve readability
749d699
@lhotari
Remove permits check when entries have already been read
d1f13a8
- discarding entries at this point is a waste
- it's unnecessary to be accurate with permits. The message sending will
  handle subtracting permits.
@lhotari
Rename configuration property that uses msgInReplay concept
a263ad4
@lhotari
lhotari marked this pull request as ready for review August 29, 2024 19:31
@lhotari
lhotari force-pushed the lh-limit-keyshared-dispatching-read-ahead branch from 62a9fbf to a263ad4 Compare August 29, 2024 19:31
@lhotari
lhotari requested review from dao-jun, dlg99, eolivelli and nodece August 29, 2024 20:00
lhotari
lhotari commented Sep 6, 2024
View reviewed changes
Comment thread conf/broker.conf Resolved

Uh oh!

There was an error while loading. Please reload this page.

lhotari
lhotari commented Sep 6, 2024
View reviewed changes
Comment thread .../apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumers.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

lhotari added 2 commits September 7, 2024 09:37
@lhotari
Fix formula mentioned in doc (max->min)
bf89d96
@lhotari
Fix IntelliJ warning
e937a4e
@lhotari lhotari mentioned this pull request Sep 7, 2024
[Bug] key-SHARED subscription is not performing redelivery and going in infinite while loop of reading messages from disk and not dispatching any messages #21656
Closed
2 tasks done
lhotari added 2 commits September 10, 2024 09:57
@lhotari
Implement ConcurrentBitmapSortedLongPairSet.first
4c777af
@lhotari
Merge remote-tracking branch 'origin/master' into lh-limit-keyshared-…
9532f87
…dispatching-read-ahead
@lhotari lhotari mentioned this pull request Sep 12, 2024
[improve][pip] PIP-377: Automatic retry for failed acknowledgements #23267
Closed
1 of 4 tasks
lhotari added 3 commits September 18, 2024 12:32
@lhotari
Add testing utilities
0cdd5f7
@lhotari
Merge remote-tracking branch 'origin/master' into HEAD
02b18f6
@lhotari
Add test for read limit and fix the detected issue
b0d9fa0
@lhotari
lhotari marked this pull request as ready for review September 18, 2024 11:15
lhotari added 2 commits September 18, 2024 14:25
@lhotari
Reset read ahead limits to defaults after test method
7570136
@lhotari
Speed up tests using receiveAndAckMessages by consuming in multiple t…
8804bd0
…hreads
@lhotari
lhotari dismissed poorbarcode’s stale review September 18, 2024 11:37

Outdated comment

@lhotari lhotari added this to the 4.0.0 milestone Sep 18, 2024
lhotari added 4 commits September 18, 2024 14:56
@lhotari
Increase the default read ahead limit to 2000/50000
ba596a9
@lhotari
Follow the advice of setting to <= 2 * managedLedgerMaxUnackedRangesT…
48ff1af
…oPersist
@lhotari
Use max unacked messages limits when look ahead limits are disabled
57eaa77
@lhotari
Fix flaky test
c9e72c4
@lhotari
lhotari merged commit 77570d5 into apache:master Sep 18, 2024
This was referenced Sep 19, 2024
Flaky-test: AdminApiTransactionTest.testGetTransactionBufferInternalStats #23162
Closed
[fix] Key_Shared mode consumption latency when low traffic #23340
Merged
@poorbarcode

poorbarcode commented Sep 23, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

@lhotari

  • Three weeks ago: I submitted a Request Change

  • Two weeks ago, you left a comment: Noticing more challenges to cover while getting into the tests. Setting this to draft mode until the concerns are addressed and tests have been added. Some of the concerns are related to [Bug] Consumers getting stuck since read more entries doesn't properly handle retries with backoff #23264.

  • 5 days ago: you dismissed the Request Change, and left a comment: "Outdated comment"

Between step-2 and step-3, you never marked it as available to review and never ask to review again, then you merged the PR 😂

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari

lhotari commented Sep 24, 2024

Copy link
Copy Markdown
Member Author

I'm sorry @poorbarcode. Please let me explain the misunderstanding.

5 days ago: you dismissed the Request Change, and left a comment: "Outdated comment"

For me, the "request for changes" comment was "Please do not merge this PR fast, I will finish my review tomorrow" (#23231 (review)). That's why I dismissed it with "Outdated comment". I had already addressed also the other review comments you had made.

Between step-2 and step-3, you never marked it as available to review and never ask to review again, then you merged the PR 😂

I'm sorry for that. I did request a review, but you didn't respond. You can check the timeline. The PR was in draft mode for some time, but the reason for that was that the PR was already approved and I didn't want anyone to merge it. I didn't realize that you wouldn't be reviewing it because of the draft status.

The changes in this PR aren't final, if you have review feedback, it's possible also address that after the PR has been merged. Please add comments to this PR of any concerns you may have.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@poorbarcode

poorbarcode commented Sep 24, 2024

Copy link
Copy Markdown
Contributor

@lhotari

Sure, thanks for replying this comment. ❤️

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Oct 9, 2024
[Draft] [fix] [broker] Add a limitation of max memory usage of the replay queue #20169
Closed
[Bug] Consumers getting stuck since read more entries doesn't properly handle retries with backoff #23264
Closed
hanmz pushed a commit to hanmz/pulsar that referenced this pull request Feb 12, 2025
@lhotari @merlimat
@equanz hanmz
[improve][broker] Add limits for Key_Shared Subscription look ahead i…
a095792
…n dispatching (apache#23231)

Co-authored-by: Matteo Merli <[email protected]>
Co-authored-by: Yuri Mizushima <[email protected]>
@lhotari lhotari mentioned this pull request Apr 16, 2026
Add WARN log when cursor ack holes exceed managedLedgerMaxUnackedRangesToPersist #25540
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@eolivelli eolivelli eolivelli left review comments
@merlimat merlimat merlimat approved these changes
@dlg99 dlg99 dlg99 approved these changes
@equanz equanz equanz approved these changes
@nodece nodece nodece approved these changes
@dao-jun dao-jun dao-jun approved these changes
@liudezhi2098 liudezhi2098 liudezhi2098 approved these changes
@codelipenghui codelipenghui Awaiting requested review from codelipenghui
@rdhabalia rdhabalia Awaiting requested review from rdhabalia
@hezhangjian hezhangjian Awaiting requested review from hezhangjian
@tisonkun tisonkun Awaiting requested review from tisonkun
@michaeljmarshall michaeljmarshall Awaiting requested review from michaeljmarshall
@thetumbled thetumbled Awaiting requested review from thetumbled
@liangyepianzhou liangyepianzhou Awaiting requested review from liangyepianzhou
@poorbarcode poorbarcode Awaiting requested review from poorbarcode

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

doc-required Your PR changes impact docs and you will update later. ready-to-test

Projects

Apache Pulsar / Key_Shared and Acknowledgement reliability and usability improvements
Status: Done

Milestone

4.0.0

Development

Successfully merging this pull request may close these issues.

[Bug] Key_Shared subscription could deliver messages late and nonContiguousDeletedMessagesRange could exceed managedLedgerMaxUnackedRangesToPersist

Uh oh!

There was an error while loading. Please reload this page.

10 participants

@lhotari @equanz @codecov-commenter @poorbarcode @merlimat @dlg99 @eolivelli @nodece @dao-jun @liudezhi2098
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.