Patterncore
Polling Consumer
Also called Polling Consumer pattern, synchronous receiver, pull consumer, polling receiver.
A polling consumer asks the channel for a message when it is ready for one, so the application controls when and how fast it consumes; an event-driven consumer is called when a message comes.
- Family
- integration
- Intent
- Let an application consume messages at its own pace, by a consumer that makes an explicit call to receive the next message, with no wait, a fixed wait or a wait until a message comes.
- Also called
- synchronous receiver
Intent
Let an application take the next message when it is ready for it, not when the message comes. The book asks: "How can an application consume a message when the application is ready?"12 The answer: "The application should use a Polling Consumer", "one that explicitly makes a call when it wants to receive a message."1
Problem
Messages come at the pace of the senders. A receiver that is called for each message as it comes must keep up with that pace, or it gets more work than it can do. The book's chapter on endpoints says that consumers that are event-driven tend to process messages as fast as they come, which can overload a server.3
Some receivers also have their own rhythm. A batch job runs once an hour. A worker takes the next job only when it has finished the last one.
The forces are these. The receiver wants control of when and how many messages it takes. But each call costs a request, and a call that finds nothing is wasted. And a long time between calls leaves messages waiting in the queue.
Solution
Give the application a consumer object with a receive call. When the application is ready, it calls receive, processes the message, and then calls receive again.1 Between the calls, new messages wait in the channel.
[ queue ] <--- receive(wait) --- consumer <--- next, please ---------- application
---- message or none --> ---- message --------------->
The participants are the channel, the consumer and the application. The book calls this a synchronous receiver, because the thread of the receiver blocks until a message comes. How the consumer gets the message from the messaging system is a detail of the implementation; the application only knows that it gets no message until it asks.1
Three ways to wait. Messaging APIs usually have a receive that blocks until a message comes, and calls that return at once when there is none.1 Camel's PollingConsumer has receive(), which "Waits until a message is available and then returns it; potentially blocking forever", receive(long), which waits up to a timeout, and receiveNoWait(), which returns at once.4
Short and long polling. Each call is a request to the broker. With short polling, Amazon SQS answers at once, even when it finds no message. With long polling, it waits until at least one message is there, or until the wait time ends; the longest wait is 20 seconds. Long polling has fewer empty responses, and this can lower the cost.5 The program below compares three consumers on the same minute with four messages.
# Four messages arrive in one minute. Three consumers poll the same queue.
arrivals = [3.2, 3.4, 15.5, 41.7]
END = 60.0
def short_poll(interval):
requests, empty, delays = 0, 0, []
queue = list(arrivals)
t = 0.0
while t < END:
requests += 1
got = [a for a in queue if a <= t]
queue = [a for a in queue if a > t]
if not got:
empty += 1
delays += [t - a for a in got]
t += interval
return requests, empty, delays
def long_poll(wait):
requests, empty, delays = 0, 0, []
queue = list(arrivals)
t = 0.0
while t < END:
requests += 1
nxt = [a for a in queue if a <= t + wait]
if not nxt:
empty += 1
t += wait
continue
first = min(nxt)
t = max(t, first) # the reply goes out when a message is there
got = [a for a in queue if a <= t]
queue = [a for a in queue if a > t]
delays += [t - a for a in got]
return requests, empty, delays
for name, (requests, empty, delays) in [
("short poll every 1 s", short_poll(1.0)),
("short poll every 10 s", short_poll(10.0)),
("long poll, wait up to 20 s", long_poll(20.0)),
]:
print(f"{name}: {requests} requests, {empty} empty, "
f"{len(delays)} messages, longest delay {max(delays):.1f} s")
short poll every 1 s: 60 requests, 57 empty, 4 messages, longest delay 0.8 s
short poll every 10 s: 6 requests, 3 empty, 4 messages, longest delay 8.3 s
long poll, wait up to 20 s: 6 requests, 2 empty, 4 messages, longest delay 0.0 s
A short poll every second gets each message within a second, but 57 of its 60 requests are empty. A short poll every 10 seconds makes 6 requests, but a message waits up to 8.3 seconds. A long poll makes 6 requests too, with 2 empty ones, and takes each message as soon as it comes.
Example
Each example file polls an in-memory queue. A poll waits up to 300 ms for the first message and then takes at most two, so the consumer decides the size of each batch. The first poll uses no wait and returns at once. Poll 4 starts on an empty queue, and a producer adds one order 50 ms later; the poll returns it at once. Poll 5 finds nothing in 300 ms, and the consumer stops.
import queue
import threading
import time
orders = queue.Queue()
def poll(max_messages, timeout):
"""Wait up to timeout seconds for one message, then take up to max_messages."""
try:
batch = [orders.get(timeout=timeout) if timeout else orders.get_nowait()]
except queue.Empty:
return []
while len(batch) < max_messages:
try:
batch.append(orders.get_nowait())
except queue.Empty:
break
return batch
print("poll 0, no wait:", poll(2, 0) or "empty")
for n in range(1, 6):
orders.put(f"order-{n}")
print("producer: 5 orders on the queue")
late = threading.Timer(0.05, lambda: orders.put("order-6"))
n = 0
while True:
n += 1
if n == 4:
late.start() # a producer sends one more order while the consumer waits
batch = poll(2, 0.3)
if not batch:
print(f"poll {n}: nothing in 300 ms, the consumer stops")
break
print(f"poll {n}:", " ".join(batch), f"({orders.qsize()} left)")
# the consumer works on the batch here, at its own pace
poll 0, no wait: empty
producer: 5 orders on the queue
poll 1: order-1 order-2 (3 left)
poll 2: order-3 order-4 (1 left)
poll 3: order-5 (0 left)
poll 4: order-6 (0 left)
poll 5: nothing in 300 ms, the consumer stops
- Verdict: idiom.
queue.Queue.get(timeout=...)is a blocking receive with a limit, andget_nowaitis the receive with no wait; both raisequeue.Emptywhen there is no message. - The first
getwaits; the next ones do not, so a batch takes only the messages that are already there. threading.Timerplays a producer that sends while the consumer waits in poll 4.
import java.util.*;
import java.util.concurrent.*;
public class Main {
static final BlockingQueue<String> orders = new LinkedBlockingQueue<>();
// Wait up to timeoutMs for one message, then take up to max messages.
static List<String> poll(int max, long timeoutMs) throws InterruptedException {
String first = timeoutMs == 0 ? orders.poll() : orders.poll(timeoutMs, TimeUnit.MILLISECONDS);
List<String> batch = new ArrayList<>();
if (first == null) return batch;
batch.add(first);
orders.drainTo(batch, max - 1);
return batch;
}
public static void main(String[] args) throws InterruptedException {
System.out.println("poll 0, no wait: " + (poll(2, 0).isEmpty() ? "empty" : "?"));
for (int n = 1; n <= 5; n++) orders.add("order-" + n);
System.out.println("producer: 5 orders on the queue");
ScheduledExecutorService producer = Executors.newSingleThreadScheduledExecutor();
for (int n = 1; ; n++) {
if (n == 4) {
// a producer sends one more order while the consumer waits
producer.schedule(() -> orders.add("order-6"), 50, TimeUnit.MILLISECONDS);
}
List<String> batch = poll(2, 300);
if (batch.isEmpty()) {
System.out.println("poll " + n + ": nothing in 300 ms, the consumer stops");
break;
}
System.out.println("poll " + n + ": " + String.join(" ", batch) + " (" + orders.size() + " left)");
// the consumer works on the batch here, at its own pace
}
producer.shutdown();
}
}
poll 0, no wait: empty
producer: 5 orders on the queue
poll 1: order-1 order-2 (3 left)
poll 2: order-3 order-4 (1 left)
poll 3: order-5 (0 left)
poll 4: order-6 (0 left)
poll 5: nothing in 300 ms, the consumer stops
- Verdict: idiom.
BlockingQueue.poll()returnsnullat once, andpoll(timeout, unit)waits up to the timeout; this is the same pair asreceiveNoWait()andreceive(long)in a messaging API. drainTo(batch, max - 1)takes the rest of the batch with no wait.- A
ScheduledExecutorServiceplays a producer that sends while the consumer waits in poll 4.
using System.Collections.Concurrent;
var orders = new BlockingCollection<string>();
// Wait up to timeoutMs for one message, then take up to max messages.
List<string> Poll(int max, int timeoutMs)
{
var batch = new List<string>();
if (!orders.TryTake(out var first, timeoutMs)) return batch;
batch.Add(first);
while (batch.Count < max && orders.TryTake(out var next)) batch.Add(next);
return batch;
}
Console.WriteLine("poll 0, no wait: " + (Poll(2, 0).Count == 0 ? "empty" : "?"));
for (int n = 1; n <= 5; n++) orders.Add($"order-{n}");
Console.WriteLine("producer: 5 orders on the queue");
Timer? late = null;
for (int n = 1; ; n++)
{
if (n == 4)
{
// a producer sends one more order while the consumer waits
late = new Timer(_ => orders.Add("order-6"), null, 50, Timeout.Infinite);
}
var batch = Poll(2, 300);
if (batch.Count == 0)
{
Console.WriteLine($"poll {n}: nothing in 300 ms, the consumer stops");
break;
}
Console.WriteLine($"poll {n}: {string.Join(" ", batch)} ({orders.Count} left)");
// the consumer works on the batch here, at its own pace
}
late?.Dispose();
poll 0, no wait: empty
producer: 5 orders on the queue
poll 1: order-1 order-2 (3 left)
poll 2: order-3 order-4 (1 left)
poll 3: order-5 (0 left)
poll 4: order-6 (0 left)
poll 5: nothing in 300 ms, the consumer stops
- Verdict: idiom.
BlockingCollection<T>.TryTake(out item, timeout)waits up to the timeout, and with a timeout of 0 it returns at once. TryTake(out next)with no timeout fills the rest of the batch from what is already there.- A
System.Threading.Timerplays a producer that sends while the consumer waits in poll 4.
package main
import (
"fmt"
"strings"
"time"
)
var orders = make(chan string, 16)
// poll waits up to timeout for one message, then takes up to limit messages.
func poll(limit int, timeout time.Duration) []string {
var batch []string
if timeout == 0 {
select {
case m := <-orders:
batch = append(batch, m)
default:
return nil
}
} else {
select {
case m := <-orders:
batch = append(batch, m)
case <-time.After(timeout):
return nil
}
}
for len(batch) < limit {
select {
case m := <-orders:
batch = append(batch, m)
default:
return batch
}
}
return batch
}
func main() {
if b := poll(2, 0); b == nil {
fmt.Println("poll 0, no wait: empty")
}
for n := 1; n <= 5; n++ {
orders <- fmt.Sprintf("order-%d", n)
}
fmt.Println("producer: 5 orders on the queue")
for n := 1; ; n++ {
if n == 4 {
// a producer sends one more order while the consumer waits
time.AfterFunc(50*time.Millisecond, func() { orders <- "order-6" })
}
batch := poll(2, 300*time.Millisecond)
if batch == nil {
fmt.Printf("poll %d: nothing in 300 ms, the consumer stops\n", n)
break
}
fmt.Printf("poll %d: %s (%d left)\n", n, strings.Join(batch, " "), len(orders))
// the consumer works on the batch here, at its own pace
}
}
poll 0, no wait: empty
producer: 5 orders on the queue
poll 1: order-1 order-2 (3 left)
poll 2: order-3 order-4 (1 left)
poll 3: order-5 (0 left)
poll 4: order-6 (0 left)
poll 5: nothing in 300 ms, the consumer stops
- Verdict: idiom. A
selectwith adefaultcase is a receive with no wait, and aselectwithtime.Afteris a receive with a timeout. len(orders)gives the number of values in the buffer of the channel, which stands for the depth of the queue.time.AfterFuncplays a producer that sends while the consumer waits in poll 4.
Consequences
Benefits.
- Throttling. The book says that polling gives the best throttling: when the server is busy, it does not call receive, so the messages stay in the queue.3
- Control of the batch. The consumer chooses how many messages it takes in one call.
- Transactions. The book names one polling consumer as the safest way to use a transactional client.3
Liabilities.
- Wasted calls. A poll that finds no message costs a request. In the program, 57 of 60 short polls are empty.
- Delay. A message waits until the next poll; a longer interval means a longer wait.
- A thread for each consumer. A blocking receive holds its thread while it waits.
- False empty responses. An SQS short poll asks only a subset of the servers, so a poll can return no message while the queue has messages. With fewer than 1,000 messages in the queue, a later request returns them.5
When not to use it
When each message must be handled as soon as it comes. An event-driven consumer is called by the messaging system for each message. The book asks: "How can an application automatically consume messages as they become available?" The answer: "The application should use an Event-Driven Consumer", which the messaging system hands each message as it is delivered.6
When there are many channels with few messages. A blocked thread for each channel, or a poll loop for each one, costs more than one callback for each message.
Variants and related patterns
Event-Driven Consumer. The other choice for a receiver. It has no thread of its own until the messaging system calls it with a message. RabbitMQ consumers are event-driven by default, and the EIP site uses one as its example.6 The book lists the choice between the two as a main decision for each message endpoint.3
Event-driven inside, polling outside. Camel's default EventDrivenPollingConsumer receives the messages by events into an internal queue, of 1000 messages by default, and the application polls that queue.4 The book also says that the consumer may or may not poll the messaging system; the application only polls the consumer.1
Competing consumers. A group of Competing Consumers can be polling consumers, so that each one takes a message only when it is free.3
Guarded suspension. In one program, a blocking receive on a queue is a Guarded suspension: the call waits until the condition, a message in the queue, is true.
Known uses
- Apache Camel:
PollingConsumerfromEndpoint.createPollingConsumer(), theConsumerTemplate, and the Poll Enrich EIP, as the Polling Consumer page of 4.14.0 lists.4 - Amazon SQS: each consumer calls
ReceiveMessage;WaitTimeSecondsgreater than 0 makes the call a long poll.5 - JMS-style APIs: a
receivethat blocks, andreceiveNoWait(), which returns at once if no message is there.1
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Polling Consumer (problem and solution under CC BY), problem and solution statements; pattern text
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 10, Messaging Endpoints, Polling Consumer
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Messaging Endpoints, message consumer patterns; message endpoint themes
- Apache Camel 4.14.0 documentation source, Polling Consumer, PollingConsumer API; two kinds of Polling Consumer implementations
- Amazon Simple Queue Service Developer Guide, Amazon SQS short and long polling, whole page
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Event-Driven Consumer (problem and solution under CC BY), problem and solution statements; pattern text; example, RabbitMQ consumer
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 BR46VV Edit this page History Report an error Markdown