Synchronous service-to-service communication means one microservice calls another microservice’s REST API and waits for the response before it continues.It is used when the caller needs the answer immediately, for example to check that a product exists before saving its stock.Spring offers three ways to make these calls: RestClient (fluent and blocking), WebClient (reactive, but it can be used in blocking mode with block()), and OpenFeign (a declarative interface)In this demo, the Inventory service calls the Product service with all three clients, and you choose the client with a request parameter so you can compare them.
Features
- The same remote call is shown with three different clients.
- Every call blocks the caller’s thread until the response arrives.
- Automatic JSON to Java conversion in all three clients.
- Different error handling per client, all mapped to the same 400 and 503 responses.
- GET and POST calls with each client.
- A compare endpoint that runs the same call through all three clients and shows the time taken.
- Each service has its own database and shares data only through APIs.
Synchronous Service-to-Service Communication Types
The three clients
| Client | Style | Dependency | Best for |
|---|---|---|---|
RestClient |
Fluent API, blocking | spring-boot-starter-web |
Normal MVC applications, simple and readable calls |
WebClient |
Fluent API, reactive (blocking with block()) |
spring-boot-starter-webflux |
Apps that also need non-blocking calls or streaming |
| OpenFeign | Declarative interface | spring-cloud-starter-openfeign |
Many calls to the same service with less code |
Comparison
| Point | RestClient | WebClient | OpenFeign |
|---|---|---|---|
| Code you write | Request builder in the service | Request builder in the service | Only an interface |
| Return type | Plain object | Mono or Flux, then block() here |
Plain object |
| 404 error | HttpClientErrorException.NotFound |
WebClientResponseException.NotFound |
FeignException.NotFound |
| Service down | ResourceAccessException |
WebClientRequestException |
RetryableException |
| Timeouts and logging | Set on the request factory | Set on the HTTP connector | Set in application.properties |
Synchronous vs asynchronous communication
| Type | Meaning | Example |
|---|---|---|
| Synchronous | The caller waits for the response | REST call with RestClient, Feign, or WebClient + block() |
| Asynchronous | The caller does not wait | Messaging (Kafka, RabbitMQ) or non-blocking WebClient |
When to use which
| Situation | Choice |
|---|---|
| A simple call in a normal Spring MVC service | RestClient |
| Many endpoints of the same service, with clean code | OpenFeign |
| Reactive application or non-blocking calls | WebClient |
Hands-on Experiment: Create a Product and Inventory Management System Using RestClient, WebClient, and OpenFeign
Aim: To create two Spring Boot microservices (Product and Inventory) where the Inventory service calls the Product service synchronously with RestClient, WebClient, and OpenFeign, with the data stored in MySQL.
The following steps are involved in developing this hands-on experiment.
- Step 1: Generate the Project
- Step 2: Project Structure
- Step 3: Create Product Micro Service
- Step 4: Create Inventory Micro Service with the Three Clients
- Step 5: Run the Application
Step-by-Step Application Development
Step 1: Generate the Project
Use Spring Initializr with:
- Project: Maven
- Language: Java
- Spring Boot version: 3.3.x (latest stable)
- Group: com.example
- Artifact: sync-communication-demo (parent), with modules
product-serviceandinventory-service - Packaging: Jar
- Java version: 17
- Dependencies for product-service: Spring Web, Spring Data JPA, MySQL Driver
- Dependencies for inventory-service: Spring Web, Spring Reactive Web (this provides
WebClient), OpenFeign, Spring Data JPA, MySQL Driver
Download the generated ZIPs and place both services as modules inside one parent folder sync-communication-demo. The ready-made multi-module project is also in the zip.
Step 2: Project Structure

