Skip to content
Learni
View all tutorials
Cloud

How to Use Azure Service Bus for Messaging in 2026

Lire en français

Introduction

Azure Service Bus is a Microsoft cloud messaging service designed for reliable asynchronous communication between applications. Unlike simple queues like those in RabbitMQ, it offers advanced features such as sessions, dead-letter queues, transactions, and automatic scaling. In 2026, with the rise of microservices and event-driven architectures, mastering Service Bus is essential to avoid tight coupling and handle traffic spikes.

This beginner tutorial guides you step by step to create a namespace, a queue, and implement sending/receiving messages using the Node.js SDK. Imagine an e-commerce app: orders are sent to a Service Bus queue and processed by an independent worker, preventing bottlenecks. By the end, you'll have a production-ready setup. Estimated time: 30 minutes. Prepare your free Azure account.

Prerequisites

  • Free Azure account (create one at portal.azure.com)
  • Azure CLI installed (download via winget install -e --id Microsoft.AzureCLI on Windows or docs)
  • Node.js 20+ and npm
  • Editor like VS Code
  • Active Azure subscription (the free one works for this tutorial)

Connect to Azure and create the namespace

terminal
az login
az account set --subscription "Votre Subscription ID" # Remplacez par votre ID de souscription
az group create --name rg-servicebus-tutorial --location "East US"
az servicebus namespace create --resource-group rg-servicebus-tutorial --name monnamespaceunique2026 --location "East US" --sku Standard
az servicebus namespace authorization-rule create --resource-group rg-servicebus-tutorial --namespace-name monnamespaceunique2026 --name RootManageSharedAccessKey

This script connects you to Azure, creates a resource group, and a Standard Service Bus namespace (which supports topics/sessions). Replace 'monnamespaceunique2026' with a globally unique name (add numbers). The 'RootManageSharedAccessKey' authorization rule generates the primary connection string. Check for uniqueness with az servicebus namespace list to avoid duplication errors.

Retrieve the connection string and create the queue

terminal
CONNECTION_STRING=$(az servicebus namespace authorization-rule keys list --resource-group rg-servicebus-tutorial --namespace-name monnamespaceunique2026 --name RootManageSharedAccessKey --query primaryConnectionString -o tsv)
echo "Connection String: $CONNECTION_STRING" > .env
az servicebus queue create --resource-group rg-servicebus-tutorial --namespace-name monnamespaceunique2026 --name ma-queue-tutorial --enable-session false --max-size-in-mb 1024

Here, we extract the primary connection string and store it in .env for security (never commit in production). The 'ma-queue-tutorial' queue is created with 1 GB max size and no sessions for this beginner tutorial. Use enable-session true later to order messages by session ID. Copy the string for the following code examples.

Initialize the Node.js project and install the SDK

terminal
mkdir servicebus-tutorial && cd servicebus-tutorial
npm init -y
npm install @azure/service-bus @azure/identity dotenv
touch send.ts receive.ts .env
tsc --init # Configure TypeScript si désiré, ou utilisez ts-node

We create a Node.js project, install the official Azure Service Bus SDK (v7+ in 2026), dotenv to load .env, and identity for advanced auth. The send.ts/receive.ts files will be our main scripts. Run with npx ts-node send.ts after coding. Avoid old SDK versions that lack async/await support.

Complete script to send messages

send.ts
import { ServiceBusClient } from "@azure/service-bus";
import * as dotenv from "dotenv";
dotenv.config();

const connectionString = process.env.CONNECTION_STRING!;
const queueName = "ma-queue-tutorial";

async function sendMessages() {
  const sbClient = new ServiceBusClient(connectionString);
  const sender = sbClient.createSender(queueName);

  try {
    // Envoi d'un message simple
    await sender.sendMessages({ body: "Bonjour Azure Service Bus !" });
    console.log("Message envoyé.");

    // Envoi de 3 messages avec propriétés
    const messages = [
      { body: "Message 1", messageId: "msg1", userProperties: { priority: "high" } },
      { body: "Message 2", messageId: "msg2" },
      { body: "Message 3", messageId: "msg3", timeToLiveInSeconds: 300 }
    ];
    await sender.sendMessages(messages);
    console.log("Batch de 3 messages envoyé.");
  } finally {
    await sender.close();
    await sbClient.close();
  }
}

