Skip to content

NestJS RabbitMQ

RabbitMQ is excellent for work queues and routing with acknowledgements. Nest supports it through Transport.RMQ.

Configuring RabbitMQ Transport

Point Nest at RabbitMQ URLs and a queue name. Consumers acknowledge messages according to Nest/RMQ options; failed handling can nack/requeue based on configuration.

{
  transport: Transport.RMQ,
  options: {
    urls: ['amqp://localhost:5672'],
    queue: 'orders_queue',
    queueOptions: { durable: true },
  },
}

Durable queues survive broker restarts when combined with persistent message publishing settings.

Work Queue Pattern

@MessagePattern('process_order')
processOrder(@Payload() data: ProcessOrderDto, @Ctx() context: RmqContext) {
  const channel = context.getChannelRef();
  const originalMsg = context.getMessage();
  // work...
  channel.ack(originalMsg);
}
  • Manual acks are useful when processing must finish before acknowledgement.
  • Use separate queues for different workloads to isolate failures.
  • Prefetch limits control how many unacked messages a consumer holds.
  • Dead-letter exchanges catch poisoned messages after max retries.

RabbitMQ Nest Cheatsheet

Key RMQ ideas in Nest apps.

Concept Purpose
Queue Buffer of pending work
Exchange Routing entry point
Binding Links exchange routing to queues
Ack/Nack Confirm or reject processing
DLX Dead-letter failed messages

RabbitMQ vs Kafka (Brief)

RabbitMQ is often simpler for task queues and complex routing. Kafka is stronger for durable replayable logs and high-throughput stream processing. Choose based on need, not hype.

Reliability Settings

Durable queues, persistent messages, publisher confirms, and careful ack timing reduce data loss—test failure modes deliberately.

Common Mistakes

  • Auto-acking before work completes, then losing tasks on crash.
  • Infinite requeue loops for permanently bad payloads.
  • One giant shared queue for unrelated job types.
  • Forgetting TLS/credentials for production brokers.

Key Takeaways

  • Nest RMQ transport connects microservices to RabbitMQ queues.
  • Acknowledgements control reliability of work processing.
  • Use durable queues and DLX for production hardening.
  • Prefer RabbitMQ for work queues; Kafka for event streams—know the difference.

Pro Tip

Log correlation ids from HTTP requests into RabbitMQ payloads so traces remain connected from API gateway to workers.