Possible memory leak receiving messages in servicebus 0.50.3
- Package Name: servicebus
- Package Version: 0.50.3
- Operating System: Linux Alpine/Debian, OSX
- Python Version: 3.8.6
Describe the bug Apparently memory leaks from receiving messages.
To Reproduce Steps to reproduce the behavior:
- create a queue client
- create a receiver
- receive (and ignore) a message
- back to point 1
Expected behavior No relevant memory usage increase.
Code
Here a sample of the code I use to replicate. Notice I am not processing messages and I am running against an empty queue.
import os
from azure.servicebus import ServiceBusClient, ReceiveSettleMode
if __name__ == '__main__':
service_bus_client = ServiceBusClient(service_namespace=os.environ['AZURE_BUS_NAMESPACE'],
shared_access_key_name=os.environ['AZURE_BUS_KEY_NAME'],
shared_access_key_value=os.environ['AZURE_BUS_KEY_VALUE'])
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
for _ in range (1000000):
# ofc I could create the queue once, but this is closer to my actual code
queue = service_bus_client.get_queue(queue_name=queue_name)
with queue.get_receiver(mode=ReceiveSettleMode.PeekLock) as receiver:
msg_batch = receiver.fetch_next(max_batch_size=1, timeout=1)
# notice I do not really expect to receive any message, printing just to keep it busy....
print(msg_batch)
Additional context
I know that I am not running on the latest version, but I have the feeling the issue might be in the uamqp layer and therefore of interest for also the new versions as well.
hey @andrea-cassioli-maersk , thanks for reporting.
Could you also share the version of uamqp that you use? (pip show uamqp would give version number)
Here it is
08:29 $ pip3.8 show uamqp
Name: uamqp
Version: 1.2.12
Summary: AMQP 1.0 Client Library for Python
A bit more investigation. Running
import os
from azure.servicebus import ServiceBusClient, ReceiveSettleMode
if __name__ == '__main__':
service_bus_client = ServiceBusClient(service_namespace=os.environ['AZURE_BUS_NAMESPACE'],
shared_access_key_name=os.environ['AZURE_BUS_KEY_NAME'],
shared_access_key_value=os.environ['AZURE_BUS_KEY_VALUE'])
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
for _ in range(1000000):
queue = service_bus_client.get_queue(queue_name=queue_name)
with queue.get_receiver(mode=ReceiveSettleMode.PeekLock) as receiver:
msg_batch = receiver.fetch_next(max_batch_size=1, timeout=1)
# notice I do not really expect to receive any message, printing just to keep it busy....
print(msg_batch)
Still I see memory increase. However, the following code runs clean:
import os
from azure.servicebus import ServiceBusClient, ReceiveSettleMode
if __name__ == '__main__':
service_bus_client = ServiceBusClient(service_namespace=os.environ['AZURE_BUS_NAMESPACE'],
shared_access_key_name=os.environ['AZURE_BUS_KEY_NAME'],
shared_access_key_value=os.environ['AZURE_BUS_KEY_VALUE'])
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
queue = service_bus_client.get_queue(queue_name=queue_name)
with queue.get_receiver(mode=ReceiveSettleMode.PeekLock) as receiver:
for _ in range(1000000):
msg_batch = receiver.fetch_next(max_batch_size=1, timeout=1)
# notice I do not really expect to receive any message, printing just to keep it busy....
print(msg_batch)
So I think the receiver must be the reason.
I have tried version 7 and I see similar behaviour. For instance
import os
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError
if __name__ == '__main__':
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
for i in range(100000):
with service_bus_client.get_queue_receiver(queue_name=queue_name) as receiver:
try:
received_msgs = receiver.peek_messages(max_message_count=1, timeout=10)
print(i, received_msgs)
except OperationTimeoutError:
pass
shows a slow memory increase, but
import os
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError
if __name__ == '__main__':
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
with service_bus_client.get_queue_receiver(queue_name=queue_name) as receiver:
for i in range(100000):
try:
received_msgs = receiver.peek_messages(max_message_count=1, timeout=10)
print(i, received_msgs)
except OperationTimeoutError:
pass
it is again clean.
Hi guys, any thoughts?
hey @andrea-cassioli-maersk , sorry it's a bit crowded recently and I really appreciate your debugging process.
based on what you provide, I think it's either the connection or client in uamqp that causes the issue. As you may know the uamqp library is built on top of c libraries. It's could be the cython binding layer or the c libraries leaking the memory.
will you get memory leak if you only get receiver not try to establish the connection? (suppose you're using v5)
with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
for i in range(100000):
service_bus_client.get_queue_receiver(queue_name=queue_name)
Thanks @yunhaoling , just tried what you proposed on v7 (did you mean 0.5?
import os
from azure.servicebus import ServiceBusClient
if __name__ == '__main__':
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
while True:
service_bus_client.get_queue_receiver(queue_name=queue_name)
and the memory just explodes!
However
import os
import time
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError
if __name__ == '__main__':
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
while True:
with service_bus_client.get_queue_receiver(queue_name=queue_name) as r:
pass
seems stable with a tiny increase in memory consumption.
hey @andrea-cassioli-maersk , may I ask how long do you run the program with the code?
import os
import time
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError
if __name__ == '__main__':
queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
while True:
with service_bus_client.get_queue_receiver(queue_name=queue_name) as r:
pass
I'm wondering whether it's because running not long enough that the garbage collection doesn't kick in yet
I tried running that code in a docker container for say 2 hours and the memory increased several Mb. Not sure if the GC should already kick in already.
BTW, my application runs for days and there I see the memory going up to fill Gbytes. This behaviour started when we moved to 0.50.
Any feedback? It would be good to know if it is an issue in 0.50.X and whether upgrading to 7 will solve the issue.
hey @andrea-cassioli-maersk , confirming the issue on linux -- I ran the code on a linux vm over 24 hrs and the memory did increase constantly. thanks for your instructions! at least we know that the leak happens during the connection establishment/shutdown process. I believe it's an issue in the uamqp, I need further investigation into the underlying module like Cython, C, that's the place where leaks most likely could take place.
Hey @yunhaoling thanks for confirming the issue! Indeed we spot it on Linux Docker containers and then confirmed on Mac as well.
Do you believe upgrading to version 7 would solve, or at least mitigate?
@andrea-cassioli-maersk , I don't think so as the leak happened in uamqp, but I would strongly recommend you to upgrade v7, as we v0.50 is deprecated.
I have found a potential leaking place in the cython layer https://github.com/Azure/azure-uamqp-python/blob/b7de7bab1b8d0b2457ff77bd3b3188efb5c1b065/src/cbs.pyx#L26-L37 where a C string is not deallocated properly, will try something to see if fixing this one could mitigate the leak issue.
@yunhaoling thanks for the clarification, we will migrate to 7 soon. Please keep me posted on the leak.
Just to confirm, the memory leak is definitely affecting version 7. We update our code and we are experiencing the same issue.
This leak is affecting us too. It's not good for it's to be leaking memory like this. It could well be in the underlying C libraries somewhere.
hey folks, I have some free cycles this week and will dig deep into the underlying C libraries to see if can find anything.
posting updates for the memory leak issue:
it seems like the memory happens during the session establishment process in the cython layer, in the on_link_attached callback source and target from the c module would be cloned (reference count + 1), while I didn't find any code that destroy those two cloned variables (reference count -1).
more details could be found in my PR: https://github.com/Azure/azure-uamqp-python/pull/215.
I'm still testing and finding the right solution for it, thanks for your patience
hey folks, we have released uamqp v1.4.0 which fixed the memory leak in uamqp cython layer.
please update the uamqp via pip install uamqp --upgrade to try out the fix.
I have validated the fix by valgrind (which is a C memory debug tool), no memory leaks on my side. (The memory usage might grow but after a while python GC would kick in).
I'm closing the issue now. feel free to reopen if you still run encounter the issue, thanks for your patience!
also details could be found here in the PR: https://github.com/Azure/azure-uamqp-python/pull/230
Hi @yunhaoling, it seems there are still some memory issues in version 7.2.0 of the service bus python package.
I ran a similar version to the script below for around 6 hours, explicitly calling the GC every few iterations and the memory just kept growing.
while passed_secs < time_limit_secs:
# ofc I could create the queue once, but this is closer to my actual code
with service_bus_client.get_queue_receiver(queue_name=queue_name) as receiver:
msg_batch = receiver.receive_messages(max_message_count=1,
max_wait_time=3)
# notice I do not really expect to receive any message, printing just to keep it busy....
print(msg_batch)
if cnt % 100 == 0:
print("Forcing GC to run")
gc.collect()
Below you can see also a plot of how the memory grows:

When instead I initialized the service bus client within the while loop above, we see that the memory increases at a much slower rate:

Could you check if you see the same at your end?