Service Communication: Sync vs Async

Service Communication: Sync vs Async in Java: Two services need to talk. You have a fundamental choice, and it shapes everything else.

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.

SynchronousAsynchronous
Couplingtight — B must be uploose — B can be down
LatencyA waits for BA returns immediately
Consistencyimmediateeventual
Debuggingstraightforwardharder 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

  1. Synchronous chains: A → B → C → D means the slowest link sets your latency and any failure kills the whole request.
  2. Non-idempotent consumers: At-least-once delivery makes duplicates a certainty, not an edge case.
  3. Distributed transactions across services: Two-phase commit does not scale. Use the saga pattern with compensating actions.
  4. 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

  1. The Fallback: Add a Feign fallback and confirm it runs when the target service is stopped.
  2. The Second Consumer: Add a new consumer group to an existing topic without modifying the publisher.
  3. The Duplicate: Deliver the same event twice to a non-idempotent handler, observe the double effect, then make it idempotent.