Video in progress

What's the problem with the Kafka and HTTP calls in this order-creating method?

@Transactional
public Order create(CreateOrderRequest req) {
    Order order = orderRepo.save(Order.from(req));
    kafkaTemplate.send("order-events", order.getId().toString(),
            new OrderCreated(order.getId(), order.getTotal()));
    inventoryClient.reserve(order.getId(), req.items()); // HTTP call
    return order;
}

The Kafka message goes out before the transaction commits. If the commit fails, other services get an event for an order that doesn't exist; if Kafka fails, the event is lost. The fix is an outbox, or at least sending after the commit.

📖 Answer

There are three problems here.

  1. The event goes out before the commit. send runs immediately (it's asynchronous, but it doesn't wait for the transaction). Then if inventoryClient.reserve throws an exception, the transaction rolls back: there's no order, but the OrderCreated event has already reached notification-service and an SMS has gone to the customer.

  2. An HTTP call inside the transaction. If inventory-service doesn't respond for 5 seconds, the DB connection is held for 5 seconds. Under load, the connection pool runs out.

  3. The reverse case exists too. The commit went through, but the broker was temporarily down: the event is lost, and other services never learn about the order.

The fixed version:

@Transactional
public Order create(CreateOrderRequest req) {
    Order order = orderRepo.save(Order.pending(req));
    outboxRepo.save(OutboxEvent.of("OrderCreated", order.getId(), payload(order)));
    return order;
}

The reservation isn't synchronous: inventory-service hears the OrderCreated event and reserves, returns the result as an event, and the order moves from PENDING to CONFIRMED. So this is a small saga.

Sending inside @TransactionalEventListener(phase = AFTER_COMMIT) solves the first problem but not the third: if the application goes down after the commit, the event is still lost.