leizhiyuan opened a new issue, #11537:
URL: https://github.com/apache/rocketmq/issues/11537
### Before Creating the Bug Report
- [x] I found a bug, not just asking a question, which should be created in
GitHub Discussions.
- [x] I have searched the GitHub Issues and GitHub Discussions of this
repository and believe that this is not a duplicate.
- [x] I have confirmed that this bug belongs to the current repository, not
other repositories of RocketMQ.
### Runtime platform environment
Linux x86_64 (TencentOS Server 4, kernel 6.6), 32 cores. The problems are in
the Java client and are not OS-specific.
### RocketMQ version
- branch: `develop`
- version: `5.5.1`
- commit: `28960fd2f795a6903665c3d6c037501059df0760` (`ProduceAccumulator`
was last changed by #9016)
### JDK Version
- Unit tests: Corretto 8u492 (same major version as CI) and Corretto 21.0.12
- Benchmarks: Corretto 21.0.12 and Corretto 25.0.5
### Describe the Bug
#### Background
With `autoBatch=true`, `DefaultMQProducer#sendByAccumulator` passes
batchable messages to `ProduceAccumulator`, which is shared by all producers
with the same client ID (RIP-27, #3717). Messages are grouped by `(topic,
queue, waitStoreMsgOK, tag)` into a `MessageAccumulation`. A batch is sent as
one `MessageBatch` once it exceeds `batchMaxBytes` or once `batchMaxDelayMs`
has expired. The total number of buffered bytes is limited by
`totalBatchMaxBytes`: `tryAddMessage` reserves a message's body size in
`currentlyHoldSize` before the message enters the accumulator, and the size is
released when its batch completes.
On the sync path, each caller enqueues its message and then waits inside
`synchronized (batch)`:
```java
synchronized (this) {
while (!this.closed.get()) {
if (readyToSend()) {
this.send(); // network call, made while holding the batch
monitor
break;
} else {
this.wait();
}
}
return ret;
}
```
When the hold time expires, only `GuardForSyncSendService` wakes the
waiters. Every `holdMs / 2` it visits each sync batch and calls `synchronized
(v) { v.notify(); }`. On the async path, `GuardForAsyncSendService` sends the
expired batches.
#### Problems
Each problem below is reproduced on `develop` by one of the unit tests
listed under *Steps to Reproduce*.
**Correctness**
1. **Messages that never enter the accumulator leak hold size.**
`canBatch()` calls `tryAddMessage()`, which reserves the body size, *before* it
checks the delay, retry-topic and producer-group conditions.
`sendByAccumulator` only validates the message after that. As a result, delayed
messages, retry-topic messages, messages that carry `PROPERTY_PRODUCER_GROUP`,
and messages rejected by `Validators.checkMessage` (for example, a body that is
too large) all reserve bytes that are never released. Once the default 32 MB
`totalBatchMaxBytes` has leaked, `tryAddMessage` always returns false and
auto-batching is disabled for the whole client instance without any error.
2. **Async sends leak hold size when `sendDirect` throws synchronously**,
for example `MQClientException("executor rejected")` or a batch encoding error.
The callbacks receive `onException`, but `currentlyHoldSize` is never
decremented.
3. **When a sync batch send fails, every caller except the one that sent the
batch gets a `NullPointerException`** instead of the actual broker or client
exception: those callers read `sendResults[index]`, which was never assigned.
Applications cannot classify or retry the failure.
4. **An interrupted sync caller abandons a message that is already in the
batch.** `wait()` throws `InterruptedException` out of `add()`, but the message
stays in the batch. If no other caller joins that batch, nobody sends it,
because the guard only calls `notify()` and never sends. The message is never
delivered and its hold size is never released. If instead the application
retries after the `InterruptedException` and the original batch is later sent
by another caller, the message is delivered twice.
5. **One user callback that throws breaks the rest of an async batch.** If
callback *i* throws inside the `onSuccess` dispatch loop, control jumps to
`onException`. Callbacks after *i* never receive `onSuccess`, and callbacks
before *i* receive `onSuccess` and *then* `onException`.
6. **Sent batches are never removed from `syncSendBatchs` /
`asyncSendBatchs`.** The guards only remove batches whose `messagesSize == 0`,
but `messagesSize` is never decremented after a send. Each aggregate key
therefore keeps its last closed batch, including all of its message bodies,
until a new message for the same key arrives. With many queues or tags, this
memory is held indefinitely.
**Performance and scalability**
7. **The network send runs while the batch monitor is held, and the sync
guard takes every batch monitor in turn.** While one batch is in flight, the
guard blocks on that batch's monitor, so expired batches of *other* queues are
not woken until that send returns. With a slow broker, one queue's RTT is added
to the latency of the other queues. In addition, waiters are only woken by the
guard's poll every `holdMs / 2`, which adds on average about 3 ms to each sync
send with the default `holdMs = 10`.
8. **Virtual threads.** On JDK 21–23, blocking inside `synchronized` pins
the carrier thread. With 50,000 virtual-thread senders, `sendDirect` runs
inside `synchronized (batch)`; one 15-second JFR recording showed 2,601
`jdk.VirtualThreadPinned` events at `MessageAccumulation.send` ← `add`. In that
setup, **49,744 of the 50,000 threads did not complete a single send in 10 s**,
and the total throughput was 17k msg/s. JDK 25 (JEP 491) removes the pinning,
but sends are still serialized per batch under the monitor: about 0.9M msg/s
with a p50 latency of about 52 ms, for a broker RTT of 1 ms.
### Steps to Reproduce
**A. Unit tests.** I ran the regression tests from the linked PR against
`develop` (`28960fd2f`). Two package-private read-only accessors
(`getCurrentlyHoldSize()` and `pendingBatchCount()`) were added for the
assertions, and the guard threads were started:
| Test | Result on `develop` | Problem |
|---|---|---|
| `DefaultMQProducerTest#testAutoBatch_unbatchableMessageReleasesHoldSize`
(delayed message) | 18 bytes leaked | 1 |
| `DefaultMQProducerTest#testAutoBatch_invalidMessageReleasesHoldSize` (body
over `maxMessageSize`) | 28 bytes leaked | 1 |
|
`ProduceAccumulatorTest#testAsyncSend_synchronousSendFailureReleasesHoldSize` |
2 bytes leaked | 2 |
|
`ProduceAccumulatorTest#testSyncSend_failurePropagatesToEveryMessageInBatch` |
`NullPointerException` instead of `MQBrokerException` | 3 |
|
`ProduceAccumulatorTest#testSyncSend_interruptWhileWaitingDoesNotStrandMessage`
| batch never sent (0 sends) | 4 |
| `ProduceAccumulatorTest#testAsyncSend_throwingCallbackDoesNotAffectOthers`
| only 1 of 2 callbacks received `onSuccess` | 5 |
| `ProduceAccumulatorTest#testSentBatchesAreRemoved` | 20 batches still in
the maps after every send completed | 6 |
| `ProduceAccumulatorTest#testSyncSend_slowBatchDoesNotBlockOtherBatches` |
a send to another queue did not complete within 2 s | 7 |
If the guard threads are *not* started (the situation in #10935, where
another producer with the same client ID has been shut down), sync sends on
`develop` never complete: three more tests time out.
**B. Benchmark.** The closed-loop benchmark below uses a mock broker
(`sendDirect` sleeps for the RTT). It mirrors `sendByAccumulator`: reserve the
hold size, then sync-send one 128-byte message, in a loop. All accumulator
settings are defaults (`holdMs = 10`, `batchMaxBytes = 32 KB`,
`totalBatchMaxBytes = 32 MB`). It uses 5 s of warm-up and a 10 s measurement
window, and is run against the `ProduceAccumulator` class from `develop` and
from the PR.
```
java -cp <client classes>:<deps>:.
org.apache.rocketmq.client.producer.AccumulatorBench virtual 50000 3 1 5 10
java -cp <client classes>:<deps>:.
org.apache.rocketmq.client.producer.AccumulatorBench platform 64 4 20 5 10
```
### What Did You Expect to See?
- `currentlyHoldSize` returns to 0 once all messages have completed, on
every code path.
- Every sync caller receives its own result or the real send exception.
Interrupting a caller neither loses nor strands its message.
- Every async callback receives exactly one result.
- Completed batches are released.
- Batches with different keys do not block each other. Sync latency is about
`holdMs + broker RTT`, and throughput scales with the number of virtual-thread
senders.
### What Did You See Instead?
See the unit test results in table A. Benchmark results:
**64 platform threads, 4 queues**
| JDK | Broker RTT | `develop`: TPS, p50 / p99 | PR: TPS, p50 / p99 |
|---|---|---|---|
| 21 | 1 ms | 4,357, 15.3 / 15.8 ms | 5,684, 11.3 / 11.5 ms |
| 21 | 20 ms | 1,412, 46.5 / 47.5 ms (*) | 2,112, 30.3 / 30.5 ms |
| 25 | 1 ms | 4,414, 15.3 / 16.3 ms | 5,691, 11.3 / 11.4 ms |
| 25 | 20 ms | 2,099, 30.5 / 31.0 ms (*) | 2,112, 30.3 / 30.5 ms |
(*) At 20 ms, `develop` alternates between two modes from run to run:
1.4k–2.1k TPS with a p99 of 31–67 ms, depending on whether the guard gets stuck
behind an in-flight batch (problem 7). The PR is stable at the closed-loop
limit of 64 / (10 ms + 20 ms) ≈ 2.1k TPS.
**50,000 virtual threads, 3 queues**
| JDK | Broker RTT | `develop`: TPS, p50 / p99, threads with 0 sends in 10 s
| PR: TPS, p50 / p99, threads with 0 sends in 10 s |
|---|---|---|---|
| 21 | 1 ms | 17.2k, 15.2 / 17.3 ms (**), 49,744 | 3.29M, 14.6 / 27.7 ms, 0 |
| 21 | 20 ms | 7.1k, 32.9 / 47.8 ms (**), 49,744 | 2.39M, 20.6 / 29.7 ms, 0 |
| 25 | 1 ms | 0.95M, 51.2 / 113.7 ms, 0 | 3.49M, 4.8 / 54.8 ms, 0 |
| 25 | 20 ms | 0.91M, 52.3 / 103.1 ms, 0 | 2.33M, 20.7 / 30.3 ms, 0 |
(**) These latencies only cover the 256 threads that made progress.
In every run, the number of acknowledged messages equals the number sent to
the broker, and the hold size is 0 after draining. After draining, `develop`
still holds 3–4 closed batches in its maps (problem 6), while the PR holds none.
At 1 ms on JDK 25, the PR saturates the CPU (about 98% in a separate JFR
run). The tail latency is then dominated by unfair scheduling under saturation:
p999 2.6 s, max 8.8 s. With 5,000 virtual threads, the PR reaches 2.8M TPS with
a p99 of 7.1 ms and a max of 165 ms.
### Additional Context
#### Proposed fix (see the linked PR)
- Reserve hold size only after the message has been validated and is known
to be batchable. `tryAddMessage` uses a CAS loop instead of a global
`synchronized`.
- Each `MessageAccumulation` completes exactly one `CompletableFuture`. Its
completion handler releases the hold size once and dispatches the results, with
each callback isolated from the others. This removes the per-path release logic.
- A batch removes itself from its map as soon as it is closed.
- Sync callers wait on their own future instead of on the batch monitor, and
the network send runs outside any lock. The caller that opened a batch waits
with the hold timeout and sends the batch when it expires; the other callers
wait without a timeout. This creates one timer per batch instead of one per
caller, which matters with tens of thousands of virtual threads.
`GuardForSyncSendService` is removed, and `GuardForAsyncSendService` only sends
expired async batches.
- A caller whose message is already in a batch waits for that batch even if
it is interrupted, then restores the interrupt flag.
- No public API changes: only package-private `ProduceAccumulator` methods
change. The two unused `send` overloads without a `MessageQueue` are removed.
#### Related
- #10935 / #10937 (shared accumulator lifecycle across producers with the
same client ID): the sync path no longer depends on a guard thread, so the sync
part of #10935 (sync sends hang after another producer is shut down) no longer
applies. The async path still depends on the lifecycle of
`GuardForAsyncSendService`, which #10937 addresses. Both PRs modify
`ProduceAccumulator`, so whichever one is merged second will need a rebase; I
am happy to do that.
- #8134 (unused parameter of `send(SendCallback)`) is also covered by this
change.
#### Limitations
The benchmarks use a mock broker. Absolute numbers show the accumulator's
own limits rather than end-to-end throughput, and a real broker and network
were not benchmarked.
<details>
<summary>Benchmark source (<code>AccumulatorBench.java</code>, compiles with
<code>--release 8</code>; virtual threads are created via reflection)</summary>
```java
package org.apache.rocketmq.client.producer;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.LongAdder;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageBatch;
import org.apache.rocketmq.common.message.MessageQueue;
/**
* Closed-loop benchmark of the auto-batching accumulator with a mock broker.
* Every sender thread loops: reserve hold size, sync-send one 128B message,
repeat
* (same steps as DefaultMQProducer#sendByAccumulator). sendDirect sleeps to
simulate the broker RTT.
*
* args: virtual|platform threads queues sendLatencyMs warmupSec measureSec
*/
public class AccumulatorBench {
private static final int BUCKET_US = 100;
private static final AtomicLongArray HIST = new
AtomicLongArray(300_000); // 0.1ms buckets, up to 30s
private static volatile boolean recording;
public static void main(String[] args) throws Exception {
boolean virtual = "virtual".equals(args[0]);
int threads = Integer.parseInt(args[1]);
int queueNum = Integer.parseInt(args[2]);
long latencyMs = Long.parseLong(args[3]);
int warmupSec = Integer.parseInt(args[4]);
int measureSec = Integer.parseInt(args[5]);
LongAdder sentToBroker = new LongAdder();
LongAdder batches = new LongAdder();
DefaultMQProducer producer = new DefaultMQProducer() {
@Override
public SendResult sendDirect(Message msg, MessageQueue mq,
SendCallback cb) throws InterruptedException {
Thread.sleep(latencyMs);
batches.increment();
for (Message ignored : (MessageBatch) msg) {
sentToBroker.increment();
}
SendResult result = new SendResult();
result.setMsgId("1");
if (cb != null) {
cb.onSuccess(result);
}
return result;
}
};
ProduceAccumulator accumulator = new ProduceAccumulator("bench");
accumulator.start();
MessageQueue[] queues = new MessageQueue[queueNum];
for (int i = 0; i < queueNum; i++) {
queues[i] = new MessageQueue("T", "b", i);
}
byte[] body = new byte[128];
AtomicBoolean stop = new AtomicBoolean();
LongAdder acked = new LongAdder();
AtomicIntegerArray perThread = new AtomicIntegerArray(threads);
ExecutorService senders = virtual
? (ExecutorService)
Executors.class.getMethod("newVirtualThreadPerTaskExecutor").invoke(null)
: Executors.newFixedThreadPool(threads);
for (int t = 0; t < threads; t++) {
int tid = t;
senders.submit(() -> {
int n = 0;
while (!stop.get()) {
Message msg = new Message("T", body);
long start = System.nanoTime();
try {
if (!accumulator.tryAddMessage(msg)) {
throw new
IllegalStateException("totalBatchMaxBytes exhausted");
}
accumulator.send(msg, queues[(tid + n++) %
queueNum], producer);
acked.increment();
} catch (Exception e) {
e.printStackTrace();
return;
}
if (recording) {
perThread.incrementAndGet(tid);
long us = (System.nanoTime() - start) / 1000;
HIST.incrementAndGet((int) Math.min(us / BUCKET_US,
HIST.length() - 1));
}
}
});
}
Thread.sleep(warmupSec * 1000L);
long acked0 = acked.sum();
long batches0 = batches.sum();
long sent0 = sentToBroker.sum();
recording = true;
long t0 = System.nanoTime();
Thread.sleep(measureSec * 1000L);
recording = false;
double wall = (System.nanoTime() - t0) / 1e9;
long ackedN = acked.sum() - acked0;
long batchesN = batches.sum() - batches0;
long sentN = sentToBroker.sum() - sent0;
int[] counts = new int[threads];
int starved = 0;
for (int i = 0; i < threads; i++) {
counts[i] = perThread.get(i);
starved += counts[i] == 0 ? 1 : 0;
}
Arrays.sort(counts);
System.out.printf("%s threads=%d queues=%d sendLatency=%dms%n",
virtual ? "virtual" : "platform", threads, queueNum, latencyMs);
System.out.printf(" tps=%.0f avgBatchSize=%.1f%n", ackedN / wall,
batchesN == 0 ? 0.0 : sentN / (double) batchesN);
System.out.printf(" latency p50=%.1fms p99=%.1fms p999=%.1fms
max=%.1fms%n",
percentile(0.50), percentile(0.99), percentile(0.999),
percentile(1.0));
System.out.printf(" threads with 0 sends in %ds: %d of %d
(per-thread sends min=%d p50=%d max=%d)%n",
measureSec, starved, threads, counts[0], counts[threads / 2],
counts[threads - 1]);
stop.set(true);
senders.shutdown();
boolean drained = senders.awaitTermination(60, TimeUnit.SECONDS);
Thread.sleep(200);
System.out.printf(" drained=%s acked=%d sentToBroker=%d
holdSizeAfterDrain=%d batchesLeftInMaps=%d%n",
drained, acked.sum(), sentToBroker.sum(), holdSize(accumulator),
batchesLeft(accumulator));
System.exit(0);
}
private static double percentile(double p) {
long total = 0;
for (int i = 0; i < HIST.length(); i++) {
total += HIST.get(i);
}
long target = (long) Math.ceil(total * p);
long seen = 0;
for (int i = 0; i < HIST.length(); i++) {
seen += HIST.get(i);
if (seen >= target && HIST.get(i) > 0) {
return (i + 1) * BUCKET_US / 1000.0;
}
}
return -1;
}
private static Object field(ProduceAccumulator accumulator, String name)
throws Exception {
Field f = ProduceAccumulator.class.getDeclaredField(name);
f.setAccessible(true);
return f.get(accumulator);
}
private static long holdSize(ProduceAccumulator accumulator) throws
Exception {
return ((AtomicLong) field(accumulator, "currentlyHoldSize")).get();
}
private static int batchesLeft(ProduceAccumulator accumulator) throws
Exception {
return ((Map<?, ?>) field(accumulator, "syncSendBatchs")).size()
+ ((Map<?, ?>) field(accumulator, "asyncSendBatchs")).size();
}
}
```
</details>
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]