Competing Consumers & Work Queues in C#
Quick Answer: Competing consumers let you run multiple C# worker instances on the same RabbitMQ queue. RabbitMQ sends each task to only one free worker, so heavy background jobs finish faster without duplicate work.
Imagine Priya runs a food delivery app in Bengaluru. At 8:00 PM on Sunday, 3,000 customers place dinner orders in one minute.
Each order needs a PDF GST invoice, which takes 2 seconds to build. One single C# worker needs 100 minutes to finish that one-minute rush.
How do we clear that backlog in minutes without sending the same invoice twice?
1. Why Do We Need Competing Consumers?
The problem without competing consumers
In a basic setup, Priya's Order API pushes jobs into one queue named invoice-jobs. Only one C# worker reads from it.
Example 1: A single C# worker processing invoices one by one
This simple setup works on a quiet afternoon, but falls behind during dinner rush.
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (sender, ea) =>
{
var orderId = Encoding.UTF8.GetString(ea.Body.ToArray());
// Heavy PDF work takes 2 seconds per order
await GeneratePdfInvoiceAsync(orderId);
await channel.BasicAckAsync(ea.DeliveryTag, false);
};
await channel.BasicConsumeAsync("invoice-jobs", autoAck: false, consumer);
What happens under load (sample scale)
20:00:00 -> Queue depth: 3,000 invoices waiting 20:00:02 -> Worker A finished BLR-8421 (2,999 left) 20:00:04 -> Worker A finished BLR-8422 (2,998 left)
This setup works on a quiet day. However, it breaks when real traffic arrives.
- One worker can only finish 30 invoices per minute.
- The queue grows faster than the worker can drain it.
- Customers wait over an hour to get their GST receipt.
- If that single worker crashes, invoice generation stops completely.
Now think about a cricket match night with 15,000 orders in five minutes. We need a way to add more C# workers on demand. We also need each invoice to be generated exactly once.
The solution: Competing Consumers & Work Queues
Work Queue = a shared RabbitMQ queue that holds time-consuming tasks for background workers.
Competing Consumers = multiple independent worker instances listening to the same queue and sharing the load.
We keep the exact same invoice-jobs queue. We simply start three instances of Priya's C# worker app: Worker A, Worker B, and Worker C. RabbitMQ hands each message to only one worker, so two workers never process the same order.
Competing Consumers Pattern – Priya's Bengaluru Food App
One shared queue distributes heavy PDF invoice jobs across three C# workers with zero duplicate work.
Each order message is delivered to exactly one worker. Adding more workers scales throughput horizontally.
2. How Competing Consumers Work in C#
By default, RabbitMQ uses Round-Robin Dispatch. Round-Robin Dispatch = sending messages to workers in strict turn order (A, B, C, A, B, C).
Round-robin has one flaw. If Worker A gets a huge 20-item catering invoice, RabbitMQ still keeps piling more jobs onto Worker A while Worker B sits idle.
Prefetch Count = the maximum number of unacknowledged messages a worker can hold at one time. Setting prefetchCount to 1 turns on fair dispatch.
Example 2: Fair-dispatch C# worker with BasicQosAsync
Run this same console app in three terminals to create three competing consumers.
var workerName = args.Length > 0 ? args[0] : "Worker-A";
// Tell RabbitMQ: give me only 1 job until I finish and ack it
await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (sender, ea) =>
{
var orderId = Encoding.UTF8.GetString(ea.Body.ToArray());
Console.WriteLine($"[{workerName}] Processing {orderId}...");
await GeneratePdfInvoiceAsync(orderId);
await channel.BasicAckAsync(ea.DeliveryTag, multiple: false);
};
await channel.BasicConsumeAsync(
queue: "invoice-jobs",
autoAck: false,
consumer: consumer);
Expected output across three running instances
[Worker-A] Processing BLR-8421... [Worker-B] Processing BLR-8422... [Worker-C] Processing BLR-8423... [Worker-B] Processing BLR-8424... (Worker-B finished first and got the next job)
BasicQosAsync with prefetchCount: 1 stops RabbitMQ from overloading a slow worker.
autoAck: false tells RabbitMQ to keep the message safe until BasicAckAsync runs. If Worker A crashes mid-PDF, RabbitMQ automatically hands that order to Worker B.
| Without competing consumers | With competing consumers (3 workers) |
|---|---|
| 1 worker handles 30 invoices per minute. | 3 workers handle 90 invoices per minute. |
| A worker crash stops all PDF generation. | Other workers keep running and pick up dropped jobs. |
| You must buy a bigger machine to scale up. | You simply start more .NET containers to scale out. |
The important terms to remember
- Work Queue = a shared queue that holds background tasks waiting for workers.
- Competing Consumers = multiple worker instances reading from the same queue in parallel.
- Fair Dispatch = using
prefetchCount: 1so busy workers do not get new jobs until they finish. - Manual Acknowledgment = calling
BasicAckAsynconly after the job succeeds.
3. Common Mistakes to Avoid
1. Skipping BasicQosAsync on heavy tasks
Without a prefetch limit, RabbitMQ pushes hundreds of messages into one worker's memory. If that worker restarts, all those jobs are delayed.
Better approach: Always call BasicQosAsync(0, 1, false) for slow, CPU-heavy jobs like PDF generation.
2. Assuming strict message order
When three workers run in parallel, BLR-8422 may finish before BLR-8421. Competing consumers trade strict ordering for high speed.
Better approach: Use competing consumers only for independent tasks. If order matters, process related events in a single partition or queue.
4. Interview Questions & Practice
Question 1: How do you prevent two C# workers from processing the same RabbitMQ message?
What the interviewer expects: Understanding that RabbitMQ delivers each queued message to only one consumer, plus knowing how crashes can cause redelivery.
Strong answer: "In Priya's food app, all three C# workers subscribe to the same invoice-jobs queue. RabbitMQ sends each order to only one worker at a time. If a worker crashes before calling BasicAckAsync, RabbitMQ redelivers that job to another worker, so we also make invoice generation safe to retry."
Practice: Hospital lab report generator
A hospital portal in Chennai generates 500 blood-test PDF reports every morning. Run two instances of your C# worker with prefetchCount: 1 and add a 3-second delay to simulate heavy work.
Expected result: Both terminals pick up different patient IDs at the same time and finish the batch twice as fast.
5. Next Steps
- Previous Article: Connection & Channel Lifecycle Management in .NET
- Next Article: Direct Exchanges – Exact-Match Task Routing
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.