00:00

Communication in Microservices

Last updated:

In a microservices architecture, an application is divided into small, independent services, each responsible for a specific business function. These services need to communicate with one another to perform business operations, such as processing customer orders, managing payments, and updating inventory. The communication approach directly impacts the application's performance, scalability, reliability, and maintainability.

This tutorial explains how services communicate in a microservices architecture, focusing on the two primary communication styles: synchronous and asynchronous communication.

1. What Is Microservices Communication?

Microservices communication is the process by which independent services exchange data and coordinate with one another to complete business operations. It typically uses synchronous communication, such as REST APIs and gRPC, or asynchronous communication, such as messaging and event-driven systems using Kafka or RabbitMQ. The choice depends on response-time requirements, service dependencies, scalability, and reliability.

2. Challenges of Communication in Microservices

In a monolithic application, components communicate through direct method calls within the same process. In microservices, communication happens over a network, introducing additional complexity, potential failures, and latency. As a result, services must be designed to handle network issues, partial failures, and communication delays.

Method call in a monolithNetwork call between microservices
SpeedNanosecondsMilliseconds, often 100,000 times slower
Can it fail?Practically neverYes: timeouts, dropped connections, crashed services
DataObjects passed directlyData must be serialized, for example to JSON, and parsed again
TransactionsOne database transaction covers everythingNo shared transaction; each service has its own database
ChangesThe compiler checks both sidesBoth sides must agree on an API contract that can drift apart
DebuggingOne stack traceA request spans many services and logs

Good communication design is about accepting these facts and planning for them. The Communication Challenges in Microservices guide looks at each problem in detail.

3. Synchronous vs. Asynchronous Communication in Microservices

Microservices use two communication approaches: synchronous and asynchronous. Each approach differs in how services exchange information, handle responses, and manage dependencies. Understanding these differences helps you choose the right communication method based on your application's requirements.

3.1 Synchronous communication (request–response)

A client service sends a request and then waits for a response before it continues. It is a real-time “ask and wait for an answer” pattern.

  • How it works: the caller blocks, or waits, until it receives a response or the request times out.
  • Common protocols: HTTP/REST is the most widely used; gRPC is popular for its high performance.
  • Best for: situations where the result is needed right away, such as a user waiting for a page to load.
  • Drawback: it creates chains of dependencies. If one service is slow or down, the failure can cascade and make the whole request slow or unresponsive.
Synchronous communication: each caller waits for the answer A chain of synchronous calls. The client sends a request to Order Service and waits. Order Service sends a request to Inventory Service and also waits. Inventory Service answers, then Order Service answers the client. Every caller is blocked until the service below it responds, so one slow service slows the whole chain. Clientbrowser or app Order Servicecalls Inventory Inventory Servicechecks stock HTTP request response REST / gRPC call response The caller sends a request and waits until the answer comes back ⏳ waiting… ⏳ waiting… ⚙ working ✓ got the answer If Inventory Service is slow or down, Order Service and the client wait too Synchronous communication: each caller waits for the answer A chain of synchronous calls. The client sends a request to Order Service and waits. Order Service sends a request to Inventory Service and also waits. Inventory Service answers, then Order Service answers the client. Every caller is blocked until the service below it responds, so one slow service slows the whole chain. Clientbrowser or app Order Servicecalls Inventory Inventory Servicechecks stock HTTP request response REST / gRPC response ⏳ waiting… ⏳ waiting… ⚙ working ✓ answered If Inventory Service is slow or down, Order Service and the client wait too
Synchronous: each caller is blocked until the service it called responds, so delays add up along the chain.

3.2 Asynchronous communication (event-driven)

A service (the publisher) sends a message but does not wait for a response. It announces that “something has happened”. Interested services (subscribers) receive the message and act on it in their own time.

  • How it works: a message broker, such as RabbitMQ, Apache Kafka or Amazon SQS, sits in the middle. The publisher sends a message to the broker, and the broker delivers it to the subscribers.
  • Common patterns: message queues and publish/subscribe (pub/sub).
  • Best for: background processing, tasks that do not need an instant result, and decoupling services to improve resilience.
  • Drawback: the system has more parts, and following a request from start to end takes extra tooling.
