Patterncore
Competing Consumers
Also called Competing Consumers pattern, competing consumer, work queue consumers, worker pool on a queue.
Competing consumers are many consumers on one point-to-point channel; the messaging system gives each message to one of them, so the work is shared and processed in parallel.
- Family
- integration
- Intent
- Process messages in parallel and share the load, by many consumers that receive from one point-to-point channel, where each message goes to only one consumer.
- Also called
- competing consumer
Intent
Let many consumers share the work of one queue, so that the messages are processed in parallel. The book asks: "How can a messaging client process multiple messages concurrently?"12 The answer: "Create multiple Competing Consumers on a single channel so that the consumers can process multiple messages concurrently."1
Problem
An application puts work on a queue faster than one consumer can process it. The load also changes. The Azure page gives the example of a system that must process many hundreds of requests per second at peak hours, and few at other times.3 One consumer becomes the bottleneck, and the queue grows.
More threads in one consumer help only up to the limits of one process, and one process is a single point of failure.
The forces are these. Each message must be processed by one consumer only. No consumer must be idle while another has a backlog. And a consumer that stops must not lose the message that it holds.
Solution
Start many consumers on one Point-to-Point Channel. Each consumer receives from the channel, and the messaging system gives each message to one of them. The consumers compete, and the messaging system, not the consumers, decides which one gets a message.1
+--> [ consumer 1 ]
producers ---> [ work queue ] ----+--> [ consumer 2 ] each message goes to one consumer
| +--> [ consumer 3 ]
+--> [ dead letters ] (a message that fails too often)
The participants are the producers, the queue, the consumers and often a Dead Letter Channel. The pattern needs a point-to-point channel. On a Publish-Subscribe Channel, each consumer gets its own copy, so more consumers make more copies, not less work for each one.13
Acknowledgements. A consumer tells the broker when it has processed a message. In the RabbitMQ tutorial, when a consumer stops before its ack, RabbitMQ puts the message back on the queue and gives it to another consumer.4 Azure Service Bus does the same with PeekLock: the message stays in the queue but is hidden from the other consumers, and it becomes visible again if the consumer abandons it.3 So a message can come more than once, and the consumers must be safe for this; see Idempotent Receiver.
How the broker chooses. By default, RabbitMQ gives each message to the next consumer in turn, and it does not look at how many unacknowledged messages a consumer has. With basic_qos(prefetch_count=1), it gives a consumer a new message only after the consumer has acknowledged the last one.4 The program below simulates two workers and six messages. The odd messages take 5 ticks and the even ones 1 tick.
# Two workers share one queue. Odd messages take 5 ticks, even ones 1 tick.
costs = {1: 5, 2: 1, 3: 5, 4: 1, 5: 5, 6: 1}
def round_robin(workers):
# The broker gives message n to worker n mod k when it arrives.
busy = [0] * workers
done = []
for m, cost in costs.items():
w = (m - 1) % workers
busy[w] += cost
done.append((busy[w], m, w))
return busy, sorted(done)
def prefetch_one(workers):
# The broker gives the next message to a worker only when it is free.
free_at = [0] * workers
busy = [0] * workers
done = []
for m, cost in costs.items():
w = min(range(workers), key=lambda i: (free_at[i], i))
free_at[w] += cost
busy[w] += cost
done.append((free_at[w], m, w))
return busy, sorted(done)
for name, plan in [("round robin", round_robin), ("prefetch 1", prefetch_one)]:
busy, done = plan(2)
print(f"{name}: worker 1 busy {busy[0]} ticks, worker 2 busy {busy[1]} ticks,"
f" all done at tick {max(t for t, _, _ in done)}")
print(" order of completion:", " ".join(f"m{m}" for _, m, _ in done))
round robin: worker 1 busy 15 ticks, worker 2 busy 3 ticks, all done at tick 15
order of completion: m2 m4 m6 m1 m3 m5
prefetch 1: worker 1 busy 11 ticks, worker 2 busy 7 ticks, all done at tick 11
order of completion: m2 m1 m3 m4 m6 m5
With round robin, worker 1 gets all the heavy messages and is busy for 15 ticks, while worker 2 is idle after 3 ticks. With a prefetch of 1, the work is shared and all is done at tick 11. In both runs, the messages complete in an order that is not the order in which they were sent.
Example
Each example file starts three workers on one in-memory queue with eight jobs. Job 4 fails on its first delivery, as with a short outage of a database, and goes back on the queue. Job 7 always fails. After three deliveries it goes to the dead letter channel, so that it does not come back for ever. Which worker gets which job changes from run to run, so the programs sort the events by job number before they print them.
import queue
import threading
import time
MAX_DELIVERIES = 3
WORKERS = 3
jobs = queue.Queue()
lock = threading.Lock()
results, events = {}, []
pending = 8
deliveries = 0
def handle(job, attempt):
time.sleep(0.04)
if job == 4 and attempt == 1:
raise RuntimeError("timeout of the database")
if job == 7:
raise ValueError("bad payload")
return job * job
def worker():
global pending, deliveries
while True:
item = jobs.get()
if item is None:
return
job, attempt = item
with lock:
deliveries += 1
try:
result = handle(job, attempt)
except Exception as e:
with lock:
if attempt < MAX_DELIVERIES:
events.append((job, attempt, f"failed on delivery {attempt} ({e}), back on the queue"))
jobs.put((job, attempt + 1))
continue
events.append((job, attempt, f"failed on delivery {attempt} ({e}), to the dead letter channel"))
result = None
with lock:
if result is not None:
results[job] = result
pending -= 1
if pending == 0:
for _ in range(WORKERS):
jobs.put(None)
for job in range(1, 9):
jobs.put((job, 1))
threads = [threading.Thread(target=worker) for _ in range(WORKERS)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{WORKERS} workers, 8 jobs on one queue")
for job, attempt, text in sorted(events):
print(f"job {job}: {text}")
print(f"done: {len(results)} jobs, results", " ".join(str(results[j]) for j in sorted(results)))
print(f"deliveries: {deliveries}")
3 workers, 8 jobs on one queue
job 4: failed on delivery 1 (timeout of the database), back on the queue
job 7: failed on delivery 1 (bad payload), back on the queue
job 7: failed on delivery 2 (bad payload), back on the queue
job 7: failed on delivery 3 (bad payload), to the dead letter channel
done: 7 jobs, results 1 4 9 16 25 36 64
deliveries: 11
- Verdict: idiom.
queue.Queueis safe for many threads, and three threads that callgeton the same queue are competing consumers. - A failed job is put back on the queue with its delivery count plus one; at the limit, it goes to the dead letter channel and counts as finished.
- When the count of open jobs reaches 0, the program puts one
Nonefor each worker, so that each thread ends.
import java.util.*;
import java.util.concurrent.*;
public class Main {
static final int MAX_DELIVERIES = 3, WORKERS = 3;
record Delivery(int job, int attempt) {}
record Event(int job, int attempt, String text) {}
static final BlockingQueue<Delivery> jobs = new LinkedBlockingQueue<>();
static final Delivery STOP = new Delivery(0, 0);
static final Map<Integer, Integer> results = new TreeMap<>();
static final List<Event> events = new ArrayList<>();
static int pending = 8, deliveries = 0;
static int handle(int job, int attempt) throws Exception {
Thread.sleep(40);
if (job == 4 && attempt == 1) throw new Exception("timeout of the database");
if (job == 7) throw new Exception("bad payload");
return job * job;
}
static void worker() {
try {
while (true) {
Delivery d = jobs.take();
if (d == STOP) return;
synchronized (Main.class) { deliveries++; }
Integer result = null;
Exception error = null;
try { result = handle(d.job(), d.attempt()); } catch (Exception e) { error = e; }
synchronized (Main.class) {
if (error != null && d.attempt() < MAX_DELIVERIES) {
events.add(new Event(d.job(), d.attempt(), "failed on delivery " + d.attempt()
+ " (" + error.getMessage() + "), back on the queue"));
jobs.add(new Delivery(d.job(), d.attempt() + 1));
continue;
}
if (error != null) {
events.add(new Event(d.job(), d.attempt(), "failed on delivery " + d.attempt()
+ " (" + error.getMessage() + "), to the dead letter channel"));
} else {
results.put(d.job(), result);
}
if (--pending == 0) {
for (int i = 0; i < WORKERS; i++) jobs.add(STOP);
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
for (int job = 1; job <= 8; job++) jobs.add(new Delivery(job, 1));
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < WORKERS; i++) {
Thread t = new Thread(Main::worker);
t.start();
threads.add(t);
}
for (Thread t : threads) t.join();
System.out.println(WORKERS + " workers, 8 jobs on one queue");
events.sort(Comparator.comparingInt(Event::job).thenComparingInt(Event::attempt));
for (Event e : events) System.out.println("job " + e.job() + ": " + e.text());
StringJoiner values = new StringJoiner(" ");
results.values().forEach(v -> values.add(v.toString()));
System.out.println("done: " + results.size() + " jobs, results " + values);
System.out.println("deliveries: " + deliveries);
}
}
3 workers, 8 jobs on one queue
job 4: failed on delivery 1 (timeout of the database), back on the queue
job 7: failed on delivery 1 (bad payload), back on the queue
job 7: failed on delivery 2 (bad payload), back on the queue
job 7: failed on delivery 3 (bad payload), to the dead letter channel
done: 7 jobs, results 1 4 9 16 25 36 64
deliveries: 11
- Verdict: idiom. A
LinkedBlockingQueuewith three threads that calltakeis the standard form; in a broker client,concurrentConsumersor a listener container does the same. - The
STOPrecord is a poison pill: the last finished job puts one for each thread. - The shared counters and lists are changed only inside
synchronized, so the threads do not lose updates.
using System.Collections.Concurrent;
const int MaxDeliveries = 3, Workers = 3;
var jobs = new BlockingCollection<(int Job, int Attempt)>();
var gate = new object();
var results = new SortedDictionary<int, int>();
var events = new List<(int Job, int Attempt, string Text)>();
int pending = 8, deliveries = 0;
int Handle(int job, int attempt)
{
Thread.Sleep(40);
if (job == 4 && attempt == 1) throw new TimeoutException("timeout of the database");
if (job == 7) throw new FormatException("bad payload");
return job * job;
}
void Worker()
{
foreach (var (job, attempt) in jobs.GetConsumingEnumerable())
{
lock (gate) deliveries++;
int? result = null;
Exception? error = null;
try { result = Handle(job, attempt); } catch (Exception e) { error = e; }
lock (gate)
{
if (error != null && attempt < MaxDeliveries)
{
events.Add((job, attempt, $"failed on delivery {attempt} ({error.Message}), back on the queue"));
jobs.Add((job, attempt + 1));
continue;
}
if (error != null)
events.Add((job, attempt, $"failed on delivery {attempt} ({error.Message}), to the dead letter channel"));
else
results[job] = result!.Value;
if (--pending == 0) jobs.CompleteAdding();
}
}
}
for (int job = 1; job <= 8; job++) jobs.Add((job, 1));
var threads = Enumerable.Range(0, Workers).Select(_ => new Thread(Worker)).ToList();
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
Console.WriteLine($"{Workers} workers, 8 jobs on one queue");
foreach (var e in events.OrderBy(e => e.Job).ThenBy(e => e.Attempt))
Console.WriteLine($"job {e.Job}: {e.Text}");
Console.WriteLine($"done: {results.Count} jobs, results {string.Join(" ", results.Values)}");
Console.WriteLine($"deliveries: {deliveries}");
3 workers, 8 jobs on one queue
job 4: failed on delivery 1 (timeout of the database), back on the queue
job 7: failed on delivery 1 (bad payload), back on the queue
job 7: failed on delivery 2 (bad payload), back on the queue
job 7: failed on delivery 3 (bad payload), to the dead letter channel
done: 7 jobs, results 1 4 9 16 25 36 64
deliveries: 11
- Verdict: idiom.
BlockingCollection<T>withGetConsumingEnumerablegives each item to one of the threads that read it. CompleteAddingafter the last finished job ends the loop in each thread.- A
lockon one object protects the counters, the results and the events.
package main
import (
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
)
const maxDeliveries = 3
const workers = 3
type delivery struct{ job, attempt int }
type event struct {
job, attempt int
text string
}
func handle(job, attempt int) (int, error) {
time.Sleep(40 * time.Millisecond)
if job == 4 && attempt == 1 {
return 0, errors.New("timeout of the database")
}
if job == 7 {
return 0, errors.New("bad payload")
}
return job * job, nil
}
func main() {
jobs := make(chan delivery, 16)
var mu sync.Mutex
results := map[int]int{}
var events []event
pending, deliveries := 8, 0
for job := 1; job <= 8; job++ {
jobs <- delivery{job, 1}
}
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for d := range jobs {
mu.Lock()
deliveries++
mu.Unlock()
result, err := handle(d.job, d.attempt)
mu.Lock()
if err != nil && d.attempt < maxDeliveries {
events = append(events, event{d.job, d.attempt,
fmt.Sprintf("failed on delivery %d (%v), back on the queue", d.attempt, err)})
jobs <- delivery{d.job, d.attempt + 1}
mu.Unlock()
continue
}
if err != nil {
events = append(events, event{d.job, d.attempt,
fmt.Sprintf("failed on delivery %d (%v), to the dead letter channel", d.attempt, err)})
} else {
results[d.job] = result
}
pending--
if pending == 0 {
close(jobs)
}
mu.Unlock()
}
}()
}
wg.Wait()
fmt.Printf("%d workers, 8 jobs on one queue\n", workers)
sort.Slice(events, func(i, j int) bool {
if events[i].job != events[j].job {
return events[i].job < events[j].job
}
return events[i].attempt < events[j].attempt
})
for _, e := range events {
fmt.Printf("job %d: %s\n", e.job, e.text)
}
keys := make([]int, 0, len(results))
for k := range results {
keys = append(keys, k)
}
sort.Ints(keys)
parts := make([]string, len(keys))
for i, k := range keys {
parts[i] = fmt.Sprint(results[k])
}
fmt.Printf("done: %d jobs, results %s\n", len(results), strings.Join(parts, " "))
fmt.Printf("deliveries: %d\n", deliveries)
}
3 workers, 8 jobs on one queue
job 4: failed on delivery 1 (timeout of the database), back on the queue
job 7: failed on delivery 1 (bad payload), back on the queue
job 7: failed on delivery 2 (bad payload), back on the queue
job 7: failed on delivery 3 (bad payload), to the dead letter channel
done: 7 jobs, results 1 4 9 16 25 36 64
deliveries: 11
- Verdict: idiom. Three goroutines that
rangeover one channel are competing consumers; the Go runtime gives each value to one receiver. - A failed job is sent back on the channel; the buffer of 16 keeps the send from blocking while the worker holds the mutex.
- The last finished job closes the channel, which ends the
rangeloop of each goroutine.
Consequences
Benefits.
- Throughput. The consumers work in parallel, and the number of consumers can change with the length of the queue. Azure Functions adds consumer instances as the queue grows, and can scale down to zero when it is empty.3
- Availability. If one consumer fails, the others go on, and a message with no ack goes to another consumer.34
- Simple producers. The producers send to one queue and do not know how many consumers there are.
- Throttling. Each consumer takes one message at a time, so the number of consumers limits the rate at which messages are consumed.5
Liabilities.
- No order. The Azure page says that the order in which the consumers receive messages is not guaranteed.3 In the program above, m5 completes after m6.
- Duplicates. A redelivery after a failure means that a message can be processed twice.
- Poison messages. A message that always fails comes back again and again. Service Bus moves a message to a dead-letter queue when its delivery count is more than
MaxDeliveryCount.3 - Transactions. The book warns that competing consumers that control their transactions from outside the messaging system can have serious problems.5
- Fixed assignment in Kafka. The EIP site describes a Kafka consumer group: each partition is a channel of its own, and each consumer reads its partitions. So the choice of the consumer is made in advance, a consumer with an empty partition cannot help the others, and a group cannot have more active consumers than the topic has partitions.1
When not to use it
When the order matters. If the messages must be processed in sequence, use one consumer, or a feature that sends a group of related messages to one consumer, such as message sessions in Service Bus.3
When the tasks depend on each other. The Azure page names a workload that cannot be split into separate tasks, and tasks that must run synchronously, one after the other.3
When each consumer needs each message. That is a publish-subscribe channel, not a work queue.
Variants and related patterns
Message Dispatcher. The book asks: "How can multiple consumers on a single channel coordinate their message processing?" The answer: "Create a Message Dispatcher on a channel that will consume messages from a channel and distribute them to performers."6 Here the application chooses the performer for a message, for example by its content, where competing consumers leave the choice to the messaging system.
Polling or event-driven. Each competing consumer can be a Polling Consumer or an event-driven consumer, and it can also be a transactional client.5
A thread pool in one process. When a component does not allow many consumers, Camel can hand the messages of one consumer to a Thread pool with the Threads EIP. Its documentation calls the result "quasi like" competing consumers.7 In one program, the same shape is a Work queue.
Known uses
- RabbitMQ: the work queues tutorial runs two workers on one queue, with round-robin dispatch, manual acks and
prefetch_count=1.4 - Apache Camel: the JMS component starts five consumers on one queue with
concurrentConsumers=5, as the Competing Consumers page of 4.14.0 shows.7 - Azure: Service Bus queues with Azure Functions triggers. The runtime receives in PeekLock mode, calls Complete on success, may call Abandon on a failure, and renews the lock while a function runs.3
- Apache Kafka: the consumers of a consumer group share the partitions of a topic.1
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Competing Consumers (problem and solution under CC BY), problem and solution statements; pattern text; example, Apache Kafka
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 10, Messaging Endpoints, Competing Consumers
- Microsoft, Azure Architecture Center, Competing Consumers pattern, context and problem; solution; problems and considerations; when to use this pattern; example
- RabbitMQ tutorials, Work Queues (Python), round-robin dispatching; message acknowledgment; fair dispatch
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Messaging Endpoints, message consumer patterns; message endpoint themes
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Message Dispatcher (problem and solution under CC BY), problem and solution statements; pattern text
- Apache Camel 4.14.0 documentation source, Competing Consumers, competing consumers with JMS; competing consumers with thread pool
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 0FHWAR Edit this page History Report an error Markdown