Skip to content

CPU usage 100% when use Key_Shared #15445

Closed

Description

@Shawyeok

Describe the bug
When use Key_Shared, if one consumer consume slowly and others are normal, MessageRedeliveryController#messagesToRedeliver will keep growing and could be very large.

MessageRedeliveryController#getMessagesToReplayNow will be very expensive cause messagesToRedeliver.items() is a O(n) operation in both time and space complexity.

public Set<PositionImpl> getMessagesToReplayNow(int maxMessagesToRead) {
if (hashesToBeBlocked != null) {
// allowOutOfOrderDelivery is false
return messagesToRedeliver.items().stream()
.sorted((l1, l2) -> ComparisonChain.start().compare(l1.first, l2.first)
.compare(l1.second, l2.second).result())
.limit(maxMessagesToRead).map(longPair -> new PositionImpl(longPair.first, longPair.second))
.collect(Collectors.toCollection(TreeSet::new));
} else {
// allowOutOfOrderDelivery is true
return messagesToRedeliver.items(maxMessagesToRead,
(ledgerId, entryId) -> new PositionImpl(ledgerId, entryId));
}
}

In this situation, one thread cpu usage could be 100%, this could effects the publish latency of other topics on the same broker instance.

To Reproduce
Steps to reproduce the behavior:

  1. start a standalone cluster
  2. start a producer
$ bin/pulsar-perf produce -mk random persistent://public/default/test
  1. start a slow consumer and a normal consumer
$ bin/pulsar-perf consume -st Key_Shared persistent://public/default/test
$ bin/pulsar-perf consume -st Key_Shared -r 0.1 persistent://public/default/test

Screenshots
CPU flame graph
image

Additional context

  • pulsar: 2.8.1

Activity

  1. added
    type/bug
    on May 5, 2022
  2. Shawyeok commented on May 5, 2022

    @Shawyeok
    ContributorAuthor

    When use Key_Shared, if one consumer consume slowly and others are normal, MessageRedeliveryController#messagesToRedeliver will keep growing and could be very large.

    Additional context:
    The slow consumer will ends with zero availablePermits, and message positions will be recorded in MessageRedeliveryController#messagesToRedeliver, when none of the whole batch of messages sent to consumer, isDispatcherStuckOnReplays will be marked.

    if (totalMessagesSent == 0 && (recentlyJoinedConsumers == null || recentlyJoinedConsumers.isEmpty())) {
    // This means, that all the messages we've just read cannot be dispatched right now.
    // This condition can only happen when:
    // 1. We have consumers ready to accept messages (otherwise the would not haven been triggered)
    // 2. All keys in the current set of messages are routing to consumers that are currently busy
    // and stuck is not caused by stuckConsumers
    //
    // The solution here is to move on and read next batch of messages which might hopefully contain
    // also keys meant for other consumers.
    //
    // We do it unless that are "recently joined consumers". In that case, we would be looking
    // ahead in the stream while the new consumers are not ready to accept the new messages,
    // therefore would be most likely only increase the distance between read-position and mark-delete
    // position.
    if (!nextStuckConsumers.isEmpty()) {
    isDispatcherStuckOnReplays = true;
    stuckConsumers.addAll(nextStuckConsumers);
    }
    // readMoreEntries should run regardless whether or not stuck is caused by
    // stuckConsumers for avoid stopping dispatch.
    topic.getBrokerService().executor().execute(() -> readMoreEntries());

    Next time call getMessagesToReplayNow in readMoreEntries, it'll returns empty, then it'll read next batch of messages by cursor, therefor more message positions will be recorded.

    protected synchronized Set<PositionImpl> getMessagesToReplayNow(int maxMessagesToRead) {
    if (isDispatcherStuckOnReplays) {
    // If we're stuck on replay, we want to move forward reading on the topic (until the overall max-unacked
    // messages kicks in), instead of keep replaying the same old messages, since the consumer that these
    // messages are routing to might be busy at the moment
    this.isDispatcherStuckOnReplays = false;
    return Collections.emptySet();
    } else {
    return super.getMessagesToReplayNow(maxMessagesToRead);
    }
    }

    if (totalMessagesSent == 0 && (recentlyJoinedConsumers == null || recentlyJoinedConsumers.isEmpty())) {
    // This means, that all the messages we've just read cannot be dispatched right now.
    // This condition can only happen when:
    // 1. We have consumers ready to accept messages (otherwise the would not haven been triggered)
    // 2. All keys in the current set of messages are routing to consumers that are currently busy
    // and stuck is not caused by stuckConsumers
    //
    // The solution here is to move on and read next batch of messages which might hopefully contain
    // also keys meant for other consumers.
    //
    // We do it unless that are "recently joined consumers". In that case, we would be looking
    // ahead in the stream while the new consumers are not ready to accept the new messages,
    // therefore would be most likely only increase the distance between read-position and mark-delete
    // position.
    if (!nextStuckConsumers.isEmpty()) {
    isDispatcherStuckOnReplays = true;
    stuckConsumers.addAll(nextStuckConsumers);
    }
    // readMoreEntries should run regardless whether or not stuck is caused by
    // stuckConsumers for avoid stopping dispatch.
    topic.getBrokerService().executor().execute(() -> readMoreEntries());

  3. added this to the 2.11.0 milestone on May 5, 2022
  4. merlimat commented on May 5, 2022

    @merlimat
    Contributor

    @Shawyeok Can you attach the flame graph directly?

  5. Shawyeok commented on May 6, 2022

    @Shawyeok
    ContributorAuthor

    @Shawyeok Can you attach the flame graph directly?

    @merlimat cpu_profile.html.zip attached

  6. surahman commented on May 11, 2022

    @surahman
    Member

    This is a very interesting issue to examine.

    I think the time bound is likely O(n*log(n)) due to the TreeSet generation (sorting) here:

    Edit:
    We sort here to get the limit of items (top few?) in the collection:

    .sorted((l1, l2) -> ComparisonChain.start().compare(l1.first, l2.first)
    .compare(l1.second, l2.second).result())
    .limit(maxMessagesToRead).map(longPair -> new PositionImpl(longPair.first, longPair.second))

    We then generate a TreeSet, which is an LLRB Tree, with a sorted list. This will rebalance the tree during each insert (expensive):

    I know there is typically an order guarantee within, but not across, partitions of topics in pub-sub systems. If there is no need for an ordered iteration through the set it might be possible to squeeze a little bit of performance out of using a HashSet. You would need a custom comparator and equality implementation for the data type being inserted.

  7. github-actions commented on Jun 12, 2022

    @github-actions

    The issue had no activity for 30 days, mark with Stale label.

  8. modified the milestones: 2.11.0, 2.12.0 on Jul 26, 2022
  9. zhanghaou commented on Dec 5, 2022

    @zhanghaou
    Contributor

    We also encounter such problem,topics in the same broker publish latency is very high. Any suggestions? @merlimat @codelipenghui

  10. codelipenghui commented on Dec 5, 2022

    @codelipenghui
    Contributor

    The issue should be fixed by #17804
    @zhanghaou @Shawyeok

  11. zhanghaou commented on Dec 5, 2022

    @zhanghaou
    Contributor

    @codelipenghui Does the fix pr can be cherry pick to branch 2.8.X?

  12. codelipenghui commented on Dec 5, 2022

    @codelipenghui
    Contributor

    @zhanghaou We are only applying security patches for 2.8.x release for now.

  13. zhanghaou commented on Dec 5, 2022

    @zhanghaou
    Contributor

    @codelipenghui OK, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Staletype/bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions