You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "codelipenghui (via GitHub)" <gi...@apache.org> on 2026/10/15 22:48:44 UTC

[PR] [fix][broker] Fix inflated rate stats of newly created consumers [pulsar]

codelipenghui opened a new pull request, #26928:
URL: https://github.com/apache/pulsar/pull/26928

   ### Motivation
   
   Consumer rate stats (`msgRateOut`, `msgThroughputOut`, `messageAckRate`, `msgRateRedeliver`, `chunkedMessageRate`) are inflated for consumers created shortly before the stats update.
   
   - Each `Consumer` creates its `Rate`s in its constructor, and a `Rate` starts its period at construction (`lastCalculatedTime = System.nanoTime()`). The stats update, which runs every `statsUpdateFrequencyInSecs` (60 s by default), divides the events counted since then by `now - lastCalculatedTime`.
   - A new consumer receives a burst as soon as it sends its flow permits, because the broker fills its receiver queue. If the consumer was created Δ before the stats update, its first rate is "burst / Δ", which is huge for a small Δ. That value is then held until the next stats update, or until the consumer disconnects.
   - Subscription, topic, namespace and bundle rates add up the rates of the connected consumers. So the inflated value shows up in topic stats, in `pulsar_rate_out` / `pulsar_throughput_out`, and in the bundle stats used by the load manager. The byte and message counters stay correct.
   
   The `__compaction` subscription hits this on every compaction run:
   
   - The compaction check (`brokerServiceCompactionMonitorIntervalInSeconds`) and the stats update both run on 60 s fixed-rate timers started at broker startup, so on a given broker they fire close together.
   - Each compaction run creates a new `RawReader` consumer with a 1000-entry receiver queue. It gets a burst as soon as it starts reading and can be only a fraction of a second old when its rate is calculated.
   - A scrape only shows the spike if it lands while the compactor is connected. So one partition can report a throughput far above its byte counters while the others don't.
   
   The arithmetic in isolation: `new Rate()`, record 26 MB, wait 90 ms, `calculateRate()` gives 26 MB / 0.09 s ≈ 290 MB/s.
   
   ### Modifications
   
   - `AbstractTopic#endStatsPeriod()` returns the time since the previous stats update of the topic and starts the next period. It is only called from `updateRates`, which runs under the `PulsarStats` lock.
   - `PersistentTopic#updateRates` and `NonPersistentTopic#updateRates` call it once and pass the period to every consumer.
   - `Consumer#updateRates()` becomes `Consumer#updateRates(double periodInSeconds)` and calculates all its rates over the given period.
   
   Consumers that existed for the whole period get the same period as before, so their rates don't change. A consumer created during the period now has its events averaged over the whole period, consistent with the counters, instead of over its own age.
   
   Producers, replicators and the expiry monitor still compute rates over their own age. They are out of scope for this PR.
   
   ### Verifying this change
   
   - [ ] Make sure that the change passes the CI checks.
   
   This change added tests and can be verified as follows:
   
   - Added `ConsumerStatsTest#testNewConsumerRateCoversTheWholeStatsPeriod`. A consumer created about 1 s after the previous stats update receives a burst of 100 messages, and its `msgRateOut` / `msgThroughputOut` must equal its counters divided by the stats period. Without the fix, the consumer reported 896 msg/s instead of ~88 msg/s.
   - The periodic stats task is disabled in `ConsumerStatsTest`, so it can't shift the stats period the tests check. `testMessageAckRateMetric` now calls `BrokerService#updateRates()` instead of `Consumer#updateRates()`.
   - `ConsumerStatsTest`, `PrometheusMetricsTest`, `NonPersistentTopicTest`, `SimpleProducerConsumerStatTest`, `DispatcherBlockConsumerTest#testBlockDispatcherStats` and `KeySharedSubscriptionTest#testDeliveryOfRemainingMessagesWithoutDeadlock` pass locally.
   
   ### Does this pull request potentially affect one of the following parts:
   
   <!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
   
   *If the box was checked, please highlight the changes*
   
   - [ ] Dependencies (add or upgrade a dependency)
   - [ ] The public API
   - [ ] The schema
   - [ ] The default values of configurations
   - [ ] The threading model
   - [ ] The binary protocol
   - [ ] The REST endpoints
   - [ ] The admin CLI options
   - [x] The metrics
   - [ ] Anything that affects deployment
   
   The metrics: no metric is added, removed or renamed. Only the rate values of consumers that connected during the current stats period change, along with the subscription, topic, namespace and broker rates aggregated from them. These rates are now averaged over the topic's stats period instead of over the consumer's age.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][broker] Fix inflated rate stats of newly created consumers [pulsar]

Posted by "poorbarcode (via GitHub)" <gi...@apache.org>.
poorbarcode commented on code in PR #26928:
URL: https://github.com/apache/pulsar/pull/26928#discussion_r4290243057


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Consumer.java:
##########
@@ -1178,11 +1178,11 @@ void beforeSettingBlockedConsumerOnUnackedMessages() {
         // Test hook for deterministically ordering a threshold crossing against an unblock.
     }
 
-    public void updateRates() {
-        msgOut.calculateRate();
-        chunkedMessageRate.calculateRate();
-        msgRedeliver.calculateRate();
-        messageAckRate.calculateRate();
+    public void updateRates(double periodInSeconds) {
+        msgOut.calculateRate(periodInSeconds);

Review Comment:
   Perhaps we just need to do it this way: consider the `period` as `1` when it is less than `1`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][broker] Fix inflated rate stats of newly created consumers [pulsar]

Posted by "codelipenghui (via GitHub)" <gi...@apache.org>.
codelipenghui merged PR #26928:
URL: https://github.com/apache/pulsar/pull/26928


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][broker] Fix inflated rate stats of newly created consumers [pulsar]

Posted by "poorbarcode (via GitHub)" <gi...@apache.org>.
poorbarcode commented on code in PR #26928:
URL: https://github.com/apache/pulsar/pull/26928#discussion_r4290503706


##########
pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/ConsumerStatsTest.java:
##########
@@ -435,6 +438,44 @@ private void testMessageAckRateMetric(String topicName, boolean exposeTopicLevel
         }
     }
 
+    @Test
+    public void testNewConsumerRateIsNotInflatedByItsInitialBurst() throws Exception {
+        final String topicName = newUniqueName("persistent://my-property/my-ns/new-consumer-rate");
+        final int messages = 100;
+        @Cleanup
+        Producer<byte[]> producer = pulsarClient.newProducer()
+                .topic(topicName)
+                .enableBatching(false)
+                .create();
+        for (int i = 0; i < messages; i++) {
+            producer.send(new byte[1024]);
+        }
+        admin.topics().createSubscription(topicName, "sub", MessageId.earliest);
+        // reload the topic, so that it is as young as the consumer
+        admin.topics().unload(topicName);
+
+        // like the compaction reader, a new consumer receives a burst as soon as it sends its flow permits
+        long consumerCreationLowerBound = System.nanoTime();
+        @Cleanup
+        Consumer<byte[]> consumer = pulsarClient.newConsumer()
+                .topic(topicName)
+                .subscriptionName("sub")
+                .subscribe();
+        org.apache.pulsar.broker.service.Consumer brokerConsumer = pulsar.getBrokerService()

Review Comment:
   In the test before submitting the code this time: the variable `periodStartUpperBound` should set its initial value after the consumer is created, because the `consumer.rate.lastCalculatedTime` of the consumer is initialised only when the consumer is created. This is the reason why the original test has always failed.
   
   - update rate the first time
     - set `periodStartUpperBound`: `time_update_1st_before`
     - set `periodStartUpperBound`: `time_update_1st`
     - set `periodStartUpperBound`: `time_update_1st_after`
   - create consumer, then `consumer.rate.lastCalculatedTime` is `time_create_consumer`
   - update rate the second time
     - set `periodEndLowerBound`: `time_update_2st_before`
     - set `periodStartUpperBound`: `time_update_2st`
     - set `periodEndLowerBound`: `time_update_2st_after`
   
   Then the test(before submitting the code this time) assumed `time_update_2st_before - time_update_1st_after` should be smaller than `time_update_2st - time_create_consumer`, but it is wrong, which is the root cause of the failure of the test
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][broker] Fix inflated rate stats of newly created consumers [pulsar]

Posted by "poorbarcode (via GitHub)" <gi...@apache.org>.
poorbarcode commented on code in PR #26928:
URL: https://github.com/apache/pulsar/pull/26928#discussion_r4290223687


##########
pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/ConsumerStatsTest.java:
##########
@@ -435,6 +437,51 @@ private void testMessageAckRateMetric(String topicName, boolean exposeTopicLevel
         }
     }
 
+    @Test
+    public void testNewConsumerRateCoversTheWholeStatsPeriod() throws Exception {
+        final String topicName = newUniqueName("persistent://my-property/my-ns/new-consumer-rate");
+        final int messages = 100;
+        @Cleanup
+        Producer<byte[]> producer = pulsarClient.newProducer()
+                .topic(topicName)
+                .enableBatching(false)
+                .create();
+        for (int i = 0; i < messages; i++) {
+            producer.send(new byte[1024]);
+        }
+
+        // start a stats period that is much longer than the age of the consumer created below

Review Comment:
   It seems that this solution merely forces the extension of "period" and simultaneously forces the reduction of the value of consumer rate (relative to the actual value), because the creation time of the topic is always less than that of the consumer.
   
   In the test, if we unload the topic before creating the consumer, the creation time of the topic will be close to that of the consumer, and this test will fail.
   
   ```java
   admin.topics().createSubscription(topicName, "sub", MessageId.earliest);
   admin.topics().unload(topicName);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org