<?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 Tech Proverb on Medium]]></title>
        <description><![CDATA[Stories by Tech Proverb on Medium]]></description>
        <link>https://medium.com/@techiecuriosity?source=rss-3dddaf5ed765------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JyBt1tjj-ERDENayV_Vy9A.jpeg</url>
            <title>Stories by Tech Proverb on Medium</title>
            <link>https://medium.com/@techiecuriosity?source=rss-3dddaf5ed765------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:57:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@techiecuriosity/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[Microservices design : Sidecar pattern explained]]></title>
            <link>https://levelup.gitconnected.com/microservices-design-sidecar-pattern-explained-e5e0bd3c0a23?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5e0bd3c0a23</guid>
            <category><![CDATA[isolation]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[sidecar-pattern]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[encapsulation]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 00:15:55 GMT</pubDate>
            <atom:updated>2024-11-04T00:15:55.738Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservices design : Sidecar pattern explained</h3><h4>The role of Sidecars in Microservices architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDQeJLBR4QOoKj2xlQM7Xw.png" /><figcaption>Sidecar pattern</figcaption></figure><h3>Context and Problem</h3><p>Modern applications often require components that provide common functionality across different services, such as:</p><ul><li>Monitoring and logging</li><li>Configuration management</li><li>Service discovery</li><li>Network communication</li><li>Security features</li></ul><p>Implementing these features <strong>directly into each application</strong> can lead to:</p><ul><li><strong>Code duplication</strong> : When every service tries to handle the same functionalities, you end up with a lot of repetitive code, which can lead to inconsistencies and bugs.</li><li><strong>Increased complexity</strong> : Each service managing its own set of features makes the entire architecture more complicated and harder to navigate.</li><li><strong>Reduced maintainability</strong> : With shared features spread across different services, keeping everything updated becomes a real headache and is prone to errors.</li><li><strong>Language/framework constraints</strong> : If your services are built on different technologies, it can be tough to implement a consistent solution across the board.</li><li><strong>Difficult updates and modifications</strong> : Making updates to shared functionalities often means changing multiple services, complicating deployments and increasing the risk of downtime.</li></ul><h3>Solution : The Sidecar pattern</h3><p>The Sidecar pattern addresses these challenges by:</p><ol><li>Deploying supporting components as separate services</li><li>Co-locating these services with the main application</li><li>Providing a consistent interface for cross-cutting concerns</li><li>Enabling independent updates and maintenance</li></ol><h4>Key Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*qskpCSmh48gEKkV6Bt_P_Q.png" /><figcaption>Main application &amp; Sidecar</figcaption></figure><ol><li><strong>Parent (Main) Application<br>- </strong>Contains core business logic<br>- Focuses on primary functionality<br>- Remains language/framework agnostic</li><li><strong>Sidecar<br></strong>A co-located helper that <br>- Handles cross-cutting concerns<br>- Provides supporting features<br>- Can be developed independently<br>- Shares lifecycle with parent application</li></ol><h3>Types of communication flows</h3><p>With the Sidecar pattern, that are 2 ways in which communication flows :</p><ul><li>Sidecar <strong>as Proxy</strong></li><li>Sidecar <strong>as Companion Service</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55Yb73eA2tLiy7mYylCZbw.png" /><figcaption>Sidecar pattern : Communication flows</figcaption></figure><h3><strong>Pattern 1</strong> : Sidecar <strong>as Proxy</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mLMHRmWrLfIQYaY6cDHCQ.png" /><figcaption>Sidecar as <strong>Proxy</strong></figcaption></figure><p>In this flow,</p><ul><li>External traffic <strong>first goes through the sidecar</strong></li><li>Sidecar handles cross-cutting concerns (<em>authentication, gateway functions, etc.</em>)</li><li>Validated/processed requests are then forwarded to the main application</li><li>Common use cases: <strong>API Gateway, Authentication, Rate Limiting</strong></li></ul><h3>Pattern 2: Sidecar as Companion Service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQQPxt-B8dUTyjMA-pEqvQ.png" /><figcaption>Sidecar as <strong>Companion service</strong></figcaption></figure><ul><li>External traffic <strong>goes directly to the main application</strong></li><li>Sidecar operates <strong>alongside</strong> the main application</li><li>Main app communicates with sidecar for supporting operations</li><li>Common use cases: <strong>Logging, Monitoring, Configuration</strong></li></ul><h3>Real-Life Example: Sidecar vs. Non-Sidecar Approach</h3><p>As an example, we can consider a real-world example of a payment processing service.</p><h4>Without Sidecar Pattern:</h4><pre>public class PaymentService {<br>    public void processPayment(Payment payment) {<br>        // Handle payment logic<br>        validatePayment(payment);<br>        // Log transaction<br>        logger.info(&quot;Processing payment: &quot; + payment.getId());<br>        // Encrypt sensitive data<br>        encryptData(payment);<br>        // Monitor metrics<br>        recordMetrics(payment);<br>        // Actual payment processing<br>        executePayment(payment);<br>    }<br>    <br>    private void validatePayment(Payment payment) { /* ... */ }<br>    private void encryptData(Payment payment) { /* ... */ }<br>    private void recordMetrics(Payment payment) { /* ... */ }<br>    private void executePayment(Payment payment) { /* ... */ }<br>}</pre><h4>With Sidecar Pattern:</h4><pre>// Main Application<br>public class PaymentService {<br>    public void processPayment(Payment payment) {<br>        // Focus only on core payment logic<br>        validatePayment(payment);<br>        executePayment(payment);<br>    }<br>    <br>    private void validatePayment(Payment payment) { /* ... */ }<br>    private void executePayment(Payment payment) { /* ... */ }<br>}<br><br>// Sidecar Component<br>public class PaymentSidecar {<br>    public void beforePaymentProcess(Payment payment) {<br>        // Handle cross-cutting concerns<br>        logTransaction(payment);<br>        encryptData(payment);<br>        recordMetrics(payment);<br>    }<br>    <br>    private void logTransaction(Payment payment) { /* ... */ }<br>    private void encryptData(Payment payment) { /* ... */ }<br>    private void recordMetrics(Payment payment) { /* ... */ }<br>}</pre><h3><strong>Best Practices for Sidecar Pattern</strong></h3><ul><li><strong>Keep It Simple : </strong>Implement sidecars only when they add clear value and maintain strict boundaries between components. Avoid feature creep and keep responsibilities well-defined between the main application and sidecars.</li><li><strong>Handle Failures Gracefully : </strong>Build resilience through proper error handling with circuit breakers and fallback mechanisms. This ensures the system can handle failures gracefully and maintain core functionality even when components fail.</li><li><strong>Security First : </strong>Prioritize security by encrypting communication channels, implementing strong authentication, and conducting regular security audits. Proper access controls and logging are essential for maintaining system integrity.</li></ul><h3>Challenges and Considerations</h3><ul><li><strong>Performance Impact:</strong> Sidecars introduce performance overhead through additional network communication and resource consumption. Each sidecar requires dedicated CPU and memory, increasing infrastructure costs. The <strong>extra network hops</strong> between main application and sidecars can impact response times, making efficient caching and capacity planning essential.</li><li><strong>Increased Complexity:</strong> Implementing sidecars significantly complicates system architecture as additional configurations in container orchestration platforms need to be managed. The operational overhead grows with more components to monitor.</li><li><strong>Deployment Challenges:</strong> Managing deployments becomes more challenging with sidecars due to version compatibility requirements and coordinated update needs.</li><li><strong>Testing Complexity:</strong> Testing distributed systems with sidecars requires a more comprehensive approach as we need to validate component interactions, simulate network failures, and test performance across the entire system.</li></ul><h3>Conclusion</h3><p>The Sidecar pattern is a powerful architectural solution for managing cross-cutting concerns in distributed systems. While it introduces some complexity, the benefits of isolation, maintainability, and flexibility often outweigh the challenges. Successful implementation requires careful consideration of use cases, proper design of communication interfaces, and attention to operational concerns.</p><p>Key takeaways:</p><ol><li>Use when cross-cutting concerns benefit from isolation</li><li>Consider performance and resource implications</li><li>Follow best practices for communication and deployment</li><li>Monitor and manage properly in production</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5e0bd3c0a23" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/microservices-design-sidecar-pattern-explained-e5e0bd3c0a23">Microservices design : Sidecar pattern explained</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explained : ‘Service mesh’ pattern for microservices]]></title>
            <link>https://blog.devops.dev/explained-service-mesh-pattern-for-microservices-0a4ee020b967?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4ee020b967</guid>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[service-discovery]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 07:44:06 GMT</pubDate>
            <atom:updated>2024-10-28T19:03:22.492Z</atom:updated>
            <content:encoded><![CDATA[<h3>Explained : ‘Service mesh’ design pattern for microservices</h3><h4>How does it really help? Is it an overkill?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cpFmRTzuPexzFbO1_S2cA.png" /><figcaption>Service mesh architecture</figcaption></figure><p>A service mesh is an infrastructure layer that sits between your microservices, handling service-to-service communication. It provides a consistent way to secure, connect, and monitor microservices, regardless of the underlying platform or programming language used.</p><h3>Key components of a service mesh</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vIrUMcb7ezOpV5jSiOq0A.png" /><figcaption>Control plane &amp; Data plane</figcaption></figure><p>1. <strong>Data Plane</strong>: A set of intelligent proxies (<em>sidecars</em>) deployed alongside each service instance. This is where actual traffic flows.</p><p>2. <strong>Control Plane</strong>: A centralized management layer that configures and coordinates the <em>data plane</em> proxies.</p><h3>Why Should You Care About Service Mesh?</h3><p>Because it has the following benefits:</p><p>1. <strong>Enhanced Observability</strong>: Gain deep insights into service behavior and performance.</p><p>2. <strong>Improved Security</strong>: Implement consistent security policies across your entire infrastructure.</p><p>3. <strong>Traffic Management</strong>: Easily control and optimize inter-service communication.</p><p>4. <strong>Platform Independence</strong>: Abstract away the complexities of different underlying platforms.</p><h3>Example 1 : E-commerce application</h3><p>If we use an e-commerce platform as example, we have microservices for <em>user management, inventory, ordering, </em>and<em> payment processing</em>.</p><h4><strong>Without a service mesh</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ifacF1ZADd94zW5RhCZ2w.png" /><figcaption>E-commerce app <strong>without</strong> Service Mesh</figcaption></figure><ul><li>Each service would need to implement its own <strong><em>security</em></strong><em>, </em><strong><em>load balancing</em></strong><em>, </em>and<em> </em><strong><em>observability features</em></strong><em>.</em></li><li>This can lead to inconsistencies and increased complexity.</li></ul><h4><strong>With a service mesh</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rJxWIUFcRArEZ3CKAWXnw.png" /><figcaption>E-commerce app <strong>with</strong> Service Mesh</figcaption></figure><ul><li>Your <em>inventory service</em> can communicate securely with the <em>ordering service</em> <strong>without either service needing to implement encryption or authentication.</strong></li><li>You can easily implement circuit breaking between the <em>ordering</em> and <em>payment</em> <em>services</em> to prevent cascading failures.</li><li>You gain detailed insights into communication patterns and performance metrics <strong>across all services</strong> without modifying any application code.</li></ul><h3>Example 2 : Ride-sharing application</h3><p>For a ride-sharing application which has <em>user service, driver-matching </em>and<em> route-calculation </em>microservices,</p><h4><strong>Without Service Mesh</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwmEjHH-DPpbMWd2CqecZA.png" /><figcaption>Ride sharing app <strong>without</strong> Service Mesh</figcaption></figure><ul><li>The <em>user service</em> implements <strong>its own authentication </strong>and<strong> encryption</strong> for communicating with the <em>driver-matching</em> service.</li><li>The <em>driver-matching</em> service implements <strong>custom load balancing</strong> to distribute requests to multiple instances of the <em>route-calculation</em> service.</li><li>Each service implements its own logging and monitoring solution.</li></ul><h4><strong>With Service Mesh</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sczUomc2Xul-SZ-HEWknxQ.png" /><figcaption>Ride sharing app <strong>with</strong> Service Mesh</figcaption></figure><ul><li><strong>Authentication</strong> and <strong>encryption</strong> between services are handled <strong>uniformly</strong> by the service mesh proxies.</li><li><strong>Load balancing is managed by the service mesh</strong>, which can make intelligent routing decisions based on real-time metrics.</li><li><strong>Centralized logging </strong>and<strong> monitoring</strong> are provided out-of-the-box by the service mesh, giving a consistent view of the entire system.</li></ul><h3>Challenges and Common Mistakes in Service Mesh Implementation</h3><ul><li><strong>Overcomplicating Simple Architectures</strong>: Introducing a service mesh where it’s not needed can add unnecessary complexity.</li><li><strong>Neglecting Performance Impact</strong>: Failing to account for the <em>additional latency</em> introduced by service mesh proxies.</li><li><strong>Inadequate Monitoring</strong>: Not leveraging the full observability capabilities provided by the service mesh.</li><li><strong>Inconsistent Policy Enforcement</strong>: Failing to implement uniform policies across all services.</li><li><strong>Ignoring Platform Limitations</strong>: Not considering the resource requirements and platform compatibility of the chosen service mesh solution.</li></ul><h3>Building a New Application: Should You Consider Service Mesh?</h3><p>If you’re starting a new application, consider these factors when deciding on service mesh adoption:</p><p>1. <strong>Anticipated Scale</strong>: If you expect rapid growth or a large number of services, implementing a service mesh early can be beneficial.</p><p>2. <strong>Team Expertise</strong>: Ensure your team has the skills to manage and maintain a service mesh infrastructure.</p><p>3. <strong>Future Requirements</strong>: If you foresee needs for advanced traffic management or security features, a service mesh can provide a solid foundation.</p><p>A practical solution is to start without a service mesh and introduce it later as your application grows and evolves.</p><h3>Conclusion</h3><p>Service mesh architecture is a powerful but complex solution for managing microservice communications.</p><p>Though it offers significant benefits like <strong>centralized management</strong> of cross-cutting concerns, <strong>standardized service-to-service communication</strong>, and <strong>improved observability</strong>, it also introduces additional complexity and overhead. The <em>proxy-per-service</em> pattern can increase resource consumption and latency, making it important to carefully evaluate whether the benefits justify the operational costs.</p><p>Service mesh is particularly valuable for large-scale distributed systems where consistent handling of security, traffic management, and observability outweighs the added complexity. However, for smaller applications with few services, implementing a service mesh might be overkill and simpler solutions could be more appropriate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4ee020b967" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/explained-service-mesh-pattern-for-microservices-0a4ee020b967">Explained : ‘Service mesh’ pattern for microservices</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding I/O bound vs CPU bound operations]]></title>
            <link>https://levelup.gitconnected.com/understanding-i-o-bound-vs-cpu-bound-operations-d06ed2c301a0?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/d06ed2c301a0</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[input-output]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[cpu]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 17:44:44 GMT</pubDate>
            <atom:updated>2024-10-15T17:44:44.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring this distinction in a CRUD application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tr_9lhhvY2Kpga-1V5jNCg.png" /></figure><p>In software development, it’s vital to know the difference between I/O bound and CPU bound operations.</p><p><strong>‘I/O bound’</strong> means an operation’s performance is primarily limited by <strong><em>input/output operations</em></strong>. When we say an operation or program is <strong>‘CPU bound’</strong>, it means that its performance is primarily limited by the <strong><em>CPU’s processing power</em></strong> rather than other factors.</p><p>This knowledge can be key to debugging performance issues in applications, hence it is a crucial skill for building performant apps.</p><h3>Understanding the Basics</h3><p>A good analogy to understand the difference is to think of your application as a chef in a kitchen. Sometimes, the chef is cooking (<em>CPU operation</em>). Other times, they’re waiting for ingredients from the storage room (<em>I/O operations</em>).</p><h4>I/O Bound Operations</h4><p>I/O bound operations are like waiting for ingredients in our kitchen analogy. These operations wait most of the time for I/O to finish.</p><p>Common I/O Bound Operations:<br><em>- Reading from or writing to a database<br>- Network requests<br>- File system operations<br>- User input</em></p><p>Simple Java example of an I/O bound operation:</p><pre>public class FileReadExample {<br><br> public static String readLargeFile(String filePath) {<br><br>   StringBuilder content = new StringBuilder();<br><br>   try (<br>     // I/O Operation: Opening the file for reading<br>     FileReader fileReader = new FileReader(filePath);<br>     <br>     // I/O Operation: Creating a buffered reader for efficient reading<br>     BufferedReader reader = new BufferedReader(fileReader)<br>   ) {<br><br>     String line;<br><br>     // I/O Operation: Reading the file line by line<br>     while ((line = reader.readLine()) != null) {<br>       content.append(line).append(&quot;\n&quot;);<br>     }<br><br>   } catch (IOException e) {<br>     // This block handles I/O exceptions that may occur during file operations<br>     e.printStackTrace();<br>   }<br>   // Note: File is automatically closed here due to try-with-resources<br>   // which is also an I/O operation (closing the file)<br><br>   return content.toString();<br>  }<br>}</pre><h4>CPU Bound Operations</h4><p>CPU bound operations are like the actual cooking in our kitchen analogy. These operations spend most of their time processing data in the CPU.</p><p>Common CPU Bound Operations:<br><em> — Complex mathematical calculations<br> — Image processing<br> — Encryption/decryption<br> — Sorting large datasets in memory</em></p><pre>public class CPUBoundExample {<br><br> public static long calculateFactorial(int n) {<br><br>    // CPU Operation: Conditional check<br>    if (n == 0 || n == 1) <br>      return 1;<br><br>    // CPU Operation: Variable initialization<br>    long result = 1;<br><br>    // CPU Operation: Loop initialization and condition check<br>    for (int i = 2; i &lt;= n; i++) {<br>      // CPU Operations:<br>      // 1. Multiplication<br>      // 2. Assignment<br>      // 3. Loop variable increment<br>      result *= i;<br>    }<br><br>    // CPU Operation: Returning the calculated value<br>    return result;<br>   }<br>}</pre><h3>CRUD Applications: I/O vs CPU Bound</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad59yYSueel7rF7vYXK6Rg.png" /><figcaption>I/O vs CPU in a CRUD application</figcaption></figure><p>In a typical CRUD (Create, Read, Update, Delete) application, most operations are I/O bound due to database interactions. Nevertheless, it’s essential to identify when operations might be CPU bound for performance optimization purposes.</p><h4>Identifying Operation Types in CRUD Applications</h4><p>To determine if an operation is I/O bound or CPU bound in a CRUD application, we can consider these factors:</p><p><strong>Database Interaction Time:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ei_l8u1hbpnxA_JAUPBCEg.png" /></figure><p><strong>Data Processing Time:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WpsyGu2nmtmHV45gxNpVQ.png" /></figure><p>These metrics will show if <em>database I/O</em> or <em>application processing</em> is the bottleneck. I/O bound operations will show <strong>higher database interaction times</strong>, while CPU bound operations will have <strong>longer processing times</strong>.</p><h3>Practical Examples</h3><p>Let’s look at practical examples in a typical CRUD application:</p><h4>I/O Bound Examples:</h4><ol><li>User profile retrieval</li></ol><pre>public UserProfile getUserProfile(Long userId) {<br> return userRepository.findById(userId) // I/O bound: Database read<br> .orElseThrow(() -&gt; new UserNotFoundException(userId));<br>}</pre><p>2. Batch Update</p><pre>public void updateUserStatuses(List&lt;UserStatus&gt; statuses) {<br>  userRepository.saveAll(statuses); // I/O bound: Multiple database writes<br>}</pre><h4>CPU Bound Examples:</h4><p>1. Report Generation</p><pre>public SalesReport generateMonthlyReport(List&lt;Transaction&gt; transactions) {<br> return transactions.parallelStream()<br> .collect(groupingBy(Transaction::getCategory,<br> summarizingDouble(Transaction::getAmount))); // CPU bound: Data processing<br>}</pre><h4>Other Types of Bounds</h4><p>While I/O bound and CPU bound are the most common, there are other types of bounds:</p><ol><li><strong>Memory Bound</strong>: Operations limited by memory capacity or speed</li><li><strong>Cache Bound</strong>: Performance limited by cache capacity or speed</li><li><strong>Network Bound</strong>: A specific type of I/O bound, limited by network capacity</li></ol><h3>Best Practices and Optimization Techniques</h3><h4>For I/O Bound Operations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qD_mK0CUhqrrFXl4K2mfaA.png" /><figcaption>I/O optimization techniques</figcaption></figure><p><strong>For CPU Bound Operations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnd3JqFUQm-wD4mLoATiUg.png" /><figcaption>CPU optimization techniques</figcaption></figure><h3>Conclusion</h3><p>Knowing the difference between I/O bound and CPU bound operations can be key for developing efficient apps.</p><p>Most CRUD applications are I/O bound, but awareness of CPU bound operations can help you make better architectural decisions and optimize your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d06ed2c301a0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-i-o-bound-vs-cpu-bound-operations-d06ed2c301a0">Understanding I/O bound vs CPU bound operations</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices design: Command Query Responsibility Segregation (CQRS) pattern]]></title>
            <link>https://levelup.gitconnected.com/microservices-design-command-query-responsibility-segregation-cqrs-pattern-ffab236fd935?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffab236fd935</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 17:48:40 GMT</pubDate>
            <atom:updated>2024-10-01T17:48:40.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing CQRS vs. Traditional CRUD Data Access Patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMFK8YcyeJQ4Lqjie3Q0kQ.png" /><figcaption>Image credit : <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs">https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs</a></figcaption></figure><p>CQRS, or <em>Command Query Responsibility Segregation </em>pattern advocates a clean separation between two core functions in software systems viz.</p><ul><li>handling write operations (<strong><em>commands</em></strong>)</li><li>processing read operations (<strong><em>queries</em></strong>)</li></ul><p>In essence, this pattern separates <strong><em>data mutation</em></strong> and <strong><em>data retrieval</em></strong> operations in your apps. This helps to design applications that are both scalable and maintainable, especially when dealing with complex requirements.</p><h3>Key Components of a CQRS-enabled system</h3><p>There are 4 important components in a CQRS system, as listed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHhp5iytsbI7Po0uM5gQ5g.png" /></figure><h3>Comparing Data Access Patterns: CRUD vs CQRS</h3><p>The best way to explain the CQRS pattern is to compare it to the familiar CRUD-based pattern.</p><p>Let’s use a simple online bookstore as our example, where we have operations to <strong>save</strong>, <strong>fetch,</strong> and <strong>delete</strong> books.</p><h4>Traditional CRUD application</h4><p>In a CRUD application, we usually have one service and one database for both reading and writing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umITDDA6N6Ju7oqE_2bXww.png" /><figcaption>Traditional CRUD design</figcaption></figure><pre>public class Book {<br>    private String id;<br>    private String title;<br>    private double price;<br>    // Constructor, getters, setters omitted<br>}<br><br>public interface BookRepository {<br>    void save(Book book);<br>    Book findById(String id);<br>    List&lt;Book&gt; findAll();<br>    void delete(String id);<br>}<br><br>public class BookService {<br>    private final BookRepository repository;<br><br>    public BookService(BookRepository repository) {<br>        this.repository = repository;<br>    }<br><br>    public void createBook(Book book) { repository.save(book); }<br><br>    public Book getBook(String id) { return repository.findById(id); }<br><br>    public List&lt;Book&gt; getAllBooks() { return repository.findAll(); }<br><br>    public void updateBook(Book book) { repository.save(book); }<br><br>    public void deleteBook(String id) { repository.delete(id); }<br>}</pre><h4>CQRS-based application</h4><p>In CQRS, we separate the <strong>command</strong> <strong><em>(write)</em></strong> and <strong>query</strong> <strong><em>(read)</em></strong> tasks. So, we have <strong>separate</strong> models for commands and queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fuBMlcsPuDHuquEYPt11A.png" /><figcaption>CQRS-based design</figcaption></figure><p>The code example below shows two things : <br>- The BookCommandServicecreates books. <br>- The BookQueryService reads book info.</p><pre>// Command model<br>public class CreateBookCommand {<br>    private String title;<br>    private String author;<br>    private double price;<br>    // Constructor, getters<br>}<br><br>public class BookCommandService {<br>    public void createBook(CreateBookCommand command) {<br>        // Create book in write database<br>    }<br><br>    public void deleteBook(CreateBookCommand command) {<br>        // Delete book in write database<br>    }<br>}<br><br>-----------------------------------------------------------------------------<br><br>// Query model<br>public class BookDetailsDTO {<br>    private String id;<br>    private String title;<br>    private String author;<br>    private double price;<br>    // Constructor, getters<br>}<br><br>public class BookQueryService {<br>    public BookDetailsDTO getBook(String id) {<br>        // Fetch book from read database<br>    }<br>}</pre><h3>Question: In CQRS, how can we ensure that data in the write and read databases are in sync?</h3><p>Pertinent question. In CQRS, the <strong>Write DB</strong> and <strong>Read DB</strong> are separate. The challenge is to keep them in sync. This syncing is achieved through <a href="https://medium.com/devops-dev/event-driven-messaging-the-key-to-scalable-resilient-microservices-619226236844"><strong>event-driven architecture</strong></a>:</p><ol><li>When a command is processed, it generates an event <em>(for example, “BookCreatedEvent”). </em>This event is published either by the <strong>command model</strong> or by the <strong>Write DB</strong>.</li><li>This event is published to a message queue or event stream (<em>for example, Kafka</em>).</li><li>A sync mechanism (often called an <em>event handler</em>) subscribes to these events.</li><li>When an event is received, the sync mechanism updates the <strong>Read DB</strong> accordingly. This event is typically consumed and processed by the <strong>query model</strong>.</li></ol><pre>// Command model<br>public class BookCommandService {<br>    private final ApplicationEventPublisher eventPublisher;<br><br>    public BookCommandService(ApplicationEventPublisher eventPublisher) {<br>        this.eventPublisher = eventPublisher;<br>    }<br><br>    public void createBook(CreateBookCommand command) {<br>        // Logic to create the book in the write database<br>        String bookId = writeDatabase.saveBook(command);<br><br>        // Create and publish the event<br>        BookCreatedEvent event = new BookCreatedEvent(<br>            bookId,<br>            command.getTitle(),<br>            command.getAuthor(),<br>            command.getPrice()<br>        );<br>        eventPublisher.publishEvent(event);<br>    }<br>}<br><br>-----------------------------------------------------------------------------<br><br>// Query model<br>public class BookCreatedEvent {<br>    private String id;<br>    private String title;<br>    private String author;<br>    private double price;<br>    // Constructor, getters<br>}<br><br>public class ReadDbSyncHandler {<br>    @EventListener<br>    public void handleBookCreatedEvent(BookCreatedEvent event) {<br>        BookDetailsDTO bookDetails = new BookDetailsDTO(<br>            event.getId(), event.getTitle(), event.getAuthor(), event.getPrice()<br>        );<br>        readDbRepository.save(bookDetails);<br>    }<br>}</pre><h3>Question: Should the command and query models be in different microservices? Or can they be in the same microservice?</h3><p>Whether to place <strong>Command</strong> and <strong>Query</strong> models in separate microservices depends on the specific use case:</p><ol><li><strong>Same Microservice</strong>: For small apps or tightly-coupled domains, it may be best to keep both models in the same microservice. This simplifies deployment and reduces network overhead.</li><li><strong>Separate Microservices</strong>: For large apps, or to scale reads and writes independently, it helps to separate into distinct microservices. This allows for independent scaling and deployment of read and write services.</li></ol><p>Base the decision on the requirements, scale, and complexity of the application. A good strategy would be to start with a single microservice and split it later, if needed, when the application grows.</p><h3>So What are the benefits gained by moving to CQRS?</h3><h4>Improved Performance</h4><blockquote><strong>Example</strong>: In an e-commerce app, <strong>read-heavy</strong> product searches can be optimized separately. Use caching and indexing on the <strong>read side</strong> to speed up product info retrieval. This won’t affect the <strong>write-heavy</strong> order processing.</blockquote><h4>Enhanced Scalability</h4><blockquote><strong>Example</strong>: During a flash sale, we can scale up the <strong>read side</strong> with more <strong>read replicas</strong> to handle the increased traffic from customers browsing products. The <strong>write side</strong> can stay on a smaller instance to process orders.</blockquote><h4>Simplified Complex Models</h4><blockquote><strong>Example: </strong>In a banking app, the <strong>command model</strong> handles complex tasks, like fund transfers with checks and rules. The <strong>query model</strong> retrieves account balances or transaction history.</blockquote><h4>Better Security</h4><blockquote><strong>Example: </strong>In a healthcare app, <strong>sensitive patient data</strong> must be protected. Only <strong>authorized personnel</strong> should be allowed to <strong>write</strong> (for example, update medical records). Others should only have <strong>read access</strong> to view this data.</blockquote><h4>Flexibility in Data Storage</h4><blockquote><strong>Example</strong>: A social media platform might use a <strong>NoSQL database</strong> for the <strong>read side</strong> to quickly retrieve user feeds. It could use a <strong>relational database</strong> for the <strong>write side </strong>to manage structured user profiles and relationships.</blockquote><h4>Improved Maintainability</h4><blockquote><strong>Example</strong>: In an online learning platform, if the requirements for reporting student progress change, developers can modify the <strong>query model</strong>. This won’t impact how students submit assignments or how grades are processed. The <strong>write model</strong> is unchanged.</blockquote><h3>Are there any drawbacks to the CQRS approach?</h3><p>As with any pattern, there are drawbacks to the CQRS pattern as well. The primary drawbacks are as follows:</p><h4>Eventual consistency</h4><p>The write and read databases are separate and synced asynchronously. So, they might be out of sync for a time. This eventual consistency model can be challenging to work with, especially in systems where immediate consistency is expected.</p><p>The following sequence diagram shows a <strong>delay</strong> in consuming the <strong>BookCreatedEvent</strong>. It causes a “<em>Book not found</em>” error, as the <strong>read database</strong> was temporarily <em>out of sync</em> with the <strong>write database.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6XE08HAfoTGsIxvmeYXFA.png" /><figcaption>Eventual consistency drawback</figcaption></figure><h4>Increased complexity</h4><p>CQRS introduces more complexity to the system architecture. We must now manage separate models, databases, and sync processes. This can make the system harder to understand and maintain.</p><h4>Potential for data inconsistencies</h4><p>If not implemented carefully, there’s a risk of <strong>data inconsistency</strong> between the <strong>write</strong> and <strong>read</strong> databases. This can happen due to <em>failed events, network issues, </em>or <em>bugs</em> in the synchronization process.</p><p>Other drawbacks are the <em>learning curve, overhead</em> for simple apps and <em>testing</em> <em>complexity</em>.</p><h3>Summary</h3><p>CQRS is an architectural pattern that splits an app’s data model into two parts: one for writing and one for reading. This separation allows to optimize each side independently, potentially boosting performance and scalability.</p><p>CQRS has great benefits. But, weigh them against the added complexity and risks in your context. By carefully considering your application’s requirements and constraints, you should determine whether CQRS is the right fit for your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffab236fd935" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/microservices-design-command-query-responsibility-segregation-cqrs-pattern-ffab236fd935">Microservices design: Command Query Responsibility Segregation (CQRS) pattern</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explained : ‘Event Sourcing’ design pattern for Microservices]]></title>
            <link>https://blog.devops.dev/explained-event-sourcing-design-pattern-for-microservices-43f3d625443a?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f3d625443a</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 07:53:03 GMT</pubDate>
            <atom:updated>2024-09-14T06:24:33.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Explained : ‘Event Sourcing’ design pattern for Microservices</h3><h4>A fundamental shift in how we think about storing data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzfKr9ZL-BLaRmiaIUBakw.png" /><figcaption>Image credit : <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing">https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing</a></figcaption></figure><h3>What is Event Sourcing really?</h3><p>Event Sourcing is a design pattern that fundamentally changes how we think about and store data. It offers a unique approach to data management and state tracking. Essentially,</p><blockquote>Instead of storing <strong>only the current state</strong> of an entity, Event Sourcing stores <strong>every<em> </em>change</strong> <em>to an entity’s state </em><strong>as a sequence of events</strong>.</blockquote><p>These events are stored in the order they occurred, creating an immutable log that serves as the single source of truth for the system.</p><p><strong>EventStoreDB</strong>, <strong>Apache Kafka</strong> and even <strong>PostgreSQL</strong> are some of the popular databases used as event stores in such event-sourced systems.</p><h4>Example 1 : Bank account balance</h4><p>Imagine your bank account as an example. <br>- In a traditional system, you’d only see your <strong>current balance</strong>. <br>- With Event Sourcing, you’d have a record of <strong><em>every deposit, withdrawal, </em></strong><em>and</em><strong><em> transfer</em></strong> that led to that balance.</p><h4>Example 2: Customer data management</h4><p>In traditional data management systems, including most applications using CRUD (Create, Read, Update, Delete) operations, the focus is on maintaining the current state of entities. Let’s break this down:</p><h4>- Current state focus</h4><p>In a traditional system, when you look at a database record, you see only the latest version of that data. For example, if you look at a customer s’ data, you might see:</p><pre>User ID: 12345<br>Name: John Smith<br>Email: john.smith@example.com<br>Address: 123 Main St, Anytown, USA</pre><p>This represents the user’s information as it stands right now.</p><h4>- Updates o<strong>verwrite</strong> previous data</h4><p>When you make a change in a traditional system, you typically overwrite the existing data. If John Smith moves to a new address, you’d update the record:</p><pre>UPDATE users SET address = &#39;456 Elm St, Newtown, USA&#39; WHERE user_id = 12345;</pre><p>After this update, <strong>the old address is lost</strong>. The database only keeps the new, current address. You can’t easily answer questions like</p><ul><li><strong><em>“What was John’s address last year?”</em></strong></li><li><strong><em>“How many times has John changed his email?”</em></strong></li><li><strong><em>“How did we reach the state that the data is in presently?”</em></strong></li></ul><h4>Now, let’s contrast this with <strong>Event Sourcing:</strong></h4><h4>- Event-Based Record</h4><p>Instead of storing just the current state, Event Sourcing keeps a record of <strong><em>all events</em></strong> that led to that state. For John Smith, you might have a series of events:</p><pre>UserCreated(id: 12345, name: &quot;John Smith&quot;, email: &quot;john@example.com&quot;, address: &quot;123 Main St, Anytown, USA&quot;)<br>EmailChanged(userId: 12345, newEmail: &quot;john.smith@example.com&quot;)<br>AddressChanged(userId: 12345, newAddress: &quot;456 Elm St, Newtown, USA&quot;)</pre><h4>- State is Derived</h4><p>The current state isn’t stored directly but is <strong>derived</strong> by applying all events in sequence. To get John’s current address, you’d process all events related to his user ID, arriving at the final state.</p><p>With Event Sourcing, you maintain a complete, immutable history of all changes, hence you can easily reconstruct past states or analyze the sequence of changes over time.</p><p>You could ask temporal queries such as <strong><em>“What was John’s address on January 1st last year?”</em> </strong>by replaying events up to that date.</p><h3>Question: Event Sourcing looks similar to using Audit Tables in traditional DB. Why can’t I simply add an audit table (that maintains a history of all changes) instead of using Event Sourcing pattern?</h3><p>Valid question. While adding an audit table to a traditional database might seem like a simpler alternative to Event Sourcing, there are key differences:</p><p>1. <strong>Granularity</strong>: Audit tables typically record high-level changes, while Event Sourcing captures every state mutation.</p><p>2. <strong>Source of Truth</strong>: In Event Sourcing, <strong>events</strong> are the primary source of truth. With audit tables, they’re secondary to the main data store.</p><p>3. <strong>Reconstruction</strong>: Event Sourcing allows easy reconstruction of past states. Audit tables typically don’t provide this capability out-of-the-box.</p><p>4. <strong>Design Impact</strong>: Event Sourcing often leads to a more <strong>event-driven</strong> design, while audit tables are usually an add-on to existing structures.</p><p>5. <strong>Performance</strong>: Event Sourcing can optimize certain operations <em>(like concurrent writes, handling heavy write volume)</em> but may require more work for reads. Audit tables generally have less impact on existing operations.</p><p>So while audit tables can improve traceability, they don’t provide the full benefits of an event-sourced system.</p><h3>Traditional CRUD vs. Event Sourcing: Code Comparison</h3><p>Let’s compare these approaches using a real-life example: an e-commerce order management system.</p><h4>Traditional CRUD Approach</h4><p>In a CRUD-based system, you might have an Order table with columns like id, status, total_amount, and last_updated_at. When an order&#39;s status changes, you simply update the status column:</p><pre>public void updateOrderStatus(Long orderId, String newStatus) {<br>    Order order = orderRepository.findById(orderId);<br>    order.setStatus(newStatus);<br>    order.setLastUpdatedAt(LocalDateTime.now());<br>    orderRepository.save(order);<br>}</pre><p>This approach is straightforward but loses the history of status changes.</p><h4>Event Sourcing Approach</h4><p>With Event Sourcing, you’d have an OrderEvents table that records every event related to an order:</p><pre>public void changeOrderStatus(Long orderId, String newStatus) {<br>    OrderStatusChangedEvent event = new OrderStatusChangedEvent(orderId, newStatus, LocalDateTime.now());<br>    eventStore.append(event);<br>    <br>    // Optionally update a read model for quick status lookups<br>    updateOrderReadModel(orderId, newStatus);<br>}</pre><p>To get the current state of an order, you’d replay all events:</p><pre>public Order getOrder(Long orderId) {<br>    List&lt;Event&gt; events = eventStore.getEventsForOrder(orderId);<br>    Order order = new Order(orderId);<br>    for (Event event : events) {<br>        order.apply(event);<br>    }<br>    return order;<br>}<br><br>public class Order {<br>    private final Long orderId;<br>    private String status;<br>    private final Map&lt;String, OrderItem&gt; items;<br>    private BigDecimal totalAmount;<br><br>    public Order(Long orderId) {<br>        this.orderId = orderId;<br>        this.status = &quot;CREATED&quot;;<br>        this.items = new HashMap&lt;&gt;();<br>        this.totalAmount = BigDecimal.ZERO;<br>    }<br><br>    public void apply(Event event) {<br>        switch (event.getType()) {<br>            case &quot;ORDER_CREATED&quot;:<br>                applyOrderCreated(event); // Apply Order creation logic<br>                break;<br>            case &quot;ITEM_ADDED&quot;:<br>                applyItemAdded(event); // Apply Order addition logic<br>                break;<br>            case &quot;ITEM_REMOVED&quot;:<br>                applyItemRemoved(event); // Apply Order removal logic<br>                break;<br>            case &quot;ORDER_CONFIRMED&quot;:<br>                applyOrderConfirmed(event); // Apply Order confirmation logic<br>                break;<br>            case &quot;ORDER_CANCELLED&quot;:<br>                applyOrderCancelled(event); // Apply Order cancellation logic<br>                break;<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown event type: &quot; + event.getType());<br>        }<br>    }<br><br>   private void applyItemAdded(Event event) {<br>        String itemId = (String) event.getData().get(&quot;itemId&quot;);<br>        String itemName = (String) event.getData().get(&quot;itemName&quot;);<br>        int quantity = (Integer) event.getData().get(&quot;quantity&quot;);<br>        BigDecimal price = new BigDecimal(event.getData().get(&quot;price&quot;).toString());<br><br>        OrderItem existingItem = items.get(itemId);<br>        if (existingItem != null) {<br>            existingItem.addQuantity(quantity);<br>        } else {<br>            items.put(itemId, new OrderItem(itemId, itemName, quantity, price));<br>        }  <br><br>        // add amount to total amount<br>        totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(quantity)));<br>    }<br><br>   private void applyItemRemoved(Event event) {<br>        // code omitted for brevity       <br><br>        // deduct amount from total amount<br>        totalAmount = totalAmount.subtract(item.getPrice().multiply(BigDecimal.valueOf(quantity)))<br>    }<br><br>    // code omitted for brevity<br>}</pre><p>This approach preserves the entire history of the order, allowing you to reconstruct its state at any point in time.</p><h3>When to Use Event Sourcing</h3><p>Consider using event sourcing when the following scenarios are applicable to your application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzHWRyffmRgqo-5DJ8Zjtw.png" /></figure><h3>When to Avoid Event Sourcing</h3><p>Avoid using event sourcing when the following scenarios are applicable to your application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrD0rgRf_Ga7hAG1MCe79A.png" /></figure><h3><strong>Optimizing Read Latency in Event Sourcing</strong></h3><p>Since we replay all events to figure out the present state, there could be significant read latency compared to the traditional CRUD approach. To achieve good read performance with Event Sourcing, we need to consider the following recommendations:</p><p>1. <strong>Implement CQRS</strong>: Maintain separate read models optimized for your query patterns.<br>2. <strong>Use Snapshots</strong>: Periodically save the current state to avoid replaying all events for every read.<br>3. <strong>Caching</strong>: Implement caching strategies for frequently accessed data.<br>4. <strong>Denormalization</strong>: In read models, denormalize data to reduce the need for joins.<br>5. <strong>Asynchronous Projections</strong>: Update read models asynchronously to avoid impacting write performance.</p><h3>Conclusion</h3><p><strong>Event Sourcing</strong> can bring significant benefits to microservices architectures, particularly in domains with complex business logic, high auditability requirements, or the need for temporal queries.</p><p>However, it’s not a one-size-fits-all solution and requires careful consideration of your specific use case, team expertise, and system requirements.</p><p>Whether you’re starting a new project or considering a migration, Event Sourcing can be a valuable tool in achieving these goals when applied judiciously and implemented with care.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f3d625443a" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/explained-event-sourcing-design-pattern-for-microservices-43f3d625443a">Explained : ‘Event Sourcing’ design pattern for Microservices</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices design : Using SAGA pattern for distributed transactions]]></title>
            <link>https://blog.devops.dev/microservices-design-using-saga-pattern-for-distributed-transactions-84a01fc27abe?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a01fc27abe</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[microservices-design]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 23:56:31 GMT</pubDate>
            <atom:updated>2024-09-17T07:16:25.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservices design : Using SAGA pattern for distributed transactions</h3><h4>And understanding the distinction between the 2 Saga approaches</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e7M85b24nyHgMBjnPVisw.png" /><figcaption>Image credit : <a href="https://microservices.io/patterns/data/saga.html">https://microservices.io/patterns/data/saga.html</a></figcaption></figure><blockquote>The <strong>Saga pattern</strong> <br>- is a <strong>distributed transaction pattern</strong> <br>- that ensures <strong>data consistency <br>- </strong>across <strong>multiple microservices</strong> <br>- without relying on<strong> </strong>traditional<strong> two-phase commit protocols</strong>.</blockquote><p>The above definition has a lot of details to unpack. A quick breakdown of the important aspects of this definition is as follows:</p><h4><strong>Distributed Transaction Pattern:</strong></h4><ul><li><strong>Meaning :</strong> <em>A pattern to handle </em><strong><em>transactions</em></strong><em> involving </em><strong><em>multiple services</em></strong><em>.</em><br><strong>Example :</strong> <em>Placing an order involves transactions across </em><strong><em>Inventory Service</em></strong><em>, </em><strong><em>Payment Service</em></strong><em>, and </em><strong><em>Shipping Service</em></strong><em>.</em></li></ul><h4><strong>Ensure Data Consistency:</strong></h4><ul><li><strong>Meaning</strong>: <em>Make sure the system as a whole reflects all changes correctly after the transaction is completed. </em><br><strong>Example</strong>: <em>If an order is placed and </em><strong><em>paid</em></strong><em> for, the </em><strong><em>inventory</em></strong><em> should be updated, and the </em><strong><em>product</em></strong><em> should be shipped.</em></li></ul><h4><strong>Across Multiple Microservices:</strong></h4><ul><li><strong>Meaning:</strong> <em>Involves several independent services each handling a </em><strong><em>specific</em></strong><em> part of the </em><strong><em>overall</em></strong><em> transaction.</em><br><strong>Example:</strong> <em>The Order Service creates the order, Inventory Service manages stock, Payment Service processes the payment, and Shipping Service arranges delivery.</em></li></ul><h4><strong>Without Relying on Traditional Two-Phase Commit Protocols:</strong></h4><ul><li><strong>Meaning</strong>: <em>Avoids the complex, performance-impacting coordination of a classic 2-phase distributed transaction protocol.</em><br><strong>Example</strong>: <em>Instead of waiting for </em><strong><em>all</em></strong><em> services to agree before committing, each service handles its own transaction and compensates if necessary.</em></li></ul><h3>The Distributed Transaction Dilemma</h3><p>To understand this concept better, let’s use a real-world example involving an <strong>e-commerce platform</strong> where:</p><p>1. Customers can place orders<br>2. Make payments<br>3. Have items shipped to their address</p><ul><li>In a <strong>monolithic application</strong>, handling a customer order is straightforward. We typically use a <strong><em>single database transaction</em></strong> to <em>update inventory</em>, <em>process payment</em>, and <em>create a shipping order</em>. If something goes wrong during any of these 3 steps, we cancel the customer order by rolling back this single transaction.</li><li>In a <strong>microservices</strong> based architecture, each of these tasks might be managed by a different service with its own database, so things are not as straightforward.</li></ul><p>Let’s compare three approaches to handling this scenario in a microservices-based system:</p><ol><li>The Naive Approach (No Saga)</li><li>The Two-Phase Commit Approach(2PC)</li><li>The Saga Pattern Approach</li></ol><h4>1. The Naive Approach (No Saga)</h4><p>We coordinate all these steps without any special pattern:</p><pre>public void processOrder(Order order) {<br>    inventoryService.reduceStock(order.getItems());<br>    paymentService.processPayment(order.getTotal());<br>    shippingService.createShippingOrder(order);<br>}</pre><p>This looks simple, but what happens if the payment fails <strong><em>after</em></strong> we’ve already reduced the stock? Or if the shipping service is down <strong><em>after</em></strong> we’ve taken the customer’s money? We’d end up with inconsistent data across our services.</p><h4>2. The Two-Phase Commit Approach (2PC)</h4><p>Two-Phase Commit (2PC) is a classic approach for handling distributed transactions. It works like this:</p><ul><li>Prepare Phase: The coordinator asks all participants if they’re ready to commit.</li><li>Commit Phase: If all participants agree, the coordinator tells everyone to commit.</li></ul><pre>public void processOrder(Order order) {<br>    // Prepare phase<br>    boolean inventoryPrepared = inventoryService.prepareReduceStock(order.getItems());<br>    boolean paymentPrepared = paymentService.prepareProcessPayment(order.getTotal());<br>    boolean shippingPrepared = shippingService.prepareCreateShippingOrder(order);<br><br>    // Commit or rollback phase<br>    if (inventoryPrepared &amp;&amp; paymentPrepared &amp;&amp; shippingPrepared) {<br>        // Commit<br>        inventoryService.reduceStock(order.getItems());<br>        paymentService.processPayment(order.getTotal());<br>        shippingService.createShippingOrder(order);<br>    } else {<br>        // Rollback (implement rollback logic for each service)<br>        inventoryService.rollbackReduceStock();<br>        paymentService.rollbackProcessPayment();<br>        shippingService.rollbackCreateShippingOrder();<br>    }<br>}</pre><p>While 2PC ensures consistency, it has some significant drawbacks in the microservices world:</p><ul><li>It’s synchronous and blocking, which can lead to performance issues.</li><li>It requires <strong><em>all</em></strong> participants to support the 2PC protocol, which can be challenging.</li><li>It doesn’t handle long-lived transactions well, making it less effective for complex workflows.</li></ul><h4>3. The Saga Pattern Approach</h4><p>The Saga pattern takes a different approach. Instead of one big transaction, we break it down into a <strong><em>series of local transactions</em></strong>, each with its own <strong><em>compensating action</em></strong> in case of failure.</p><p>Here’s how an order process might be handled with the Saga Pattern:</p><ol><li>Create Order <em>(Compensating action: </em><strong><em>Cancel Order</em></strong><em>)</em></li><li>Reserve Inventory <em>(Compensating action: </em><strong><em>Release Inventory</em></strong><em>)</em></li><li>Process Payment <em>(Compensating action: </em><strong><em>Refund Payment</em></strong><em>)</em></li><li>Create Shipping Order (<em>Compensating action: </em><strong><em>Cancel Shipping</em></strong>)</li></ol><p>If any step fails, we trigger <strong>compensating actions</strong> for all completed steps in <strong>reverse order</strong>.</p><pre>public class OrderSaga {<br>    private final OrderService orderService;<br>    private final InventoryService inventoryService;<br>    private final PaymentService paymentService;<br>    private final ShippingService shippingService;<br><br>    public void processOrder(Order order) {<br>        try {<br>            orderService.createOrder(order);<br>            inventoryService.reserveInventory(order.getItems());<br>            paymentService.processPayment(order.getTotal());<br>            shippingService.createShippingOrder(order);<br>        } catch (Exception e) {<br>            compensate(order);<br>            throw new OrderProcessingException(&quot;Order processing failed&quot;, e);<br>        }<br>    }<br><br>    private void compensate(Order order) {<br>        try {<br>            shippingService.cancelShipping(order);<br>            paymentService.refundPayment(order.getTotal());<br>            inventoryService.releaseInventory(order.getItems());<br>            orderService.cancelOrder(order);<br>        } catch (Exception e) {<br>            // Log the compensation failure for manual intervention<br>            logger.error(&quot;Compensation failed for order: &quot; + order.getId(), e);<br>        }<br>    }<br>}</pre><h3>Saga pattern vs 2-Phase Commit (2PC)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcMnHfU1FewyAZG9KRfLUw.png" /><figcaption>Saga vs 2PC</figcaption></figure><h3>Implementing Sagas: Choreography vs. Orchestration</h3><p>There are two main ways to implement the Saga pattern:</p><ul><li><strong>Choreography</strong>: Each service publishes events that trigger the next service in the saga. Services independently coordinate and interact with each other based on predefined rules or events.</li><li><strong>Orchestration</strong>: A central coordinator manages the entire saga flow. A central service or controller manages and directs the interactions between different services.</li></ul><h4>Choreography Example</h4><p>In this approach, each service reacts to events from other services.</p><pre>// OrderService.java<br>public class OrderService {<br>    private EventBus eventBus;<br><br>    public void createOrder(Order order) {<br>        // Create order logic<br>        eventBus.publish(new OrderCreatedEvent(order.getId()));<br>    }<br><br>    @EventHandler<br>    public void onPaymentProcessed(PaymentProcessedEvent event) {<br>        // Update order status<br>        eventBus.publish(new OrderCompletedEvent(event.getOrderId()));<br>    }<br>}<br><br>// InventoryService.java<br>public class InventoryService {<br>    private EventBus eventBus;<br><br>    @EventHandler<br>    public void onOrderCreated(OrderCreatedEvent event) {<br>        // Reserve inventory<br>        eventBus.publish(new InventoryReservedEvent(event.getOrderId()));<br>    }<br>}<br><br>// PaymentService.java<br>public class PaymentService {<br>    private EventBus eventBus;<br><br>    @EventHandler<br>    public void onInventoryReserved(InventoryReservedEvent event) {<br>        // Process payment<br>        eventBus.publish(new PaymentProcessedEvent(event.getOrderId()));<br>    }<br>}</pre><h4>Orchestration Example</h4><p>Here, a central orchestrator <strong>OrderSaga</strong> manages the entire process.</p><pre>// OrderSaga.java<br>public class OrderSaga {<br>    private OrderService orderService;<br>    private InventoryService inventoryService;<br>    private PaymentService paymentService;<br><br>    public void process(String orderId) {<br>        try {<br>            Order order = orderService.getOrder(orderId);<br>            inventoryService.reserveInventory(order);<br>            paymentService.processPayment(order);<br>            orderService.completeOrder(orderId);<br>        } catch (Exception e) {<br>            compensate(orderId);<br>        }<br>    }<br><br>    private void compensate(String orderId) {<br>        // Implement compensation logic<br>    }<br>}<br><br>// OrderService.java<br>public class OrderService {<br>    public void createOrder(Order order) {<br>        // Create order logic<br>        new OrderSaga().process(order.getId());<br>    }<br>}<br><br>// InventoryService.java<br>public class InventoryService {<br>    public void reserveInventory(Order order) {<br>        // Reserve inventory logic<br>    }<br>}<br><br>// PaymentService.java<br>public class PaymentService {<br>    public void processPayment(Order order) {<br>        // Process payment logic<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUyUIUFf6vlK2Zc_4zROMQ.png" /><figcaption>Choreography vs Orchestration</figcaption></figure><h3>Conclusion</h3><p>The Saga pattern is a powerful solution in the microservices toolbox. It excels in scenarios where you need to maintain data consistency across multiple services without sacrificing the autonomy and loose coupling that make microservices great.</p><p>However, implementing Sagas requires careful thought about the business process, potential failure scenarios, and how to design effective compensating actions.</p><p>Consider leveraging the Saga pattern the next time you’re faced with a distributed transaction challenge in your microservices architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a01fc27abe" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/microservices-design-using-saga-pattern-for-distributed-transactions-84a01fc27abe">Microservices design : Using SAGA pattern for distributed transactions</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database per service : Microservice design pattern]]></title>
            <link>https://blog.devops.dev/database-per-service-microservice-design-pattern-97b080ffb2dc?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b080ffb2dc</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 08:52:35 GMT</pubDate>
            <atom:updated>2024-09-10T15:16:49.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>Database per service : Understanding this Microservice design pattern</h3><h4>Though relatively easy to understand, it can result in nanoservices, if not careful</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGpuAfW7OyuyXwF_otl16Q.png" /><figcaption>Image credit : <a href="https://microservices.io/patterns/data/database-per-service.html">https://microservices.io/patterns/data/database-per-service.html</a></figcaption></figure><p>The “Database Per Microservice” pattern is a commonly used pattern with distributed microservices architecture, wherein each microservice manages its own dedicated database. This approach contrasts sharply with traditional monolithic architectures that rely on a single, shared database.</p><h3>What Is the need for this pattern?</h3><p>In a microservices setup, services must be loosely coupled so that they can be developed, deployed and scaled independently. At the same time, different services might have different data storage requirements.</p><p>The “Database Per Microservice” pattern is an implementation of this principle wherein <strong>each microservice’s data is private to that service and accessible only via its API</strong>. <strong>A service’s transactions only involve its database.</strong></p><p>In practice, this pattern allows each service to scale independently, completely control the lifecycle of the data it manages (<em>i.e. data creation, updation, deletion</em>) as well as the freedom to pick and choose the database best suited for its’ needs.</p><h3>How Does It Work?</h3><p>There are several ways to implement this pattern, such as :</p><ul><li><strong>Private Tables Per Service</strong>: Each service uses its own set of tables, which it manages through its API.</li><li><strong>Schema Per Service</strong>: Each service operates within its own database schema.</li><li><strong>Database Server Per Service</strong>: Each service runs on its own dedicated database server.</li></ul><p>For instance, in an e-commerce application:</p><blockquote>The <strong>Order Service</strong> might use <strong>MySQL</strong> database to manage structured order data.<br>The <strong>Product Catalog Service</strong> could use <strong>MongoDB</strong> for flexible product details.<br>The <strong>Recommendation Engine</strong> might rely on <strong>Neo4j</strong> to model user relationships.</blockquote><h3>The Upsides and Scalability Benefits</h3><ul><li><strong>Isolation</strong>: Each service has its own data, so changes in one service don’t impact others.</li><li><strong>Independent Scaling</strong>: Services can scale their databases according to their specific needs, making resource use more efficient.</li><li><strong>Technology Flexibility</strong>: Each service can choose the best database technology for its requirements, boosting performance and scalability.</li><li><strong>Better Maintainability</strong>: Managing data within each service’s own boundary makes it easier to maintain and update.</li><li><strong>Optimized Performance</strong>: Dedicated databases reduce the performance issues often seen with a shared database.</li><li><strong>Reduced Coupling</strong>: Separate databases mean services are less dependent on each other, which simplifies scaling and upgrades.</li><li><strong>Fault Isolation</strong>: Issues with one service’s database won’t affect others, which makes the overall system more resilient.</li><li><strong>Distributed Load</strong>: Distributing data across multiple databases can handle a higher overall load compared to a single, centralized database.</li></ul><h3>Challenges</h3><p>Despite the benefits, there are some challenges to consider when adopting this pattern:</p><ul><li><strong>Data Consistency</strong>: Ensuring data consistency across distributed databases can be tricky, especially when transactions span multiple services. <em>The </em><a href="https://medium.com/@techiecuriosity/microservices-design-using-saga-pattern-for-distributed-transactions-84a01fc27abe"><strong><em>Saga Pattern</em></strong></a><em> is one way to manage this complexity.</em></li><li><strong>Querying Across Services</strong>: Getting data from multiple services can be complicated and might require complex API setups or event-driven syncs.</li><li><strong>Operational Overhead</strong>: Managing several databases increases complexity and demands a more robust infrastructure.</li><li><strong>Inter-Service Communication</strong>: Services need reliable communication methods. Failures can disrupt workflows, so tools like circuit breakers are essential.</li></ul><h3>ALERT: Watch Out for ‘Nanoservices’</h3><p>While the Database Per Microservice pattern isn’t a bad idea on its own, it can lead to issues if not handled carefully:</p><ul><li><strong>Over-decomposition</strong>: Going overboard might result in too many tiny services, each with its own database, <strong>leading to nanoservices</strong> — services that are too small and don’t offer much business value on their own.</li><li><strong>Increased Complexity</strong>: A large number of small services with individual databases can make the system harder to manage and maintain.</li></ul><h4>So how to avoid Nanoservices?</h4><p>Assume we have an e-commerce application. To avoid falling into the trap of nanoservices, we could implement this design pattern using the principles in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ea9baM8_Kbs7ozJm3gvoag.png" /></figure><h3>Pattern Summary</h3><h4>When It Works Best</h4><ul><li><strong>Microservices Architecture</strong>: This pattern is a natural fit for microservices, aligning with its core principles.</li><li><strong>Distinct Data Needs</strong>: It’s useful when different services have unique data storage or scaling requirements.</li></ul><h4>When to Be Cautious</h4><ul><li><strong>Simple Applications</strong>: For simpler applications that don’t need the complexity of microservices, a monolithic architecture might be easier to manage.</li><li><strong>Frequent Transactions</strong>: If your application requires frequent cross-service transactions, managing consistency might become complex and challenging.</li></ul><p><strong>Database per Microservice</strong> is powerful as it offers a lot of advantages, such as giving each service control over its data, the type of database to use, and the ability for the service to scale independently. This flexibility makes the whole system better at handling more traffic and adapting to changes.</p><p>However, keeping data consistent across different services can be tricky, and managing the increased complexity is a challenge.</p><p>The trick is to design services around real business needs and keep them at a sensible size. This way, you can enjoy the advantages without falling into the trap of creating too many tiny, hard-to-manage services, known as nanoservices. The goal is to find the right balance between letting services operate independently and keeping the system as a whole easy to manage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b080ffb2dc" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/database-per-service-microservice-design-pattern-97b080ffb2dc">Database per service : Microservice design pattern</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices 101 : Why to use Service discovery pattern?]]></title>
            <link>https://blog.devops.dev/microservices-101-why-to-use-service-discovery-pattern-8ed574ff5e6c?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ed574ff5e6c</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[service-discovery]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 07:18:55 GMT</pubDate>
            <atom:updated>2024-09-22T08:09:09.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservices design : Why to use Service discovery pattern?</h3><h4>And is it really needed if your microservices are already behind a load balancer?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*GCmjibEYKEwZKMZSuWomWg.png" /><figcaption>Service discovery via Service Registry</figcaption></figure><p>In distributed microservices architecture, where applications are broken down into small, independent services, one critical challenge emerges: <strong><em>How do these services find and communicate with each other in a constantly changing environment?</em></strong></p><p>The <strong>Service Discovery pattern</strong> is designed to deal with this challenge.</p><h3>The Challenge: Dynamic Service Locations</h3><p>Consider an e-commerce platform built with microservices. You have services for user authentication, product catalog, shopping cart, and order processing. In a static world, you might hardcode service locations:</p><pre>public class ServiceLocator {<br>  public static final String AUTH_SERVICE = &quot;http://auth-service:8080&quot;;<br>  public static final String CATALOG_SERVICE = &quot;http://catalog-service:8081&quot;;<br>  public static final String CART_SERVICE = &quot;http://cart-service:8082&quot;;<br>  public static final String ORDER_SERVICE = &quot;http://order-service:8083&quot;;<br>}</pre><p>However, in the dynamic world of microservices, where services scale, move, and update frequently, this approach quickly leads to outdated addresses and system instability.</p><h3>Service Discovery to the Rescue</h3><p>Service Discovery acts as a <strong><em>dynamic directory</em></strong> for your microservices. Services register themselves, and clients lookup the current address when they need to make a call.</p><h4>Implementing Service Discovery</h4><p>Let’s explore the two main approaches to service discovery:</p><ul><li><strong>Client-side</strong> <strong>discovery</strong></li><li><strong>Server-side discovery</strong></li></ul><h4>Client-Side Discovery</h4><p>In this approach, the client is responsible for determining the location of service instances and load balancing requests.</p><pre>public class ClientSideDiscoveryExample {<br>    private ServiceRegistry serviceRegistry;<br><br>    public ClientSideDiscoveryExample(ServiceRegistry serviceRegistry) {<br>        this.serviceRegistry = serviceRegistry;<br>    }<br><br>    public String callAuthService() throws Exception {<br>      ServiceInstance authService = serviceRegistry.getService(&quot;auth-service&quot;);<br>      String serviceUrl = String.format(&quot;http://%s:%d&quot;, authService.getHost(), authService.getPort());<br>        <br>        // Make the actual call using your preferred HTTP client<br>        return HttpClient.newHttpClient()<br>            .send(HttpRequest.newBuilder(URI.create(serviceUrl + &quot;/validate&quot;))<br>                .GET()<br>                .build(), <br>                HttpResponse.BodyHandlers.ofString())<br>            .body();<br>    }<br>}</pre><h4>Server-Side Discovery</h4><p>Here, clients communicate through a load balancer, which handles service discovery and routing.</p><pre>public class ServerSideDiscoveryExample {<br>    private static final String LOAD_BALANCER_URL = &quot;http://api.myapp.com&quot;;<br><br>    public String callAuthService() throws Exception {<br>        String serviceUrl = LOAD_BALANCER_URL + &quot;/auth-service/validate&quot;;<br>        <br>        return HttpClient.newHttpClient()<br>            .send(HttpRequest.newBuilder(URI.create(serviceUrl))<br>                .GET()<br>                .build(), <br>                HttpResponse.BodyHandlers.ofString())<br>            .body();<br>    }<br>}</pre><h3>Question: My microservices are already behind the load balancer, hence clients can use the load balancer endpoint to call my service. Do I still need service discovery?</h3><p>A valid question. Load balancers, especially in AWS, do indeed provide quite a few features that overlap with service discovery, but there are additional benefits that a <strong>service discovery framework</strong> can provide over a load balancer-based approach.</p><p>The differences and benefits are listed in the side-to-side comparison below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FedjOZty8jWCogFprGlGQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDLnxeNni9XD_SWM9aSK2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6sPj4qp4YCQSNy8MKrKhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g40FGz5j4NmA5Ssq7r3lTQ.png" /></figure><h3>Real-World Example: Spring Cloud Netflix</h3><p><em>Consul, Eureka, Istio, Kubernetes Service Discovery, ZooKeeper, Spring Cloud Netflix</em> are some of the popular frameworks for implementing service discovery.</p><p>In the example below, we use <em>Spring Cloud Netflix</em> for a robust implementation of service discovery. Here’s how you might register a service:</p><pre>@SpringBootApplication<br>@EnableEurekaClient<br>public class MyService {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyService.class, args);<br>    }<br>}</pre><p>And in your `<strong>application.properties</strong>`:</p><pre>spring.application.name=my-service<br>eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/</pre><p>To look up a service and make a call:</p><pre>@Service<br>public class ServiceCaller {<br>  @Autowired<br>  private DiscoveryClient discoveryClient;<br><br>public String callAuthService() {<br>  List&lt;ServiceInstance&gt; instances = discoveryClient.getInstances(&quot;auth-service&quot;);<br>      if (instances != null &amp;&amp; !instances.isEmpty()) {<br>        ServiceInstance serviceInstance = instances.get(0);<br>          String serviceUrl = serviceInstance.getUri().toString();<br>            <br>         // Make the call using RestTemplate or WebClient<br>          RestTemplate restTemplate = new RestTemplate();<br>          return restTemplate.getForObject(serviceUrl + &quot;/validate&quot;, String.class);<br>      }<br>      return null;<br>  }<br>}</pre><h3>Beyond Basic Discovery: Health Checks and Circuit Breaking</h3><p>Modern service discovery systems often integrate with additional features like <strong>health checks</strong> and <strong>circuit breaking</strong>:</p><pre>public class AdvancedServiceDiscovery {<br>    private CircuitBreaker circuitBreaker;<br><br>    public AdvancedServiceDiscovery() {<br>        this.circuitBreaker = new CircuitBreaker(5, Duration.ofSeconds(30));<br>    }<br><br>    public boolean healthCheck(String serviceUrl) {<br>        try {<br>            HttpClient client = HttpClient.newHttpClient();<br>            HttpResponse&lt;String&gt; response = client.send(<br>                HttpRequest.newBuilder(URI.create(serviceUrl + &quot;/health&quot;))<br>                    .GET()<br>                    .build(),<br>                HttpResponse.BodyHandlers.ofString()<br>            );<br>            return response.statusCode() == 200;<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }<br><br>    public String callService(String serviceUrl) throws Exception {<br>        return circuitBreaker.run(() -&gt; {<br>            HttpClient client = HttpClient.newHttpClient();<br>            return client.send(<br>                HttpRequest.newBuilder(URI.create(serviceUrl))<br>                    .GET()<br>                    .build(),<br>                HttpResponse.BodyHandlers.ofString()<br>            ).body();<br>        });<br>    }<br>}<br><br>class CircuitBreaker {<br>    // Implementation details omitted for brevity<br>}</pre><h3>Conclusion</h3><p>Service discovery is a crucial pattern in building resilient, scalable microservices architectures. Though there is some level of effort required to setup and maintain the service discovery framework, the benefits that we get out it are worth the investment. Whether you choose client-side or server-side discovery, implementing this pattern is key to creating flexible and robust microservices systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ed574ff5e6c" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/microservices-101-why-to-use-service-discovery-pattern-8ed574ff5e6c">Microservices 101 : Why to use Service discovery pattern?</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Circuit Breaker Pattern: Protecting Microservices from Cascading Failures]]></title>
            <link>https://blog.devops.dev/circuit-breaker-pattern-protecting-microservices-from-cascading-failures-0b8f5c56b960?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b8f5c56b960</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[resilience-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 07:12:14 GMT</pubDate>
            <atom:updated>2024-09-04T18:46:22.892Z</atom:updated>
            <content:encoded><![CDATA[<h4>and how it differs from the ‘Retry Pattern’</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hseURxIFRU9E3lEOoeGGA.png" /><figcaption>Image credit : <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker">https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker</a></figcaption></figure><p>Microservices architectures bring numerous benefits, but also introduce new challenges. One such challenge is the <strong>risk of cascading failures</strong>, where a single service’s failure takes down the entire system. The <strong>circuit breaker pattern</strong> is designed exclusively to deal with this scenario.</p><h3>What is the Circuit Breaker Pattern?</h3><blockquote>The Circuit Breaker pattern prevents an application<strong> from repeatedly trying to execute an operation that’s likely to fail.</strong></blockquote><p>It’s designed to:</p><ol><li>Detect failures quickly</li><li>Avoid cascading failures in a distributed system</li><li>Allow time for faults to be fixed before retrying operations</li></ol><h3>Why do we need it?</h3><p>‘Cause in distributed environments, calls to remote services can fail for various reasons:</p><ol><li>Slow network connections</li><li>Timeouts</li><li>Overcommitted resources</li><li>Temporary unavailability</li></ol><p>While some of these issues resolve quickly, others may persist. Continually retrying a failing operation can waste resources and potentially cause cascading failures throughout your system. These blocked/retried requests can consume valuable system resources, including memory, threads, and database connections. If these resources become depleted, it can lead to failures in other parts of the system, even those unrelated to the original issue. <br>The Circuit Breaker pattern, on the other hand, provides an alternate, smart way to handle such remote service failure scenarios and still prevent cascading failures.</p><h3>So How Does It Work?</h3><p>The Circuit Breaker acts as a proxy for potentially failing operations by monitoring recent failures, and deciding whether to allow the operation to proceed or return an immediate exception.</p><p>The pattern operates like an electrical circuit breaker, with three main states:</p><ul><li><strong>Closed</strong>: Normal operation. Requests pass through to the external service.</li><li><strong>Open</strong>: Failure detected. Requests immediately fail without attempting to call the external service.</li><li><strong>Half-Open:</strong> After a timeout, allows a limited number of test requests to pass through to the external service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwZa1euZZnf5Yjhj9vp9YA.png" /><figcaption>The 3 states of a Circuit Breaker</figcaption></figure><h3>Wouldn’t the retry pattern suffice?</h3><p>Although the Retry Pattern and Circuit Breaker Pattern share some similarities, they approach failures differently:</p><ul><li><strong>Retry Pattern:</strong> Assumes that failures are temporary and will likely resolve quickly. It retries the operation a specified number of times or with increasing delays, based on the assumption that the issue will be resolved by the time the next attempt is made.</li><li><strong>Circuit Breaker Pattern:</strong> Takes a more cautious approach. It temporarily blocks requests to a failing service to prevent further strain on the system. The circuit breaker only allows requests again when the previously failing service has demonstrated that it can successfully handle calls, thus avoiding repeated failures.</li></ul><p>Though the Circuit Breaker pattern and the Retry pattern are both used to improve system resilience, they differ in their approach and use cases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0T5J6x1HY8iIH9nJygERw.png" /><figcaption>Circuit breaker pattern vs Retry pattern</figcaption></figure><p>In essence, <strong><em>the Retry Pattern is more optimistic</em></strong>, assuming that retrying will eventually succeed, while <strong><em>the Circuit Breaker Pattern is more conservative</em></strong>, pausing interactions until the service is reliably functional.</p><h3>How about a Code example?</h3><p>Imagine you’re building an e-commerce application that relies on an external payment service to process transactions.</p><h4>Without a Circuit Breaker</h4><p>Here’s what might happen when the payment service is experiencing issues:</p><pre>public class PaymentService {<br>    public boolean processPayment(Order order) {<br>        try {<br>            // This call might take up to 30 seconds to timeout<br>            return externalPaymentAPI.processPayment(order);<br>        } catch (Exception e) {<br>            return false;<br>        }<br>    }<br>}</pre><p>In this scenario, if the external payment service is down, each request might take up to 30 seconds before timing out. During this time, the application is tying up resources waiting for a response, and users are left waiting.</p><h4>With a Circuit Breaker</h4><pre>import io.github.resilience4j.circuitbreaker.CircuitBreaker;<br>import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;<br>import io.vavr.control.Try;<br><br>import java.time.Duration;<br><br>public class PaymentService {<br>    private final CircuitBreaker circuitBreaker;<br>    private final ExternalPaymentAPI externalPaymentAPI;<br><br>    public PaymentService(ExternalPaymentAPI externalPaymentAPI) {<br>        this.externalPaymentAPI = externalPaymentAPI;<br>        <br>        CircuitBreakerConfig config = CircuitBreakerConfig.custom()<br>            .failureRateThreshold(50) // Percentage of failed external calls<br>            .waitDurationInOpenState(Duration.ofSeconds(10)) // Duration for which external calls are blocked <br>            .slidingWindowSize(5) // Number of calls sampled<br>            .build();<br>        <br>        this.circuitBreaker = CircuitBreaker.of(&quot;paymentServiceBreaker&quot;, config);<br>    }<br><br>    public boolean processPayment(Order order) {<br>        return Try.ofSupplier(CircuitBreaker.decorateSupplier(circuitBreaker, <br>                () -&gt; externalPaymentAPI.processPayment(order)))<br>            .recover(throwable -&gt; {<br>                // Fallback: record the payment for later processing<br>                recordPaymentForLaterProcessing(order);<br>                return true;<br>            })<br>            .get();<br>    }<br><br>    private void recordPaymentForLaterProcessing(Order order) {<br>        // Logic to save the order for later payment processing<br>    }<br>}</pre><p>Here’s how this circuit breaker implementation demonstrates “Fail Fast and Recover”:</p><h4>Fail Fast:</h4><ul><li>If 50% of the last 5 requests fail (as set by failureRateThreshold and slidingWindowSize), the circuit opens.</li><li>When the circuit is open, subsequent calls to processPayment will immediately &quot;fail fast&quot; without even attempting to call the external service.</li><li>This prevents the 30-second wait times, immediately freeing up system resources and providing a quick response to the user.</li></ul><h4>Recover:</h4><ul><li>The recover method provides a fallback mechanism. In this case, we&#39;re recording the payment for later processing.</li><li>Users receive a quick response (<em>the order is accepted but payment will be processed later</em>), providing a degraded but still functional service.</li><li>After 10 seconds (set by waitDurationInOpenState), the circuit will allow a test request through. If successful, it will close the circuit, allowing normal operation to resume.</li></ul><h4>Benefits in Practice</h4><ol><li><strong>Resource Conservation</strong>: Instead of tying up threads and connections with long-running requests, the system quickly moves on to handle other tasks.</li><li><strong>Improved User Experience</strong>: Users get fast feedback instead of waiting for timeouts, even if the actual payment processing is delayed.</li><li><strong>System Resilience</strong>: By failing fast and providing a fallback, the overall e-commerce system can continue to function even when the payment service is down.</li><li><strong>Automatic Recovery</strong>: The system will automatically attempt to resume normal operations after a short delay, without manual intervention.</li></ol><p>This example demonstrates how the Circuit Breaker pattern enables a system to fail fast when issues are detected, but also provides mechanisms for graceful degradation and automatic recovery. It’s a powerful tool for building resilient systems that can maintain some level of functionality even when critical dependencies fail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b8f5c56b960" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/circuit-breaker-pattern-protecting-microservices-from-cascading-failures-0b8f5c56b960">Circuit Breaker Pattern: Protecting Microservices from Cascading Failures</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices design : How Does an API Gateway Work?]]></title>
            <link>https://blog.devops.dev/microservices-design-how-does-an-api-gateway-work-8d16ffd89c4c?source=rss-3dddaf5ed765------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d16ffd89c4c</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[microservices-design]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Tech Proverb]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 18:34:29 GMT</pubDate>
            <atom:updated>2024-09-04T18:46:17.044Z</atom:updated>
            <content:encoded><![CDATA[<h4>And the benefits of adopting it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeY9Krs9LA30h_s3nFFzNg.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/architecture/microservices/design/gateway">https://learn.microsoft.com/en-us/azure/architecture/microservices/design/gateway</a></figcaption></figure><p>An API Gateway acts as a reverse proxy, intercepting incoming client requests and routing them to the appropriate backend microservices. It provides a unified interface, abstracting the underlying complexity of the microservices architecture.</p><h3><strong>Key components and functionalities of an API Gateway:</strong></h3><ol><li><strong>Request Routing:</strong> The API Gateway receives incoming requests from clients and determines the appropriate microservice to handle them based on defined routing rules or policies. This can involve URL path matching, query parameters, or custom logic.</li><li><strong>Protocol Translation:</strong> If necessary, the API Gateway can translate between different communication protocols (e.g., REST, GraphQL, gRPC) to ensure compatibility between clients and microservices.</li><li><strong>Authentication and Authorization:</strong> The API Gateway can enforce security measures such as API key validation, OAuth, and role-based access control to protect microservices from unauthorized access.</li><li><strong>Rate Limiting and Throttling:</strong> To prevent abuse and ensure fair resource allocation, the API Gateway can implement rate limiting and throttling policies to restrict the number of requests a client can make within a given time period.</li><li><strong>Caching:</strong> The API Gateway can cache frequently accessed data to improve performance and reduce load on microservices. This can be particularly effective for static content or frequently repeated API calls.</li><li><strong>API Versioning:</strong> The API Gateway can handle API versioning, allowing for gradual changes and updates without impacting existing clients.</li><li><strong>Request Aggregation and Composition:</strong> For complex operations that involve multiple microservices, the API Gateway can aggregate requests, combining responses into a single response for the client.</li><li><strong>Monitoring and Logging:</strong> The API Gateway can collect metrics and logs to provide insights into API usage, performance, and security. This information can be used for troubleshooting, optimization, and billing.</li></ol><h3><strong>Benefits of Using an API Gateway</strong></h3><ul><li><strong>Reduced Client Complexity:</strong> Clients interact with a single endpoint, simplifying integration and reducing complexity.</li><li><strong>Improved Performance:</strong> Caching, load balancing, and request aggregation can enhance performance.</li><li><strong>Enhanced Security:</strong> Centralized security measures can protect microservices from unauthorized access.</li><li><strong>Simplified Development:</strong> Developers can focus on building microservices without worrying about low-level concerns like authentication, authorization, and rate limiting.</li><li><strong>Scalability:</strong> The API Gateway can be scaled independently to handle increasing traffic.</li><li><strong>API Management:</strong> The API Gateway provides a platform for managing and governing APIs, including versioning, documentation, and analytics.</li></ul><h3>Potential Drawbacks</h3><ul><li><strong>Increased Complexity:</strong> Implementing an API Gateway adds another layer to the architecture, which requires development and maintenance.</li><li><strong>Potential Performance Impact:</strong> The additional network hop through the gateway may introduce some latency, although this is often negligible for most applications.</li><li><strong>Single Point of Failure Concern:</strong> If not properly designed and implemented, the API Gateway could become a single point of failure</li></ul><h3>Comparison with direct client-to-microservice approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*mYf1Zz1c-ZR7Xv1tEWQiiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*RVkxUv6NW4mzbdq3wzojVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZIX_cgS46lJNXWjYEc5tZw.png" /></figure><h3><strong>In Conclusion</strong></h3><p>The API Gateway pattern offers significant benefits in managing the complexity of microservices architectures. While it introduces some additional complexity, the advantages in terms of simplified client interaction, enhanced security, and optimized performance often outweigh the drawbacks for many applications.</p><p>However, it’s essential to carefully evaluate your specific use case. For smaller applications or those with simple architectures, the overhead of an API Gateway might not be justified. As with any architectural decision, consider your project’s unique requirements, scale, and future growth plans when deciding whether to implement an API Gateway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d16ffd89c4c" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/microservices-design-how-does-an-api-gateway-work-8d16ffd89c4c">Microservices design : How Does an API Gateway Work?</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>