<?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 İnci KÜÇÜK on Medium]]></title>
        <description><![CDATA[Stories by İnci KÜÇÜK on Medium]]></description>
        <link>https://medium.com/@incikucuk98?source=rss-4bce8edd4a99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4sWIivY0zKsR-KCX8r75mw.jpeg</url>
            <title>Stories by İnci KÜÇÜK on Medium</title>
            <link>https://medium.com/@incikucuk98?source=rss-4bce8edd4a99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:26:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@incikucuk98/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[Understanding JaCoCo: A Simple Guide for Spring Boot Projects]]></title>
            <link>https://blog.stackademic.com/understanding-jacoco-a-simple-guide-for-spring-boot-projects-8053d43fb268?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/8053d43fb268</guid>
            <category><![CDATA[spring-testing]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[code-coverage-tools]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jacoco]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 06:45:05 GMT</pubDate>
            <atom:updated>2025-01-13T07:29:21.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvDNguyhQ7dni_KAo9kneg.png" /></figure><p>Code quality is a key part of successful software projects. Ensuring your code is well-tested helps prevent bugs and improve maintainability. This is where <strong>JaCoCo</strong>, a Java code coverage tool, becomes useful. In this guide, we’ll explain JaCoCo in simple terms, why you need it, and how to use it in Spring Boot projects.</p><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk?tab=repositories"><em>https://github.com/incikucuk</em></a></blockquote><h3>What is JaCoCo?</h3><p><strong>JaCoCo (Java Code Coverage)</strong> measures how much of your code is covered by tests. It shows which parts of your code are tested and which are not, helping you identify gaps. With clear reports, JaCoCo makes it easier to improve your tests and boost your code’s reliability.</p><h3>Why Use JaCoCo?</h3><ol><li><strong>Improve Test Quality:</strong> Find untested parts of your code.</li><li><strong>Clear Reports:</strong> Get easy-to-read visual and metric-based insights.</li><li><strong>Easy CI/CD Integration:</strong> Add JaCoCo to your automation pipelines.</li><li><strong>SonarQube Ready:</strong> Integrate reports with SonarQube for deeper analysis.</li><li><strong>Lightweight:</strong> Runs without slowing down your testing process.</li></ol><h3>How to Use JaCoCo in Spring Boot Projects</h3><p>You can add JaCoCo to your Spring Boot projects easily. It works with tools like Maven and Gradle.</p><h3>Adding JaCoCo with Maven</h3><h4>Step 1: Update pom.xml</h4><p>Add the following plugin to your Maven project:</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br>            &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;0.8.10&lt;/version&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;prepare-agent&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                &lt;/execution&gt;<br>                &lt;execution&gt;<br>                    &lt;id&gt;report&lt;/id&gt;<br>                    &lt;phase&gt;verify&lt;/phase&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;report&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><h4>Step 2: Generate a Report</h4><p>Run this command to create a test coverage report:</p><pre>mvn clean verify</pre><p>The report will be available at target/site/jacoco/index.html. Open it in your browser to check test coverage.</p><h3>Example: Testing a Simple User Service</h3><p>Let’s create a basic <strong>User Account</strong> service and test it using JaCoCo.</p><h4>Service Code</h4><pre>@Service<br>public class UserAccountService {<br>    private final Map&lt;String, String&gt; userDatabase = new HashMap&lt;&gt;();</pre><pre>    public String createUser(String username, String email) {<br>        if (userDatabase.containsKey(username)) {<br>            throw new IllegalArgumentException(&quot;User already exists&quot;);<br>        }<br>        userDatabase.put(username, email);<br>        return &quot;User created successfully&quot;;<br>    }</pre><pre>    public String getUserEmail(String username) {<br>        return userDatabase.get(username);<br>    }<br>}</pre><h4>Writing Tests</h4><p>We’ll use JUnit to test the service:</p><pre>@SpringBootTest<br>public class UserAccountServiceTest {</pre><pre>    @Autowired<br>    private UserAccountService userAccountService;</pre><pre>    @Test<br>    public void testCreateUser_Success() {<br>        String result = userAccountService.createUser(&quot;john_doe&quot;, &quot;john.doe@example.com&quot;);<br>        Assertions.assertEquals(&quot;User created successfully&quot;, result);<br>    }</pre><pre>    @Test<br>    public void testCreateUser_UserAlreadyExists() {<br>        userAccountService.createUser(&quot;jane_doe&quot;, &quot;jane.doe@example.com&quot;);<br>        Assertions.assertThrows(IllegalArgumentException.class, () -&gt; {<br>            userAccountService.createUser(&quot;jane_doe&quot;, &quot;jane.doe@example.com&quot;);<br>        });<br>    }</pre><pre>    @Test<br>    public void testGetUserEmail() {<br>        userAccountService.createUser(&quot;john_doe&quot;, &quot;john.doe@example.com&quot;);<br>        String email = userAccountService.getUserEmail(&quot;john_doe&quot;);<br>        Assertions.assertEquals(&quot;john.doe@example.com&quot;, email);<br>    }<br>}</pre><h4>View the Report</h4><p>Run mvn clean verify and open target/site/jacoco/index.html to see:</p><ul><li><strong>Line Coverage:</strong> Percentage of lines covered by tests.</li><li><strong>Branch Coverage:</strong> How well conditional statements are tested.</li></ul><h3>Using JaCoCo with SonarQube</h3><p>SonarQube is a tool for analyzing code quality. By integrating JaCoCo, you can add test coverage details to SonarQube reports.</p><h3>How to Set Up SonarQube</h3><h4>Step 1: Install SonarQube</h4><p>Run SonarQube locally using Docker:</p><pre>docker run -d --name sonarqube -p 9000:9000 sonarqube:lts</pre><p>Access it at http://localhost:9000 (default login: admin/admin).</p><h4>Step 2: Generate JaCoCo Reports</h4><p>Run the following command to create a report in XML format:</p><pre>mvn clean verify</pre><p>The XML file will be located at target/site/jacoco/jacoco.xml.</p><h4>Step 3: Upload to SonarQube</h4><p>Send the JaCoCo report to SonarQube with this command:</p><pre>mvn sonar:sonar \<br>  -Dsonar.projectKey=YourProjectKey \<br>  -Dsonar.host.url=http://localhost:9000 \<br>  -Dsonar.login=YourToken</pre><p>Replace YourProjectKey with your project’s name and YourToken with your personal access token.</p><h4>Step 4: Review in SonarQube</h4><p>Once uploaded, view test coverage and other insights on the SonarQube dashboard. This includes:</p><ul><li><strong>Test Coverage</strong></li><li><strong>Code Smells</strong></li><li><strong>Security Issues</strong></li></ul><h4>Automate with CI/CD</h4><p>You can add these steps to CI/CD tools like Jenkins or GitLab CI for automated quality checks.</p><p>JaCoCo is an essential tool for improving test coverage in Java projects. It integrates seamlessly with Spring Boot and tools like SonarQube, offering detailed insights into your code’s quality.</p><p>…</p><blockquote><strong>I hope it will be useful for you. :)<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</strong></blockquote><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk">https://github.com/incikucuk</a></blockquote><blockquote><strong>Delightful encodings!</strong></blockquote><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8053d43fb268" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/understanding-jacoco-a-simple-guide-for-spring-boot-projects-8053d43fb268">Understanding JaCoCo: A Simple Guide for Spring Boot Projects</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Explore Tactical DDD (Tactical Domain-Based Design)- with an Example]]></title>
            <link>https://blog.stackademic.com/lets-explore-tactical-ddd-tactical-domain-based-design-with-an-example-ca1b642ceb53?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1b642ceb53</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 09:45:09 GMT</pubDate>
            <atom:updated>2024-12-12T08:53:23.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*JIScdhLizM-fFXMa.png" /></figure><p><strong>Tactical Domain-Driven Design (Tactical DDD)</strong> is a set of patterns and practices that help software developers design the inner workings of a system in a way that closely aligns with the business domain. It’s about managing the complexity of your business logic and ensuring that it is properly represented in the software.</p><p>While <strong>Strategic DDD</strong> is focused on high-level decisions — like defining <strong>bounded contexts</strong> and deciding how different parts of the system interact — <strong>Tactical DDD</strong> provides the <strong>specific building blocks</strong> to implement the domain model. It’s a set of tools you can use to shape the software at a granular level, ensuring that your domain logic is <strong>well-structured</strong>, <strong>maintainable</strong>, and <strong>aligned with business needs</strong>.</p><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk?tab=repositories">https://github.com/incikucuk</a></blockquote><h3>Key Concepts in Tactical DDD</h3><ol><li><strong>Entities</strong>: These are objects that have a distinct identity and can change over time. The identity allows them to be tracked across different states and operations. For example, an “Order” in an e-commerce system is an entity — its identity persists even if the order’s contents or status change.</li><li><strong>Value Objects</strong>: These are objects that don’t have a unique identity but represent something important in the domain. Value objects are immutable, meaning they can’t be changed after creation. For instance, an “Address” could be a value object because it doesn’t need an identity, just the specific attributes (street, city, etc.).</li><li><strong>Aggregates</strong>: These are clusters of entities and value objects that are treated as a single unit. They enforce business rules and are responsible for ensuring the consistency of the system. A <strong>ShoppingCart</strong> aggregate might consist of an <strong>Order</strong> (entity), <strong>OrderItems</strong> (entities), and the total amount (value object).</li><li><strong>Repositories</strong>: Repositories act as gateways to aggregates and entities. They abstract away the details of how objects are stored and retrieved. Think of a <strong>CustomerRepository</strong> that lets you fetch customer data from a database.</li><li><strong>Services</strong>: Domain services are used to contain logic that doesn’t naturally fit within an entity or value object. For example, if you need to calculate the total cost of an order, that might be a domain service.</li><li><strong>Factories</strong>: Factories are responsible for creating complex aggregates or entities. They help isolate the complexity of creation and ensure that objects are created in a valid state.</li><li><strong>Domain Events</strong>: These represent significant occurrences in the domain that may trigger actions in other parts of the system. For example, when an <strong>Order</strong> is placed, it might trigger an <strong>OrderPlacedEvent</strong>, which could notify an inventory service to reserve stock.</li><li><strong>Specifications</strong>: These are used to represent complex business rules that can be reused in queries or validations. For instance, a specification could define that an order is only valid if it meets certain criteria (e.g., total amount, delivery date).</li></ol><h3>When Should Tactical DDD Be Used?</h3><p>Tactical DDD is especially useful in projects where the business logic is <strong>complex</strong>, <strong>evolving</strong>, and requires careful organization. It is best suited for:</p><ol><li><strong>Large, complex applications</strong>: If the domain of your application involves intricate business rules, regulatory compliance, or frequent changes (e.g., insurance systems, banking applications), Tactical DDD can help you ensure the codebase accurately reflects the business needs.</li></ol><blockquote><em>Example</em>: In an <strong>insurance</strong> application, different types of policies, claims, and customer data need to be carefully modeled. A policy might involve multiple entities (Policy, Claim, Beneficiary), value objects (CoverageDetails), and services to calculate premium amounts or assess risk. Tactical DDD helps you model these aspects cleanly, ensuring that the system can handle complex scenarios without becoming a tangled mess of code.</blockquote><p><strong>2. Microservices architectures</strong>: In a microservices environment, each service should be aligned with a specific <strong>bounded context</strong>. Tactical DDD helps define clear boundaries for each service’s domain and ensures that each service has its own well-defined <strong>model</strong>.</p><blockquote><strong><em>Example:</em></strong> In a <strong>multi-service e-commerce</strong> system, you might have separate services for Orders, Payments, and Shipping. Each of these services should have its own model for handling things like products, payments, or shipping addresses. Tactical DDD ensures that each service has clear responsibilities and avoids leaking domain logic between services.</blockquote><p><strong>3. Systems with rapidly changing business rules</strong>: If the business is constantly evolving, the domain model needs to be flexible and adaptable. Tactical DDD’s patterns provide a structure that allows the domain to evolve over time without breaking the existing system.</p><blockquote><em>Example</em>: In a <strong>financial trading platform</strong>, rules about risk assessment and asset allocation may change frequently due to market conditions. Tactical DDD lets you keep these rules in dedicated <strong>domain services</strong>, ensuring the model can be updated independently as business logic changes.</blockquote><p><strong>4. Refactoring legacy systems</strong>: If you’re working with a legacy system that has accumulated a lot of technical debt, Tactical DDD can guide the <strong>refactoring process</strong>, helping you break the system down into more manageable and understandable components.</p><blockquote><em>Example</em>: If you have a monolithic <strong>banking application</strong> with messy domain logic, you could apply Tactical DDD principles to break down the domain into aggregates (Customer, Account), services (AccountService), and repositories (CustomerRepository). This structure would help the team maintain and evolve the system in a more organized manner.</blockquote><p><strong>Tactical Domain-Driven Design (Tactical DDD)</strong> is a set of patterns and practices used to implement domain models in software. It focuses on the <strong>inner workings</strong> of the system, offering specific tools and design principles to turn business requirements into a clean, maintainable codebase. In this context, we work with <strong>entities</strong>, <strong>value objects</strong>, <strong>aggregates</strong>, <strong>repositories</strong>, <strong>domain services</strong>, <strong>factories</strong>, and <strong>domain events</strong>, among others.</p><blockquote>Let’s break down some of the most important concepts in Tactical DDD, and then I’ll walk you through an example with specific classes (like entities and others).</blockquote><pre>+-----------------------------+       +--------------------------+       +---------------------------+<br>|       Customer Entity       |&lt;-----&gt;|       Order Entity       |&lt;-----&gt;|      OrderItem Entity     |<br>|-----------------------------|       |--------------------------|       |---------------------------|<br>| - Customer ID (Unique)      |       | - Order ID (Unique)      |       | - OrderItem ID (Unique)   |<br>| - Name                      |       | - Customer (Entity)      |       | - Quantity                |<br>| - Address                   |       | - Order Items (Entities) |       | - Unit Price              |<br>| - Email                     |       | - Total Price (Value Obj)|       | - Discount                |<br>+-----------------------------+       | - Order Status           |       +---------------------------+<br>                                      | - Shipping Address       |               |<br>                                      +--------------------------+               |<br>                                                |                             |<br>                                                |                             |<br>                                        +--------------------------+   +--------------------------+<br>                                        |        Money (Value Object) |   |   OrderStatus (Value Object) |<br>                                        |--------------------------|   |----------------------------|<br>                                        | - Amount                 |   | - Status (Enum: PENDING,   |<br>                                        | - Currency               |   |   SHIPPED, CANCELLED)     |<br>                                        +--------------------------+   +----------------------------+<br>                                                    <br>                                                |<br>                                  +-----------------------------+<br>                                  |     Order Repository        |<br>                                  |-----------------------------|<br>                                  | - findById(Order ID)        |<br>                                  | - save(Order)               |<br>                                  | - delete(Order)             |<br>                                  +-----------------------------+<br>                                                |<br>                                                <br>                                  +-----------------------------+<br>                                  |    OrderService (Domain Service)|<br>                                  |-----------------------------|<br>                                  | - placeOrder(Order)         |<br>                                  | - calculateTotalPrice(Order)|<br>                                  | - applyDiscount(Order)      |<br>                                  +-----------------------------+<br>                                                |<br>                                                <br>                                  +-----------------------------+<br>                                  |       OrderFactory          |<br>                                  |-----------------------------|<br>                                  | - createOrder(Customer)     |<br>                                  | - initializeOrder(Order)    |<br>                                  +-----------------------------+<br>                                                |<br>                                                <br>                                  +-----------------------------+<br>                                  |   OrderPlacedEvent (Domain Event)|<br>                                  |-----------------------------|<br>                                  | - Order ID (Unique)         |<br>                                  | - Order Status (Enum)       |<br>                                  +-----------------------------+<br>         </pre><h3>Explanation of the Schema:</h3><ol><li><strong>Entities</strong>:</li></ol><ul><li><strong>Customer</strong>: Represents a customer in the system. It has an identity (e.g., Customer ID), and its state can change (e.g., name, address).</li><li><strong>Order</strong>: Represents a customer’s order. It also has a unique identity (Order ID) and contains information like order date, status, and the customer that placed it. The Order aggregate is the main point of entry for the business logic and validation.</li></ul><p><strong>2. Value Objects</strong>:</p><ul><li><strong>Money</strong>: Represents the amount and currency for the price of the order. This object is immutable and has no identity. It is used within the Order to store the total price.</li></ul><p><strong>3. Aggregates</strong>:</p><ul><li><strong>Order</strong>: The Order entity is an aggregate root that contains related entities like OrderItems. The Order aggregate ensures that the business rules (like recalculating the total price or checking if the order is valid) are enforced.</li></ul><p><strong>4. Repositories</strong>:</p><ul><li><strong>Order Repository</strong>: A repository abstracts the data layer, providing methods to retrieve, store, and delete Order aggregates. This keeps the domain logic independent of persistence mechanisms.</li></ul><p><strong>5. Domain Services</strong>:</p><ul><li><strong>Order Service</strong>: Contains business logic that doesn’t naturally fit within an entity or value object. For example, the OrderService might contain the logic for placing an order, checking stock, and updating the status.</li></ul><p><strong>6. Factories</strong>:</p><ul><li><strong>Order Factory</strong>: The factory is responsible for creating Order aggregates. If there are complex setup requirements (such as initializing OrderItems or applying discounts), the factory encapsulates this logic to ensure Order creation is consistent and easy to manage.</li></ul><p><strong>7. Domain Events</strong>:</p><ul><li><strong>Order Placed Event</strong>: Represents an important event in the domain, such as an order being successfully placed. This event could trigger other systems (e.g., inventory or shipping services) asynchronously. Events help decouple components and maintain a reactive architecture.</li></ul><h3>How These Components Work Together?</h3><ul><li><strong>Order</strong> (Aggregate Root) interacts with <strong>OrderItem</strong> (Entities), and the total price is updated using the <strong>Money</strong> (Value Object).</li><li>The <strong>OrderRepository</strong> is responsible for saving and retrieving Order aggregates from the database.</li><li><strong>OrderService</strong> handles domain logic like <strong>placing an order</strong>, ensuring stock availability, etc.</li><li>The <strong>OrderFactory</strong> ensures Order objects are created in a consistent way.</li><li>Once an order is placed, an <strong>Order Placed Event</strong> is fired, which could trigger other actions in the system (e.g., sending an email to the customer, notifying the inventory system, etc.).</li></ul><blockquote>Congratulations !, I hope to work :)</blockquote><blockquote><strong><em>I hope it will be useful for you. :)<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</em></strong></blockquote><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk"><em>https://github.com/incikucuk</em></a></blockquote><blockquote><strong><em>Delightful encodings!</em></strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li><li>Have a story to share? <a href="https://formulatools.co/f/cJh1CStlo9jJmhIegBM9"><strong>Join our global community of writers today!</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1b642ceb53" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/lets-explore-tactical-ddd-tactical-domain-based-design-with-an-example-ca1b642ceb53">Let’s Explore Tactical DDD (Tactical Domain-Based Design)- with an Example</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS (Command Query Responsibility Segregation) Pattern with an Example]]></title>
            <link>https://blog.stackademic.com/cqrs-command-query-responsibility-segregation-pattern-with-an-example-c9fcd164928e?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9fcd164928e</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[cqrs-pattern]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 08:49:03 GMT</pubDate>
            <atom:updated>2024-12-06T09:18:49.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voteReXBxCL9k7UhdH5vng.png" /></figure><p>CQRS is a software architectural pattern that separates the operations for reading data (queries) and writing data (commands). The main principle of CQRS is to have distinct models and mechanisms for handling command (write) and query (read) operations. This pattern is particularly useful in <strong>microservices architectures</strong> because it allows each type of operation (reading and writing) to be optimized independently, leading to better scalability, performance, and flexibility in complex systems.</p><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk?tab=repositories"><em>https://github.com/incikucuk</em></a></blockquote><h3>What are the core concepts of CQRS?</h3><ol><li><strong>Commands (Writes):</strong></li></ol><ul><li>Commands represent actions that change the state of the system. These actions might involve creating, updating, or deleting data in the system. Commands generally don’t return a result; they just perform an action.</li><li>For commands, the system ensures <strong>atomicity</strong> and <strong>consistency</strong> to maintain the integrity of data. Commands are typically <strong>synchronous</strong> and may involve complex transactional operations to guarantee that data changes are reliable.</li></ul><p><strong>2. Queries (Reads):</strong></p><ul><li>Queries represent actions that retrieve data from the system without changing its state. These actions focus on <strong>reading data</strong> and typically return the requested information.</li><li>Read operations are often optimized for <strong>performance</strong> and can be implemented using <strong>denormalized</strong> data models (i.e., data that is stored in a way that is more efficient for querying but may have redundant data).</li></ul><h3>Why Use CQRS in Microservices?</h3><p>In a microservices architecture, CQRS provides several benefits due to the different requirements for reading and writing data. Here’s why it makes sense to separate commands and queries:</p><ol><li><strong>Different Requirements for Read and Write Operations:</strong></li></ol><ul><li><strong>Write operations</strong> need to ensure <strong>data consistency</strong> and <strong>transaction integrity</strong>. They often involve ACID (Atomicity, Consistency, Isolation, Durability) properties and may need to ensure strict consistency across the system.</li><li><strong>Read operations</strong> are optimized for <strong>performance</strong> and <strong>speed</strong>, often requiring denormalized data or even caching mechanisms to ensure fast responses.</li></ul><p><strong>2. Why separate them?</strong> Because writing data requires strict consistency, while reading data can be more flexible and optimized for speed.</p><p><strong>3. Optimizing Read and Write Models Independently:</strong></p><ul><li><strong>Write models</strong> often work with normalized, relational databases to ensure data consistency and integrity. These models focus on the accuracy and correctness of updates.</li><li><strong>Read models</strong> might be <strong>denormalized</strong> for better performance, often using NoSQL databases or caching systems to speed up query responses. In CQRS, the <strong>read model</strong> may also be structured in a way that allows for faster querying, even if the underlying write model is complex.</li></ul><p><strong>4. Scalability of Reads and Writes:</strong></p><ul><li>In systems with heavy <strong>read traffic</strong>, the read model may need to be <strong>scaled independently</strong> from the write model. For example, in an e-commerce platform, while users may frequently view product details (read), the number of product updates (write) is much less frequent.</li><li>With CQRS, you can scale read and write services independently to accommodate their different traffic patterns.</li></ul><p><strong>5. Eventual Consistency and Asynchronous Updates:</strong></p><ul><li>In CQRS, especially when combined with <strong>Event Sourcing</strong>, the system may not need to maintain immediate consistency across all services. For instance, a <strong>write</strong> operation may create an event (such as an “OrderPlaced” event) that updates the <strong>read</strong> model asynchronously. This means that there may be a slight delay between the time data is written and the time it is reflected in the read model (known as <strong>eventual consistency</strong>).</li><li><strong>Eventual consistency</strong> helps systems scale better and handle distributed environments where real-time consistency isn’t a strict requirement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*NQSMeJNp4lVFijeTuL1Z6w.png" /></figure><h3>Benefits of CQRS in Microservices</h3><ol><li><strong>Improved Performance:</strong></li></ol><ul><li>By optimizing the read and write operations independently, each operation can be designed to perform its best. Read operations can be highly optimized for speed (e.g., through denormalization or caching), while write operations can ensure consistency and data integrity.</li></ul><p><strong>2. Independent Scalability:</strong></p><ul><li>Since reads and writes are handled by different models, they can be scaled independently based on the traffic each generates. For instance, a system with high read traffic (e.g., a search engine) can scale the query service without needing to scale the command service.</li></ul><p><strong>3. Flexibility and Evolvability:</strong></p><ul><li>With CQRS, the system becomes more flexible because changes to one model (read or write) do not necessarily impact the other. This is particularly useful in large systems with complex requirements where the read and write operations evolve at different rates.</li></ul><p><strong>4. Asynchronous Processing and Event-Driven Architecture:</strong></p><ul><li>CQRS facilitates <strong>asynchronous communication</strong> and <strong>event-driven</strong> architectures, which allow for better responsiveness and scalability. By handling events asynchronously, you can build a system that can respond to high loads without blocking or waiting for real-time consistency.</li></ul><h4>How to Build this architecture? Here it’s :) CQRS Flow: Step-by-Step</h4><ol><li><strong>Command Processing (Write Operations):</strong></li></ol><ul><li>A <strong>User</strong> or <strong>Client</strong> initiates a write operation (e.g., placing an order).</li><li>The <strong>Command Handler</strong> processes the command and updates the <strong>Write Model</strong> (which could be a relational database).</li><li>If <strong>Event Sourcing</strong> is used, the <strong>Event Store</strong> records the resulting events (e.g., “OrderPlaced”).</li></ul><p><strong>2. Event Propagation:</strong></p><ul><li>After a command is processed, an <strong>Event</strong> is triggered and placed on the <strong>Event Bus</strong>.</li><li>The <strong>Event Bus</strong> transmits these events to the read side, which may update the <strong>Read Model</strong> based on the event.</li></ul><p><strong>3. Query Processing (Read Operations):</strong></p><ul><li>When the system needs to handle read operations (e.g., fetching an order’s details), a <strong>Query Handler</strong> is invoked.</li><li>The <strong>Query Handler</strong> retrieves data from the <strong>Read Model</strong>, which is optimized for fast retrieval, often using a <strong>NoSQL database</strong> or <strong>cache</strong> to store denormalized, query-friendly data.</li></ul><p><strong>4. Data Synchronization:</strong></p><ul><li>The <strong>Event Bus</strong> ensures eventual consistency between the <strong>Write Model</strong> and the <strong>Read Model</strong>. As events are published, the read side is eventually updated, but not necessarily in real-time. This leads to <strong>eventual consistency</strong>, where the read model might be slightly out-of-sync with the write model at any given time.</li></ul><h3>CQRS Diagram Explanation</h3><p>CQRS is a pattern that splits the handling of <strong>write operations</strong> (commands) and <strong>read operations</strong> (queries) into separate models, which can be optimized independently. The key idea behind CQRS is to separate the responsibilities of command and query processing to handle each with the most appropriate design, enhancing performance, scalability, and flexibility. This approach works particularly well in microservices architectures.</p><h4>Here’s how the components of a CQRS system would typically interact, visualized in a basic diagram format:</h4><pre>+------------------+           +-------------------------+           +-------------------+<br>|      User        |  -----&gt;   |    Command Handler      |  -----&gt;   |   Write Model     |<br>|    (Client)      |           |  (Process Commands)      |           |     (SQL DB)      |<br>+------------------+           +-------------------------+           +-------------------+<br>                                               |<br>                                         +-------------------+<br>                                         |    Event Store    |<br>                                         |  (Event Sourcing) |<br>                                         +-------------------+<br>                                               |<br>                                     +------------------------+<br>                                     |        Event Bus       |<br>                                     +------------------------+<br>                                               |<br>+---------------------+         +-------------------------+         +---------------------+<br>|   Query Handler     |  &lt;----&gt; |      Read Model         |  &lt;----&gt; |  NoSQL DB / Cache   |<br>|   (Process Queries) |         |   (Denormalized Data)   |         |   (Fast Access)     |<br>+---------------------+         +-------------------------+         +---------------------+<br>                                               |<br>                                        +--------------+<br>                                        |    User      |<br>                                        |   (Client)   |<br>                                        +--------------+</pre><h3>Components in the Diagram:</h3><ol><li><strong>Command Handler</strong>: Handles write operations (commands) and updates the system state by modifying the write model.</li><li><strong>Event Store</strong>: Stores events that are generated after commands are executed. These events represent state changes in the system.</li><li><strong>Event Bus</strong>: Acts as the mediator for communication between the write side and the read side. Events are passed through the event bus and consumed by the read model to update the read side.</li><li><strong>Query Handler</strong>: Handles read operations and fetches data from the read model.</li><li><strong>Read Model</strong>: Optimized for read access, typically denormalized for faster querying, and stored in systems like NoSQL databases or caches.</li><li><strong>NoSQL DB / Cache</strong>: The data store used for fast read access, providing quick responses to queries by utilizing denormalized data and caching mechanisms.</li></ol><blockquote><em>Congratulations !, I hope to work :)</em></blockquote><blockquote><strong>I hope it will be useful for you. :)<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</strong></blockquote><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk">https://github.com/incikucuk</a></blockquote><blockquote><strong>Delightful encodings!</strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9fcd164928e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/cqrs-command-query-responsibility-segregation-pattern-with-an-example-c9fcd164928e">CQRS (Command Query Responsibility Segregation) Pattern with an Example</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add the SSH Key to GitHub: -fatal: repository does not exist.]]></title>
            <link>https://blog.stackademic.com/add-the-ssh-key-to-github-fatal-repository-does-not-exist-333f969eb04c?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/333f969eb04c</guid>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[git-clone]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ssh-keys]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 13:14:50 GMT</pubDate>
            <atom:updated>2024-11-28T18:55:32.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Et5cWjcbblHcY5_0jjCR1Q.png" /></figure><p><strong><em>If you are also encountering this error while cloning a project, try these steps as well!</em></strong></p><h3>Why Use SSH Keys with Git and GitHub?</h3><p>SSH (Secure Shell) keys are used as a more secure and efficient way of authenticating your identity to services like GitHub, rather than relying on traditional username/password authentication. Here’s one of these why SSH keys are commonly used: “Secure Authentication”.</p><h3>Secure Authentication</h3><ul><li><strong>Passwordless Login</strong>: SSH keys allow you to authenticate with GitHub without needing to enter your username and password every time you perform Git operations (e.g., git clone, git push, git pull).</li><li><strong>Encrypted Communication</strong>: SSH keys provide an encrypted connection between your computer and GitHub, making it more secure than using HTTPS alone. It ensures that the data transferred between your computer and GitHub is protected from eavesdropping or tampering.</li></ul><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk?tab=repositories">https://github.com/incikucuk</a></blockquote><h3>1. Generate a New SSH Key (If You Don’t Have One)</h3><p>If you don’t already have an SSH key, you need to generate one:</p><h4>a. Open your terminal and run:</h4><pre>ssh-keygen -t ed25519 -C &quot;your_email@example.com&quot;</pre><ul><li>If your system doesn’t support ed25519, use:</li></ul><pre>ssh-keygen -t rsa -b 4096 -C &quot;your_email@example.com&quot;</pre><h4>b. When prompted:</h4><ul><li><strong>Location to save key</strong>: Press Enter to accept the default location (~/.ssh/id_ed25519 or ~/.ssh/id_rsa).</li><li><strong>Passphrase</strong>: Optional but recommended. Press Enter to skip or set a secure passphrase.</li></ul><h3>2. Add Your SSH Key to the SSH Agent</h3><p>To ensure your key is available for Git operations:</p><p>a. Start the SSH agent:</p><pre>eval &quot;$(ssh-agent -s)&quot;</pre><p>b. Add your SSH key:</p><pre>ssh-add ~/.ssh/id_ed25519</pre><p>(Replace id_ed25519 with id_rsa if using RSA.)</p><h3>3. Copy Your SSH Public Key</h3><p>Now, copy your public key to add it to GitHub:</p><h4>a. Run the following command to display the key:</h4><pre>cat ~/.ssh/id_ed25519.pub</pre><p>(Use id_rsa.pub if using RSA.)</p><p>b. Copy the output (starting with ssh-ed25519 or ssh-rsa).</p><h3>4. Add the SSH Key to GitHub</h3><h4>a. Log in to <a href="https://github.com/">GitHub</a>.</h4><h4>b. Go to Settings:</h4><ul><li>Click on your profile picture in the top-right corner.</li><li>Navigate to <strong>Settings</strong> &gt; <strong>SSH and GPG keys</strong>.</li></ul><h4>c. Click New SSH Key:</h4><ul><li>Title: Give it a recognizable name (e.g., “Work Laptop”).</li><li>Key: Paste your copied public key.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlTwurVdlOEGsiBw8ajPmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0iP1TcmdfOgfq9QVW1Bag.png" /><figcaption>Settings/SSH and GPG keys</figcaption></figure><h4>d. Click Add SSH Key.</h4><h3>5. Test the Connection</h3><p>To ensure your SSH key works:</p><pre>ssh -T git@github.com</pre><p>If successful, you should see:</p><pre>Hi username! You&#39;ve successfully authenticated, but GitHub does not provide shell access.</pre><p>Now turn off your terminal and turn it on again and try;</p><pre>git clone &quot;project-link&quot;</pre><blockquote>Congratulations !, I hope to work :)</blockquote><blockquote><strong><em>I hope it will be useful for you. :)<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</em></strong></blockquote><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk"><em>https://github.com/incikucuk</em></a></blockquote><blockquote><strong><em>Delightful encodings!</em></strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=333f969eb04c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/add-the-ssh-key-to-github-fatal-repository-does-not-exist-333f969eb04c">Add the SSH Key to GitHub: -fatal: repository does not exist.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concepts of Liveness and Readiness in Microservices]]></title>
            <link>https://blog.stackademic.com/concepts-of-liveness-and-readiness-in-microservices-ab29f891ea4a?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab29f891ea4a</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[config-server]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 06:13:57 GMT</pubDate>
            <atom:updated>2024-11-22T12:46:51.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8-Jrj5E9B0QBRhmg1kPMmA.png" /></figure><p><strong>Liveness</strong> and <strong>readiness</strong> are two important health check concepts that help ensure the availability and operational stability of each service within a microservice architecture. These checks are vital for proper monitoring, load balancing, and service management.</p><p>Let’s get started! :)</p><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk?tab=repositories"><em>https://github.com/incikucuk</em></a></blockquote><h3>1. Liveness:</h3><p>Liveness refers to the ability of a microservice to function and remain alive. A <strong>liveness check</strong> is used to determine whether a service is still running and capable of performing its task. If a liveness check fails, it typically indicates that the service has entered an irrecoverable state, and the orchestrator (like Kubernetes) can restart the service or trigger some form of recovery.</p><ul><li><strong>Purpose</strong>: To determine whether the service is still alive, i.e., it hasn’t crashed or gone into an irrecoverable state.</li><li><strong>When to Use</strong>: If the service has become unresponsive, stuck, or deadlocked, a liveness probe can ensure the system recognizes this and restarts the service to restore functionality.</li></ul><h4>Example of Liveness Check:</h4><ul><li><strong>Typical use case</strong>: In a web application, if the service gets stuck on a deadlock or enters an infinite loop, a liveness probe can detect this and restart the service.</li></ul><h3>2. Readiness:</h3><p>Readiness refers to whether a service is ready to handle requests. A <strong>readiness check</strong> is used to assess whether a service has completed its startup process and is prepared to process traffic. This is particularly important during service initialization or when dependencies are still being established (e.g., connecting to a database or caching system).</p><ul><li><strong>Purpose</strong>: To verify whether the service has finished initializing and can start accepting traffic.</li><li><strong>When to Use</strong>: If the service is not yet fully initialized or waiting on some dependencies (like a database or a cache), it should fail the readiness probe until everything is ready to handle traffic.</li></ul><h4>Example of Readiness Check:</h4><ul><li><strong>Typical use case</strong>: A microservice might require some setup before it can accept requests, such as establishing a connection to an external database. A readiness probe will check whether this connection has been established before allowing traffic to reach the service.</li></ul><h3>How These Concepts are Used in Microservices:</h3><p>Let’s consider a <strong>specific example</strong>: A <strong>e-commerce system</strong> built using microservices architecture.</p><ul><li><strong>E-commerce microservices</strong>: This could include a user service, product catalog service, order service, payment service, etc.</li></ul><h3>Scenario:</h3><p>Suppose the system is deployed on <strong>Kubernetes</strong>, and each service has its own set of requirements. The <strong>Order Service</strong> interacts with a <strong>Payment Service</strong>, and the <strong>User Service</strong> communicates with a <strong>Database</strong>. Here’s how liveness and readiness checks are applied:</p><h4><strong>Order Service</strong>:</h4><ul><li><strong>Liveness Check</strong>: This service should have a liveness probe to ensure that it remains operational. If it becomes stuck or unresponsive (e.g., an internal deadlock), Kubernetes will restart the service. A simple HTTP endpoint like /health/liveness can be implemented to return a status code 200 if the service is running.</li><li><strong>Readiness Check</strong>: The order service needs to check whether it can interact with its dependencies (e.g., database or payment gateway). A /health/readiness endpoint might check whether the payment service is reachable or the database connection is established. If any dependency isn&#39;t ready, the service won&#39;t accept traffic until it&#39;s fully ready.</li></ul><h4><strong>Payment Service</strong>:</h4><ul><li><strong>Liveness Check</strong>: If the payment service is stuck (e.g., due to a bug in the payment gateway integration), the liveness probe would detect this and initiate a restart.</li><li><strong>Readiness Check</strong>: If the payment service requires a connection to an external payment provider API, a readiness check could verify whether the external API is reachable and the service is able to process transactions. Only after this check would the service begin accepting payment requests.</li></ul><h4><strong>User Service</strong>:</h4><ul><li><strong>Liveness Check</strong>: The user service could also have a liveness probe to ensure that the service is running. If the service has a failure, such as memory exhaustion or deadlock, the probe would fail, and the orchestrator would restart it.</li><li><strong>Readiness Check</strong>: This could ensure that the database connection is ready, as the service might rely on an external database for storing user information.</li></ul><h4>Example of Implementing Health Checks:</h4><p>In <strong>Kubernetes</strong>, you can define liveness and readiness probes in your deployment YAML files. Below is an example configuration for a microservice.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: orders-service<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: orders-service<br>  template:<br>    metadata:<br>      labels:<br>        app: orders-service<br>    spec:<br>      containers:<br>        - name: orders-service<br>          image: orders-service:latest<br>          ports:<br>            - containerPort: 8080<br>          livenessProbe:<br>            httpGet:<br>              path: /health/liveness<br>              port: 8080<br>            initialDelaySeconds: 5<br>            periodSeconds: 10<br>          readinessProbe:<br>            httpGet:<br>              path: /health/readiness<br>              port: 8080<br>            initialDelaySeconds: 5<br>            periodSeconds: 10</pre><p>In this example: (you can take a look at the item below if you’re have no idea about Actuator in Spring Boot: <strong>How to Use Spring Boot Actuator for Liveness and Readiness</strong>)</p><ul><li><strong>Liveness Probe</strong>: It checks /health/liveness every 10 seconds after an initial delay of 5 seconds. If the probe fails, Kubernetes will restart the pod.</li><li><strong>Readiness Probe</strong>: It checks /health/readiness to determine if the service is ready to accept traffic. If this fails, the service will be marked as unavailable for routing, preventing traffic from being sent to it until it’s ready.</li></ul><h3>Benefits of Liveness and Readiness in Microservices:</h3><ol><li><strong>Automated Recovery</strong>: Services that are not responsive or in a failed state can be automatically restarted by the orchestrator.</li><li><strong>Avoid Traffic to Unready Services</strong>: Ensures that requests are only routed to services that are fully initialized and ready to handle traffic, improving reliability and user experience.</li><li><strong>Early Failure Detection</strong>: These probes allow you to detect problems early, before they impact the user experience, and take appropriate corrective actions.</li></ol><h3>Configuring Readiness and Liveness in Spring Boot with Actuator</h3><p>Spring Boot Actuator exposes a /actuator/health endpoint by default, but you can customize this endpoint to provide separate checks for <strong>liveness</strong> and <strong>readiness</strong>.</p><p>Here’s how you can check and configure <strong>readiness</strong> and <strong>liveness</strong> checks using Spring Boot Actuator:</p><h3>1. Add Spring Boot Actuator Dependency</h3><p>First, you need to add the <strong>Spring Boot Actuator</strong> dependency to your project.</p><p>If you are using <strong>Maven</strong>, add the following dependency to your pom.xml:</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><p>For <strong>Gradle</strong>, add this to your build.gradle:</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter-actuator&#39;</pre><h3>2. Configure application.properties for Actuator</h3><p>To enable <strong>readiness</strong> and <strong>liveness</strong> checks, you need to configure Spring Boot Actuator in your application.properties or application.yml file.</p><h4>Example of application.properties configuration:</h4><pre># Expose actuator health endpoints<br>management.endpoints.web.exposure.include=health,info<br><br># Enable Liveness and Readiness probes<br>management.endpoint.health.probes.enabled=true<br><br># Show health details (optional, useful for debugging)<br>management.endpoint.health.show-details=always</pre><h3>3. Accessing the Health Check Endpoints</h3><p>By default, Spring Boot exposes a <strong>generic health check</strong> at /actuator/health. If you have configured both <strong>liveness</strong> and <strong>readiness</strong> checks, the following paths will be exposed:</p><ul><li><strong>Liveness Check</strong>: /actuator/health/liveness</li><li><strong>Readiness Check</strong>: /actuator/health/readiness</li></ul><p>If you want to check the health of your service, you can visit the following URLs (assuming your Spring Boot app is running locally on port 8080):</p><ul><li><strong>Liveness Check</strong>: <a href="http://localhost:8080/actuator/health/liveness">http://localhost:8080/actuator/health/liveness</a></li><li><strong>Readiness Check</strong>: <a href="http://localhost:8080/actuator/health/readiness">http://localhost:8080/actuator/health/readiness</a></li></ul><blockquote><strong>I hope it will be useful for you. :)<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</strong></blockquote><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk">https://github.com/incikucuk</a></blockquote><blockquote><strong>Delightful encodings!</strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab29f891ea4a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/concepts-of-liveness-and-readiness-in-microservices-ab29f891ea4a">Concepts of Liveness and Readiness in Microservices</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using and Dockerizing Spring Cloud Bus with RabbitMQ in Microservices]]></title>
            <link>https://blog.stackademic.com/using-and-dockerizing-spring-cloud-bus-with-rabbitmq-in-microservices-bcfe845f9c89?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcfe845f9c89</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-cloud-bus]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 06:57:31 GMT</pubDate>
            <atom:updated>2024-11-18T13:34:34.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*S7mp0R4IsterF3JpPBVJdg.png" /></figure><h3>What’s Spring Cloud Bus?</h3><p><strong>Spring Cloud Bus</strong> is a part of the <strong>Spring Cloud</strong> ecosystem that provides a simple way for microservices to communicate with each other through a <strong>distributed event bus</strong>. It facilitates <strong>event-driven communication</strong> between services, allowing them to share state or notify each other about specific events, such as configuration changes or system status updates.</p><p>In microservices architectures, there are typically many independent services that need to share information. Spring Cloud Bus provides a lightweight mechanism for propagating <strong>events</strong> or <strong>messages</strong> across a system. It can be thought of as a <strong>messaging infrastructure</strong> for microservices, enabling a variety of use cases like <strong>dynamic configuration updates</strong>, <strong>service communication</strong>, <strong>health monitoring</strong>, and <strong>distributed tracing</strong>.</p><p>Let’s get started! :)</p><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk?tab=repositories"><em>https://github.com/incikucuk</em></a></blockquote><h3>Use and Purpose of Spring Cloud Bus in Microservice Projects</h3><p>In <strong>microservice projects</strong>, <strong>Spring Cloud Bus</strong> serves several purposes:</p><ol><li><strong>Event Propagation</strong>:</li></ol><ul><li>Spring Cloud Bus allows microservices to <strong>publish</strong> and <strong>subscribe</strong> to events. This is useful for decoupling services, where one service can notify others about changes, updates, or tasks that need to be performed without the services directly knowing each other.</li></ul><p><strong>Example: </strong>Service A completes a task and publishes an event that triggers Service B to start processing or updating a related state.</p><p><strong>2. Dynamic Configuration Updates</strong>:</p><ul><li>When using <strong>Spring Cloud Config Server</strong> to manage external configurations for your microservices, Spring Cloud Bus helps <strong>propagate configuration changes</strong> to all connected services in real-time. This eliminates the need to restart services for configuration changes.</li></ul><p><strong>Example</strong>: You update a configuration property in the <strong>Config Server</strong>; Spring Cloud Bus will broadcast the change to all microservices, and they can reload the configuration dynamically.</p><p><strong>3. Decoupling Services</strong>:</p><ul><li>Microservices in a Spring Cloud Bus setup do not need to directly communicate with each other. Instead, they can publish events to a message broker, and other services can <strong>listen</strong> to these events asynchronously. This makes it easier to scale services independently and adds flexibility to your system.</li></ul><p><strong>Example: </strong>A service sends an event when a new user is created, and other services, like the notification service, subscribe to the event and send a welcome message.</p><p><strong>4. Distributed Systems Communication</strong>:</p><ul><li>Spring Cloud Bus enables <strong>asynchronous communication</strong> across distributed services. It can handle message propagation between services running in different data centers or cloud environments, using a message broker such as <strong>RabbitMQ</strong> or <strong>Apache Kafka</strong>.</li></ul><h3>How is Spring Cloud Bus Used in Microservice Projects?</h3><p>Spring Cloud Bus is most commonly used in microservices projects that employ <strong>event-driven architecture</strong>. Here’s how to set it up:</p><ol><li><strong>Dependencies</strong>:</li></ol><ul><li>Add the Spring Cloud Bus starter and the messaging infrastructure (RabbitMQ or Kafka) dependencies to your pom.xml or build.gradle file.</li></ul><p>For <strong>RabbitMQ</strong>:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-bus-amqp&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>For <strong>Kafka</strong>:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-bus-kafka&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>2. Configuration</strong>:</p><ul><li><strong>Message Broker Configuration</strong>: Spring Cloud Bus requires a message broker like <strong>RabbitMQ</strong> or <strong>Kafka</strong>. You need to configure the broker in your application properties.</li></ul><p>Example configuration for RabbitMQ:</p><pre>spring:<br>  cloud:<br>    stream:<br>      bindings:<br>        input:<br>          destination: bus<br>          group: service-group<br>        output:<br>          destination: bus<br>      rabbitmq:<br>        host: localhost<br>        port: 5672</pre><p>For Kafka;</p><pre>spring:<br>  cloud:<br>    stream:<br>      bindings:<br>        input:<br>          destination: bus<br>          group: service-group<br>        output:<br>          destination: bus<br>      kafka:<br>        bootstrap-servers: localhost:9092</pre><p><strong>3.Spring Cloud Config Integration</strong>:</p><ul><li>If you’re using Spring Cloud Config to manage external configurations, Spring Cloud Bus can propagate configuration changes across all microservices. The microservices need to be annotated with @RefreshScope to support dynamic configuration refresh.</li></ul><p>Example:</p><pre>@Configuration<br>@RefreshScope<br>public class MyConfig {<br>    @Value(&quot;${my.property}&quot;)<br>    private String myProperty;<br><br>    public String getMyProperty() {<br>        return myProperty;<br>    }<br>}</pre><p><strong>4.Event Publishing</strong>:</p><ul><li>A service can publish events to the bus when a specific action occurs. For example, if a configuration changes or a system event needs to be broadcast, the service can publish an event.</li></ul><p>Example:</p><pre>@PostMapping(&quot;/refresh&quot;)<br>public void triggerRefresh() {<br>    context.publishEvent(new RefreshEvent(this));<br>}</pre><p><strong>5.Event Listening</strong>:</p><ul><li>Services can subscribe to events from the bus. You can use Spring’s @EventListener annotation to listen for specific events.</li></ul><p>Example:</p><pre>@Component<br>public class EventListener {<br><br>    @EventListener<br>    public void handleRefreshEvent(RefreshEvent event) {<br>        // Handle the event (e.g., refresh application context)<br>        System.out.println(&quot;Received refresh event: &quot; + event);<br>    }<br>}</pre><p><strong>6. Testing Spring Cloud Bus</strong>: To test Spring Cloud Bus in a <strong>microservices environment</strong>, you need to verify the interaction between services, message propagation, and dynamic configuration updates.</p><h3>Setting Up and Testing Spring Cloud Bus with Docker and RabbitMQ</h3><p>You can run your microservices, message broker, and the Spring Cloud Bus setup using <strong>Docker</strong>. Here’s how to set up <strong>Docker</strong> for Spring Cloud Bus with <strong>RabbitMQ</strong> and test it.</p><h4>1. Docker Setup for RabbitMQ:</h4><p>You can use <strong>Docker Compose</strong> to run RabbitMQ along with your Spring Boot applications.</p><p>Create a docker-compose.yml file:</p><pre>version: &#39;3&#39;<br>services:<br>  rabbitmq:<br>    image: rabbitmq:3-management<br>    container_name: rabbitmq<br>    ports:<br>      - &quot;15672:15672&quot;   # RabbitMQ Management UI<br>      - &quot;5672:5672&quot;     # AMQP protocol<br>    networks:<br>      - bus-network<br>  service-a:<br>    image: service-a:latest<br>    networks:<br>      - bus-network<br>    depends_on:<br>      - rabbitmq<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=default<br>  service-b:<br>    image: service-b:latest<br>    networks:<br>      - bus-network<br>    depends_on:<br>      - rabbitmq<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=default<br><br>networks:<br>  bus-network:<br>    driver: bridge</pre><p>This sets up <strong>RabbitMQ</strong> with the management interface on port 15672 and the AMQP protocol on port 5672. The services (service-a, service-b) are connected to the same network and can communicate via RabbitMQ.</p><h4>2. Dockerizing Spring Boot Services:</h4><p>For each Spring Boot service (service-a, service-b), create a <strong>Dockerfile</strong> to build and run the application in Docker containers.</p><p>Example Dockerfile:</p><pre>FROM openjdk:17-jdk-alpine<br>VOLUME /tmp<br>COPY target/service-a.jar service-a.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/service-a.jar&quot;]</pre><p>Then, build and run the services using Docker:</p><pre>docker build -t service-a .<br>docker build -t service-b .<br>docker-compose up --build</pre><h4>3. Testing Event Propagation and Configuration Updates:</h4><ol><li><strong>Trigger an Event</strong>: In your service-a, you could trigger an event like a configuration refresh or any other business event by calling an endpoint (e.g., /refresh).</li><li><strong>Monitor Logs</strong>: Check the logs of both service-a and service-b to see if the event is received and handled appropriately. You should see something like:</li></ol><pre>Received refresh event: RefreshEvent[...]</pre><p><strong>3. Verify Configuration Propagation</strong>: If you’re testing dynamic configuration propagation, you can update a property in the Spring Cloud Config Server (or directly in your service properties) and trigger a refresh event to ensure that all services respond to the change.</p><p>When using <strong>Docker</strong> with <strong>RabbitMQ</strong> for testing Spring Cloud Bus, the steps involve setting up RabbitMQ as the message broker, Dockerizing the Spring Boot microservices, and ensuring proper event publishing and listening across services. Once the setup is running, you can test by triggering events (such as configuration refreshes) and verifying that the services respond to these events correctly.</p><blockquote><strong><em>I hope it will be useful for you. :)<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</em></strong></blockquote><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk"><em>https://github.com/incikucuk</em></a></blockquote><blockquote><strong><em>Delightful encodings!</em></strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcfe845f9c89" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/using-and-dockerizing-spring-cloud-bus-with-rabbitmq-in-microservices-bcfe845f9c89">Using and Dockerizing Spring Cloud Bus with RabbitMQ in Microservices</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerize According to the needs of Your Microservice Projects with Docker Image Creation Tools]]></title>
            <link>https://blog.stackademic.com/containerize-according-to-the-needs-of-your-microservice-projects-with-docker-image-creation-tools-e05335e7865e?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05335e7865e</guid>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-toolbox]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 06:42:13 GMT</pubDate>
            <atom:updated>2024-11-12T01:05:36.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D13JDzrrtrHu_ZKkIgi79Q.png" /></figure><h3>What is a Docker Image?</h3><p>A <strong>Docker image</strong> is a lightweight, stand-alone, and executable package that contains everything needed to run a piece of software: the code, runtime, libraries, environment variables, and configurations. It’s essentially a snapshot of an application and its environment at a specific point in time, encapsulated in a single file format that Docker can use to run containers.</p><h4>Docker Image Creation Tools: Overview and How to Use Them</h4><p>Docker image creation tools are utilities and libraries that help automate, streamline, or simplify the process of building Docker images. These tools offer varying levels of abstraction, from full manual control over the image creation (via Dockerfiles) to fully automated solutions that require little to no input (like Buildpacks and Google Jib).</p><p>The purpose of these tools is to make it easier to package applications and their dependencies into containers, providing a consistent and portable environment across development, testing, and production.</p><p>Let’s get started! :)</p><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk?tab=repositories">https://github.com/incikucuk</a></blockquote><h3>Types of Docker Image Creation Tools</h3><p>Here are some of the most common tools for creating Docker images:</p><h3>1. Dockerfile</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*QrBBbvgb-Nd6R_zxnhYFug.png" /></figure><h4>What is it?</h4><p>A Dockerfile is the fundamental tool for creating Docker images manually. It is a text file containing a series of instructions that Docker uses to build an image. These instructions specify the operating system, dependencies, environment variables, commands, and files that should be included in the image.</p><h4>How to Use It:</h4><ol><li><strong>Create a Dockerfile</strong>: Define a set of instructions for how the image should be built.</li><li><strong>Build the Image</strong>: Use the docker build command to generate the image based on the Dockerfile.</li></ol><p>Example Dockerfile:</p><pre># Start with an official Node.js base image<br>FROM node:16</pre><pre># Set the working directory in the container<br>WORKDIR /app</pre><pre># Copy package.json and install dependencies<br>COPY package*.json ./<br>RUN npm install</pre><pre># Copy the rest of the application files<br>COPY . .</pre><pre># Expose the port<br>EXPOSE 3000</pre><pre># Start the application<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p>To build and run the image:</p><pre>docker build -t my-app .<br>docker run -p 3000:3000 my-app</pre><h4>When to Use:</h4><ul><li><strong>Full Control</strong>: When you need granular control over the image creation process.</li><li><strong>Custom Applications</strong>: When you need to specify particular dependencies, configurations, or build steps.</li><li><strong>Production-ready Images</strong>: When you’re building images for production environments, where reproducibility and performance are important.</li></ul><h4>Best Projects to Use Dockerfile:</h4><ul><li><strong>Web applications (backend, frontend)</strong>.</li><li><strong>Microservices</strong> that require specific software configurations.</li><li><strong>Custom software solutions</strong> that need full control over the build process.</li><li><strong>CI/CD pipelines</strong> where automation and reproducibility are required.</li></ul><h3>2. Docker Buildx (Advanced Docker Build)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*tulvUNfBJuApcfkqYqLSGQ.png" /></figure><p>Docker <strong>Buildx</strong> is an extension of the docker build command that allows for advanced building techniques, including multi-platform builds and better caching.</p><h4>How to Use It:</h4><ol><li><strong>Enable Buildx</strong>: Docker Buildx is available with Docker 19.03 or later. You need to enable the experimental features to use Buildx.</li><li><strong>Create a Build Context</strong>: You can build images across different platforms (e.g., ARM, x86) and even cache layers more efficiently.</li></ol><p>Example:</p><pre>DOCKER_BUILDKIT=1 docker buildx build --platform linux/amd64,linux/arm64 -t my-multi-platform-app .</pre><h4>When to Use:</h4><ul><li><strong>Cross-platform Builds</strong>: When you need to build images for multiple platforms (e.g., x86_64 and ARM-based systems).</li><li><strong>Optimized Builds</strong>: When you need better caching and parallel builds to speed up the image creation process.</li></ul><h4>Best Projects to Use Buildx:</h4><ul><li><strong>Cross-platform applications</strong> (e.g., supporting both Linux x86 and ARM architectures).</li><li><strong>Microservices</strong> deployed across diverse environments (e.g., Kubernetes clusters on different hardware).</li><li><strong>Performance-sensitive builds</strong> in CI/CD pipelines.</li></ul><h3>3. Buildpacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*CwRdhOKMr-2nY1By7j4Ljw.png" /></figure><h4>What is it?</h4><p>Buildpacks are tools designed to automate the process of building Docker images, primarily focused on platform-as-a-service (PaaS) models like <strong>Heroku</strong>. A Buildpack inspects the source code, determines the environment (e.g., Node.js, Python, Java), installs the necessary runtime and dependencies, and packages everything into a Docker image.</p><h4>How to Use It:</h4><ol><li><strong>Install Buildpack CLI Tools</strong>: Tools like pack CLI or ko (for Kubernetes) allow you to build images using Buildpacks.</li><li><strong>Build the Image</strong>: After setting up the Buildpack, you can build the image with a simple command.</li></ol><p>Example:</p><pre>pack build my-app --path ./my-app</pre><p>The Buildpack will:</p><ul><li>Detect the language and framework (e.g., Node.js, Python).</li><li>Install dependencies.</li><li>Package the application into a Docker image.</li></ul><h4>When to Use:</h4><ul><li><strong>Simplified Docker Image Creation</strong>: When you want a streamlined process that automates most of the steps in creating an image.</li><li><strong>Cloud-native apps</strong>: Ideal for apps that are designed to run in cloud-native environments, where Buildpacks automatically handle environment setup and dependency management.</li><li><strong>Teams with little Docker experience</strong>: For teams that prefer not to deal with the complexities of writing Dockerfiles.</li></ul><h4>Best Projects to Use Buildpacks:</h4><ul><li><strong>Web applications</strong> (especially those built with common frameworks).</li><li><strong>Microservices</strong> where you want to focus on application code rather than managing containers.</li><li><strong>Cloud-native applications</strong> that are designed to be easily portable across platforms (e.g., Kubernetes or Heroku-like environments).</li></ul><h3>4. Google Jib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*zWAv_eMToxjkfdGeRsxbfA.png" /></figure><h4>What is it?</h4><p><a href="https://github.com/GoogleContainerTools/jib">Google Jib</a> is a tool specifically for building Docker images for Java applications. Unlike Dockerfiles, Jib builds images without requiring the Docker daemon. It works by directly building layers for Java applications and pushing them to Docker or other container registries, avoiding the overhead of running a Docker daemon.</p><h4>How to Use It:</h4><ul><li><strong>Maven Integration</strong>: Jib integrates with Maven or Gradle, and you can configure it via your pom.xml (for Maven) or build.gradle (for Gradle).</li></ul><p>Example Maven configuration for Jib:</p><pre>&lt;plugin&gt;<br>  &lt;groupId&gt;com.google.cloud.tools&lt;/groupId&gt;<br>  &lt;artifactId&gt;jib-maven-plugin&lt;/artifactId&gt;<br>  &lt;version&gt;3.1.4&lt;/version&gt;<br>  &lt;configuration&gt;<br>    &lt;to&gt;<br>      &lt;image&gt;gcr.io/my-project/my-java-app&lt;/image&gt;<br>    &lt;/to&gt;<br>  &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>Build the image:</p><pre>mvn compile jib:build</pre><h4>When to Use:</h4><ul><li><strong>Java Applications</strong>: Jib is optimized for building images for Java-based applications, and it removes the need for Dockerfiles.</li><li><strong>Speed and Efficiency</strong>: Jib uses a layered approach, which optimizes caching and speeds up image builds.</li><li><strong>CI/CD</strong>: Jib is designed to work well in CI/CD environments, especially for Java developers using Maven or Gradle.</li></ul><h4>Best Projects to Use Jib:</h4><ul><li><strong>Java-based microservices</strong>.</li><li><strong>Spring Boot applications</strong> or other Java applications deployed to container environments.</li><li><strong>Projects where Maven or Gradle is the primary build tool</strong>.</li></ul><h3>5. Kaniko</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFR2dyDgYJEov8r7jBOX1A.png" /></figure><h4>What is it?</h4><p><a href="https://github.com/GoogleContainerTools/kaniko">Kaniko</a> is an open-source tool for building container images from a Dockerfile, inside a container or Kubernetes cluster. Kaniko is optimized for environments where Docker is not available or where using Docker in a containerized environment is inefficient (such as within a CI/CD pipeline).</p><h4>How to Use It:</h4><ol><li><strong>Install Kaniko</strong>: Kaniko is designed to run in a Kubernetes cluster or a Docker container.</li><li><strong>Run the Kaniko build</strong>: You can provide it with a Dockerfile and a build context, and it will create the Docker image.</li></ol><p>Example:</p><pre>/kaniko/executor --context $BUILD_CONTEXT --dockerfile $DOCKERFILE --destination $IMAGE_TAG</pre><h4>When to Use:</h4><ul><li><strong>CI/CD Pipelines</strong>: Kaniko is particularly useful in CI/CD pipelines where running a Docker daemon is either not possible or inefficient.</li><li><strong>Kubernetes-based Builds</strong>: Kaniko runs inside Kubernetes clusters, making it ideal for building images in Kubernetes-native workflows.</li></ul><h4>Best Projects to Use Kaniko:</h4><ul><li><strong>CI/CD pipelines</strong> for building images in cloud environments (e.g., Kubernetes).</li><li><strong>Containerized environments</strong> where you don’t want to run Docker inside a container.</li></ul><h3>6. Docker Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RG8aewFe3lNDwvC4TLDSNA.png" /></figure><h4>What is it?</h4><p>Docker Compose is a tool used for defining and running multi-container Docker applications. It is not an image creation tool per se, but it helps manage multi-container applications that need to be packaged into Docker images.</p><h4>How to Use It:</h4><ol><li><strong>Define a </strong><strong>docker-compose.yml file</strong>: This file specifies services, networks, and volumes that Docker Compose will manage.</li><li><strong>Run Docker Compose</strong>: It automatically builds the images for the services defined in the Compose file.</li></ol><p>Example:</p><pre>version: &#39;3.7&#39;<br>services:<br>  web:<br>    build: ./web<br>    ports:<br>      - &quot;5000:5000&quot;<br>  db:<br>    image: postgres:alpine</pre><h4>When to Use:</h4><ul><li><strong>Multi-container Applications</strong>: If your project requires more than one service (e.g., web app and database) to be run together.</li><li><strong>Local Development</strong>: For local development, where multiple services need to be built and run together.</li></ul><h4>Best Projects to Use Docker Compose:</h4><ul><li><strong>Full-stack applications</strong> with multiple components (e.g., web server + database).</li><li><strong>Microservice architectures</strong> that require orchestration of multiple Docker containers.</li></ul><h3>Summary of When to Use Each Tool:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjNadkiYWqeWYPyLBKn4Mg.png" /></figure><blockquote><strong>I hope it will be useful for you.<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</strong></blockquote><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk">https://github.com/incikucuk</a></blockquote><blockquote><strong>Delightful encodings!</strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05335e7865e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/containerize-according-to-the-needs-of-your-microservice-projects-with-docker-image-creation-tools-e05335e7865e">Containerize According to the needs of Your Microservice Projects with Docker Image Creation Tools</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strengthen Your Microservice Projects using 12-Factor & 15-Factor Methodologies]]></title>
            <link>https://blog.stackademic.com/strengthen-your-microservice-projects-using-12-factor-15-factor-methodologies-8f436a7a268d?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f436a7a268d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[methodology]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 05:57:53 GMT</pubDate>
            <atom:updated>2024-11-11T03:32:48.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ul1puTVxHXh-uWpeFUOAhg.jpeg" /></figure><p>The terms “12-factor” and “15-factor” methodologies refer to design principles for building cloud-native applications. These methodologies are often cited in the context of Spring Cloud, but they are not unique to it — rather, they are general principles for building modern applications that are scalable, maintainable, and resilient in cloud environments.</p><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk?tab=repositories"><em>https://github.com/incikucuk</em></a></blockquote><h3>12-Factor Methodology</h3><p>The <strong>12-Factor App</strong> methodology is a set of 12 principles for building software-as-a-service (SaaS) applications that are intended to be deployed on cloud platforms. It was first proposed by Heroku, and while it isn’t specific to Spring Cloud, it forms the foundation for how modern cloud-native applications (including those built with Spring Cloud) should be designed.</p><p><strong>Here are the 12 factors:</strong></p><ol><li><strong>Codebase</strong>: Maintain a single codebase for an application, with multiple deployments (environments).</li><li><strong>Dependencies</strong>: Explicitly declare and isolate dependencies (e.g., using a build tool like Maven or Gradle).</li><li><strong>Config</strong>: Store configuration in the environment (rather than in code).</li><li><strong>Backing services</strong>: Treat backing services (e.g., databases, message queues) as attached resources, which can be swapped easily.</li><li><strong>Build, release, run</strong>: Separate the build, release, and run stages of the application.</li><li><strong>Processes</strong>: Execute the application as one or more stateless processes. State should be stored in external systems (e.g., a database).</li><li><strong>Port binding</strong>: Export services via port binding, rather than relying on a web server configuration.</li><li><strong>Concurrency</strong>: Scale out via the process model, by running multiple instances of stateless processes.</li><li><strong>Disposability</strong>: Make processes quick to start and stop to facilitate scaling and resilience.</li><li><strong>Dev/prod parity</strong>: Keep development, staging, and production environments as similar as possible.</li><li><strong>Logs</strong>: Treat logs as event streams, and send them to a centralized log system for easy access and analysis.</li><li><strong>Admin processes</strong>: Run administrative/management tasks as one-off processes (e.g., database migrations).</li></ol><p><em>These principles are meant to make applications easier to scale, maintain, and operate in dynamic cloud environments, and are widely used in the development of Spring Cloud-based microservices applications.</em></p><h3>15-Factor Methodology</h3><p>The <strong>15-Factor App</strong> methodology builds on the 12-factor principles and adds a few more recommendations that enhance the design of modern cloud applications. It is typically used for applications that require more complex architectures (e.g., microservices, serverless, or distributed systems) and need additional considerations for operational management.</p><p><strong>Here are the additional three factors (13–15) that are part of the 15-factor methodology:</strong></p><ol><li><strong>Microservices</strong>: Treat each component of the application as a microservice. This encourages splitting the application into smaller, independently deployable services that can communicate with each other using lightweight protocols (e.g., HTTP, gRPC).</li><li><strong>Rate-limiting</strong>: Design the application to handle high traffic and impose rate-limiting to avoid overloading resources, which is important in distributed environments.</li><li><strong>Circuit Breakers</strong>: Implement resilience mechanisms, such as circuit breakers, to handle service failures gracefully and prevent cascading failures in a microservice-based architecture.</li></ol><h3>How Do the 12-Factor and 15-Factor Methodologies Relate to Spring Cloud?</h3><p>Spring Cloud is a framework for building distributed systems and microservices, and its features align well with the 12-factor principles. Here’s how Spring Cloud helps implement these methodologies:</p><ul><li><strong>Configuration Management</strong>: Spring Cloud provides tools like Spring Cloud Config for centralized configuration management, which aligns with the 12-factor principle of storing config in the environment rather than in the application code.</li><li><strong>Service Discovery</strong>: Spring Cloud integrates with service discovery tools like Eureka, enabling microservices to automatically discover and communicate with each other, which is aligned with factors like “Concurrency” and “Backing Services.”</li><li><strong>Resilience</strong>: Spring Cloud has built-in support for resilience patterns (e.g., circuit breakers via Spring Cloud Circuit Breaker or Hystrix), which is in line with the “Circuit Breakers” principle from the 15-factor methodology.</li><li><strong>Microservices</strong>: Spring Cloud promotes a microservices-based architecture through components like Spring Cloud Gateway (API Gateway) and Spring Cloud Stream (for messaging). This aligns directly with the “Microservices” principle in the 15-factor methodology.</li><li><strong>Logging and Monitoring</strong>: Spring Cloud supports integration with centralized logging and monitoring systems (such as Spring Boot Actuator, ELK stack, or Prometheus), which is aligned with the “Logs” factor in the 12-factor methodology.</li><li><strong>Scalability</strong>: Spring Cloud offers features like Spring Cloud Kubernetes for scaling applications and managing containers in Kubernetes clusters, which supports the “Concurrency” and “Disposability” principles.</li></ul><h3>Why Should We Use These Methodologies?</h3><p>Using the 12-factor or 15-factor methodologies in Spring Cloud applications brings several benefits:</p><ol><li><strong>Portability</strong>: The application is designed in a way that allows it to run on any cloud platform or in any environment (e.g., Kubernetes, AWS, Azure), which is crucial for cloud-native applications.</li><li><strong>Scalability</strong>: The design principles (such as process isolation, disposability, and horizontal scaling) help ensure that applications can scale efficiently as traffic increases.</li><li><strong>Resilience</strong>: The focus on statelessness, circuit breakers, and decentralized configuration makes it easier to build fault-tolerant and self-healing systems.</li><li><strong>Maintainability</strong>: With clear separation of concerns (build, release, run), explicit dependency management, and centralized configuration, the application becomes easier to maintain and update.</li><li><strong>Flexibility</strong>: Following these methodologies makes it easier to swap out components or services, enabling a more agile and flexible approach to application development and deployment.</li><li><strong>Improved Developer Experience</strong>: A consistent approach to building cloud-native apps helps teams adopt best practices, reducing the complexity of deployment, debugging, and scaling.</li></ol><h3><strong>What is the benefit to us in using microservice projects?</strong></h3><p>Here are the <strong>key benefits</strong> of using microservices in your projects:</p><h4>1. Scalability</h4><ul><li><strong>Independent Scaling</strong>: With microservices, each service can be scaled independently based on demand. For example, if one part of the application (e.g., payment processing) experiences higher load, it can be scaled without affecting other services (e.g., user authentication). This granular scaling helps optimize resource usage and reduces infrastructure costs.</li><li><strong>Flexible Deployment</strong>: Services can be deployed to different environments or cloud providers based on performance or cost considerations.</li></ul><h4>2. Flexibility in Technology Choices</h4><ul><li><strong>Polyglot Programming</strong>: Since each microservice is a standalone unit, you can choose the best technology stack for each service. For instance, one service could be written in Java, another in Python, and another in Go, depending on the specific needs of the service (e.g., performance, third-party libraries, or developer expertise).</li><li><strong>No Lock-in to a Single Stack</strong>: In monolithic applications, all components are often tied to the same technology stack. With microservices, you’re free to update or change technologies for specific services without rewriting the entire application.</li></ul><h4>3. Improved Developer Productivity</h4><ul><li><strong>Smaller, Focused Teams</strong>: Microservices allow teams to focus on specific areas of the application (e.g., user management, billing, or shipping). Each team can work autonomously on their microservice, leading to faster development cycles and a more efficient development process.</li><li><strong>Faster Deployment and Continuous Integration/Continuous Delivery (CI/CD)</strong>: Since services are decoupled, they can be developed, tested, and deployed independently. This enables continuous deployment, quicker releases, and faster feedback loops, which is essential in modern agile development.</li></ul><h4>4. Fault Isolation and Resilience</h4><ul><li><strong>Fault Isolation</strong>: In a microservices architecture, failure in one service doesn’t necessarily bring down the entire application. If a service fails, other services can continue to operate, and failure can be handled with patterns like <strong>circuit breakers</strong> and <strong>fallbacks</strong>. This makes your application more resilient to faults.</li><li><strong>Easier Recovery</strong>: Since services are isolated, failures are easier to detect and troubleshoot. Monitoring individual microservices helps identify issues faster, reducing downtime and speeding up recovery times.</li></ul><h4>5. Faster Time-to-Market</h4><ul><li><strong>Parallel Development</strong>: Different microservices can be developed in parallel by different teams. This parallel development accelerates the delivery of new features, allowing faster releases and updates.</li><li><strong>Frequent Releases</strong>: Microservices can be deployed independently, so teams can release new versions of specific services frequently without waiting for other services. This is a key enabler for <strong>Continuous Integration</strong> and <strong>Continuous Deployment (CI/CD)</strong> practices.</li></ul><h4>6. Optimized for Cloud and Containerization</h4><ul><li><strong>Better Cloud Integration</strong>: Microservices are a natural fit for cloud environments. Cloud platforms like <strong>AWS</strong>, <strong>Azure</strong>, and <strong>Google Cloud</strong> provide services and features (like Kubernetes) that help manage microservices at scale. Microservices can be easily containerized with <strong>Docker</strong>, and container orchestration systems (like <strong>Kubernetes</strong>) handle scaling, deployment, and fault tolerance automatically.</li><li><strong>Resource Efficiency</strong>: Microservices can be deployed on different servers or containers based on their resource requirements, leading to more efficient utilization of infrastructure.</li></ul><h4>7. Improved Maintainability and Modularity</h4><ul><li><strong>Decoupled Services</strong>: Since each service is responsible for a single business function, it’s easier to maintain, test, and refactor them individually. This leads to a more modular and flexible codebase.</li><li><strong>Easier Updates and Bug Fixes</strong>: With microservices, updates or fixes can be applied to individual services without disrupting the entire system. For example, if a bug is discovered in the user authentication service, it can be fixed and deployed independently of the payment service.</li></ul><h4>8. Easier to Adopt New Business Capabilities</h4><ul><li><strong>Incremental Changes</strong>: Microservices allow teams to incrementally add new features or business capabilities to the application. New services can be introduced without major rewrites, enabling faster innovation.</li><li><strong>Adapt to Market Changes</strong>: With microservices, it is easier to integrate new technologies, adopt third-party services, or pivot the application as the business evolves, ensuring long-term agility.</li></ul><h4>9. Better Security</h4><ul><li><strong>Isolated Security Layers</strong>: Since each microservice can have its own authentication and authorization rules, security is better isolated and can be customized based on the specific requirements of each service. For example, the payment service might require stricter security measures (e.g., two-factor authentication), while a user profile service might not need the same level of security.</li><li><strong>Granular Control</strong>: Security policies can be enforced at the service level, and you can limit the attack surface of each microservice.</li></ul><h4>10. Improved Testing</h4><ul><li><strong>Independent Testing</strong>: Each microservice can be tested independently, which simplifies unit testing and integration testing. You can mock or simulate other services during testing, and this makes it easier to isolate issues.</li><li><strong>Automated Testing</strong>: The modular nature of microservices fits well with automated testing frameworks, which can be set up to test individual services or the entire application in an integrated environment.</li></ul><h4>11. Simplified Legacy Migration</h4><ul><li><strong>Gradual Transition</strong>: In a legacy monolithic system, it can be challenging to migrate to a microservices-based architecture all at once. Microservices allow for a gradual migration approach where parts of the monolith can be replaced incrementally by microservices. This minimizes risk and ensures continuous operation during the transition.</li><li><strong>Service Strangulation</strong>: You can adopt a “Strangler Fig” pattern, where you gradually replace parts of the legacy system with new microservices, instead of rewriting everything from scratch.</li></ul><h4>12. Better Handling of Complex Business Logic</h4><ul><li><strong>Domain-Driven Design (DDD)</strong>: Microservices align well with the principles of <strong>Domain-Driven Design</strong> (DDD), where each service corresponds to a specific domain or subdomain of the business. This enables the application to mirror the business processes more closely, making it easier to implement and understand complex business logic.</li><li><strong>Decentralized Data Management</strong>: Each microservice can have its own data storage mechanism, which allows it to optimize its data model for its specific needs. This reduces the need for complex shared databases and tight coupling.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*pZu5A8HUjuHy82L37heX8Q.png" /></figure><h3>Where are the 12-Factor and 15-Factor Methodologies used?</h3><p>The <strong>12-factor</strong> and <strong>15-factor</strong> methodologies are best suited for <strong>cloud-native</strong> applications, especially in the context of <strong>microservices architecture</strong>. They provide guidelines that help in building scalable, maintainable, and resilient systems. Here’s where and how you can apply these methodologies:</p><h4>1. Cloud-Native Applications</h4><ul><li><strong>Platform-Agnostic</strong>: These methodologies emphasize building applications that are platform-independent, meaning they can be deployed on any cloud platform (AWS, Azure, Google Cloud, etc.), or on-premises infrastructure. If your application is designed to run in the cloud, these methodologies ensure that it can leverage the advantages of cloud computing, such as scalability, high availability, and resource efficiency.</li><li><strong>Containerization</strong>: The methodologies are well-suited for containerized applications using Docker and Kubernetes, as they focus on creating stateless, decoupled services that are easy to containerize, scale, and deploy.</li><li><strong>Continuous Delivery</strong>: The principles align well with <strong>Continuous Integration/Continuous Deployment (CI/CD)</strong> practices, which are common in cloud-native applications. This allows teams to release features quickly and frequently, ensuring rapid time-to-market and continuous feedback.</li></ul><h4>2. Microservices Architectures</h4><ul><li><strong>Decentralized Systems</strong>: Microservices break down large monolithic applications into smaller, independently deployable services. The 12-factor and 15-factor principles guide the design of each service, ensuring that it can be scaled, deployed, and maintained independently. This makes microservices a natural fit for these methodologies.</li><li><strong>Service Discovery</strong>: The methodologies stress the importance of services being able to discover and communicate with each other. In a microservices architecture, service discovery is often implemented through tools like <strong>Eureka</strong>, <strong>Consul</strong>, or <strong>Kubernetes</strong>, which are consistent with the 12-factor principles (e.g., treating backing services as attached resources).</li></ul><h4>3. Distributed Systems</h4><ul><li><strong>Fault Tolerance and Resilience</strong>: The 15-factor methodology, in particular, emphasizes resilience patterns like <strong>circuit breakers</strong> and <strong>rate-limiting</strong>, which are crucial for distributed systems. These systems often need to handle failures gracefully without impacting the overall system. The 12-factor methodology’s principle of <strong>statelessness</strong> and <strong>disposability</strong> fits perfectly with building resilient distributed systems.</li><li><strong>Communication</strong>: Distributed systems rely heavily on communication between services (e.g., using <strong>REST APIs</strong>, <strong>gRPC</strong>, or message brokers like <strong>Kafka</strong>). The principles in the 12-factor methodology — such as <strong>port binding</strong> (using HTTP APIs and ports for communication) and <strong>environment configuration</strong> — ensure that your services are easily configurable and communicate effectively across various environments.</li></ul><h4>4. Microservices in Enterprise Applications</h4><ul><li><strong>Agility in Large Systems</strong>: Enterprise applications often evolve quickly and need to support a wide range of business domains. Microservices, when combined with the 12-factor and 15-factor principles, enable agility within enterprise systems by allowing each team to focus on different parts of the business logic. This modularity ensures that developers can maintain and update services without disrupting the entire system.</li><li><strong>Legacy System Modernization</strong>: These methodologies are especially useful when migrating legacy applications to microservices. You can incrementally adopt a microservices architecture by applying the 12-factor principles to new services while migrating legacy components step by step. This is commonly referred to as the <strong>“Strangler Fig” pattern</strong>, where monolithic components are gradually replaced by microservices without a full rewrite.</li></ul><h4>5. API-Driven Development</h4><ul><li><strong>API Gateway</strong>: In a microservices-based architecture, an <strong>API Gateway</strong> often acts as the entry point for clients (e.g., mobile apps, web apps). The 12-factor principles emphasize that services should expose their functionality through standard HTTP or REST APIs, making it easy to integrate with API gateways, service discovery mechanisms, and external consumers.</li><li><strong>Service Interaction</strong>: Microservices communicate with each other via APIs or messaging systems, which must be standardized. The <strong>“12-factor app”</strong> principle of <strong>“port binding”</strong> emphasizes that microservices expose their services over a specific port, and services should be accessible via simple, self-contained API calls.</li></ul><h4>6. Serverless Architectures</h4><ul><li><strong>Statelessness</strong>: Serverless computing, such as AWS Lambda or Azure Functions, is built around the idea of running stateless functions that can be scaled automatically. The <strong>statelessness</strong> and <strong>disposability</strong> principles in the 12-factor methodology align perfectly with serverless applications, where each function is ephemeral and runs independently.</li><li><strong>Environment Configuration</strong>: Serverless applications often rely heavily on environment variables for configuration, which ties into the <strong>“Config”</strong> factor of the 12-factor methodology. Serverless frameworks like AWS Lambda support externalized configuration, enabling you to manage environment-specific settings and secrets securely.</li></ul><h4>7. Continuous Integration and Continuous Delivery (CI/CD) Pipelines</h4><ul><li><strong>Automated Pipelines</strong>: The principles of separation between <strong>build</strong>, <strong>release</strong>, and <strong>run</strong> are key to implementing <strong>CI/CD</strong> pipelines. Microservices allow for automated deployment pipelines where services are independently tested, built, and deployed, resulting in fast feedback cycles and shorter release times.</li><li><strong>Versioning and Rollback</strong>: As each microservice is independent, its versioning and rollback can be managed separately, without affecting other services. This flexibility in deployment and version control allows for frequent updates and easier rollbacks if something goes wrong.</li></ul><h4>8. Data-Intensive Applications</h4><ul><li><strong>Decentralized Data Management</strong>: Microservices often use <strong>decentralized data models</strong>, where each service has its own database (or other persistent storage). The 12-factor principle of managing <strong>dependencies</strong> (including databases) independently helps each microservice maintain its own data storage, improving modularity and reducing the risk of data inconsistencies.</li><li><strong>Event-Driven Architectures</strong>: For systems requiring real-time data processing or high-throughput events, microservices can integrate with event-driven architectures (e.g., using <strong>Apache Kafka</strong>, <strong>RabbitMQ</strong>, or <strong>AWS SNS/SQS</strong>). The principles of <strong>port binding</strong> and <strong>externalized configuration</strong> ensure that these systems can be connected seamlessly while maintaining independence and flexibility.</li></ul><h4>9. Enterprise Integration and B2B Systems</h4><ul><li><strong>Integration with External Systems</strong>: When building systems that need to integrate with multiple external parties, such as <strong>B2B applications</strong>, microservices and the 12-factor methodology provide a robust framework for designing services that can easily interface with external APIs, databases, or message brokers.</li><li><strong>Event-Driven Architecture</strong>: In B2B systems, <strong>event-driven architectures</strong> are often used to capture and respond to changes or transactions. The <strong>12-factor principles</strong> help ensure that each service can subscribe to or publish events through a messaging system, ensuring reliable and scalable integrations.</li></ul><h4>10. Mobile and Web Applications</h4><ul><li><strong>API-First Development</strong>: For modern mobile and web applications, microservices provide a backend that can be accessed through RESTful APIs, GraphQL, or gRPC. The <strong>12-factor</strong> principles, particularly the <strong>statelessness</strong> and <strong>port binding</strong> rules, ensure that the backend can scale and respond to client requests efficiently, even when traffic spikes.</li><li><strong>Separation of Concerns</strong>: Microservices help isolate backend functionality into specific services (e.g., user management, content delivery, notifications), ensuring that mobile and web clients interact with clear and well-defined endpoints.</li></ul><h4>11. E-commerce Platforms</h4><ul><li><strong>Scalability</strong>: E-commerce platforms often experience sudden spikes in traffic (e.g., during sales events). Microservices allow parts of the application (e.g., inventory management, order processing, payment services) to scale independently based on demand.</li><li><strong>Resilience</strong>: Microservices’ resilience patterns (e.g., <strong>circuit breakers</strong>, <strong>bulkheads</strong>) ensure that if one service (e.g., payment gateway) fails, the rest of the system can continue to operate without service degradation.</li></ul><h3>Summary: Where to Use 12-Factor and 15-Factor Methodologies</h3><p>You can use the <strong>12-factor</strong> and <strong>15-factor methodologies</strong> in any project that requires:</p><ul><li><strong>Cloud-native</strong> design with a focus on scalability, resiliency, and maintainability.</li><li><strong>Microservices</strong> architecture, especially when you need flexibility, modularity, and independent deployment of services.</li><li><strong>Distributed systems</strong> or <strong>event-driven architectures</strong> where independent, stateless services need to communicate reliably.</li><li>Projects that leverage <strong>CI/CD</strong> pipelines, <strong>serverless architectures</strong>, or <strong>containers</strong> like Docker and Kubernetes.</li></ul><blockquote>I hope it will be useful for you.<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</blockquote><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk">https://github.com/incikucuk</a></blockquote><blockquote><strong>Delightful encodings!</strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f436a7a268d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/strengthen-your-microservice-projects-using-12-factor-15-factor-methodologies-8f436a7a268d">Strengthen Your Microservice Projects using 12-Factor &amp; 15-Factor Methodologies</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Microservice Projects with Profiles Using Spring Cloud Config Server]]></title>
            <link>https://blog.stackademic.com/manage-microservice-projects-with-profiles-using-spring-cloud-config-server-fc3da3527819?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3da3527819</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 06:30:18 GMT</pubDate>
            <atom:updated>2024-11-11T03:32:11.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>Manage Microservice Projects with Profiles Using Spring Cloud Config Server and Docker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cC-h_Tko-EOZ4vJFN3H3tQ.png" /></figure><p>In a <strong>Spring Boot</strong> microservices architecture, the use of <strong>profiles</strong> plays a crucial role in managing environment-specific configurations, promoting flexibility, and supporting deployment in various environments (e.g., development, testing, production).</p><p>In Spring Boot, profiles are a mechanism for defining beans and configuration settings that are specific to a given environment or context.</p><p>Let’s find out! :)</p><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk?tab=repositories"><em>https://github.com/incikucuk</em></a></blockquote><h3>What is a Profile in Spring Boot?</h3><p>A profile in Spring Boot is a way to segregate parts of your application configuration that should be active in different environments. It allows you to specify which configurations should be used based on the environment where the application is running, without having to modify the application’s code.</p><p>Spring Boot profiles are typically used to activate certain beans, properties, or configurations based on the active profile. This can be useful when dealing with different deployment scenarios, such as:</p><ul><li>Local development</li><li>Testing (unit tests, integration tests)</li><li>Staging</li><li>Production</li></ul><p>Profiles in Spring Boot are typically specified via the application.properties or application.yml files, but they can also be set programmatically.</p><h3>Importance of Profiles in a Microservice Architecture</h3><ol><li><strong>Environment-Specific Configurations:</strong> Microservices are often deployed across multiple environments (e.g., development, testing, production). Profiles help ensure that each service uses the correct configuration for its environment without needing code changes.</li><li><strong>Isolation of Environment-Specific Logic:</strong> Profiles allow you to isolate configuration that is specific to the environment. This avoids “hardcoding” sensitive information like database URLs, credentials, or API keys, which could otherwise vary across environments.</li><li><strong>Simplifies Deployment and Testing:</strong> Profiles make it easier to test microservices in different environments without having to modify the application. This is especially useful when you have integration or acceptance tests that run in separate environments like staging or CI/CD pipelines.</li><li><strong>Flexibility and Scalability:</strong> In a microservices architecture, different services might need different configurations based on their environment. For example, one service may require an in-memory database for testing, while another might require a real database in production. Profiles help achieve this kind of flexibility.</li><li><strong>Centralized Configuration Management:</strong> Profiles allow you to define environment-specific properties in one place (the application.properties files) and keep the configuration centralized, reducing the risk of configuration drift across multiple services.</li><li><strong>Secure Configuration:</strong> For sensitive information (e.g., credentials or API keys), profiles can help avoid accidental exposure. For instance, you can have different database credentials in the dev and prod profiles, ensuring that production credentials are not exposed in a development environment.</li><li><strong>Customization for Different Microservices:</strong> In microservices, each service may need to behave differently in various environments. Profiles allow each service to have a customized set of configurations for different stages in the pipeline, from development to production.</li></ol><h4>Example Use Case of Profiles in a Microservices Project</h4><p>Imagine a scenario where you have multiple Spring Boot microservices, such as user-service, order-service, and payment-service. Each of these services may have different configurations for connecting to their respective databases.</p><p>For example:</p><ul><li>user-service might use a PostgreSQL database in production and an H2 database in development.</li><li>order-service might use an Oracle database in production and a MySQL database in staging.</li></ul><p>By setting up profiles, each microservice can have its own configuration for connecting to these databases, ensuring that each service behaves correctly in its respective environment.</p><pre># application.properties (default)<br>spring.datasource.url=jdbc:mysql://localhost:3306/default_db<br><br># application-dev.properties<br>spring.datasource.url=jdbc:h2:mem:testdb<br><br># application-prod.properties<br>spring.datasource.url=jdbc:postgresql://prod-db:5432/prod_db</pre><h4><strong>How to Configure with Docker?</strong></h4><p>To configure a <strong>Spring Boot</strong> application with <strong>Docker</strong> using a application.yml file, you typically define different profiles for different environments (e.g., dev, prod, test). You can then use Docker to set the active profile at runtime by passing environment variables or using Docker Compose. This allows Spring Boot to pick up the correct configuration based on the environment in which the Docker container is running.</p><p>Here’s a step-by-step guide on how to configure and use the application.yml file in conjunction with Docker:</p><h4>1. Define Profiles in application.yml</h4><p>You can define multiple profiles within a single application.yml file. The spring.profiles.active property determines which profile is active, and you can override this at runtime using Docker environment variables.</p><p>Here’s an example application.yml file with multiple profiles:application.yml</p><pre>spring:<br>  profiles:<br>    active: @spring.profiles.active@<br><br>  datasource:<br>    url: jdbc:mysql://localhost:3306/mydb<br>    username: root<br>    password: rootpassword<br><br>---<br>spring:<br>  profiles: dev<br>  datasource:<br>    url: jdbc:h2:mem:testdb<br>    username: sa<br>    password: password<br><br>---<br>spring:<br>  profiles: prod<br>  datasource:<br>    url: jdbc:mysql://prod-db:3306/prod_db<br>    username: prod_user<br>    password: prod_pass</pre><ul><li>The main configuration (default) sets up a MySQL database connection.</li><li>The dev profile uses an H2 in-memory database.</li><li>The prod profile uses a MySQL database with a different URL and credentials.</li></ul><p>Note that we are using @spring.profiles.active@, which is a placeholder that will be replaced during the build or runtime.</p><h4>2. Configure Active Profile Using Docker</h4><p>You can pass the active profile as an environment variable to the Docker container. The active profile can then be read in the application.yml file.</p><h4><strong>Option 1: Set the Profile Using Docker Environment Variables</strong></h4><p>The preferred way to configure the active profile in Docker is to set the SPRING_PROFILES_ACTIVE environment variable when running the container.</p><ul><li><strong>Dockerfile</strong>: Ensure the Dockerfile is set up to run your Spring Boot application.</li></ul><pre># Use an OpenJDK base image<br>FROM openjdk:17-jdk-slim<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy the compiled Spring Boot JAR file into the container<br>COPY target/my-springboot-app.jar /app/my-springboot-app.jar<br><br># Set the default profile to &quot;dev&quot;<br>ENV SPRING_PROFILES_ACTIVE=dev<br><br># Expose the port your application will run on<br>EXPOSE 8080<br><br># Run the Spring Boot application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;my-springboot-app.jar&quot;]</pre><p>Here, we use the SPRING_PROFILES_ACTIVE environment variable to set the active profile. The value can be overridden when running the container.</p><ul><li><strong>Build the Docker Image</strong>:</li></ul><pre>docker build -t my-springboot-app .</pre><ul><li><strong>Run the Docker Container with a Specific Profile</strong>:</li></ul><p>To run the container with a specific profile, you can pass the SPRING_PROFILES_ACTIVE environment variable:</p><pre>docker run -e SPRING_PROFILES_ACTIVE=prod -p 8080:8080 my-springboot-app</pre><p>In this example:</p><ul><li>The profile prod will be active, so the prod datasource configuration will be used (i.e., connecting to the prod-db MySQL database).</li><li>The application will be accessible on port 8080 on the host machine.</li></ul><h4><strong>Option 2: Use Docker Compose</strong></h4><p>If you have multiple services and want to orchestrate them with <strong>Docker Compose</strong>, you can set the active profile for each service individually in the docker-compose.yml file.</p><p>Here’s an example docker-compose.yml configuration for multiple Spring Boot services with different profiles:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  user-service:<br>    image: my-springboot-app<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=dev<br>    ports:<br>      - &quot;8081:8080&quot;<br><br>  order-service:<br>    image: my-springboot-app<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=prod<br>    ports:<br>      - &quot;8082:8080&quot;</pre><p>In this example:</p><ul><li>user-service uses the dev profile (with an H2 in-memory database).</li><li>order-service uses the prod profile (with a MySQL database).</li><li><strong>Start the Docker Compose services</strong>:</li></ul><pre>docker-compose up</pre><p>This will start both services, each with the specified profile. :)</p><h3>3. Override Profiles Using Environment Variables</h3><p>As mentioned, the SPRING_PROFILES_ACTIVE environment variable can be passed to the Docker container at runtime, which will override the profile defined in the application.yml.</p><ul><li>For <strong>development</strong>:</li></ul><pre>docker run -e SPRING_PROFILES_ACTIVE=dev -p 8080:8080 my-springboot-app</pre><ul><li>For <strong>production</strong>:</li></ul><pre>docker run -e SPRING_PROFILES_ACTIVE=prod -p 8080:8080 my-springboot-app</pre><h3>4. Use docker-compose.yml for Multiple Environments</h3><p>If you want to manage multiple profiles in different environments (such as development, staging, and production), <strong>Docker Compose</strong> is a good way to set this up.</p><p>For instance, you could have a docker-compose.yml file like this:</p><h4>docker-compose.yml (for multiple environments)</h4><pre>version: &#39;3.8&#39;<br><br>services:<br>  my-springboot-app-dev:<br>    image: my-springboot-app<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=dev<br>    ports:<br>      - &quot;8080:8080&quot;<br><br>  my-springboot-app-prod:<br>    image: my-springboot-app<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=prod<br>    ports:<br>      - &quot;8081:8080&quot;</pre><p>In this example:</p><ul><li>my-springboot-app-dev uses the dev profile (running on port 8080).</li><li>my-springboot-app-prod uses the prod profile (running on port 8081).</li></ul><p>You can then start both services with Docker Compose:</p><pre>docker-compose up</pre><h3>5. In Summary,</h3><ul><li><strong>Profiles in Spring Boot</strong> allow you to define environment-specific configurations in your application.yml.</li><li><strong>Docker</strong> provides flexibility to pass environment variables like SPRING_PROFILES_ACTIVE at runtime, allowing you to dynamically switch between profiles (e.g., dev, prod).</li><li><strong>Docker Compose</strong> is useful for managing multiple microservices that may require different profiles for each service.</li><li>This approach ensures that the configuration remains flexible and easily adaptable to different environments (development, staging, production) without needing to modify the application code.</li></ul><p>By setting the SPRING_PROFILES_ACTIVE environment variable, Docker will load the corresponding configuration from application.yml, enabling the correct profile settings for your application.</p><blockquote><strong><em>I hope it will be useful for you.<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</em></strong></blockquote><blockquote><strong><em>LinkedIn:</em></strong><em> </em><a href="https://www.linkedin.com/in/inci-kucuk/"><em>https://www.linkedin.com/in/inci-kucuk</em></a></blockquote><blockquote><strong><em>GitHub:</em></strong><em> </em><a href="https://github.com/incikucuk"><em>https://github.com/incikucuk</em></a></blockquote><blockquote><strong><em>Delightful encodings!</em></strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3da3527819" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/manage-microservice-projects-with-profiles-using-spring-cloud-config-server-fc3da3527819">Manage Microservice Projects with Profiles Using Spring Cloud Config Server</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Move Your Monolithic Projects to Microservice Structures with the Strangler Design Pattern]]></title>
            <link>https://blog.stackademic.com/move-your-monolithic-projects-to-microservice-structures-with-the-strangle-design-pattern-c8a48a433607?source=rss-4bce8edd4a99------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8a48a433607</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[İnci KÜÇÜK]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 07:21:32 GMT</pubDate>
            <atom:updated>2024-11-20T16:24:21.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Ye_Mc2dVHQMR_hAMom812g.png" /></figure><p>The Strangler Fig pattern is a software design approach used to gradually replace an existing system with a new one. Named after the way strangler figs grow around existing trees, the pattern allows for a phased migration where new features are developed in the new system while the old system is still operational. Over time, as more features are built and the old system’s functionality is replaced, the old system can be completely phased out.</p><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk?tab=repositories">https://github.com/incikucuk</a></blockquote><h4><strong><em>The Strangler Fig pattern has several advantages and disadvantages. Here’s a breakdown:</em></strong></h4><h3>Advantages</h3><ol><li><strong>Reduced Risk</strong>: By migrating features incrementally, the risk of a complete system failure is minimized. If something goes wrong, only a small part of the application is affected.</li><li><strong>Continuous Delivery</strong>: New features can be developed and deployed in the new system without waiting for the entire migration to be completed. This promotes agility and responsiveness to user needs.</li><li><strong>Flexibility</strong>: The approach allows teams to adapt to changing requirements throughout the migration process. You can prioritize which features to migrate based on business needs.</li><li><strong>Preservation of Existing Functionality</strong>: The old system remains operational while the new system is being built, ensuring that users continue to have access to necessary features.</li><li><strong>Incremental Learning</strong>: Teams can learn from the new system as they build it, allowing them to refine their approach based on real-world feedback.</li><li><strong>Easier Testing</strong>: Smaller, incremental changes can be easier to test and validate compared to large, sweeping migrations.</li></ol><h3>Disadvantages</h3><ol><li><strong>Complexity</strong>: Managing two systems simultaneously can introduce complexity in architecture, deployment, and operations, requiring careful planning and coordination.</li><li><strong>Performance Overhead</strong>: If not designed properly, the interaction between the old and new systems can create performance bottlenecks, especially if data needs to be synchronized.</li><li><strong>Temporary Duplication of Efforts</strong>: Some functionality may need to be implemented in both systems temporarily, leading to duplicated work until the migration is complete.</li><li><strong>Integration Challenges</strong>: Ensuring seamless communication between the old and new systems can be challenging, particularly if they use different technologies or architectures.</li><li><strong>Cultural Resistance</strong>: Teams may face resistance to change, especially if the old system is well understood and relied upon. Stakeholders may be hesitant to adopt new technologies.</li><li><strong>Longer Migration Time</strong>: The incremental approach may extend the overall migration timeline compared to a big-bang approach, which could delay the benefits of modernization.</li></ol><h3>Key Steps in the Strangler Fig Pattern:</h3><ol><li><strong>Identify the System:</strong> Start with an existing application or system that needs to be replaced.</li><li><strong>Create a New System:</strong> Develop the new system alongside the existing one, ensuring it can handle the required functionality.</li><li><strong>Redirect Traffic:</strong> Gradually route requests from the old system to the new one, using techniques like feature flags or routing rules.</li><li><strong>Replace Functionality:</strong> Continuously add features to the new system, removing corresponding functionality from the old system.</li><li><strong>Decommission the Old System:</strong> Once all functionality has been migrated, the old system can be safely decommissioned.</li></ol><h3>Application in a Spring Boot Project:</h3><p>In a Spring Boot project, you can implement the Strangler Fig pattern as follows:</p><ol><li><strong>Microservices Architecture:</strong> If your old system is monolithic, you can start breaking it down into microservices using Spring Boot. Each microservice can be developed and deployed independently.</li><li><strong>API Gateway:</strong> Use an API gateway (like Spring Cloud Gateway) to manage requests. You can route traffic to the old and new services based on request paths or other criteria.</li><li><strong>Feature Toggles:</strong> Implement feature toggles to control which parts of the application are served by the old versus the new system. Spring provides libraries for managing feature flags.</li><li><strong>Data Migration:</strong> If your new system has a different data model, you can gradually migrate data from the old database to the new one, ensuring both systems can access necessary data during the transition.</li><li><strong>Monitoring and Testing:</strong> Continuously monitor the performance and functionality of both systems. Use Spring Boot’s testing features to ensure that the new system behaves as expected.</li></ol><blockquote><strong><em>Here’s a simple example of a Spring Boot project that demonstrates the Strangler Fig pattern.</em></strong></blockquote><blockquote><strong><em>This example will illustrate how to gradually migrate a simple CRUD (Create, Read, Update, Delete) application for managing “Products” from a legacy monolithic system to a new microservices-based architecture.</em></strong></blockquote><h3>Project Structure</h3><p>The project will consist of two main components:</p><ol><li><strong>Legacy Product Service (Monolithic)</strong>: This will be the existing service.</li><li><strong>New Product Microservice</strong>: This will be the new service where functionality is gradually migrated.</li></ol><h3>Step-by-Step Implementation</h3><h4>1. Legacy Product Service</h4><p><strong>Legacy Product Service (monolithic)</strong></p><pre>// LegacyProductController.java<br>@RestController<br>@RequestMapping(&quot;/api/legacy/products&quot;)<br>public class LegacyProductController {<br><br>    private List&lt;Product&gt; products = new ArrayList&lt;&gt;();<br><br>    @GetMapping<br>    public List&lt;Product&gt; getAllProducts() {<br>        return products;<br>    }<br><br>    @PostMapping<br>    public void addProduct(@RequestBody Product product) {<br>        products.add(product);<br>    }<br><br>    // Other CRUD methods...<br>}</pre><h4>Product Class</h4><pre>// Product.java<br>public class Product {<br>    private String id;<br>    private String name;<br>    private double price;<br><br>    // Getters and setters...<br>}</pre><h4>2. New Product Microservice</h4><p><strong>New Product Microservice</strong></p><pre>// NewProductController.java<br>@RestController<br>@RequestMapping(&quot;/api/new/products&quot;)<br>public class NewProductController {<br><br>    private List&lt;Product&gt; products = new ArrayList&lt;&gt;();<br><br>    @GetMapping<br>    public List&lt;Product&gt; getAllProducts() {<br>        return products;<br>    }<br><br>    @PostMapping<br>    public void addProduct(@RequestBody Product product) {<br>        products.add(product);<br>    }<br><br>    // Other CRUD methods...<br>}</pre><p><strong>Gateway Configuration</strong></p><p>To manage requests between the legacy and new systems, you can use Spring Cloud Gateway.</p><pre>// GatewayConfiguration.java<br>@Configuration<br>@EnableWebFlux<br>public class GatewayConfiguration {<br><br>    @Bean<br>    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {<br>        return builder.routes()<br>                .route(&quot;legacy-products&quot;, r -&gt; r.path(&quot;/api/legacy/products/**&quot;)<br>                        .uri(&quot;http://localhost:8081&quot;)) // Legacy service URI<br>                .route(&quot;new-products&quot;, r -&gt; r.path(&quot;/api/new/products/**&quot;)<br>                        .uri(&quot;http://localhost:8082&quot;)) // New service URI<br>                .build();<br>    }<br>}</pre><h3>Running the Application</h3><ol><li><strong>Legacy Product Service</strong>: Run this on port 8081.</li><li><strong>New Product Microservice</strong>: Run this on port 8082.</li><li><strong>API Gateway</strong>: Run this on port 8080.</li></ol><h4>Traffic Routing</h4><p>When you send requests to http://localhost:8080/api/legacy/products, they will be routed to the legacy service. As you build new features in the new product microservice, you can start redirecting traffic for specific endpoints to <a href="http://localhost:8080/api/new/products.">http://localhost:8080/api/new/products.</a></p><h4>Gradual Migration</h4><ol><li>Start by implementing new features only in the new microservice.</li><li>As functionality is added, update the API Gateway to redirect traffic from the legacy service to the new service.</li><li>Once all functionality is migrated, the legacy service can be decommissioned.</li></ol><p><em>This example provides a basic structure for applying the Strangler Fig pattern using Spring Boot. You can expand this by adding a database, authentication, and other features as needed. This approach allows for a controlled migration with minimal disruption to users.</em></p><blockquote><strong>I hope it will be useful for you.<br>Don’t forget to follow me, your support and feedback are very important for me, Thanks..</strong></blockquote><blockquote><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/inci-kucuk/">https://www.linkedin.com/in/inci-kucuk</a></blockquote><blockquote><strong>GitHub:</strong> <a href="https://github.com/incikucuk">https://github.com/incikucuk</a></blockquote><blockquote><strong>Delightful encodings!</strong></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8a48a433607" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/move-your-monolithic-projects-to-microservice-structures-with-the-strangle-design-pattern-c8a48a433607">Move Your Monolithic Projects to Microservice Structures with the Strangler Design Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>