azure-sdk-for-java: [BUG] Topic subscription randomly stops consuming messages after likely initial connection loss

Describe the bug We have observed the following behavior infrequently in our applications:

  • App launches and the azure servicebus topic subscription clients are created and start consuming messages
  • This runs perfectly fine afterwards
  • Eventually randomly we can see logs indicating a likely connection loss to servicebus (usually they happen at the same time across otherwise unrelated applications in our company so likely it’s something network related but ultimately a random short term connection loss especially with services in the internet can just happen and should be expected and just fixed by a quick reconnect)
  • Said reconnect in I’d say likely 99,9% works perfectly fine and after usually less than 3 seconds apps start consuming messages perfectly fine again
  • HOWEVER: Very rarely single apps will stop consuming messages for an undefined long time. What’s worth noting is if the affected application is listening on multiple subscriptions with different client java objects each then still absolutely all of them seem to be affected in this app. Weirdly enough ever now and then some apps eventually recover again but it can take upwards of 24 hours for them to do so or last all the way until they get restarted/undeployed

More details in the later sections

Exception or Stack Trace I’ll add a few logs here showing the individual stages described above (All timestamps are in Europe/Vienna timezone)

  1. As said usually at first we notice something likely related to some connection loss or so terminating the subscription clients. These logs are similarly repeated multiple times for different subscriptions and connectionIds, this is just here the first one that happened but within a few seconds we got the same logs for all our subscriptions existing in this app and also the same in other apps