Asynchronous communication through a message broker Order Service publishes an OrderPlaced event to a message broker such as Kafka or RabbitMQ and carries on immediately without waiting. The broker delivers the event to each subscriber: Email Service, Inventory Service and Shipping Service. Each subscriber processes it in its own time; Shipping Service is offline at first and catches up when it comes back. The publisher sends an event and carries on; subscribers react in their own time Order Servicepublisher Message broker Kafka / RabbitMQ OrderPlaced Email Servicesends confirmation Inventory Servicereserves stock Shipping Serviceoffline, catches up later ✓ carries on If a subscriber is down, the broker keeps the event until it comes back Asynchronous communication through a message broker Order Service publishes an OrderPlaced event to a message broker such as Kafka or RabbitMQ and carries on immediately without waiting. The broker delivers the event to each subscriber: Email Service, Inventory Service and Shipping Service. Each subscriber processes it in its own time; Shipping Service is offline at first and catches up when it comes back. Order Servicepublisher Message broker Kafka / RabbitMQ OrderPlaced Email Servicesends confirmation Inventory Servicereserves stock Shipping Serviceoffline, catches up later ✓ carries on If a subscriber is down, the broker keeps the event until it comes back
Asynchronous: the publisher hands the event to the broker and carries on; each subscriber processes it when it is ready.
Synchronous (request–response)Asynchronous (event-driven)
How it worksThe caller sends a request and waits for the answerThe sender publishes a message and carries on without waiting
AnalogyA phone callA text message or a letter
Common technologiesHTTP/REST, gRPC, GraphQLApache Kafka, RabbitMQ, Amazon SQS and SNS
CouplingTight: both services must be running at the same timeLoose: the receiver can be offline and catch up later
Best forAnswers needed immediately, such as showing a page or checking stockBackground work and informing other services that something happened
Main drawbackChains of calls: one slow or failed service affects all callersMore moving parts and harder end-to-end tracking

4. Synchronous Communication with REST and gRPC

4.1 Calling a REST API with RestClient

RestClient, available since Spring Framework 6.1 (Spring Boot 3.2), is the modern way to make synchronous HTTP calls in Spring. Always set timeouts, so a slow service cannot block your threads forever:

InventoryClient.java
package com.example.order.client;

import java.time.Duration;

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

@Component
public class InventoryClient {

    private final RestClient restClient;

    public InventoryClient(RestClient.Builder builder) {
        SimpleClientHttpRequestFactory factory =
                new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(Duration.ofSeconds(2));
        factory.setReadTimeout(Duration.ofSeconds(3));

        this.restClient = builder
                .baseUrl("http://localhost:8082")
                .requestFactory(factory)
                .build();
    }

    public boolean reserve(String productId, int quantity) {
        ReservationResponse response = restClient.post()
                .uri("/inventory/reservations")
                .body(new ReservationRequest(productId, quantity))
                .retrieve()
                .body(ReservationResponse.class);

        return response != null && response.reserved();
    }

    public record ReservationRequest(String productId, int quantity) {
    }

    public record ReservationResponse(boolean reserved) {
    }
}

5. Asynchronous Communication with Message Brokers

5.1 Queues and topics

Message queue (point-to-point)Topic (publish/subscribe)
Who receives a message?One consumerEvery subscribed service
Typical useSharing work, such as “resize this image”Announcing events, such as “order confirmed”
AnalogyA ticket queue at a bank counterA radio broadcast

5.2 Publishing an event with Apache Kafka

An event describes something that has already happened. Name it in the past tense, and include the data subscribers will need:

OrderConfirmedEvent.java
package com.example.events;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;

public record OrderConfirmedEvent(
        String eventId,
        String orderId,
        String customerId,
        List<OrderLine> lines,
        BigDecimal total,
        Instant confirmedAt) {

    public record OrderLine(String productId, int quantity) {
    }
}
OrderEventPublisher.java
package com.example.order.messaging;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import com.example.events.OrderConfirmedEvent;

@Component
public class OrderEventPublisher {

    private static final String TOPIC = "order-confirmed";

    private final KafkaTemplate<String, OrderConfirmedEvent> kafkaTemplate;

    public OrderEventPublisher(KafkaTemplate<String, OrderConfirmedEvent> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void publish(OrderConfirmedEvent event) {
        // The order ID is the key, so all events for one order keep their order
        kafkaTemplate.send(TOPIC, event.orderId(), event);
    }
}
application.yml (order service)
spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer

5.3 Subscribing to the event

ShippingEventListener.java
package com.example.shipping.messaging;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import com.example.events.OrderConfirmedEvent;
import com.example.shipping.ShippingService;

@Component
public class ShippingEventListener {

    private final ShippingService shippingService;

    public ShippingEventListener(ShippingService shippingService) {
        this.shippingService = shippingService;
    }

    @KafkaListener(topics = "order-confirmed", groupId = "shipping-service")
    public void onOrderConfirmed(OrderConfirmedEvent event) {
        shippingService.createShipment(event.orderId(), event.lines());
    }
}
application.yml (shipping service)
spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      properties:
        spring.json.trusted.packages: "com.example.events"

The groupId matters. Every different group receives its own copy of each event, so the shipping service and the notification service (with groupId = "notification-service") both get every order. Several instances of the same group share the work instead, which is how a service scales out.

Version note: The JSON serializer class names shown are from Spring for Apache Kafka 3.x (Spring Boot 3). Newer versions also provide Jackson 3 based serializers; check the reference guide for your version. See Asynchronous Communication in Microservices and Event-Driven Architecture for more.

6. One-to-One and One-to-Many Interactions

Communication can also be described by how many receivers a message has:

PatternReceiversStyleExample
Request–responseOneSynchronousOrder service asks inventory: “Is product 123 in stock?”
Asynchronous request–responseOneAsynchronousSend “generate invoice” and receive “invoice ready” later on a reply queue
One-way notificationOneAsynchronous“Resize this uploaded image” put on a work queue
Publish/subscribeManyAsynchronous“Order confirmed” received by shipping, notifications and analytics

7. A Practical Example: The E-Commerce Order Flow

Let us walk through placing an order in an online store built with microservices.

Services involved:

  • Order service: manages order creation and status.
  • Inventory service: tracks product stock levels.
  • Payment service: handles card payments.
  • Shipping service: arranges delivery.
  • Notification service: sends emails and alerts to the customer.

Step 1: the user clicks “Place Order” (synchronous)

  1. The front end sends a request to the order service to create a new order.
  2. The order service makes a synchronous call to the inventory service: “Are 2 units of product 123 available?” Answer: “Yes, they are reserved for you.”
  3. It then makes another synchronous call to the payment service: “Charge this customer $50.00.” Answer: “Payment successful. Transaction ID: TXN789.”
  4. Only after both succeed does the order service mark the order as confirmed and reply to the browser: “Your order was successful!”

Step 2: handling the aftermath (asynchronous)

