Patterncore
Request-Reply
Also called Request-Reply pattern, request-response, request/reply, RPC over messaging.
Request-Reply is a pair of messages on two channels: a requestor sends a request with a return address, and the replier sends the answer to that address. It gives two-way talk over one-way messages.
- Family
- integration
- Intent
- Get an answer from another program over messaging, by a request message that names a reply channel and a reply message that the replier sends on that channel.
- Also called
- request-response, request/reply
Intent
Get an answer over messaging. A message goes one way, from a sender to a receiver, but a program often needs a result. The book asks: "When an application sends a message, how can it get a response from the receiver?"12 The answer: "Send a pair of Request-Reply messages, each on its own channel."1
Problem
A web shop must show the price of an item, and the prices are in another program that reads a queue. The web shop can put a request on the queue, but a queue only carries messages away from the sender. The price program needs a way to send the answer back, and the web shop needs a way to wait for it.
The forces are these. The price program has many clients, such as the web shop and a mobile app, and it should not need a list of them. A client must not wait for ever when the price program is down. And the answer must go to the client that asked, not to all the clients.
Solution
The requestor sends a request message on a request channel, and the replier sends a reply message on a reply channel. The book gives the two roles: the requestor sends the request and waits for the reply, and the replier gets the request and answers it.1 The request channel can be point-to-point or publish-subscribe, but the reply channel is almost always a Point-to-Point Channel, because only the requestor needs the reply.1
requestor --- request {id: q1, reply_to: replies.web, body: A1} ---> [ prices ] ---> replier
^ |
+------------- reply {correlation_id: q1, body: 1999 cents} <--- [ replies.web ] <-+
A return address. The replier must know where to send the reply. The Return Address pattern answers: "The request message should contain a Return Address that indicates where to send the reply message."3 Then the replier needs no list of its clients, and two clients can get their replies on different channels. In Jakarta Messaging, the address is the header field JMSReplyTo: "It is the destination where a reply to the message should be sent."4 In AMQP 0-9-1, the property reply_to is "Commonly used to name a callback queue."5
A correlation identifier. When a requestor has many requests in progress, the reply must name the request that it answers.6 The page Correlation Identifier gives the details.
Which reply channel. Jakarta Messaging gives "temporary queues and topics that can be used as a unique destination for replies."4 A new queue for each request costs a lot, and RabbitMQ advises: "A better approach is to create a single reply queue per requester and reuse it across requests."7 RabbitMQ also has a special address: "Direct Reply-To lets you implement RPC (request/reply) patterns like those in tutorial 6 without creating a dedicated reply queue".7
How the requestor waits. The book gives two ways.1 In a synchronous block, one thread sends the request and waits for the reply. It is simple, but the thread holds one request at a time. In an asynchronous callback, one thread sends requests, and another thread reads all the replies and runs the callback of each request. Many requests can then share one reply channel.
A timeout. A reply can be late or never come. The RabbitMQ tutorial asks: "Should a client have some kind of timeout for the RPC?"5 In the program below, three requests go to one replier at tick 0, and the requestor waits 3 ticks for each reply.
TIMEOUT = 3 # ticks that the requestor waits for each reply
# Three requests are sent at tick 0. One replier works on them one at a time.
requests = [("r1", 1), ("r2", 5), ("r3", 2)] # the request id and its work in ticks
events = []
t = 0
for rid, work in requests:
t += work
events.append((t, 1, rid, "reply"))
events.append((TIMEOUT, 0, rid, "timeout")) # at a tie, the timeout comes first
pending = {rid for rid, _ in requests}
for tick, _, rid, kind in sorted(events):
if kind == "timeout":
if rid in pending:
pending.discard(rid)
print(f"tick {tick}: {rid} timed out")
elif rid in pending:
pending.discard(rid)
print(f"tick {tick}: reply for {rid}")
else:
print(f"tick {tick}: late reply for {rid}, dropped")
tick 1: reply for r1
tick 3: r2 timed out
tick 3: r3 timed out
tick 6: late reply for r2, dropped
tick 8: late reply for r3, dropped
The slow request r2 times out. The request r3 is fast, but it waits behind r2 in the queue, so it also times out. Both replies come later, and the requestor drops them, because it gave up on those requests. A timeout does not tell the requestor whether the request was lost or only slow: the replier can still do the work.
Example
Each example file has three named channels, as on a broker: prices for the requests, and a reply channel for each of two requestors, web and mobile. A replier thread reads prices and sends each reply to the channel in the reply_to field of the request. Each requestor waits at most 2 seconds for its reply. The third request asks for an unknown item, and the reply carries the error, so that the requestor does not wait for nothing.
import queue
import threading
PRICES = {"A1": 1999, "B2": 500}
# Named channels, as on a broker: one request channel and one reply channel for each requestor.
channels = {"prices": queue.Queue(), "replies.web": queue.Queue(), "replies.mobile": queue.Queue()}
def replier():
while (request := channels["prices"].get()) is not None:
sku = request["body"]
if sku in PRICES:
reply = {"correlation_id": request["id"], "body": f"{PRICES[sku]} cents"}
else:
reply = {"correlation_id": request["id"], "body": f"error unknown sku {sku}"}
channels[request["reply_to"]].put(reply) # the return address of the request
def ask(requestor, rid, sku):
reply_to = "replies." + requestor
channels["prices"].put({"id": rid, "reply_to": reply_to, "body": sku})
try:
reply = channels[reply_to].get(timeout=2) # block, but not for ever
except queue.Empty:
return f"{requestor} asked for {sku}: no reply in 2 s"
return f"{requestor} asked for {sku}: {reply['body']}"
worker = threading.Thread(target=replier)
worker.start()
print(ask("web", "q1", "A1"))
print(ask("mobile", "q2", "B2"))
print(ask("web", "q3", "Z9"))
channels["prices"].put(None) # stop the replier
worker.join()
web asked for A1: 1999 cents
mobile asked for B2: 500 cents
web asked for Z9: error unknown sku Z9
- Verdict: idiom. Python has no request-reply channel, but
queue.Queueand a thread give the two channels and the replier. With a broker, the names of the channels are queue names, andreply_tois a property of the message. get(timeout=2)blocks, but it raisesqueue.Emptyafter 2 seconds, so a requestor does not wait for ever.- The replier reads the
reply_tofield of each request and does not know the requestors.Noneon the request channel stops it.
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Main {
record Message(String id, String replyTo, String correlationId, String body) {}
static final Map<String, Integer> PRICES = Map.of("A1", 1999, "B2", 500);
static final Message STOP = new Message("", "", "", "");
// Named channels, as on a broker: one request channel and one reply channel for each requestor.
static final Map<String, BlockingQueue<Message>> CHANNELS = Map.of(
"prices", new LinkedBlockingQueue<>(),
"replies.web", new LinkedBlockingQueue<>(),
"replies.mobile", new LinkedBlockingQueue<>());
static void replier() {
try {
Message request;
while ((request = CHANNELS.get("prices").take()) != STOP) {
var price = PRICES.get(request.body());
var body = price != null ? price + " cents" : "error unknown sku " + request.body();
CHANNELS.get(request.replyTo()).put(new Message("", "", request.id(), body)); // the return address
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static String ask(String requestor, String id, String sku) throws InterruptedException {
var replyTo = "replies." + requestor;
CHANNELS.get("prices").put(new Message(id, replyTo, "", sku));
var reply = CHANNELS.get(replyTo).poll(2, TimeUnit.SECONDS); // block, but not for ever
if (reply == null) {
return requestor + " asked for " + sku + ": no reply in 2 s";
}
return requestor + " asked for " + sku + ": " + reply.body();
}
public static void main(String[] args) throws InterruptedException {
var worker = new Thread(Main::replier);
worker.start();
System.out.println(ask("web", "q1", "A1"));
System.out.println(ask("mobile", "q2", "B2"));
System.out.println(ask("web", "q3", "Z9"));
CHANNELS.get("prices").put(STOP); // stop the replier
worker.join();
}
}
web asked for A1: 1999 cents
mobile asked for B2: 500 cents
web asked for Z9: error unknown sku Z9
- Verdict: idiom. Java has no request-reply channel in the standard library. A
LinkedBlockingQueuefor each channel and a thread for the replier give the pattern in one process. poll(2, TimeUnit.SECONDS)returnsnullwhen no reply comes in 2 seconds, so the requestor can report a timeout.- The message
STOPis compared by reference with!=, so it cannot be mistaken for a real request with the same fields.
using System.Collections.Concurrent;
var prices = new Dictionary<string, int> { ["A1"] = 1999, ["B2"] = 500 };
// Named channels, as on a broker: one request channel and one reply channel for each requestor.
var channels = new Dictionary<string, BlockingCollection<Message>>
{
["prices"] = new(),
["replies.web"] = new(),
["replies.mobile"] = new(),
};
var worker = new Thread(() =>
{
foreach (var request in channels["prices"].GetConsumingEnumerable())
{
var body = prices.TryGetValue(request.Body, out var p) ? $"{p} cents" : $"error unknown sku {request.Body}";
channels[request.ReplyTo].Add(new Message("", "", request.Id, body)); // the return address
}
});
worker.Start();
Console.WriteLine(Ask("web", "q1", "A1"));
Console.WriteLine(Ask("mobile", "q2", "B2"));
Console.WriteLine(Ask("web", "q3", "Z9"));
channels["prices"].CompleteAdding(); // stop the replier
worker.Join();
string Ask(string requestor, string id, string sku)
{
var replyTo = "replies." + requestor;
channels["prices"].Add(new Message(id, replyTo, "", sku));
if (!channels[replyTo].TryTake(out var reply, TimeSpan.FromSeconds(2))) // block, but not for ever
{
return $"{requestor} asked for {sku}: no reply in 2 s";
}
return $"{requestor} asked for {sku}: {reply.Body}";
}
record Message(string Id, string ReplyTo, string CorrelationId, string Body);
web asked for A1: 1999 cents
mobile asked for B2: 500 cents
web asked for Z9: error unknown sku Z9
- Verdict: idiom. .NET has no request-reply channel in the base library. A
BlockingCollectionfor each channel and a thread for the replier give the pattern in one process. TryTakewith aTimeSpanreturnsfalsewhen no reply comes in 2 seconds.CompleteAddingends the loop ofGetConsumingEnumerablein the replier, so the thread stops. MassTransit gives the same pattern over a broker with request clients.
package main
import (
"fmt"
"time"
)
type message struct {
ID, ReplyTo, CorrelationID, Body string
}
var prices = map[string]int{"A1": 1999, "B2": 500}
// Named channels, as on a broker: one request channel and one reply channel for each requestor.
var channels = map[string]chan message{
"prices": make(chan message),
"replies.web": make(chan message, 1),
"replies.mobile": make(chan message, 1),
}
func replier(done chan<- struct{}) {
for request := range channels["prices"] {
body := fmt.Sprintf("error unknown sku %s", request.Body)
if p, ok := prices[request.Body]; ok {
body = fmt.Sprintf("%d cents", p)
}
channels[request.ReplyTo] <- message{CorrelationID: request.ID, Body: body} // the return address
}
close(done)
}
func ask(requestor, id, sku string) string {
replyTo := "replies." + requestor
channels["prices"] <- message{ID: id, ReplyTo: replyTo, Body: sku}
select { // block, but not for ever
case reply := <-channels[replyTo]:
return fmt.Sprintf("%s asked for %s: %s", requestor, sku, reply.Body)
case <-time.After(2 * time.Second):
return fmt.Sprintf("%s asked for %s: no reply in 2 s", requestor, sku)
}
}
func main() {
done := make(chan struct{})
go replier(done)
fmt.Println(ask("web", "q1", "A1"))
fmt.Println(ask("mobile", "q2", "B2"))
fmt.Println(ask("web", "q3", "Z9"))
close(channels["prices"]) // stop the replier
<-done
}
web asked for A1: 1999 cents
mobile asked for B2: 500 cents
web asked for Z9: error unknown sku Z9
- Verdict: idiom. Go has no request-reply channel, but channels and a goroutine give the two channels and the replier.
selectwithtime.Afterwaits for the reply or for 2 seconds, whichever comes first.- In one Go program, the return address can also be a channel value in the request, as in the Go example of the Return Address page; here it is a name, as on a broker.
Consequences
Benefits.
- Answers over messaging. The requestor gets a result and keeps the benefits of a channel: the request waits in a queue when the replier is busy.
- The replier does not know its clients. Each request carries its return address, so new clients need no change in the replier.3
- Many replies on one channel. With callbacks and a correlation identifier, one requestor can have many requests in progress.
Liabilities.
- Waiting. A requestor that waits for a reply is coupled in time to the replier again, as with a remote call. RabbitMQ says: "When in doubt avoid RPC."5
- Timeouts are hard to choose. Too short, and fast requests behind a slow one fail, as in the program above. Too long, and the user waits.
- Late replies. After a timeout, the reply can still come. The requestor must drop it, and the work may already be done, so a second try must be safe to repeat.
- State in the requestor. With callbacks, the requestor must keep a table of the requests in progress and remove an entry after a timeout, or the table grows.
- Errors. The reply must also carry failures, or the requestor waits until the timeout for each error.
When not to use it
When no answer is needed. Send an Event Message or a Command Message and do not wait.
When the answer is needed at once and both programs are always up. A direct call over HTTP or gRPC is simpler than two channels and a correlation table.
For a long chain of steps. RabbitMQ advises: "If you can, you should use an asynchronous pipeline - instead of RPC-like blocking, results are asynchronously pushed to a next computation stage."5
Variants and related patterns
Return Address and Correlation Identifier. The two helper patterns that the book names for the reply.6
Messaging RPC. The request is a Command Message and the reply is a document with a result or an exception.6
Requests to many repliers. On a publish-subscribe request channel, the request goes to all the repliers that are interested, not to one.1
A reply that may not come. A message that is not processed in time can go to a Dead Letter Channel.
Known uses
- RabbitMQ Java client: RpcClient.doCall at v5.22.0 sets
correlationIdandreplyToon each request, waits with a timeout, and on a timeout removes the entry of the request from its table, with the comment "Avoid potential leak."8 - Jakarta Messaging:
JMSReplyTo, temporary queues, and the helper classesQueueRequestorandTopicRequestor.4 - RabbitMQ:
reply_towith a callback queue, and Direct Reply-To with no reply queue.57
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Request-Reply (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 5, Message Construction, Request-Reply and Return Address
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Return Address (problem and solution under CC BY), problem and solution statements; pattern text
- Jakarta Messaging 3.1 specification, 2.16 Request/reply; 3.4.6 JMSReplyTo
- RabbitMQ tutorials, Remote procedure call (RPC), using the Pika Python client, A note on RPC; Callback queue; Summary
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Message Construction, Returning a response
- RabbitMQ documentation, Direct Reply-To, Overview; Motivation
- RabbitMQ Java client v5.22.0 source, RpcClient.java, method doCall, lines 305 to 327
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 8W7TX4 Edit this page History Report an error Markdown