GeezerVison is showing github.com — [Bug] [functions-worker] WorkerUtils.createExclusiveProducerWithRetry leaks orphan exclusive producer when createAsync().get() times out · Issue #25936 · apache/pulsar
[Bug] [functions-worker] WorkerUtils.createExclusiveProducerWithRetry leaks orphan exclusive producer when createAsync().get() times out #25936Labels type/bugThe PR fixed a bug or issue reported a bug DescriptionSearch 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
Pulsar broker version (where the bug was first observed):
- Apache Pulsar 2.11.2 (internal custom build with broker-side plugins — the affected pulsar-functions/worker code path is the unmodified upstream version, no Boomi changes there)
- Linux on Kubernetes (Amazon EKS, eu-central-1)
- Amazon Linux 2 base, x86_64
- OpenJDK 17 (Amazon Corretto 17.0.2)
Pulsar broker version (verified the code path is unchanged on):
Pulsar client library:
- pulsar-client-java embedded in pulsar-functions-worker (same Pulsar version as the broker — the function-worker process constructs its PulsarClient against the local broker)
Client OS / hardware / Java:
- Same as broker: Linux on EKS, Amazon Linux 2, x86_64, OpenJDK 17 (Corretto 17.0.2). Workers and brokers run as separate StatefulSets on the same Kubernetes cluster.
Deployment shape:
- 3 broker pods, 4 function-worker pods, both as Kubernetes StatefulSets deployed via an Apache Pulsar Helm chart derivative
- brokerDeduplicationEnabled is unset on persistent://functions/internal/* topics, so they're created with dedup disabled (confirmed in broker logs: BrokerService: Created topic ... - dedup is
disabled). This is the upstream default; relevant because it eliminates the inactivity-based reaper as a recovery path for the orphan producer.
Issue Description
Root cause (from source analysis)
WorkerUtils.createExclusiveProducerWithRetry at pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/WorkerUtils.java (lines 415-444 in 2.11.2; structurally identical on master)
bounds producer creation with createAsync().get(10, TimeUnit.SECONDS). When get() throws TimeoutException, the catch block logs and returns to the retry loop. The in-flight
CompletableFuture is neither cancelled nor disposed.
The underlying ProducerImpl state machine continues to run on the PulsarClient IO thread. If the producer eventually registers with the broker (DNS resolves, broker accepts the create), it does so
as an orphan — registered with the broker, but no caller holds a reference. Every subsequent retry attempts to register a fresh ProducerImpl with the same exclusive producer name and is rejected.
Note that CompletableFuture.cancel(true) would not be sufficient — per its Javadoc, "the mayInterruptIfRunning parameter has no effect in this implementation". The producer state machine doesn't
observe cancellation; cancel() only updates the future's terminal state. The orphan still registers.
The orphan does not reap because:
- The client never sends CloseProducer (no caller reference exists to invoke close())
- The TCP connection stays alive (shared with other producers/consumers on the same PulsarClient, e.g., the worker's assignment-tailer Reader)
- The internal topics used by Pulsar Functions are created with brokerDeduplicationEnabled=false (verified in our broker logs: BrokerService: Created topic
persistent://functions/internal/assignments - dedup is disabled), so the broker's inactivity-based producer reaper does not apply
Relationship to existing PRs
Two recent PRs addressed adjacent slices of the orphan-producer problem space:
This issue extends the orphan-producer fix surface from #24539 to cover the timeout path in pulsar-functions/worker. Possible paths I'd want maintainer input on before writing a PR:
- Reuse FutureUtil from [fix][client] Close orphan producer or consumer when the creation is interrupted #24539 — if the helper from [fix][client] Close orphan producer or consumer when the creation is interrupted #24539 is generic enough to handle the timeout case, the fix in WorkerUtils would be a one-line conversion. Cleaner, but I'd want to confirm the
helper API fits.
- Inline whenComplete cleanup in WorkerUtils — the catch block attaches a callback that calls closeAsync() if the future eventually resolves with a producer. Diff is ~5 lines plus comment.
- Push the disposal logic into ProducerBuilderImpl/ProducerImpl itself — broader change, but would prevent the bug class showing up in any createAsync().get(timeout) caller. More invasive; likely
requires a PIP.
Error messages
We observed this in production on Pulsar 2.11.2 on 2026-05-23. DNS resolution to the new bundle owner lagged ~12 seconds during a broker StatefulSet rolling restart on
Kubernetes. The new leader was stuck for ~1 hour until manual kubectl rollout restart of the functions-worker StatefulSet. Internal RCA evidence available on request.
Concrete log fingerprint (with worker-specific identifiers redacted):
Broker side:
INFO o.a.p.b.s.BrokerService - Created topic persistent://functions/internal/assignments - dedup is disabled
INFO o.a.p.b.s.p.PersistentTopic - [persistent://functions/internal/assignments] Updated topic epoch to 1
INFO o.a.p.b.s.ServerCnx - [/<worker-ip>] Created new producer: Producer{
topic=persistent://functions/internal/assignments,
producerName=<workerId>-scheduler-manager,
producerId=0}
( ... no `Removed producer` for the lifetime of the worker JVM ... )
Worker side:
INFO ProducerStatsRecorderImpl - Starting Pulsar producer perf with config:
{producerName=<workerId>-scheduler-manager, ...} <- Producer #1
( ... DNS resolution failures for several seconds ... )
INFO ProducerImpl - [<workerId>-scheduler-manager] Created producer on cnx [id: ...]
Topic has an existing exclusive producer: <workerId>-scheduler-manager
( ... repeats every 10s, matching sleepInBetweenMs=10000 ... )
The two distinct Starting Pulsar producer perf lines — each from a separate ProducerImpl constructor — combined with the fact that WorkerUtils.createExclusiveProducerWithRetry only retries on
exception, prove the first createAsync().get(10s) threw TimeoutException. The successful Created producer on cnx line in between (from the IO thread) proves the broker accepted the first
registration. That's the orphan.
Reproducing the issue
Minimal reproduce step
The bug surfaces during a function-worker leader handoff when the broker that owns the assignments-topic bundle becomes unavailable AND the new bundle owner has DNS resolution lag exceeding 10
seconds (the hard-coded timeout in WorkerUtils.createExclusiveProducerWithRetry).
Synthetic reproduction (no production cluster needed):
- Deploy a 3-broker, 3-worker Pulsar Functions cluster (e.g., via apache/pulsar-helm-chart on kind/minikube).
- Identify which broker currently owns persistent://functions/internal/assignments, and which worker is the leader (via the participants Failover subscription on
persistent://functions/internal/coordinate).
- Add a network delay rule that fails DNS resolution for the broker pod that owns the assignments bundle for ~15 seconds. Tools that work:
- Toxiproxy with a latency toxic on the DNS port
- tc qdisc add ... delay 15000ms on the broker pod's veth
- A CoreDNS plugin temporarily blocking the headless-service A record
- Delete the broker pod that owns the bundle, forcing it to migrate to the broker affected by the DNS delay.
- Tail the new leader worker's logs.
What did you expect to see?
After at most a few retries, the new leader successfully acquires its -scheduler-manager exclusive producer on persistent://functions/internal/assignments, and can publish assignment
updates.
What did you see instead?
The new leader logs ProducerFencedException: Topic has an existing exclusive producer: -scheduler-manager every 10 seconds indefinitely. The producer name in the error message is the
leader's own producer. The cascade persists until the function-worker process is restarted.
Additional information
No response
Are you willing to submit a PR?
- I'm willing to submit a PR!
Activitylhotari commented on Jun 4, 2026 Reacted by Ashwin Dakappagari changed the title [-][Bug][/-] [+][Bug] [functions-worker] WorkerUtils.createExclusiveProducerWithRetry leaks orphan exclusive producer when createAsync().get() times out[/+] on Jun 4, 2026lhotari commented on Jun 4, 2026 @ashwindakappagari Thanks for reporting this. The simplest way to fix this is to remove the timeout from producer creation in createExclusiveProducerWithRetry.
I did find a way to make the code to handle the timeout without leaving an orphan producer, however this doesn't solve the problem:
CompletableFuture<Producer<byte[]>> producerFuture = client.newProducer().topic(topic)
.accessMode(ProducerAccessMode.Exclusive)
.enableBatching(false)
.blockIfQueueFull(true)
.compressionType(CompressionType.LZ4)
.producerName(producerName)
.createAsync();
CompletableFuture<Producer<byte[]>> timeoutFuture = producerFuture.orTimeout(10, TimeUnit.SECONDS);
timeoutFuture.exceptionally(t -> {
if (FutureUtil.unwrapCompletionException(t) instanceof TimeoutException) {
// Since the
producerFuture.thenCompose(Producer::closeAsync);
}
throw FutureUtil.wrapToCompletionException(t);
});
return timeoutFuture.get();
That causes more problems than it solves. The producer creation will continue to be in-flight and retrying the creation will just add another creation into the queue and that will fail due to the previous one being created. The Pulsar client doesn't support .orTimeout/.cancel for the future returned by createAsync.
The future returned by createAsync will complete with a timeout exception after the client's operationTimeout (default 30 seconds). It's better to rely on that.
That means that the fix would simply be .createAsync().get(10, TimeUnit.SECONDS) -> .createAsync().get().
One small detail is that Pulsar client might have a gap in the case where the successful producer creation would take more than 30 seconds to return back to the client. That most likely doesn't happen in practice. lhotari commented on Jun 4, 2026 Wrapping with FutureUtil.getAndCleanupOnInterrupt could be also done as suggested, however thread interruption would most likely not happen in the context of where WorkerUtils is used. ashwindakappagari commented on Jun 4, 2026 Thanks @lhotari — agree on the one-liner approach.
One question: the residual gap where producer creation succeeds slightly past operationTimeoutMs is exactly the bug class we're fixing, just narrower. In environments where broker pod replacement DNS recovery can exceed 30s (we observed 12s, but tail latencies during AZ-spanning rollouts have been seen higher), the orphan can still form.
Would you be open to a whenComplete-style cleanup on the residual future? Diff is +5 lines, eliminates the gap entirely.
Hope thats a fair Q.
Appreciate your quick response. ashwindakappagari commented on Jun 4, 2026
Thanks @lhotari — agree on the one-liner approach.
One question: the residual gap where producer creation succeeds slightly past operationTimeoutMs is exactly the bug class we're fixing, just narrower. In environments where broker pod replacement DNS recovery can exceed 30s (we observed 12s, but tail latencies during AZ-spanning rollouts have been seen higher), the orphan can still form.
Would you be open to a whenComplete-style cleanup on the residual future? Diff is +5 lines, eliminates the gap entirely.
Hope thats a fair Q.
Appreciate your quick response.
Hi @lhotari . This is what I have in mind.
public static Producer<byte[]> createExclusiveProducerWithRetry(PulsarClient client,
String topic,
String producerName,
Supplier<Boolean> isLeader,
int sleepInBetweenMs) throws NotLeaderAnymore {
try {
int tries = 0;
do {
CompletableFuture<Producer<byte[]>> producerFuture = null;
try {
producerFuture = client.newProducer().topic(topic)
.accessMode(ProducerAccessMode.Exclusive)
.enableBatching(false)
.blockIfQueueFull(true)
.compressionType(CompressionType.LZ4)
.producerName(producerName)
.createAsync();
return producerFuture.get(10, TimeUnit.SECONDS); //or make this 25 sec. close to the default timeout
} catch (Exception e) {
log.info("Encountered exception while at creating exclusive producer to topic {}",
topic, e);
if (producerFuture != null) {
producerFuture.whenComplete((p, err) -> {
if (p != null) {
try { p.closeAsync(); } catch (Exception ignored) { }
}
});
}
}
tries++;
if (tries % 6 == 0) {
if (log.isDebugEnabled()) {
log.debug("Failed to acquire exclusive producer ... after {} attempts.", topic, tries);
}
}
Thread.sleep(sleepInBetweenMs);
} while (isLeader.get());
} catch (InterruptedException e) {
throw new RuntimeException("Failed to create exclusive producer on topic " + topic, e);
}
throw new NotLeaderAnymore();
}
lhotari commented on Jun 4, 2026
One question: the residual gap where producer creation succeeds slightly past operationTimeoutMs is exactly the bug class we're fixing, just narrower. In environments where broker pod replacement DNS recovery can exceed 30s (we observed 12s, but tail latencies during AZ-spanning rollouts have been seen higher), the orphan can still form.
Would you be open to a whenComplete-style cleanup on the residual future? Diff is +5 lines, eliminates the gap entirely.
Hope thats a fair Q.
Appreciate your quick response.
If the exceeds 30 seconds, the Pulsar client's operationTimeout should be increased. There shouldn't be any timeout handling in WorkerUtils.createExclusiveProducerWithRetry .
In your case, since you are on an old version of Pulsar, you might be hitting multiple DNS issues that have been fixed in Pulsar / Netty. I'd strongly recommend to upgrade to a maintained Pulsar version to get the fixes. lhotari commented on Jun 4, 2026 #23590 is an important fix that you are missing. lhotari commented on Jun 4, 2026 In addition, there are also DNS related improvements / fixes on Netty side. ashwindakappagari commented on Jun 4, 2026 @lhotari Thank you.
Yes, we are in the process of upgrading. As you know, we have to deal with the current situation.
if you could share your view on the proposal here #25936 (comment) , that would be great. lhotari commented on Jun 4, 2026
@lhotari Thank you. Yes, we are in the process of upgrading. As you know, we have to deal with the current situation. if you could share your view on the proposal here #25936 (comment) , that would be great.
There shouldn't be a .get(10, TimeUnit.SECONDS) call in the code.
For clarity, this would be the way:
public static Producer<byte[]> createExclusiveProducerWithRetry(PulsarClient client,
String topic,
String producerName,
Supplier<Boolean> isLeader,
int sleepInBetweenMs) throws NotLeaderAnymore {
try {
int tries = 0;
do {
try {
CompletableFuture<Producer<byte[]>> producerFuture = client.newProducer().topic(topic)
.accessMode(ProducerAccessMode.Exclusive)
.enableBatching(false)
.blockIfQueueFull(true)
.compressionType(CompressionType.LZ4)
.producerName(producerName)
.createAsync();
return FutureUtil.getAndCleanupOnInterrupt(producerFuture, Producer::closeAsync);
} catch (Exception e) {
log.info().attr("topic", topic).exception(e)
.log("Encountered exception while creating exclusive producer");
}
tries++;
if (tries % 6 == 0) {
log.debug().attr("topic", topic)
.attr("attempts", tries)
.log("Failed to acquire exclusive producer."
+ " Will retry if we are still the leader.");
}
Thread.sleep(sleepInBetweenMs);
} while (isLeader.get());
} catch (InterruptedException e) {
throw new RuntimeException("Failed to create exclusive producer on topic " + topic, e);
}
throw new NotLeaderAnymore();
}
The FutureUtil.getAndCleanupOnInterrupt handles the InterruptedException and that's sufficient.
The timeout will need to rely on Pulsar client's operationTimeout. That can be configured with brokerClient_operationTimeoutMs in functions_worker.yml.
|
# You can add extra configuration options for the Pulsar Client and the Pulsar Admin Client |
|
# by prefixing them with "brokerClient_". These configurations are applied after hard coded configuration |
|
# and before the above brokerClient configurations named above. |
|
// Apply all arbitrary configuration. This must be called before setting any fields annotated as |
|
// @Secret on the ClientConfigurationData object because of the way they are serialized. |
|
// See https://github.com/apache/pulsar/issues/8509 for more information. |
|
clientBuilder.loadConf( |
|
PropertiesUtils.filterAndMapProperties(workerConfig.getProperties(), "brokerClient_")); |
lhotari commented on Jun 4, 2026
In environments where broker pod replacement DNS recovery can exceed 30s (we observed 12s, but tail latencies during AZ-spanning rollouts have been seen higher)
Just wondering if the DNS resolution issue is a deployment issue where the broker statefulset pod's DNS name won't resolve until the pod is healthy. Apache Pulsar Helm chart had such an issue that was just recently resolved. The solution (and issue) is described here: apache/pulsar-helm-chart#437 . The Pulsar Helm chart 4.6.0 release notes has more context: https://github.com/apache/pulsar-helm-chart/releases/tag/pulsar-4.6.0
Regardless, the fix to WorkerUtils.createExclusiveProducerWithRetry is needed. lhotari commented on Jun 4, 2026 Would you like to create a PR with a fix? I shared my view about the fix in #25936 (comment). ashwindakappagari commented on Jun 5, 2026 You have been very kind to me. Your comments are very insightful. Thank you.
I will be happy to create a PR with the fix you proposed. lhotari commented on Jun 5, 2026
You have been very kind to me. Your comments are very insightful. Thank you. I will be happy to create a PR with the fix you proposed.
@ashwindakappagari I'm sorry, but I already went forward and created a fix in #25942 since I'd like to include the fix in 4.0.11/4.2.2 which I'm about to start releasing today. Reacted by Ashwin Dakappagari
MetadataMetadatatype/bugThe PR fixed a bug or issue reported a bug DevelopmentNo branches or pull requestsIssue actions
|