How to Communicate Between Services Sync or Async in Java
Choose synchronous requests or asynchronous messages between Java services based on whether the caller needs an answer now, and design for failure either way.

Every time one service needs another, you choose between asking and telling. Asking is a synchronous call: send a request, wait for the answer. Telling is an asynchronous message: publish a fact and move on. The choice shapes failure behavior, latency and the amount of code, and it is easier to change early than late. This post gives a way to choose. The protocol options are compared in REST vs GraphQL vs gRPC.
Synchronous: ask and wait
Stock stock = inventoryClient.get()
.uri("/stock/{sku}", sku)
.retrieve()
.body(Stock.class);The caller blocks until the answer arrives. Benefits: simple to reason about, immediate feedback, easy to test and trace. Costs: availability multiplies (if each of three services is up 99.9 percent of the time, a chain of all three is about 99.7 percent), latencies add, and a slow callee ties up the caller's threads, the failure in timeouts between services.
Use it when:
- The caller needs the result to continue (a price lookup before showing a cart).
- A user is waiting for an answer.
- The operation is a query with no side effects.
Asynchronous: tell and move on
kafka.send("orders", order.id(), new OrderPlaced(order.id(), order.totalCents()));The publisher records that something happened; consumers react in their own time. Benefits: the publisher does not depend on consumers being up, spikes are absorbed by the broker, and adding a consumer needs no change to the publisher. Costs: the system is eventually consistent, a request cannot return the result of a downstream effect, debugging a flow means following messages across services, and consumers see duplicates. See Kafka topics, keys and partitions and reliable consumers.
Use it when:
- The work can happen after the response (sending an email, updating a search index).
- Several services care about the same event.
- The receiver may be unavailable or slow.
- You need to smooth bursts of load.
Commands, queries and events
| Kind | Example | Usual style |
|---|---|---|
| Query | Get stock for a SKU | Sync |
| Command | Reserve stock | Sync if the caller needs success or failure; async if it can be queued |
| Event | OrderPlaced | Async |
An event describes the past and has no single recipient. A command asks for something and expects it to be done. Sending commands over a message queue is fine, and treating a queue as a way to hide a request-response flow that really needs an answer produces correlation-id plumbing.
Handling failure in each style
Sync: set a connect and read timeout, retry only idempotent calls with backoff, use a circuit breaker so a dead dependency fails fast, and decide what the caller does when the answer never arrives (a cached value, a degraded response, an error).
Async: make the consumer idempotent (the same message can arrive twice), keep a dead-letter topic for messages that cannot be processed, monitor consumer lag, and write the message to the broker reliably. The last part is the dual-write problem: saving to the database and sending to Kafka are two operations, and one can fail. The transactional outbox pattern writes the event to a table in the same transaction and a relay publishes it.
Mixing the two
A typical flow: the user's request arrives synchronously at the order service, which validates, saves the order and publishes OrderPlaced. Billing, inventory and notifications react asynchronously. The user gets a quick "order received" response, and the state converges. For a query that needs data from several services, a gateway or a composition service makes parallel sync calls, or reads from a replicated view built from events.
A decision list
- Does the caller need the answer to proceed? Sync.
- Can the work wait, or is the receiver sometimes down? Async.
- Does more than one service react? Async.
- Is it a query? Sync.
- Not sure? Start sync for simplicity, and make the call idempotent so it can move to async later.
A synchronous client that fails the right way
The synchronous call shown at the top works on a good day. Production needs a timeout, a bounded retry for reads and a breaker that stops hammering a dead dependency. With Resilience4j and Spring Boot the configuration is declarative:
resilience4j:
circuitbreaker:
instances:
inventory:
slidingWindowSize: 20
failureRateThreshold: 50
waitDurationInOpenState: 10s
retry:
instances:
inventory:
maxAttempts: 3
waitDuration: 200ms
retryExceptions:
- java.io.IOException
- org.springframework.web.client.ResourceAccessException@Component
class InventoryClient {
private final RestClient http;
InventoryClient(RestClient.Builder builder) {
var factory = new JdkClientHttpRequestFactory(
HttpClient.newBuilder().connectTimeout(Duration.ofMillis(300)).build());
factory.setReadTimeout(Duration.ofSeconds(1));
this.http = builder.baseUrl("http://inventory").requestFactory(factory).build();
}
@CircuitBreaker(name = "inventory", fallbackMethod = "unknownStock")
@Retry(name = "inventory")
Stock stockFor(String sku) {
return http.get().uri("/stock/{sku}", sku).retrieve().body(Stock.class);
}
Stock unknownStock(String sku, Throwable cause) {
return Stock.unknown(sku); // the caller decides how to show "unknown"
}
}Three decisions are in those lines. The retry applies only to a call that is a read, because retrying a POST that may have succeeded creates duplicates. The timeouts are short, since a caller that waits 30 seconds for an answer has already lost the user. And the fallback returns an explicit "unknown" value rather than zero, because a fabricated zero would tell the shop the item is out of stock when the truth is that nobody knows.
The dual-write problem and the outbox
The asynchronous example above hides a trap. Saving the order and publishing the event are two operations on two systems, and a crash between them loses one:
@Transactional
public Order place(CreateOrder request) {
Order order = orders.save(Order.from(request));
kafka.send("orders", order.id(), new OrderPlaced(order.id())); // not part of the transaction
return order;
}If the commit fails after the send, consumers hear about an order that does not exist. If the send fails after the commit, the order exists and nobody learns of it. The outbox pattern fixes this by writing the event to a table in the same transaction and publishing it separately:
@Transactional
public Order place(CreateOrder request) {
Order order = orders.save(Order.from(request));
outbox.save(new OutboxEvent("orders", order.id(), toJson(new OrderPlaced(order.id()))));
return order;
}
@Component
class OutboxPublisher {
@Scheduled(fixedDelay = 500)
@Transactional
void publish() {
for (OutboxEvent event : outbox.findTop100ByPublishedAtIsNullOrderByIdAsc()) {
kafka.send(event.topic(), event.key(), event.payload()).join();
event.markPublished(Instant.now());
}
}
}Both writes commit together or not at all. The publisher may send an event twice, if it crashes after send and before the row is marked, so consumers must tolerate duplicates. That is the price, and it is a better one than lost events. A change-data-capture connector reading the outbox table is the production-grade version of the same idea.
An idempotent consumer
Because delivery is at least once, the consumer needs to recognize a message it has already handled. The simplest reliable form records processed message ids in the same transaction as the effect:
@KafkaListener(topics = "orders", groupId = "billing")
@Transactional
void on(ConsumerRecord<String, OrderPlaced> record) {
String messageId = record.topic() + "-" + record.partition() + "-" + record.offset();
if (processed.existsById(messageId)) {
return; // seen before, do nothing
}
invoices.save(Invoice.forOrder(record.value()));
processed.save(new ProcessedMessage(messageId));
}A unique constraint on the id makes the check race-safe: two concurrent deliveries cannot both insert. Prefer a business key (the order id) over the offset when the same event can be republished with a new offset, as the outbox publisher may do.
Messages that cannot be processed
A message that always fails will block a partition if the consumer retries forever. Retry a few times with a delay, then move it to a dead-letter topic where a person can look at it:
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template);
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3));
}Alert on the dead-letter topic's depth and on consumer lag, because those two numbers are the asynchronous equivalent of an error rate. A quiet dead-letter topic is a sign that failures are being handled, and a growing one is an incident that has not yet reached a user.
Where this does not apply
Inside a single service or a modular monolith, in-process method calls and events do the same job without a network. The Enterprise Integration Patterns catalog and the Spring for Apache Kafka reference are the primary sources.


