Azure Servicebus Py
MicrosoftOfficialCreated by Microsoft
- Skill
- Tool integration
- Automation and integrations
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The azure-servicebus-py skill provides the Python SDK for interacting with Azure Service Bus. It enables developers to implement enterprise messaging patterns, including message queuing, publish-subscribe topics, and session-based ordered processing. The skill emphasizes secure authentication via DefaultAzureCredential and provides patterns for message settlement, dead-letter queue management, and high-throughput batch operations.
What it does
- Connects to Azure Service Bus namespaces for messaging operations.
- Supports sending and receiving messages via queues and topics.
- Implements message settlement actions like complete, abandon, and dead-letter.
- Provides support for FIFO message ordering using sessions.
- Enables scheduling of messages for future delivery.
- Facilitates batch message processing for improved throughput.
When to use it
- When building cloud-native applications requiring reliable asynchronous communication.
- When implementing pub/sub architectures using Azure Service Bus topics.
- When needing to handle poison messages via dead-letter queues.
- When requiring ordered processing of related messages using sessions.
- When integrating Python applications with Azure messaging infrastructure.
Advantages
- Native support for Azure identity-based authentication.
- Provides both synchronous and asynchronous client implementations.
- Includes built-in support for message batching and session management.
- Offers granular control over message settlement and retry logic.
Usage examples
- “How do I send a batch of messages to an Azure Service Bus queue?”
- The agent provides a code snippet using ServiceBusClient and ServiceBusSender to create and send a batch of messages, including logic for handling batch size limits.
- “Show me how to process messages from a dead-letter queue.”
- The agent provides an example using ServiceBusSubQueue.DEAD_LETTER to initialize a receiver and iterate through messages, including accessing dead-letter reasons.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/microsoft/azure-servicebus-py/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip azure-servicebus-py.zip -d .agents/skills
Documentation by Microsoft
Azure Service Bus SDK for Python
Enterprise messaging for reliable cloud communication with queues and pub/sub topics.
Installation
pip install azure-servicebus azure-identityEnvironment Variables
SERVICEBUS_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net # Required for all auth methods
SERVICEBUS_QUEUE_NAME=myqueue # Required for queue operations
SERVICEBUS_TOPIC_NAME=mytopic # Required for topic operations
SERVICEBUS_SUBSCRIPTION_NAME=mysubscription # Required for subscription operations
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in productionAuthentication & Lifecycle
🔑 Two rules apply to every code sample below:
Prefer
DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
Local dev:
DefaultAzureCredentialworks as-is.Production: set
AZURE_TOKEN_CREDENTIALS=prod(orAZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
Sync:
with <Client>(...) as client:Async:
async with <Client>(...) as client:andasync with DefaultAzureCredential() as credential:(fromazure.identity.aio)Snippets may abbreviate this setup, but production code should always follow both rules.
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.servicebus import ServiceBusClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
namespace = "<namespace>.servicebus.windows.net"
with ServiceBusClient(
fully_qualified_namespace=namespace,
credential=credential
) as client:
# Use client here (see following sections for operations)
...Client Types
| Client | Purpose | Get From |
|---|---|---|
ServiceBusClient | Connection management | Direct instantiation |
ServiceBusSender | Send messages | client.get_queue_sender() / get_topic_sender() |
ServiceBusReceiver | Receive messages | client.get_queue_receiver() / get_subscription_receiver() |
Send Messages (Async)
import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
from azure.identity.aio import DefaultAzureCredential
async def send_messages():
credential = DefaultAzureCredential()
async with ServiceBusClient(
fully_qualified_namespace="<namespace>.servicebus.windows.net",
credential=credential
) as client:
sender = client.get_queue_sender(queue_name="myqueue")
async with sender:
# Single message
message = ServiceBusMessage("Hello, Service Bus!")
await sender.send_messages(message)
# Batch of messages
messages = [ServiceBusMessage(f"Message {i}") for i in range(10)]
await sender.send_messages(messages)
# Message batch (for size control)
batch = await sender.create_message_batch()
for i in range(100):
try:
batch.add_message(ServiceBusMessage(f"Batch message {i}"))
except ValueError: # Batch full
await sender.send_messages(batch)
batch = await sender.create_message_batch()
batch.add_message(ServiceBusMessage(f"Batch message {i}"))
await sender.send_messages(batch)
asyncio.run(send_messages())Receive Messages (Async)
async def receive_messages():
credential = DefaultAzureCredential()
async with ServiceBusClient(
fully_qualified_namespace="<namespace>.servicebus.windows.net",
credential=credential
) as client:
receiver = client.get_queue_receiver(queue_name="myqueue")
async with receiver:
# Receive batch
messages = await receiver.receive_messages(
max_message_count=10,
max_wait_time=5 # seconds
)
for msg in messages:
print(f"Received: {str(msg)}")
await receiver.complete_message(msg) # Remove from queue
asyncio.run(receive_messages())Receive Modes
| Mode | Behavior | Use Case |
|---|---|---|
PEEK_LOCK (default) | Message locked, must complete/abandon | Reliable processing |
RECEIVE_AND_DELETE | Removed immediately on receive | At-most-once delivery |
from azure.servicebus import ServiceBusReceiveMode
receiver = client.get_queue_receiver(
queue_name="myqueue",
receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE
)Message Settlement
async with receiver:
messages = await receiver.receive_messages(max_message_count=1)
for msg in messages:
try:
# Process message...
await receiver.complete_message(msg) # Success - remove from queue
except ProcessingError:
await receiver.abandon_message(msg) # Retry later
except PermanentError:
await receiver.dead_letter_message(
msg,
reason="ProcessingFailed",
error_description="Could not process"
)| Action | Effect |
|---|---|
complete_message() | Remove from queue (success) |
abandon_message() | Release lock, retry immediately |
dead_letter_message() | Move to dead-letter queue |
defer_message() | Set aside, receive by sequence number |
Topics and Subscriptions
# Send to topic
sender = client.get_topic_sender(topic_name="mytopic")
async with sender:
await sender.send_messages(ServiceBusMessage("Topic message"))
# Receive from subscription
receiver = client.get_subscription_receiver(
topic_name="mytopic",
subscription_name="mysubscription"
)
async with receiver:
messages = await receiver.receive_messages(max_message_count=10)Sessions (FIFO)
# Send with session
message = ServiceBusMessage("Session message")
message.session_id = "order-123"
await sender.send_messages(message)
# Receive from specific session
receiver = client.get_queue_receiver(
queue_name="session-queue",
session_id="order-123"
)
# Receive from next available session
from azure.servicebus import NEXT_AVAILABLE_SESSION
receiver = client.get_queue_receiver(
queue_name="session-queue",
session_id=NEXT_AVAILABLE_SESSION
)Scheduled Messages
from datetime import datetime, timedelta, timezone
message = ServiceBusMessage("Scheduled message")
scheduled_time = datetime.now(timezone.utc) + timedelta(minutes=10)
# Schedule message
sequence_number = await sender.schedule_messages(message, scheduled_time)
# Cancel scheduled message
await sender.cancel_scheduled_messages(sequence_number)Dead-Letter Queue
from azure.servicebus import ServiceBusSubQueue
# Receive from dead-letter queue
dlq_receiver = client.get_queue_receiver(
queue_name="myqueue",
sub_queue=ServiceBusSubQueue.DEAD_LETTER
)
async with dlq_receiver:
messages = await dlq_receiver.receive_messages(max_message_count=10)
for msg in messages:
print(f"Dead-lettered: {msg.dead_letter_reason}")
await dlq_receiver.complete_message(msg)Sync Client (for simple scripts)
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential
with ServiceBusClient(
fully_qualified_namespace="<namespace>.servicebus.windows.net",
credential=DefaultAzureCredential()
) as client:
with client.get_queue_sender("myqueue") as sender:
sender.send_messages(ServiceBusMessage("Sync message"))
with client.get_queue_receiver("myqueue") as receiver:
for msg in receiver:
print(str(msg))
receiver.complete_message(msg)Best Practices
Pick sync OR async and stay consistent. Do not mix
azure.xxxsync clients withazure.xxx.aioasync clients in the same call path. Choose one mode per module.Always use context managers for clients and async credentials. Wrap every client in
with Client(...) as client:(sync) orasync with Client(...) as client:(async) for proper cleanup. For asyncDefaultAzureCredentialfromazure.identity.aio, also useasync with credential:so tokens and transports are cleaned up.Use
DefaultAzureCredentialfor portable auth across local dev and Azure (avoid connection strings / API keys when possible).Use async client for production workloads
Complete messages after successful processing
Use dead-letter queue for poison messages
Use sessions for ordered, FIFO processing
Use message batches for high-throughput scenarios
Set
max_wait_timeto avoid infinite blocking
Reference Files
| File | Contents |
|---|---|
| references/patterns.md | Competing consumers, sessions, retry patterns, request-response, transactions |
| references/dead-letter.md | DLQ handling, poison messages, reprocessing strategies |
| scripts/setup_servicebus.py | CLI for queue/topic/subscription management and DLQ monitoring |
Files
- ATTRIBUTION.mdAdded by AutoGineer968 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md10.1 KiB
- references/dead-letter.md13.8 KiB
- references/patterns.md13.6 KiB
- scripts/setup_servicebus.pyScript13.0 KiB
references/patterns.md
Messaging Patterns Reference
Advanced messaging patterns for Azure Service Bus.
Competing Consumers
Multiple receivers processing messages from the same queue in parallel:
import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.identity.aio import DefaultAzureCredential
async def worker(worker_id: int, namespace: str, queue_name: str):
"""Worker that processes messages from a shared queue."""
credential = DefaultAzureCredential()
async with ServiceBusClient(
fully_qualified_namespace=namespace,
credential=credential
) as client:
receiver = client.get_queue_receiver(queue_name=queue_name)
async with receiver:
while True:
messages = await receiver.receive_messages(
max_message_count=10,
max_wait_time=5
)
if not messages:
continue
for msg in messages:
try:
print(f"Worker {worker_id}: Processing {str(msg)}")
await process_message(msg)
await receiver.complete_message(msg)
except Exception as e:
print(f"Worker {worker_id}: Error - {e}")
await receiver.abandon_message(msg)
async def run_workers(num_workers: int, namespace: str, queue_name: str):
"""Run multiple workers concurrently."""
workers = [
worker(i, namespace, queue_name)
for i in range(num_workers)
]
await asyncio.gather(*workers)
# Run 5 competing consumers
asyncio.run(run_workers(5, "myns.servicebus.windows.net", "work-queue"))Message Sessions (Ordered Processing)
Sessions ensure FIFO ordering for related messages:
from azure.servicebus import ServiceBusMessage, NEXT_AVAILABLE_SESSION
from azure.servicebus.aio import ServiceBusClient
async def send_order_messages(sender, order_id: str, items: list[str]):
"""Send order items as session messages (processed in order)."""
for i, item in enumerate(items):
message = ServiceBusMessage(
body=item,
session_id=order_id,
message_id=f"{order_id}-{i}"
)
# Messages with same session_id processed in send order
await sender.send_messages(message)
async def process_order_session(client, queue_name: str):
"""Process one session's messages in order."""
# Get next available session
receiver = client.get_queue_receiver(
queue_name=queue_name,
session_id=NEXT_AVAILABLE_SESSION,
max_wait_time=30
)
async with receiver:
session = receiver.session
print(f"Processing session: {session.session_id}")
# Set session state (for checkpointing)
await session.set_state(b"processing")
async for msg in receiver:
print(f" Item: {str(msg)}")
await receiver.complete_message(msg)
# Mark session complete
await session.set_state(b"completed")
print(f"Session {session.session_id} completed")
async def session_worker(client, queue_name: str):
"""Continuously process sessions."""
while True:
try:
await process_order_session(client, queue_name)
except Exception as e:
if "No session available" in str(e):
await asyncio.sleep(1) # Wait for new sessions
else:
raiseRetry Patterns
Automatic Retry with Max Delivery Count
Service Bus automatically retries abandoned messages up to maxDeliveryCount:
async def process_with_retry_tracking(receiver, msg):
"""Process message with delivery count awareness."""
delivery_count = msg.delivery_count
max_retries = 5 # Should match queue's maxDeliveryCount
print(f"Processing message (attempt {delivery_count}/{max_retries})")
try:
await process_message(msg)
await receiver.complete_message(msg)
except TransientError:
if delivery_count >= max_retries - 1:
# Last retry - dead-letter with context
await receiver.dead_letter_message(
msg,
reason="MaxRetriesExceeded",
error_description=f"Failed after {delivery_count} attempts"
)
else:
# Abandon for automatic retry
await receiver.abandon_message(msg)
except PermanentError as e:
# Immediate dead-letter for non-retryable errors
await receiver.dead_letter_message(
msg,
reason="PermanentFailure",
error_description=str(e)
)Exponential Backoff with Scheduled Retry
from datetime import datetime, timedelta, timezone
async def process_with_backoff(client, receiver, msg):
"""Retry with exponential backoff using scheduled messages."""
retry_count = int(msg.application_properties.get("retry_count", 0))
max_retries = 5
try:
await process_message(msg)
await receiver.complete_message(msg)
except TransientError:
if retry_count >= max_retries:
await receiver.dead_letter_message(
msg,
reason="MaxRetriesExceeded",
error_description=f"Failed after {retry_count} retries"
)
return
# Calculate backoff: 2^retry seconds (1, 2, 4, 8, 16 seconds)
backoff_seconds = 2 ** retry_count
retry_time = datetime.now(timezone.utc) + timedelta(seconds=backoff_seconds)
# Create retry message with incremented count
retry_message = ServiceBusMessage(
body=msg.body,
application_properties={
**dict(msg.application_properties or {}),
"retry_count": retry_count + 1,
"original_enqueue_time": str(msg.enqueued_time_utc)
}
)
# Complete original and schedule retry
await receiver.complete_message(msg)
sender = client.get_queue_sender(queue_name=receiver.entity_path)
async with sender:
await sender.schedule_messages(retry_message, retry_time)
print(f"Scheduled retry {retry_count + 1} for {retry_time}")Request-Response Pattern
Using reply queues for synchronous-style communication:
import uuid
from asyncio import Event, wait_for
class RequestResponseClient:
"""Send requests and wait for correlated responses."""
def __init__(self, client, request_queue: str, response_queue: str):
self.client = client
self.request_queue = request_queue
self.response_queue = response_queue
self.pending_requests: dict[str, tuple[Event, dict]] = {}
async def start_response_listener(self):
"""Background task to receive responses."""
receiver = self.client.get_queue_receiver(
queue_name=self.response_queue
)
async with receiver:
async for msg in receiver:
correlation_id = msg.correlation_id
if correlation_id in self.pending_requests:
event, result = self.pending_requests[correlation_id]
result["response"] = msg.body
event.set()
await receiver.complete_message(msg)
async def send_request(self, body: str, timeout: float = 30.0) -> bytes:
"""Send request and wait for response."""
message_id = str(uuid.uuid4())
event = Event()
result = {}
self.pending_requests[message_id] = (event, result)
try:
# Send request with reply-to
message = ServiceBusMessage(
body=body,
message_id=message_id,
reply_to=self.response_queue
)
sender = self.client.get_queue_sender(self.request_queue)
async with sender:
await sender.send_messages(message)
# Wait for response
await wait_for(event.wait(), timeout=timeout)
return result["response"]
finally:
del self.pending_requests[message_id]
# Request processor (server side)
async def process_requests(client, request_queue: str):
"""Process requests and send responses."""
receiver = client.get_queue_receiver(queue_name=request_queue)
async with receiver:
async for msg in receiver:
# Process request
response_body = f"Processed: {str(msg.body)}"
# Send response to reply_to queue
if msg.reply_to:
response = ServiceBusMessage(
body=response_body,
correlation_id=msg.message_id
)
sender = client.get_queue_sender(queue_name=msg.reply_to)
async with sender:
await sender.send_messages(response)
await receiver.complete_message(msg)Pub/Sub with Filters
Topics with filtered subscriptions:
# Publisher sends messages with properties
async def publish_events(sender, events: list[dict]):
"""Publish events with filterable properties."""
for event in events:
message = ServiceBusMessage(
body=json.dumps(event["data"]),
application_properties={
"event_type": event["type"],
"priority": event["priority"],
"region": event["region"]
}
)
await sender.send_messages(message)
# Subscribers receive filtered messages
# (Filters configured via Azure Portal or Management SDK)
#
# Subscription "high-priority": SqlFilter("priority = 'high'")
# Subscription "us-region": SqlFilter("region = 'us'")
# Subscription "orders": CorrelationFilter(label='order')
async def subscribe_high_priority(client, topic: str):
"""Receive only high-priority messages."""
receiver = client.get_subscription_receiver(
topic_name=topic,
subscription_name="high-priority"
)
async with receiver:
async for msg in receiver:
print(f"High priority: {str(msg)}")
await receiver.complete_message(msg)Transaction Support
Atomic operations within a single entity:
from azure.servicebus import ServiceBusMessage
async def transactional_receive_and_forward(client, source_queue: str, dest_queue: str):
"""Receive from one queue and send to another atomically."""
receiver = client.get_queue_receiver(queue_name=source_queue)
sender = client.get_queue_sender(queue_name=dest_queue)
async with receiver, sender:
messages = await receiver.receive_messages(max_message_count=1)
if messages:
msg = messages[0]
# Start transaction
async with receiver.transaction_scope() as txn:
# Transform message
new_msg = ServiceBusMessage(
body=f"Forwarded: {str(msg.body)}",
application_properties={"original_id": msg.message_id}
)
# Both operations in same transaction
await sender.send_messages(new_msg, transaction=txn)
await receiver.complete_message(msg, transaction=txn)
# Transaction commits when context exits without errorBatch Processing with Prefetch
Optimize throughput with prefetching:
async def batch_processor(client, queue_name: str, batch_size: int = 100):
"""Process messages in batches with prefetch."""
receiver = client.get_queue_receiver(
queue_name=queue_name,
prefetch_count=batch_size * 2 # Prefetch 2x batch size
)
async with receiver:
while True:
messages = await receiver.receive_messages(
max_message_count=batch_size,
max_wait_time=5
)
if not messages:
continue
# Process batch
results = await process_batch([str(m.body) for m in messages])
# Complete successful, abandon failed
for msg, success in zip(messages, results):
if success:
await receiver.complete_message(msg)
else:
await receiver.abandon_message(msg)Message Properties Reference
| Property | Type | Description |
|---|---|---|
message_id | str | Unique message identifier |
session_id | str | Session identifier for FIFO |
correlation_id | str | For request-response correlation |
reply_to | str | Queue for responses |
reply_to_session_id | str | Session ID for responses |
subject | str | Message label/type |
to | str | Destination hint |
content_type | str | MIME type (e.g., "application/json") |
time_to_live | timedelta | Message expiration |
scheduled_enqueue_time_utc | datetime | Scheduled delivery time |
application_properties | dict | Custom key-value pairs |
Best Practices Summary
| Pattern | When to Use |
|---|---|
| Competing Consumers | Scale message processing horizontally |
| Sessions | Ordered processing for related messages |
| Scheduled Messages | Delayed delivery, exponential backoff |
| Request-Response | Synchronous-style communication |
| Topics/Filters | Pub/sub with selective routing |
| Transactions | Atomic multi-operation guarantees |
| Prefetch | High-throughput batch processing |
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an API key, Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Microsoft
- Publisher
- Microsoft (Official)
- Source
- microsoft/skills · .github/plugins/azure-sdk-python/skills/azure-servicebus-py · commit 0696600
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Microsoft.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download azure-servicebus-py.zip