sendMessages().catch((err) => {
  console.error("Erreur:", err);
  process.exit(1);
});

This script loads the connection string from .env, creates a sender for the queue, and sends a simple message plus a batch with IDs, custom properties (userProperties), and TTL (timeToLiveInSeconds). The finally block ensures clients are closed to prevent memory leaks. In production, wrap in a global try-catch and log with a logger like Winston.

Complete script to receive and process messages

receive.ts
import { ServiceBusClient } from "@azure/service-bus";
import * as dotenv from "dotenv";
dotenv.config();

const connectionString = process.env.CONNECTION_STRING!;
const queueName = "ma-queue-tutorial";

async function receiveMessages() {
  const sbClient = new ServiceBusClient(connectionString);
  const receiver = sbClient.createReceiver(queueName, { receiveMode: "peekLock" });

  try {
    const messages = await receiver.receiveMessages(10, { maxWaitTimeInMs: 5000 });
    for (const message of messages) {
      console.log(`Message ID: ${message.messageId}, Body: ${message.body}, Properties:`, message.applicationProperties);

      // Simuler traitement
      await new Promise(r => setTimeout(r, 1000));

      // Completer (ack) le message
      await receiver.completeMessage(message);
      console.log(`Message ${message.messageId} traité et acké.");
    }
  } finally {
    await receiver.close();
    await sbClient.close();
  }
}

receiveMessages().catch((err) => {
  console.error("Erreur:", err);
  process.exit(1);
});

Use 'peekLock' to lock messages during processing (vs 'receiveAndDelete' for fire-and-forget). receiveMessages(10) waits up to 5s for 10 messages. After simulated processing, completeMessage() removes them from the queue. If it crashes, they return after lockDuration (default 30s) or go to dead-letter. Add abandonMessage() for retries or deadLetterMessage() for fatal errors.

Clean up Azure resources

terminal
az servicebus queue delete --resource-group rg-servicebus-tutorial --namespace-name monnamespaceunique2026 --name ma-queue-tutorial
az servicebus namespace delete --resource-group rg-servicebus-tutorial --name monnamespaceunique2026 --yes

Delete the queue then the namespace to avoid costs (Standard ~$0.05/hour). The --yes option skips confirmation. Verify in portal.azure.com that everything is gone. In production, use Azure Resource Manager templates (ARM/Bicep) for IaC instead of manual CLI.

Best practices

  • Secure credentials: Use Azure Managed Identity or SAS tokens instead of connection strings in production. Store in Key Vault.
  • Session management: Enable for ordering related messages (e.g., by userId) with createSessionReceiver.
  • Monitoring: Integrate Application Insights to track metrics (throughput, dead-letters) via Azure Portal > Metrics.
  • Scalability: Choose Premium SKU for >5TB/namespace and auto-partitioning.
  • Batching: Send/receive in batches up to 100 messages to optimize throughput.

Common errors to avoid

  • Non-unique namespace: Azure rejects with 'NamespaceAlreadyExists'. Add timestamp or UUID to the name.
  • Forgetting close(): Causes AMQP connection exhaustion. Always use finally {} or try-with-resources.
  • Wrong ReceiveMode: 'peekLock' without complete/abandon leaves messages locked indefinitely.
  • No retry policy: Implement exponential backoff for transient errors (e.g., NetworkTransientError).

Next steps

Move on to topics/subscriptions for pub/sub: Azure Service Bus Topics Docs. Explore dead-letter queues and transactions. For .NET, check the official SDK. Master Bicep for IaC. Check out our Learni Azure training for AZ-204 certification. Practice on free Azure Sandbox.