spring-boottransactionsspring-kafkajdbctemplate

Execute a Database Update Operation and Non DB Function inside a Transaction (both-or-none) in Spring Boot


I have a database record update and a Kafka message push, which should be executed in an all-or-none way.

 public int UpdateRecord();
 public int puahMessageToKafka();

The scenario is,

The deployed Server getting failed after updating the database record (before pushing the message to Kafka) for some external reason (Etc: Kubernetes Pod crashes). I need the database record update rollbacked in a case like this.

Spring boot annotations like @Transactional will not work in this case. Because it supports only for database related operations.

What would be the best way to handle this?


Solution

  • It seems Spring for Apache Kafka also supports transactions, along with database updates. It allows the capability to rollback Kafka messages, where the Consumer won't read the rollbacked Kafka messages.

     @Transactional
     public void test(){
        UpdateRecord();
        puahMessageToKafka();
     }
    

    By implementing something like above (with some other config changes), it will make sure both database update and the Kafka message will be committed in a all-or-none manner.