Junior — Middle
How to distinguish between synchronous and asynchronous interaction between services, and what are the main differences?
sobes.tech AI
Answer from AI
Synchronous interaction between services means that the calling service sends a request and waits for a response, blocking further execution until the result is received. Asynchronous interaction is when a service sends a request and continues working without waiting for a response, which may arrive later via callback, event, or message queue.
Main differences:
- Waiting time: In synchronous calls, the client waits for a response; in asynchronous calls, it does not.
- Coupling: Synchronous interaction is more tightly coupled in time, asynchronous is more loosely coupled.
- Error handling: In synchronous cases, errors are handled immediately; in asynchronous, later, upon receiving the response.
- Performance: Asynchrony allows better resource utilization and scalability.
Example of a synchronous call in Java:
String response = restTemplate.getForObject("http://service/api/data", String.class);
System.out.println(response);
Asynchronous example with CompletableFuture:
CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://service/api/data", String.class))
.thenAccept(response -> System.out.println(response));
// main thread is not blocked