API / Microservices Design Patterns Interview Questions
What is the Request-Reply (Correlation ID) pattern for async messaging?
The Request-Reply pattern enables synchronous-like request/response semantics over an asynchronous message channel. The requestor sends a message to a request channel, attaches a unique Correlation ID and a reply-to address (a dedicated reply channel or a temporary queue), and waits for a response. The responder processes the request, copies the Correlation ID into its reply, and publishes the response to the reply channel. The requestor matches incoming responses to pending requests using the Correlation ID.
// Requestor
String correlationId = UUID.randomUUID().toString();
Message request = MessageBuilder
.withBody(payload)
.setHeader("correlationId", correlationId)
.setHeader("replyTo", "order-reply-queue")
.build();
requestChannel.send(request);
CompletableFuture<Response> pending = pendingRequests.put(correlationId);
// ... asynchronously wait for response on "order-reply-queue"
// Responder
Message request = requestChannel.receive();
String corrId = request.getHeaders().get("correlationId");
Response resp = processRequest(request.getBody());
Message reply = MessageBuilder.withBody(resp)
.setHeader("correlationId", corrId).build();
replyChannel.send(reply);
// Requestor matches incoming reply
String corrId = reply.getHeaders().get("correlationId");
pendingRequests.complete(corrId, reply.getBody());
The Correlation ID is essential when multiple in-flight requests use the same reply channel: without it, the requestor cannot determine which response corresponds to which request. If two concurrent requests share the same Correlation ID, each requestor will receive the wrong reply or the ID collision will cause a missed response. IDs must therefore be globally unique (UUID v4 is standard) and the pending-request registry must be thread-safe.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
