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.

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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this article, we’ll take a fresh look at the CQRS pattern, exploring its benefits and trade-offs in a modular Spring Boot application. We’ll use Spring Modulith to structure our code into clearly separated modules and to enable asynchronous, event-driven communication between them.

This approach is inspired by our colleague Gaetano Piazzolla’s article, where he demonstrates CQRS with Spring Modulith in a product catalog. Here, we’ll adapt the same ideas to a movie ticket booking system and keep the two sides in sync via domain events.

2. Spring Modulith

Spring Modulith helps us structure Spring Boot applications into clear and loosely connected modules. It encourages modeling each module around a specific business area rather than technical concerns, similar to the Vertical Slice Architecture. Additionally, Spring Modulith also includes tools to verify and test the boundaries between modules, which we’ll use in our code samples.

Let’s start by adding the spring-modulith-core dependency to our pom.xml file:

<dependency>
    <groupId>org.springframework.modulith</groupId>
    <artifactId>spring-modulith-core</artifactId>
    <version>1.4.2</version>
</dependency>

In this article, we’re building the backend for a cinema ticket booking system. We split the domain into two subdomains: “movies” and “tickets”. The movies module manages movie search, screening rooms, and seat availability. The “tickets” module takes care of ticket booking and cancellation.

Spring Modulith verifies our project structure and assumes that the logical modules in our app are created as packages at the root level. Let’s follow this philosophy and place the “movie” and “ticket” packages directly at the root of our package structure:

