<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by raghuram gururajan on Medium]]></title>
        <description><![CDATA[Stories by raghuram gururajan on Medium]]></description>
        <link>https://medium.com/@raghuramg?source=rss-a3ba45180fd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ijP_VsHskgG101VhSmXq6w.png</url>
            <title>Stories by raghuram gururajan on Medium</title>
            <link>https://medium.com/@raghuramg?source=rss-a3ba45180fd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:36:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raghuramg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing event sourcing/CQRS using Axon and Spring boot]]></title>
            <link>https://raghuramg.medium.com/implementing-event-sourcing-cqrs-using-axon-and-spring-boot-6eaa9ddde89f?source=rss-a3ba45180fd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eaa9ddde89f</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[axon-framework]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[raghuram gururajan]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 22:50:27 GMT</pubDate>
            <atom:updated>2021-03-05T23:52:56.296Z</atom:updated>
            <content:encoded><![CDATA[<h4>Modern Day Web Applications and the common problems faced</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*qAcpV4QWIaCeMZ-MbxHy7g.jpeg" /><figcaption><strong>MVC application architecture</strong></figcaption></figure><p>Traditional MVC architecture emerged as a means of scaling from client-server applications to internet-based applications that could support hundreds of thousands of users. By adding a load-balanced presentation tier on top of processing logic we can handle load more effectively and provide a higher degree of resiliency.</p><p>Tiered architecture makes it difficult to define clear abstractions since the layers tend to be separated by their <em>technical</em> role rather than the business functionality. One of the main problems of tiered architecture is around the separation of concerns. As the application grows it becomes impossible to tell where things are going wrong and minor feature requests necessitate code changes in every layer. De-coupling is never achieved and it becomes impossible to scale such systems.</p><p>The most common use case use for interacting with such multi tiered applications is as a CRUD(<strong>c</strong>reate new records, <strong>r</strong>ead records, <strong>u</strong>pdate existing records, and <strong>d</strong>elete records) store. In the simplest case, our interactions are all about storing and retrieving these records. As our needs become more sophisticated we steadily move away from that model. Individual functionalities/endpoints in a system might see radically different usage characteristics.In a system which receives a lot of traffic, you might see a lot of writes, as compared to reads. Or, only relatively few writes, but a lot of reads; or, you might see one component of the system to be used much more often than others.</p><h3>What is Event Sourcing?</h3><p>Event sourcing is a powerful distributed system’s pattern that records all state changes made to an application in sequence in which the original changes were applied. These records serve as system from where current state can be sourced from. It also servers as an audit log of all the events that happened within the application over its lifetime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*K65jjAZOnsQGCFm7WkcAkw.jpeg" /></figure><p>Event sourcing promotes decentralized change handling and state querying.Events normally get triggered in response to <strong>commands</strong> issued by users of the system, background processes or from an external system. At its core, event sourcing focuses on system change <strong>events</strong>.</p><p>Designing systems with a focus on events and event logs provides core benefits as below:</p><ul><li>Encourages <a href="https://www.martinfowler.com/bliki/CQRS.html">command/query responsibility</a> (CQRS) separation, allowing writes and reads to be independently optimized</li><li>Provides state history and audit history that can be useful in answering the question of what did the system look like at specific times in the past, and what were all events up to that point</li></ul><h3>What is CQRS?</h3><p>CQRS also known as command/ query responsibility pattern helps us to scale components of the system independently of each other . Depending on the traffic and the number of calls to the application we might want to scale the read(query) or write(command) components of the systems independently.</p><p>Conceptually CQRS has two separate models one for read and another one for write. By separating the models we are able to decouple into separate logical process or perhaps on separate hardware.</p><p>A good example would be a e-commerce system where the user looking at the order web page that is rendered by the read(query) model. If a change is made to the order/write model the resulting change is communicated to the query model to render the updated change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*oQcrOGbV-MZ3K0Uklo-ghQ.png" /><figcaption><strong>Command Query Responsibility Pattern</strong></figcaption></figure><p>Before looking into the components of CQRS/Event sourcing in detail let us understand some of the DDD(Domain Driven Design) terms .</p><h3>DDD(Domain Driven Design)</h3><p>Every software application has a model that forms part of its core design. If a model is a true representation of the domain , then the model can adapt to changes easily and has changes of surviving as the software evolves. The fundamental purpose of DDD is to ensure that the model that is implemented in the code reflects the domain. Achieving and maintaining such an alignment is the true purpose of DDD.</p><h4>DDD terms:</h4><h4>Domain</h4><p>Domain can be defined as a sphere of knowledge or activity around which the entire business logic revolves. It is also referred as domain layer or domain logic.</p><h4><strong>Domain Model</strong></h4><p>Conceptual object model representing different parts of the domain, that will be used in our software. It includes both behavior and data</p><h4>Bounded Context</h4><p>The context to which a model can be applied. In a complex project we can have multiple domains, each with their own bounded context.</p><h4>Ubiquitous Language</h4><p>The common domain language used within the team and in the code .</p><h4>Entity</h4><p>An object that is defined primarily by its identity is called entity. Entity can contain attributes that are defined by the application user.</p><h4>Value Object</h4><p>An object that has attributes but no identity. It should be treated as immutable.</p><h4>Aggregate</h4><p>A collection of values and entities which are bound together by a root entity, known as aggregate root. The aggregate root encapsulates these objects and external objects should not reference its members. This guarantees the consistency of changes being made within the aggregate.</p><h4>Domain Event</h4><p>An event that is triggered from the model as a result of decision within the domain. Aggregates maintain the business rules and we implement decision points within aggregates and they are also responsible for creating Domain Events.</p><h3>Implementation of DDD</h3><p>Let’s get started with a simple implementation of Banking System. In such a system there is a single <strong>entity</strong>, representing a bank account. The account contains the current account balance and we should be able to withdraw or deposit money. Given this design we can identify following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bR_eE8lTPsuKJLYNi5iLJA.jpeg" /><figcaption><strong>Banking System</strong></figcaption></figure><p>As seen from the above diagram we have BankAccount as an entity. To support functionalities of creating account, add money and withdraw money we have commands CreateAccountCommand,DepositMoneyCommand and WithdrawMoneyCommand respectively. The events corresponding to these commands are AccountCreatedEvent, DepositMoneyEvent, WithdrawMoneyEvent, HoldAccountEvent, InactiveAccountEvent. For making changes to the entity state we use command service and to read the latest details of the account we use the query service .</p><h4>Core requirements of a banking system</h4><p>Below are some of the core requirements of a banking system</p><ul><li><strong>Consistency</strong>, the updates made to the account balance and the corresponding reads to the account should reflect the right balance</li><li><strong>Availability, </strong>our system should be highly available to respond to all user request for deposit, withdraw of money etc</li><li><strong>Traceability</strong>, In the event of any issues or auditing we should be able to answer any questions regarding the data and series of operations performed on it.</li><li><strong>Performance</strong>, Our customers should be able to perform any banking operation (withdraw,deposit etc) in a fast and efficient manner</li></ul><p>In a banking system maintaining the correct account balance is critical and we need to be fully transparent on our data and justify every operation that happened on the account, leading to its current balance. Our business decisions are based on current state of the system/account balance and we should ensure that there are no dirty reads that leads to incorrect decision in the system.</p><h4>How to ensure consistency?</h4><p>In CQRS system all the commands go through the <strong>stateful</strong> component called aggregate. In our example below it would be “BankAccountAggregate”. An aggregate handles commands and produces events based on its internal state. Aggregate uses this state to make business decisions. Since there is one instance of <strong>aggregate per bank account it ensures consistency</strong> and we do not need to rely on transactions and locks. The below diagram shows an example of sequence of events and how our aggregates handles them to ensure consistency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*kqGqygVi7oob9lXCVHZ6Vw.jpeg" /><figcaption><strong>Bank account aggregate receiving and processing commands</strong></figcaption></figure><h4>How to ensure availability?</h4><p>We should be able to respond to all incoming requests to the banking application with a short response time and we might have lot more read requests compared to write requests. In order for us to efficiently response to request the event store should be asynchronous and thereby the write requests can post the events and continue further without waiting for a response from event store. The read/write side of the application is decoupled in CQRS model it can be deployed on individual machines that can be scaled up independently based on the nature of traffic for reads/writes.</p><h4>How to ensure traceability?</h4><p>Since in EventSourcing we can recreate the state of the system based on all the events that lead to that state from the event store. We can effectively trace our application and justify each of the operations that happened on the account that lead to the current state/balance on the account.</p><p>Let us look at the steps to set up our project along with dependencies now.</p><h3>Project Dependencies</h3><p>We will use maven as our build tool and the main dependencies are as below</p><ul><li><strong>Spring Boot Starter Web </strong>— This dependency adds support for web application capabilities. It also contains Tomcat dependencies to run your application.</li><li><strong>Spring Boot Starter Data JPA</strong> — This dependency adds support for JPA and Hibernate. Basically, these dependencies are needed to connect to a database.</li><li><strong>Axon Spring Boot Starter</strong> — This is an important dependency for our application. It adds support for Axon Framework that helps us in implementing CQRS/Event sourcing in our application.</li><li><strong>H2 Database</strong> — This adds dependency for H2 in-memory database support.</li><li><strong>Spring Boot Starter Actuator</strong> — This enables Spring Boot actuator endpoints to gather run-time statistics about our application.</li><li><strong>Springfox Swagger2 and Springfox Swagger UI</strong> — These dependencies will help us enable Swagger for our Spring Boot application.We will be using Swagger for documenting our API end-points.</li></ul><h4>Why Axon Framework ?</h4><p>CQRS and Event Sourcing require specific infrastructure require specific infrastructure requirements for storing events (the Event Store) and event transmission (the Messaging Hub) of Commands, Queries, and Events.</p><p>The <a href="https://axoniq.io/product-overview/axon-framework">Axon Framework</a> makes it easier to implement CQRS and event sourcing with minimal boilerplate code and a proven, tested library. The framework provides APIs for easily writing commands, event-sourced aggregates, command handlers, events, event handlers, queries and query handlers. A typical architecture of Axon Framework looks like below and more details can be found here <a href="https://docs.axoniq.io/reference-guide/architecture-overview">https://docs.axoniq.io/reference-guide/architecture-overview</a>. Lets take a look at the basic components of CQRS implemented using Axon framework for our banking application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*7eIXexkbQHmtKFsW2UGDvA.jpeg" /><figcaption>Classic CQRS implementation</figcaption></figure><p>The different steps of execution are as below</p><ul><li>Command handler receives all the command request for creating account, deposit money, withdraw money etc</li><li>Command processing part takes care of handling all command and generating appropriate events. The business rules are executed and events are validated and persisted to event store.</li><li>After events are persisted they are published to message queue</li><li>Query processing application listens to events . The application takes the event payload and persists them in query store based on the required read models</li><li>Query handler is responsible for handling incoming read queries for our application. It retrieves the data from query store and outputs the same</li></ul><p>We will get started by creating a basic spring boot project using <a href="https://start.spring.io/">https://start.spring.io</a> and after creating our project let us add the below dependencies to POM.xml.</p><p>Please note that we will be excluding the axon-server-connector dependencies. This dependency is needed if we plan to run axon server separately and connect our application to the same. If you plan to run axon server separately you can checkout this article from <a href="https://www.infoq.com/articles/axon-server-cqrs-event-sourcing-java/">InfoQ</a> that gives you more insights</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>   &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.axonframework&lt;/groupId&gt;<br>   &lt;artifactId&gt;axon-spring-boot-starter&lt;/artifactId&gt;<br>   &lt;version&gt;4.1.2&lt;/version&gt;<br>   &lt;exclusions&gt;<br>    &lt;exclusion&gt;<br>     &lt;groupId&gt;org.axonframework&lt;/groupId&gt;<br>     &lt;artifactId&gt;axon-server-connector&lt;/artifactId&gt;<br>    &lt;/exclusion&gt;<br>   &lt;/exclusions&gt;<br> &lt;/dependency&gt;</pre><pre>&lt;!-- Swagger --&gt;<br> &lt;dependency&gt;<br>   &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>   &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;<br>   &lt;version&gt;2.9.2&lt;/version&gt;<br> &lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>   &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;<br>   &lt;version&gt;2.9.2&lt;/version&gt;<br> &lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;<br>   &lt;scope&gt;provided&lt;/scope&gt;<br> &lt;/dependency&gt;</pre><h4>Configuring the in memory H2 database</h4><p>Spring boot provides support for our application to connect to in memory store with username “sa” and empty password. Let us change the parameters as below. You can find more details on h2 in this good article by <a href="https://www.baeldung.com/spring-boot-h2-database">baeldung</a>.</p><pre><em>#H2 settings<br></em>spring.h2.console.enabled=true<br>spring.h2.console.path=/h2-console<br>spring.datasource.url=jdbc:h2:mem:testdb<br>spring.datasource.driverClassName=org.h2.Driver<br>spring.datasource.username=sa<br>spring.datasource.password=password<em><br></em>spring.jpa.hibernate.ddl-auto=create</pre><h4>Creating the Event Sourced Entity</h4><p>Let us create the model for our banking application. Our AccountEntityAggregate looks like as below</p><pre>@Aggregate<br><strong>public class </strong>AccountEntityAggregate {<br>    @AggregateIdentifier<br>    <strong>private </strong>String <strong>id</strong>;<br><br>    <strong>private double balance</strong>;<br><br>    <strong>private </strong>String <strong>currency</strong>;<br><br>    <strong>private </strong>String <strong>status</strong>;<br>}</pre><p>In the above entity the @Aggregate annotation indicates that this entity will be managed by Axon. This is similar to @Entity annotation in JPA. @AggregateIdentifier annotation is used to identify particular instance of Aggregate. It is similar to the @Id annotation in JPA.</p><p>We need a separate entity to handle the query view as below. As you can see from the below entity we can query current account balance, account status etc. Its basically a JPA entity</p><pre>@Entity<br><strong>public class </strong>AccountDetailsQueryEntity {<br><br>    @Id<br>    <strong>private </strong>String <strong>id</strong>;<br><br>    <strong>private double balance</strong>;<br><br>    <strong>private </strong>String <strong>currency</strong>;<br><br>    <strong>private </strong>Status <strong>status</strong>;<br><br>    <strong>public void </strong>setId(String id) {<br>        <strong>this</strong>.<strong>id </strong>= id;<br>    }<br><br>    <strong>public </strong>String getId() {<br>        <strong>return id</strong>;<br>    }<br><br>    <strong>public double </strong>getBalance() {<br>        <strong>return balance</strong>;<br>    }<br><br>    <strong>public void </strong>setBalance(<strong>double </strong>balance) {<br>        <strong>this</strong>.<strong>balance </strong>= balance;<br>    }<br><br>    <strong>public </strong>String getCurrency() {<br>        <strong>return currency</strong>;<br>    }<br><br>    <strong>public void </strong>setCurrency(String currency) {<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br><br>    <strong>public </strong>Status getStatus() {<br>        <strong>return status</strong>;<br>    }<br><br>    <strong>public void </strong>setStatus(Status status) {<br>        <strong>this</strong>.<strong>status </strong>= status;<br>    }<br><br>    @Override<br>    <strong>public </strong>String toString() {<br>        <strong>return &quot;AccountDetailsQueryEntity{&quot; </strong>+<br>                <strong>&quot;id=&#39;&quot; </strong>+ <strong>id </strong>+ <strong>&#39;\&#39;&#39; </strong>+<br>                <strong>&quot;, balance =&quot; </strong>+ <strong>balance </strong>+<br>                <strong>&quot;, currency=&#39;&quot; </strong>+ <strong>currency </strong>+ <strong>&#39;\&#39;&#39; </strong>+<br>                <strong>&quot;, status=&#39;&quot; </strong>+ <strong>status </strong>+ <strong>&#39;\&#39;&#39; </strong>+<br>                <strong>&#39;}&#39;</strong>;<br>    }<br>}</pre><p>We also need to define a JPA repository for the above entity. By extending the default CrudRepository( Spring Data repository) abstraction , it makes our life easier by significantly reducing the amount of boilerplate code required to implement data access layers for various persistence stores. More details about spring data repositories can be found <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference">here</a>.</p><pre><strong>public interface </strong>AccountDetailsRepository <strong>extends </strong>CrudRepository&lt;AccountDetailsQueryEntity, String&gt; {<br>}</pre><h4>Creating the Commands and Events</h4><p>Commands play an important role in CQRS architecture. They explicitly represent what our clients can do with our application. Commands can also be defined as user initiated actions that can change the state of your aggregate. In our banking application following are the main commands and events that we will be creating</p><h4>Primary Commands:</h4><p>BaseCommand<br>CreateAccountCommand<br>DepositMoneyCommand<br>WithdrawMoneyCommand</p><h4>Events created for above commands:</h4><p>BaseEvent<br>AccountCreatedEvent<br>ActivateAccountEvent<br>DepositMoneyEvent<br>WithdrawMoneyEvent<br>HoldAccountEvent<br>InactiveAccountEvent</p><p>Let us start defining these commands and events starting from the BaseCommand and Base Event.</p><h4>BaseCommand</h4><pre><strong>public class </strong>BaseCommand&lt;T&gt; {<br><br>    @TargetAggregateIdentifier<br>    <strong>public final </strong>T <strong>id</strong>;<br><br>    <strong>public </strong>BaseCommand(T id) {<br>        <strong>this</strong>.<strong>id </strong>= id;<br>    }<br>}</pre><h4>BaseEvent</h4><pre><strong>public class </strong>BaseEvent&lt;T&gt; {<br><br>    <strong>public final </strong>T <strong>id</strong>;<br><br>    <strong>public </strong>BaseEvent(T id) {<br>        <strong>this</strong>.<strong>id </strong>= id;<br>    }<br>}</pre><p>Important thing to notice here is the @TargetAggregateIdentifier on the BaseCommand class. This identifier is used by Axon to determine which instance of Aggregate should handle the command. We had put the annotation on the id field.</p><p>Let us implement the other commands as below. All the below commands will extend from the BaseCommand and provide the Generic type of id field as string.</p><h4>Create Bank Account Command</h4><pre><strong>public class </strong>CreateAccountCommand <strong>extends </strong>BaseCommand&lt;String&gt; {<br><br>    <strong>public final double accountBalance</strong>;<br><br>    <strong>public final </strong>String <strong>currency</strong>;<br><br>    <strong>public </strong>CreateAccountCommand(String id, <strong>double </strong>accountBalance, String currency) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>accountBalance </strong>= accountBalance;<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><h4>Deposit Money Command</h4><pre><strong>public class </strong>DepositMoneyCommand <strong>extends </strong>BaseCommand&lt;String&gt; {<br><br>    <strong>public final double amount</strong>;<br><br>    <strong>public final </strong>String <strong>currency</strong>;<br><br>    <strong>public </strong>DepositMoneyCommand(String id, <strong>double </strong>amount, String currency) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>amount </strong>= amount;<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><h4>Withdraw Money Command</h4><pre><strong>public class </strong>WithdrawMoneyCommand <strong>extends </strong>BaseCommand&lt;String&gt; {<br><br>    <strong>public final double amount</strong>;<br><br>    <strong>public final </strong>String <strong>currency</strong>;<br><br>    <strong>public </strong>WithdrawMoneyCommand(String id, <strong>double </strong>amount, String currency) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>amount </strong>= amount;<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><h4>Lets implement the events:<br>Account Created Event</h4><pre><strong>public class </strong>AccountCreatedEvent <strong>extends </strong>BaseEvent&lt;String&gt; {<br><br>    <strong>public final double balance</strong>;<br><br>    <strong>public final </strong>String <strong>currency</strong>;<br><br>    <strong>public </strong>AccountCreatedEvent(String id, <strong>double </strong>balance, String currency) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>balance </strong>= balance;<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><h4>Activate Account Event</h4><pre><strong>public class </strong>ActivateAccountEvent  <strong>extends </strong>BaseEvent&lt;String&gt;{<br>    <strong>public final </strong>Status <strong>status</strong>;<br><br>    <strong>public </strong>ActivateAccountEvent(String id, Status status) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>status </strong>= status;<br>    }<br>}</pre><h4>Deposit Money Event</h4><pre><strong>public class </strong>DepositMoneyEvent <strong>extends </strong>BaseEvent&lt;String&gt; {<br><br>    <strong>public final double creditAmount</strong>;<br><br>    <strong>public final </strong>String <strong>currency</strong>;<br><br>    <strong>public </strong>DepositMoneyEvent(String id, <strong>double </strong>creditAmount, String currency) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>creditAmount </strong>= creditAmount;<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><h4>Withdraw Money Event</h4><pre><strong>public class </strong>WithdrawMoneyEvent <strong>extends </strong>BaseEvent&lt;String&gt; {<br><br>    <strong>public final double debitAmount</strong>;<br><br>    <strong>public final </strong>String <strong>currency</strong>;<br><br>    <strong>public </strong>WithdrawMoneyEvent(String id, <strong>double </strong>debitAmount, String currency) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>debitAmount </strong>= debitAmount;<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><p><strong>Hold Account Event</strong></p><p>When we attempt to withdraw amount that is greater than the remaining balance on the account. The account is put temporarily on hold status. This hold status will be removed next time we try to do a deposit.</p><pre><strong>public class </strong>HoldAccountEvent <strong>extends </strong>BaseEvent&lt;String&gt;{<br>    <strong>public final </strong>Status <strong>status</strong>;<br>    <strong>public </strong>String <strong>errorMsg</strong>;<br><br>    <strong>public </strong>HoldAccountEvent(String id, Status status, String errorMsg) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>status </strong>= status;<br>        <strong>this</strong>.<strong>errorMsg </strong>= errorMsg;<br>    }<br>}</pre><h4>Inactive Account Event</h4><p>This event is triggered when we try to withdraw when the account status is not active.</p><pre><strong>public class </strong>InactiveAccountEvent <strong>extends </strong>BaseEvent&lt;String&gt;  {<br><br>    <strong>public </strong>String <strong>errorMsg</strong>;<br><br>    <strong>public </strong>InactiveAccountEvent(String id, String errorMsg) {<br>        <strong>super</strong>(id);<br>        <strong>this</strong>.<strong>errorMsg </strong>= errorMsg;<br><br>    }<br>}</pre><h4>Command Handlers/Event Handlers</h4><p>We need to implement handlers for the above commands and events. These handlers can be defined as methods on our Aggregate class. The main reason behind defining them as part of aggregate class is because they need access to state of the aggregate.</p><p>Lets define the AccountAggregate as below</p><pre><strong>package </strong>com.eventsourcing.eventsourcingdemo.aggregates;<br><br><strong>import </strong>com.eventsourcing.eventsourcingdemo.command.CreateAccountCommand;<br><strong>import </strong>com.eventsourcing.eventsourcingdemo.command.DepositMoneyCommand;<br><strong>import </strong>com.eventsourcing.eventsourcingdemo.command.WithdrawMoneyCommand;<br><strong>import </strong>com.eventsourcing.eventsourcingdemo.event.*;<br><strong>import </strong>org.axonframework.commandhandling.CommandHandler;<br><strong>import </strong>org.axonframework.eventsourcing.EventSourcingHandler;<br><strong>import </strong>org.axonframework.modelling.command.AggregateIdentifier;<br><strong>import </strong>org.axonframework.modelling.command.AggregateLifecycle;<br><strong>import </strong>org.axonframework.spring.stereotype.Aggregate;<br><br>@Aggregate<br><strong>public class </strong>BankAccountAggregate {<br><br>    @AggregateIdentifier<br>    <strong>private </strong>String <strong>id</strong>;<br><br>    <strong>private double balance</strong>;<br><br>    <strong>private </strong>String <strong>currency</strong>;<br><br>    <strong>private </strong>Status <strong>status</strong>;<br><br>    <strong>private </strong>String <strong>errorMsg</strong>;<br><br>    <strong>public </strong>BankAccountAggregate() {<br>    }<br><br>    @CommandHandler<br>    <strong>public </strong>BankAccountAggregate(CreateAccountCommand createAccountCommand){<br>        AggregateLifecycle.<em>apply</em>(<strong>new </strong>AccountCreatedEvent(createAccountCommand.<strong>id</strong>, createAccountCommand.<strong>accountBalance</strong>, createAccountCommand.<strong>currency</strong>));<br>    }<br><br>    @EventSourcingHandler<br>    <strong>protected void </strong>on(AccountCreatedEvent accountCreatedEvent){<br>        <strong>this</strong>.<strong>id </strong>= accountCreatedEvent.<strong>id</strong>;<br>        <strong>this</strong>.<strong>balance </strong>= accountCreatedEvent.<strong>balance</strong>;<br>        <strong>this</strong>.<strong>currency </strong>= accountCreatedEvent.<strong>currency</strong>;<br>        <strong>this</strong>.<strong>status </strong>= Status.<strong><em>CREATED</em></strong>;<br>        AggregateLifecycle.<em>apply</em>(<strong>new </strong>ActivateAccountEvent(<strong>this</strong>.<strong>id</strong>, Status.<strong><em>ACTIVATED</em></strong>));<br><br>    }<br><br>    @CommandHandler<br>    <strong>protected void </strong>on(DepositMoneyCommand depositMoneyCommand){<br>        AggregateLifecycle.<em>apply</em>(<strong>new </strong>DepositMoneyEvent(depositMoneyCommand.<strong>id</strong>, depositMoneyCommand.<strong>amount</strong>, depositMoneyCommand.<strong>currency</strong>));<br>    }<br><br>    @EventSourcingHandler<br>    <strong>protected void </strong>on(DepositMoneyEvent depositMoneyEvent){<br><br>        <strong>if </strong>(<strong>this</strong>.<strong>balance </strong>&lt; 0 &amp; (<strong>this</strong>.<strong>balance </strong>+ depositMoneyEvent.<strong>creditAmount</strong>) &gt;= 0){<br>            <strong>if</strong>(<strong>this</strong>.<strong>status </strong>!= Status.<strong><em>ACTIVATED</em></strong>) {<br>                AggregateLifecycle.<em>apply</em>(<strong>new </strong>ActivateAccountEvent(depositMoneyEvent.<strong>id</strong>, Status.<strong><em>ACTIVATED</em></strong>));<br><br>            }<br>        }<br><br>        <strong>this</strong>.<strong>balance </strong>+= depositMoneyEvent.<strong>creditAmount</strong>;<br>    }<br><br>    @CommandHandler<br>    <strong>protected void </strong>on(WithdrawMoneyCommand withdrawMoneyCommand){<br>        AggregateLifecycle.<em>apply</em>(<strong>new </strong>WithdrawMoneyEvent(withdrawMoneyCommand.<strong>id</strong>, withdrawMoneyCommand.<strong>amount</strong>, withdrawMoneyCommand.<strong>currency</strong>));<br>    }<br><br>    @EventSourcingHandler<br>    <strong>protected void </strong>on(WithdrawMoneyEvent withdrawMoneyEvent){<br>        <strong>if </strong>(<strong>this</strong>.<strong>status </strong>!= Status.<strong><em>ACTIVATED</em></strong>) {<br>            AggregateLifecycle.<em>apply</em>(<strong>new </strong>InactiveAccountEvent(withdrawMoneyEvent.<strong>id</strong>, <strong>&quot;inactive account&quot;</strong>));<br>            <strong>return</strong>;<br>        }<br><br>        <strong>if </strong>(<strong>this</strong>.<strong>balance </strong>&gt;= 0 &amp; (<strong>this</strong>.<strong>balance </strong>- withdrawMoneyEvent.<strong>debitAmount</strong>) &lt; 0){<br>            AggregateLifecycle.<em>apply</em>(<strong>new </strong>HoldAccountEvent(withdrawMoneyEvent.<strong>id</strong>, Status.<strong><em>HOLD</em></strong>, <strong>&quot;insufficient balance&quot;</strong>));<br>        }<br>        <strong>else </strong>{<br>            <strong>this</strong>.<strong>balance </strong>-= withdrawMoneyEvent.<strong>debitAmount</strong>;<br>        }<br><br>    }<br><br>    @EventSourcingHandler<br>    <strong>protected void </strong>on(ActivateAccountEvent activateAccountEvent){<br>        <strong>this</strong>.<strong>status </strong>= activateAccountEvent.<strong>status</strong>;<br>    }<br><br>    @EventSourcingHandler<br>    <strong>protected void </strong>on(HoldAccountEvent holdAccountEvent){<br>        <strong>this</strong>.<strong>status </strong>= holdAccountEvent.<strong>status</strong>;<br>        <strong>this</strong>.<strong>errorMsg </strong>= holdAccountEvent.<strong>errorMsg</strong>;<br>    }<br><br>    @EventSourcingHandler<br>    <strong>protected void </strong>on(InactiveAccountEvent inactiveAccountEvent){<br>        <strong>this</strong>.<strong>errorMsg </strong>= inactiveAccountEvent.<strong>errorMsg</strong>;<br>    }<br>}</pre><p>As you can see from the above code there are three command handlers corresponding to the three commands we create i.e for create account, deposit money, withdraw money . In each of these command handlers we call AggregateLifecycle.<em>apply() method to register the events. </em>Each of these events are handled by the corresponding EventSourcingHandlers for those events.</p><p>Also any state changes of the aggregate should be handled inside the EventSourcingHandlers. AggregateIdentifier must be set in the first method annotated with EventSourcingHandler. Another important point is we had defined a no-arg constructor since its needed by the Axon framework to create an empty instance of aggregate and then apply the events. If there is no-arg constructor Axon framework will throw an exception</p><p>We have to define RESTFul interfaces for our banking application to perform account operations over API’s.</p><p>Lets start with defining the basic DTO objects that our service layer will be using</p><h4>Data Transfer Objects</h4><p>These are standard POJO’s with getter and setter methods that our service layer will use.</p><p><strong>CreateAccountDTO</strong> is used for creating new account</p><pre><strong>public class </strong>CreateAccountDTO {<br>    <strong>private double startingBalance</strong>;<br><br>    <strong>private </strong>String <strong>currency</strong>;<br><br>    <strong>public double </strong>getStartingBalance() {<br>        <strong>return startingBalance</strong>;<br>    }<br><br>    <strong>public void </strong>setStartingBalance(<strong>double </strong>startingBalance) {<br>        <strong>this</strong>.<strong>startingBalance </strong>= startingBalance;<br>    }<br><br>    <strong>public </strong>String getCurrency() {<br>        <strong>return currency</strong>;<br>    }<br><br>    <strong>public void </strong>setCurrency(String currency) {<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><p><strong>DepositMoneyDTO </strong>is used for adding money to the account</p><pre><strong>public class </strong>DepositMoneyDTO {<br>    <strong>private double creditAmount</strong>;<br><br>    <strong>private </strong>String <strong>currency</strong>;<br><br>    <strong>public double </strong>getCreditAmount() {<br>        <strong>return creditAmount</strong>;<br>    }<br><br>    <strong>public void </strong>setCreditAmount(<strong>double </strong>creditAmount) {<br>        <strong>this</strong>.<strong>creditAmount </strong>= creditAmount;<br>    }<br><br>    <strong>public </strong>String getCurrency() {<br>        <strong>return currency</strong>;<br>    }<br><br>    <strong>public void </strong>setCurrency(String currency) {<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><p><strong>WithdrawMoneyDTO</strong> is used for withdrawing money from the account</p><pre><strong>public class </strong>WithdrawMoneyDTO {<br>    <strong>private double amount</strong>;<br><br>    <strong>private </strong>String <strong>currency</strong>;<br><br>    <strong>public double </strong>getAmount() {<br>        <strong>return amount</strong>;<br>    }<br><br>    <strong>public void </strong>setAmount(<strong>double </strong>amount) {<br>        <strong>this</strong>.<strong>amount </strong>= amount;<br>    }<br><br>    <strong>public </strong>String getCurrency() {<br>        <strong>return currency</strong>;<br>    }<br><br>    <strong>public void </strong>setCurrency(String currency) {<br>        <strong>this</strong>.<strong>currency </strong>= currency;<br>    }<br>}</pre><p>Let us define the Service layer that will be using these DTO’s to handle the commands and queries. The service layer has two main classes i.e the AccountCommandService and AccountDetailsQueryService for the command and query functions. The interface and implementation classes for the service layer are defined as below.</p><p><strong>AccountCommandService</strong></p><pre><strong>public interface </strong>AccountCommandService {<br><br>    <strong>public </strong>CompletableFuture&lt;String&gt; createAccount(CreateAccountDTO createAccountDTO);<br>    <strong>public </strong>CompletableFuture&lt;String&gt; depositMoneyToAccount(String accountNum, DepositMoneyDTO depositMoneyDTO);<br>    <strong>public </strong>CompletableFuture&lt;String&gt; withdrawMoneyFromAccount(String accountNum, WithdrawMoneyDTO withdrawMoneyDTO);<br>}</pre><p><strong>AccountDetailsQueryService</strong></p><pre><strong>public interface </strong>AccountDetailsQueryService {<br>    <strong>public </strong>List&lt;Object&gt; listEventsForAccount(String accountNumber);<br>    <strong>public </strong>AccountDetailsQueryEntity getAccountDetails(String accountNumber);</pre><pre>}</pre><p><strong>AccountCommandServiceImpl</strong></p><pre>@Service<br><strong>public class </strong>AccountCommandServiceImpl <strong>implements </strong>AccountCommandService {<br>    <strong>private final </strong>CommandGateway <strong>commandGateway</strong>;<br><br>    <strong>public </strong>AccountCommandServiceImpl(CommandGateway commandGateway)    <br>    {<br>        <strong>this</strong>.<strong>commandGateway </strong>= commandGateway;<br>    }<br><br>    @Override<br>    <strong>public </strong>CompletableFuture&lt;String&gt; createAccount(CreateAccountDTO createAccountDTO) {<br>        <strong>return commandGateway</strong>.send(<strong>new </strong>CreateAccountCommand(UUID.<em>randomUUID</em>().toString(), createAccountDTO.getStartingBalance(), createAccountDTO.getCurrency()));<br>    }<br><br>    @Override<br>    <strong>public </strong>CompletableFuture&lt;String&gt; depositMoneyToAccount(String accountNumber, DepositMoneyDTO depositMoneyDTO) {<br>        <strong>return commandGateway</strong>.send(<strong>new </strong>DepositMoneyCommand(accountNumber, depositMoneyDTO.getCreditAmount(), depositMoneyDTO.getCurrency()));<br>    }<br><br>    @Override<br>    <strong>public </strong>CompletableFuture&lt;String&gt; withdrawMoneyFromAccount(String accountNumber, WithdrawMoneyDTO withdrawMoneyDTO) {<br>        <strong>return commandGateway</strong>.send(<strong>new </strong>WithdrawMoneyCommand(accountNumber, withdrawMoneyDTO.getAmount(), withdrawMoneyDTO.getCurrency()));<br>    }<br>}</pre><p><strong>AccountDetailsQueryServiceImpl</strong></p><pre>@Service<br><strong>public class </strong>AccountDetailsQueryServiceImpl <strong>implements </strong>AccountDetailsQueryService{<br>    <strong>private final </strong>EventStore <strong>eventStore</strong>;<br><br>    <strong>public </strong>AccountDetailsQueryServiceImpl(EventStore eventStore) {<br>        <strong>this</strong>.<strong>eventStore </strong>= eventStore;<br>    }<br><br>    @Override<br>    <strong>public </strong>List&lt;Object&gt; listEventsForAccount(String accountNumber) {<br>        <strong>return eventStore</strong>.readEvents(accountNumber).asStream().map( s -&gt; s.getPayload()).collect(Collectors.<em>toList</em>());<br>    }</pre><pre>  @Override<br>  <strong>public </strong>AccountDetailsQueryEntity getAccountDetails(String <br>         accountNumber) {<br>        <strong>return accountRepository</strong>.findById(accountNumber).get();<br>  }</pre><p>Some of the important points to note here is that</p><ul><li>AccountCommandServiceImpl uses CommandGateway and the default implementation is provided by Axon and we send a command through the command gateway and wait for response.</li><li>AccountDetailsQueryServiceImpl uses the eventstore provided by Axon to read events for a particular AggregateId. We call the readEvents() method with AggregateId/accountNumber as input.</li></ul><h4>Account Query Manager</h4><p>When we invoke commands for deposit money ,withdraw money, account creation etc there is a domain event that gets generated from aggregate and it is persisted in the event store. The latest details of the particular instance of aggregate should also be reflected as part of the query entity. We need to build a handler that looks into aggregate events and populates the query entities</p><pre>@Component<br><strong>public class </strong>AccountQueryManager {<br><br>    @Autowired<br>    <strong>private </strong>AccountDetailsRepository <strong>accountDetailsRepository</strong>;<br><br>    @Autowired<br>    @Qualifier(<strong>&quot;accountAggregateRepository&quot;</strong>)<br>    <strong>private </strong>EventSourcingRepository&lt;BankAccountAggregate&gt; <strong>accountAggregateRepository</strong>;<br><br>    @EventSourcingHandler<br>    <strong>void </strong>on(BaseEvent event){<br>        persistAccount(buildQueryAccount(getAccountFromEvent(event)));<br>    }<br><br>    <strong>private </strong>AccountDetailsQueryEntity buildQueryAccount(BankAccountAggregate accountAggregate){<br>        AccountDetailsQueryEntity accountQueryEntity = findExistingOrCreateQueryAccount(accountAggregate.getId());<br><br>        accountQueryEntity.setId(accountAggregate.getId());<br>        accountQueryEntity.setBalance(accountAggregate.getBalance());<br>        accountQueryEntity.setCurrency(accountAggregate.getCurrency());<br>        accountQueryEntity.setStatus(accountAggregate.getStatus());<br><br>        <strong>return </strong>accountQueryEntity;<br>    }<br><br><br>    <strong>private </strong>BankAccountAggregate getAccountFromEvent(BaseEvent event){<br>        <strong>return accountAggregateRepository</strong>.load(event.<strong>id</strong>.toString()).getWrappedAggregate().getAggregateRoot();<br>    }<br><br>    <strong>private </strong>AccountDetailsQueryEntity findExistingOrCreateQueryAccount(String id){<br>        <strong>return accountDetailsRepository</strong>.findById(id).isPresent() ? <strong>accountDetailsRepository</strong>.findById(id).get() : <strong>new </strong>AccountDetailsQueryEntity();<br>    }<br><br><br>    <strong>private void </strong>persistAccount(AccountDetailsQueryEntity accountQueryEntity){<br>        <strong>accountDetailsRepository</strong>.save(accountQueryEntity);<br>    }<br>}</pre><p>The main workflow for the above AccountQueryManager is as below</p><ul><li>We inject instance of AccountDetailsRepository and the event sourcing repository BankAccountAggregate that is managed by Axon.</li><li>We need a method to handle events occurring on the aggregate. The method marked with @EventSourcingHandler acts as the method that handles events created from aggregate. Inside this method we use the instance of EventSourcingRepository to extract the correct BankAccountAggregate class from event store.</li><li>If we are able to find an instance of BankAccountAggregate from event store in the above step , we use this instance to populate AccountDetailsQueryEntity object</li><li>We use the AccountDetailsRepository to save AccountDetailsQueryEntity object to the query store.</li></ul><h4>Defining Rest Interfaces</h4><p>In order for the end user to interact with our application we need the API layer/Rest Interfaces defined for our banking application. We will implement two controllers one for handling commands and another one for handling queries.</p><p>The main workflow for the controllers are as below</p><ul><li>Request is sent to the controllers for create account, deposit money, withdraw money etc</li><li>Controller internally calls service methods that internally call the CommandGateway to trigger the commands</li><li>EventHandlers execute the command and the result is sent back to the end point</li></ul><p>The controller to handle the command is implemented as below</p><pre>@RequestMapping(value = <strong>&quot;/account&quot;</strong>)<br>@Api(value = <strong>&quot;Banking Account Commands&quot;</strong>, description = <strong>&quot;Banking Account Command Related Endpoints&quot;</strong>, tags = <strong>&quot;Bank Account Commands&quot;</strong>)<br><strong>public class </strong>AccountCommandController {<br><br>    <strong>private final </strong>AccountCommandService <strong>accountCommandService</strong>;<br><br>    <strong>public </strong>AccountCommandController(AccountCommandService accountCommandService) {<br>        <strong>this</strong>.<strong>accountCommandService </strong>= accountCommandService;<br>    }<br><br>    @PostMapping(value = <strong>&quot;/create&quot;</strong>)<br>    <strong>public </strong>CompletableFuture&lt;String&gt; createAccount(@RequestBody CreateAccountDTO createAccountDTO){<br>        <strong>return accountCommandService</strong>.createAccount(createAccountDTO);<br>    }<br><br>    @PutMapping(value = <strong>&quot;/credits/{accountNumber}&quot;</strong>)<br>    <strong>public </strong>CompletableFuture&lt;String&gt; creditMoneyToAccount(@PathVariable(value = <strong>&quot;accountNumber&quot;</strong>) String accountNumber,<br>                                                          @RequestBody DepositMoneyDTO depositMoneyDTO){<br>        <strong>return accountCommandService</strong>.depositMoneyToAccount(accountNumber, depositMoneyDTO);<br>    }<br><br>    @PutMapping(value = <strong>&quot;/debits/{accountNumber}&quot;</strong>)<br>    <strong>public </strong>CompletableFuture&lt;String&gt; debitMoneyFromAccount(@PathVariable(value = <strong>&quot;accountNumber&quot;</strong>) String accountNumber,<br>                                                           @RequestBody WithdrawMoneyDTO withdrawMoneyDTO){<br>        <strong>return accountCommandService</strong>.withdrawMoneyFromAccount(accountNumber, withdrawMoneyDTO);<br>    }<br>}</pre><p>The controller to handle queries is implemented as below</p><pre>@RestController<br>@RequestMapping(value = <strong>&quot;/account&quot;</strong>)<br>@Api(value = <strong>&quot;Bank Account Queries&quot;</strong>, description = <strong>&quot;Bank Account Query Events Endpoint&quot;</strong>, tags = <strong>&quot;Bank Account Queries&quot;</strong>)<br><strong>public class </strong>AccountQueryController {<br>    <strong>private final </strong>AccountDetailsQueryService <strong>accountDetailsQueryService</strong>;<br><br>    <strong>public </strong>AccountQueryController(AccountDetailsQueryService accountDetailsQueryService) {<br>        <strong>this</strong>.<strong>accountDetailsQueryService </strong>= accountDetailsQueryService;<br>    }<br><br>    @GetMapping(<strong>&quot;/{accountNumber}&quot;</strong>)<br>    <strong>public </strong>AccountDetailsQueryEntity getAccountDetails(@PathVariable(value = <strong>&quot;accountNumber&quot;</strong>) String accountNumber){<br>        <strong>return accountDetailsQueryService</strong>.getAccountDetails(accountNumber);<br>    }<br><br>    @GetMapping(<strong>&quot;/{accountNumber}/events&quot;</strong>)<br>    <strong>public </strong>List&lt;Object&gt; listEventsForAccount(@PathVariable(value = <strong>&quot;accountNumber&quot;</strong>) String accountNumber){<br>        <strong>return accountDetailsQueryService</strong>.listEventsForAccount(accountNumber);<br>    }<br>}</pre><h4>Configuring swagger</h4><p>Swagger provides a nice user interface to query and test our REST API endpoints. We had added dependencies for swagger in the beginning of our set up for the project. We also need a config for swagger to scan the base packages where our API’s are defined. The basic configuration for swagger can be defined as below</p><pre>@Configuration<br>@EnableSwagger2<br><strong>public class </strong>SwaggerConfig {<br><br>    @Bean<br>    <strong>public </strong>Docket apiDocket(){<br>        <strong>return new </strong>Docket(DocumentationType.<strong><em>SWAGGER_2</em></strong>)<br>                .select()<br>                .apis(RequestHandlerSelectors.<em>basePackage</em>(<strong>&quot;com.eventsourcing.eventsourcingdemo&quot;</strong>))<br>                .paths(PathSelectors.<em>any</em>())<br>                .build()<br>                .apiInfo(getApiInfo());<br>    }<br><br>    <strong>private </strong>ApiInfo getApiInfo(){<br>        <strong>return new </strong>ApiInfo(<br>                <strong>&quot;Event Sourcing using Axon and Spring Boot&quot;</strong>,<br>                <strong>&quot;Application to demonstrate Event Sourcing of banking app using Axon and Spring Boot&quot;</strong>,<br>                <strong>&quot;1.0.0&quot;</strong>,<br>                <strong>&quot;Terms of Service&quot;</strong>,<br>                <strong>&quot;&quot;</strong>,<br>                <strong>&quot;&quot;</strong>,<br>                <strong>&quot;&quot;</strong>);<br>    }<br><br>}</pre><h4>Building our application and running the same</h4><p>We can run <em>mvn clean package spring-boot:run </em>to build and run our application and the swagger-ui can be accessed at <a href="http://localhost:8080/swagger-ui.html"><em>http://localhost:8080/swagger-ui.html</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0Yai2zSGYwg5HMXwTJzAQ.png" /></figure><p>As we can see above swagger ui provides us an interface to execute our commands and queries . Lets walk through the steps of creating account, deposit money, withdraw money etc and verify all the results in each step</p><h4>Creating the account</h4><p>Let us create an account with starting balance as 100 and lets verify the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e91jNjNH6zIwbDUDjrwO1g.png" /></figure><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3v4pB-mqk6qw4QhGmNbxfQ.png" /></figure><p>As you can see the HTTP response code is 200 indicating that the call was successful. The output also displays the created account id as an UUID . We can check the data from the h2-console (<em>http://localhost:8080/h2-console) </em>also as below . The database that we had configured in application.properties is testdb with username “sa” and password as “password”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ndnv4utOHm5SB37ZUJf9rA.png" /></figure><p>As part of the account creation there are two events created AccountCreateEvent,ActivateAccountEvent and we can query the DOMAIN_EVENT_ENTRY to get the details using the query below</p><pre>SELECT PAYLOAD_TYPE , AGGREGATE_IDENTIFIER, SEQUENCE_NUMBER , PAYLOAD   FROM DOMAIN_EVENT_ENTRY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heZS4dIu0JbXQKe35Mf9jA.png" /></figure><p>As we know that in CQRS we have an event store where all command related events/writes are store and we have a read entity/query model (AccountDetailsQueryEntity) from where we can get account related details like current balance etc.</p><p>We can query the ACCOUNT_DETAILS_QUERY_ENTITY to get the current balance as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmw8Uon05rg4GrImj8xxtw.png" /></figure><p>We can also verify the same using our endpoint for account/{accountNumber}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giELUtX8eFUS4aHCEkVlqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWVibr_O33VXOMZm1JleqA.png" /></figure><h4>Deposit money to the bank account</h4><p>Let us deposit 100$ into our bank account using the deposit money api as below. The account number passed as input is the one that we generated above using create account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJeHTnJ3ONEiTrEjR3QSpA.png" /></figure><p>After successful execution of above request we can see deposit event generated as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpq8Rwp2i3Riy_XXpF9aZg.png" /></figure><p>Lets verify if the account balance got updated with our deposit by invoking /account/{accountNumber} endpoint as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYCVJ4Jq8dfwhtlM-nzzWA.png" /></figure><h4>Withdraw money from the bank account</h4><p>Let us try to withdraw 200$ from the bank account using the withdraw money API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJ-6u1km536X2KfnEgVdVg.png" /></figure><p>Let us verify if the withdraw event got generated for the above request as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*td3fG_ane90wcFPDMSZCqg.png" /></figure><p>Let us verify the events getting generated using the endpoint <strong>/account/{accountNumber}/events</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZoJIVHd5BmAdtYDMaVF8Q.png" /></figure><p>Let us also verify the account balance as below using <strong>/account/{accountNumber}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6f1fRF4GsoV-0Oz9Qdwyow.png" /></figure><p>Let us try to withdraw another 100$ and check if our account is put on Hold Status with HoldAccountEvent getting generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Brv0skYlgZZdbNje4DlC_w.png" /></figure><p>As we can see below we can see HoldAccountEvent getting generated since we are trying to withdraw more than the account balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MM6N3v9rEA8HA5J0X7Hrtg.png" /></figure><h4>Listing all the events for the bank account</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wN6Gu1o06rZAk_gnv8SVtw.png" /></figure><p>The results are shown as below and you can see all the events displayed in a consolidated view .</p><p>We can verify all the events generated so far using the endpoint <strong>/account/{accountNumber}/events</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVqSsNmlUM2BKSB6qMJ8Qg.png" /></figure><h4>Conclusion</h4><p>We have demonstrated how Event sourcing and CQRS can be implemented with a spring boot application with Axon framework. Axon framework provides us as all the backbone components to implement Event Sourcing/CQRS. This application might not be covering all aspects of a complete banking application but it is a sample application that helps in understanding the overall implementation of CQRS/Event sourcing.</p><p>Banks have started adopting CQRS and Event sourcing patterns very well and one such example is Memo Bank . You can find more details here <a href="https://memo.bank/en/magazine/choosing-an-architecture/">https://memo.bank/en/magazine/choosing-an-architecture/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eaa9ddde89f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autoscaling spring boot applications running on K8s cluster in AWS]]></title>
            <link>https://raghuramg.medium.com/autoscaling-spring-boot-applications-running-on-k8s-cluster-in-aws-3b22f13b89e4?source=rss-a3ba45180fd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b22f13b89e4</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[raghuram gururajan]]></dc:creator>
            <pubDate>Sat, 26 Dec 2020 20:16:58 GMT</pubDate>
            <atom:updated>2020-12-26T20:16:58.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bm_ML7QF20Sydp_y" /></figure><p>Photo by<a href="https://unsplash.com/@exdigy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Dominik Lückmann</a> on<a href="https://unsplash.com/s/photos/container?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></p><p>In this article, we will understand how we can create a simple spring boot micro service and deploy on Kubernetes cluster running on AWS and autoscale the application. After reading this article you will be able to deploy your own micro service on AWS and autoscale based on predefined parameters.</p><p>You might be wondering if we are able to deploy the Spring boot micro service on EC2 VM’s and individually scale these instances do we still need containers? If we want to achieve true scaling, low cost, faster deployment and consistency then containers are a must for micro services. Individual applications running on containers can be scaled independently of each other.</p><p>Time to deploy and start application on containers is much faster compared to bare metal machines or VM’s. Overall, containers start up time is in seconds, also container orchestration takes care of better utilization of resources. One of the most popular tool used for container orchestration is Kubernetes. It provides platform for container orchestration along with other useful services including container creation, scale-up/down , rollbacks, load balancing and service discovery.</p><h3><strong>Basics:</strong></h3><p>Containers are an abstraction at the app layer that packages code and dependencies together as below. By containerizing the application platform and its dependencies alone, differences in OS distributions and underlying infrastructure are abstracted away. Virtual machines are abstraction of physical hardware turning one server into many servers. Containers by contrast, isolate application’s execution environment from one another, but share the same underlying OS kernel.</p><p>Most of our web applications consist of several components like web server, database, cache etc and containers make it possible to compose these services into functional units. Each of these units can be treated as a separate container and can be maintained, updated and modified independently of others. Lightweight and portable containers make it easier for us to build and maintain micro services based applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOl0O-oqdIBjaxputhgfGA.png" /></figure><h3><strong>What is Docker ?</strong></h3><p>Docker is an open source project that was launched in 2013 to popularize the container technology and its a platform that helps developers build light weight and portable software containers.</p><p>Docker consist of a docker engine that is a core component and it has a server and client, communication between the two is via Rest API. The server contains a docker daemon called dockerd which can create and manage containers. The Rest API is used to instruct docker daemon what action to perform. The client is a CLI(command line interface) that is used to enter docker commands</p><h4><strong>The main components of docker are:</strong></h4><p>1)Docker client and server</p><p>2)Docker image</p><p>3)Docker registry</p><p>4)Docker container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*nY_4yhP1ZkB5cy2z" /></figure><h4><strong>Docker Client and Docker Server</strong></h4><p>Docker client(Command Line Interface-CLI) is the primary way to interact with docker. When the user types command such as docker pull command, the client sends an instruction to the docker daemon to perform the operation by interacting with other components(image, container and registry). The communication between the Docker Client and Docker host is through REST API.</p><p>Docker daemon is actually a server that interacts with operating system and performs services. It constantly listens to the Docker API requests issued by client to see if it needs to service any requests and manages docker objects like images, containers, networks and volumes.</p><h4><strong>Docker image</strong></h4><p>Docker image can be considered as a template that contains instructions for docker container. The template is defined in a language called YAML (Yet Another Markup Language). Docker image is built using YAML and stored as a file in the docker registry and can be treated as a portable file that contains specification of which components the container will run. Each image consist of several key layers and each layer depends on the layer below it. Image layers are created by executing each command in the docker file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*cBKwvejcG5BiyTzx" /></figure><p>From the above docker image we can see that there are four layers of instructs</p><ul><li><strong>From</strong> : Base image to build our image</li><li><strong>Pull</strong> : Adds file from docker repository</li><li><strong>Run</strong>: Builds your container</li><li><strong>Cmd</strong>: Specifies which command to run within the container</li></ul><h4><strong>Docker Registry</strong></h4><p>Docker registry is a collection of docker images and it’s a repository to host various types of images. Docker Hub is one of publicly accessible docker registry that contain official docker images from open source projects and software vendors and also unofficial images from general public. You can provide a tag name with each image so that it is easy for people to find and share them in registry. You can also create your own registry for your use internally. The main commands used for interaction with registry are PUSH and PULL. PULL command retrieves the docker image from registry and PUSH command is used to push a latest created image to registry.</p><h4><strong>Docker Container</strong></h4><p>Docker container is a runnable instance of container image. It is portable and can be considered as an executable package of application and dependencies together. A container is defined by its image and also the configuration options and by default container is well isolated from other containers and the host machine. A container can be started by a simple command using docker RUN as below</p><p><strong>docker run ubuntu</strong></p><p>If the image is not available locally then as the first step the image is downloaded from registry and an instance of container will be created from the image and it becomes available for your execution.</p><h3><strong>What is Kubernetes ?</strong></h3><p>Containers are lightweight, flexible and faster but with increased number of containers and management of the same if we don’t take right actions to manage them it will affect the availability of the system.</p><p>Kubernetes provides the platform to automate activities like container creation, deployment, replacement and scale-up/down of containers, rollbacks etc. It also provides other useful services for micro services like Service Discovery, Load Balancing and Fault Tolerance etc. The good part is with Kubernetes we don’t need any additional framework to implement these additional services and they are provided out of box for us to leverage the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LboDWBiJHc6N50Ay" /></figure><h4><strong>Pods</strong></h4><p>Pods are basic building blocks of Kubernetes. To reduce coupling the best practice is to use single container pods. If we need two instances of our service running, we will need to have two instances of pods running.</p><h4><strong>Controllers</strong></h4><p>Controller consist of individual process that monitor the state of cluster and continuously aim in driving the current state towards the provided desired state of the cluster. Example of controllers are Deployment , ReplicaSet and NodeController.</p><h4><strong>Services</strong></h4><p>Services add a layer of abstraction over the pods. The abstraction defines a policy through which pods are accessed. Services also load balance request across pods.</p><h4><strong>Volumes</strong></h4><p>Containers are ephemeral and once the container crashes , all its data is lost. Volumes help in restoring container to the previous known state. Volumes provide storage for the container and they can be attached to any pod.</p><h4><strong>ConfigMaps and Secrets</strong></h4><p>ConfigMaps and Secrets allow users to configure applications externally. Allows passing sensitive information without hardcoding the same inside the container.</p><h4><strong>Deployments</strong></h4><p>Deployment helps in transitioning current environment to the desired state in a controlled manner. Deploys replication controller or replica set which further deploys the pods.</p><h4><strong>StatefulSet</strong></h4><p>StatefulSet is the ReplicaSet equivalent for stateful application. Maintains uniqueness of each pod across different deployments and scaling operations.</p><h4><strong>Basic Architecture of Kubernetes Cluster</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7m2KAIqGxBroZxl5" /></figure><p>As you can see above the basic architecture building blocks of kubernetes consist of a Master Node and one or more Worker Nodes. The primary components and their role are as below</p><h4><strong>Controller Manager</strong></h4><p>This is the primary component of the Master node that runs controller processes related to replication, endpoints, node and service account. Controller manager ensures that it monitors and responds to situation when nodes go down or ensuring pod replication etc.</p><h4><strong>Scheduler</strong></h4><p>Scheduler is responsible for allocating a node when a pod is created.</p><h4><strong>API Server</strong></h4><p>API server is the interface for Kubernetes control plane. All interactions have to go through API Server. External and internal components in Kubernetes cluster interact through API Server.</p><h4><strong>Kubelet</strong></h4><p>Kubelet is an agent that runs on each node and ensures that the containers inside the pod are running.</p><h4><strong>Container Runtime</strong></h4><p>Container runtime is the implementation of runtime engine responsible for running containers. Kubernetes supports different container runtimes like Docker, CRI-O, Container etc.</p><h4><strong>Kube-Proxy</strong></h4><p>Kube-Proxy is a component that allows the external access of internally deployed applications running on pod. Kube proxy configures the network rules to allow application access</p><p>Different modes for configuring network rules include</p><ul><li>Userspace</li><li>IPtables</li><li>IPVS</li></ul><h4><strong>ClusterStore</strong></h4><p>Cluster store is a distributed store used to store all data that is used to manage the cluster. ETCD is a distributed key-value cluster store used in Kubernetes. When we have multiple nodes and multiple masters in the cluster, etc maintains all the information of the nodes in the cluster in the distributed store.</p><h4><strong>What happens when you create a pod in Kubernetes ?</strong></h4><p>Lets explore under the hood what happens when you try to run the below command to create a pod using kubectl</p><pre>kubectl run web - image=nginx - replicas=3</pre><p>Step1 : After running the above command Kubectl generates a manifest describing the deployment</p><p>Step 2 : The manifest is sent to Kubernetes API Server</p><p>Step 3 : Kubernetes API server validates the manifest and persist to etcd</p><p>Step 4: Controller manager has a controller for deployment that notices that new deployment has been created and it creates a replica set based on deployment.</p><p>Step 5: ReplicaSet controller creates POD objects are stores them in etc but there still details to be added to the POD object like the node details etc . They are in PENDING state since they are not scheduled on any node</p><p>Step 6 : Scheduler notices that there are PENDING pod objects and tries to schedule these PODS on nodes that have resources available in the cluster</p><p>Step 7: The PODS now are now actually created on the nodes and their status updated is updated with node information and RUNNING state in etc and we have successfully completed our workflow.</p><h3><strong>Kubernetes in AWS</strong></h3><p>The below diagram shows a typical Kubernetes running on a typical two node cluster in AWS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*FwAFCVDf83GJL--h" /></figure><h4><strong>Core concepts in AWS Eco System</strong></h4><h4><strong>VPC</strong></h4><p>Amazon Virtual Private Cloud (VPC) is a private subsection of AWS that lets you provision a logically isolated section of the Amazon Web Services where you can launch AWS resources in a virtual network that you define. You have full control over who has access to the AWS resources that you place inside your VPC.</p><h4><strong>Route 53</strong></h4><p>Amazon Route 53 is a highly available and scalable Domain Name Service (DNS). Route 53 translates the domain name into IP addresses to direct traffic to your website.</p><h4><strong>Internet Gateway</strong></h4><p>Internet Gateway is a logical connection between Amazon VPC and the internet. An internet gateway has two main goals</p><p>a)Provide target in your VPC route tables for internet-routable traffic</p><p>b)Perform network address translation for instances that have been assigned public IP addresses.</p><h4><strong>ELB</strong></h4><p>AWS Elastic Load Balancer automatically distributes incoming application traffic across multiple Amazon EC2 instances. It helps you achieve fault tolerance in your application by providing the required amount of load balancing capacity needed to route application traffic. Different types of load balancer that AWS provides are</p><ul><li>Network Load Balancer (TCP/SSL)</li><li>Application Load Balancer (HTTP/HTTPS)</li></ul><h4><strong>Network Access Control List</strong></h4><p>A network access control list is an optional layer of security for your VPC that acts as a firewall controlling traffic in and out of one or more subnets</p><h4><strong>Subnet</strong></h4><p>A subnet is a sub-section of a network which includes all computers in a specific location.</p><h4><strong>Availability Zone</strong></h4><p>Any AWS resource that we launch must be placed in a VPC subnet. Any given subnet must be located in an availability zone. You can utilize multiple availability zone to create redundancy in your architecture. This is what allows for High Availability and Fault Tolerant systems.</p><h4><strong>Security Group</strong></h4><p>Security groups are similar to NACLs, they allow or deny traffic. However security groups are found only at the instance level. Security group acts like a virtual firewall that controls the traffic to one or more instances. We add rules to each security group that allow traffic to or from its associated instances. You can modify the rules for a security group at anytime, the new rules are automatically applied to instances within the group.</p><h3><strong>Spring boot Application(WeatherAPI service)</strong></h3><p>Now let us take a look at our spring boot application. Its a simple web application that returns you the current weather given a city and country as a parameter. Lets take a look at the structure of the web application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LtdFDxek1--aURmQ" /></figure><p>The main classes of our application are</p><h4><strong>WeatherApiDemoApplication</strong></h4><p>This is the main class to bootstrap or launch a spring application. This class automatically creates the application context from class path, scans the configuration classes and launches the application.</p><h4><strong>WeatherService</strong></h4><p>This class contains all the business logic w.r.t to getting the current weather info. This class also interfaces with <a href="http://api.openweathermap.org/">api.openweathermap.org</a> and retrieves the details of weather based on city, country etc.</p><h4><strong>CurrentWeather</strong></h4><p>This class represents the model that holds the weather related info and this model is populated with weather related info by WeatherService and returned back to WeatherController. CurrentWeather model contains attributes like city, country, temperature, wind speed etc</p><h4><strong>WeatherController</strong></h4><p>WeatherController is the class that implements the RESTFul web services for our weather api. It takes care of mapping the request data to the define request handler method. WeatherController integrates with WeatherService. To get the weather data based on input parameters and once the response body is generated it converts into necessary format and returns back to the user.</p><p>The default city and country is San Jose and USA respectively. A sample invocation of the API would return something as below.</p><pre>curl -X GET http://localhost:8080/current-weather?city=Georgia&amp;country=USA</pre><h4><strong>Output:</strong></h4><pre>{&quot;description&quot;:&quot;Clouds&quot;,&quot;temperature&quot;:11.7,&quot;feelsLike&quot;:10.98,&quot;windSpeed&quot;:0.94,&quot;country&quot;:&quot;USA&quot;,&quot;city&quot;:&quot;Georgia&quot;}</pre><h4><strong>The core dependencies of our application are</strong></h4><ul><li>Spring boot starter for web/tomcat</li><li>Micrometer</li><li>Actuator</li></ul><p>Sample pom.xml dependencies</p><pre>&lt;<strong>dependencies</strong>&gt;<br>   &lt;<strong>dependency</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;spring-boot-starter-web&lt;/<strong>artifactId</strong>&gt;<br>   &lt;/<strong>dependency</strong>&gt;<br><br>   &lt;<strong>dependency</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;spring-boot-starter-tomcat&lt;/<strong>artifactId</strong>&gt;<br>      &lt;<strong>scope</strong>&gt;provided&lt;/<strong>scope</strong>&gt;<br>   &lt;/<strong>dependency</strong>&gt;<br>   &lt;<strong>dependency</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;spring-boot-starter-test&lt;/<strong>artifactId</strong>&gt;<br>      &lt;<strong>scope</strong>&gt;test&lt;/<strong>scope</strong>&gt;<br>   &lt;/<strong>dependency</strong>&gt;<br>   &lt;<strong>dependency</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;io.micrometer&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;micrometer-registry-prometheus&lt;/<strong>artifactId</strong>&gt;<br>   &lt;/<strong>dependency</strong>&gt;<br><br>   &lt;<strong>dependency</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;spring-boot-starter-actuator&lt;/<strong>artifactId</strong>&gt;<br>   &lt;/<strong>dependency</strong>&gt;<br>&lt;/<strong>dependencies</strong>&gt;</pre><h4><strong>Actuator:</strong></h4><p>Spring boot actuator provides secured endpoints for monitoring and managing your application. Actuator is mainly used to expose operational information (health, metrics, info, dump, env) about your running application .</p><p>You can find more information about Actuator<a href="https://www.baeldung.com/spring-boot-actuators"> here</a></p><h4><strong>Prometheus:</strong></h4><p>Prometheus pulls metrics(keys/values) from application and stores the data as time-series, allowing users to query data and alert in a real time fashion. Prometheus will hit targets to collect metrics, aggregate data, show data or alert if some threshold is met.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*JGhzxTAwcFhMo0uC" /></figure><p>As you can see above there are three components of a prometheus server</p><ul><li>Metrics retrieval component ( To pull metrics from multiple servers/machines)</li><li>Metrics storage component ( Stores metrics data in a time series fashion)</li><li>HttpServer ( provides API to expose metrics to the outside world for querying)</li></ul><p>Simple example of metrics displayed on prometheus endpoint for our weather application. As you can see below we are able to track the number of requests for our endpoint /health and /current-weather .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LdbzeLdVaoPF4hjD" /></figure><p>Lets build and push our spring boot weather app to docker hub and we can pull it later on our Kubernetes pods when creating a deployment</p><p>The docker file used for my weather app is very simple as below</p><pre>FROM tomcat:8.0.51-jre8-alpine</pre><pre>EXPOSE 8080</pre><pre>RUN rm -rf /usr/local/tomcat/webapps/*</pre><pre>COPY target/*.war /usr/local/tomcat/webapps/ROOT.war</pre><pre>CMD [“catalina.sh”,”run”]</pre><p>I am also using a dockerfile-maven-plugin from Spotify to build docker image of the weather app The plugin configuration is as below. The plugin will build a docker image as part of</p><pre>mvn clean install</pre><p>The main plugin section in pom.xml looks as below</p><pre>&lt;<strong>plugins</strong>&gt;<br>   &lt;<strong>plugin</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;spring-boot-maven-plugin&lt;/<strong>artifactId</strong>&gt;<br>   &lt;/<strong>plugin</strong>&gt;<br>   &lt;<strong>plugin</strong>&gt;<br>      &lt;<strong>groupId</strong>&gt;com.spotify&lt;/<strong>groupId</strong>&gt;<br>      &lt;<strong>artifactId</strong>&gt;dockerfile-maven-plugin&lt;/<strong>artifactId</strong>&gt;<br>      &lt;<strong>version</strong>&gt;1.4.10&lt;/<strong>version</strong>&gt;<br>      &lt;<strong>executions</strong>&gt;<br>         &lt;<strong>execution</strong>&gt;<br>            &lt;<strong>id</strong>&gt;default&lt;/<strong>id</strong>&gt;<br>            &lt;<strong>goals</strong>&gt;<br>               &lt;<strong>goal</strong>&gt;build&lt;/<strong>goal</strong>&gt;<br>            &lt;/<strong>goals</strong>&gt;<br>         &lt;/<strong>execution</strong>&gt;<br>      &lt;/<strong>executions</strong>&gt;<br>      &lt;<strong>configuration</strong>&gt;<br>         &lt;<strong>repository</strong>&gt;raghuramg24/${project.name}&lt;/<strong>repository</strong>&gt;<br>         &lt;<strong>tag</strong>&gt;${project.version}&lt;/<strong>tag</strong>&gt;<br>         &lt;<strong>skipDockerInfo</strong>&gt;true&lt;/<strong>skipDockerInfo</strong>&gt;<br>      &lt;/<strong>configuration</strong>&gt;<br>   &lt;/<strong>plugin</strong>&gt;<br>&lt;/<strong>plugins</strong>&gt;</pre><p>Also make sure that you are configuring your repository name and also make sure that you are doing docker push after the image is built to docker hub.</p><h3><strong>Auto scaling applications in Kubernetes</strong></h3><p>There are two basic principles when it comes to scaling applications</p><p>a) When there is increase in traffic or number of requests, the application should automatically scale up to meet the demand</p><p>b)When there is decrease in traffic the application should automatically scale down to not waste resources</p><h4><strong>Auto scaling options in Kubernetes</strong></h4><p>Kubernetes provides the below options for autoscaling our applications</p><ul><li>Horizontal Pod Autoscaler</li><li>Vertical Pod Autoscaler</li><li>Cluster Autoscaler</li></ul><p>Horizontal Pod Autoscaler auto scales the number of replicas in the system. Vertical Pod Autoscaler increases and decreases the compute resources of container. Cluster Autoscaler scales the number of nodes in a cluster.</p><p>Each of these types of auto scaling components are used for different use cases and in this article we will be discussing about Horizontal Pod Autoscaler. Horizontal Pod Autoscaler can monitor specific metrics of your application continuously and adjust the number of replicas to meet the demand.The number of replicas created is based on user provided target value for the metric.</p><p>Metrics Registry is the component where prometheus is integrated with Pod AutoScaler to help with metric collection and exposing the same to POD autoscaler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/0*kue4O-PtWgMzzscl" /></figure><p>Now we are going to look at how we can set up a simple Kubernetes cluster on AWS and deploy our application. After ensuring our application is successfully running in the Kubernetes pods we will look at auto scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*U7Pw8FjMqBQbhdg6" /></figure><p>HorizontalPODAutoscaler can scale the number of pods based on memory, CPU or any other custom metrics. The custom metrics are pulled using Custom Metrics API. We will have only one instance of our Spring boot application deployed on a POD initially and all the metrics related to the same will be obtained by prometheus by querying the end point /actuator/prometheus. Subsequently based on the config setting on the HorizontalPODScaler and the metric value it will scale up the pod if the value of metric exceeds the assumed value.</p><h3><strong>Set up of Kubernetes cluster in AWS</strong></h3><p>The steps below indicate the different steps in setting the AWS instances and deploying our application on Kubernetes and auto scaling the same.Lets go through the different steps in detail now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S8HijxoEkbZ01woc" /></figure><h4><strong>1.Creating VPC:</strong></h4><p>As a first step, let us create a VPC with CIDR as 10.0.0.0/16. For each AWS resource that we create we need to associate the tag “kubernetes.io/cluster/kubernetes” with the value “owned”. This tag will be used by K8s for auto discovering AWS resources related to Kubernetes stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*AVUZKQZAMLIzEKC8" /></figure><h4><strong>2</strong>.<strong>Enable the DNS hostnames</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*C4RYejWUCldsIkPl" /></figure><h4><strong>3.Create Subnet in the above VPC</strong></h4><p>Lets create subnet in the VPC(kubernetes-cluster-vpc) that we created above. Create it with CIDR 10.0.0.0/24 and add our tag “kubernetes.io/cluster/kubernetes” with value “owned”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*f_E0CYrK83gALxyp" /></figure><h4><strong>4.Auto Assign IP</strong></h4><p>After the subnet is created lets enable the auto assign IP settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*uagAiUhFFiaRmmGo" /></figure><h4><strong>5.Internet Gateway</strong></h4><p>In order for us to have the traffic routed from subnet into the Internet we need Internet Gateway. Lets also associate the Internet Gateway to our VPC(kubernetes-cluster-vpc) created above.</p><p>Add tag “kubernetes.io/cluster/kubernetes” with value “owned”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*i7FmGUsz9EKVHfKg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*3EYBfF6XXLnLe4tW" /></figure><h4><strong>6.Route table</strong></h4><p>A route table contains a set of rules, called routes that is used to determine how to direct the traffic from the gateway or subnet. Each subnet in the VPC must be associated with a route table, which controls the routing for the subnet. Each route in a route table specifies a destination and a target and that determines which way the network packets need to go to get to their destination.</p><p>Create a route table and associate with the above VPC(kubernetes-cluster-VPC) and also add our tag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6Npi_Me0ShjJeUD" /></figure><p>Edit the routes after the route table is created and add 0.0.0.0/0 (CIDR notation equivalent to 0.0.0.0 with a mask of 0.0.0.0), because if you make a binary comparison between the destination IP and the mask 0.0.0.0, it matches any IP address including the 0.0.0.0 IP itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rk4rMTgYIf6P4Dyq" /></figure><p>Attach this route table to the subnet(kubernetes-cluster-net) that we created earlier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uesBHS6VrYl6tqIE" /></figure><h4><strong>7.IAM Roles</strong></h4><p>In order to get Kubernetes working with AWS we need to set up roles/policies in IAM for master and worker nodes. Lets see how to create them.</p><p><strong>IAM Master Role/policy:</strong></p><p>We need to first define IAM master policy by going to IAM &gt; Create policy from AWS console and click on JSON tab as below. You can refer to the policy for control plane<a href="https://github.com/kubernetes/cloud-provider-aws/blob/c069a213f31419dbc6cc634f8a841ca11f20d3f5/docs/book/prerequisites.md"> here</a> and copy the JSON into the create policy JSON tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZkiNey1gCd_Mgas" /></figure><p>The JSON will look something like below</p><pre>{<br>   &quot;Version&quot;:&quot;2012–10–17&quot;,<br>   &quot;Statement&quot;:[<br>      {<br>         &quot;Effect&quot;:&quot;Allow&quot;,<br>         &quot;Action&quot;:[<br>            &quot;autoscaling:DescribeAutoScalingGroups&quot;,<br>            &quot;autoscaling:DescribeLaunchConfigurations&quot;,<br>            &quot;autoscaling:DescribeTags&quot;,<br>            &quot;ec2:DescribeInstances&quot;,<br>            &quot;ec2:DescribeRegions&quot;,<br>            &quot;ec2:DescribeRouteTables&quot;,<br>            &quot;ec2:DescribeSecurityGroups&quot;,<br>            &quot;ec2:DescribeSubnets&quot;,<br>            &quot;ec2:DescribeVolumes&quot;,<br>            &quot;ec2:CreateSecurityGroup&quot;,<br>            &quot;ec2:CreateTags&quot;,<br>            &quot;ec2:CreateVolume&quot;,<br>            &quot;ec2:ModifyInstanceAttribute&quot;,<br>            &quot;ec2:ModifyVolume&quot;,<br>            &quot;ec2:AttachVolume&quot;,<br>            &quot;ec2:AuthorizeSecurityGroupIngress&quot;,<br>            &quot;ec2:CreateRoute&quot;,<br>            &quot;ec2:DeleteRoute&quot;,<br>            &quot;ec2:DeleteSecurityGroup&quot;,<br>            &quot;ec2:DeleteVolume&quot;,<br>            &quot;ec2:DetachVolume&quot;,<br>            &quot;ec2:RevokeSecurityGroupIngress&quot;,<br>            &quot;ec2:DescribeVpcs&quot;,<br>            &quot;elasticloadbalancing:AddTags&quot;,<br>            &quot;elasticloadbalancing:AttachLoadBalancerToSubnets&quot;,<br>            &quot;elasticloadbalancing:ApplySecurityGroupsToLoadBalancer&quot;,<br>            &quot;elasticloadbalancing:CreateLoadBalancer&quot;,<br>            &quot;elasticloadbalancing:CreateLoadBalancerPolicy&quot;,<br>            &quot;elasticloadbalancing:CreateLoadBalancerListeners&quot;,<br>            &quot;elasticloadbalancing:ConfigureHealthCheck&quot;,<br>            &quot;elasticloadbalancing:DeleteLoadBalancer&quot;,<br>            &quot;elasticloadbalancing:DeleteLoadBalancerListeners&quot;,<br>            &quot;elasticloadbalancing:DescribeLoadBalancers&quot;,<br>            &quot;elasticloadbalancing:DescribeLoadBalancerAttributes&quot;,<br>            &quot;elasticloadbalancing:DetachLoadBalancerFromSubnets&quot;,<br>            &quot;elasticloadbalancing:DeregisterInstancesFromLoadBalancer&quot;,<br>            &quot;elasticloadbalancing:ModifyLoadBalancerAttributes&quot;,<br>            &quot;elasticloadbalancing:RegisterInstancesWithLoadBalancer&quot;,<br>            &quot;elasticloadbalancing:SetLoadBalancerPoliciesForBackendServer&quot;,<br>            &quot;elasticloadbalancing:AddTags&quot;,<br>            &quot;elasticloadbalancing:CreateListener&quot;,<br>            &quot;elasticloadbalancing:CreateTargetGroup&quot;,<br>            &quot;elasticloadbalancing:DeleteListener&quot;,<br>            &quot;elasticloadbalancing:DeleteTargetGroup&quot;,<br>            &quot;elasticloadbalancing:DescribeListeners&quot;,<br>            &quot;elasticloadbalancing:DescribeLoadBalancerPolicies&quot;,<br>            &quot;elasticloadbalancing:DescribeTargetGroups&quot;,<br>            &quot;elasticloadbalancing:DescribeTargetHealth&quot;,<br>            &quot;elasticloadbalancing:ModifyListener&quot;,<br>            &quot;elasticloadbalancing:ModifyTargetGroup&quot;,<br>            &quot;elasticloadbalancing:RegisterTargets&quot;,<br>            &quot;elasticloadbalancing:DeregisterTargets&quot;,<br>            &quot;elasticloadbalancing:SetLoadBalancerPoliciesOfListener&quot;,<br>            &quot;iam:CreateServiceLinkedRole&quot;,<br>            &quot;kms:DescribeKey&quot;<br>         ],<br>         &quot;Resource&quot;:[<br>            &quot;*&quot;<br>         ]<br>      }<br>   ]<br>}</pre><p>You can give a name for the policy like kubernetes-iam-master-policy and save the same</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oEbGvXYH7S3WmxZR" /></figure><p><strong>Now create a IAM role for the above created policy as below</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CtPvaR_7ibGJ-zEB" /></figure><p><strong>Also add the tags as below</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z_GjXq3FxBogIUdh" /></figure><p><strong>Now create a policy for the worker node as below</strong></p><p>You<strong> </strong>can<strong> </strong>look at this example <a href="https://github.com/kubernetes/cloud-provider-aws/blob/c069a213f31419dbc6cc634f8a841ca11f20d3f5/docs/book/prerequisites.md">here</a> and copy the details for Node policy for worker and create a worker policy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YBYeyq_FlRqIiDFy" /></figure><p><strong>Now lets create a role with the above created policy with tag kubernetes.io/cluster/kubernetes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*leVr5vezuuko6-or" /></figure><h4><strong>8.Creating Ec2 instances</strong></h4><p>Create two Ec2 instances one for master and one for worker with corresponding roles. Make sure that we are associating the above created subnet (kubernetes-cluster-net), VPC (kubernetes-cluster-VPC) with the instances. We have also make sure that we have the tag <strong>kubernetes.io/cluster/kubernetes</strong> added to the instances<strong>. I will be using Ubuntu Server 18.04 LTS image for creating EC2 instances .</strong></p><p>We have to select instance type that has at least 2 CPU’s when installing Kubernetes master and therefore I will be using t2.medium for both master and worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gmZ5znebxIl4ZdIT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KwTiEKfGVD2O0sgO" /></figure><h4><strong>Create security group</strong></h4><p>Lets create security group called kubernetes-security-group to allow all traffic to the instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qu3cWW6rGatkcImB" /></figure><h4><strong>Create Key pair</strong></h4><p>Before you launch the instance AWS will prompt you to create keys that will help you to access the instance in future. Store the keys in a folder where you access at a later point for installing kubernetes. Make sure that the permissions on the keypair file is changed to 600.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*Mvueig6ruunBMLoS" /></figure><h4><strong>Steps for worker node</strong></h4><p>Follow the above steps for worker node also and do remember to selected worker role and the security group kubernetes-security-group created earlier. Also do remember to select the key created earlier before launching the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mmir4WE32-s85a7x" /></figure><h4><strong>9.Installing Kubernetes</strong></h4><p>Perform the below steps on both the instances of Ec2</p><h4><strong>Update packages list and installed packages</strong></h4><pre>apt update &amp;&amp; apt -y upgrade</pre><h4><strong>Adding Docker and Kubernetes repositories</strong></h4><pre>curl -fsSL <a href="https://download.docker.com/linux/ubuntu/gpg">https://download.docker.com/linux/ubuntu/gpg</a> | sudo apt-key add -</pre><pre>add-apt-repository “deb [arch=amd64] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> $(lsb_release -cs) stable”</pre><pre>curl -s <a href="https://packages.cloud.google.com/apt/doc/apt-key.gpg">https://packages.cloud.google.com/apt/doc/apt-key.gpg</a> | sudo apt-key add -</pre><h4><strong>Update and install docker ,kubelet,kubeadm,kubectl</strong></h4><pre>apt install -y docker-ce kubelet kubeadm kubectl</pre><h4><strong>Get full qualified hostname and set it as hostname</strong></h4><pre>curl <a href="http://169.254.169.254/latest/meta-data/local-hostname">http://169.254.169.254/latest/meta-data/local-hostname</a></pre><pre>ip-10–0–0–25.ec2.internal</pre><p>Set the hostname as FQDN</p><pre>hostnamectl set-hostname ip-10–0–0–25.ec2.internal</pre><p>Verify the hostname</p><pre>ip-10–0–0–25.ec2.internal</pre><h4><strong>Initialization of Master Node</strong></h4><p>Create a master yaml with the below configuration</p><pre>apiVersion: kubeadm.k8s.io/v1beta2</pre><pre>kind: ClusterConfiguration</pre><pre>networking:</pre><pre>serviceSubnet: “10.100.0.0/16”</pre><pre>podSubnet: “10.244.0.0/16”</pre><pre>apiServer:</pre><pre>  extraArgs:</pre><pre>  cloud-provider: “aws”</pre><pre>controllerManager:</pre><pre>   extraArgs:</pre><pre>cloud-provider: “aws”</pre><p>Initialize the Custer with the above config using the command</p><pre>kubeadm init — config master.yaml</pre><p>After you run the command successfully, you should notice the output as below</p><pre>Your Kubernetes control-plane has initialized successfully!</pre><pre>To start using your cluster, you need to run the following as a regular user:</pre><pre>mkdir -p $HOME/.kube</pre><pre>sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config</pre><pre>sudo chown $(id -u):$(id -g) $HOME/.kube/config</pre><pre>Alternatively, if you are the root user, you can run:</pre><pre>export KUBECONFIG=/etc/kubernetes/admin.conf</pre><pre>You should now deploy a pod network to the cluster.</pre><pre>Run “kubectl apply -f [podnetwork].yaml” with one of the options listed at:</pre><pre><a href="https://kubernetes.io/docs/concepts/cluster-administration/addons/">https://kubernetes.io/docs/concepts/cluster-administration/addons/</a></pre><pre>Then you can join any number of worker nodes by running the following on each as root:</pre><pre>kubeadm join 10.0.0.35:6443 — token v2w4nw.zss3ev6ur7jpcsqy \ — discovery-token-ca-cert-hash sha256:33979f52b7e6fa5e549ee192d17c3cc0b5b5b98639ced6036f83a9938934c436</pre><p>Make a note of the hash,token and the api server endpoint (i.e 10.0.0.35:6443) we may need all of them when setting up the worker</p><p>As the next step run the above commands on your master node , these commands were listed as part of your initial output of kubeadm command</p><pre>mkdir -p $HOME/.kube</pre><pre>sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config</pre><pre>sudo chown $(id -u):$(id -g) $HOME/.kube/config</pre><h4><strong>Kubernetes Networking</strong></h4><p>In Kubernetes, every Pod has a real IP address and each Pod communicates with other Pods using that IP address. Within the same node direct pod-to-pod communication is possible without requiring any kind of proxy or address translation. But when we have PODS that need communication across different nodes we need CNI (Container Network Interface)</p><p>Container Networking Interface, is basically an external module with a well defined interface that can be called by kubernetes to execute actions to provide networking functionality. There are different flavours of CNI implementation that are available in the market and Flannel is one of them and we will be using Flannel in our article.</p><h4><strong>Installing Flannel:</strong></h4><p>Execute the below command on the master node to install Flannel network.</p><pre>kubectl apply -f <a href="https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml">https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml</a></pre><p>You should see output similar to one below</p><pre>podsecuritypolicy.policy/psp.flannel.unprivileged created</pre><pre>clusterrole.rbac.authorization.k8s.io/flannel created</pre><pre>clusterrolebinding.rbac.authorization.k8s.io/flannel created</pre><pre>serviceaccount/flannel created</pre><pre>configmap/kube-flannel-cfg created</pre><pre>daemonset.apps/kube-flannel-ds created</pre><p>Lets check the status of node to make sure that our master node has a ready status by executing the below command</p><pre>kubectl get nodes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fSooX14dbDr_ofhc" /></figure><h4><strong>Initialization of Worker node</strong></h4><p>On the worker node that you have created make sure to use the below YAML file to initialize the worker with the token, hash and the api server endpoint generated above in the master node during kubeadm initialization.</p><pre>apiVersion: kubeadm.k8s.io/v1beta1<br>kind: JoinConfiguration<br>discovery:<br>  bootstrapToken:<br>     token: &quot;v2w4nw.zss3ev6ur7jpcsqy&quot;<br>     apiServerEndpoint: &quot;10.0.0.35:6443&quot;<br>     caCertHashes:- &quot;sha256:33979f52b7e6fa5e549ee192d17c3cc0b5b5b98639ced6036f83a9938934c436&quot;<br>nodeRegistration:<br>  name: ip-10–0–0–147.ec2.internal<br>  kubeletExtraArgs:<br>  cloud-provider: aws</pre><p>Run the below command to join the node to the cluster</p><pre>kubeadm join — config=worker.yaml</pre><p>You should see the output as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pr0wSkUG7iYB9NKS" /></figure><p>You can verify if your worker node has joined by executing the below command on master</p><pre>kubectl get nodes</pre><p>You should be able to see two nodes in the cluster now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rFOMLRXF26f5OrGn" /></figure><h3><strong>10.Installing Prometheus</strong></h3><h4><strong>Prerequisites:(Master)</strong></h4><h4><strong>Install Curl:</strong></h4><pre>sudo apt install curl</pre><h4><strong>Install Helm</strong></h4><pre>curl -sSL <a href="https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3">https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3</a> | bash</pre><pre>helm repo add prometheus-community <a href="https://prometheus-community.github.io/helm-charts">https://prometheus-community.github.io/helm-charts</a></pre><pre>helm repo add stable <a href="https://charts.helm.sh/stable/">https://charts.helm.sh/stable/</a></pre><h4><strong>Update the repo</strong></h4><pre>helm repo update</pre><p>Install prometheus through helm</p><p>helm install prometheus prometheus-community/prometheus</p><p>After installing prometheus ensure that you have all your pods in a running state by executing the below command</p><pre>kubectl get pods — all-namespaces</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wOZqevq98mCwjH2f" /></figure><h3><strong>Deploying Spring boot application on Kubernetes</strong></h3><p>Let us deploy our spring boot application on Kubernetes using weatherapidemo.yaml similar to the one below. Prior to execution of this step awe need to ensure that our image weatherapidemo:0.0.1-SNAPSHOT is pushed to the docker hub repository</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: weatherapidemo<br>spec:<br>  selector:<br>    matchLabels:<br>      app: weatherapidemo<br>  template:<br>    metadata:<br>      annotations:<br>        prometheus.io/path: /actuator/prometheus<br>        prometheus.io/scrape: &quot;true&quot;<br>        prometheus.io/port: &quot;8080&quot;<br>      labels:<br>        app: weatherapidemo<br>    spec:<br>      containers:<br>      - name: weatherapidemo<br>        image: raghuramg24/weatherapidemo:0.0.1-SNAPSHOT<br>        ports:<br>        - containerPort: 8080</pre><p>You can create deployment resource using the below command for our weatherapidemo</p><pre>kubectl create -f weatherapidemo.yaml</pre><p>To verify if the deployment is successful we can execute the below command</p><pre>kubectl get deployments</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t9BEbuIwifad5jzp" /></figure><p>You can see output similar to the above if the deployment is successful. We should be able to see our deployment weatherapidemo in the list.</p><p>Check if there are corresponding pods created with weatherapidemo corresponding to the above deployment by executing</p><pre>kubectl get pods — all-namespaces</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KiTwHAkH43KBEe58" /></figure><p>As you can see from the above list that our pod with weatherapidemo container is up and running</p><p>After successfully executing the above command and creating the adapter try to find out the IP address for our weatherapi demo and try executing couple of times the below command to make sure you are getting the output. Please note that you need to replace the IP address (10.244.1.6) with your own pod IP address.</p><pre>curl — location — request GET &#39;http://10.244.1.6:8080/current-weather?city=Milpitas&amp;country=USA&#39;</pre><h4><strong>Install Prometheus adapter for capturing metrics from our application</strong></h4><p>As we saw from our above Spring boot application weatherapidemo that it exposes the metrics like http_server_requests_seconds_count for each of the Rest API that the application exposes. Prometheus adapter pulls metrics from the Prometheus instance and exposes them as the Custom Metrics API. In this step, you will have to provide configuration for pulling a custom metric exposed by the Spring Boot Actuator. Let’s define a custom rule to pull the desired metric from Prometheus.</p><p>prometheus:</p><pre>prometheus:<br>  url: <a href="http://prometheus-server.default.svc/">http://prometheus-server.default.svc</a><br>  port: 80<br>  path: &quot;&quot;</pre><pre>rules:<br>  default: true<br>  custom:<br>  - seriesQuery: &#39;{__name__=~&quot;^http_server_requests_seconds_.*&quot;}&#39;<br>    resources:<br>      overrides:<br>        kubernetes_namespace:<br>          resource: namespace<br>        kubernetes_pod_name:<br>          resource: pod<br>    name:<br>      matches: &quot;^http_server_requests_seconds_count(.*)&quot;<br>      as: &quot;http_server_requests_seconds_count_sum&quot;<br>    metricsQuery: sum(&lt;&lt;.Series&gt;&gt;{&lt;&lt;.LabelMatchers&gt;&gt;,uri=~&quot;/current-weather.*&quot;}) by (&lt;&lt;.GroupBy&gt;&gt;)</pre><p>Note that the URI contains the endpoint for which we are capturing metrics as “/current-weather”.</p><p>Lets execute the below command to install the prometheus adapter as below</p><pre>helm install -f weatherapiconfig.yaml prometheus-adapter prometheus-community/prometheus-adapter</pre><p>After executing the above command u can try executing the below url to see if you are able to see the values captured and returned as part of your endpoint</p><pre>kubectl get — raw /apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/http_server_requests_seconds_count_sum</pre><p>Your output should look like something as below. Note that I have hit the endpoint /current-weather 3 times and therefore it shows “3” in the value section.</p><pre>{“kind”:”MetricValueList”,”apiVersion”:”custom.metrics.k8s.io/v1beta1&quot;,”metadata”:{“selfLink”:”/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/%2A/http_server_requests_seconds_count_sum”},”items”:[{“describedObject”:{“kind”:”Pod”,”namespace”:”default”,”name”:”weatherapidemo-7d8d5f9d6b-kr8hb”,”apiVersion”:”/v1&quot;},”metricName”:”http_server_requests_seconds_count_sum”,”timestamp”:”2020–12–26T00:45:38Z”,”value”:”3&quot;,”selector”:null}]}</pre><h4><strong>Install Horizontal POD autoscaler of Kubernetes</strong></h4><p>This is the final step that will help us in auto scaling our spring boot application. HorizontalPodAutoscaler is capable to autoscaling the number of instances of our PODs based on the metric name and average value provided. A sample autoscaler created for our weatherapidemo would like below.</p><pre>apiVersion: autoscaling/v2beta2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: weatherapidemo<br>  namespace: default<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: weatherapidemo<br>  minReplicas: 1<br>  maxReplicas: 10<br>  metrics:<br>    - type: Pods<br>      pods:<br>        metric:<br>          name: http_server_requests_seconds_count_sum<br>        target:<br>          type: AverageValue<br>          averageValue: 6</pre><p>As you can see from the above HorizontalPodAutoScaler spec details we have the minimumReplicas set to 1 and maximumReplicas set to 10. This config indicates that as part of scale up there needs to be at least 1 minimum pod created and a max of 10 pods created. The average value indicates the threshold for the number of request i.e when the number request per second goes beyond 6 then the pods for weatherapidemo are autoscaled. Lets see the current number of pods for weatherapidemo using the below command</p><pre>kubectl get pods — all-namespaces | grep “weatherapidemo”</pre><p>You should be seeing only one instance of weatherapidemo running</p><p>Create the pod autoscaler by running the below command</p><pre>kubectl apply -f podautoscaler.yaml</pre><p>Try to execute the CURL command multiple times one after another and then you start to see that your PODS are getting created automatically as below</p><pre>curl — location — request GET ‘http://&lt;podipaddress&gt;:8080/current-weather?city=Milpitas&amp;country=USA&amp;appId=888438ee801053da344ce7bdc04d8e42’</pre><p><strong>Autoscaling is working!!!!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Y1ypCpOYWt2KQkL" /></figure><p>Lets also try to create a service type LoadBalancer so that you can hit this request outside of this cluster and you can see them autoscaling</p><pre>kind: Service<br>apiVersion: v1<br>metadata:<br>  name: weatherapidemo<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: weatherapidemo<br>  ports:<br>    - name: http<br>      protocol: TCP<br>      # ELB&#39;s port<br>      port: 80</pre><p>You can see that once the above service is created there is a corresponding external load balancer also created in AWS and you can notice your instance id also part of the load balancer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4pX918mqihmkBcC" /></figure><p>Lets see the steps involved in redirecting the external traffic to the POD using ELB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*GqKnMwfRUigduIZp" /></figure><p><strong>NodePort</strong> exposes a service externally to the cluster by means of the target nodes IP address and the NodePort</p><p><strong>TargetPort</strong> is the port on which the service will send requests to, that your pod will be listening on</p><p><strong>Container Port</strong> exposes the Kubernetes service on the specified port within the cluster. Other pods within the cluster can communicate with this server on the specified port</p><p>Now we can also hit the AWS ELB url and try to auto scale our weatherapidemo pods</p><pre>curl — location — request GET ‘http://a37966cad0aa0428fb59b06a790525f6-2126778632.us-east-1.elb.amazonaws.com:8080/current-weather?city=Milpitas&amp;country=USA&amp;appId=888438ee801053da344ce7bdc04d8e42&#39;</pre><p>And after sending subsequent requests one after another and once we reach the threshold of 6 we can start to see the PODS getting auto created as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RWJ7f4FSEhYUbJpi" /></figure><p>We have successfully completed setting up of kubernetes cluster on AWS, deploying our application and autoscaling the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b22f13b89e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>