You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/01/16 11:46:17 UTC

(pulsar) branch branch-3.0 updated (6af24f1b2e1 -> 026cccf857d)

This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a change to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git


    from 6af24f1b2e1 [fix][admin] Fix asyncGetRequest to handle 204 (#25124)
     new c22f3d5b2f1 [fix][fn] complete flushAsync before closeAsync in ProducerCache and wait for completion in closing the cache (#25140)
     new 859da928fc7 [fix][proxy] Fix memory leaks in ParserProxyHandler (#25142)
     new 026cccf857d [fix][sec] Upgrade vertx to address CVE-2026-1002 (#25152)

The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 distribution/server/src/assemble/LICENSE.bin.txt   |  10 +-
 pom.xml                                            |   2 +-
 .../pulsar/functions/instance/ProducerCache.java   |  31 ++++-
 .../functions/instance/ProducerCacheTest.java      |  36 ++++++
 .../pulsar/proxy/server/DirectProxyHandler.java    |   9 +-
 .../pulsar/proxy/server/ParserProxyHandler.java    | 125 +++++++++++++--------
 .../apache/pulsar/proxy/server/ProxyService.java   |  12 +-
 .../apache/pulsar/proxy/server/ProxyStatsTest.java |  58 ++++++++++
 8 files changed, 221 insertions(+), 62 deletions(-)


(pulsar) 01/03: [fix][fn] complete flushAsync before closeAsync in ProducerCache and wait for completion in closing the cache (#25140)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit c22f3d5b2f11635a9c3b6070786129a7298164e6
Author: Ilya Brin <do...@users.noreply.github.com>
AuthorDate: Wed Jan 14 07:57:14 2026 -0600

    [fix][fn] complete flushAsync before closeAsync in ProducerCache and wait for completion in closing the cache (#25140)
    
    Co-authored-by: Lari Hotari <lh...@apache.org>
    (cherry picked from commit 21819c67c8fa322ef82371d753490d5b4c5026c5)
---
 .../pulsar/functions/instance/ProducerCache.java   | 31 +++++++++++++++----
 .../functions/instance/ProducerCacheTest.java      | 36 ++++++++++++++++++++++
 2 files changed, 61 insertions(+), 6 deletions(-)

diff --git a/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/ProducerCache.java b/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/ProducerCache.java
index 2e10581b352..32632ef0695 100644
--- a/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/ProducerCache.java
+++ b/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/ProducerCache.java
@@ -22,12 +22,16 @@ import com.github.benmanes.caffeine.cache.Cache;
 import com.github.benmanes.caffeine.cache.Caffeine;
 import com.github.benmanes.caffeine.cache.Scheduler;
 import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.MoreExecutors;
+import io.netty.util.concurrent.DefaultThreadFactory;
 import java.io.Closeable;
 import java.time.Duration;
 import java.util.concurrent.Callable;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import lombok.extern.slf4j.Slf4j;
@@ -59,15 +63,19 @@ public class ProducerCache implements Closeable {
 
     private final Cache<ProducerCacheKey, Producer<?>> cache;
     private final AtomicBoolean closed = new AtomicBoolean(false);
-    private final CopyOnWriteArrayList<CompletableFuture<Void>> closeFutures = new CopyOnWriteArrayList<>();
+    @VisibleForTesting
+    final CopyOnWriteArrayList<CompletableFuture<Void>> closeFutures = new CopyOnWriteArrayList<>();
+    private final ExecutorService cacheExecutor;
 
     public ProducerCache() {
+        cacheExecutor = Executors.newSingleThreadExecutor(new DefaultThreadFactory("ProducerCache"));
         Caffeine<ProducerCacheKey, Producer<?>> builder = Caffeine.newBuilder()
                 .scheduler(Scheduler.systemScheduler())
+                .executor(cacheExecutor)
                 .<ProducerCacheKey, Producer<?>>removalListener((key, producer, cause) -> {
                     log.info("Closing producer for topic {}, cause {}", key.topic(), cause);
                     CompletableFuture closeFuture =
-                            CompletableFuture.supplyAsync(() -> producer.flushAsync(), Runnable::run)
+                            producer.flushAsync()
                                     .orTimeout(FLUSH_OR_CLOSE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                                     .exceptionally(ex -> {
                                         Throwable unwrappedCause = FutureUtil.unwrapCompletionException(ex);
@@ -128,10 +136,21 @@ public class ProducerCache implements Closeable {
     public void close() {
         if (closed.compareAndSet(false, true)) {
             cache.invalidateAll();
-            try {
-                FutureUtil.waitForAll(closeFutures).get();
-            } catch (InterruptedException | ExecutionException e) {
-                log.warn("Failed to close producers", e);
+            // schedule the waiting job on the cache executor
+            cacheExecutor.execute(() -> {
+                try {
+                    FutureUtil.waitForAll(closeFutures).get();
+                } catch (InterruptedException | ExecutionException e) {
+                    log.warn("Failed to close producers", e);
+                }
+            });
+            // Wait for the cache executor to terminate.
+            // The eviction jobs and waiting for the close futures to complete will run on the single-threaded
+            // cache executor, so we need to wait for them to finish to ensure that the cache is closed properly.
+            boolean terminated = MoreExecutors.shutdownAndAwaitTermination(cacheExecutor,
+                    Duration.ofSeconds(FLUSH_OR_CLOSE_TIMEOUT_SECONDS));
+            if (!terminated) {
+                log.warn("Failed to shutdown cache executor gracefully.");
             }
         }
     }
diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java
index af95a7901b6..129651c8804 100644
--- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java
+++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java
@@ -20,7 +20,10 @@ package org.apache.pulsar.functions.instance;
 
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
 import org.apache.pulsar.client.api.Producer;
 import org.apache.pulsar.client.api.PulsarClientException;
 import org.testng.annotations.Test;
@@ -61,4 +64,37 @@ public class ProducerCacheTest {
         cache.close();
     }
 
+    @Test
+    public void shouldCompleteFlushBeforeCloseAndWaitForClosing() {
+        ProducerCache cache = new ProducerCache();
+        Producer producer = mock(Producer.class);
+        AtomicBoolean flushCompleted = new AtomicBoolean(false);
+        when(producer.flushAsync()).thenReturn(CompletableFuture.supplyAsync(() -> {
+            try {
+                // add delay to make sure that cache close waits for completion of flushAsync
+                Thread.sleep(100);
+            } catch (InterruptedException e) {
+                // ignore
+            }
+            flushCompleted.set(true);
+            return null;
+        }));
+        AtomicBoolean closeCompleted = new AtomicBoolean(false);
+        when(producer.closeAsync()).thenReturn(CompletableFuture.supplyAsync(() -> {
+            try {
+                // add delay to make sure that cache close waits for completion of closeAsync
+                Thread.sleep(100);
+            } catch (InterruptedException e) {
+                // ignore
+            }
+            closeCompleted.set(true);
+            return null;
+        }));
+        cache.getOrCreateProducer(ProducerCache.CacheArea.CONTEXT_CACHE, "topic", "key",
+                () -> (Producer<Object>) producer);
+        cache.close();
+        assertTrue(flushCompleted.get());
+        assertTrue(closeCompleted.get());
+        assertEquals(cache.closeFutures.size(), 1);
+    }
 }
\ No newline at end of file


(pulsar) 03/03: [fix][sec] Upgrade vertx to address CVE-2026-1002 (#25152)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 026cccf857d7bda5b692f71c31180a4f4cee0a9b
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Jan 16 12:43:50 2026 +0200

    [fix][sec] Upgrade vertx to address CVE-2026-1002 (#25152)
    
    (cherry picked from commit dff4f1e95aee2addffa6db38e19984755f5aca38)
---
 distribution/server/src/assemble/LICENSE.bin.txt | 10 +++++-----
 pom.xml                                          |  2 +-
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/distribution/server/src/assemble/LICENSE.bin.txt b/distribution/server/src/assemble/LICENSE.bin.txt
index 95d2bd23fb2..7c1181c65f7 100644
--- a/distribution/server/src/assemble/LICENSE.bin.txt
+++ b/distribution/server/src/assemble/LICENSE.bin.txt
@@ -476,11 +476,11 @@ The Apache Software License, Version 2.0
   * JCTools - Java Concurrency Tools for the JVM
     - org.jctools-jctools-core-2.1.2.jar
   * Vertx
-    - io.vertx-vertx-auth-common-4.5.22.jar
-    - io.vertx-vertx-bridge-common-4.5.22.jar
-    - io.vertx-vertx-core-4.5.22.jar
-    - io.vertx-vertx-web-4.5.22.jar
-    - io.vertx-vertx-web-common-4.5.22.jar
+    - io.vertx-vertx-auth-common-4.5.24.jar
+    - io.vertx-vertx-bridge-common-4.5.24.jar
+    - io.vertx-vertx-core-4.5.24.jar
+    - io.vertx-vertx-web-4.5.24.jar
+    - io.vertx-vertx-web-common-4.5.24.jar
   * Apache ZooKeeper
     - org.apache.zookeeper-zookeeper-3.9.4.jar
     - org.apache.zookeeper-zookeeper-jute-3.9.4.jar
diff --git a/pom.xml b/pom.xml
index ec6f4f88698..4a81b436905 100644
--- a/pom.xml
+++ b/pom.xml
@@ -148,7 +148,7 @@ flexible messaging model and an intuitive client API.</description>
     <jersey.version>2.42</jersey.version>
     <athenz.version>1.10.62</athenz.version>
     <prometheus.version>0.16.0</prometheus.version>
-    <vertx.version>4.5.22</vertx.version>
+    <vertx.version>4.5.24</vertx.version>
     <rocksdb.version>7.9.2</rocksdb.version>
     <slf4j.version>1.7.32</slf4j.version>
     <commons.collections4.version>4.4</commons.collections4.version>


(pulsar) 02/03: [fix][proxy] Fix memory leaks in ParserProxyHandler (#25142)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 859da928fc7de3740d1918b828635a8de8860537
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Thu Jan 15 10:39:11 2026 +0200

    [fix][proxy] Fix memory leaks in ParserProxyHandler (#25142)
    
    (cherry picked from commit 99fdca8af6742dd36bec93ab0038fb572e6eeb0e)
---
 .../pulsar/proxy/server/DirectProxyHandler.java    |   9 +-
 .../pulsar/proxy/server/ParserProxyHandler.java    | 125 +++++++++++++--------
 .../apache/pulsar/proxy/server/ProxyService.java   |  12 +-
 .../apache/pulsar/proxy/server/ProxyStatsTest.java |  58 ++++++++++
 4 files changed, 154 insertions(+), 50 deletions(-)

diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/DirectProxyHandler.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/DirectProxyHandler.java
index ac5af17f273..34b17f4352e 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/DirectProxyHandler.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/DirectProxyHandler.java
@@ -450,26 +450,27 @@ public class DirectProxyHandler {
             } else {
                 // Enable parsing feature, proxyLogLevel(1 or 2)
                 // Add parser handler
+                ParserProxyHandler.Context parserContext = ParserProxyHandler.createContext();
                 if (connected.hasMaxMessageSize()) {
                     FrameDecoderUtil.replaceFrameDecoder(inboundChannel.pipeline(),
                             connected.getMaxMessageSize());
                     FrameDecoderUtil.replaceFrameDecoder(outboundChannel.pipeline(),
                             connected.getMaxMessageSize());
                     inboundChannel.pipeline().addBefore("handler", "inboundParser",
-                            new ParserProxyHandler(service,
+                            new ParserProxyHandler(parserContext, service,
                                     ParserProxyHandler.FRONTEND_CONN,
                                     connected.getMaxMessageSize(), outboundChannel.id()));
                     outboundChannel.pipeline().addBefore("proxyOutboundHandler", "outboundParser",
-                            new ParserProxyHandler(service,
+                            new ParserProxyHandler(parserContext, service,
                                     ParserProxyHandler.BACKEND_CONN,
                                     connected.getMaxMessageSize(), inboundChannel.id()));
                 } else {
                     inboundChannel.pipeline().addBefore("handler", "inboundParser",
-                            new ParserProxyHandler(service,
+                            new ParserProxyHandler(parserContext, service,
                                     ParserProxyHandler.FRONTEND_CONN,
                                     Commands.DEFAULT_MAX_MESSAGE_SIZE, outboundChannel.id()));
                     outboundChannel.pipeline().addBefore("proxyOutboundHandler", "outboundParser",
-                            new ParserProxyHandler(service,
+                            new ParserProxyHandler(parserContext, service,
                                     ParserProxyHandler.BACKEND_CONN,
                                     Commands.DEFAULT_MAX_MESSAGE_SIZE, inboundChannel.id()));
                 }
diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ParserProxyHandler.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ParserProxyHandler.java
index 3a98311eb15..6e4a5a7cd44 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ParserProxyHandler.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ParserProxyHandler.java
@@ -31,6 +31,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import lombok.Getter;
 import org.apache.commons.lang3.mutable.MutableLong;
 import org.apache.pulsar.common.api.proto.BaseCommand;
 import org.apache.pulsar.common.api.raw.MessageParser;
@@ -53,27 +54,41 @@ public class ParserProxyHandler extends ChannelInboundHandlerAdapter {
 
     private final int maxMessageSize;
     private final ChannelId peerChannelId;
+    @Getter
+    private final Context context;
     private final ProxyService service;
 
 
-    /**
-     * producerid + channelid as key.
-     */
-    private static final Map<String, String> producerHashMap = new ConcurrentHashMap<>();
+    public static class Context {
+        /**
+         * producerid as key.
+         */
+        @Getter
+        private final Map<Long, String> producerIdToTopicName = new ConcurrentHashMap<>();
 
-    /**
-     * consumerid + channelid as key.
-     */
-    private static final Map<String, String> consumerHashMap = new ConcurrentHashMap<>();
+        /**
+         * consumerid as key.
+         */
+        @Getter
+        private final Map<Long, String> consumerIdToTopicName = new ConcurrentHashMap<>();
 
-    public ParserProxyHandler(ProxyService service, String type, int maxMessageSize,
+        private Context() {
+        }
+    }
+
+    public ParserProxyHandler(Context context, ProxyService service, String type, int maxMessageSize,
                               ChannelId peerChannelId) {
+        this.context = context;
         this.service = service;
         this.connType = type;
         this.maxMessageSize = maxMessageSize;
         this.peerChannelId = peerChannelId;
     }
 
+    public static Context createContext() {
+        return new Context();
+    }
+
     private void logging(Channel conn, BaseCommand.Type cmdtype, String info, List<RawMessage> messages) {
 
         if (messages != null) {
@@ -115,64 +130,86 @@ public class ParserProxyHandler extends ChannelInboundHandlerAdapter {
 
             switch (cmd.getType()) {
                 case PRODUCER:
-                    ParserProxyHandler.producerHashMap.put(cmd.getProducer().getProducerId() + "," + ctx.channel().id(),
-                            cmd.getProducer().getTopic());
+                    topicName = cmd.getProducer().getTopic();
+                    context.producerIdToTopicName.put(cmd.getProducer().getProducerId(), topicName);
 
                     String producerName = "";
                     if (cmd.getProducer().hasProducerName()){
                         producerName = cmd.getProducer().getProducerName();
                     }
                     logging(ctx.channel(), cmd.getType(), "{producer:" + producerName
-                            + ",topic:" + cmd.getProducer().getTopic() + "}", null);
+                            + ",topic:" + topicName + "}", null);
+                    break;
+                case CLOSE_PRODUCER:
+                    context.producerIdToTopicName.remove(cmd.getCloseProducer().getProducerId());
+                    logging(ctx.channel(), cmd.getType(), "", null);
                     break;
-
                 case SEND:
                     if (service.getProxyLogLevel() != 2) {
                         logging(ctx.channel(), cmd.getType(), "", null);
                         break;
                     }
-                    topicName = TopicName.toFullTopicName(ParserProxyHandler.producerHashMap.get(
-                            cmd.getSend().getProducerId() + "," + ctx.channel().id()));
-                    MutableLong msgBytes = new MutableLong(0);
-                    MessageParser.parseMessage(topicName, -1L,
-                            -1L, buffer, (message) -> {
-                                messages.add(message);
-                                msgBytes.add(message.getData().readableBytes());
-                            }, maxMessageSize);
-                    // update topic stats
-                    TopicStats topicStats = this.service.getTopicStats().computeIfAbsent(topicName,
-                        topic -> new TopicStats());
-                    topicStats.getMsgInRate().recordMultipleEvents(messages.size(), msgBytes.longValue());
-                    logging(ctx.channel(), cmd.getType(), "", messages);
+                    long producerId = cmd.getSend().getProducerId();
+                    String topicForProducer = context.producerIdToTopicName.get(producerId);
+                    if (topicForProducer != null) {
+                        topicName = TopicName.toFullTopicName(topicForProducer);
+                        MutableLong msgBytes = new MutableLong(0);
+                        MessageParser.parseMessage(topicName, -1L,
+                                -1L, buffer, (message) -> {
+                                    messages.add(message);
+                                    msgBytes.add(message.getData().readableBytes());
+                                }, maxMessageSize);
+                        // update topic stats
+                        TopicStats topicStats = this.service.getTopicStats().computeIfAbsent(topicName,
+                                topic -> new TopicStats());
+                        topicStats.getMsgInRate().recordMultipleEvents(messages.size(), msgBytes.longValue());
+                        logging(ctx.channel(), cmd.getType(), "", messages);
+                    } else {
+                        logging(ctx.channel(), cmd.getType(),
+                                "Cannot find topic name for producerId " + producerId, null);
+                    }
                     break;
 
                 case SUBSCRIBE:
-                    ParserProxyHandler.consumerHashMap.put(cmd.getSubscribe().getConsumerId() + ","
-                                    + ctx.channel().id(), cmd.getSubscribe().getTopic());
+                    topicName = cmd.getSubscribe().getTopic();
+                    context.consumerIdToTopicName.put(cmd.getSubscribe().getConsumerId(), topicName);
 
                     logging(ctx.channel(), cmd.getType(), "{consumer:" + cmd.getSubscribe().getConsumerName()
-                            + ",topic:" + cmd.getSubscribe().getTopic() + "}", null);
+                            + ",topic:" + topicName + "}", null);
+                    break;
+                case CLOSE_CONSUMER:
+                    context.consumerIdToTopicName.remove(cmd.getCloseConsumer().getConsumerId());
+                    logging(ctx.channel(), cmd.getType(), "", null);
+                    break;
+                case UNSUBSCRIBE:
+                    context.consumerIdToTopicName.remove(cmd.getUnsubscribe().getConsumerId());
+                    logging(ctx.channel(), cmd.getType(), "", null);
                     break;
-
                 case MESSAGE:
                     if (service.getProxyLogLevel() != 2) {
                         logging(ctx.channel(), cmd.getType(), "", null);
                         break;
                     }
-                    topicName = TopicName.toFullTopicName(ParserProxyHandler.consumerHashMap.get(
-                            cmd.getMessage().getConsumerId() + "," + peerChannelId));
-
-                    msgBytes = new MutableLong(0);
-                    MessageParser.parseMessage(topicName, -1L,
-                            -1L, buffer, (message) -> {
-                                messages.add(message);
-                                msgBytes.add(message.getData().readableBytes());
-                            }, maxMessageSize);
-                    // update topic stats
-                    topicStats = this.service.getTopicStats().computeIfAbsent(topicName.toString(),
-                            topic -> new TopicStats());
-                    topicStats.getMsgOutRate().recordMultipleEvents(messages.size(), msgBytes.longValue());
-                    logging(ctx.channel(), cmd.getType(), "", messages);
+                    long consumerId = cmd.getMessage().getConsumerId();
+                    String topicForConsumer = context.consumerIdToTopicName.get(consumerId);
+                    if (topicForConsumer != null) {
+                        topicName = TopicName.toFullTopicName(topicForConsumer);
+
+                        MutableLong msgBytes = new MutableLong(0);
+                        MessageParser.parseMessage(topicName, -1L,
+                                -1L, buffer, (message) -> {
+                                    messages.add(message);
+                                    msgBytes.add(message.getData().readableBytes());
+                                }, maxMessageSize);
+                        // update topic stats
+                        TopicStats topicStats = this.service.getTopicStats().computeIfAbsent(topicName.toString(),
+                                topic -> new TopicStats());
+                        topicStats.getMsgOutRate().recordMultipleEvents(messages.size(), msgBytes.longValue());
+                        logging(ctx.channel(), cmd.getType(), "", messages);
+                    } else {
+                        logging(ctx.channel(), cmd.getType(), "Cannot find topic name for consumerId " + consumerId,
+                                null);
+                    }
                     break;
 
                  default:
diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyService.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyService.java
index 1acc34f12f4..1ea7832e9b8 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyService.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyService.java
@@ -53,7 +53,6 @@ import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
 import lombok.Getter;
-import lombok.Setter;
 import org.apache.pulsar.broker.ServiceConfigurationUtils;
 import org.apache.pulsar.broker.authentication.AuthenticationService;
 import org.apache.pulsar.broker.authorization.AuthorizationService;
@@ -110,7 +109,6 @@ public class ProxyService implements Closeable {
     protected final AtomicReference<Semaphore> lookupRequestSemaphore;
 
     @Getter
-    @Setter
     protected int proxyLogLevel;
 
     @Getter
@@ -528,4 +526,14 @@ public class ProxyService implements Closeable {
     protected LookupProxyHandler newLookupProxyHandler(ProxyConnection proxyConnection) {
         return new LookupProxyHandler(this, proxyConnection);
     }
+
+    public void setProxyLogLevel(int proxyLogLevel) {
+        this.proxyLogLevel = proxyLogLevel;
+        // clear the topic stats when proxy log level is changed to < 2
+        // this is a way to avoid the proxy consuming too much memory when there are a lot of topics and log level
+        // has been temporarily set to 2
+        if (proxyLogLevel < 2) {
+            topicStats.clear();
+        }
+    }
 }
diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyStatsTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyStatsTest.java
index 5769571d187..0f40bb9b72b 100644
--- a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyStatsTest.java
+++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyStatsTest.java
@@ -21,7 +21,9 @@ package org.apache.pulsar.proxy.server;
 import static java.util.Objects.requireNonNull;
 import static org.mockito.Mockito.doReturn;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
 import com.google.gson.Gson;
 import com.google.gson.reflect.TypeToken;
 
@@ -209,6 +211,62 @@ public class ProxyStatsTest extends MockedPulsarServiceBaseTest {
 
         consumer.close();
         consumer2.close();
+
+        // check that topic stats are cleared after setting proxy log level to 0
+        assertFalse(proxyService.getTopicStats().isEmpty());
+        proxyService.setProxyLogLevel(0);
+        assertTrue(proxyService.getTopicStats().isEmpty());
+    }
+
+    @Test
+    public void testMemoryLeakFixed() throws Exception {
+        proxyService.setProxyLogLevel(2);
+        final String topicName = "persistent://sample/test/local/topic-stats";
+        final String topicName2 = "persistent://sample/test/local/topic-stats-2";
+
+        @Cleanup
+        PulsarClient client = PulsarClient.builder().serviceUrl(proxyService.getServiceUrl()).build();
+        Producer<byte[]> producer1 = client.newProducer(Schema.BYTES).topic(topicName).enableBatching(false)
+                .producerName("producer1").messageRoutingMode(MessageRoutingMode.SinglePartition).create();
+
+        Producer<byte[]> producer2 = client.newProducer(Schema.BYTES).topic(topicName2).enableBatching(false)
+                .producerName("producer2").messageRoutingMode(MessageRoutingMode.SinglePartition).create();
+
+        Consumer<byte[]> consumer = client.newConsumer().topic(topicName).subscriptionName("my-sub").subscribe();
+        Consumer<byte[]> consumer2 = client.newConsumer().topic(topicName2).subscriptionName("my-sub")
+                .subscribe();
+
+        int totalMessages = 10;
+        for (int i = 0; i < totalMessages; i++) {
+            producer1.send("test".getBytes());
+            producer2.send("test".getBytes());
+        }
+
+        for (int i = 0; i < totalMessages; i++) {
+            Message<byte[]> msg = consumer.receive(1, TimeUnit.SECONDS);
+            requireNonNull(msg);
+            consumer.acknowledge(msg);
+            msg = consumer2.receive(1, TimeUnit.SECONDS);
+        }
+
+        ParserProxyHandler.Context context = proxyService.getClientCnxs().stream().map(proxyConnection -> {
+            ParserProxyHandler parserProxyHandler = proxyConnection.ctx().pipeline().get(ParserProxyHandler.class);
+            return parserProxyHandler != null ? parserProxyHandler.getContext() : null;
+        }).filter(c -> c != null && !c.getConsumerIdToTopicName().isEmpty()).findFirst().get();
+
+        assertEquals(context.getConsumerIdToTopicName().size(), 2);
+        assertEquals(context.getProducerIdToTopicName().size(), 2);
+
+
+        consumer.close();
+        assertEquals(context.getConsumerIdToTopicName().size(), 1);
+        consumer2.close();
+        assertEquals(context.getConsumerIdToTopicName().size(), 0);
+
+        producer1.close();
+        assertEquals(context.getProducerIdToTopicName().size(), 1);
+        producer2.close();
+        assertEquals(context.getProducerIdToTopicName().size(), 0);
     }
 
     /**