Jun 11, 2024 @ 20:53:36.960 {"az.sdk.message":"Receiver emitted terminal completion.","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_edc9a5_1718126796076","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}
Jun 11, 2024 @ 20:53:36.960 {"az.sdk.message":"Current mediator reached terminal completion-state (retriable:true).","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_edc9a5_1718126796076","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01","retryAfter":1000}
  1. So as expected from the wording of the previous log shortly after we get logs showing that the new connections are opened again
Jun 11, 2024 @ 20:53:38.035 {"az.sdk.message":"Setting next mediator and waiting for activation.","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}
Jun 11, 2024 @ 20:53:38.097 {"az.sdk.message":"The mediator is active.","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}
  1. So far this would look pretty good again and is what we usually see before the app starts consuming messages again. Here however no message processing logs started to show up but instead a bit later we got a few more logs showing some kind of error, and since one of them specifically asks to report it is why we are already opening this bug
Jun 11, 2024 @ 20:54:38.070 {"az.sdk.message":"Unhandled exception while processing events in reactor, report this error.","exception":"java.lang.NullPointerException: uncorrelated channel: 74","connectionId":"MF_a311b3_1718132016996"}

so some kind of NPE, sadly I was unable to find anything else like a stack or so on the logs, so sorry about this being only so little. After this one we get another few logs a bit later all following roughly this one, so seemingly the connection is closed yet again

Jun 11, 2024 @ 20:55:38.076 {"az.sdk.message":"Receiver emitted terminal completion.","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}
Jun 11, 2024 @ 20:55:38.076 {"az.sdk.message":"Current mediator reached terminal completion-state (retriable:true).","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01","retryAfter":1000}
  1. Finally after this 2nd time of apparent connection loss now totally new logs starts to endlessly repeat every few minutes
Jun 11, 2024 @ 21:00:12.218 {"az.sdk.message":"Terminal error signal from Upstream|RetryLoop arrived at MessageFlux.","exception":"Retries exhausted: 3/3","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}
Jun 11, 2024 @ 21:00:12.218 {"az.sdk.message":"MessageFlux reached a terminal error-state, signaling it downstream.","exception":"Retries exhausted: 3/3","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}
Jun 11, 2024 @ 21:00:12.218 {"az.sdk.message":"Downstream cancellation signal arrived at MessageFlux.","messageFlux":"mf_9d516e_1718126796078","connectionId":"MF_a311b3_1718132016996","linkName":"preparer-topic_preparer/subscriptions/preparer_AT01_84ea87_1718126796078","entityPath":"preparer-topic_preparer/subscriptions/preparer_AT01"}

These errors randomly show up again every few minutes for hours on end afterwards, during all of this time this application is no longer receiving any messages

  1. Optional: This one is then even more rare and does not always happen before we just restart or redeploy our applications. But sometimes after a seemingly random time we see yet another strange error, and even stranger after this one suddenly the application starts consuming messages again for whatever reason
Jun 12, 2024 @ 19:49:52.371 {"az.sdk.message":"Unhandled exception while processing events in reactor, report this error.","exception":"java.lang.NullPointerException","connectionId":"MF_c2211b_1718132083255"}

So yet another NPE. But weirdly after this error showed up the subscribers were yet again recreated, the repeating logs stopped and eventually messages started getting processed again. As said this does not always happen, nor is there a fixed time for it to happen, we had apps running for multiple days never recovering until terminated.

To Reproduce Steps to reproduce the behavior: Sadly I was so far not able to provide a reliable way to reproduce it. I was experimenting a bit with interrupting my local network connection but so far was unable to reproduce this behavior from our openshift deployments on my machine.

One guess maybe from the logs above would be that it may be necessary to loose the connection twice within a short time, the 2nd one while the first reconnect is still ongoing, but this is really just a guess. Also could be some race condition happening only with sufficient load, there’s a limit to how much I can manage locally at once. Maybe the NPEs asking to get reported or some other logs do provide someone with deeper code understanding already with some further idea.

We will also continue looking into this on our side and post any updates, while it is not that bad since it seems overall pretty rare usually only noticing it in a few single applications every few days with hundreds of them running and thanks to high available setup usually messages still get processed by other replicas, just maybe with a bit less throughput, we still would prefer to be reliable in this area.

Code Snippet Here’s the code how we are usually creating our subscribers

final ServiceBusClientBuilder.ServiceBusProcessorClientBuilder builder =
	resolveBuilder(String.format(CONNECTION_HOST_URL, connection.getHost(), connection.getKeyName(), connection.getKey()))
		.processor()
		.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
		.topicName("the-topic-name")
		.subscriptionName("the-subscription-name")
		.prefetchCount(0)
		.maxConcurrentCalls(<1 to 10 usually>)
		.maxAutoLockRenewDuration(<usually around 10min>)
		.processMessage(serviceBusMessageHandler::receiveMessage)
		.processError(serviceBusMessageHandler::handleError);

Expected behavior Lost subscription connections are always recreated and running applications always reliably recover once the connection can be recreated and start consuming messages again

Screenshots None

Setup (please complete the following information):

  • OS: Openshift hosts are RHEL based, actual app images are various between debian/rhel/alpine
  • IDE: IntelliJ/Eclipse
  • Library/Libraries: com.azure:azure-messaging-servicebus:7.16.0, getting 7.17.0 out will likely take a bit but from a quick check of the changelog no relevant changes were found anyway
  • Java version: Multiple, mostly 11 and 17, few 21. Usually openjdk based
  • App Server/Environment: Tomcat, embedded by srping
  • Frameworks: Spring Boot 2.7.x or 3.2.x

Further information If there’s anything else needed just let me know and I’ll try to provide it, e.g. specific logs

Information Checklist Kindly make sure that you have added all the following information above and checkoff the required fields otherwise we will treat the issuer as an incomplete report

  • Bug Description Added
  • Repro Steps Added
  • Setup information Added

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 30 (18 by maintainers)

Most upvoted comments

Hi @anuchandy thanks a lot for the info, that was fast! Otherwise everything great here and just from a small check still never any issues in the opt-in application, so I’ll see we get this updated as fast as possible so we soon will be safe in all our applications. Hope also everything is well on your site! Thanks also for the amazing write-up regarding CPU limits, this and the links has provided my team with strong arguments why many of our current sizings are “not ideal” and we’ve finally started with improvements in this area!

Hi @TheDevOps, I hope you are doing well.

As promised, posting here about the 7.17.6 release -

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-servicebus</artifactId>
    <version>7.17.6</version>
</dependency>

this version has -

  1. opt-in “com.azure.core.amqp.cache” on by default.
  2. the HMAC token bug fix.

Closing this, I’ll leave a comment when the Service Bus library that opt-in the flag by default is released.

For those who are reading, this comment is not about the RCA of the original issue but discusses how certain CPU settings could theoretically cause the Service Bus client to halt. It is recommended that you review the following two sections if you are containerizing an application that utilizes the Service Bus library.

  • Section-1: Average CPU usage can be misleading.
  • Section-2: Tuning CPU and Thread pool size.

Average CPU usage can be misleading

This section outlines the side effects experienced by a library due to CPU settings in Kubernetes, in production. We’ll refer this library as HEI-client. The HEI-client has similar characteristics and performance expectations as the Service Bus library.

First, let’s start with the overview of the threading model in the Service Bus library. There are two categories of threads,

  1. IO-Thread – this single thread responsible for all IO operations, message decoding and resource cleanup in an AMQP connection.
  2. Worker Threads – these are all threads responsible for pumping messages to the Processor handlers.

Image

As we can see, the single IO-Thread is a scarce resource. The overall “performance” and “reliability” of the library depends on health and available system resources for the IO-Thread.

By “performance”, we refer to the timely delivery of messages and the processing of dispositions (complete and abandon operations). If the library processes 1000 messages per second, then there will be 1000 dispositions as well, resulting in approximately 2000 events per second enqueued to the IO-Thread’s event queue. The IO-Thread must process these events efficiently to maintain high throughput, which in turn depends on available CPU cycles.

By “reliability”, we refer to the role IO-thread has when the connection is lost, the IO-Thread is responsible for reaching out to each receiver one by one (serially), draining their in-memory messages and performing cleanup (closing resources, freeing internal states etc…). After the completion of cleanup across all receivers, the current IO-Thread is responsible for setting up the next connection and next IO-Thread. Failure in any of these steps can halt system progress. A halt in IO-Thread won’t cause high CPU usage, making it hard to detect by common monitoring systems.

For these reasons, it is recommended to leave one CPU core for Service Bus library IO-Thread and have additional core for Worker Threads depending on the application workload (more on this in the next section).

The HEI-client is like the Service Bus library, with IO-Thread and Worker Threads. Let’s examine the resourcing issues encountered by the HEI-client and draw comparisons to the Service Bus client.

The diagram below illustrates the latency spikes experienced by the HEI-client. While the average latency remained approximately 10ms, the application periodically encountered significant latency spikes. The chart identifies two such instances where the latency increased to 50ms and 80ms, respectively, thus impacting the SLA.

Latency

The networking module of HEI-client provides a metric indicating the number of pending tasks in the task-queue associated with its threads. A correlation is observed between latency spikes and the periods when there were numerous outstanding tasks in the thread task-queue.

ThreadPoolQueueLength

Like HEI-client, the IO-Thread in the Service Bus library has a task queue (called Qpid event queue as shown in the threading model diagram). The Service Bus library’s Worker Threads from the bounded elastic thread pool also have similar task queues. Unfortunately, neither the Qpid library nor the Reactor bounded elastic pool has task-queue length metric available.

Now looking at the CPU usage of the HEI-client, the average CPU usage stayed 20-25% range, drawing no correlation between CPU usage and the latency spike or thread’s task-queue length.

CPUAverage

Upon further investigation, it was determined that average CPU utilization graphs are not reliable indicators for assessing whether limits are being reached. The appropriate method is to inspect the pod’s cpu.stat file for the “number of throttled periods” and the “total time spent throttled”.

The monitoring system used by HEI-Client had agents capturing these throttling stats from the pods. E.g., Prometheus can alert when container experiences CPU throttling. The diagram below shows the CPU throttling chart for HEI-Client.

CPUThrottle

As we can see there is a correlation between the CPU throttling and latency spike / thread’s tasks-queue length.

It was discovered that the containers had CPU “limit” set. Although the Kubernetes cluster has sufficient CPUs available globally, the limit imposed on the container restricted the HEI-Client from utilizing the spare CPU cycles. This led to a lower average CPU in usage graph while there were latency spikes.

The Kubernetes experts involved in the discussion shared the following references outlining problems with “limit” -

  1. Stop Using CPU Limits on Kubernetes
  2. CPUThrottlingHigh Prometheus Alert
  3. Resource-QoS

Tuning CPU and Thread pool size

We have seen a quite handful of Service Bus cases, where application hangs and bumping the cores and/or tuning the thread pool size brought back the processing to normal. The library team’s investigations are based on SDK logs to identify any issue in SDKs and don’t cover resource constraints imposed by the host environment. The resource allocation depends on user-specific workloads and is outside library team’s scope/expertise, but we have the following general guidelines -

  • Dedicate a core for IO-Thread.
  • Compute and assign the Worker Thread pool size
    • The user chosen max-concurrent-calls setting dictates the size of the Worker Thread pool.
    • For e.g., if there are 20 Processors each with max-concurrent-calls set to 10, the total concurrency would be 200. An additional ~20 should be added as a reservation for internal use of the library, resulting in Worker Thread pool of size 220.
    • The Worker Thread pool size can be set using the system property reactor.schedulers.defaultBoundedElasticSize.
  • Limit 30-40 Worker threads per core. So, for a Worker Thread pool of size 220, there should be 5-7 cores.

A starting point of 30-40 Worker threads per core is generally recommended; however, you may need to adjust based on the application’s specific workload characteristics. This could involve either reducing or increasing the number of cores as required. The following formula can be used to compute the optimal number of cores, Ncpu,

Ncpu = Max(2, Thread_pool_size / (Ucpu * (1 + W/C)))

The formula first ensures a minimum of 2 cores, based on the recommendation from Java team at Microsoft for any containerized application, Containerize your Java applications | Microsoft Docs.

The second part of the formula, Thread_pool_size / (Ucpu * (1 + W/C)), is derived from the pool sizing guideline in “Java Concurrency in Practice” book.

Where

Thread_pool_size :

The size of the Worker Thread pool computed based on max-concurrent-calls (220 in the above example).

Ucpu :

Target CPU utilization for the application (0 <= Ucpu <= 1). For example, if we want 70% of CPU to be allocated for the application and 30% for the rest (JVM GC threads, other apps), then this value Ucpu is 0.7.

W/C :

Ratio of Wait-Time (W) to Compute-Time ©, this is what application developer should “measure” (specific to their application workload) using profiling tools -

  • “Wait-Time (W)” is the average duration the Worker Threads waits for IO.
  • “Compute-Time ©” is the average duration the Worker Thread spends on the CPU (computation).

Profiling the application in a setup close to real traffic will help find these numbers.

For example, consider an application that on average spends 500ms on I/O (e.g., calling a REST API) and 5ms on computation (e.g., processing the JSON response). If the required thread pool size is 220 and the desired CPU utilization (Ucpu) is 0.7, the formula would be applied as follows:

Ncpu       = Max(2, Thread_pool_size / (Ucpu * (1 + W/C))) 
           = Max(2, 220 / (0.7 * (1 + 500/5)))
           = Max(2, 200 / (0.7 * 101))
           = Max(2, 3.1)
           = 3.1 cores = 3100millicore

So, 3.1 core are required to support Worker Thread pool of size 220.

The primary factor determining the core count is the pool size, which is based on the application’s chosen “concurrency” level (Processors multiplied by max-concurrent-calls). It is crucial to select a value that aligns with the actual processing requirements. For e.g., with a “concurrency” of 200 (e.g., 20 Processors each with 10 max-concurrent-calls) and an average processing time of 500ms, the application aims to handle 400 messages per second, i.e., 24,000 messages per minute. Therefore, it makes sense to evaluate whether this indeed corresponds to the expected incoming load and if the external service calls within the processor handler (such as database interactions and API calls) are optimized to manage such a volume efficiently. The quality of the network, the Service Bus tier and throughput units are other factors to consider.

It is worth noting that the Worker Thread pool does not immediately create threads equal to the pool size. The pool size represents an upper limit, and the pool will expand or shrink within this limit based on the workload.

Hello @anuchandy

alright it’s the promised Friday again so time for my final update: Still not a single instance of no messages being processed has been observed in the application with the opt-in enabled! Also yet another detailed review of the logs showed no further issues either. Considering it has been 10 days now in an application where it previously happened almost daily I’m absolutely positive that it is indeed fixed.

So maybe to just summarize the whole ticket again in this final location:

  • Previously in multiple applications we would notice extended periods where random replicas stop processing messages all together
  • A later discussed likely important point is that in all these applications we are using the same builder object to listen on multiple subscriptions of the same topic. Internally in the azure servicebus library this means that the connection is reused for all those processing clients created by the same builder object
  • First analysis pointed to that rarely during a reconnect of the multiple clients created with a shared builder sometimes one of them would timeout and likely due to some race condition then shutdown itself and thus the whole connection which results in all other clients sharing the same connection to also do so and also for some reason not immediately attempt another reconnect but stay inactive. The more clients sharing the connection and the higher the overall load on the affected topic the higher the chance to encounter this issue it seems
  • In release 7.17.4 a currently opt-in requiring refactoring is contained in the azure servicebus library that does a major rework of exactly this internal logic. For details how to enable this opt-in and some more see https://github.com/Azure/azure-sdk-for-java/issues/40608#issuecomment-2383479174 and some of the following comments
  • During all the discussions we discovered another issue in this area with multiple processor clients on a shared connection and the security token refresh in parallel threads that got fixed in 7.17.5 so ideally use this or a later one if this issue affects you
  • With 7.17.5 and the opt-in enabled we have not observed the issue happen a single time over 10 days in an application where before this we usually saw it at least every 1 or 2 days in 1 replica. For me personally this more than confirms the expectation that these refactoring has also addressed this issue
  • At a later date (around February to my last information) the current opt-in will become the default in the library at which point even without doing anything other than updating to this release this issue should resolve itself

So in short if someone else is regularly affected by the problem described here and also has a shared builder for multiple subscribers setup I strongly recommend to update to 7.17.5 or later and perform the small opt-in change for all builders in the application.

For my project we will check which apps besides the one we did all our tests right now are also affected regularly enough to warrant enabling the opt-in for them and for those we only see it like once a month we will just continue our previous “monitor, get notified and restart” approach until it gets resolved by a small update of the library eventually. For us this is a totally acceptable solution and the issue can be closed if you don’t see any need to keep it open any longer. Maybe if possible just drop a small final comment once the version where the current opt-in becomes the default is released, might be interesting for others that stumble into this issue as well.

Besides this thanks for all the help and the great discussions during this issue!

Hello @anuchandy

As promised here’s my Friday update: We updated our application for our PROD cluster with the opt-in enabled this Tuesday and so it has now been running for almost 72 hours. And the so far great news: There hasn’t been a single instance of a noticeable timeframe where any pod stopped to process messages. While it is “only” 3 days in this application so far it has been pretty common to see it almost daily in at least 1 pod, so I have a very good feeling that the bigger internal reworkings will also have solved this issue right now. Still if you do not mind I’d like to keep monitoring it for 1 more week so we have 10 days total before I think it would be fine to close this ticket with pointing to the big reworkings and opting-in to them if you need it early or waiting until it becomes the default. If it never happens in this timeframe I’m absolutely certain that this reworkings have fixed this issue. I’d also like to look into the logs a bit more if I can spot anything else since the switch, but from a first quick glance besides the already known and fixed token renewal due to the non threadsafe object (which I hope we will also get around to deploying the fix for it as well soon) that besides some logs is not really causing any observable issues with the message processing I did not immediately spot anything else, but sadly I didn’t have as much time as I wanted yet for this topic, but I’ll definitely try to get it next week. I’ll provide another update next week, but already thanks a lot for all the support and fingers crossed we can soon close this!

Hello @TheDevOps, good morning!, thanks for the response.

Yes, it’s recommended to use opt-in for Sender as well. you’re correct—the opt-in syntax for Sender remains the same. Just a small note: when transitioning to central management for Sender, please ensure that the current nature (whether dedicated or shared) of the Sender builder remains unchanged to avoid any shifts in connection handling behavior.

Good morning @anuchandy

As usual thanks for the great responses!

Your guess with a different builder being used for the sender is almost certainly correct, while we do have a central library location where we create all our subscribers for topics defined in an applications yaml signature and then all the “tenant groups” (this is always the _XX01 and so on you can see at the end of the sub names, we generally have some 50~80 tenants grouped as e.g. _AT01 as the first Austrian grouping and so on) where the specific application build is active currently. Senders however are generated locally by the application team “as required” and the only thing our library does is adding some interceptors that set the required routing headers (such as the tenant group sending a message so it gets then routed to the correct tenant group subscription) but the builder object is unrelated to the subscriber builder right now and so also does not have any opt-in code right now. Even though we are not currently observing any issues such as the NPE you mentioned I assume it’s generally recommended to ideally perform the opt-in for both senders and subscribers? I’ll try to sync if we currently have any easy way to maybe also centrally do it for senders in this case. I assume the syntax is generally the same as for subscribers?

For the private stuff you’ll get a mail from me any minute!