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.
-
The event goes out before the commit.
sendruns immediately (it's asynchronous, but it doesn't wait for the transaction). Then ifinventoryClient.reservethrows an exception, the transaction rolls back: there's no order, but theOrderCreatedevent has already reachednotification-serviceand an SMS has gone to the customer. -
An HTTP call inside the transaction. If
inventory-servicedoesn't respond for 5 seconds, the DB connection is held for 5 seconds. Under load, the connection pool runs out. -
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.
Sign up to mark studied questions and save your progress.