  1. The order service publishes an OrderConfirmed event to the message broker. Its job is now done; it does not know or care who listens.
  2. The shipping service receives the event, creates a shipping label and schedules a courier pickup.
  3. The notification service receives the same event and emails the customer an order summary.
The e-commerce order flow: a synchronous step, then an asynchronous step Placing an order. Step 1 is synchronous and the customer waits: the browser asks Order Service to place the order, Order Service asks Inventory Service to reserve stock, then asks Payment Service to charge the card, and only after both succeed does it tell the browser the order was successful. Step 2 is asynchronous: Order Service publishes an OrderConfirmed event to a message broker and is done; Shipping Service books a courier and Notification Service emails the customer in the background. STEP 1 · Place order (synchronous): the customer waits STEP 2 · Aftermath (asynchronous): happens in the background Browserthe customer Order Servicecreates the order Inventory Servicereserves stock Payment Servicecharges the card Message broker Kafka / RabbitMQ Shipping Servicebooks a courier Notification Serviceemails the customer ① place order ④ order successful ② reserve stock ③ charge $50 ⑤ OrderConfirmed event ⑥ ⏳ waiting… ✓ order successful ① The browser asks Order Service to place the order ② Order Service reserves stock with Inventory Service and waits ③ Order Service charges the card through Payment Service and waits ④ Both succeeded, so the customer sees "Your order was successful!" ⑤ Order Service publishes an OrderConfirmed event and is done ⑥ Shipping and Notification react in the background Step 1 (stock and payment) is synchronous; step 2 (shipping and email) is asynchronous The e-commerce order flow: a synchronous step, then an asynchronous step Placing an order. Step 1 is synchronous and the customer waits: the browser asks Order Service to place the order, Order Service asks Inventory Service to reserve stock, then asks Payment Service to charge the card, and only after both succeed does it tell the browser the order was successful. Step 2 is asynchronous: Order Service publishes an OrderConfirmed event to a message broker and is done; Shipping Service books a courier and Notification Service emails the customer in the background. STEP 1 · Place order (synchronous) the customer waits STEP 2 · Aftermath (asynchronous) happens in the background Browserthe customer Order Servicecreates the order Inventoryreserves stock Paymentcharges the card Message broker Kafka / RabbitMQ Shippingbooks a courier Notificationemails the customer ① order ④ answer ② ③ ⑤ OrderConfirmed ⑥ ⏳ waiting ✓ success ① The browser asks Order Serviceto place the order ② Order Service reserves stockwith Inventory Service and waits ③ Order Service charges the cardthrough Payment Service and waits ④ Both succeeded: the customer sees"Your order was successful!" ⑤ Order Service publishes anOrderConfirmed event and is done ⑥ Shipping and Notification reactin the background Step 1 (stock, payment) is synchronous;step 2 (shipping, email) is asynchronous
Step 1 uses synchronous calls because the customer needs the result now.
Step 2 uses an event because shipping and email can happen later.

This hybrid approach is very common. Synchronous calls are used where an immediate answer is essential, and asynchronous events decouple the follow-up steps. If the shipping service is temporarily down, the OrderConfirmed event simply waits in the broker until it comes back, so a shipping problem never stops customers from placing orders.

Keep it simple, but know the gaps: This example leaves out what happens if payment fails after stock was reserved, or if the application crashes between saving the order and publishing the event. Section 12 explains the patterns that handle these cases.

8. Choosing Between Synchronous and Asynchronous Communication

Choosing between synchronous and asynchronous communication in microservices depends on the business requirements, response time, and reliability needs. Use the following questions to determine which communication style is most suitable for your use case.

Business scenarioIf yes, prefer
Does the caller need the response to continue right now?Synchronous
Is a user waiting on screen for this exact result?Synchronous
Can the work happen a few seconds or minutes later?Asynchronous
Do several services need to react to the same thing?Asynchronous (publish/subscribe)
Must the work survive the receiver being down for a while?Asynchronous
Is the work slow or heavy, such as reports, video or bulk email?Asynchronous
Do you need to absorb sudden traffic spikes?Asynchronous (the queue acts as a buffer)

9. Resilience Patterns for Reliable Microservice Communication

Reliable communication is essential in microservices because network failures, service outages, and traffic spikes can occur at any time. To maintain system stability and prevent cascading failures, use resilience patterns that handle failures gracefully, control resource consumption, and ensure requests are processed safely. The following techniques help make inter-service communication more reliable.

TechniqueProtects againstLearn more
TimeoutsWaiting forever for a slow serviceTimeout pattern
Retries with backoffShort, temporary failuresRetry pattern
Circuit breakerHammering a service that is already failingCircuit breaker pattern
BulkheadOne slow dependency using up all threadsBulkhead pattern
Rate limitingToo many requests overloading a serviceRate limiting pattern
IdempotencyDuplicate requests or messages causing duplicate effectsSection 11.2 below

9.1 Retry and circuit breaker with Resilience4j

StockChecker.java
package com.example.order.client;

import org.springframework.stereotype.Component;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;

@Component
public class StockChecker {

    private final InventoryApi inventoryApi;

    public StockChecker(InventoryApi inventoryApi) {
        this.inventoryApi = inventoryApi;
    }

    // Reading stock is safe to retry; it changes nothing
    @Retry(name = "inventory")
    @CircuitBreaker(name = "inventory", fallbackMethod = "stockUnknown")
    public StockStatus check(String productId) {
        return inventoryApi.getStock(productId);
    }

