Concept Explanation
Two services need to talk. You have a fundamental choice, and it shapes everything else.
Synchronous — service A calls B and waits for the answer. Asynchronous — service A publishes an event and moves on; B handles it whenever it can.
| Synchronous | Asynchronous | |
|---|---|---|
| Coupling | tight — B must be up | loose — B can be down |
| Latency | A waits for B | A returns immediately |
| Consistency | immediate | eventual |
| Debugging | straightforward | harder to trace |
| Use for | "is this in stock?" | "an order was placed" |
Synchronous with Feign
@FeignClient(name = "pricing-service",
fallback = PricingFallback.class)
public interface PricingClient {
@GetMapping("/api/price/{sku}")
Price priceFor(@PathVariable String sku);
}
@Component
class PricingFallback implements PricingClient {
public Price priceFor(String sku) {
return Price.unavailable(); // degrade rather than fail
}
}
Timeouts are mandatory:
feign:
client:
config:
default:
connectTimeout: 3000
readTimeout: 5000
Asynchronous with Events
// Publisher — the order service
@Service
public class OrderService {
private final KafkaTemplate<String, OrderPlaced> kafka;
@Transactional
public Order place(OrderRequest req) {
Order order = repo.save(Order.from(req));
kafka.send("orders", new OrderPlaced(order.getId(), order.getTotal()));
return order; // returns without waiting on anyone
}
}
// Consumers — each reacts independently
@KafkaListener(topics = "orders", groupId = "email-service")
public void sendConfirmation(OrderPlaced event) {
email.confirm(event.orderId());
}
@KafkaListener(topics = "orders", groupId = "analytics-service")
public void record(OrderPlaced event) {
analytics.track(event);
}
Adding a third consumer later requires no change to the order service. That decoupling is the whole point.
Eventual Consistency
The trade-off: for a moment, the order exists but no confirmation email has been sent. That is usually fine — but the system must be designed for it. The UI says "order received, confirmation on its way" rather than pretending everything already completed.
Idempotency
Networks retry. A message can be delivered twice. Handlers must therefore be safe to run more than once:
@KafkaListener(topics = "payments")
public void handle(PaymentEvent event) {
if (processed.contains(event.id())) return; // already handled
charge(event);
processed.add(event.id());
}
Without this, a retried payment event charges the customer twice.
Common Mistakes
- Synchronous chains: A → B → C → D means the slowest link sets your latency and any failure kills the whole request.
- Non-idempotent consumers: At-least-once delivery makes duplicates a certainty, not an edge case.
- Distributed transactions across services: Two-phase commit does not scale. Use the saga pattern with compensating actions.
- Sharing a database between services: Now they are one service with extra network hops.
Best Practices
- Async by default for anything that is not needed to answer the current request.
- Version event schemas and add fields additively so old consumers keep working.
- Make every consumer idempotent — assume duplicates.
- Publish events describing facts (
OrderPlaced), not commands (SendEmail). Facts stay true; commands couple you to a recipient.
Practice Exercises
- The Fallback: Add a Feign fallback and confirm it runs when the target service is stopped.
- The Second Consumer: Add a new consumer group to an existing topic without modifying the publisher.
- The Duplicate: Deliver the same event twice to a non-idempotent handler, observe the double effect, then make it idempotent.