You can synchronize Kafka producer-only transactions with other transaction managers (e.g., DataSourceTransactionManager for databases).
Default Behavior (DB-first):
When using @Transactional on a method that performs both DB and Kafka operations, the interceptor starts the transaction. The KafkaTemplate synchronizes with the existing transaction manager. When the method exits, the database transaction commits first, followed by the Kafka transaction.
Kafka-first Behavior:
If you require the Kafka transaction to commit before the database transaction, use nested @Transactional methods:
- The outer method should be configured to use the
DataSourceTransactionManager. - The inner method should be configured to use the
KafkaTransactionManager.
Error Handling Note:
Starting with versions 2.5.17, 2.6.12, 2.7.9, and 2.8.0, if the synchronized Kafka transaction fails to commit after the primary transaction (e.g., the DB) has already committed, the exception is thrown to the caller. You should implement remedial actions to compensate for the already-committed primary transaction.