Performance: Service-to-service communication
This affects the speed and responsiveness of backend interactions that impact frontend load times and user experience.
Jump into concepts and practice - no test required
private final WebClient webClient = WebClient.create(); Mono<String> response = webClient.get().uri("http://service/api/data").retrieve().bodyToMono(String.class);
RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject("http://service/api/data", String.class);
| Pattern | Thread Usage | Latency Impact | Network Cost | Verdict |
|---|---|---|---|---|
| Synchronous RestTemplate per call | Blocks thread | High latency | Medium | [X] Bad |
| Non-blocking WebClient with pooling | Non-blocking | Low latency | Medium | [OK] Good |
| Sequential service calls | Blocks threads sequentially | High cumulative latency | Medium | [X] Bad |
| Parallel reactive calls | Non-blocking | Low cumulative latency | Medium | [OK] Good |
| Large payloads | N/A | High latency | High | [X] Bad |
| Minimal DTOs with compression | N/A | Low latency | Low | [OK] Good |
RestTemplate bean in Spring Boot for service-to-service calls?WebClient client = WebClient.create("http://service-b/api/greet");
String response = client.get()
.retrieve()
.bodyToMono(String.class)
.block();
System.out.println(response);block() method waits for the response synchronously and returns the body content.@Autowired
private RestTemplate restTemplate;
public String callService() {
String url = "http://service-c/api/data";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}timeout(Duration.ofSeconds(2)) to limit wait time and onErrorReturn to provide fallback on errors.block(Duration) which times out and throws an exception instead of providing a fallback; RestTemplate restTemplate = new RestTemplate();
restTemplate.setTimeout(2000);
String result = restTemplate.getForObject("http://service-d/api", String.class); tries to set timeout on RestTemplate incorrectly; WebClient client = WebClient.builder()
.baseUrl("http://service-d/api")
.build();
String result = client.get()
.retrieve()
.bodyToMono(String.class)
.block(); lacks timeout and error handling.