Getting Started with Azure Service Bus: Queues, Topics, and Subscriptions with Node.js

Shikhar ShuklaShikhar Shukla
4 min read

In modern cloud applications, different components or microservices often need to talk to each other asynchronously. A common and scalable solution for this is a message broker. Azure Service Bus is one such enterprise-grade message broker offered by Microsoft Azure.

In this guide, we will understand the core concepts of Azure Service Bus including Queues, Topics, and Subscriptions, and we will also walk through working Node.js code examples. These steps are based on a real-world SOP (Standard Operating Procedure) used in live production projects.

What is Azure Service Bus

Azure Service Bus is a fully managed message broker that allows different systems and applications to exchange messages reliably. It supports both:

  • Queue-based messaging (point-to-point)

  • Topic-based messaging (publish-subscribe)

This helps in building loosely coupled, distributed systems where components don’t need to be online at the same time.

Messaging Models

1. Queues

A Queue in Azure Service Bus follows the First-In-First-Out (FIFO) principle. One component sends a message to the queue and another component reads it when ready.

Use case: Order processing systems, ticket booking apps, etc.

Only one receiver receives the message, and once it’s processed, the message is removed from the queue.

Queues are supported in Basic, Standard, and Premium tiers.

2. Topics and Subscriptions

A Topic works as a broadcast channel. When a message is sent to a topic, it is duplicated to all its subscriptions. Each subscription acts like its own virtual queue.

Use case: Sending notifications to multiple services like mobile apps, web apps, or email services.

Topics and Subscriptions are only supported in Standard and Premium tiers.

Setting Up Azure Service Bus

Step 1: Create a Namespace

  1. Go to the Azure Portal

  2. Search for Service Bus and click + Create

  3. Choose a name, region, resource group, and pricing tier

  4. Click Review and Create

The Namespace is a container that holds queues and topics. It also defines the security boundary through Shared Access Policies.

Step 2: Create a Queue

  1. Go to your namespace

  2. Click on Queues and then + Queue

  3. Enter a name like orders-queue

  4. Leave default options and click Create

You can now send messages to this queue using either the portal or code.

Step 3: Create a Topic and Subscriptions

  1. Go to your namespace

  2. Click on Topics and then + Topic

  3. Name it notifications-topic and create

  4. Click the topic > Subscriptions > + Subscription

  5. Add one or more subscriptions, for example web-app-sub, mobile-app-sub

Each subscription gets a copy of every message sent to the topic.

Using Node.js with Azure Service Bus

First, install the required package:

npm install @azure/service-bus

Queue Example: Sending and Receiving Messages

const { ServiceBusClient } = require("@azure/service-bus");

const connectionString = "YOUR_FULL_CONNECTION_STRING";
const queueName = "orders-queue";

const sbClient = new ServiceBusClient(connectionString);
const sender = sbClient.createSender(queueName);
const receiver = sbClient.createReceiver(queueName);

async function sendMessage() {
  const message = {
    body: {
      name: "Shikhar",
      purpose: "Test message from Node.js"
    },
    contentType: "application/json"
  };
  await sender.sendMessages(message);
  console.log("Message sent successfully");
}

async function receiveMessage() {
  const messages = await receiver.receiveMessages(1, { maxWaitTimeInMs: 5000 });

  if (messages.length === 0) {
    console.log("No messages received");
    return;
  }

  for (const msg of messages) {
    console.log("Received message:", msg.body);
    await receiver.completeMessage(msg);
  }
}

async function main() {
  await sendMessage();
  await receiveMessage();
  await sender.close();
  await receiver.close();
  await sbClient.close();
}

main().catch((err) => console.error("Error:", err));

Topic and Subscription Example

const { ServiceBusClient } = require("@azure/service-bus");

const connectionString = "YOUR_FULL_CONNECTION_STRING";
const topicName = "notifications-topic";
const subscriptionName = "web-app-sub";

const sbClient = new ServiceBusClient(connectionString);
const sender = sbClient.createSender(topicName);
const receiver = sbClient.createReceiver(topicName, subscriptionName);

async function sendMessageToTopic() {
  const message = {
    body: {
      event: "New Offer",
      description: "50 percent OFF for all users"
    },
    contentType: "application/json"
  };
  await sender.sendMessages(message);
  console.log("Message sent to topic");
}

async function receiveFromSubscription() {
  const messages = await receiver.receiveMessages(1, { maxWaitTimeInMs: 5000 });

  if (messages.length === 0) {
    console.log("No messages in subscription");
    return;
  }

  for (const msg of messages) {
    console.log("Received from subscription:", msg.body);
    await receiver.completeMessage(msg);
  }
}

async function main() {
  await sendMessageToTopic();
  await receiveFromSubscription();
  await sender.close();
  await receiver.close();
  await sbClient.close();
}

main().catch((err) => console.error("Error:", err));

Queue vs Topic Comparison

FeatureQueueTopic + Subscriptions
Messaging PatternOne-to-OneOne-to-Many
ReceiverOnly oneAll subscribers
Supported TiersBasic, Standard, PremiumStandard, Premium
Use CasesOrder ProcessingNotifications to users
Message RoutingSimpleCan use filters and rules

Conclusion

Azure Service Bus provides a robust solution for decoupling systems and enabling reliable messaging between services. Whether you’re using queues for point-to-point delivery or topics for publish-subscribe broadcasting, Azure Service Bus handles it with reliability and scalability.

With the Node.js SDK, integrating Azure Service Bus into your applications becomes seamless. You can scale messaging for real-time applications, background processing, and cross-service communication without much complexity.

If you’re building microservices or distributed systems on Azure, Service Bus is a must-have tool in your architecture.

0
Subscribe to my newsletter

Read articles from Shikhar Shukla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shikhar Shukla
Shikhar Shukla