Azure Service Bus Client Library for Python
raw JSON → 7.14.3 verified Tue May 12 auth: no python install: verified
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.
pip install azure-servicebus azure-identity aiohttp Common errors
error ModuleNotFoundError: No module named 'azure.servicebus' ↓
cause This error typically occurs when the `azure-servicebus` package is not installed in the current Python environment, or there's a conflict with a local module named `azure`.
fix
Ensure the package is correctly installed:
pip install azure-servicebus. If a local azure.py file or directory exists, rename it to avoid conflicts. error ImportError: cannot import name 'ServiceBusClient' from partially initialized module 'azure.servicebus' ↓
cause This usually indicates a circular import where your own Python file or module has a name that conflicts with an `azure.servicebus` submodule (e.g., `azure.py`, `servicebus.py`, or `ServiceBusClient.py`), or a version incompatibility.
fix
Rename any local files or modules that might conflict with
azure or azure.servicebus components. If the issue persists, try installing a specific, potentially older, version of the library (e.g., pip install azure-servicebus==7.0.0) to check for version incompatibilities. error ServiceBusAuthenticationError: CBS Authentication Expired ↓
cause This error, along with `UnauthorizedAccessException`, means the credentials used to connect to Azure Service Bus are invalid, expired, or lack the necessary permissions. Common causes include incorrect connection strings, expired Shared Access Signature (SAS) tokens, or insufficient RBAC roles.
fix
Verify that your connection string is correct and has the required 'Send' and/or 'Listen' permissions. Ensure SAS tokens, if used, are not expired. Check Azure portal for the correct connection string under 'Shared access policies' for your Service Bus namespace or queue/topic.
error MessageLockLostError: The lock on the message is lost. ↓
cause This exception occurs when the lock on a received message expires before the message can be processed and settled (completed, abandoned, dead-lettered, or deferred). This can happen if message processing takes too long, or due to network issues.
fix
Increase the message lock duration for your queue or subscription in the Azure portal to allow more time for processing. Alternatively, use
AutoLockRenewer to automatically extend the message lock while the message is being processed. error AttributeError: 'NoneType' object has no attribute 'decode' ↓
cause This error typically occurs when attempting to call `.decode()` on a message body that is `None`, or when `msg.body` returns a generator object that has been exhausted or is not handled correctly before decoding.
fix
Before decoding, explicitly check if the message body is not
None and ensure you are correctly extracting the payload from ServiceBusReceivedMessage.body. For instance, iterate over the body correctly if it's a generator, or access the byte content directly if available: if msg.body: message_content = next(msg.body).decode('utf-8'). Warnings
breaking 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. ↓
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.
gotcha 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. ↓
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.
gotcha 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. ↓
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).
gotcha 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. ↓
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.
gotcha 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. ↓
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.
gotcha 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. ↓
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.
gotcha 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. ↓
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.
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 1.03s 54.0M
3.10 alpine (musl) - - 1.03s 53.2M
3.10 slim (glibc) wheel 7.0s 0.74s 56M
3.10 slim (glibc) - - 0.74s 55M
3.11 alpine (musl) wheel - 1.23s 58.7M
3.11 alpine (musl) - - 1.30s 57.9M
3.11 slim (glibc) wheel 5.9s 1.07s 61M
3.11 slim (glibc) - - 1.03s 60M
3.12 alpine (musl) wheel - 1.14s 50.2M
3.12 alpine (musl) - - 1.17s 49.4M
3.12 slim (glibc) wheel 4.6s 1.15s 52M
3.12 slim (glibc) - - 1.26s 52M
3.13 alpine (musl) wheel - 1.12s 49.9M
3.13 alpine (musl) - - 1.13s 49.0M
3.13 slim (glibc) wheel 5.2s 1.12s 52M
3.13 slim (glibc) - - 1.17s 51M
3.9 alpine (musl) wheel - 1.02s 54.9M
3.9 alpine (musl) - - 0.97s 53.9M
3.9 slim (glibc) wheel 8.0s 0.93s 57M
3.9 slim (glibc) - - 0.81s 56M
Imports
- ServiceBusClient
from azure.servicebus import ServiceBusClient - ServiceBusMessage
from azure.servicebus import ServiceBusMessage - ServiceBusReceivedMessage
from azure.servicebus import ServiceBusReceivedMessage - DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart last tested: 2026-04-24
import os
from azure.servicebus import ServiceBusClient, ServiceBusMessage
# Retrieve connection string from environment variable
CONNECTION_STR = os.environ.get('AZURE_SERVICEBUS_CONNECTION_STRING', 'Endpoint=sb://<YOUR_NAMESPACE>.servicebus.windows.net/;SharedAccessKeyName=<KEY_NAME>;SharedAccessKey=<KEY_VALUE>')
QUEUE_NAME = os.environ.get('AZURE_SERVICEBUS_QUEUE_NAME', 'myqueue')
def send_single_message():
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)
with servicebus_client: # automatically closes client on exit
sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
with sender: # automatically closes sender on exit
message = ServiceBusMessage("Hello, Service Bus!")
sender.send_messages(message)
print(f"Sent a single message to queue: {QUEUE_NAME}")
def receive_single_message():
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)
with servicebus_client:
receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5) # max_wait_time in seconds
with receiver:
received_messages = receiver.receive_messages(max_messages=1)
for msg in received_messages:
print(f"Received message: {msg.body}")
# Complete the message to remove it from the queue
receiver.complete_message(msg)
print("Message completed.")
if not received_messages:
print(f"No messages received from queue: {QUEUE_NAME}")
if __name__ == '__main__':
# Ensure AZURE_SERVICEBUS_CONNECTION_STRING and AZURE_SERVICEBUS_QUEUE_NAME are set as environment variables
# or replace placeholder values in the CONNECTION_STR and QUEUE_NAME variables.
print("Sending message...")
send_single_message()
print("Receiving message...")
receive_single_message()