Skip to content

[Bug] Java consumer occasionally missing one message of a batched entry #25145

Closed

Description

@YinY1

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

  1. added
    type/bug
    on Jan 15, 2026
  2. changed the title [-][Bug][/-] [+][Bug] Java consumer occasionally missing one message of a batched entry[/+] on Jan 15, 2026
  3. lhotari commented on Jan 15, 2026

    @lhotari
    Member

    I haven't checked it yet, but there's a possibility that the test code contains a race condition with the receiptTracker handling.
    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()).

  4. YinY1 commented on Jan 15, 2026

    @YinY1
    Author

    I haven't checked it yet, but there's a possibility that the test code contains a race condition with the receiptTracker handling.
    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()).

    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 computeIfAbsent and 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!

  5. lhotari commented on Jan 15, 2026

    @lhotari
    Member
  6. YinY1 commented on Jan 15, 2026

    @YinY1
    Author

    @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.

    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:

    public static void main(String[] args) throws PulsarClientException, InterruptedException, PulsarAdminException {
        // ...
    
                    // Find and report any message that wasn't received by BOTH subscriptions.
    +             boolean inconsistentFound = false;
                    for (MessageId sentId : sentMessageIds) {
                        Set<String> receivedBy = receiptTracker.getOrDefault(sentId, Collections.emptySet());
                        if (receivedBy.size() < 2) {
      +                     inconsistentFound = true;
                            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);
                            }
                        }
                    }
    
                    System.out.println("Shutting down...");
                    client.close();
                    System.out.println("Done.");
      + 
      +             if (inconsistentFound) {
      +                 System.err.println("Inconsistency detected!");
      +                 System.exit(1);
      +             }
                }

    Additionally, I used a script to execute the program in a loop:

    iteration=0
    while true; do
            iteration=$((iteration + 1))
            echo "====== Iteration ${iteration} ======"
            echo "Start time: $(date)"
            rm -rf /workspace/output
            mkdir -p /workspace/output
            current_time=$(date +%Y%m%d-%H%M%S)
    
            java -jar /workspace/target/test-scenario-issue-25145-1.0-SNAPSHOT.jar 2>&1 | tee /workspace/log/output_${current_time}.log
            rc=${PIPESTATUS[0]}
    
            if [ "${rc}" -eq 0 ]; then
                echo "====== Iteration ${iteration} completed successfully ======"
                echo "Sleeping 10s before next iteration..."
                sleep 10
                continue
            else
                echo "====== Iteration ${iteration} failed with exit code ${rc} ======"
                echo "Inconsistency detected. Total iterations run: ${iteration}"
                echo "Log saved to: /workspace/log/output_${current_time}.log"
                exit ${rc}
            fi
    done

    After running for a while, the issue reappeared. Here is the output log:

    ====== Iteration 7 ======
    Start time: Thu Jan 15 04:05:10 PM UTC 2026
    SLF4J(W): No SLF4J providers were found.
    SLF4J(W): Defaulting to no-operation (NOP) logger implementation
    SLF4J(W): See https://www.slf4j.org/codes.html#noProviders for further details.
    Starting producer task...
    Starting consumer task for subscription [sub-2]...
    Starting consumer task for subscription [sub-1]...
    Finished producer task.
    Finished consumer task for subscription [sub-1].
    Finished consumer task for subscription [sub-2].
    --- Total Acked Messages per Subscription ---
    Subscription [sub-1]: 100000 acks
    Subscription [sub-2]: 100000 acks
    Shutting down...
    Done.
    ====== Iteration 7 completed successfully ======
    Sleeping 10s before next iteration...
    ====== Iteration 8 ======
    Start time: Thu Jan 15 04:05:51 PM UTC 2026
    SLF4J(W): No SLF4J providers were found.
    SLF4J(W): Defaulting to no-operation (NOP) logger implementation
    SLF4J(W): See https://www.slf4j.org/codes.html#noProviders for further details.
    Starting producer task...
    Starting consumer task for subscription [sub-1]...
    Starting consumer task for subscription [sub-2]...
    Finished producer task.
    Finished consumer task for subscription [sub-2].
    Finished consumer task for subscription [sub-1].
    --- Total Acked Messages per Subscription ---
    Subscription [sub-1]: 99999 acks
    Subscription [sub-2]: 100000 acks
    [5426:163:7:582] not received from [sub-1]!
    Shutting down...
    Done.
    Inconsistency detected!
    ====== Iteration 8 failed with exit code 1 ======
    Inconsistency detected. Total iterations run: 8
    

    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 batchIndexAcknowledgement or PersistentAcknowledgmentsGroupingTracker.

    Additionally, I run this test demo and broker 4.0.8 on k8s.

    Thanks for your patience again!

  7. lhotari commented on Jan 21, 2026

    @lhotari
    Member

    Additionally, I run this test demo and broker 4.0.8 on k8s.

    @YinY1 Do you run the test case within the Pulsar cluster? Do you connect to brokers via the Pulsar Proxy?

  8. lhotari commented on Jan 21, 2026

    @lhotari
    Member

    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

  9. YinY1 commented on Jan 21, 2026

    @YinY1
    Author

    Additionally, I run this test demo and broker 4.0.8 on k8s.

    @YinY1 Do you run the test case within the Pulsar cluster? Do you connect to brokers via the Pulsar Proxy?

    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.

  10. berg223 commented on Jan 24, 2026

    @berg223
    Contributor

    @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:

            Thread producerThread = startThread(() -> producerTask(client));
            producerThread.join();
            Thread consumerThread1 = startThread(() -> consumerTask(client, "sub-1"));
            Thread consumerThread2 = startThread(() -> consumerTask(client, "sub-2"));
    
            // wait until all threads complete
            consumerThread1.join();
            consumerThread2.join();
    
    click to show full code which check passed 300 times
    package org.apache;
    
    import java.util.Collections;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicLong;
    import lombok.Cleanup;
    import lombok.SneakyThrows;
    import org.apache.pulsar.client.admin.PulsarAdmin;
    import org.apache.pulsar.client.admin.PulsarAdminException;
    import org.apache.pulsar.client.api.Consumer;
    import org.apache.pulsar.client.api.Message;
    import org.apache.pulsar.client.api.MessageId;
    import org.apache.pulsar.client.api.Producer;
    import org.apache.pulsar.client.api.PulsarClient;
    import org.apache.pulsar.client.api.PulsarClientException;
    import org.apache.pulsar.client.api.Schema;
    import org.apache.pulsar.client.api.SubscriptionInitialPosition;
    
    /**
     * Attempt to reproduce an issue described in https://github.com/apache/pulsar/issues/25145.
     * This class is based on PulsarBatchAckPseudoDemo shared in the issue description.
     */
    public class TestScenarioIssue25145 {
        private static String PULSAR_BROKER_URL = "pulsar://127.0.0.1:6650";
        private static String PULSAR_SERVICE_URL = "http://127.0.0.1:8080";
        static final String TOPIC_NAME = "partitioned_topic_25145";
        static Set<MessageId> sentMessageIds = 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) throws PulsarClientException, InterruptedException, PulsarAdminException {
            for (int i = 0; i < 1000; i++) {
                runOnce();
                System.out.println("passed check iteration " + i);
                Thread.sleep(10_000);
                sentMessageIds.clear();
                receiptTracker.clear();
                ackCounters.values().forEach(count -> count.set(0));
            }
        }
    
        private static void runOnce() throws PulsarClientException, PulsarAdminException, InterruptedException {
            PulsarClient client = PulsarClient.builder()
                    .serviceUrl(PULSAR_BROKER_URL)
                    .build();
    
            @Cleanup
            PulsarAdmin pulsarAdmin = PulsarAdmin.builder()
                    .serviceHttpUrl(PULSAR_SERVICE_URL)
                    .build();
    
            try {
                pulsarAdmin.topics().createPartitionedTopic(TOPIC_NAME, 16);
            } catch (PulsarAdminException.ConflictException e) {
                // Topic already exists, ignore.
            }
    
            // Run producer and consumers concurrently in background threads.
            Thread producerThread = startThread(() -> producerTask(client));
            producerThread.join();
            Thread consumerThread1 = startThread(() -> consumerTask(client, "sub-1"));
            Thread consumerThread2 = startThread(() -> consumerTask(client, "sub-2"));
    
            // wait until all threads complete
            consumerThread1.join();
            consumerThread2.join();
    
            // --- 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.
            boolean inconsistentFound = false;
            for (MessageId sentId : sentMessageIds) {
                Set<String> receivedBy = receiptTracker.getOrDefault(sentId, Collections.emptySet());
                if (receivedBy.size() < 2) {
                    inconsistentFound = true;
                    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);
                    }
                    break;
                }
            }
    
            System.out.println("Shutting down...");
            client.close();
            System.out.println("Done.");
            if (inconsistentFound) {
                System.err.println("Inconsistency detected!");
                System.exit(1);
            }
        }
    
    
        private static Thread startThread(Runnable runnable) {
            Thread thread = new Thread(runnable);
            thread.start();
            return thread;
        }
    
        // --- Producer Task Logic ---
        @SneakyThrows
        static void producerTask(PulsarClient client) {
            System.out.println("Starting producer task...");
            Producer<String> producer = client.newProducer(Schema.STRING)
                    .topic(TOPIC_NAME)
                    .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);
                });
            }
            producer.flush();
            System.out.println("Finished producer task.");
        }
    
        // --- Consumer Task Logic ---
        @SneakyThrows
        static void consumerTask(PulsarClient client, String subscriptionName) {
            System.out.println("Starting consumer task for subscription [" + subscriptionName + "]...");
            Consumer consumer = client.newConsumer().topic(TOPIC_NAME)
                    .subscriptionName(subscriptionName)
                    .enableBatchIndexAcknowledgment(true)
                    .acknowledgmentGroupTime(100, TimeUnit.MILLISECONDS)
                    .maxAcknowledgmentGroupSize(1000)
                    .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
                    .subscribe();
    
            try {
    //            while (ackCounters.get(subscriptionName).get() < sentMessageIds.size()) {
                while (true) {// Run until the main thread stops it.
                    Message<String> message = consumer.receive(10, TimeUnit.SECONDS);
                    if (message == null) {
                        break;
                    }
    
                    // Step 1: Mark as received BEFORE acknowledging.
                    Set<String> receipts =
                            receiptTracker.computeIfAbsent(message.getMessageId(), k -> ConcurrentHashMap.newKeySet());
                    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);
                }
            } catch (PulsarClientException e) {
                if (!(e.getCause() instanceof InterruptedException)) {
                    throw e;
                }
            }
    
            System.out.println("Finished consumer task for subscription [" + subscriptionName + "].");
        }
    }

    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-3

  11. YinY1 commented on Jan 26, 2026

    @YinY1
    Author

    @berg223 I used both Earliest and Latest in 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 orders

  12. YinY1 commented on Jan 26, 2026

    @YinY1
    Author

    @berg223 I set subscriptionInitialPosition(SubscriptionInitialPosition.Earliest) (use your full code) and use following thread order and reproduced it:

            Thread producerThread = startThread(() -> producerTask(client));
            Thread consumerThread1 = startThread(() -> consumerTask(client, "sub-1"));
            Thread consumerThread2 = startThread(() -> consumerTask(client, "sub-2"));
    
            producerThread.join();
            consumerThread1.join();
            consumerThread2.join();

    Inconsistency found in turn 59:

    passed check iteration 58
    Starting producer task...
    Starting consumer task for subscription [sub-1]...
    Starting consumer task for subscription [sub-2]...
    Finished producer task.
    Finished consumer task for subscription [sub-2].
    Finished consumer task for subscription [sub-1].
    --- Total Acked Messages per Subscription ---
    Subscription [sub-1]: 1000000 acks
    Subscription [sub-2]: 999999 acks
    [9436:4283:2:905] not received from [sub-2]!
    Shutting down...
    Done.
    Inconsistency detected!
    ====== Iteration 1 failed with exit code 1 ======
    
    Then I got internal-stat:
    $ pulsar-admin --admin-url http://pulsar-mini-proxy.pulsar:80 topics stats-internal persistent://public/default/partitioned_topic_25145-partition-2
    
    {
      "entriesAddedCounter" : 4300,
      "numberOfEntries" : 4300,
      "totalSize" : 132530392,
      "currentLedgerEntries" : 4300,
      "currentLedgerSize" : 132530392,
      "lastLedgerCreatedTimestamp" : "2026-01-26T02:23:49.505Z",
      "waitingCursorsCount" : 0,
      "pendingAddEntriesCount" : 0,
      "lastConfirmedEntry" : "9436:4299",
      "state" : "LedgerOpened",
      "ledgers" : [ {
        "ledgerId" : 9436,
        "entries" : 0,
        "size" : 0,
        "offloaded" : false,
        "underReplicated" : false
      } ],
      "cursors" : {
        "sub-2" : {
          "markDeletePosition" : "9436:4282",
          "readPosition" : "9436:4300",
          "waitingReadOp" : false,
          "pendingReadOps" : 0,
          "messagesConsumedCounter" : 4299,
          "cursorLedger" : 9458,
          "cursorLedgerLastEntry" : 243,
          "individuallyDeletedMessages" : "[(9436:4283..9436:4299]]",
          "lastLedgerSwitchTimestamp" : "2026-01-26T02:23:50.491Z",
          "state" : "Open",
          "active" : false,
          "numberOfEntriesSinceFirstNotAckedMessage" : 18,
          "totalNonContiguousDeletedMessagesRange" : 1,
          "subscriptionHavePendingRead" : false,
          "subscriptionHavePendingReplayRead" : false,
          "properties" : { }
        },
        "sub-1" : {
          "markDeletePosition" : "9436:4299",
          "readPosition" : "9436:4300",
          "waitingReadOp" : false,
          "pendingReadOps" : 0,
          "messagesConsumedCounter" : 4300,
          "cursorLedger" : 9468,
          "cursorLedgerLastEntry" : 246,
          "individuallyDeletedMessages" : "[]",
          "lastLedgerSwitchTimestamp" : "2026-01-26T02:23:50.49Z",
          "state" : "Open",
          "active" : false,
          "numberOfEntriesSinceFirstNotAckedMessage" : 1,
          "totalNonContiguousDeletedMessagesRange" : 0,
          "subscriptionHavePendingRead" : false,
          "subscriptionHavePendingReplayRead" : false,
          "properties" : { }
        }
      },
      "schemaLedgers" : [ {
        "ledgerId" : 9422,
        "entries" : 1,
        "size" : 119,
        "offloaded" : false,
        "underReplicated" : false
      } ],
      "compactedLedger" : {
        "ledgerId" : -1,
        "entries" : -1,
        "size" : -1,
        "offloaded" : false,
        "underReplicated" : false
      }
    }
    

    So I changed to another order with a new topic:

                Thread producerThread = startThread(() -> producerTask(client));
                producerThread.join();
    
                Thread consumerThread1 = startThread(() -> consumerTask(client, "sub-1"));
                Thread consumerThread2 = startThread(() -> consumerTask(client, "sub-2"));
    
                // wait until all threads complete
                consumerThread1.join();
                consumerThread2.join();

    But I still reproduced the problem in turn 92:

    passed check iteration 91
    Starting producer task...
    Finished producer task.
    Starting consumer task for subscription [sub-1]...
    Starting consumer task for subscription [sub-2]...
    Finished consumer task for subscription [sub-2].
    Finished consumer task for subscription [sub-1].
    --- Total Acked Messages per Subscription ---
    Subscription [sub-1]: 1000000 acks
    Subscription [sub-2]: 999999 acks
    [9473:5795:7:941] not received from [sub-2]!
    Shutting down...
    Done.
    Inconsistency detected!
    
    Internal stats is similar:
    $ pulsar-admin --admin-url http://pulsar-mini-proxy.pulsar:80 topics stats-internal persistent://public/default/partitioned_topic_25145_2-partition-7
    {
      "entriesAddedCounter" : 5798,
      "numberOfEntries" : 5798,
      "totalSize" : 178354015,
      "currentLedgerEntries" : 5798,
      "currentLedgerSize" : 178354015,
      "lastLedgerCreatedTimestamp" : "2026-01-26T03:38:11.802Z",
      "waitingCursorsCount" : 0,
      "pendingAddEntriesCount" : 0,
      "lastConfirmedEntry" : "9473:5797",
      "state" : "LedgerOpened",
      "ledgers" : [ {
        "ledgerId" : 9473,
        "entries" : 0,
        "size" : 0,
        "offloaded" : false,
        "underReplicated" : false
      } ],
      "cursors" : {
        "sub-2" : {
          "markDeletePosition" : "9473:5794",
          "readPosition" : "9473:5798",
          "waitingReadOp" : false,
          "pendingReadOps" : 0,
          "messagesConsumedCounter" : 5797,
          "cursorLedger" : 9504,
          "cursorLedgerLastEntry" : 220,
          "individuallyDeletedMessages" : "[(9473:5795..9473:5797]]",
          "lastLedgerSwitchTimestamp" : "2026-01-26T03:38:14.776Z",
          "state" : "Open",
          "active" : false,
          "numberOfEntriesSinceFirstNotAckedMessage" : 4,
          "totalNonContiguousDeletedMessagesRange" : 1,
          "subscriptionHavePendingRead" : false,
          "subscriptionHavePendingReplayRead" : false,
          "properties" : { }
        },
        "sub-1" : {
          "markDeletePosition" : "9473:5797",
          "readPosition" : "9473:5798",
          "waitingReadOp" : false,
          "pendingReadOps" : 0,
          "messagesConsumedCounter" : 5798,
          "cursorLedger" : 9506,
          "cursorLedgerLastEntry" : 231,
          "individuallyDeletedMessages" : "[]",
          "lastLedgerSwitchTimestamp" : "2026-01-26T03:38:14.777Z",
          "state" : "Open",
          "active" : false,
          "numberOfEntriesSinceFirstNotAckedMessage" : 1,
          "totalNonContiguousDeletedMessagesRange" : 0,
          "subscriptionHavePendingRead" : false,
          "subscriptionHavePendingReplayRead" : false,
          "properties" : { }
        }
      },
      "schemaLedgers" : [ {
        "ledgerId" : 9472,
        "entries" : 1,
        "size" : 121,
        "offloaded" : false,
        "underReplicated" : false
      } ],
      "compactedLedger" : {
        "ledgerId" : -1,
        "entries" : -1,
        "size" : -1,
        "offloaded" : false,
        "underReplicated" : false
      }
    }
    
  13. berg223 commented on Jan 26, 2026

    @berg223
    Contributor

    @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:

    1. Thread A: receive batch messages from broker. It will filter duplicate message by ackBitSet.
    org.apache.pulsar.client.impl.ConsumerImpl#receiveIndividualMessagesFromBatch
        org.apache.pulsar.client.impl.PersistentAcknowledgmentsGroupingTracker#isDuplicate
    
    1. Thread B: flush ack request to broker. It will clear the ackBitSet at the end.
    org.apache.pulsar.client.impl.PersistentAcknowledgmentsGroupingTracker#flushAsync
        org.apache.pulsar.client.impl.PersistentAcknowledgmentsGroupingTracker#newMessageAckCommandAndWrite
            org.apache.pulsar.common.protocol.Commands#newMultiMessageAck
                org.apache.pulsar.common.protocol.Commands#newMultiMessageAckCommon
                    org.apache.pulsar.common.util.collections.ConcurrentBitSetRecyclable#recycle
    

    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:

    2628511 2026-01-26T02:04:10,170+0800 [pulsar-client-io-1-5] DEBUG org.apache.pulsar.client.impl.PersistentAcknowledgm        entsGroupingTracker - [ConsumerBase{subscription='sub-2', consumerName='zfGrH', topic='persistent://public/default/partitioned_topic_25145-partition-6'}] Before pendingIndividualBatchIndexAcks messageId 17:33:6:589
    
    
    2628602 2026-01-26T02:04:10,170+0800 [pulsar-client-io-1-5] DEBUG org.apache.pulsar.client.impl.PersistentAcknowledgm        entsGroupingTracker - [ConsumerBase{subscription='sub-2', consumerName='zfGrH', topic='persistent://public/default/partitioned_topic_25145-partition-6'}] After pendingIndividualBatchIndexAcks messageId 17:33:6:589 isEmpty true
    
    
    2628589 2026-01-26T02:04:10,171+0800 [pulsar-client-io-1-3] DEBUG org.apache.pulsar.client.impl.PersistentAcknowledgm        entsGroupingTracker - [ConsumerBase{subscription='sub-2', consumerName='zfGrH', topic='persistent://public/default/partitioned_topic_25145-partition-6'}] polled pending batch index ack, messageId 17:33:6
    
    2628599 2026-01-26T02:04:10,171+0800 [pulsar-client-io-1-3] DEBUG org.apache.pulsar.common.protocol.Commands - before         recycle 17:33
    
    2628601 2026-01-26T02:04:10,171+0800 [pulsar-client-io-1-3] DEBUG org.apache.pulsar.common.protocol.Commands - after         recycle 17:33
    
    2628604 2026-01-26T02:04:10,171+0800 [pulsar-client-io-1-5] DEBUG org.apache.pulsar.client.impl.PersistentAcknowledgm        entsGroupingTracker - [ConsumerBase{subscription='sub-2', consumerName='zfGrH', topic='persistent://public/de        fault/partitioned_topic_25145-partition-6'}] complete ackSet check messageId 17:33:6:589
    
  14. lhotari commented on Jan 28, 2026

    @lhotari
    Member

    I have reproduced the issue in my branch named reproduce_issue_25145 And a PR will be committed in the next days.

    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).

  15. berg223 commented on Jan 28, 2026

    @berg223
    Contributor

    @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.

    1. The issue still exists after 100 iteration.
    2. The cost time for every iteration increased from 49s to 90s. And new exception has been thrown:
    Exception in thread "Thread-6" org.apache.pulsar.client.api.PulsarClientException$TimeoutException: The producer standalone-0-2 can not send message to the topic persistent://public/default/partitioned_topic_25145-partition-0 within given timeout : createdAt 32.415 seconds ago, firstSentAt 29.177 seconds ago, lastSentAt 29.177 seconds ago, retryCount 1
    	at org.apache.pulsar.client.api.PulsarClientException.unwrap(PulsarClientException.java:1072)
    	at org.apache.pulsar.client.impl.ProducerBase.flush(ProducerBase.java:130)
    	at org.apache.TestScenarioIssue25145.producerTask(TestScenarioIssue25145.java:123)
    	at org.apache.TestScenarioIssue25145.lambda$runOnce$1(TestScenarioIssue25145.java:63)
    	at java.base/java.lang.Thread.run(Thread.java:1583)

    I have changed the trial solution from synchonized to:

                    boolean[] hasPendingAcks = new boolean[1];
                    pendingIndividualBatchIndexAcks.compute(key, (__, bitSet) -> {
                        // We can add some code about count CAS rery times here
                        // We cannot replace compute to computeIfPresent because here could be triggered with pollFirstEntry concurrently. 
                        // But pollFirstEntry complete first then here cannot be triggered again.
                        hasPendingAcks[0] = bitSet != null && !bitSet.get(messageIdAdv.getBatchIndex());
                        return bitSet;
                    });
                    return hasPendingAcks[0];

    It behaves same as previous trial. And the CAS counter shows low competition and CAS has succeed first time over 90 percent.

    1. I have no idea about how to write the test code. It seems hard to reproduce it in a simple unit test.

    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.

  16. oneby-wang commented on Feb 3, 2026

    @oneby-wang
    Contributor

    @berg223 Good catch, I'm working on this issue and a PR will be committed soon.

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

    type/bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions