MessagingC# · TypeScript

Competing Consumers

Several consumer instances read from the same queue, each message going to exactly one of them, so throughput scales by adding consumers.

On this page
  1. Problem
  2. Context
  3. Solution
  4. Implementation
  5. Trade-offs
  6. Alternatives
  7. Anti-patterns
  8. Related lessons
  9. Interview questions

Problem

Background work arrives unevenly: image uploads spike in the evening, order confirmations surge during a sale, imports land in large batches. A single worker processing messages one by one falls behind during peaks, and the queue grows until messages are hours old.

Processing the work inside the request that produced it is no better. The user waits for slow tasks, a failure loses the work, and the web tier has to be sized for the heaviest background job instead of for serving requests.

Context

Use this pattern when:

  • Work items are independent: processing one does not require the result of another (or ordering is only needed per key).
  • Arrival rate varies, and throughput must scale up and down with it.
  • Each item must be processed, and a crashed worker must not lose the item it was holding.
  • A broker such as RabbitMQ, Amazon SQS, Azure Service Bus or Kafka is available.

Solution

Producers send messages to one queue. Any number of identical consumer instances connect to it, and the broker delivers each message to exactly one of them. Adding consumers raises throughput roughly linearly until a shared dependency such as the database becomes the bottleneck.

A consumer acknowledges a message only after it has finished processing. If it crashes or fails, the broker redelivers the message to another consumer, after the connection drops (RabbitMQ) or the visibility timeout expires (SQS). Because redelivery can happen after work was partly or fully done, handlers must be idempotent.

Flow control keeps work evenly spread: a prefetch limit stops one consumer from hoarding messages it cannot process yet. Autoscaling on queue depth or message age adds consumers during peaks and removes them when the queue drains. In Kafka the same idea applies per partition: a consumer group assigns each partition to one member, so parallelism is capped by the partition count.

How it works, step by step

  1. 1Producers publish work items to a durable queue.
  2. 2N consumer instances subscribe; the broker hands each message to one consumer, limited by prefetch.
  3. 3The consumer processes the message idempotently.
  4. 4On success it acknowledges, and the broker removes the message.
  5. 5On failure or crash the message is redelivered; after too many attempts it moves to a dead letter queue.

Implementation

The C# example uses a BackgroundService with the Azure Service Bus processor, which handles concurrency, locks and redelivery. The TypeScript example shows the same loop against RabbitMQ with amqplib.

C#Worker with Azure Service Bus processor
using Azure.Messaging.ServiceBus;

public sealed class ThumbnailWorker(ServiceBusClient client, IThumbnailer thumbnailer, ILogger<ThumbnailWorker> log)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await using var processor = client.CreateProcessor("thumbnails", new ServiceBusProcessorOptions
        {
            MaxConcurrentCalls = 8,       // parallelism inside this instance
            PrefetchCount = 16,           // small buffer, avoids hoarding
            AutoCompleteMessages = false, // acknowledge only after success
        });

        processor.ProcessMessageAsync += async args =>
        {
            var imageId = args.Message.Body.ToString();
            // Idempotent: regenerating an existing thumbnail just overwrites it.
            await thumbnailer.GenerateAsync(imageId, args.CancellationToken);
            await args.CompleteMessageAsync(args.Message, args.CancellationToken);
        };

        processor.ProcessErrorAsync += args =>
        {
            log.LogError(args.Exception, "Processing failed ({Source})", args.ErrorSource);
            return Task.CompletedTask;
        };

        await processor.StartProcessingAsync(stoppingToken);
        try
        {
            await Task.Delay(Timeout.Infinite, stoppingToken);
        }
        catch (OperationCanceledException)
        {
            // Shutting down: stop taking new messages, let in-flight ones finish.
        }
        await processor.StopProcessingAsync();
    }
}

public interface IThumbnailer
{
    Task GenerateAsync(string imageId, CancellationToken ct);
}

An exception thrown from the handler abandons the message, so Service Bus redelivers it; after MaxDeliveryCount attempts it moves to the dead letter sub-queue. Run more instances of this worker to scale out.

TypeScriptRabbitMQ consumer with manual acks and prefetch
import amqp from 'amqplib';

type Job = { imageId: string };

export async function startWorker(generate: (job: Job) => Promise<void>) {
  const connection = await amqp.connect(process.env.AMQP_URL ?? 'amqp://localhost');
  const channel = await connection.createChannel();

  await channel.assertQueue('thumbnails', { durable: true });
  // At most 4 unacknowledged messages per worker: work spreads across instances.
  await channel.prefetch(4);

  await channel.consume('thumbnails', async (message) => {
    if (!message) return; // consumer cancelled by the broker

    try {
      const job = JSON.parse(message.content.toString()) as Job;
      await generate(job);
      channel.ack(message);
    } catch (error) {
      console.error('job failed', error);
      // requeue=false: let the queue's dead-letter exchange take it
      // instead of looping on a message that keeps failing.
      channel.nack(message, false, false);
    }
  }, { noAck: false });

  const shutdown = async () => {
    await channel.close();
    await connection.close();
  };
  process.once('SIGTERM', shutdown);
  return shutdown;
}

Configure the queue with an x-dead-letter-exchange argument so rejected messages are kept for inspection rather than dropped.

In production

  • Acknowledge after processing, never before; early acks lose messages when a worker crashes.
  • Make handlers idempotent, because redelivery after a timeout or crash is normal behaviour, not an edge case.
  • Keep prefetch small for slow, uneven tasks and larger for fast, uniform ones.
  • Autoscale on queue age (oldest message) rather than depth alone; age is what users experience.
  • Watch the shared downstream: ten times the consumers can mean ten times the database connections.

Trade-offs

Benefits

  • Throughput scales horizontally by adding consumers.
  • Peaks are absorbed by the queue instead of overwhelming workers or users.
  • A failed consumer does not lose work; another consumer picks it up.
  • Producers and consumers deploy and scale independently.

Costs

  • No global ordering: parallel consumers finish messages in a different order than they were sent.
  • At-least-once delivery forces idempotent handlers.
  • More instances increase pressure on shared resources such as databases and third-party APIs.
  • Poison messages can be retried repeatedly unless a dead letter policy is configured.

Alternatives

Partitioned consumers
Kafka consumer groups or Service Bus sessions keep per-key ordering by assigning each key to one consumer, at the cost of parallelism capped by the number of partitions.
Publish/subscribe
Every subscriber receives every message; used when several services each need to react, not to share work.
Batch jobs
Process accumulated work on a schedule when latency does not matter and bulk operations are much cheaper.

Anti-patterns

Auto-acknowledging on receive
The message is removed before work is done, so any crash or exception loses it silently.
Unlimited prefetch
One consumer grabs thousands of messages and processes them slowly while other consumers sit idle.
Assuming in-order processing
With several consumers, message 2 can finish before message 1; logic that needs ordering must use partitioning or versioning.
Requeueing failures forever
A poison message returned to the head of the queue blocks or slows everyone; cap attempts and dead-letter it.

Interview questions

How does adding consumers to a Kafka topic differ from adding them to a RabbitMQ queue?

In RabbitMQ any number of consumers can share a queue, and each message goes to one of them. In Kafka a consumer group assigns each partition to exactly one member, so consumers beyond the partition count sit idle; scaling requires more partitions.

Why must consumers be idempotent in this pattern?

A message is redelivered whenever its acknowledgement does not reach the broker, for example after a crash, a network blip or a visibility timeout that expired during slow processing. The same message can therefore be processed twice, and only an idempotent handler makes that harmless.

What metric would you autoscale consumers on?

Queue age, meaning how long the oldest message has waited, maps directly to user-visible delay. Depth is useful too but depends on message size and processing time; combine with consumer CPU and downstream saturation to avoid scaling into a database bottleneck.

How do you preserve order for events belonging to the same customer while still scaling out?

Partition by customer id: Kafka partitions, Service Bus sessions or consistent hashing of keys to queues ensure one consumer handles a given customer at a time. Different customers still process in parallel.