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).
amqplibnpm 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 });
// 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();
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Use Redis Pub/Sub for lightweight inter-service messaging.
Process queued jobs with background worker consumers.
Containerize individual microservices with Docker Compose.