Repository navigation
Description
Search before reporting
- I searched in the issues and found nothing similar.
Read release policy
- I understand that unsupported versions don't get bug fixes. I will attempt to reproduce the issue on a supported version of Pulsar client and Pulsar broker.
User environment
broker and client are in a same machine use same java
- OS: Linux version 5.4.241-1-tlinux4-0017.16 (mockbuild@VM-81-152-TS3) (gcc version 8.5.0 20210514 (Tencent 8.5.0-23) (GCC)) SMP Thu Dec 12 21:16:37 CST 2024
- Broker version: 4.1.1
- Client version: 4.1.1 (Java)
- Java version:
- openjdk version "24.0.2" 2025-07-15
- OpenJDK Runtime Environment Temurin-24.0.2+12 (build 24.0.2+12)
- OpenJDK 64-Bit Server VM Temurin-24.0.2+12 (build 24.0.2+12, mixed mode, sharing)
Issue Description
What happened
What I did
Continuously produced a certain amount of messages to a partitioned topic, and consumed those messages with two subscriptions [sub-1, sub-2] individually, and check their consistency. Consistent means a message has been sent and received from all subscriptions, so it will be checked after received and before acknowledged.
options i used (use default if not mentioned)
- producer
- batchingMaxMessagess = 1000
- consumer
- enableBatchIndexAcknowledgment = true
- ack mode = Individual
- acknowledgmentGroupTime = 100ms
- maxAcknowledgmentGroupSize = 1000
Expected
All messages produced could be received from all subscriptions.
If produced 1000000, I should get
--- Total Acked Messages per Subscription ---
2026-01-14 11:56:07.351 [main] INFO org.example.Main - Subscription [sub-2]: 1000000 acks
2026-01-14 11:56:07.351 [main] INFO org.example.Main - Subscription [sub-1]: 1000000 acks
Happened
Occasionally, missed one message with a random batch index
--- Total Acked Messages per Subscription ---
2026-01-14 11:56:07.351 [main] INFO org.example.Main - Subscription [sub-2]: 999999 acks
2026-01-14 11:56:07.351 [main] INFO org.example.Main - Subscription [sub-1]: 1000000 acks
2026-01-14 11:56:07.351 [main] ERROR org.example.Main - [0:123:0:45] not received from [sub-2]!
Why a bug
If set enableBatchIndexAcknowledgment = true or set acknowledgmentGroupTime = 0,
this will not occur.
And broker has a backlog pointed to these entry, while consumer.receive() could not get that missing message even after calling redeliverUnacknowledgedMessages()
** use go client (not support Batch Index Acknowledgment) will not occur **
Error messages
if enable DEBUG for .apache.pulsar.client.impl.PersistentAcknowledgmentsGroupingTracker, found
Flushing pending acks to broker: last-cumulative-ack: [] -- individual-acks: [] -- individual-batch-index-acks: [(0, 123, {})]
Reproducing the issue
pseudocode:
public class PulsarBatchAckPseudoDemo {
static Set<MessageId> sentMessageIds = new ConcurrentHashMap.newKeySet();
static Map<MessageId, Set<String>> receiptTracker = new ConcurrentHashMap<>();
static Map<String, AtomicLong> ackCounters = Map.of("sub-1", new AtomicLong(0), "sub-2", new AtomicLong(0));
public static void main(String[] args) {
// Assume a partitioned topic is already created.
PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://127.0.0.1:6650").build();
// Run producer and consumers concurrently in background threads.
startThread(() -> producerTask(client));
startThread(() -> consumerTask(client, "sub-1"));
startThread(() -> consumerTask(client, "sub-2"));
// Let the test run for a while, then stop threads and verify.
sleep(90_000); // Wait for a generous amount of time.
// --- Verification ---
System.out.println("--- Total Acked Messages per Subscription ---");
System.out.printf("Subscription [sub-1]: %d acks%n", ackCounters.get("sub-1").get());
System.out.printf("Subscription [sub-2]: %d acks%n", ackCounters.get("sub-2").get());
// Find and report any message that wasn't received by BOTH subscriptions.
for (MessageId sentId : sentMessageIds) {
Set<String> receivedBy = receiptTracker.getOrDefault(sentId, Collections.emptySet());
if (receivedBy.size() < 2) {
if (!receivedBy.contains("sub-1")) {
System.err.printf("[%s] not received from [sub-1]!%n", sentId);
}
if (!receivedBy.contains("sub-2")) {
System.err.printf("[%s] not received from [sub-2]!%n", sentId);
}
}
}
}
// --- Producer Task Logic ---
@SneakyThrows
static void producerTask(PulsarClient client) {
Producer producer = client.newProducer().topic("partitioned_topic").batchingMaxMessages(1000).create();
for (int i = 0; i < 1_000_000; i++) {
// Asynchronously send and register the MessageId upon completion.
producer.sendAsync("message-payload-" + i).thenAccept(messageId -> {
sentMessageIds.add(messageId);
receiptTracker.put(messageId, ConcurrentHashMap.newKeySet());
});
}
}
// --- Consumer Task Logic ---
@SneakyThrows
static void consumerTask(PulsarClient client, String subscriptionName) {
Consumer consumer = client.newConsumer().topic("partitioned_topic").subscriptionName(subscriptionName)
.enableBatchIndexAcknowledgement(true).acknowledgmentGroupTime(100, TimeUnit.MILLISECONDS)
.acknowledgementGroupSize(1000).subscribe();
while (true) { // Run until the main thread stops it.
Message<String> message = consumer.receive();
// Step 1: Mark as received BEFORE acknowledging.
Set<String> receipts = receiptTracker.get(message.getMessageId());
if (receipts != null) {
receipts.add(subscriptionName);
}
// Step 2: Increment the counter for the final report.
ackCounters.get(subscriptionName).incrementAndGet();
// Step 3: Acknowledge the message individually.
consumer.acknowledge(message);
}
}
}Additional information
No response
Are you willing to submit a PR?
- I'm willing to submit a PR!
Activity
[-][Bug][/-][+][Bug] Java consumer occasionally missing one message of a batched entry[/+]lhotari commentedon Jan 15, 2026
I haven't checked it yet, but there's a possibility that the test code contains a race condition with the
receiptTrackerhandling.You can remove
if (receipts != null) {in the consumer task logic to find out. It would be null if there's a race condition.To fix the race condition, I'd recommend extracting a method for getting the receipt tracker and use something like
receiveTracker.computeIfAbsent(messageId, __ -> ConcurrentHashMap.newKeySet()).YinY1 commentedon Jan 15, 2026
I'm sorry about my mistake in this demo. Because of the complexity of the the actual production code, I did not copy the code direcetly but rewrote a test demo without a careful check.
Indeed I do use
computeIfAbsentand other thread safe methods in my code, I will correct this test demo ASAP.This bug is so rare that during testing I produce and consume 100,000 messages per iteration; sometimes it can be reproduced within five test cycles, while other times it cannot be reproduced even after more than ten cycles.
Thanks for your patience again!
lhotari commentedon Jan 15, 2026
@YinY1 I created https://github.com/lhotari/pulsar-playground/blob/master/src/main/java/com/github/lhotari/pulsar/playground/TestScenarioIssue25145.java based on PulsarBatchAckPseudoDemo. I wasn't able to reproduce the problem after fixing the race condition.
YinY1 commentedon Jan 15, 2026
Thank you so much for providing the fix code! And I apologize for not addressing my code issue in a timely manner.
I used the code you provided and made some simple modifications so that I could run loop tests, and I modified the number of messages to produced in each iteration. The main changes are as follows:
Additionally, I used a script to execute the program in a loop:
After running for a while, the issue reappeared. Here is the output log:
Unfortunately, I didn't enable the debug log for AckGroupingTracker, so I'm unable to provide the tracker's status at that time.
I've tested in different broker versions, (multi replicas, no standalone): 2.9.0, 4.0.8 and 4.1.1, and bug still occurred. As I mentioned above, I prefer this bug is caused by
batchIndexAcknowledgementorPersistentAcknowledgmentsGroupingTracker.Additionally, I run this test demo and broker 4.0.8 on k8s.
Thanks for your patience again!
lhotari commentedon Jan 21, 2026
@YinY1 Do you run the test case within the Pulsar cluster? Do you connect to brokers via the Pulsar Proxy?
lhotari commentedon Jan 21, 2026
I've tried to reproduce the issue with 4.0.8 version in k8s without success. I'm running the test app outside of k8s.
I updated the test app to reflect similar changes as you have made:
https://github.com/lhotari/pulsar-playground/blob/master/src/main/java/com/github/lhotari/pulsar/playground/TestScenarioIssue25145.java
And I added the script and a k8s deployment:
https://github.com/lhotari/pulsar-playground/tree/master/issues/issue25145
YinY1 commentedon Jan 21, 2026
I also run test app in k8s issue-25145.yaml, but not in the same pod/stateful set as Pulsar cluster.
For 4.0.8 version cluster (3 replicas), I used Pulsar Proxy, but for 4.1.1 version I connected directly without proxy.
berg223 commentedon Jan 24, 2026
@YinY1
There may be a misuse and you should set
subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)in your reproduce code. Because default value for subscriptionInitialPosition is Latest. And the thread order is important too:click to show full code which check passed 300 times
If issue exists. You can provide more info of stats by running command like:
./bin/pulsar-admin topics stats-internal persistent://public/default/partitioned_topic_25145-partition-3YinY1 commentedon Jan 26, 2026
@berg223 I used both
EarliestandLatestin other test code (not this reproduce code) and still reproduce the problem, so I didn't set this option in the reproduce code; I notice that your consumers are start after sending all messages, I will try to reproduce again with different thread ordersYinY1 commentedon Jan 26, 2026
@berg223 I set
subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)(use your full code) and use following thread order and reproduced it:Inconsistency found in turn 59:
Then I got internal-stat:
So I changed to another order with a new topic:
But I still reproduced the problem in turn 92:
Internal stats is similar:
berg223 commentedon Jan 26, 2026
@YinY1 @lhotari I have reproduced the issue in my branch named reproduce_issue_25145 And a PR will be committed in the next days.
Consumer lost message due to race condition in acknowledge with batch message
There are two threads:
In the race condition, thread B cleared the ackBitSet. Then thread A mistakenly believe the message is duplicate and ignored it.
I have abstracted the log:
lhotari commentedon Jan 28, 2026
Great work @berg223 . Looking forward to the PR. It would be great to include the fix to the next set of Pulsar releases that are about to happen (mailing list).
berg223 commentedon Jan 28, 2026
@lhotari I have met more unexpected issues by a simple trial solution in my another branch named fix_issue_25145_trial. And I don't have enough time to solve the following problems before Sunday.
I have changed the trial solution from synchonized to:
It behaves same as previous trial. And the CAS counter shows low competition and CAS has succeed first time over 90 percent.
The above problems has confused me for days. Any help in these problems is welcome!
I will be back to take over the remaining work this Sunday if nobody commit the fix PR.
oneby-wang commentedon Feb 3, 2026
@berg223 Good catch, I'm working on this issue and a PR will be committed soon.