eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this tutorial, we’ll explore the challenges of maintaining data consistency between database operations and messaging. We’ll begin by examining the problem and then implement the transactional outbox pattern to address key issues.

Next, we’ll introduce Eventuate Tram to populate the outbox table with messages ready to be published to a specific topic. Finally, we’ll run the Eventuate CDC Service in its own Docker container to monitor changes in the outbox table and publish the corresponding messages through Kafka.

2. When Do We Need Transactional Messaging?

Just like we often rely on database transactions to ensure atomicity in data operations, we might also need to publish messages to a message broker atomically. For instance, sometimes we need to save data to the database and publish a message to a message broker as a single, atomic operation.

Although this may seem straightforward, it presents some hidden challenges. Let’s explore this problem using a simple use-case where we’ll try to save a Comment entity to the database and publish an event to the baeldung.comment.added Kafka topic.

A naive approach is to publish the message within a transactional block. For instance, if we use Spring Data JPA for database operations and KafkaTemplate to send messages, our domain service might look like this:

@Service
class CommentService {

    private final CommentRepository comments;
    private final KafkaTemplate<Long, CommentAddedEvent> kafkaTemplate;
 
    // constructor
   
    @Transactional
    public Long save(Comment comment) {
        Comment saved = this.comments.save(comment);
        log.info("Comment created: {}", saved);

        CommentAddedEvent commentAdded = new CommentAddedEvent(saved.getId(), saved.getArticleSlug());
        kafkaTemplate.send("baeldung.comment.added", saved.getId(), commentAdded);
    }

}

However, this approach publishes the Kafka message before the database commit happens. In other words, we risk sending the message even if the transaction fails at commit time, and the operation is rolled back.

On the other hand, if we try removing the @Transactional annotation, Spring won’t roll back the DB inserts when the publishing to Kafka fails. Needless to say, neither approach is ideal, as both can lead to inconsistent data across systems.

3. The Transactional Outbox Pattern

We can implement the Transactional Outbox pattern to ensure eventual consistency in our system. This pattern involves saving messages in a special database table (i.e., the “outbox”) within the same transaction as our data changes.

Afterward, a separate process reads the outbox and publishes the messages to the message broker. It then updates, removes, or marks the records as published to keep track of what has been sent:

Transactional Outbox Pattern

A similar issue can happen when publishing the event and updating the outbox table. We want to avoid updating the outbox unless the event is successfully published, to prevent losing events. On the other hand, if the event is sent but the database update fails, the system might retry and send the event again. This can result in duplicate events, but it’s better than losing them.

Overall, this approach ensures “at least once” delivery, prioritizing reliability over avoiding duplicates.

4. Demo Application Overview

In this article, we’ll work with a simple Spring Boot application that manages article comments for a blogging site like Baeldung. Users can add comments to an article by sending POST requests to the /api/articles/{slug}/comments endpoint:

curl --location "http://localhost:8080/api/articles/oop-best-practices/comments" \
--header "Content-Type: application/json" \
--data "{
    \"articleAuthor\": \"Andrey the Author\",
    \"text\": \"Great article!\",
    \"commentAuthor\": \"Richard the Reader\"
}"

For quick testing, we can run this curl command using the post-comment.bat script located in src/rest/resources.

When a Comment entity is saved to the database, the system also publishes a Kafka message. This message includes the newly saved Comment ID and the article slug, and is sent to a topic named baeldung.comment.added.

To set up the local environment, we’ll use Docker to start containers for PostgreSQL, Kafka, and Eventuate’s CDC Service. This can be done easily using the eventuate-docker-compose.yml file located in src/test/resources. We’ll also start the Spring Boot application locally using the eventuate profile:

Transactional Outbox Pattern - Components Involved

To see everything in practice, we can also refer to our integration test, EventuateTramLiveTest.

5. Eventuate Tram

Eventuate is a Java platform that supports core microservices patterns like CQRS, Event Sourcing, and Transaction Sagas. One of its components, Eventuate Tram, enables reliable inter-service communication through the transactional outbox pattern and event publishing.

Let’s integrate Eventuate Tram to ensure at-least-once delivery of Kafka messages in our example. First, we add the necessary dependencies for eventuate-tram-spring-jdbc-kafka and eventuate-tram-spring-events to our pom.xml:

