Azure Servicebus TS
MicrosoftOfficialCreated by Microsoft
- Skill
- Tool integration
- Cloud and DevOps
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive guide to using the @azure/service-bus SDK for building messaging applications. It covers core operations including sending and receiving messages, managing queues and topics, handling message sessions, implementing dead-letter queues, and managing message lifecycles. The documentation includes best practices for authentication using Microsoft Entra, error handling strategies, and patterns for both pull-based and event-driven messaging architectures.
What it does
- Facilitates point-to-point messaging via queues and fan-out patterns via topics and subscriptions.
- Supports message batching for efficient throughput.
- Provides mechanisms for message settlement, including completion, abandonment, and deferral.
- Enables advanced messaging features like message sessions for ordered processing and scheduled delivery.
- Includes robust error handling patterns for transient and permanent service bus errors.
- Demonstrates secure authentication using Azure Identity credentials.
When to use it
- When building decoupled, event-driven microservices architectures.
- When implementing reliable background job processing or task distribution.
- When requiring ordered message processing using sessions.
- When needing to handle complex messaging scenarios like dead-lettering and message deferral.
- When integrating JavaScript or TypeScript applications with Azure messaging infrastructure.
Advantages
- Native support for TypeScript with strong typing for messaging operations.
- Built-in support for Azure-standard authentication and security practices.
- Comprehensive error handling guidance for production reliability.
- Flexible consumption models including both pull-based and push-based event-driven patterns.
- Efficient resource management through client reuse and batching.
Usage examples
- “How do I send a JSON message to an Azure Service Bus queue using TypeScript?”
- The agent provides a code snippet using ServiceBusClient and ServiceBusSender to send a message with a JSON body and appropriate content type.
- “Show me how to set up an event-driven subscriber for a Service Bus queue.”
- The agent demonstrates using the receiver.subscribe() method with processMessage and processError callbacks for handling incoming messages.
- “How should I handle a MessageLockLost error in my Service Bus application?”
- The agent explains that this is a non-retryable error indicating the lock expired, and provides a pattern for handling it within the error callback.
- “What is the best way to send multiple messages to a queue efficiently?”
- The agent provides a pattern using createMessageBatch() and tryAddMessage() to optimize message throughput.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/microsoft/azure-servicebus-ts/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip azure-servicebus-ts.zip -d .agents/skills
Documentation by Microsoft
Azure Service Bus SDK for TypeScript
Enterprise messaging with queues, topics, and subscriptions.
Installation
npm install @azure/service-bus @azure/identityEnvironment Variables
SERVICEBUS_NAMESPACE=<namespace>.servicebus.windows.net
SERVICEBUS_QUEUE_NAME=my-queue
SERVICEBUS_TOPIC_NAME=my-topic
SERVICEBUS_SUBSCRIPTION_NAME=my-subscription
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in productionAuthentication
import { ServiceBusClient } from "@azure/service-bus";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();
const fullyQualifiedNamespace = process.env.SERVICEBUS_NAMESPACE!;
const client = new ServiceBusClient(fullyQualifiedNamespace, credential);Core Workflow
Send Messages to Queue
const sender = client.createSender("my-queue");
// Single message
await sender.sendMessages({
body: { orderId: "12345", amount: 99.99 },
contentType: "application/json",
});
// Batch messages
const batch = await sender.createMessageBatch();
batch.tryAddMessage({ body: "Message 1" });
batch.tryAddMessage({ body: "Message 2" });
await sender.sendMessages(batch);
await sender.close();Receive Messages from Queue
const receiver = client.createReceiver("my-queue");
// Receive batch
const messages = await receiver.receiveMessages(10, { maxWaitTimeInMs: 5000 });
for (const message of messages) {
console.log(`Received: ${message.body}`);
await receiver.completeMessage(message);
}
await receiver.close();Subscribe to Messages (Event-Driven)
const receiver = client.createReceiver("my-queue");
const subscription = receiver.subscribe({
processMessage: async (message) => {
console.log(`Processing: ${message.body}`);
// Message auto-completed on success
},
processError: async (args) => {
console.error(`Error: ${args.error}`);
},
});
// Stop after some time
setTimeout(async () => {
await subscription.close();
await receiver.close();
}, 60000);Topics and Subscriptions
// Send to topic
const topicSender = client.createSender("my-topic");
await topicSender.sendMessages({
body: { event: "order.created", data: { orderId: "123" } },
applicationProperties: { eventType: "order.created" },
});
// Receive from subscription
const subscriptionReceiver = client.createReceiver("my-topic", "my-subscription");
const messages = await subscriptionReceiver.receiveMessages(10);Message Sessions
// Send session message
const sender = client.createSender("session-queue");
await sender.sendMessages({
body: { step: 1, data: "First step" },
sessionId: "workflow-123",
});
// Receive session messages
const sessionReceiver = await client.acceptSession("session-queue", "workflow-123");
const messages = await sessionReceiver.receiveMessages(10);
// Get/set session state
const state = await sessionReceiver.getSessionState();
await sessionReceiver.setSessionState(Buffer.from(JSON.stringify({ progress: 50 })));
await sessionReceiver.close();Dead-Letter Handling
// Move to dead-letter
await receiver.deadLetterMessage(message, {
deadLetterReason: "Validation failed",
deadLetterErrorDescription: "Missing required field: orderId",
});
// Process dead-letter queue
const dlqReceiver = client.createReceiver("my-queue", { subQueueType: "deadLetter" });
const dlqMessages = await dlqReceiver.receiveMessages(10);
for (const msg of dlqMessages) {
console.log(`DLQ Reason: ${msg.deadLetterReason}`);
// Reprocess or log
await dlqReceiver.completeMessage(msg);
}Scheduled Messages
const sender = client.createSender("my-queue");
// Schedule for future delivery
const scheduledTime = new Date(Date.now() + 60000); // 1 minute from now
const sequenceNumber = await sender.scheduleMessages(
{ body: "Delayed message" },
scheduledTime
);
// Cancel scheduled message
await sender.cancelScheduledMessages(sequenceNumber);Message Deferral
// Defer message for later
await receiver.deferMessage(message);
// Receive deferred message by sequence number
const deferredMessage = await receiver.receiveDeferredMessages(message.sequenceNumber!);
await receiver.completeMessage(deferredMessage[0]);Peek Messages (Non-Destructive)
const receiver = client.createReceiver("my-queue");
// Peek without removing
const peekedMessages = await receiver.peekMessages(10);
for (const msg of peekedMessages) {
console.log(`Peeked: ${msg.body}`);
}Key Types
import {
ServiceBusClient,
ServiceBusSender,
ServiceBusReceiver,
ServiceBusSessionReceiver,
ServiceBusMessage,
ServiceBusReceivedMessage,
ProcessMessageCallback,
ProcessErrorCallback,
} from "@azure/service-bus";Receive Modes
// Peek-Lock (default) - message locked until completed/abandoned
const receiver = client.createReceiver("my-queue", { receiveMode: "peekLock" });
await receiver.completeMessage(message); // Remove from queue
await receiver.abandonMessage(message); // Return to queue
await receiver.deferMessage(message); // Defer for later
await receiver.deadLetterMessage(message); // Move to DLQ
// Receive-and-Delete - message removed immediately
const receiver = client.createReceiver("my-queue", { receiveMode: "receiveAndDelete" });Best Practices
Use Microsoft Entra Token Credential - Use
DefaultAzureCredentialfor local development; useManagedIdentityCredentialorWorkloadIdentityCredentialfor productionReuse clients - Create
ServiceBusClientonce, share across senders/receiversClose resources - Always close senders/receivers when done
Handle errors - Implement
processErrorcallback for subscription receiversUse sessions for ordering - When message order matters within a group
Configure dead-letter - Always handle DLQ messages
Batch sends - Use
createMessageBatch()for multiple messages
Reference Documentation
For detailed patterns, see:
Queues vs Topics Patterns - Queue/topic patterns, sessions, receive modes, message settlement
Error Handling and Reliability - ServiceBusError codes, DLQ handling, lock renewal, graceful shutdown
Files
- ATTRIBUTION.mdAdded by AutoGineer976 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md7.1 KiB
- references/error-handling.md11.3 KiB
- references/queues-topics.md9.5 KiB
references/queues-topics.md
Queues vs Topics Patterns
Detailed patterns for Azure Service Bus queues and topics with @azure/service-bus.
Queue Patterns (Point-to-Point)
Queues deliver each message to exactly one consumer. Use for work distribution.
Basic Queue Sender
import { ServiceBusClient, ServiceBusMessage } from "@azure/service-bus";
import { DefaultAzureCredential } from "@azure/identity";
const client = new ServiceBusClient(
process.env.SERVICEBUS_NAMESPACE!,
new DefaultAzureCredential()
);
const sender = client.createSender("order-queue");
// Send single message
const message: ServiceBusMessage = {
body: { orderId: "12345", amount: 99.99 },
contentType: "application/json",
messageId: "unique-id-12345",
correlationId: "request-abc",
applicationProperties: {
priority: "high",
source: "web-app",
},
};
await sender.sendMessages(message);
await sender.close();Batch Sending (Recommended for Multiple Messages)
const sender = client.createSender("order-queue");
// Create batch with size limits
const batch = await sender.createMessageBatch();
const orders = [
{ orderId: "001", amount: 50 },
{ orderId: "002", amount: 75 },
{ orderId: "003", amount: 100 },
];
for (const order of orders) {
const added = batch.tryAddMessage({ body: order });
if (!added) {
// Batch is full - send current batch and create new one
await sender.sendMessages(batch);
const newBatch = await sender.createMessageBatch();
newBatch.tryAddMessage({ body: order });
}
}
// Send remaining messages
if (batch.count > 0) {
await sender.sendMessages(batch);
}
await sender.close();Queue Receiver (Pull Model)
const receiver = client.createReceiver("order-queue", {
receiveMode: "peekLock", // Default - message locked until settled
});
// Receive batch of messages
const messages = await receiver.receiveMessages(10, {
maxWaitTimeInMs: 5000,
});
for (const message of messages) {
try {
const order = message.body;
console.log(`Processing order: ${order.orderId}`);
// Process successfully - remove from queue
await receiver.completeMessage(message);
} catch (error) {
// Processing failed - return to queue for retry
await receiver.abandonMessage(message);
}
}
await receiver.close();Queue Subscriber (Push Model - Event-Driven)
const receiver = client.createReceiver("order-queue");
const subscription = receiver.subscribe({
processMessage: async (message) => {
console.log(`Received: ${JSON.stringify(message.body)}`);
// Message auto-completed on success when using subscribe()
},
processError: async (args) => {
console.error(`Error source: ${args.errorSource}`);
console.error(`Error: ${args.error.message}`);
if (args.error.code === "MessageLockLost") {
console.log("Message lock expired - will be redelivered");
}
},
}, {
autoCompleteMessages: true, // Default
maxConcurrentCalls: 5,
});
// Graceful shutdown
process.on("SIGTERM", async () => {
await subscription.close();
await receiver.close();
await client.close();
});Topic Patterns (Publish-Subscribe)
Topics deliver messages to multiple subscriptions. Use for fan-out scenarios.
Topic Publisher
// Sending to a topic is identical to sending to a queue
const sender = client.createSender("order-events");
await sender.sendMessages({
body: { event: "order.created", orderId: "12345" },
applicationProperties: {
eventType: "order.created",
region: "us-west",
},
subject: "orders/created", // Can be used for filtering
});
await sender.close();Subscription Receiver
// Receive from a specific subscription
const receiver = client.createReceiver(
"order-events", // Topic name
"billing-service" // Subscription name
);
const messages = await receiver.receiveMessages(10);
for (const message of messages) {
console.log(`Billing received: ${message.body.event}`);
await receiver.completeMessage(message);
}Multiple Subscriptions (Fan-Out)
// Each subscription gets a copy of every message
// Create receivers for different services
const billingReceiver = client.createReceiver("order-events", "billing");
const inventoryReceiver = client.createReceiver("order-events", "inventory");
const notificationReceiver = client.createReceiver("order-events", "notifications");
// Each processes independently
billingReceiver.subscribe({
processMessage: async (msg) => {
await processBilling(msg.body);
},
processError: async (args) => console.error(args.error),
});
inventoryReceiver.subscribe({
processMessage: async (msg) => {
await updateInventory(msg.body);
},
processError: async (args) => console.error(args.error),
});Session-Enabled Queues (Ordered Processing)
Sessions guarantee FIFO ordering within a session and enable stateful processing.
Send Session Messages
const sender = client.createSender("workflow-queue");
// All messages with same sessionId processed in order by same receiver
await sender.sendMessages([
{ body: { step: 1, action: "validate" }, sessionId: "order-123" },
{ body: { step: 2, action: "charge" }, sessionId: "order-123" },
{ body: { step: 3, action: "fulfill" }, sessionId: "order-123" },
]);Accept Specific Session
// Lock a specific session
const sessionReceiver = await client.acceptSession(
"workflow-queue",
"order-123"
);
// Process all messages for this session in order
const messages = await sessionReceiver.receiveMessages(10);
for (const message of messages) {
console.log(`Step ${message.body.step}: ${message.body.action}`);
await sessionReceiver.completeMessage(message);
}
await sessionReceiver.close();Accept Next Available Session
// Accept any available session (load balancing)
const sessionReceiver = await client.acceptNextSession("workflow-queue", {
maxAutoLockRenewalDurationInMs: 300000, // 5 minutes
});
console.log(`Processing session: ${sessionReceiver.sessionId}`);
// Get/set session state for checkpointing
const state = await sessionReceiver.getSessionState();
if (state) {
const checkpoint = JSON.parse(state.toString());
console.log(`Resuming from step: ${checkpoint.lastStep}`);
}
// Process messages...
// Save checkpoint
await sessionReceiver.setSessionState(
Buffer.from(JSON.stringify({ lastStep: 3, status: "complete" }))
);
await sessionReceiver.close();Receive Modes
Peek-Lock (Default - At-Least-Once)
const receiver = client.createReceiver("my-queue", {
receiveMode: "peekLock",
});
const [message] = await receiver.receiveMessages(1);
// Message is locked - other receivers can't see it
// You MUST settle the message:
await receiver.completeMessage(message); // Success - remove from queue
await receiver.abandonMessage(message); // Failure - return to queue
await receiver.deferMessage(message); // Defer - retrieve by sequence number
await receiver.deadLetterMessage(message); // Move to DLQReceive-and-Delete (At-Most-Once)
const receiver = client.createReceiver("my-queue", {
receiveMode: "receiveAndDelete",
});
const [message] = await receiver.receiveMessages(1);
// Message is immediately deleted - no settlement needed
// If processing fails, message is lost
console.log(`Received and deleted: ${message.body}`);Message Settlement Actions
const receiver = client.createReceiver("my-queue");
const [message] = await receiver.receiveMessages(1);
// COMPLETE: Processing succeeded, remove message
await receiver.completeMessage(message);
// ABANDON: Processing failed, return to queue for retry
// Increments deliveryCount
await receiver.abandonMessage(message, {
propertiesToModify: { retryReason: "timeout" },
});
// DEFER: Can't process now, retrieve later by sequence number
await receiver.deferMessage(message);
// Later: await receiver.receiveDeferredMessages([message.sequenceNumber!]);
// DEAD LETTER: Poison message, move to DLQ
await receiver.deadLetterMessage(message, {
deadLetterReason: "ValidationFailed",
deadLetterErrorDescription: "Missing required field: customerId",
});Scheduled Messages
const sender = client.createSender("my-queue");
// Schedule for future delivery
const scheduledTime = new Date(Date.now() + 60 * 60 * 1000); // 1 hour from now
const sequenceNumbers = await sender.scheduleMessages(
[
{ body: "Reminder: Complete your order" },
{ body: "Your cart is waiting" },
],
scheduledTime
);
console.log(`Scheduled messages: ${sequenceNumbers}`);
// Cancel scheduled messages if needed
await sender.cancelScheduledMessages(sequenceNumbers);Peek Messages (Non-Destructive)
const receiver = client.createReceiver("my-queue");
// Peek without removing or locking
const peekedMessages = await receiver.peekMessages(10);
for (const msg of peekedMessages) {
console.log(`Peeked: ${msg.body}`);
console.log(`Sequence: ${msg.sequenceNumber}`);
console.log(`Enqueued: ${msg.enqueuedTimeUtc}`);
}
// Peek from specific sequence number
const moreMessages = await receiver.peekMessages(10, {
fromSequenceNumber: 100n,
});When to Use Queues vs Topics
| Scenario | Use |
|---|---|
| Work distribution (one consumer per message) | Queue |
| Fan-out (multiple consumers per message) | Topic |
| Competing consumers (load balancing) | Queue |
| Event broadcasting | Topic |
| Request-reply pattern | Queue with reply-to |
| Ordered processing | Session-enabled Queue |
| Filtered delivery | Topic with subscription filters |
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 Node.js
Security
No issues found by our static scan· No issues found
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-typescript/skills/azure-servicebus-ts · 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-ts.zip