Node.js Microservices - Event-Driven Architecture with RabbitMQ & Message Queues

Monolithic backends struggle as systems grow: a bug in one component can bring down the entire application. In a Microservices Architecture, independent services (e.g., Auth Service, Payment Service, Order Service, Notification Service) communicate asynchronously through Message Queues (RabbitMQ).

Publishing Messages to RabbitMQ with amqplib

npm install amqplib
// producer.js (Order Service)
const amqp = require('amqplib');

async function publishOrderEvent(orderData) {
  // Connect to RabbitMQ broker
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();

  const QUEUE = 'orders_queue';

  // Ensure queue exists
  await channel.assertQueue(QUEUE, { durable: true });

  // Send message as binary buffer
  channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(orderData)), {
    persistent: true // Store to disk so messages survive RabbitMQ restarts
  });

  console.log('[PRODUCED] Order event sent to RabbitMQ:', orderData.orderId);

  await channel.close();
  await connection.close();
}

publishOrderEvent({ orderId: 'ORD-5541', user: 'rahul@example.com', amount: 99.99 });

Consuming Messages with Worker Acknowledgments

// consumer.js (Email Notification Service Worker)
const amqp = require('amqplib');

async function startNotificationWorker() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();

  const QUEUE = 'orders_queue';
  await channel.assertQueue(QUEUE, { durable: true });

  // Fair dispatch: Don't give a worker more than 1 unacknowledged message
  channel.prefetch(1);

  console.log('[WORKER READY] Waiting for order messages...');

  channel.consume(QUEUE, async (msg) => {
    if (msg !== null) {
      const order = JSON.parse(msg.content.toString());
      console.log(`[CONSUMED] Sending order confirmation email to ${order.user}...`);

      // Simulate sending email
      await new Promise(resolve => setTimeout(resolve, 1000));

      // CRITICAL: Acknowledge message processing complete!
      channel.ack(msg);
      console.log(`[ACKNOWLEDGED] Order #${order.orderId} processed.`);
    }
  }, { noAck: false });
}

startNotificationWorker();

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is a Message Queue and why is it used in microservices?

A message queue (e.g. RabbitMQ, Kafka) is an intermediary buffer that receives messages from producers and delivers them to consumers asynchronously. It allows microservices to communicate without direct HTTP coupling, preventing cascading failures and absorbing sudden traffic spikes without data loss.

Q2. What is the difference between Point-to-Point and Publish/Subscribe (Pub/Sub) messaging?

In Point-to-Point (Queue), each message is consumed by exactly one worker (e.g. processing a payment). In Pub/Sub (Topics/Fanout), a published message is broadcast to all active subscribers simultaneously (e.g. notifying user, updating analytics, and sending SMS).

Q3. What are Message Acknowledgments (ACKs) in RabbitMQ?

An acknowledgment is a confirmation sent from the consumer back to RabbitMQ indicating that the message was received and processed successfully. If the consumer crashes before sending an ACK, RabbitMQ re-queues the message to be delivered to another worker, guaranteeing zero data loss.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Redis In-Memory Caching

Use Redis Pub/Sub for lightweight inter-service messaging.

Task Scheduling & Background Workers

Process queued jobs with background worker consumers.

Docker & Containerization

Containerize individual microservices with Docker Compose.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!