{"id":834,"library":"azure-servicebus","title":"Azure Service Bus Client Library for Python","description":"The `azure-servicebus` library (version 7.14.3) is the Microsoft Azure Service Bus client for Python. It provides high-performance, cloud-managed messaging capabilities for real-time and fault-tolerant communication between distributed senders and receivers. It supports various asynchronous messaging patterns, including structured first-in-first-out messaging, publish/subscribe, and scalable queues and topics. The library is actively maintained with regular releases.","status":"active","version":"7.14.3","language":"python","source_language":"en","source_url":"https://github.com/Azure/azure-sdk-for-python","tags":["azure","messaging","service bus","queue","pub/sub","cloud"],"install":[{"cmd":"pip install azure-servicebus azure-identity aiohttp","lang":"bash","label":"Install core, identity, and async dependencies"}],"dependencies":[{"reason":"Recommended for passwordless authentication using Azure Active Directory, especially in production environments.","package":"azure-identity","optional":false},{"reason":"Required for using the asynchronous (async) API functionality of azure-servicebus.","package":"aiohttp","optional":true}],"imports":[{"symbol":"ServiceBusClient","correct":"from azure.servicebus import ServiceBusClient"},{"symbol":"ServiceBusMessage","correct":"from azure.servicebus import ServiceBusMessage"},{"symbol":"ServiceBusReceivedMessage","correct":"from azure.servicebus import ServiceBusReceivedMessage"},{"note":"Used for Azure AD authentication, often preferred over connection strings in production.","symbol":"DefaultAzureCredential","correct":"from azure.identity import DefaultAzureCredential"}],"quickstart":{"code":"import os\nfrom azure.servicebus import ServiceBusClient, ServiceBusMessage\n\n# Retrieve connection string from environment variable\nCONNECTION_STR = os.environ.get('AZURE_SERVICEBUS_CONNECTION_STRING', 'Endpoint=sb://<YOUR_NAMESPACE>.servicebus.windows.net/;SharedAccessKeyName=<KEY_NAME>;SharedAccessKey=<KEY_VALUE>')\nQUEUE_NAME = os.environ.get('AZURE_SERVICEBUS_QUEUE_NAME', 'myqueue')\n\ndef send_single_message():\n    servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)\n    with servicebus_client: # automatically closes client on exit\n        sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)\n        with sender: # automatically closes sender on exit\n            message = ServiceBusMessage(\"Hello, Service Bus!\")\n            sender.send_messages(message)\n            print(f\"Sent a single message to queue: {QUEUE_NAME}\")\n\ndef receive_single_message():\n    servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)\n    with servicebus_client:\n        receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5) # max_wait_time in seconds\n        with receiver:\n            received_messages = receiver.receive_messages(max_messages=1)\n            for msg in received_messages:\n                print(f\"Received message: {msg.body}\")\n                # Complete the message to remove it from the queue\n                receiver.complete_message(msg)\n                print(\"Message completed.\")\n            if not received_messages:\n                print(f\"No messages received from queue: {QUEUE_NAME}\")\n\nif __name__ == '__main__':\n    # Ensure AZURE_SERVICEBUS_CONNECTION_STRING and AZURE_SERVICEBUS_QUEUE_NAME are set as environment variables\n    # or replace placeholder values in the CONNECTION_STR and QUEUE_NAME variables.\n    print(\"Sending message...\")\n    send_single_message()\n    print(\"Receiving message...\")\n    receive_single_message()\n","lang":"python","description":"This quickstart demonstrates how to send and receive a single message using Azure Service Bus queues. It initializes a `ServiceBusClient` from a connection string, then obtains a sender to send a `ServiceBusMessage` and a receiver to receive and complete a `ServiceBusReceivedMessage`. For production, using `azure-identity` with `DefaultAzureCredential` is recommended over connection strings. Ensure the `AZURE_SERVICEBUS_CONNECTION_STRING` and `AZURE_SERVICEBUS_QUEUE_NAME` environment variables are set."},"warnings":[{"fix":"Migrate code to the new API patterns. Refer to the official Azure SDK for Python migration guides for detailed steps. Primarily, `ServiceBusClient` is now the entry point, and `azure-identity` classes like `DefaultAzureCredential` are used for authentication instead of connection strings directly in the client constructor.","message":"Major breaking changes occurred between versions v0.50.x and v7.x of the `azure-servicebus` library. The API surface was significantly revamped to align with the Azure SDK guidelines, including new client constructors, authentication patterns (shifting to `azure-identity`), and object models for messages and clients.","severity":"breaking","affected_versions":"< 7.0.0"},{"fix":"Implement robust error handling and retry mechanisms. Ensure message settlement (complete, abandon, defer, dead-letter) is performed promptly. For session-enabled entities, be prepared to re-accept sessions if a `SessionLockLost` exception occurs. Consider adjusting lock durations and prefetch counts.","message":"Message or session locks can be lost before their expiration time due to transient network failures, network outages, or the service's 10-minute idle timeout. If a message is received but not settled before the link detaches, it cannot be settled upon reconnection, potentially leading to redelivery or dead-lettering.","severity":"gotcha","affected_versions":"7.x"},{"fix":"Treat `ServiceBusClient` instances as singletons where possible, reusing a single client instance throughout the application's lifetime. The `ServiceBusClient` manages connections for all objects created from it (senders, receivers, processors).","message":"Creating multiple `ServiceBusClient` instances within an application can lead to socket exhaustion errors, as each client typically establishes a new AMQP connection. This can deplete available network resources and cause connectivity issues.","severity":"gotcha","affected_versions":"7.x"},{"fix":"Monitor `ThrottledRequests` and `IncomingRequests` metrics in Azure. Implement back-off and retry policies in your client code to gracefully handle throttling. Consider upgrading to a higher Service Bus tier or distributing load across multiple namespaces if quotas are consistently hit.","message":"Azure Service Bus enforces quotas on messaging operations. Exceeding these quotas can result in throttling, causing send and receive operations to slow down or fail with `ServiceBusy` exceptions.","severity":"gotcha","affected_versions":"7.x"},{"fix":"Ensure proper `with` statement usage for `ServiceBusClient`, `ServiceBusSender`, and `ServiceBusReceiver` to guarantee correct closure and resource release. Avoid holding references to messages or client objects after they have been settled or explicitly closed.","message":"Errors like 'brokeredmessage has been disposed' or 'cannot access a disposed object' indicate that an attempt was made to interact with a message or client object that has already been closed or disposed. This often occurs when managing client lifetimes incorrectly or trying to settle a message that has already been settled.","severity":"gotcha","affected_versions":"7.x"},{"fix":"Verify the Service Bus connection string or the fully qualified namespace name for any typos. Ensure that the application's environment has proper DNS resolution capabilities and network connectivity to Azure Service Bus endpoints.","message":"A `ServiceBusConnectionError` with `[Errno -2] Name or service not known` indicates that the client could not resolve the hostname of the Service Bus namespace. This typically means the connection string (or the fully qualified namespace name provided) is incorrect, misspelled, or there is a DNS resolution issue within the execution environment.","severity":"gotcha","affected_versions":"7.x"},{"fix":"Verify the spelling of the Service Bus namespace hostname (e.g., `your-namespace.servicebus.windows.net`) in your connection string or the `fully_qualified_namespace` parameter. Ensure any environment variables providing the hostname are correct. Check the network environment for proper DNS configuration and connectivity to Azure endpoints.","message":"The `ServiceBusConnectionError` with `[Errno -2] Name does not resolve` indicates that the specified Service Bus namespace hostname could not be resolved to an IP address. This is typically caused by a typo in the hostname, an incorrectly configured environment variable, or a network DNS resolution issue.","severity":"gotcha","affected_versions":"7.x"}],"env_vars":null,"search_vec":"'7.14.3':14 'activ':71 'asynchron':51 'azur':1,10,18,76 'azure-servicebus':9 'bus':3,20,79 'capabl':33 'client':4,21 'cloud':30,82 'cloud-manag':29 'communic':42 'distribut':44 'fault':40 'fault-toler':39 'first':57,59 'first-in-first-out':56 'high':27 'high-perform':26 'includ':54 'librari':5,12,69 'maintain':72 'manag':31 'messag':32,52,61,77 'microsoft':17 'pattern':53 'perform':28 'provid':25 'pub/sub':81 'publish/subscribe':62 'python':7,23 'queue':65,80 'real':36 'real-tim':35 'receiv':47 'regular':74 'releas':75 'scalabl':64 'sender':45 'servic':2,19,78 'servicebus':11 'structur':55 'support':49 'time':37 'toler':41 'topic':67 'various':50 'version':13","created_at":"2026-03-29T06:03:59.020193+00:00","updated_at":"2026-04-15T23:23:59.310047+00:00","problems":{"verify_error":"error: Failed to parse: `azure-servicebus azure-identity aiohttp`\n  Caused by: Expected one of `@`, `(`, `<`, `=`, `>`, `~`, `!`, `;`, found `a`\nazure-servicebus azure-identity aiohttp\n                 ^"},"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"7.14.3","cli_name":"","cli_version":null,"type":"library","homepage":"https://azure.microsoft.com/products/service-bus","github":"https://github.com/Azure/azure-sdk-for-python.git","docs":null,"changelog":null,"pypi":"https://pypi.org/project/azure-servicebus/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["azure","communication"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"install_fail","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-05","install_tag":"verified"}}