    // Used when the inventory service is down or the circuit is open
    private StockStatus stockUnknown(String productId, Throwable ex) {
        return StockStatus.unknown(productId);
    }
}
application.yml
resilience4j:
  retry:
    instances:
      inventory:
        max-attempts: 3
        wait-duration: 500ms
  circuitbreaker:
    instances:
      inventory:
        sliding-window-size: 10
        failure-rate-threshold: 50
        wait-duration-in-open-state: 30s

These annotations need the resilience4j-spring-boot3 dependency (or Spring Cloud Circuit Breaker) together with Spring AOP.

9.2 Idempotent message handling

Most brokers guarantee at-least-once delivery: a message can arrive more than once, for example after a restart. Consumers must therefore be idempotent, meaning that handling the same message twice has the same effect as handling it once:

NotificationEventListener.java
package com.example.notification.messaging;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.example.events.OrderConfirmedEvent;
import com.example.notification.EmailService;
import com.example.notification.ProcessedEvent;
import com.example.notification.ProcessedEventRepository;

@Component
public class NotificationEventListener {

    private final ProcessedEventRepository processedEvents;
    private final EmailService emailService;

    public NotificationEventListener(ProcessedEventRepository processedEvents, EmailService emailService) {
        this.processedEvents = processedEvents;
        this.emailService = emailService;
    }

    @KafkaListener(topics = "order-confirmed", groupId = "notification-service")
    @Transactional
    public void onOrderConfirmed(OrderConfirmedEvent event) {
        // Skip events we have already handled
        if (processedEvents.existsById(event.eventId())) {
            return;
        }
        emailService.sendOrderConfirmation(event.customerId(), event.orderId());
        processedEvents.save(new ProcessedEvent(event.eventId()));
    }
}

10. Best Practices

  1. Prefer asynchronous events for anything that does not need an immediate answer.
  2. Keep synchronous call chains short; avoid one request triggering a long chain of calls.
  3. Set a timeout on every remote call, and add retries and circuit breakers where they make sense.
  4. Retry only safe operations, or use idempotency keys for operations that change data.
  5. Make message consumers idempotent, because messages can arrive more than once.
  6. Design events carefully: past-tense names, a unique event ID, and the data subscribers need.
  7. Use the outbox pattern when saving data and publishing an event must both happen.
  8. Keep contracts backward compatible, and version breaking changes.
  9. Use service discovery rather than fixed addresses.
  10. Add distributed tracing and correlation IDs from the start.
  11. Secure internal traffic too, with tokens or mutual TLS, not only the public edge.

11. Common Mistakes to Avoid

Avoid these common mistakes when designing communication between microservices. They can lead to performance bottlenecks, cascading failures, data inconsistency, and increased operational complexity. Following best practices helps build reliable, scalable, and maintainable microservices.

MistakeWhat goes wrongBetter approach
Making everything synchronousA chain of calls is only as reliable as its weakest serviceUse events for follow-up work
No timeoutsThreads pile up waiting, and the caller crashes tooSet connect and read timeouts on every client
Retrying payments blindlyCustomers are charged twiceUse idempotency keys and retry only safe calls
Chatty servicesOne page needs dozens of calls, so it is slowReturn the data callers need in fewer calls, or aggregate
Sharing a database between servicesServices become tightly coupled through tablesEach service owns its data and exposes it through APIs or events
Events that carry too little dataEvery subscriber calls back to the publisher for detailsInclude the fields subscribers need
Ignoring duplicate messagesDuplicate emails, shipments or chargesTrack processed event IDs
Breaking API changes without versionsOther services fail after a deploymentAdd fields compatibly; version breaking changes

12. Summary

Microservices communication is the nervous system that lets a distributed application work as one. Synchronous communication, using REST or gRPC, suits requests that need an immediate answer. Asynchronous communication, using brokers such as Kafka or RabbitMQ, decouples services and keeps the system working when parts fail. Most real systems combine both: query synchronously, react asynchronously. Protect every call with timeouts, retries and circuit breakers, make consumers idempotent, keep data consistent with sagas and the outbox pattern, and trace requests across services. With these practices, your services stay independent while working together reliably. Continue with Synchronous Communication and Asynchronous Communication for deeper dives.