Smooth Implementation of CQRS/ES with Spring Boot and Axon Framework

Smooth Implementation of CQRS/ES with Spring Boot and Axon Framework

Łukasz Kucik - September 21, 2018

In the last article, I described what CQRS and Event Sourcing are and what problems they solve. You can find there all the necessary details to start the implementation of these concepts. Even though CQRS/ES can be implemented without any additional frameworks or libraries, I would recommend using one of the available tools. It could ease of development process while allowing stay focused on business logic. Our choice has fallen upon the Axon framework.

What is Axon?

Axon is a Java lightweight open-source framework that helps build scalable, extensible, and maintainable applications based on the CQRS pattern. It can also support you in preparing your system for event sourcing. Axon provides an implementation of all significant building blocks like aggregates, repositories, commands, and event buses. Axon is just about making life easier for developers.

Why Axon?

Axon allows us to forget about configuration and data flow. Instead of adding a boilerplate, we can stay focused on the business rules of our application. We can distinguish some of the benefits:

  • Correct event processing. We should be aware that some of the events should be delivered earlier and some of them later. Axon guarantees to supply events to the right event handlers and process them concurrently and in the correct order.
  • Built-in test environment. Axon framework provides a test fixture that allows you to compose tests in a given-when-then style. It makes unit testing easy.
  • Spring Boot AutoConfiguration. The easiest way of configuring Axon in a Spring application. The only necessary thing is to add an appropriate dependency. Axon will automatically configure some of the essential components.
  • Annotation support. Axon provides annotation support which makes our code cleaner and we can build aggregates and event handlers without getting Axon-specific logic.

A quick configuration in Spring Boot application

Integration with Spring Boot is provided by default. The only thing we have to do is to take some steps to configure some necessary beans.

Step 1

The first step is to configure Axon dependency in the project using an appropriate build tool. Here is how you can do it with Gradle:

dependencies {
  compile('org.axonframework:axon-spring-boot-starter:3.2')
  compile('org.axonframework:axon-mongo:3.2')
  testCompile('org.axonframework:axon-test:3.2')
}

The first dependency gives us basic Axon functionality integrated with Spring. All the necessary components such as command bus, event bus, and aggregates. The second dependency is necessary to configure repositories for our aggregate or events (event store). The last dependency is related to providing building blocks for testing our aggregates.

Step 2

The configuration of the Axon is straightforward. You have to configure some Spring beans. We’ve configured EventHandlingConfiguration (the component responsible for controlling event handlers’ behavior) to abort processing all subsequent events if the execution of one of them fails. This is, of course, an additional configuration, but it is worth doing to avoid inconsistencies in the system.

@Configuration
public class AxonConfig {

private final EventHandlingConfiguration eventHandlingConfiguration;

@Autowired
public AxonConfig(EventHandlingConfiguration eventHandlingConfiguration) {
   this.eventHandlingConfiguration = eventHandlingConfiguration;
}

@PostConstruct
public void registerErrorHandling() {
   eventHandlingConfiguration.configureListenerInvocationErrorHandler(configuration -> (exception, event, listener) -> {
       String msg = String.format(
               "[EventHandling] Event handler failed when processing event with id %s. Aborting all further event handlers.",
               event.getIdentifier());
       log.error(msg, exception);
       throw exception;
   });
}}

The main idea here is to create an additional configuration file (class annotated with @Configuration). The constructor of this class injects EventHandlingConfiguration dependency which is managed by Spring itself. Thanks to tied dependency we can call configureListenerInvocationErrorHandler() on this object and handle errors by logging and propagating exceptions to upper levels.

Step 3

We use the event store to keep all emitted events in MongoDB. To create such a repository, configure the following bean:

@Bean
public EventStorageEngine eventStore(MongoTemplate mongoTemplate) {
   return new MongoEventStorageEngine(
           new JacksonSerializer(), null, mongoTemplate, new DocumentPerEventStorageStrategy());
}

With that, all events published on event bus will be automatically saved in the Mongo repository. This simple configuration enables event sourcing in our application.

And that’s it when it comes to configuration. Of course, we have much more possibilities, and we can change behavior by any means, but such a simple configuration allows us to run Axon and use its features.

CQRS implementation with Axon

CQRS

According to the diagram above, creating commands, passing them to command bus and then creating events and placing them on event bus is not CQRS yet. We have to remember about changing the state of write repository and reading current state from the read database. This is the crucial point of the CQRS pattern.

Configuring this flow should be easy as well. While passing the command to the command gateway, Spring searches methods annotated with @CommandHandler with command type as argument.

CQRS

@Value
class SubmitApplicationCommand {
   private String appId;
   private String category;
}

@AllArgsConstructor
public class ApplicationService {
   private final CommandGateway commandGateway;

   public CompletableFuture<Void> createForm(String appId) {
       return CompletableFuture.supplyAsync(() -> new SubmitExpertsFormCommand(appId, "Android"))
               .thenCompose(commandGateway::send);
   }
}

Command handler is responsible, among other things, for sending the created event to the event bus. It places an event object to statically imported apply() method from AggregateLifecycle. The event is later dispatched to find expected handlers and thanks to configured event store, all events are saved in DB automatically.

