So, as we know, cloud-native applications consist of a collection of microservices that interact with each other, as well as with external systems, through interservice communication techniques.
With the proliferation of microservices and ever-growing business requirements, establishing reliable communication between microservices in cloud-native applications has become one of the most challenging aspects.
Our goal is to demystify these concepts by creating robust connections using a common framework, following best patterns not only within microservices but also with external services.
Primarily, we’ll focus on synchronous and asynchronous communication.
In synchronous communication, one microservice invokes another and expects a response within a specific timeframe. This type of communication often uses patterns such as Request-Response and Remote Procedure Calls (RPC).
For asynchronous communication, microservices communicate by passing messages asynchronously through an intermediary (known as a message broker). We implement this using patterns like queue-based messaging and publisher-subscriber messaging.
In most cases, we end up mixing these patterns.
When building cloud-native applications, we often find that one microservice may need to invoke one or more other microservices and wait for a timely response to complete its business logic. For this kind of microservice, we can use synchronous messaging patterns. In this case, the business logic of a given microservice depends on one or more other microservices or systems.
There are many messaging patterns that can be used to build synchronous communication in a cloud-native application. One of the standard patterns is the “Request-Response” pattern.
Request-Response Pattern :
ntswer this pattern is the most commonly used commincation pattern in cloud natvie applications , as well as in the space of distributed computing at largze , donc this pattern requrie both paryty create a contract and pass data between them
In the Request-Response pattern, one microservice (acting as the client) sends a request to another microservice or system (acting as the server). The client expects to receive a response to complete its operation.
The client sends the request and waits for the response.
Assistant
During this waiting period, the client is blocked (i.e., it cannot proceed with any other work until it receives the response).
The communication channel between the client and the server remains open while the client is waiting for the response. This ensures that the client can receive the response once it's ready.
This pattern is often used for operations where the client needs an immediate response to proceed with its business logic. However, this blocking nature can introduce latency, and if the server is slow or unavailable, it can negatively impact the client’s performance.
In cloud-native applications, this pattern is typically implemented using technologies such as HTTP requests, gRPC, or similar synchronous protocols, where the client makes a request to a server and is blocked until the response is returned.
In the Request-Response pattern, we aim to establish a connection between the client and the server (microservice) to exchange data in a synchronous manner. This data exchange is known as a message. Once the connection is established, the client sends a request for data to the microservice and waits until either:
It receives the response data, or
The maximum time the client intends to wait is reached (known as a timeout).
Q- now let’s move to hands on Tutor using two seperate micrtoserce each one with deffrente buissines logic but have a depencies neeet to espblish a request - resonse syschnose commincatinn
stack : spring boot , spring cloud , github action , docker (if need it )
Q- we need to build to build proof of concept in the context of e-commerce microce archire
Q- give me fitst the roadmap okii
to how to implement his
Absolutely! Building a proof of concept (PoC) for a synchronous Request-Response communication pattern between two microservices within an e-commerce architecture is a great way to understand and implement cloud-native principles. Below is a comprehensive roadmap to guide you through this process using Spring Boot, Spring Cloud, GitHub Actions, and Docker.
Roadmap Overview
Define the Microservices and Their Responsibilities
Set Up the Development Environment
Create Individual Microservices
Service A (Client)
Service B (Server)
Implement Synchronous Request-Response Communication
Containerize Microservices with Docker
Set Up CI/CD Pipeline with GitHub Actions
Testing and Validation
Deployment and Monitoring
1. Define the Microservices and Their Responsibilities
Before diving into development, clearly define the two microservices and their respective business logic within an e-commerce context. For this PoC, let's consider:
Service A: Order Service (Client)
Responsibility: Handles customer orders.
Business Logic: When a new order is placed, it needs to verify product availability by communicating with the Inventory Service.
Service B: Inventory Service (Server)
Responsibility: Manages product inventory.
Business Logic: Provides product availability status when queried by the Order Service.
Diagram:
code
Order Service (Service A) <---- synchronous request-response ----> Inventory Service (Service B)
2. Set Up the Development Environment
Ensure you have the necessary tools and environments set up:
Java Development Kit (JDK) 17+
Spring Boot and Spring Cloud
Maven or Gradle
Docker
Git and GitHub Account
Integrated Development Environment (IDE) like IntelliJ IDEA or VS Code
Spring Cloud Config Client (if using config server)
Spring Data JPA (with H2 Database for simplicity)
Define the Domain Model:
java
@Entity
public class Product {
@Id
private Long id;
private String name;
private int quantity;
// Getters and Setters
}
Create Repository:
java
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Create Service Layer:
java
@Service
public class InventoryService {
@Autowired
private ProductRepository productRepository;
public boolean isProductAvailable(Long productId, int requestedQuantity) {
return productRepository.findById(productId)
.map(product -> product.getQuantity() >= requestedQuantity)
.orElse(false);
}
}
Expose REST Endpoint:
java
@RestController
@RequestMapping("/inventory")
public class InventoryController {
@Autowired
private InventoryService inventoryService;
@GetMapping("/availability")
public ResponseEntity<Boolean> checkAvailability(
@RequestParam Long productId,
@RequestParam int quantity) {
boolean available = inventoryService.isProductAvailable(productId, quantity);
return ResponseEntity.ok(available);
}
}
Spring Cloud Netflix Eureka Client (if using service registry)
Spring Cloud Circuit Breaker (optional for resilience)
Configure Feign Client:
java
@FeignClient(name = "inventory-service", url = "http://localhost:8081")
public interface InventoryClient {
@GetMapping("/inventory/availability")
Boolean checkAvailability(@RequestParam Long productId, @RequestParam int quantity);
}
Create Order Domain Model:
java
public class Order {
private Long orderId;
private Long productId;
private int quantity;
private String status;
// Getters and Setters
}
Create Service Layer:
java
@Service
public class OrderService {
@Autowired
private InventoryClient inventoryClient;
public Order placeOrder(Long productId, int quantity) {
boolean available = inventoryClient.checkAvailability(productId, quantity);
Order order = new Order();
order.setProductId(productId);
order.setQuantity(quantity);
order.setStatus(available ? "Confirmed" : "Rejected");
return order;
}
}
Expose REST Endpoint:
java
4. Implement Synchronous Request-Response Communication
In the above setup:
Order Service (Client) uses Feign Client to make a synchronous HTTP request to the Inventory Service (Server).
The communication is blocking; the Order Service waits for the Inventory Service to respond before proceeding.
Key Points:
Feign Clients simplify HTTP API consumption by abstracting the boilerplate code.
Ensure both services are running and accessible to each other.
Handle possible exceptions and implement timeouts to avoid indefinite blocking.
@FeignClient(name = "inventory-service", url = "http://localhost:8081", fallback = InventoryClientFallback.class)
public interface InventoryClient {
@GetMapping("/inventory/availability")
Boolean checkAvailability(@RequestParam Long productId, @RequestParam int quantity);
}
@Component
public class InventoryClientFallback implements InventoryClient {
@Override
public Boolean checkAvailability(Long productId, int quantity) {
// Default behavior when Inventory Service is down
return false;
}
}
Conclusion
By following this roadmap, you will have a functional proof of concept demonstrating synchronous Request-Response communication between two microservices in an e-commerce architecture. This setup not only illustrates the basic principles but also incorporates modern development practices such as containerization and CI/CD pipelines. From here, you can expand the architecture by adding more services, implementing asynchronous communication patterns, and enhancing resilience and scalability.
Feel free to reach out if you need further assistance or detailed guidance on any of the steps!
Not yet included in a published release.
Seed Initial Data:
Use data.sql to initialize the in-memory database with sample products.
sql
INSERT INTO product (id, name, quantity) VALUES (1, 'Laptop', 50);
INSERT INTO product (id, name, quantity) VALUES (2, 'Smartphone', 100);
Run and Test Inventory Service:
Start the application.
Use Postman or cURL to test the endpoint:
code
GET http://localhost:8081/inventory/availability?productId=1&quantity=5
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping("/place")
public ResponseEntity<Order> placeOrder(@RequestParam Long productId, @RequestParam int quantity) {
Order order = orderService.placeOrder(productId, quantity);
return ResponseEntity.ok(order);
}
}
Run and Test Order Service:
Start the application.
Use Postman or cURL to place an order:
code
POST http://localhost:8080/orders/place?productId=1&quantity=5
Verify that the Order Service communicates with the Inventory Service synchronously and returns the appropriate status.