Registry / azure / azure-servicebus

azure-servicebus

JSON →
library7.14.3pypypiunverified

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.

azurecommunication
pip install azure-servicebus azure-identity aiohttp
Install & Compatibility
Where this runs
tested against v7.14.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.925 runs
installs and imports cleanly · install 0.0s · import 1.120s · 54.1MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 6.1s · import 1.004s · 56MB
55MB installed
● package 55MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ServiceBusClient
from azure.servicebus import ServiceBusClient
ServiceBusMessage
from azure.servicebus import ServiceBusMessage
ServiceBusReceivedMessage
from azure.servicebus import ServiceBusReceivedMessage
DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Used for Azure AD authentication, often preferred over connection strings in production.

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.

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()
Debug
Known issues
breakingMajor 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.
affects: < 7.0.0
gotchaMessage 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.
affects: 7.x
gotchaCreating 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).
affects: 7.x
gotchaAzure 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.
affects: 7.x
gotchaErrors 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.
affects: 7.x
gotchaA `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.
affects: 7.x
gotchaThe `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.
affects: 7.x
Upgrade
Version history
7.14.3latest on PyPI
Audit
Dependencies
azure-identityrequiredRecommended for passwordless authentication using Azure Active Directory, especially in production environments.
aiohttpoptionalRequired for using the asynchronous (async) API functionality of azure-servicebus.
Agent activity
99 hits · last 30 days
node
16
mj12bot
3
seranking-bot
3
ahrefsbot
2
Amazon
1
amazonbot
1
bytedance
1
Resources