<?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 Andrew Khoshbin on Medium]]></title>
        <description><![CDATA[Stories by Andrew Khoshbin on Medium]]></description>
        <link>https://medium.com/@uptoamir?source=rss-96839de87430------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g9O9_nqdSFtgudowSuQpuQ.png</url>
            <title>Stories by Andrew Khoshbin on Medium</title>
            <link>https://medium.com/@uptoamir?source=rss-96839de87430------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:43:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uptoamir/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[Mastering Kubernetes: A Comprehensive Cheat Sheet for the CKA Exam and Beyond]]></title>
            <link>https://medium.com/@uptoamir/mastering-kubernetes-a-comprehensive-cheat-sheet-for-the-cka-exam-and-beyond-5f33b00e4b9f?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f33b00e4b9f</guid>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[kubernetes-best-practices]]></category>
            <category><![CDATA[linux-foundation]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 01:11:51 GMT</pubDate>
            <atom:updated>2025-03-06T01:35:36.549Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Kubernetes is a powerful platform for container orchestration, and whether you’re studying for the Certified Kubernetes Administrator (CKA) exam or looking to streamline your day-to-day cluster management, having a clear, consolidated reference is invaluable. In this post, we’ll dive into practical commands and concepts — from creating YAML manifests to understanding services, scaling, and node scheduling.</p><h3>1. Kubernetes Workflow Essentials</h3><p>Kubernetes operates as a series of coordinated components:</p><ul><li><strong>Scheduler → Controller → Kubelet → Container Runtime</strong><br>This pipeline ensures that your pods are placed on nodes, configured, and managed according to the defined state.</li></ul><h3>2. Creating and Managing YAML Manifests</h3><p>One of Kubernetes’ most powerful features is its declarative configuration. Instead of manually tweaking live objects, you generate YAML definitions to describe the desired state.</p><h3>Generate YAML with Dry Run</h3><ul><li><strong>Command:</strong></li></ul><pre>kubectl create deployment my-deployment --image=nginx --dry-run=client -o yaml &gt; my-deployment.yaml</pre><ul><li><strong>What It Does:</strong><br>Generates a YAML manifest without actually creating the deployment. Use this to review or modify the file before applying it.</li></ul><h3>Editing and Applying Changes</h3><ul><li><strong>Edit:</strong><br>Open your YAML in an editor (e.g., vi redis.yaml) to adjust settings as needed.</li><li><strong>Apply:</strong></li></ul><pre>kubectl apply -f redis.yaml</pre><ul><li>This creates or updates the resource based on your definition.</li></ul><h3>3. ReplicaSets, Deployments, and Rollouts</h3><h3>ReplicaSets (RS)</h3><ul><li><strong>Creation:</strong></li></ul><pre>kubectl create -f replicaset-definition.yaml</pre><ul><li><strong>Scaling:</strong><br>To adjust the number of replicas, use:</li></ul><pre>kubectl scale replicaset new-replica-set --replicas=0<br>kubectl scale replicaset new-replica-set --replicas=&lt;desired number&gt;</pre><ul><li><strong>Note:</strong><br>Even if you scale a resource via command line, changes in the YAML file aren’t automatically updated.</li></ul><h3>Deployments and Rollouts</h3><ul><li><strong>Creating Deployments:</strong><br>Use kubectl create deployment --help to explore options. Deployments manage ReplicaSets and offer advanced rollout strategies.</li><li><strong>Rolling Updates:</strong><br>Change the image of a deployment and record the change:</li></ul><pre>kubectl set image deployment my-deployment my-container=my-new-image --record</pre><ul><li>Rollouts help you transition versions smoothly and allow you to rollback if needed.</li><li><strong>Troubleshooting:</strong><br>If you change an image to one that doesn’t exist, kubectl rollout status may hang as Kubernetes struggles to replace pods.</li></ul><h3>4. Understanding Kubernetes Services</h3><p>Services expose your applications and abstract the underlying pod IPs.</p><h3>ClusterIP</h3><ul><li><strong>Usage:</strong><br>The default type, exposing your service internally within the cluster.</li><li><strong>Example:</strong></li></ul><pre>kubectl create service clusterip redis --tcp=6379:6379 --dry-run=client -o yaml &gt; redis-service.yaml</pre><ul><li><em>Tip:</em> When using kubectl expose, Kubernetes automatically uses the pod’s labels as selectors.</li></ul><h3>NodePort</h3><ul><li><strong>Usage:</strong><br>Exposes your service on a static port (30000–32767) on every node, allowing external traffic.</li><li><strong>Example:</strong></li></ul><pre>kubectl expose pod nginx --type=NodePort --port=80 --name=nginx-service --dry-run=client -o yaml &gt; nginx-service.yaml</pre><ul><li><em>Note:</em> You may need to edit the generated YAML to specify a custom node port.</li></ul><h3>LoadBalancer</h3><ul><li><strong>Usage:</strong><br>Common in cloud environments, this type creates an external load balancer that routes to your service.</li></ul><p><strong>Key Insight:</strong><br>Even when creating a NodePort service, Kubernetes automatically sets up a ClusterIP behind the scenes. This ensures internal traffic routing while exposing a port on each node.</p><h3>5. Scheduling, Taints, Tolerations, and Affinity</h3><h3>Scheduling Overview</h3><ul><li>If a pod isn’t assigned to a node, it’s usually because the scheduler hasn’t found a suitable match (due to resource constraints or taints).</li></ul><h3>Taints and Tolerations</h3><ul><li><strong>Taints:</strong><br>Applied to nodes to repel pods that do not tolerate them:</li></ul><pre>kubectl taint nodes node-1 key=value:NoSchedule</pre><ul><li><strong>Tolerations:</strong><br>Added to pod specifications to allow them to run on tainted nodes:</li></ul><pre>tolerations:<br>  - key: &quot;key&quot;<br>    operator: &quot;Equal&quot;<br>    value: &quot;value&quot;<br>    effect: &quot;NoSchedule&quot;</pre><ul><li><strong>Usage:</strong><br>Use taints to keep unwanted pods off specific nodes, and tolerations to grant exceptions.</li></ul><h3>Node Affinity</h3><ul><li><strong>Purpose:</strong><br>Directs pods to run on nodes with particular labels.</li><li><strong>Example:</strong></li></ul><pre>affinity:<br>  nodeAffinity:<br>    requiredDuringSchedulingIgnoredDuringExecution:<br>      nodeSelectorTerms:<br>      - matchExpressions:<br>        - key: size<br>          operator: In<br>          values:<br>          - large</pre><ul><li><strong>Combined Strategy:</strong><br>Taints and affinity can work together to finely control pod placement.</li></ul><h3>6. Namespaces and Resource Management</h3><h3>Namespaces</h3><ul><li>Use namespaces to logically separate resources.</li><li><strong>List All Pods Across Namespaces:</strong></li></ul><pre>kubectl get pods --all-namespaces</pre><ul><li>Or simply:</li></ul><pre>kubectl get pods -A</pre><h3>Resource Quotas and Limit Ranges</h3><ul><li><strong>Resource Quota:</strong><br>Limits total resources (like CPU and memory) that can be consumed in a namespace.</li><li><strong>Limit Range:</strong><br>Sets default resource requests/limits for pods that don’t specify their own.</li><li><strong>Example Limit Range:</strong></li></ul><pre>apiVersion: v1<br>kind: LimitRange<br>metadata:<br>  name: cpu-limit-range<br>  namespace: my-namespace<br>spec:<br>  limits:<br>    - type: Container<br>      defaultRequest:<br>        cpu: 100m<br>      default:<br>        cpu: 500m</pre><h3>7. Additional Tips and Gotchas</h3><ul><li><strong>Dry Run &amp; YAML Generation:</strong><br>Always leverage the --dry-run=client -o yaml flags to preview your configurations before applying changes.</li><li><strong>Port Mapping Differences:</strong><br>Unlike Docker’s -p HOST:CONTAINER, Kubernetes service definitions invert this order. Always verify which port is the internal container port and which is the external service port.</li><li><strong>Pod Restarts:</strong><br>Deleting pods that belong to a ReplicaSet will prompt Kubernetes to recreate them, similar to a restart. For controlled scaling, use the kubectl scale command.</li><li><strong>Command Shortcuts:</strong><br>Short forms like rs for ReplicaSet and deploy for Deployment can speed up your workflow when used appropriately.</li><li><strong>Watch and Debug:</strong><br>Use commands such as:</li></ul><pre>kubectl get pods --watch<br>kubectl get pods -o wide</pre><ul><li>These help you monitor changes in real time and diagnose scheduling issues.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f33b00e4b9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Circuit Breaker Pattern in Spring Cloud Gateway]]></title>
            <link>https://medium.com/@uptoamir/implementing-circuit-breaker-pattern-in-spring-cloud-gateway-b56b86697498?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56b86697498</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[resilience4j]]></category>
            <category><![CDATA[spring-cloud-gateway]]></category>
            <category><![CDATA[circuit-breaker-pattern]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 00:35:51 GMT</pubDate>
            <atom:updated>2025-07-06T02:45:32.569Z</atom:updated>
            <content:encoded><![CDATA[<p>In microservices architectures, it’s crucial to handle failures gracefully and prevent cascading failures that can bring down your entire system. The Circuit Breaker pattern is a design pattern that helps achieve this by monitoring for failures and temporarily blocking requests to a service that is failing. This article will guide you through implementing the Circuit Breaker pattern in a Spring Cloud Gateway using Resilience4j.</p><h3>What is the Circuit Breaker Pattern?</h3><p>The Circuit Breaker pattern is a stability pattern that wraps a function call to external services and monitors for failures. It has three primary states:</p><ol><li><strong>Closed:</strong> The circuit breaker is in a normal state, allowing all requests to pass through. If the failure rate crosses a threshold, it transitions to the open state.</li><li><strong>Open:</strong> The circuit breaker blocks all requests to the service. This prevents further failures and allows the system to recover. After a certain duration, it transitions to the half-open state.</li><li><strong>Half-Open:</strong> The circuit breaker allows a limited number of requests to pass through to test if the service has recovered. Depending on the outcome, it either transitions back to the closed state or reverts to the open state.</li></ol><h3>Visual Representation</h3><p>Below is a diagram that illustrates how the Circuit Breaker pattern is implemented via these three states in Resilience4j:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWrMleJYSoljGcc4srUvCQ.png" /></figure><p><em>In Resilience4j, the circuit breaker is implemented via three states: Closed, Open, and Half-Open.</em></p><h3>Integrating Circuit Breaker with Spring Cloud Gateway</h3><p>To implement the Circuit Breaker pattern in Spring Cloud Gateway, we can use the Resilience4j library. Spring Cloud Gateway provides easy integration with Resilience4j, enabling you to apply the Circuit Breaker pattern to your routes.</p><h4>1. Add Dependencies:</h4><p>First, you need to include the necessary dependencies in your pom.xml (for Maven) or build.gradle (for Gradle) file:</p><p><strong>Maven:</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-gateway&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;resilience4j-spring-boot2&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;resilience4j-circuitbreaker&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>Gradle:</strong></p><pre>implementation &#39;org.springframework.cloud:spring-cloud-starter-gateway&#39;<br>implementation &#39;io.github.resilience4j:resilience4j-spring-boot2&#39;<br>implementation &#39;io.github.resilience4j:resilience4j-circuitbreaker&#39;</pre><h4>2. Configure Circuit Breaker in application.yml:</h4><p>Next, configure the Circuit Breaker settings in the application.yml file:</p><pre>spring:<br>  cloud:<br>    gateway:<br>      routes:<br>        - id: sample-route<br>          uri: http://example-service<br>          predicates:<br>            - Path=/api/example/**<br>          filters:<br>            - name: CircuitBreaker<br>              args:<br>                name: exampleCircuitBreaker<br>                fallbackUri: forward:/fallback<br>resilience4j.circuitbreaker:<br>  instances:<br>    exampleCircuitBreaker:<br>      registerHealthIndicator: true<br>      slidingWindowSize: 10<br>      failureRateThreshold: 50<br>      waitDurationInOpenState: 10s<br>      permittedNumberOfCallsInHalfOpenState: 3<br>      minimumNumberOfCalls: 5</pre><p>In this configuration:</p><ul><li><strong>slidingWindowSize:</strong> Determines how many calls are monitored to calculate the failure rate.</li><li><strong>failureRateThreshold:</strong> The threshold percentage of failed calls before the Circuit Breaker opens.</li><li><strong>waitDurationInOpenState:</strong> The time the Circuit Breaker remains open before transitioning to half-open.</li><li><strong>permittedNumberOfCallsInHalfOpenState:</strong> The number of permitted calls in half-open state to test service recovery.</li></ul><h4>3. Implementing Fallback Mechanism:</h4><p>A fallback method can be implemented to handle the cases when the circuit breaker opens, allowing your application to degrade gracefully:</p><pre>@RestController<br>public class FallbackController {</pre><pre>    @RequestMapping(&quot;/fallback&quot;)<br>    public ResponseEntity&lt;String&gt; fallback() {<br>        return new ResponseEntity&lt;&gt;(&quot;Service is temporarily unavailable. Please try again later.&quot;, HttpStatus.SERVICE_UNAVAILABLE);<br>    }<br>}</pre><p>This fallback method returns a generic message when the service is down or the circuit breaker is open.</p><h3>Benefits of Using Circuit Breaker Pattern</h3><ul><li><strong>Failure Isolation:</strong> Prevents a failure in one service from cascading to other services.</li><li><strong>Graceful Degradation:</strong> Enables your system to degrade gracefully by providing fallback mechanisms.</li><li><strong>Resilience:</strong> Increases the overall resilience of your microservices architecture by managing failures effectively.</li></ul><h3>Conclusion</h3><p>Implementing the Circuit Breaker pattern using Resilience4j in Spring Cloud Gateway is an effective way to manage failures in your microservices architecture. By integrating this pattern, you can prevent cascading failures, improve system resilience, and provide a better user experience even during service disruptions.</p><p>Incorporating the Circuit Breaker pattern into your gateway layer ensures that your system remains robust and reliable, even when individual services fail. This approach is crucial for building fault-tolerant microservices that can handle real-world challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56b86697498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Cross-Cutting Concerns: Tracing & Logging with Spring Cloud Gateway]]></title>
            <link>https://medium.com/@uptoamir/implementing-cross-cutting-concerns-tracing-logging-with-spring-cloud-gateway-0444080ea7b9?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/0444080ea7b9</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud-gateway]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 23:14:28 GMT</pubDate>
            <atom:updated>2025-07-06T01:16:18.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tracing &amp; Logging with Spring Cloud Gateway</h3><p>Managing cross-cutting concerns such as tracing, logging, and correlation IDs is essential in microservices architectures. These features ensure that requests can be tracked across various services, simplifying debugging and enhancing the observability of the system. In this article, we’ll explore how to implement these features using Spring Cloud Gateway, specifically through a custom GlobalFilter.</p><h3>Overview of Request Flow in Spring Cloud Gateway</h3><p>Before diving into the implementation, let’s take a look at how requests flow through Spring Cloud Gateway using predicates, pre-filters, and post-filters. This flow is crucial to understand how and where you can implement cross-cutting concerns like tracing and logging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-XaFQbnJ54Q6jDWJODFwA.png" /></figure><p><em>Overview of request flow in Spring Cloud Gateway using predicates, pre-filters, and post-filters.</em></p><h3>Setting Up the Request Trace Filter</h3><p>The RequestTraceFilter class is a custom GlobalFilter in Spring Cloud Gateway that handles the creation and management of a correlation ID. This ID is used to trace requests across different microservices.</p><h4>Code Example:</h4><pre>package com.example.gateway.filters;</pre><pre>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.cloud.gateway.filter.GatewayFilterChain;<br>import org.springframework.cloud.gateway.filter.GlobalFilter;<br>import org.springframework.core.annotation.Order;<br>import org.springframework.http.HttpHeaders;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.server.ServerWebExchange;<br>import reactor.core.publisher.Mono;</pre><pre>@Order(1)<br>@Component<br>public class RequestTraceFilter implements GlobalFilter {</pre><pre>    private static final Logger logger = LoggerFactory.getLogger(RequestTraceFilter.class);</pre><pre>    @Autowired<br>    FilterUtility filterUtility;</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange exchange, GatewayFilterChain chain) {<br>        HttpHeaders requestHeaders = exchange.getRequest().getHeaders();<br>        if (isCorrelationIdPresent(requestHeaders)) {<br>            logger.debug(&quot;Correlation ID found in RequestTraceFilter: {}&quot;,<br>                    filterUtility.getCorrelationId(requestHeaders));<br>        } else {<br>            String correlationID = generateCorrelationId();<br>            exchange = filterUtility.setCorrelationId(exchange, correlationID);<br>            logger.debug(&quot;Correlation ID generated in RequestTraceFilter: {}&quot;, correlationID);<br>        }<br>        return chain.filter(exchange);<br>    }</pre><pre>    private boolean isCorrelationIdPresent(HttpHeaders requestHeaders) {<br>        return filterUtility.getCorrelationId(requestHeaders) != null;<br>    }</pre><pre>    private String generateCorrelationId() {<br>        return java.util.UUID.randomUUID().toString();<br>    }</pre><pre>}</pre><h3>Utility Class for Handling Correlation ID</h3><p>The FilterUtility class assists in managing the correlation ID. It provides methods to retrieve and set the correlation ID in the request headers.</p><h4>Code Example:</h4><pre>package com.example.gateway.filters;</pre><pre>import org.springframework.stereotype.Component;<br>import org.springframework.web.server.ServerWebExchange;<br>import org.springframework.http.HttpHeaders;<br>import java.util.List;</pre><pre>@Component<br>public class FilterUtility {</pre><pre>    public static final String CORRELATION_ID = &quot;correlation-id&quot;;</pre><pre>    public String getCorrelationId(HttpHeaders requestHeaders) {<br>        if (requestHeaders.get(CORRELATION_ID) != null) {<br>            List&lt;String&gt; requestHeaderList = requestHeaders.get(CORRELATION_ID);<br>            return requestHeaderList.stream().findFirst().get();<br>        } else {<br>            return null;<br>        }<br>    }</pre><pre>    public ServerWebExchange setRequestHeader(ServerWebExchange exchange, String name, String value) {<br>        return exchange.mutate().request(exchange.getRequest().mutate().header(name, value).build()).build();<br>    }</pre><pre>    public ServerWebExchange setCorrelationId(ServerWebExchange exchange, String correlationId) {<br>        return this.setRequestHeader(exchange, CORRELATION_ID, correlationId);<br>    }</pre><pre>}</pre><h3>Utilizing the Correlation ID in Backend Services</h3><p>Once the correlation ID is set by the Gateway, it is propagated to the backend services. This ID can then be used for logging and tracing throughout the service.</p><h4>Code Example in a Backend Controller:</h4><pre>package com.example.accounts.controller;</pre><pre>import com.example.accounts.dto.CustomerDetailsDto;<br>import com.example.accounts.dto.ErrorResponseDto;<br>import com.example.accounts.service.ICustomersService;<br>import io.swagger.v3.oas.annotations.Operation;<br>import io.swagger.v3.oas.annotations.media.Content;<br>import io.swagger.v3.oas.annotations.media.Schema;<br>import io.swagger.v3.oas.annotations.responses.ApiResponse;<br>import io.swagger.v3.oas.annotations.responses.ApiResponses;<br>import io.swagger.v3.oas.annotations.tags.Tag;<br>import jakarta.validation.constraints.Pattern;<br>import org.apache.http.HttpStatus;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.validation.annotation.Validated;<br>import org.springframework.web.bind.annotation.*;</pre><pre>@Tag(name = &quot;Customer API&quot;, description = &quot;APIs to fetch customer details&quot;)<br>@RestController<br>@RequestMapping(path=&quot;/api&quot;, produces = {MediaType.APPLICATION_JSON_VALUE})<br>@Validated<br>public class CustomerController {</pre><pre>    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);</pre><pre>    private final ICustomersService iCustomersService;</pre><pre>    public CustomerController(ICustomersService iCustomersService){<br>        this.iCustomersService = iCustomersService;<br>    }</pre><pre>    @Operation(summary = &quot;Fetch Customer Details&quot;, description = &quot;Fetch customer details based on a mobile number&quot;)<br>    @ApiResponses({<br>            @ApiResponse(responseCode = &quot;200&quot;, description = &quot;HTTP Status OK&quot;),<br>            @ApiResponse(responseCode = &quot;500&quot;, description = &quot;HTTP Status Internal Server Error&quot;, content = @Content(schema = @Schema(implementation = ErrorResponseDto.class)))<br>    })<br>    @GetMapping(&quot;/fetchCustomerDetails&quot;)<br>    public ResponseEntity&lt;CustomerDetailsDto&gt; fetchCustomerDetails(@RequestHeader(&quot;correlation-id&quot;) String correlationId,<br>                                                                    @RequestParam @Pattern(regexp=&quot;(^$|[0-9]{10})&quot;, message = &quot;Mobile number must be 10 digits&quot;)<br>                                                                    String mobileNumber) {<br>        logger.debug(&quot;Correlation ID found: {} &quot;, correlationId);<br>        CustomerDetailsDto customerDetailsDto = iCustomersService.fetchCustomerDetails(mobileNumber, correlationId);<br>        return ResponseEntity.status(HttpStatus.SC_OK).body(customerDetailsDto);</pre><pre>    }</pre><pre>}</pre><h3>Steps to Configure Spring Cloud Gateway as a Microservice</h3><p>To implement Spring Cloud Gateway in a microservices environment, you can follow these steps to set up a new Spring Boot project, register it with Eureka, and configure the necessary properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lyrky-vmKDbZKiVNDvDy-A.png" /></figure><p><em>Steps to configure a Spring Boot project as a microservice using Eureka, Spring Cloud Gateway, and other dependencies.</em></p><h3>Conclusion</h3><p>By implementing a GlobalFilter in Spring Cloud Gateway, you can efficiently manage tracing and logging across your microservices. The use of a correlation ID ensures that each request is uniquely identifiable, greatly simplifying debugging and enhancing the observability of your system. This approach helps you maintain a robust and reliable microservices architecture with minimal effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0444080ea7b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring GraalVM: A Modern Solution for High-Performance and Polyglot Applications]]></title>
            <link>https://medium.com/@uptoamir/exploring-graalvm-a-modern-solution-for-high-performance-and-polyglot-applications-8ea88d817cdf?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ea88d817cdf</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[jdk]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 23:34:28 GMT</pubDate>
            <atom:updated>2025-07-06T01:25:03.644Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving world of software development, finding a runtime that supports multiple languages, provides top-notch performance, and ensures efficient resource utilization is a developer’s dream. GraalVM, developed by Oracle, meets these needs by offering a versatile and powerful solution for both Java and non-Java languages. This article dives deep into what GraalVM is, how it operates, and the significant advantages it brings to the table.</p><h4>What is GraalVM?</h4><p>GraalVM is a high-performance runtime that provides support for multiple languages such as Java, JavaScript, Python, Ruby, R, and even languages like C and C++. It extends the Java Virtual Machine (JVM) by offering both Just-In-Time (JIT) and Ahead-Of-Time (AOT) compilation, giving developers the flexibility to optimize their applications for various needs.</p><h4>GraalVM Architecture: JIT vs. AOT</h4><p>GraalVM operates in two primary modes: Just-In-Time (JIT) compilation and Ahead-Of-Time (AOT) compilation. Each mode has its unique strengths, which can be chosen depending on the application’s requirements.</p><ul><li><strong>Just-In-Time (JIT) Compilation</strong>: JIT is traditionally how Java applications are executed on the JVM. The source code is compiled into bytecode, which is then interpreted and compiled into machine code at runtime. This process allows the runtime to optimize the code based on the actual execution patterns, leading to highly optimized performance.</li><li><strong>Ahead-Of-Time (AOT) Compilation</strong>: AOT compilation, on the other hand, compiles the application into a native executable before runtime. This approach significantly reduces the startup time, as the application is already in machine code when it begins execution. GraalVM’s AOT compilation is particularly beneficial for applications that require fast startup times, such as microservices or serverless functions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ov6QxbwG27XTNqevZKP4pw.png" /></figure><p>beautifully illustrate the differences between these two approaches:</p><ol><li><strong>Startup Process</strong>:</li></ol><ul><li>In JIT, several steps, such as class verification, interpreter logic, and profiling, are involved before the machine code is executed.</li><li>AOT eliminates these steps by loading native executable code directly from the disk, resulting in a faster startup.</li></ul><p>2. <strong>Memory and Packaging</strong>:</p><ul><li>JIT consumes more memory due to the need for dynamic code cache, runtime VM, and profiling feedback mechanisms.</li><li>AOT reduces memory consumption by eliminating these components, focusing only on the application machine code and payload, leading to compact packaging.</li></ul><h4>Key Benefits of GraalVM</h4><p>GraalVM offers a range of benefits that make it a compelling choice for modern software development:</p><ul><li><strong>Low Memory Consumption</strong>: As shown in the diagrams, GraalVM’s AOT compilation significantly reduces memory usage by stripping away unnecessary components from the final executable. This lean execution model is ideal for environments where resource efficiency is critical.</li><li><strong>Compact Packaging</strong>: AOT compilation also leads to smaller, more portable application packages. Since GraalVM doesn’t include the traditional JVM components in AOT mode, the resulting executables are much lighter, making distribution and deployment easier.</li><li><strong>Reduced Attack Surface</strong>: Security is a critical concern in today’s software landscape. GraalVM enhances security by including only the code that is reachable by the application in the final image. Features like reflection and deserialization, which can introduce vulnerabilities, are disabled unless explicitly configured, reducing the attack surface.</li><li><strong>Polyglot Support</strong>: One of GraalVM’s standout features is its polyglot capabilities. Developers can run code from multiple languages in a single application, allowing them to mix and match languages like Java, Python, JavaScript, and even C/C++. This flexibility makes GraalVM an excellent choice for projects that require different languages to handle different tasks efficiently.</li></ul><h4>Conclusion</h4><p>GraalVM represents a significant step forward in runtime environments, offering developers the flexibility to choose between JIT and AOT compilation based on their application’s needs. Its polyglot support, low memory consumption, compact packaging, and enhanced security features make it an invaluable tool for building modern, high-performance applications.</p><p>Whether you’re working on microservices, serverless functions, or complex polyglot applications, GraalVM provides the tools you need to maximize performance while minimizing resource usage. As the demand for versatile and efficient runtime environments continues to grow, GraalVM is poised to play a pivotal role in the future of software development.</p><p>Watch this video: <a href="https://www.youtube.com/watch?v=SISjh1krECE">https://www.youtube.com/watch?v=SISjh1krECE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ea88d817cdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eureka Self-Preservation Mode: A Solution to Avoid Network Trap Issues]]></title>
            <link>https://medium.com/@uptoamir/eureka-self-preservation-mode-a-solution-to-avoid-network-trap-issues-1362650e1953?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/1362650e1953</guid>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[self-preservation]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 23:29:28 GMT</pubDate>
            <atom:updated>2025-07-06T01:26:20.814Z</atom:updated>
            <content:encoded><![CDATA[<p>In a distributed microservices environment, ensuring that services remain available and resilient despite network issues is critical. Spring Cloud’s Netflix Eureka server provides a robust solution through its Self-Preservation mode, which helps prevent unnecessary evictions of healthy service instances during temporary network glitches. This article explores how Eureka’s Self-Preservation mode works and how it mitigates network trap issues.</p><h4>Understanding Eureka Self-Preservation Mode</h4><p>Eureka is a service registry that helps microservices locate each other. In a typical setup, each service instance periodically sends a heartbeat signal to the Eureka server to indicate that it is still alive and functioning. If the Eureka server doesn’t receive a heartbeat from a service instance within a certain timeframe, it assumes that the instance has become unresponsive or has crashed.</p><p><strong>1. Self-Preservation Mode Activation</strong></p><p>However, in some cases, network glitches or temporary delays can cause the Eureka server to miss heartbeats from healthy service instances. This situation can lead to the false expiration of service instances, resulting in unnecessary evictions that disrupt the system’s stability.</p><p>To address this challenge, Eureka enters Self-Preservation mode. When Self-Preservation mode is active, the existing registry entries will not be removed even if the server stops receiving heartbeats from some service instances. This prevents Eureka from mistakenly evicting all instances due to temporary network issues.</p><p><strong>2. Healthy Microservices System Before Network Problems</strong></p><h4>How Self-Preservation Mode Works</h4><p>In Self-Preservation mode, Eureka continues to serve the registered instances to client applications, even if it suspects that some instances are no longer available. This ensures that clients can still discover and interact with the available instances, maintaining the stability and availability of the service registry.</p><p><strong>3. Service Instances Entering Self-Preservation Mode Due to Network Glitches</strong></p><p>The Self-Preservation mode never expires until the downed microservices are either brought back online or the network glitch is resolved. Eureka will not expire the instances until the situation meets the configured threshold limit.</p><p><strong>4. Behavior During Self-Preservation Mode</strong></p><p>This feature is a lifesaver in environments where network glitches are common, helping to handle false-positive alarms and preventing unnecessary disruptions.</p><h4>Key Configurations for Self-Preservation Mode</h4><p>Eureka’s behavior in Self-Preservation mode is influenced by several configuration parameters:</p><p><strong>5. Key Configuration Parameters for Eureka Self-Preservation</strong></p><ul><li><strong>eureka.instance.lease-renewal-interval-in-seconds</strong>: The frequency with which a client sends heartbeats to the server to indicate it is still alive.</li><li><strong>eureka.instance.lease-expiration-duration-in-seconds</strong>: The duration the server waits since receiving the last heartbeat before it can expire an instance.</li><li><strong>eureka.server.eviction-interval-timer-in-ms</strong>: A scheduler that runs at this frequency to evict instances from the registry if their lease has expired.</li><li><strong>eureka.server.renewal-percent-threshold</strong>: The expected percentage of heartbeats per minute that Eureka anticipates.</li><li><strong>eureka.server.renewal-threshold-update-interval-ms</strong>: The frequency at which the expected heartbeats per minute are recalculated.</li><li><strong>eureka.server.enable-self-preservation</strong>: By default, this is set to true, enabling Self-Preservation mode. It can be disabled if necessary.</li></ul><h4>Conclusion</h4><p>Eureka’s Self-Preservation mode is an essential feature that enhances the resilience of a microservices architecture by preventing unnecessary service instance evictions during temporary network issues. By understanding and configuring Self-Preservation mode correctly, developers can ensure that their services remain available and stable even in the face of network disruptions.</p><p>This feature is a critical component of building robust and fault-tolerant microservices applications, particularly in cloud-native environments where network reliability can be variable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1362650e1953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Traditional Load Balancer vs.]]></title>
            <link>https://medium.com/@uptoamir/traditional-load-balancer-vs-c7708d74c827?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7708d74c827</guid>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[feign]]></category>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 22:58:22 GMT</pubDate>
            <atom:updated>2025-07-06T01:27:13.255Z</atom:updated>
            <content:encoded><![CDATA[<h3>Traditional Load Balancer vs. Cloud-Native Load Balancer (Spring Cloud Netflix Eureka and Netflix Feign Client): A Deep Dive</h3><p>In the world of microservices, efficient communication between services is crucial. Traditionally, load balancers have played a vital role in managing this communication, but as cloud-native technologies have emerged, the approach to load balancing has evolved. This article delves into the differences between traditional load balancers and cloud-native load balancers, exploring their respective architectures, challenges, and benefits.</p><h4>Traditional Load Balancers: A Static Approach</h4><p>In traditional setups, load balancers are essential for directing traffic between microservices. Here’s how they typically work:</p><ol><li><strong>Communication Between Microservices Using Traditional Load Balancers</strong></li></ol><ul><li><strong>Static IP Assignment</strong>: Each microservice instance is assigned a static IP address. The load balancer uses these IP addresses to route traffic.</li><li><strong>DNS-based Load Balancing</strong>: Load balancers often use DNS records to resolve service names to IP addresses. In the case of multiple service instances, DNS records might include multiple IP addresses, and a round-robin strategy is employed to distribute traffic.</li></ul><p><strong>2. Traditional Service Location Resolution Architecture Using DNS and a Load Balancer</strong></p><p><strong>Challenges:</strong></p><ul><li><strong>Ephemeral Nature of Services</strong>: Traditional load balancers struggle with the dynamic nature of modern cloud environments where service instances can start, stop, or be replaced frequently. Manually updating DNS records or load balancer configurations to accommodate these changes is impractical and error-prone.</li><li><strong>Single Point of Failure</strong>: If the primary load balancer fails, all traffic might be disrupted unless a backup load balancer is in place.</li><li><strong>Scalability Limitations</strong>: Traditional load balancers have limitations in scaling horizontally. The costs associated with additional licenses and infrastructure can be prohibitive.</li><li>Cloud-Native Load Balancers: A Dynamic Approach</li></ul><p>Cloud-native applications leverage the dynamic and scalable nature of cloud environments, employing advanced load balancing techniques more suited to microservices architectures:</p><ol><li><strong>Cloud-Native Load Balancer Architecture Using Service Discovery</strong></li></ol><ul><li><strong>Service Discovery</strong>: In cloud-native environments, services register themselves with a service registry (like Eureka, Consul, or Zookeeper) during startup. The registry keeps track of all running instances and their respective IP addresses.</li><li><strong>Dynamic Load Balancing</strong>: Instead of relying on static IP addresses, cloud-native load balancers use the information from the service registry to distribute traffic dynamically. When a service needs to communicate with another service, it queries the service registry to get the current IP addresses and selects one based on a load-balancing strategy (e.g., round-robin, least connections, etc.).</li></ul><p><strong>2. Cloud-Native Service Discovery and Load Balancing Workflow</strong></p><ul><li><strong>Client-Side Caching</strong>: Some cloud-native architectures include client-side caching of service instances’ IP addresses to reduce the latency of querying the service registry.</li><li><strong>Fault Tolerance and Resilience</strong>: If a service instance becomes unavailable, the service registry stops sending its IP address to clients, ensuring that traffic is only directed to healthy instances.</li></ul><p><strong>Benefits:</strong></p><ul><li><strong>Scalability</strong>: Cloud-native load balancers are inherently scalable, dynamically adjusting to the number of service instances as they scale up or down.</li><li><strong>No Single Point of Failure</strong>: The distributed nature of service discovery and load balancing in cloud-native setups eliminates the single point of failure.</li><li><strong>Automatic Failover</strong>: In case of a service instance failure, traffic is seamlessly redirected to other instances, ensuring high availability.</li></ul><h4>Conclusion</h4><p>The transition from traditional to cloud-native load balancers marks a significant evolution in handling service-to-service communication in microservices architectures. Traditional load balancers, while reliable in static environments, fall short in the dynamic, scalable world of cloud-native applications. Cloud-native load balancers, with their dynamic service discovery and load balancing capabilities, offer a more robust, scalable, and resilient solution for modern applications.</p><p><strong>Advantages of Cloud-Native Service Discovery and Load Balancing</strong></p><p><strong>Client-Side Service Discovery in a Cloud-Native Environment</strong></p><p><strong>Service Discovery Node and Load Balancing Layer in Cloud-Native Architecture</strong></p><p><strong>Spring Cloud Components for Service Discovery and Registration</strong></p><p>As you consider your architecture, understanding these differences will guide you in selecting the right load balancing strategy to meet your application’s needs, ensuring that your services are always available, scalable, and resilient in the face of failure.</p><h3>Spring Cloud Netflix Eureka and Netflix Feign Client</h3><p>To implement cloud-native service discovery and client-side load balancing, Spring Cloud offers several components, notably:</p><ul><li><strong>Spring Cloud Netflix Eureka</strong>: This is a service registry that enables services to register themselves at runtime and discover other services for communication.</li><li><strong>Netflix Feign Client</strong>: Feign is a declarative HTTP client developed by Netflix, which integrates seamlessly with Eureka. It simplifies calling services registered with Eureka by abstracting the complexities of service discovery and communication.</li></ul><p>These tools, along with other Spring Cloud components like the Spring Cloud Load Balancer, make it easier to develop and manage cloud-native microservices, ensuring efficient and reliable communication between services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7708d74c827" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing ShExCraft: Compile Your Shell Scripts into Executable Files]]></title>
            <link>https://medium.com/@uptoamir/introducing-shexcraft-compile-your-shell-scripts-into-executable-files-7dfde868fd77?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfde868fd77</guid>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[exe]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 18:18:01 GMT</pubDate>
            <atom:updated>2024-08-22T18:18:01.014Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplifying Shell Script Execution on Windows</h3><p>Shell scripts are an indispensable tool for automating tasks, managing systems, and simplifying complex workflows. However, running these scripts across different platforms, particularly on Windows, can be a challenge. That’s where ShExCraft comes in — an innovative tool that allows you to convert your shell scripts into .exe files, making them easy to execute on Windows systems.</p><p>In this article, I’ll walk you through the key features of ShExCraft, how to get started with it, and how it can simplify your shell scripting tasks, especially if you’re working in a cross-platform environment.</p><h3>What is ShExCraft?</h3><p>ShExCraft is a Rust-based tool that transforms shell scripts (.sh files) into executable files (.exe) on Windows. It’s designed to ensure that your scripts can be easily executed across different environments without worrying about the underlying shell environment or the availability of specific commands. ShExCraft also provides robust error handling, helping you identify and fix issues before they become a problem.</p><p>You can check out the source code and contribute to the project on <a href="https://github.com/uptoamir/ShExCraft">GitHub</a>.</p><h3>Key Features</h3><ul><li><strong>Parse Shell Scripts</strong>: ShExCraft converts your shell scripts into an Abstract Syntax Tree (AST), making them easier to analyze and compile.</li><li><strong>Compile to Bytecode</strong>: The AST is then transformed into bytecode, ready for further processing or execution.</li><li><strong>Compile to .EXE</strong>: The standout feature — ShExCraft generates .exe files from your shell scripts, enabling easy execution on Windows.</li><li><strong>Run Shell Scripts</strong>: If you prefer, you can run your shell scripts directly with ShExCraft, benefiting from its detailed error reporting.</li><li><strong>Error Handling</strong>: ShExCraft provides precise error messages for syntax errors, missing commands, and other issues, making debugging a breeze.</li></ul><h3>Getting Started with ShExCraft</h3><h3>Installation</h3><p>Before you can use ShExCraft, you’ll need to ensure a few prerequisites are met:</p><ol><li><strong>Rust</strong>: Make sure Rust is installed on your system. You can install Rust from the official <a href="https://www.rust-lang.org/">Rust website</a>.</li><li><strong>Mingw-w64</strong>: If you’re on a Unix-like system, you’ll need mingw-w64 for cross-compiling to .exe:</li></ol><pre>sudo apt-get install mingw-w64</pre><p>Next, clone the ShExCraft repository from GitHub:</p><pre>git clone https://github.com/uptoamir/ShExCraft.git<br>cd ShExCraft</pre><p>Build the project using Cargo:</p><pre>cargo build --release</pre><h3>Usage</h3><p>With ShExCraft installed and built, you can start using it to compile and run your shell scripts.</p><h4>Compiling a Shell Script</h4><p>To compile a shell script into bytecode:</p><pre>./target/release/shexcraft compile your_script.sh</pre><h4>Running a Shell Script</h4><p>To run a shell script with ShExCraft:</p><pre>./target/release/shexcraft run your_script.sh</pre><h4>Compiling to .EXE</h4><p>To compile a shell script directly into an executable .exe file:</p><pre>./target/release/shexcraft compile_to_exe your_script.sh</pre><p>This will generate a your_script.exe file in the current directory, which you can run on a Windows system.</p><h3>Example: Creating and Running a Shell Script</h3><p>Let’s walk through an example to see ShExCraft in action.</p><h3>Example Shell Script (example.sh)</h3><pre>#!/bin/bash<br>echo &quot;Welcome to ShExCraft!&quot;<br>mkdir new_directory<br>cd new_directory<br>touch file1.txt file2.txt<br>echo &quot;Files created successfully&quot;</pre><p>This simple script creates a directory, navigates into it, creates two files, and prints a success message.</p><h3>Example Commands</h3><ol><li><strong>Compile the script to bytecode:</strong></li></ol><pre>./target/release/shexcraft compile example.sh</pre><ol><li><strong>Run the script with error handling:</strong></li></ol><pre>./target/release/shexcraft run example.sh</pre><ol><li><strong>Compile the script to </strong><strong>.exe:</strong></li></ol><pre>./target/release/shexcraft compile_to_exe example.sh</pre><h3>Handling Errors with ShExCraft</h3><p>One of ShExCraft’s standout features is its detailed error reporting. If there’s an issue in your script — such as a command failing due to a missing file or directory — ShExCraft will pinpoint the problem and provide a clear error message. For example:</p><pre>Error: Interpreter error</pre><pre>Caused by:<br>    Command failed: mkdir new_directory<br>    error: File exists</pre><p>This helps you quickly identify and resolve issues, ensuring your scripts run smoothly.</p><h3>Conclusion</h3><p>ShExCraft is a powerful tool for developers and system administrators who rely on shell scripts and need a reliable way to execute them on Windows. Whether you’re compiling scripts into bytecode or creating .exe files, ShExCraft simplifies the process and provides the error handling you need to ensure your scripts are robust and ready for production.</p><p>Ready to give ShExCraft a try? Head over to the <a href="https://github.com/uptoamir/ShExCraft">GitHub repository</a> to get started!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfde868fd77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refresh Configurations at Runtime with Spring Cloud Bus: A Practical Guide]]></title>
            <link>https://medium.com/@uptoamir/refresh-configurations-at-runtime-with-spring-cloud-bus-a-practical-guide-38a7f739eca6?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/38a7f739eca6</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[spring-cloud-bus]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 21:02:45 GMT</pubDate>
            <atom:updated>2025-07-06T01:29:03.800Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing configuration changes in a distributed system can be tricky. Spring Cloud Config provides a centralized way to handle this, but applying changes across multiple instances can be challenging. Enter Spring Cloud Bus, which lets you propagate configuration changes instantly across your entire system, using the /actuator/busrefresh endpoint.</p><h4>What is Spring Cloud Bus?</h4><p>Spring Cloud Bus connects your microservices using a message broker like RabbitMQ or Kafka. This allows your services to broadcast events, like configuration updates, across the entire system. It’s a simple yet powerful way to keep all your services in sync without restarting them.</p><h4>Setting Up Spring Cloud Bus</h4><ol><li><strong>Add Dependencies</strong>: Make sure your project has the necessary dependencies in your pom.xml or build.gradle file.</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-bus-amqp&lt;/artifactId&gt; &lt;!-- or spring-cloud-starter-bus-kafka --&gt;<br>&lt;/dependency&gt;</pre><p><strong>2. Configure Your Message Broker</strong>: Set up RabbitMQ or Kafka in your application.yml.(this is default RMQ config, so it is optional)</p><p>For RabbitMQ:</p><pre>spring:<br>  rabbitmq:<br>    host: localhost<br>    port: 5672<br>    username: guest<br>    password: guest</pre><p>For Kafka:</p><pre>spring:<br>  kafka:<br>    bootstrap-servers: localhost:9092</pre><p><strong>3. Expose the </strong><strong>/actuator/busrefresh Endpoint</strong>: By default, this endpoint isn’t exposed, so you need to enable it in your configuration.</p><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: busrefresh</pre><h4>Using /actuator/busrefresh</h4><p>Once everything is set up, you can trigger a configuration refresh across all your services by sending a POST request to the /actuator/busrefresh endpoint on any instance.</p><pre>curl -X POST http://localhost:8080/actuator/busrefresh</pre><p>This command sends a refresh event to the message broker, which then propagates it to all connected services. Each service instance will reload its configuration without restarting, ensuring that all your microservices are updated simultaneously.</p><h4>Automating Configuration Refresh with Git Hooks and Spring Cloud Config Monitor</h4><p>Spring Cloud Config Monitor can automatically detect configuration changes and trigger a refresh event. When combined with a Git webhook via Hookdeck, this creates an automated pipeline where configuration changes in your Git repository trigger updates across your services.</p><ol><li><strong>Set Up GitHub Webhook</strong>: Configure a webhook in your GitHub repository that triggers when changes are pushed. Point this webhook to Hookdeck, which will then relay the request to your Spring Cloud Config Server.</li><li><strong>Configure Hookdeck</strong>: In Hookdeck, set up the webhook to forward GitHub events to the /monitor endpoint of your Spring Cloud Config Server.</li></ol><ul><li><strong>GitHub Webhook</strong>: Configure your GitHub webhook to point to your Hookdeck endpoint. Choose to trigger the webhook on push events.</li><li><strong>Hookdeck Setup</strong>: In Hookdeck, configure the incoming webhook to make a POST request to your Config Server’s /monitor endpoint:</li></ul><pre>https://your-config-server-url/monitor</pre><ul><li><strong>Triggering the </strong><strong>/monitor Endpoint</strong>: When you push changes to your GitHub repository, the webhook will trigger Hookdeck, which will then call the /monitor endpoint on your Spring Cloud Config Server. This endpoint listens for change events and broadcasts them using Spring Cloud Bus.</li><li>The /monitor endpoint is designed to listen for SCM (Source Control Management) events. When it detects a change (e.g., a push to your GitHub repository), it triggers a refresh across all services that are connected via Spring Cloud Bus.</li></ul><p>For a deeper dive into Spring Cloud Config’s push notifications and Spring Cloud Bus, check out the <a href="https://docs.spring.io/spring-cloud-config/reference/server/push-notifications-and-bus.html">official documentation</a>.</p><p>and now you may ask yourself why we didn’t use busrefresh as webhook ?</p><p>Spring Cloud Bus needs someone to trigger /busrefresh manually to communicate about the config change to all the applicable services where as <strong>Spring Cloud Monitor exposes the</strong> <strong>/monitor path which can be invoked using webhooks that in-turns invoke the /busrefresh path</strong>. <strong>/busrefresh doesn’t support invoking directly from webhooks</strong>.</p><h4>Advantages</h4><ul><li><strong>Instant Updates</strong>: Apply configuration changes across all instances instantly without downtime.</li><li><strong>Consistency</strong>: Ensure that all services operate with the same configuration, reducing potential discrepancies.</li><li><strong>Ease of Use</strong>: Managing configurations becomes simpler and more efficient, especially in large, distributed systems.</li></ul><h4>Potential Drawbacks</h4><ul><li><strong>Security Risks</strong>: Exposing the /actuator/busrefresh endpoint can be a security risk if not properly secured. Always restrict access to this endpoint.</li><li><strong>Performance Considerations</strong>: Frequent refreshes might impact performance, especially in large systems. Use this feature judiciously to avoid unnecessary load on your services and message broker.</li></ul><h4>Conclusion</h4><p>Spring Cloud Bus with the /actuator/busrefresh endpoint offers a seamless way to manage configuration changes in a distributed environment. By enabling real-time updates without restarting services, it keeps your microservices architecture agile and responsive.</p><p>However, with great power comes great responsibility — ensure you secure the endpoint and monitor its usage to avoid potential performance hits. With these considerations in mind, you can effectively manage your configurations, keeping your system stable, secure, and always up-to-date.</p><h4>Images Right</h4><p>All image rights belong to eazybytes.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a7f739eca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refreshing Configurations at Runtime with Spring Boot’s Actuator]]></title>
            <link>https://medium.com/@uptoamir/refreshing-configurations-at-runtime-with-spring-boots-actuator-18e14cfdf09d?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/18e14cfdf09d</guid>
            <category><![CDATA[actuator]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 19:27:52 GMT</pubDate>
            <atom:updated>2025-07-06T01:29:49.205Z</atom:updated>
            <content:encoded><![CDATA[<p>In microservices, it’s common to need configuration changes without restarting the app. Spring Boot makes this easy with its Actuator /actuator/refresh endpoint, which allows you to reload your configs on the fly.</p><h3>Quick Setup</h3><p>First, add the Spring Cloud Config and Actuator dependencies to your project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Next, configure your application.yml to expose the refresh endpoint:</p><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: refresh</pre><p>Now, anytime you need to refresh your configuration, just send a POST request (you can do it with Postman too) to /actuator/refresh:</p><pre>curl -X POST http://localhost:8080/actuator/refresh</pre><h3>When to Use It</h3><p>This is handy for situations like:</p><ul><li><strong>Feature Toggles:</strong> Instantly enable or disable features.</li><li><strong>API Updates:</strong> Change API endpoints or credentials without a restart.</li><li><strong>Debugging:</strong> Adjust logging levels in real-time.</li></ul><h3>The Catch</h3><p>But here’s the drawback: if you have a large microservices setup, say 100 services, manually calling the /actuator/refresh endpoint for each one isn&#39;t practical. It can become a maintenance headache. Automating this process or looking into centralized configuration management might be necessary for larger systems.</p><h3>Conclusion</h3><p>Using the Actuator’s refresh endpoint is a simple and effective way to keep your applications flexible and responsive. Just be mindful of the scale of your system, as refreshing configurations manually can get cumbersome as the number of services grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18e14cfdf09d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Configuration Management in Spring Boot with Spring Cloud Config Server]]></title>
            <link>https://medium.com/@uptoamir/mastering-configuration-management-in-spring-boot-with-spring-cloud-config-server-9f0af9c9761d?source=rss-96839de87430------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f0af9c9761d</guid>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <category><![CDATA[configuration-management]]></category>
            <dc:creator><![CDATA[Andrew Khoshbin]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 19:25:10 GMT</pubDate>
            <atom:updated>2024-08-18T00:00:46.376Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>As applications grow in complexity, managing configuration across multiple environments becomes challenging. Spring Boot, when combined with Spring Cloud Config Server, offers a powerful solution to manage configurations centrally. This article will focus on using GitHub as a configuration source, including how to handle sensitive data securely, while also touching on the benefits of using the classpath and file system for configuration management.</p><h3>12-Factor App Principle — Config</h3><p>This principle states that applications should store configuration in the environment rather than in the code. Config includes everything that can vary between deploys: credentials, resource handles, and application behavior configurations. By externalizing configurations, you can manage different environments (e.g., development, staging, production) without altering the codebase. so you won’t build different images for different environments and multi-stage apps.</p><h3>Spring Cloud Config and the 12-Factor App</h3><ul><li><strong>Centralized Configuration</strong>: Spring Cloud Config helps you externalize configuration, maintaining it in a central repository (often Git), which supports the 12-Factor App’s approach to separating config from the code.</li><li><strong>Environment-Specific Settings</strong>: With Spring Cloud Config, you can manage different configurations for different environments, which are dynamically injected at runtime.</li><li><strong>Dynamic Reloading</strong>: If enabled, your application can reload configurations without needing to be redeployed, adhering to the 12-Factor principle of managing config separately and avoiding hard-coding environment-specific values.</li></ul><p>In essence, Spring Cloud Config makes it easier to implement the 12-Factor Config principle by providing a flexible and scalable way to manage configurations across various environments.</p><h3>Configuration Management Approaches in Spring Boot</h3><p>Spring Boot provides several ways to manage configurations, each suited to different scenarios:</p><ol><li><strong>Classpath Configurations</strong>: Configurations are often stored in the application.yml or application.properties files within the resources directory. This method is ideal for development because the configurations are bundled with the application.</li><li><strong>File System Configurations</strong>: Spring Boot allows you to load configuration files from external locations, such as a /config directory relative to the application or directly from the working directory. This method is useful for separating configuration from the application code, especially in different environments like production or staging. One key advantage of this approach is <strong>access level control</strong>, ensuring that only authorized users can modify or access sensitive configurations.</li><li><strong>GitHub Configurations with Spring Cloud Config Server</strong>: This method centralizes configuration management by storing configuration files in a GitHub repository, offering benefits like version control, security, and easy collaboration across teams. The primary advantage of using GitHub is <strong>tracking the history of configurations</strong>, which allows teams to see changes over time, revert to previous versions, and collaborate more effectively.</li></ol><h3>GitHub Example for Spring Boot Configuration</h3><h4>Step-by-Step GitHub Configuration Example:</h4><ol><li><strong>Create a Configuration Repository</strong>:</li></ol><ul><li>Create a GitHub repository (e.g., spring-config-repo) where you will store your configuration files.</li><li>Add your configuration files like application.yml, application-dev.yml, application-prod.yml, etc.</li></ul><p>Example application.yml in the GitHub repository:</p><pre>server:<br>  port: 8080<br>logging:<br>  level:<br>    root: INFO<br>app:<br>  name: MySpringApp<br>  secret-key: {cipher}AQB5k...</pre><p>2. <strong>Encrypt Sensitive Data</strong>:</p><ul><li>Use Spring Cloud’s encryption utility to encrypt sensitive information, like secret-key.</li><li>The encrypted value is prefixed with {cipher} to indicate that it’s encrypted.</li></ul><p>Example command to encrypt a secret key:</p><pre>$ encrypt my-secret-key --key my-encryption-key</pre><p>The result will be an encrypted string, e.g., AQB5k..., which you then place in your configuration file.</p><p><strong>3. Set Up Spring Cloud Config Server</strong>:</p><ul><li>Configure your Spring Cloud Config Server to point to your GitHub repository.</li></ul><p>Example application.yml for Config Server:</p><pre>spring:<br>  cloud:<br>    config:<br>      server:<br>        git:<br>          uri: https://github.com/your-username/spring-config-repo<br>          clone-on-start: true</pre><p>This setup tells the Config Server to clone the GitHub repository and serve the configuration files stored there.</p><p><strong>4. Spring Boot Application Configuration</strong>:</p><ul><li>In your Spring Boot application, configure it to use the Config Server.</li></ul><p>Example bootstrap.yml in the Spring Boot application:</p><pre>spring:<br>  application:<br>    name: MySpringApp<br>  cloud:<br>    config:<br>      uri: http://localhost:8888<br>      name: MySpringApp</pre><p>This setup tells your Spring Boot application to fetch its configuration from the Config Server, which pulls the configuration from the GitHub repository.</p><p><strong>5. Running the Application</strong>:</p><ul><li>When you start your Spring Boot application, it will connect to the Config Server, which will fetch the configurations from the GitHub repository.</li><li>The Config Server automatically decrypts any properties prefixed with {cipher}.</li></ul><h3>Conclusion</h3><p>Using Spring Cloud Config Server with GitHub allows for centralized, secure, and version-controlled configuration management across multiple environments. By leveraging GitHub, you gain the advantage of tracking the history of your configurations, making it easy to manage changes over time. On the other hand, managing configurations through the file system offers enhanced access level control, which is critical for ensuring that sensitive configurations are protected. Whether you’re managing configurations for development, staging, or production, these approaches provide the flexibility, security, and ease of management needed for modern application development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f0af9c9761d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>