Video in progress

Strong Junior 🧩 Microservices

What's wrong in this code, and how does it show up on prod?

@Transactional
public Order create(CreateOrder cmd) {
    Order order = orderRepo.save(Order.from(cmd));
    kafkaTemplate.send("order-created", order.getId().toString(),
                       OrderCreated.from(order));
    auditService.log(order);   // sometimes throws an exception
    return order;
}

This is a "dual write": the order goes to the database and the event goes to Kafka, two separate systems. If send succeeds and then the transaction rolls back, an event goes out about an order that doesn't exist; in the opposite case, the event is lost.

📖 Answer

Unless a Kafka transaction is configured, kafkaTemplate.send(...) has nothing to do with the database transaction: the message goes to the broker almost immediately. Then auditService.log throws an exception, and Spring rolls back the INSERT in the database. The result:

  • order 812 is in the order-created topic;
  • but 812 isn't in the database;
  • warehouse-service reserves stock for an order that doesn't exist.

The reverse also happens: the database commits, but Kafka isn't available at that moment, or the service goes down after send before the message has actually been sent. The order exists, the event doesn't, and the warehouse knows nothing.

On prod this shows up as differences that appear "sometimes" and can't be reproduced: reports don't match, and support says "the order exists, but it isn't being delivered".

Ways to fix it:

  • Outbox: write the event to an outbox table in the same transaction, and let a separate relay send it to Kafka. The most reliable and the most commonly chosen option.
  • As a quick patch, send the event after the commit (@TransactionalEventListener(phase = AFTER_COMMIT)). This closes the "event about a nonexistent order" problem, but if the service goes down after the commit, the event is still lost.