spring.modulith.cqrs
|-- movie
|   |-- MovieController
|   |-- Movie
|   |-- MovieRepository
|   `-- ...
`-- ticket
    |-- BookingTicketsController
    |-- BookedTicket
    |-- BookedTicketRepository
    `-- ...

With this setup, Spring Modulith can help us verify that we don’t have cyclic dependencies between our modules. Let’s write a test that scans the base package, detects the application modules, and verifies their interaction:

@Test
void whenWeVerifyModuleStructure_thenThereAreNoUnwantedDependencies() {
    ApplicationModules.of("com.baeldung.spring.modulith.cqrs")
      .verify();
}

At this point, there are no dependencies between our modules. No class from the “movie” package depends on any class from the “ticket” package, or vice versa. Consequently, the test should pass without problems.

3. CQRS

CQRS stands for Command Query Responsibility Segregation. It’s a pattern that separates write operations (commands) from read operations (queries) in an application. Instead of using the same model for both reading and writing data, we use different models optimized for their specific tasks.

In CQRS, commands are handled by the write side, which saves the data to a write-optimized store. After that, the read model is updated using domain events, change data capture (CDC), or other syncing methods. The read side uses a separate, query-optimized structure to efficiently serve queries:

cqrs diagram 1

Another key difference between commands and queries is their complexity. Queries are often simple and can directly access the read storage to return specific projections of the data. In contrast, commands usually involve complex validations and business rules, so they rely on the domain model to enforce the correct behavior.

4. Implementing CQRS

In our application, commands handle ticket booking and cancellation. Specifically, we accept POST and DELETE requests to book a ticket for a given movie and seat number or to cancel an existing reservation. The query side is handled by the movie module, which exposes GET endpoints for searching movies, viewing screen rooms, and checking seat availability.

To keep the read model eventually consistent with the write side, we’ll use Spring Modulith’s support for publishing and handling domain events.

4.1. The Command Side

First, let’s define the commands for booking and cancelling a ticket as Java records. While we could place them in a dedicated package, doing so goes against the Spring Modulith philosophy of organizing code by business capability. However, if we still want to make it clear that these records represent commands in a CQRS setup, we can use annotations.

The jMolecules library provides a set of annotations that allow us to express architectural roles such as @Command, @QueryModel, or @DomainEvent in a descriptive and technology-neutral way. In our case, these annotations are purely descriptive and don’t affect whether the application works or not.

However, they help make the architectural intent more explicit, and we can use them later to write architectural tests that enforce constraints. Let’s import the jmolecules-cqrs-architecture and jmolecules-events modules into our pom.xml:

<dependency>
    <groupId>org.jmolecules</groupId>
    <artifactId>jmolecules-cqrs-architecture</artifactId>
    <version>1.10.0</version> 
</dependency>
<dependency>
    <groupId>org.jmolecules</groupId>
    <artifactId>jmolecules-events</artifactId>
    <version>1.10.0</version>
</dependency>

Now, let’s create the BookTicket and CancelTicket Java records and annotate them with @Command:

@Command
record BookTicket(Long movieId, String seat) {}

@Command
record CancelTicket(Long bookingId) {}

Finally, let’s create a TicketBookingCommandHandler class to handle ticket booking and cancellation. Here, we’ll perform the necessary validations and save each BookedTicket – whether it’s booked or cancelled – as a separate row in the database:

@Service
class TicketBookingCommandHandler {

    private final BookedTicketRepository bookedTickets;

    // logger, constructor

    public Long bookTicket(BookTicket booking) {
        // validate payload
        // validate seat availability
        // ...

        BookedTicket bookedTicket = new BookedTicket(booking.movieId(), booking.seat());
        bookedTicket = bookedTickets.save(bookedTicket);

        return bookedTicket.getId();
    }

    public Long cancelTicket(CancelTicket cancellation) {
         // validate payload 
         // verify if the ticket can be cancelled 
         // save the cancelled ticket to DB
    }
}

4.2. Keeping Models in Sync via Domain Events

Now that we’ve updated the write storage, we also need to ensure the query side eventually reflects the same state. Since we’re already using Spring Modulith, we can take advantage of its support for handling domain events asynchronously and outside of the original business transaction. While event publishing itself is provided by Spring, Modulith adds infrastructure to track which event deliveries succeed or fail, helping ensure eventual consistency across modules.

First, we need to define the BookingCreated and BookingCancelled domain events. While they may look similar to the commands we defined in the previous section, domain events are fundamentally different. Commands are requests to make something happen, while domain events signal that something has already happened.

To highlight this difference, let’s annotate our domain events with jMolecule’s @DomainEvent:

@DomainEvent
record BookingCreated(Long movieId, String seatNumber) {
}

@DomainEvent
record BookingCancelled(Long movieId, String seatNumber) {
}

Now, we need to instantiate the domain events and publish them from the same transaction where we save the booked and canceled tickets into the database. Let’s make the methods @Transactional and use an ApplicationEventPublisher to notify other modules about these updates:

@Service
class TicketBookingCommandHandler {

    private final BookedTicketRepository bookedTickets;
    private final ApplicationEventPublisher eventPublisher;

    // logger, constructor

    @Transactional
    public Long bookTicket(BookTicket booking) {
        // validate payload
        // validate seat availability
        // ...

        BookedTicket bookedTicket = new BookedTicket(booking.movieId(), booking.seat());
        bookedTicket = bookedTickets.save(bookedTicket);
    
        eventPublisher.publishEvent(
          new BookingCreated(bookedTicket.getMovieId(), bookedTicket.getSeatNumber()));
        return bookedTicket.getId();
    }

    @Transactional
    public Long cancelTicket(CancelTicket cancellation) {
        // validate payload
        // verify if the ticket can be cancelled
        // save the cancelled ticket to DB
        // publish BookingCancelled domain event
    }
}

The “movie” module can use a different table, schema, or even a completely separate data store. For simplicity, our demo uses the same database, but different tables, for the two modules. However, before handling queries, we need to make sure the “movie” module listens to the events published by the “ticket” module and updates its data.

If we use a simple @EventListener, the update would run in the same transaction as the write side. While this ensures atomicity, it tightly couples the two sides and limits scalability.

Instead, we can use Spring Modulith’s @ApplicationModuleListener, which listens to events asynchronously. This allows the read side to update independently, after the original transaction is committed successfully:

@Component
class TicketBookingEventHandler {

    private final MovieRepository screenRooms;

    // constructor

    @ApplicationModuleListener
    void handleTicketBooked(BookingCreated booking) {
        Movie room = screenRooms.findById(booking.movieId())
          .orElseThrow();

        room.occupySeat(booking.seatNumber());
        screenRooms.save(room);
    }

    @ApplicationModuleListener
    void handleTicketCancelled(BookingCancelled cancellation) {
        Movie room = screenRooms.findById(cancellation.movieId())
          .orElseThrow();

        room.freeSeat(cancellation.seatNumber());
        screenRooms.save(room);
    }
}

By doing this, we’ve introduced a dependency between the two modules. Previously, they were independent, but now the “movie” module listens to domain events published by the “ticket” module. This is perfectly fine, and our Spring Modulith test will still pass — as long as the dependency isn’t cyclic.

4.3. The Query Side

Let’s also define a projection for one of the queries we want to support, and annotate it with jMolecule’s @QueryModel:

@QueryModel
record UpcomingMovie(Long id, String title, Instant startTime) {
}

If our projection field names match the entity field names, Spring Data JPA can automatically map the result set to our query model. This makes it easy to return custom views without writing manual mapping code:

@Repository
interface MovieRepository extends CrudRepository<Movie, Long> {

    List<UpcomingMovie> findUpcomingMoviesByStartTimeBetween(Instant start, Instant end);

    // ...
}

Lastly, let’s implement the REST controller. Since queries are simple and don’t involve the complexity of command operations, we can skip accessing the domain service and the domain model and call the repository directly from the controller.

Moreover, we avoid exposing the Movie entity by returning dedicated query models:

@RestController
@RequestMapping("/api/movies")
class MovieController {

    private final MovieRepository movieScreens;

    // constructor
   
    @GetMapping
    List<UpcomingMovie> moviesToday(@RequestParam String range) {
        return movieScreens.findUpcomingMoviesByStartTimeBetween(now(), endTime(range));
    }

    @GetMapping("/{movieId}/seats")
    ResponseEntity<AvailableMovieSeats> movieSeating(@PathVariable Long movieId) {
        return ResponseEntity.of(
          movieScreens.findAvailableSeatsByMovieId(movieId));
    }

    private static Instant endTime(String range) { /* ... */ }
}

5. Trade-Offs

CQRS brings benefits like separation of concerns and better scalability, but it also adds complexity. Maintaining separate models for reads and writes means more code and coordination. A key challenge in CQRS is eventual consistency. Since the read side updates asynchronously, users might briefly see outdated data.

On the other hand, asynchronous communication through domain events makes the application more modular and extensible. For example, if other modules need to react to tickets being booked or canceled, they can simply listen for the corresponding domain events without touching the core logic.

Spring Modulith helps here by offering infrastructure to track event delivery, which simplifies building eventually consistent systems. However, it’s important to note that the Event Publication Registry (EPR) does not guarantee ordering or reliable delivery. It only tracks whether event delivery succeeded or failed, using Spring’s standard event multicasting under the hood.

Lastly, Spring Modulith also makes it easy to forward domain events to external message brokers using the event externalization feature, with minimal code changes.

6. Conclusion

In this tutorial, we revisited the main ideas behind the CQRS pattern and explored how to cleanly decouple application domains using logical modules, enforced with Spring Modulith. We also highlighted architectural roles using annotations from the jMolecules library, instead of relying on package structure.

Spring Modulith helped us keep the two modules eventually consistent through async domain events. Consequently, each module used a separate database table with models optimized for their specific responsibilities.

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.

Course – LS – NPI – (cat=Spring)
announcement - icon

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

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments