Video in progress

Strong Middle 🧩 Microservices

In which cases does the `OrderPlaced` event get lost or behave unexpectedly in this code?

@Transactional
public Order place(PlaceOrder cmd) {
    Order order = repo.save(Order.from(cmd));
    events.publishEvent(new OrderPlaced(order.getId()));
    return order;
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(OrderPlaced e) {
    kafka.send("orders", e.orderId().toString(), e);
    auditRepo.save(new AuditEntry("ORDER_PLACED", e.orderId()));
}

An AFTER_COMMIT listener runs after the commit: if the service dies before sending to Kafka, or the send fails, the event is lost for good while the order is saved. On top of that, a DB write inside the listener is not committed without REQUIRES_NEW.

📖 Answer

This is a half step that turns the dual write in the right direction: now the event is never sent for an order that was rolled back. But three problems remain.

The first is loss. The commit went through, and before the listener was called the pod got SIGKILL, or kafka.send went out asynchronously and the broker didn't answer. The order is in the DB, the event is nowhere. There is no mechanism to resend it either, because the event lived only in memory.

The second is auditRepo.save. In the AFTER_COMMIT phase the transaction resources are still bound to the thread, but the commit has already happened. A write inside the listener doesn't open a new transaction and doesn't get committed, so the audit entry silently disappears. The Spring docs say this openly: in this case you need @Transactional(propagation = REQUIRES_NEW). Since Spring 6.1, putting a plain @Transactional on a @TransactionalEventListener method makes the application fail at startup, precisely to prevent this mistake.

The third is errors. An exception in the listener does not go back to the caller of place() (the commit is already done), it only lands in the log. The client gets "order accepted" and the event was never sent.

The fix is to write the event to an outbox table inside the transaction:

@Transactional
public Order place(PlaceOrder cmd) {
    Order order = repo.save(Order.from(cmd));
    outbox.save(OutboxEvent.of("orders", order.getId(), new OrderPlaced(order.getId())));
    auditRepo.save(new AuditEntry("ORDER_PLACED", order.getId()));
    return order;
}

Now the order, the event and the audit entry are in one commit. A relay does the sending to Kafka, and the guarantee is at-least-once.

@TransactionalEventListener itself is not bad: it is very handy for things that can be lost, like sending an email or clearing a cache. It just isn't enough for events that "must not be lost".