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 — [fix][broker] Fix persistent throughput degradation caused by permit … · apache/pulsar@b0a2b1f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker/src
    • main/java/org/apache/pulsar/broker/service
      • AbstractDispatcherMultipleConsumers.java
      • Consumer.java
      • persistent
        • PersistentDispatcherMultipleConsumers.java
        • PersistentDispatcherMultipleConsumersClassic.java
    • test/java/org/apache/pulsar/broker/service/persistent
      • SharedDispatcherPermitAccountingTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/service/AbstractDispatcherMultipleConsumers.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/AbstractDispatcherMultipleConsumers.java
+14-1Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
public abstract class AbstractDispatcherMultipleConsumers extends AbstractBaseDispatcher {
3333

3434
protected final CopyOnWriteArrayList<Consumer> consumerList = new CopyOnWriteArrayList<>();
35-
protected final ObjectSet<Consumer> consumerSet = new ObjectHashSet<>();
35+
private final ObjectHashSet<Consumer> consumerSetImpl = new ObjectHashSet<>();
36+
protected final ObjectSet<Consumer> consumerSet = consumerSetImpl;
3637
protected volatile int currentConsumerRoundRobinIndex = 0;
3738

3839
protected static final int FALSE = 0;
@@ -58,6 +59,18 @@ public synchronized boolean canUnsubscribe(Consumer consumer) {
5859
return consumerList.size() == 1 && consumerSet.contains(consumer);
5960
}
6061

62+
/**
63+
* Checks whether the exact Consumer instance is still connected.
64+
*
65+
* <p>This differs from {@link ObjectSet#contains(Object)}, which uses {@link Consumer#equals(Object)} and can
66+
* match a replacement Consumer that reuses the same protocol identity.
67+
* The caller must hold the dispatcher monitor while checking membership and acting on the result.
68+
*/
69+
protected final boolean containsConsumerInstance(Consumer consumer) {
70+
int index = consumerSetImpl.indexOf(consumer);
71+
return consumerSetImpl.indexExists(index) && consumerSetImpl.indexGet(index) == consumer;
72+
}
73+
6174
public boolean isClosed() {
6275
return isClosed == TRUE;
6376
}
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Consumer.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Consumer.java
+65-2Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,18 @@ public class Consumer {
112112
private static final AtomicIntegerFieldUpdater<Consumer> MESSAGE_PERMITS_UPDATER =
113113
AtomicIntegerFieldUpdater.newUpdater(Consumer.class, "messagePermits");
114114
private volatile int messagePermits = 0;
115+
/**
116+
* Guards the Flow-side compound update of {@link #messagePermits} and
117+
* {@link #pendingDispatcherFlowPermits}. A Flow command increases the consumer permits before the dispatcher
118+
* processes the corresponding update asynchronously. Consumer removal can happen between those two operations,
119+
* so both values must be observed consistently when calculating how many permits are already included in the
120+
* dispatcher total.
121+
*
122+
* <p>The dispatcher callback is invoked only after this lock is released. This avoids holding the lock while
123+
* calling into the subscription and preserves the lock order used by dispatcher flow processing and removal.
124+
*/
125+
private final Object flowPermitAccountingLock = new Object();
126+
private int pendingDispatcherFlowPermits = 0;
115127
// It starts keep tracking of messagePermits once consumer gets blocked, as consumer needs two separate counts:
116128
// messagePermits (1) before and (2) after being blocked: to dispatch only blockedPermit number of messages at the
117129
// time of redelivery
@@ -840,7 +852,7 @@ public void flowPermits(int additionalNumberOfMessages) {
840852
}
841853
int oldPermits;
842854
if (!blockedConsumerOnUnackedMsgs) {
843-
oldPermits = MESSAGE_PERMITS_UPDATER.getAndAdd(this, additionalNumberOfMessages);
855+
oldPermits = addPermitsPendingDispatcherUpdate(additionalNumberOfMessages);
844856
if (log.isDebugEnabled()) {
845857
log.debug("[{}-{}] Added {} message permits in broker.service.Consumer before updating dispatcher "
846858
+ "for consumer {}", topicName, subscription, additionalNumberOfMessages, consumerId);
@@ -867,7 +879,7 @@ public void flowPermits(int additionalNumberOfMessages) {
867879
void flowConsumerBlockedPermits(Consumer consumer) {
868880
int additionalNumberOfPermits = PERMITS_RECEIVED_WHILE_CONSUMER_BLOCKED_UPDATER.getAndSet(consumer, 0);
869881
// add newly flow permits to actual consumer.messagePermits
870-
MESSAGE_PERMITS_UPDATER.getAndAdd(consumer, additionalNumberOfPermits);
882+
consumer.addPermitsPendingDispatcherUpdate(additionalNumberOfPermits);
871883
if (log.isDebugEnabled()){
872884
log.debug("[{}-{}] Added {} blocked permits to broker.service.Consumer for consumer {}", topicName,
873885
subscription, additionalNumberOfPermits, consumerId);
@@ -880,6 +892,57 @@ public int getAvailablePermits() {
880892
return MESSAGE_PERMITS_UPDATER.get(this);
881893
}
882894

895+
/**
896+
* Adds permits after a Flow command is accepted and immediately before notifying the dispatcher. The pending
897+
* count covers the interval until the dispatcher's asynchronous Flow task starts processing the same permits.
898+
*/
899+
private int addPermitsPendingDispatcherUpdate(int additionalNumberOfPermits) {
900+
if (!shouldTrackPendingDispatcherFlowPermits()) {
901+
return MESSAGE_PERMITS_UPDATER.getAndAdd(this, additionalNumberOfPermits);
902+
}
903+
synchronized (flowPermitAccountingLock) {
904+
pendingDispatcherFlowPermits += additionalNumberOfPermits;
905+
return MESSAGE_PERMITS_UPDATER.getAndAdd(this, additionalNumberOfPermits);
906+
}
907+
}
908+
909+
private boolean shouldTrackPendingDispatcherFlowPermits() {
910+
return isPersistentTopic && Subscription.isIndividualAckMode(subType);
911+
}
912+
913+
/**
914+
* Called at the start of the dispatcher's asynchronous Flow task, before checking whether this consumer is still
915+
* connected. At this point the Flow update is no longer pending: the dispatcher will either add the permits to
916+
* its total or ignore them because the consumer has already been removed.
917+
*/
918+
public void completePendingDispatcherFlow(int additionalNumberOfPermits) {
919+
synchronized (flowPermitAccountingLock) {
920+
// Preserve the accounting delta across signed int wrap, matching the other permit counters.
921+
pendingDispatcherFlowPermits -= additionalNumberOfPermits;
922+
}
923+
}
924+
925+
/**
926+
* Called while the dispatcher removes this consumer. Permits belonging to Flow tasks that have not started yet
927+
* are excluded because those permits have not been added to the dispatcher total and must not be subtracted from
928+
* it during removal.
929+
*
930+
* <p>This accounting is enabled for persistent Shared and Key_Shared dispatchers. It relies on every dispatcher
931+
* Flow task calling {@link #completePendingDispatcherFlow(int)} before applying or ignoring the update. For these
932+
* dispatchers, when observed under the dispatcher monitor, the total available permits equal the sum of this
933+
* balance over all connected consumers.
934+
*
935+
* <p>The returned balance can be negative. A pending Flow makes permits visible on the consumer before its
936+
* asynchronous dispatcher update runs, so the dispatcher can consume those permits while they are still counted
937+
* as pending. Subtracting the negative balance during removal is required to restore the dispatcher total; callers
938+
* must not clamp it to zero.
939+
*/
940+
public int getAvailablePermitsForDispatcherRemoval() {
941+
synchronized (flowPermitAccountingLock) {
942+
return MESSAGE_PERMITS_UPDATER.get(this) - pendingDispatcherFlowPermits;
943+
}
944+
}
945+
883946
/**
884947
* return 0 if there is no entry dispatched yet.
885948
*/
Collapse file

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

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
+20-6Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import com.google.common.annotations.VisibleForTesting;
2424
import com.google.common.collect.Lists;
2525
import com.google.common.collect.Range;
26+
import io.netty.channel.EventLoopGroup;
2627
import java.util.ArrayList;
2728
import java.util.Collections;
2829
import java.util.Comparator;
@@ -34,6 +35,7 @@
3435
import java.util.concurrent.CompletableFuture;
3536
import java.util.concurrent.CopyOnWriteArrayList;
3637
import java.util.concurrent.ExecutorService;
38+
import java.util.concurrent.RejectedExecutionException;
3739
import java.util.concurrent.TimeUnit;
3840
import java.util.concurrent.atomic.AtomicBoolean;
3941
import java.util.concurrent.atomic.AtomicInteger;
@@ -245,10 +247,13 @@ public synchronized void removeConsumer(Consumer consumer) throws BrokerServiceE
245247
notifyAddedToReplay.setTrue();
246248
}
247249
});
248-
totalAvailablePermits -= consumer.getAvailablePermits();
250+
// Restore the invariant that the dispatcher total equals the sum of the removal balances of the
251+
// remaining consumers. Exclude Flow permits that have not updated the dispatcher total yet.
252+
int availablePermits = consumer.getAvailablePermitsForDispatcherRemoval();
253+
totalAvailablePermits -= availablePermits;
249254
if (log.isDebugEnabled()) {
250255
log.debug("[{}] Decreased totalAvailablePermits by {} in PersistentDispatcherMultipleConsumers. "
251-
+ "New dispatcher permit count is {}", name, consumer.getAvailablePermits(),
256+
+ "New dispatcher permit count is {}", name, availablePermits,
252257
totalAvailablePermits);
253258
}
254259
if (notifyAddedToReplay.booleanValue()) {
@@ -288,13 +293,22 @@ protected synchronized void clearComponentsAfterRemovedAllConsumers() {
288293

289294
@Override
290295
public void consumerFlow(Consumer consumer, int additionalNumberOfMessages) {
291-
topic.getBrokerService().executor().execute(() -> {
292-
internalConsumerFlow(consumer, additionalNumberOfMessages);
293-
});
296+
EventLoopGroup flowExecutor = topic.getBrokerService().executor();
297+
try {
298+
flowExecutor.execute(() -> internalConsumerFlow(consumer, additionalNumberOfMessages));
299+
} catch (RejectedExecutionException e) {
300+
// Leave the permits pending so removal excludes this unapplied Flow during broker shutdown.
301+
if (log.isDebugEnabled()) {
302+
log.debug("[{}] Unable to schedule flow control update for consumer {}, executorShutdown={}",
303+
name, consumer, flowExecutor.isShuttingDown(), e);
304+
}
305+
}
294306
}
295307

296308
private synchronized void internalConsumerFlow(Consumer consumer, int additionalNumberOfMessages) {
297-
if (!consumerSet.contains(consumer)) {
309+
// The queued Flow task is no longer pending, even if the consumer was removed while the task was waiting.
310+
consumer.completePendingDispatcherFlow(additionalNumberOfMessages);
311+
if (!containsConsumerInstance(consumer)) {
298312
if (log.isDebugEnabled()) {
299313
log.debug("[{}] Ignoring flow control from disconnected consumer {}", name, consumer);
300314
}
Collapse file

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

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumersClassic.java
+20-6Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import com.google.common.annotations.VisibleForTesting;
2323
import com.google.common.collect.Lists;
2424
import com.google.common.collect.Range;
25+
import io.netty.channel.EventLoopGroup;
2526
import java.util.ArrayList;
2627
import java.util.Collections;
2728
import java.util.Comparator;
@@ -33,6 +34,7 @@
3334
import java.util.concurrent.CompletableFuture;
3435
import java.util.concurrent.CopyOnWriteArrayList;
3536
import java.util.concurrent.ExecutorService;
37+
import java.util.concurrent.RejectedExecutionException;
3638
import java.util.concurrent.TimeUnit;
3739
import java.util.concurrent.atomic.AtomicBoolean;
3840
import java.util.concurrent.atomic.AtomicInteger;
@@ -230,10 +232,13 @@ public synchronized void removeConsumer(Consumer consumer) throws BrokerServiceE
230232
consumer.getPendingAcks().forEach((ledgerId, entryId, batchSize, stickyKeyHash) -> {
231233
addMessageToReplay(ledgerId, entryId, stickyKeyHash);
232234
});
233-
totalAvailablePermits -= consumer.getAvailablePermits();
235+
// Restore the invariant that the dispatcher total equals the sum of the removal balances of the
236+
// remaining consumers. Exclude Flow permits that have not updated the dispatcher total yet.
237+
int availablePermits = consumer.getAvailablePermitsForDispatcherRemoval();
238+
totalAvailablePermits -= availablePermits;
234239
if (log.isDebugEnabled()) {
235240
log.debug("[{}] Decreased totalAvailablePermits by {} in PersistentDispatcherMultipleConsumers. "
236-
+ "New dispatcher permit count is {}", name, consumer.getAvailablePermits(),
241+
+ "New dispatcher permit count is {}", name, availablePermits,
237242
totalAvailablePermits);
238243
}
239244
readMoreEntries();
@@ -266,13 +271,22 @@ private synchronized void clearComponentsAfterRemovedAllConsumers() {
266271

267272
@Override
268273
public void consumerFlow(Consumer consumer, int additionalNumberOfMessages) {
269-
topic.getBrokerService().executor().execute(() -> {
270-
internalConsumerFlow(consumer, additionalNumberOfMessages);
271-
});
274+
EventLoopGroup flowExecutor = topic.getBrokerService().executor();
275+
try {
276+
flowExecutor.execute(() -> internalConsumerFlow(consumer, additionalNumberOfMessages));
277+
} catch (RejectedExecutionException e) {
278+
// Leave the permits pending so removal excludes this unapplied Flow during broker shutdown.
279+
if (log.isDebugEnabled()) {
280+
log.debug("[{}] Unable to schedule flow control update for consumer {}, executorShutdown={}",
281+
name, consumer, flowExecutor.isShuttingDown(), e);
282+
}
283+
}
272284
}
273285

274286
private synchronized void internalConsumerFlow(Consumer consumer, int additionalNumberOfMessages) {
275-
if (!consumerSet.contains(consumer)) {
287+
// The queued Flow task is no longer pending, even if the consumer was removed while the task was waiting.
288+
consumer.completePendingDispatcherFlow(additionalNumberOfMessages);
289+
if (!containsConsumerInstance(consumer)) {
276290
if (log.isDebugEnabled()) {
277291
log.debug("[{}] Ignoring flow control from disconnected consumer {}", name, consumer);
278292
}

0 commit comments

Comments
0 (0)
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.