RabbitMQ channel & connection best practices
In RabbitMQ, connections are expensive, channels are cheap. But “one global channel” in a hot path is also a recipe for trouble. Here’s how I usually structure things in .NET.
1. One connection per app instance (usually)
I create a single connection per process and reuse it for all publishers/consumers. That keeps connection overhead low but still lets RabbitMQ route channels independently.
2. Separate channels for publishers vs consumers
I avoid sharing a single channel across everything. At a minimum:
- One or more channels dedicated to consumers.
- One channel (or a small pool) dedicated to publishers.
This prevents consumer-side backpressure or exceptions from impacting publishing.
3. Use prefetch to control load
Prefetch tells RabbitMQ how many unacked messages a consumer can hold at once. I usually:
- Start with prefetch 10–50.
- Increase only if processing is fast and idempotent.
- Avoid prefetch 0 (unlimited) in most real systems.
4. Handle connection drops gracefully
Connections will drop over time. A resilient client:
- Wraps the connection in a manager that can recreate it.
- Rebuilds channels and consumers on reconnection.
- Logs clearly when reconnecting and when it’s stable again.