CQRS

@Value
class ApplicationSubmittedEvent {
   private String appId;
   private String category;
}

@Aggregate
@NoArgsConstructor
public class ApplicationAggregate {
   @AggregateIdentifier
   private String id;

   @CommandHandler
   public ApplicationAggregate(SubmitApplicationCommand command) {
      //some validation
       this.id = command.getAppId;
       apply(new ApplicationSubmittedEvent(command.getAppId(), command.getCategory()));
   }
}

To change the state of the write DB, we need to provide a method annotated with @EventHandler. The application can contain multiple event handlers. Each of them should perform one specific task like sending emails, logging or saving in database.

CQRS

@RequiredArgsConstructor
@Order(1)
public class ProjectingEventHandler {
   private final IApplicationSubmittedProjection projection;

   @EventHandler
   public CompletableFuture<Void> onApplicationSubmitted(ExpertsFormSubmittedEvent event) {
       return projection.submitApplication(event.getApplicationId(), event.getCategory());
   }
}

If we want to determine the processing order of all event handlers, we can annotate a class with @Order and set a sequence number. submitApplication() method is responsible for making all the necessary changes and saving new data in write DB.

These are all vital points to make our app event sourced with CQRS pattern principles. Of course, these principles can be applied only in some parts of our application depending on business needs. Event sourcing is not suitable for every application or module we are building. It is also worth to be cautious while implementing this pattern because a more complex application can be hard to maintain.

Conclusion

Implementation of CQRS and Event Sourcing is straightforward with Axon framework. More details about advanced configuration can be found on Axon’s website https://docs.axonframework.org/. Besides, Axon is constantly developed and supported. Thanks to that, we are sure that all reported issues will be fixed on a regular basis making our experience with Axon even better.

About the author

Łukasz Kucik

Łukasz Kucik

Software Engineer

Linkedin profile Twitter

Łukasz is a Software Engineer with industry experience building large-scale web applications. He provides full-stack solutions but mainly focuses on BE with Java, Kotlin, and Spring.
He believes that working in small Agile teams is the key to significant results, as good communication guarantees success. Łukasz's daily routine includes improving his coding skills by introducing clean code standards and refactoring.

This article is a part of

Zero Legacy
36 articles

Zero Legacy

What goes on behind the scenes in our engineering team? How do we solve large-scale technical challenges? How do we ensure our applications run smoothly? How do we perform testing and strive for clean code?

Follow our article series to get insight into our developers' current work and learn from their experience. Expect to see technical details, architecture discussions, reviews on libraries and tools we use, best practices on software quality, and maybe even some fail stories.

check it out

Zero Legacy

Insights from nexocode team just one click away

Sign up for our newsletter and don't miss out on the updates from our team on engineering and teal culture.

Done!

Thanks for joining the newsletter

Check your inbox for the confirmation email & enjoy the read!

This site uses cookies for analytical purposes.

Accept Privacy Policy

In the interests of your safety and to implement the principle of lawful, reliable and transparent processing of your personal data when using our services, we developed this document called the Privacy Policy. This document regulates the processing and protection of Users’ personal data in connection with their use of the Website and has been prepared by Nexocode.

To ensure the protection of Users' personal data, Nexocode applies appropriate organizational and technical solutions to prevent privacy breaches. Nexocode implements measures to ensure security at the level which ensures compliance with applicable Polish and European laws such as:

  1. Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of natural persons with regard to the processing of personal data and on the free movement of such data, and repealing Directive 95/46/EC (General Data Protection Regulation) (published in the Official Journal of the European Union L 119, p 1); Act of 10 May 2018 on personal data protection (published in the Journal of Laws of 2018, item 1000);
  2. Act of 18 July 2002 on providing services by electronic means;
  3. Telecommunications Law of 16 July 2004.

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.

1. Definitions

  1. User – a person that uses the Website, i.e. a natural person with full legal capacity, a legal person, or an organizational unit which is not a legal person to which specific provisions grant legal capacity.
  2. Nexocode – NEXOCODE sp. z o.o. with its registered office in Kraków, ul. Wadowicka 7, 30-347 Kraków, entered into the Register of Entrepreneurs of the National Court Register kept by the District Court for Kraków-Śródmieście in Kraków, 11th Commercial Department of the National Court Register, under the KRS number: 0000686992, NIP: 6762533324.
  3. Website – website run by Nexocode, at the URL: nexocode.com whose content is available to authorized persons.
  4. Cookies – small files saved by the server on the User's computer, which the server can read when when the website is accessed from the computer.
  5. SSL protocol – a special standard for transmitting data on the Internet which unlike ordinary methods of data transmission encrypts data transmission.
  6. System log – the information that the User's computer transmits to the server which may contain various data (e.g. the user’s IP number), allowing to determine the approximate location where the connection came from.
  7. IP address – individual number which is usually assigned to every computer connected to the Internet. The IP number can be permanently associated with the computer (static) or assigned to a given connection (dynamic).
  8. GDPR – Regulation 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of individuals regarding the processing of personal data and onthe free transmission of such data, repealing Directive 95/46 / EC (General Data Protection Regulation).
  9. Personal data – information about an identified or identifiable natural person ("data subject"). An identifiable natural person is a person who can be directly or indirectly identified, in particular on the basis of identifiers such as name, identification number, location data, online identifiers or one or more specific factors determining the physical, physiological, genetic, mental, economic, cultural or social identity of a natural person.
  10. Processing – any operations performed on personal data, such as collecting, recording, storing, developing, modifying, sharing, and deleting, especially when performed in IT systems.