<dependency>
    <groupId>io.eventuate.tram.core</groupId>
    <artifactId>eventuate-tram-spring-jdbc-kafka</artifactId>
    <version>0.36.0-RELEASE</version>
</dependency>
<dependency>
    <groupId>io.eventuate.tram.core</groupId>
    <artifactId>eventuate-tram-spring-events</artifactId>
    <version>0.36.0-RELEASE</version>
</dependency>

Then, we’ll import two configuration classes:

@Configuration
@Import({
    TramEventsPublisherConfiguration.class,
    TramMessageProducerJdbcConfiguration.class
})
class EventuateConfig {
}

Additionally, we’ll need to change our CommentAddedEvent record and make sure it implements the Eventuate’s DomainEvent interface:

record CommentAddedEvent(Long id, String articleSlug) implements DomainEvent {
}

Finally, we’ll refactor the domain service, which contains all the logic. This time, instead of directly publishing to Kafka, we’ll use the DomainEventPublisher bean to publish a CommentAddedEvent:

@Service
class CommentService {

    private final CommentRepository comments;
    private final DomainEventPublisher domainEvents;

    // constructor

    @Transactional
    public Long save(Comment comment) {
        Comment saved = this.comments.save(comment);
        log.info("Comment created: {}", saved);

        CommentAddedEvent commentAdded = new CommentAddedEvent(saved.getId(), saved.getArticleSlug());
        domainEvents.publish(
            "baeldung.comment.added",
            saved.getId(),
            singletonList(commentAdded)
        );
        return saved.getId();
    }

}

As a result, whenever we persist a Comment entity, we’ll also insert a CommentAddedEvent entry into the eventuate.message table within the same transaction. 

Let’s verify this by connecting to the database and querying the comment table:

mydb=# select * from comment;
 id |   article_slug    |   comment_author   |      text       
----+-------------------+--------------------+------------------
  1 | oop-best-practices | Richard the Reader | Great article!
(1 row)

Let’s also query the message table from the eventuate schema. Assuming the CDC Service is down, we can expect to retrieve only one message, marked as unpublished:

mydb=# select id, destination, published from eventuate.message;
                  id                  |        destination         | published 
--------------------------------------+----------------------------+-----------
 0000019713d8ffe4-e86a640584cf0000    | baeldung.comment.added     |     0
(1 row)

6. Eventuate’s CDC Service

Change data capture (CDC) is a technique used to detect and track changes such as inserts, updates, and deletes in a database so those changes can be captured and sent to other systems. Therefore, the Eventuate CDC Service is the component that captures changes for the outbox table and publishes them as events to our message broker.

The Eventuate CDC service currently supports several message brokers, including Apache Kafka, ActiveMQ, RabbitMQ, and Redis. For databases, it uses efficient transaction log tailing with MySQL through the binlog protocol and with Postgres using WAL. Alternatively, for other JDBC-compatible databases, it falls back on a less efficient polling approach to detect changes.

If we spin up the CDC service and re-run the test, we’ll notice that the entries from eventuate.messages table will be marked as published:

mydb=# select id, destination, published from eventuate.message;
                  id                  |        destination         | published 
--------------------------------------+----------------------------+-----------
 0000019713d8ffe4-e86a640584cf0000    | baeldung.comment.added     |     1
(1 row)

Lastly, we can use kafka-console-consumer.sh to verify that the message was successfully published to our topic:

{
  "payload": "{ \"id\": 1, \"articleSlug\": \"oop-best-practices\" }",
  "headers": {
    "PARTITION_ID": "1",
    "event-aggregate-type": "baeldung.comment.added",
    "DATE": "Tue, 27 May 2025 22:24:37 GMT",
    "event-aggregate-id": "1",
    "event-type": "com.baeldung.eventuate.tram.domain.CommentAddedEvent",
    "DESTINATION": "baeldung.comment.added",
    "ID": "0000019713d8ffe4-e86a640584cf0000"
  }
}

As expected, the message was delivered and the outbox table was updated accordingly.

7. Conclusion

In this article, we explored the complexities of transactional messaging, beginning with the challenge of atomically performing a database operation and publishing a domain event. We uncovered hidden difficulties and saw how the transactional outbox pattern helps address them.

Then, we used the Eventuate Tram framework, which implements this pattern for us. Together with the Eventuate CDC Service, which leverages change data capture to monitor the outbox table and send messages to Kafka, we achieved eventual consistency and guaranteed at-least-once delivery in our system.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)