Synchronous vs asynchronous communication
Mid-level Always asked 7 min
On this page
The question
When do you use synchronous calls between microservices, and when asynchronous messaging?
30-second answer
Use a synchronous call, HTTP or gRPC, when the caller needs the answer to continue, such as checking stock before confirming a checkout. Use asynchronous messaging when it does not: publish an event and let others react in their own time. Sync is simpler and immediately consistent, but couples services in time, so one outage spreads. Async isolates failures and absorbs bursts, but brings eventual consistency, duplicates and harder debugging.
Understand it
One service is down: sync chain or events
CompareOrders calls Payments, Inventory and Email over HTTP and waits for each. Inventory is down, so every order waits for the timeout and then fails.
View as text
A client calls Orders, which reaches three services: Payments, Inventory and Email. Inventory is drawn as down. Four facts sit below: what the client gets, what happens while Inventory is down, what Orders is coupled to, and when stock is updated.
Synchronous chain: Orders calls Payments, Inventory and Email over HTTP and waits for each. Inventory is down, so every order waits for the timeout and then fails. Client gets: 503, after a 2 s timeout. While Inventory is down: Every order fails. Coupled to: All three services, now. Stock is updated: Before the reply.
Asynchronous events: Orders saves the order, publishes OrderPlaced to a broker and answers at once. Inventory is down, so its events wait, and it catches up when it restarts. Client gets: 202 Accepted, at once. While Inventory is down: Events wait in the broker. Coupled to: Only the broker. Stock is updated: Seconds later.
A client calls Orders, which reaches three services: Payments, Inventory and Email. Inventory is drawn as down. Four facts sit below: what the client gets, what happens while Inventory is down, what Orders is coupled to, and when stock is updated.
Synchronous chain: Orders calls Payments, Inventory and Email over HTTP and waits for each. Inventory is down, so every order waits for the timeout and then fails. Client gets: 503, after a 2 s timeout. While Inventory is down: Every order fails. Coupled to: All three services, now. Stock is updated: Before the reply.
Asynchronous events: Orders saves the order, publishes OrderPlaced to a broker and answers at once. Inventory is down, so its events wait, and it catches up when it restarts. Client gets: 202 Accepted, at once. While Inventory is down: Events wait in the broker. Coupled to: Only the broker. Stock is updated: Seconds later.
Takeaway: A synchronous chain is only as available as its weakest link, because every service must be up at the same moment. Events remove that coupling in time, at the price of eventual consistency.
Fan-out: where the page latency goes
Step by stepA product page needs price, stock and reviews from three services. Called one after another, the latencies add up: the page waits 500 ms.
View as text
A timeline from 0 to 1000 ms with three lanes: price, stock and reviews. A bar in each lane shows when that call runs, and a vertical line marks when the page is ready.
A product page needs price, stock and reviews from three services. Called one after another, the latencies add up: the page waits 500 ms. The page is ready at 500 ms.
The calls do not depend on each other, so send them at once. The page now waits only for the slowest one: 300 ms. The page is ready at 300 ms.
Say one call in a hundred takes a full second. With three calls, about 3% of pages wait a second; with ten calls, almost 10%. Fan-out multiplies the tail. The page is ready at 1000 ms.
Reviews are optional, so give them a 150 ms timeout and a fallback. A slow review service now costs at most 150 ms, and the page shows reviews later. The page is ready at 150 ms.
A timeline from 0 to 1000 ms with three lanes: price, stock and reviews. A bar in each lane shows when that call runs, and a vertical line marks when the page is ready.
A product page needs price, stock and reviews from three services. Called one after another, the latencies add up: the page waits 500 ms. The page is ready at 500 ms.
The calls do not depend on each other, so send them at once. The page now waits only for the slowest one: 300 ms. The page is ready at 300 ms.
Say one call in a hundred takes a full second. With three calls, about 3% of pages wait a second; with ten calls, almost 10%. Fan-out multiplies the tail. The page is ready at 1000 ms.
Reviews are optional, so give them a 150 ms timeout and a fallback. A slow review service now costs at most 150 ms, and the page shows reviews later. The page is ready at 150 ms.
Takeaway: Sequential calls add their latencies; parallel calls cost the slowest one. The more calls a request fans out to, the more often one is slow, so optional calls need tight timeouts and fallbacks.
In code
@Bean
RestClient inventoryClient(RestClient.Builder builder) {
var factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofMillis(500)); // cannot reach it: give up fast
factory.setReadTimeout(Duration.ofSeconds(2)); // reached it, but it is slow
return builder.baseUrl("http://inventory").requestFactory(factory).build();
}
StockLevel stockOf(String sku) {
return inventory.get().uri("/stock/{sku}", sku)
.retrieve()
.body(StockLevel.class); // throws on 4xx, 5xx or a timeout
}@Service
class OrderService {
private final KafkaTemplate<String, OrderPlaced> events;
OrderService(KafkaTemplate<String, OrderPlaced> events) { this.events = events; }
void place(Order order) {
// save the order first (see the outbox module for doing both safely)
events.send("orders.placed", order.id(), new OrderPlaced(order.id(), order.lines()));
}
}
@Component
class ReserveStockOnOrder { // in the Inventory service
@KafkaListener(topics = "orders.placed", groupId = "inventory")
void on(OrderPlaced event) { /* reserve stock; runs when Inventory is up */ }
}// Wrong: one after another, 80 + 120 + 300 ms
Wrong ProductPage slow(String id) { return new ProductPage(prices.get(id), stock.get(id), reviews.get(id)); }
// Right: all at once; reviews get 150 ms, then a fallback
ProductPage fast(String id) {
var price = CompletableFuture.supplyAsync(() -> prices.get(id), pool);
var stockLevel = CompletableFuture.supplyAsync(() -> stock.get(id), pool);
var review = CompletableFuture.supplyAsync(() -> reviews.get(id), pool)
Right .completeOnTimeout(Reviews.none(), 150, TimeUnit.MILLISECONDS);
return new ProductPage(price.join(), stockLevel.join(), review.join());
}Solve it
Checkout fails whenever the email service is down
OrderService.place saves the order, then calls the Email service over HTTP to send the confirmation. When Email is
down for a deploy, checkout returns 500 and customers cannot buy. Explain the problem and fix it so that an email
outage never stops a sale.
- Name the coupling. Checkout depends on Email being up at the same moment: coupling in time. Yet the customer does not need the email to finish buying.
- Separate what must happen now from what can happen later. Saving the order is the answer to the request; the email is a consequence of it.
- Turn the call into an event. Publish
OrderPlaced, and let Email subscribe. The broker keeps the event while Email is down, and Email sends it when it comes back. - Mind the edges. Email may get the event twice, so make it idempotent by order ID. Saving and publishing must not diverge, which the transactional outbox solves.
- Check. Stop Email, place an order: checkout answers 201. Start Email: the confirmation arrives once.
// Before: Email down means checkout down
@Transactional
public OrderId placeBefore(Cart cart) {
Order order = orders.save(Order.from(cart));
emailClient.sendConfirmation(order.id(), cart.customerEmail()); // HTTP, may throw
return order.id();
}
// After: checkout only needs its own database and the broker
@Transactional
public OrderId place(Cart cart) {
Order order = orders.save(Order.from(cart));
events.publishEvent(new OrderPlaced(order.id(), cart.customerEmail())); // relayed to the broker
return order.id();
}How to answer
- A chain of synchronous calls is only as available as the product of its parts.
- Every synchronous call needs a timeout, and usually a retry and a circuit breaker.
- Messaging needs idempotent consumers, because brokers deliver at least once.
- Most systems mix both, query synchronously and propagate changes with events.
Common mistakes
- Saying async is always better. A user waiting for an answer still needs one, and request-reply over a queue is just a slower sync call.
- Calling services synchronously in a long chain without any timeout, so one slow service hangs every caller.
Follow-up questions
REST, gRPC or messaging between services, how do you choose?
REST (Representational State Transfer) over HTTP with JSON is universal, readable and cacheable: the default for public APIs and simple internal ones. gRPC uses HTTP/2 and Protocol Buffers, a compact binary format with a typed contract, for fast internal calls, streaming and polyglot clients; browsers need a proxy. Messaging through Kafka or RabbitMQ decouples sender and receiver in time, for events and work that can happen later.
- gRPC generates client and server code from a .proto file, and fails at compile time on a contract mismatch.
- JSON is easy to debug with curl; Protocol Buffers are smaller and faster to parse.
- Messaging adds a broker to run, monitor and secure.
See it in the infographic: One service is down: sync chain or events
What is temporal coupling, or coupling in time, between services?
Two services are coupled in time when one can only work while the other is up and answering. A synchronous call creates it: if Payments is down, Orders cannot finish. Messaging removes it, because the broker holds the message until the receiver is back. It is separate from coupling in format: services can still share a contract, but no longer need to be available at the same moment.
- Temporal coupling turns one outage into many, a cascading failure.
- Caching and local copies of data also reduce it, for reads.
- The broker must be highly available, since everyone now depends on it.
See it in the infographic: One service is down: sync chain or events
A page calls five services to render. How do you keep its latency low?
Call independent services in parallel, so the page waits for the slowest call rather than the sum. Give each call a tight timeout, and a fallback for optional parts such as reviews, so one slow service costs a bounded delay. Watch the tail: the more calls, the more often at least one is slow. Then cut calls: cache, keep local copies via events, or let an aggregator or a backend for frontend fetch once.
- With 1% slow calls, a page that fans out to ten services is slow almost 10% of the time.
- Measure p99 latency, not the average, which hides the tail.
- Hedged requests, sending a second copy after a delay, trim the tail for idempotent reads.
See it in the infographic: Fan-out: where the page latency goes
What makes communication between services chatty, and why is it a problem?
Chatty communication is many small calls where one would do: fetching an order, then each line, then each product, one request at a time. Each hop adds network latency, serialization and a chance of failure, so a few dozen calls make a slow and fragile request. It usually means the service boundary is in the wrong place, or the API is too fine-grained.
- Prefer coarse operations, such as getting an order with its lines in one call.
- Batch endpoints replace N calls with one.
- Services that call each other constantly may belong together.
See it in the infographic: Fan-out: where the page latency goes
How do you change an API or event without breaking the services that use it?
Make backward-compatible changes: add optional fields, never remove or rename one that consumers read, and make consumers ignore fields they do not know. For a breaking change, run both versions side by side, a new path or event version, migrate consumers, then remove the old one. Contract tests catch a provider that breaks a consumer before it deploys.
- The tolerant reader pattern lets consumers survive added fields.
- Version in the path, such as /v2/orders, or in a header or media type.
- Consumer-driven contracts, with Pact or Spring Cloud Contract, test each pair of services.
See it in the infographic: One service is down: sync chain or events
Three services each have 99.9% availability and call each other in a chain. What is the chain's availability?
About 99.7%, the product of the three: 0.999 cubed. That is roughly three times as much downtime as one service, close to 26 hours a year instead of 9. Each extra synchronous hop lowers it again, which is why long chains are avoided.
What is the difference between a command and an event message?
A command asks one specific receiver to do something, such as ReserveStock, and may be refused. An event states a fact that already happened, such as OrderPlaced, and any number of subscribers may react. Commands couple the sender to the receiver; events let the publisher ignore who listens.
Check yourself
Show answers
- About 300 ms: Correct. In parallel, the handler waits for the slowest call.
- About 500 ms: Incorrect. That is the sequential sum.
- About 80 ms: Incorrect. The fastest call finishing does not mean the others did.
Show answers
- Publish an OrderPlaced event that Email consumes: Correct. The broker keeps the event until Email is back, and checkout never waits.
- Raise the timeout to 30 seconds: Incorrect. Checkout then waits longer before failing.
- Retry the call five times: Incorrect. Retries do not help while Email is down for minutes.
Show answers
- gRPC: Correct. Binary Protocol Buffers over HTTP/2 with generated, typed stubs suit hot internal calls.
- SOAP with XML: Incorrect. Verbose and slow to parse for this load.
- A shared database table polled every second: Incorrect. Polling a shared table couples both services to its schema and adds latency.