Let's get started with a Microservice Architecture with Spring Cloud:
Implementing CQRS with Spring Modulith
Last updated: October 8, 2025
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:
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.
















