Back to results for “Architecture”
Node.js › Message Queues (RabbitMQ & Kafka)

How would you publish and consume messages using RabbitMQ in a Node.js application via the amqplib package?

Intermediate

Answer

amqplib provides a client for connecting to RabbitMQ, declaring queues (or more commonly, exchanges that route messages to queues based on rules), publishing messages to an exchange, and consuming messages from a queue via a callback invoked for each incoming message -- with the consumer responsible for explicitly acknowledging (ack) each message once it's been successfully processed, which is what allows RabbitMQ to guarantee at-least-once delivery even if a consumer crashes mid-processing.
const amqp = require('amqplib');

const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertQueue('orders');

// Publisher
channel.sendToQueue('orders', Buffer.from(JSON.stringify({ orderId: 123 })));

// Consumer
channel.consume('orders', (msg) => {
  const order = JSON.parse(msg.content.toString());
  processOrder(order);
  channel.ack(msg); // acknowledge only after successful processing
});
Real-world example An order-processing service publishes a message to a RabbitMQ queue whenever a new order is placed, with a separate, independently scalable worker process consuming from that queue and only acknowledging each message after successfully saving the order to the database, ensuring a worker crash mid-processing results in the message being redelivered rather than silently lost.

Common follow-ups: What happens to an unacknowledged message if the consumer that received it crashes before calling ack()?;How do RabbitMQ exchanges (direct, topic, fanout) differ in how they route published messages to queues?