2. Cookies

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet. The Website, in accordance with art. 173 of the Telecommunications Act of 16 July 2004 of the Republic of Poland, uses Cookies, i.e. data, in particular text files, stored on the User's end device.
Cookies are used to:

  1. improve user experience and facilitate navigation on the site;
  2. help to identify returning Users who access the website using the device on which Cookies were saved;
  3. creating statistics which help to understand how the Users use websites, which allows to improve their structure and content;
  4. adjusting the content of the Website pages to specific User’s preferences and optimizing the websites website experience to the each User's individual needs.

Cookies usually contain the name of the website from which they originate, their storage time on the end device and a unique number. On our Website, we use the following types of Cookies:

  • "Session" – cookie files stored on the User's end device until the Uses logs out, leaves the website or turns off the web browser;
  • "Persistent" – cookie files stored on the User's end device for the time specified in the Cookie file parameters or until they are deleted by the User;
  • "Performance" – cookies used specifically for gathering data on how visitors use a website to measure the performance of a website;
  • "Strictly necessary" – essential for browsing the website and using its features, such as accessing secure areas of the site;
  • "Functional" – cookies enabling remembering the settings selected by the User and personalizing the User interface;
  • "First-party" – cookies stored by the Website;
  • "Third-party" – cookies derived from a website other than the Website;
  • "Facebook cookies" – You should read Facebook cookies policy: www.facebook.com
  • "Other Google cookies" – Refer to Google cookie policy: google.com

3. How System Logs work on the Website

User's activity on the Website, including the User’s Personal Data, is recorded in System Logs. The information collected in the Logs is processed primarily for purposes related to the provision of services, i.e. for the purposes of:

  • analytics – to improve the quality of services provided by us as part of the Website and adapt its functionalities to the needs of the Users. The legal basis for processing in this case is the legitimate interest of Nexocode consisting in analyzing Users' activities and their preferences;
  • fraud detection, identification and countering threats to stability and correct operation of the Website.

4. Cookie mechanism on the Website

Our site uses basic cookies that facilitate the use of its resources. Cookies contain useful information and are stored on the User's computer – our server can read them when connecting to this computer again. Most web browsers allow cookies to be stored on the User's end device by default. Each User can change their Cookie settings in the web browser settings menu: Google ChromeOpen the menu (click the three-dot icon in the upper right corner), Settings > Advanced. In the "Privacy and security" section, click the Content Settings button. In the "Cookies and site date" section you can change the following Cookie settings:

  • Deleting cookies,
  • Blocking cookies by default,
  • Default permission for cookies,
  • Saving Cookies and website data by default and clearing them when the browser is closed,
  • Specifying exceptions for Cookies for specific websites or domains

Internet Explorer 6.0 and 7.0
From the browser menu (upper right corner): Tools > Internet Options > Privacy, click the Sites button. Use the slider to set the desired level, confirm the change with the OK button.

Mozilla Firefox
browser menu: Tools > Options > Privacy and security. Activate the “Custom” field. From there, you can check a relevant field to decide whether or not to accept cookies.

Opera
Open the browser’s settings menu: Go to the Advanced section > Site Settings > Cookies and site data. From there, adjust the setting: Allow sites to save and read cookie data

Safari
In the Safari drop-down menu, select Preferences and click the Security icon.From there, select the desired security level in the "Accept cookies" area.

Disabling Cookies in your browser does not deprive you of access to the resources of the Website. Web browsers, by default, allow storing Cookies on the User's end device. Website Users can freely adjust cookie settings. The web browser allows you to delete cookies. It is also possible to automatically block cookies. Detailed information on this subject is provided in the help or documentation of the specific web browser used by the User. The User can decide not to receive Cookies by changing browser settings. However, disabling Cookies necessary for authentication, security or remembering User preferences may impact user experience, or even make the Website unusable.

5. Additional information

External links may be placed on the Website enabling Users to directly reach other website. Also, while using the Website, cookies may also be placed on the User’s device from other entities, in particular from third parties such as Google, in order to enable the use the functionalities of the Website integrated with these third parties. Each of such providers sets out the rules for the use of cookies in their privacy policy, so for security reasons we recommend that you read the privacy policy document before using these pages. We reserve the right to change this privacy policy at any time by publishing an updated version on our Website. After making the change, the privacy policy will be published on the page with a new date. For more information on the conditions of providing services, in particular the rules of using the Website, contracting, as well as the conditions of accessing content and using the Website, please refer to the the Website’s Terms and Conditions.

Nexocode Team

Close

Want to be a part of our engineering team?

Join our teal organization and work on challenging projects.

CHECK OPEN POSITIONS