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.
More Related questions...