Step 3: Create Product Micro Service
package com.example.productservice.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String category;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal price;
public Product() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
}
package com.example.productservice.repository;
import com.example.productservice.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
package com.example.productservice.service;
import com.example.productservice.entity.Product;
import com.example.productservice.repository.ProductRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Product createProduct(Product product) {
product.setId(null);
return productRepository.save(product);
}
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Optional<Product> getProductById(Long id) {
return productRepository.findById(id);
}
public Optional<Product> updateProduct(Long id, Product updated) {
return productRepository.findById(id).map(existing -> {
existing.setName(updated.getName());
existing.setCategory(updated.getCategory());
existing.setPrice(updated.getPrice());
return productRepository.save(existing);
});
}
}
package com.example.productservice.controller;
import com.example.productservice.entity.Product;
import com.example.productservice.service.ProductService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
// POST /api/products
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
return ResponseEntity.status(HttpStatus.CREATED).body(productService.createProduct(product));
}
// GET /api/products
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
// GET /api/products/{id}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
return productService.getProductById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
// PUT /api/products/{id}
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
return productService.updateProduct(id, product)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
package com.example.productservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
spring.application.name=product-service
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/sync_product_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.error.include-message=alwaysCode language: PHP (php)
Step 4: Create Inventory Micro Service with the Three Clients
package com.example.inventoryservice.entity;
import jakarta.persistence.*;
// The inventory context stores only the productId (no JPA relationship across services)
@Entity
@Table(name = "inventory")
public class InventoryItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private Long productId;
@Column(nullable = false)
private Integer quantity;
private String location;
public InventoryItem() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getProductId() { return productId; }
public void setProductId(Long productId) { this.productId = productId; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
public String getLocation() { return location; }
public void setLocation(String location) { this.location = location; }
}
package com.example.inventoryservice.repository;
import com.example.inventoryservice.entity.InventoryItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface InventoryRepository extends JpaRepository<InventoryItem, Long> {
boolean existsByProductId(Long productId);
}
package com.example.inventoryservice.service;
import com.example.inventoryservice.entity.InventoryItem;
import com.example.inventoryservice.repository.InventoryRepository;
import feign.FeignException;
import feign.RetryableException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ResponseStatusException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
public class InventoryService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP_TYPE =
new ParameterizedTypeReference<Map<String, Object>>() {
};
private static final ParameterizedTypeReference<List<Map<String, Object>>> LIST_TYPE =
new ParameterizedTypeReference<List<Map<String, Object>>>() {
};
private final InventoryRepository inventoryRepository;
private final ProductClient productClient; // 3. OpenFeign (declarative)
private final RestClient productRestClient; // 1. RestClient (fluent, synchronous)
private final WebClient productWebClient; // 2. WebClient (reactive, used in blocking mode)
public InventoryService(InventoryRepository inventoryRepository,
ProductClient productClient,
@Value("${product.service.url}") String productServiceUrl) {
this.inventoryRepository = inventoryRepository;
this.productClient = productClient;
this.productRestClient = RestClient.builder().baseUrl(productServiceUrl).build();
this.productWebClient = WebClient.builder().baseUrl(productServiceUrl).build();
}
// ======================= Local operations =======================
public List<InventoryItem> getAllInventory() {
return inventoryRepository.findAll();
}
public Optional<InventoryItem> getInventoryById(Long id) {
return inventoryRepository.findById(id);
}
public InventoryItem addStock(Long id, int quantity) {
if (quantity <= 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "quantity must be greater than 0");
}
InventoryItem item = findItem(id);
item.setQuantity(item.getQuantity() + quantity);
return inventoryRepository.save(item);
}
public InventoryItem reduceStock(Long id, int quantity) {
InventoryItem item = findItem(id);
if (quantity <= 0 || item.getQuantity() < quantity) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
"Insufficient stock. Available: " + item.getQuantity());
}
item.setQuantity(item.getQuantity() - quantity);
return inventoryRepository.save(item);
}
// ======================= Operations that call product-service =======================
// Create inventory for an EXISTING product (product is validated with the chosen client)
public InventoryItem createInventory(InventoryItem request, String client) {
if (request.getProductId() == null || request.getQuantity() == null || request.getQuantity() < 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
"productId and a non-negative quantity are required");
}
fetchProduct(request.getProductId(), client);
if (inventoryRepository.existsByProductId(request.getProductId())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
"Inventory already exists for product id " + request.getProductId());
}
request.setId(null);
return inventoryRepository.save(request);
}
// Create a NEW product (POST through the chosen client) and its inventory record
public Map<String, Object> createProductWithStock(Map<String, Object> request, String client) {
if (request.get("name") == null || request.get("price") == null || request.get("quantity") == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "name, price and quantity are required");
}
Map<String, Object> productRequest = new LinkedHashMap<>();
productRequest.put("name", request.get("name"));
productRequest.put("category", request.get("category"));
productRequest.put("price", request.get("price"));
Map<String, Object> product = createProduct(productRequest, client);
InventoryItem item = new InventoryItem();
item.setProductId(Long.valueOf(String.valueOf(product.get("id"))));
item.setQuantity(Integer.valueOf(String.valueOf(request.get("quantity"))));
item.setLocation(request.get("location") == null ? null : String.valueOf(request.get("location")));
return toResponse(inventoryRepository.save(item), product, client);
}
// One inventory record + product details
public Map<String, Object> getInventoryWithProduct(Long id, String client) {
InventoryItem item = findItem(id);
return toResponse(item, fetchProduct(item.getProductId(), client), client);
}
// All inventory records + product details (ONE call for all products, joined in memory)
public List<Map<String, Object>> getAllInventoryWithProducts(String client) {
List<InventoryItem> items = inventoryRepository.findAll();
List<Map<String, Object>> products = fetchAllProducts(client);
Map<Long, Map<String, Object>> productMap = new HashMap<>();
for (Map<String, Object> product : products) {
productMap.put(Long.valueOf(String.valueOf(product.get("id"))), product);
}
return items.stream()
.map(item -> toResponse(item, productMap.get(item.getProductId()), client))
.toList();
}
// Call the same endpoint with all three clients and measure the time of each
public Map<String, Object> compareClients(Long id) {
InventoryItem item = findItem(id);
Map<String, Object> result = new LinkedHashMap<>();
for (String client : List.of("restclient", "webclient", "feign")) {
long start = System.nanoTime();
Map<String, Object> product = fetchProduct(item.getProductId(), client);
long millis = (System.nanoTime() - start) / 1_000_000;
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("productName", product.get("name"));
entry.put("timeMs", millis);
result.put(client, entry);
}
return result;
}
// ======================= The three clients =======================
private Map<String, Object> fetchProduct(Long productId, String client) {
try {
return switch (normalize(client)) {
case "restclient" -> productRestClient.get()
.uri("/api/products/{id}", productId)
.retrieve()
.body(MAP_TYPE);
case "webclient" -> productWebClient.get()
.uri("/api/products/{id}", productId)
.retrieve()
.bodyToMono(MAP_TYPE)
.block(); // block() makes the reactive call synchronous
case "feign" -> productClient.getProductById(productId);
default -> throw unsupportedClient(client);
};
} catch (HttpClientErrorException.NotFound | WebClientResponseException.NotFound
| FeignException.NotFound e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Product not found with id " + productId);
} catch (ResourceAccessException | WebClientRequestException | RetryableException e) {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Product service is unavailable");
}
}
private List<Map<String, Object>> fetchAllProducts(String client) {
try {
return switch (normalize(client)) {
case "restclient" -> productRestClient.get()
.uri("/api/products")
.retrieve()
.body(LIST_TYPE);
case "webclient" -> productWebClient.get()
.uri("/api/products")
.retrieve()
.bodyToMono(LIST_TYPE)
.block();
case "feign" -> productClient.getAllProducts();
default -> throw unsupportedClient(client);
};
} catch (ResourceAccessException | WebClientRequestException | RetryableException e) {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Product service is unavailable");
}
}
private Map<String, Object> createProduct(Map<String, Object> productRequest, String client) {
try {
return switch (normalize(client)) {
case "restclient" -> productRestClient.post()
.uri("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.body(productRequest)
.retrieve()
.body(MAP_TYPE);
case "webclient" -> productWebClient.post()
.uri("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(productRequest)
.retrieve()
.bodyToMono(MAP_TYPE)
.block();
case "feign" -> productClient.createProduct(productRequest);
default -> throw unsupportedClient(client);
};
} catch (ResourceAccessException | WebClientRequestException | RetryableException e) {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Product service is unavailable");
}
}
// ======================= Helpers =======================
private String normalize(String client) {
return client == null ? "feign" : client.trim().toLowerCase();
}
private ResponseStatusException unsupportedClient(String client) {
return new ResponseStatusException(HttpStatus.BAD_REQUEST,
"Unsupported client '" + client + "'. Use restclient, webclient or feign");
}
private InventoryItem findItem(Long id) {
return inventoryRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
"Inventory not found with id " + id));
}
private Map<String, Object> toResponse(InventoryItem item, Map<String, Object> product, String client) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("inventoryId", item.getId());
response.put("productId", item.getProductId());
response.put("productName", product == null ? null : product.get("name"));
response.put("category", product == null ? null : product.get("category"));
response.put("price", product == null ? null : product.get("price"));
response.put("quantity", item.getQuantity());
response.put("location", item.getLocation());
response.put("fetchedUsing", normalize(client));
return response;
}
}
package com.example.inventoryservice.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import java.util.Map;
// OpenFeign: a declarative client. Only an interface, Spring creates the implementation.
@FeignClient(name = "product-service", url = "${product.service.url}")
public interface ProductClient {
@GetMapping("/api/products/{id}")
Map<String, Object> getProductById(@PathVariable("id") Long id);
@GetMapping("/api/products")
List<Map<String, Object>> getAllProducts();
@PostMapping("/api/products")
Map<String, Object> createProduct(@RequestBody Map<String, Object> product);
}
package com.example.inventoryservice.controller;
import com.example.inventoryservice.entity.InventoryItem;
import com.example.inventoryservice.service.InventoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
// The "client" request parameter selects the HTTP client used to call product-service:
// restclient | webclient | feign (default: feign)
@RestController
@RequestMapping("/api/inventory")
public class InventoryController {
private final InventoryService inventoryService;
public InventoryController(InventoryService inventoryService) {
this.inventoryService = inventoryService;
}
// POST /api/inventory?client=restclient
@PostMapping
public ResponseEntity<InventoryItem> createInventory(@RequestBody InventoryItem item,
@RequestParam(defaultValue = "feign") String client) {
return ResponseEntity.status(HttpStatus.CREATED).body(inventoryService.createInventory(item, client));
}
// POST /api/inventory/products?client=webclient (creates the product in product-service, then its stock)
@PostMapping("/products")
public ResponseEntity<Map<String, Object>> createProductWithStock(
@RequestBody Map<String, Object> request,
@RequestParam(defaultValue = "feign") String client) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(inventoryService.createProductWithStock(request, client));
}
// GET /api/inventory
@GetMapping
public List<InventoryItem> getAllInventory() {
return inventoryService.getAllInventory();
}
// GET /api/inventory/{id}
@GetMapping("/{id}")
public ResponseEntity<InventoryItem> getInventoryById(@PathVariable Long id) {
return inventoryService.getInventoryById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
// GET /api/inventory/{id}/details?client=feign
@GetMapping("/{id}/details")
public Map<String, Object> getInventoryWithProduct(@PathVariable Long id,
@RequestParam(defaultValue = "feign") String client) {
return inventoryService.getInventoryWithProduct(id, client);
}
// GET /api/inventory/with-products?client=webclient
@GetMapping("/with-products")
public List<Map<String, Object>> getAllInventoryWithProducts(
@RequestParam(defaultValue = "feign") String client) {
return inventoryService.getAllInventoryWithProducts(client);
}
// GET /api/inventory/{id}/compare (same call with all three clients, with timing)
@GetMapping("/{id}/compare")
public Map<String, Object> compareClients(@PathVariable Long id) {
return inventoryService.compareClients(id);
}
// PUT /api/inventory/{id}/add-stock?quantity=10
@PutMapping("/{id}/add-stock")
public InventoryItem addStock(@PathVariable Long id, @RequestParam int quantity) {
return inventoryService.addStock(id, quantity);
}
// PUT /api/inventory/{id}/reduce-stock?quantity=5
@PutMapping("/{id}/reduce-stock")
public InventoryItem reduceStock(@PathVariable Long id, @RequestParam int quantity) {
return inventoryService.reduceStock(id, quantity);
}
}
package com.example.inventoryservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class InventoryServiceApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryServiceApplication.class, args);
}
}
spring.application.name=inventory-service
server.port=8082
spring.datasource.url=jdbc:mysql://localhost:3306/sync_inventory_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.error.include-message=always
# URL of the product service (used by RestClient, WebClient and OpenFeign)
product.service.url=http://localhost:8081
# Feign settings (milliseconds) and request/response logging
spring.cloud.openfeign.client.config.default.connect-timeout=3000
spring.cloud.openfeign.client.config.default.read-timeout=5000
spring.cloud.openfeign.client.config.default.logger-level=full
logging.level.com.example.inventoryservice.service.ProductClient=DEBUGCode language: PHP (php)
Step 5: Run the Microservice one by one
i. Product microservice
ii. Inventory microservice







