<?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 Sandeep Vishnu on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Vishnu on Medium]]></description>
        <link>https://medium.com/@sandeepkv93?source=rss-e07cf368a458------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-VI3-zQ5R0UGCy-Bo1o3ig.jpeg</url>
            <title>Stories by Sandeep Vishnu on Medium</title>
            <link>https://medium.com/@sandeepkv93?source=rss-e07cf368a458------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:01:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeepkv93/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[Building a Production-Ready Auto-Scaling Web Application with Kubernetes]]></title>
            <link>https://medium.com/@sandeepkv93/building-a-production-ready-auto-scaling-web-application-with-kubernetes-75c8a8ce6343?source=rss-e07cf368a458------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c8a8ce6343</guid>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[horizontal-pod-autoscaler]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sandeep Vishnu]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 20:05:57 GMT</pubDate>
            <atom:updated>2025-07-21T21:05:52.804Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how modern applications handle sudden traffic spikes without breaking a sweat? Today, let’s walk through building a complete auto-scaling web application using Kubernetes, Go, React, and some really cool automation. By the end of this guide, you’ll have a production-ready system that automatically spins up new server instances when traffic increases and scales back down when things quiet down.</p><h3>What We’re Building</h3><p>We’re creating a modern 3-tier web application that demonstrates the power of Kubernetes Horizontal Pod Autoscaling (HPA). Here’s what makes this special:</p><ul><li>Frontend: React application served by nginx with intelligent API proxying</li><li>Backend: Go API server using the latest HTTP routing features (Go 1.24+)</li><li>Database Layer: PostgreSQL for data persistence and Redis for high-performance caching</li><li>Auto-scaling: Kubernetes HPA that automatically adjusts based on CPU and memory usage</li><li>Load Testing: Built-in stress testing to see auto-scaling in action</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3J3MSx_z4aFvnhXmFvghKw.png" /></figure><h3>Chapter 1: Setting Up the Development Environment</h3><p>Before we dive into the code, let’s get our development environment ready. We’ll need:</p><ul><li>Docker Desktop: For containerization</li><li>kubectl: Kubernetes command-line tool</li><li>kind: Kubernetes in Docker (perfect for local development)</li><li>task: Task runner for automation (optional but highly recommended)</li></ul><h3>Creating Our Project Structure</h3><p>Let’s start by creating a well-organized project structure:</p><pre>mkdir kubernetes-autoscale-webapp<br>cd kubernetes-autoscale-webapp# Create our main directories<br><br>mkdir -p {backend,frontend,k8s,scripts}<br>mkdir -p k8s/{backend,frontend,database,redis,ingress,configmaps,secrets}<br>mkdir -p backend/{config,handlers,models}<br>mkdir -p frontend/src/{components,services}</pre><p>This structure keeps everything organized and makes it easy to navigate as our project grows.</p><h3>Chapter 2: Building the Go Backend</h3><p>The heart of our application is a modern Go API server. I chose Go 1.24 specifically because it includes fantastic new HTTP routing features that eliminate the need for external router libraries.</p><h3>Creating the Main Application</h3><p>Let’s start with our backend/main.go:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;database/sql&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br><br> &quot;k8s-autoscale-webapp/config&quot;<br> &quot;k8s-autoscale-webapp/handlers&quot;<br><br> &quot;github.com/go-redis/redis/v8&quot;<br> _ &quot;github.com/lib/pq&quot;<br>)<br><br>func main() {<br> // Load configuration<br> cfg := config.Load()<br> ctx := context.Background()<br><br> // Initialize database<br> db, err := initDB(cfg.DatabaseConfig)<br> if err != nil {<br>  log.Fatal(&quot;Failed to initialize database:&quot;, err)<br> }<br> defer db.Close()<br><br> // Initialize Redis<br> rdb, err := initRedis(cfg.RedisConfig, ctx)<br> if err != nil {<br>  log.Printf(&quot;Redis connection failed: %v&quot;, err)<br> } else {<br>  log.Println(&quot;Redis connected successfully&quot;)<br>  defer rdb.Close()<br> }<br><br> // Initialize handlers<br> healthHandler := handlers.NewHealthHandler(db, rdb, ctx)<br> userHandler := handlers.NewUserHandler(db, rdb, ctx)<br> stressHandler := handlers.NewStressHandler()<br><br> // Create a new ServeMux<br> mux := http.NewServeMux()<br><br> // Health check endpoint<br> mux.Handle(&quot;GET /health&quot;, healthHandler)<br> mux.Handle(&quot;GET /api/health&quot;, healthHandler)<br><br> // User endpoints using Go 1.22+ pattern matching<br> mux.HandleFunc(&quot;GET /api/users&quot;, userHandler.GetUsers)<br> mux.HandleFunc(&quot;POST /api/users&quot;, userHandler.CreateUser)<br> mux.HandleFunc(&quot;GET /api/users/{id}&quot;, userHandler.GetUser)<br><br> // Stress test endpoint<br> mux.Handle(&quot;GET /api/stress&quot;, stressHandler)<br><br> // Wrap with CORS middleware<br> handler := handlers.CORSMiddleware(mux)<br><br> log.Printf(&quot;Server starting on port %s...&quot;, cfg.ServerConfig.Port)<br> log.Fatal(http.ListenAndServe(&quot;:&quot;+cfg.ServerConfig.Port, handler))<br>}</pre><p>Notice how clean this is! The new Go 1.24 HTTP routing lets us write GET /api/users/{id} directly in the router registration. No more external dependencies for basic routing.</p><h3>Configuration Management</h3><p>Smart configuration is crucial for a cloud-native application. Here’s our backend/config/config.go:</p><pre>package config<br>import (<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>)<br>type Config struct {<br>    DatabaseConfig DatabaseConfig<br>    RedisConfig RedisConfig<br>    ServerConfig ServerConfig<br>}<br>type DatabaseConfig struct {<br>    Host string<br>    Port string<br>    User string<br>    Password string<br>    DBName string<br>}<br>func Load() * Config {<br>    return &amp;Config {<br>        DatabaseConfig: DatabaseConfig {<br>            Host: getEnv(&quot;DB_HOST&quot;, &quot;localhost&quot;),<br>            Port: getEnv(&quot;DB_PORT&quot;, &quot;5432&quot;),<br>            User: getEnv(&quot;DB_USER&quot;, &quot;postgres&quot;),<br>            Password: getEnv(&quot;DB_PASSWORD&quot;, &quot;&quot;),<br>            DBName: getEnv(&quot;DB_NAME&quot;, &quot;webapp&quot;),<br>        },<br>        RedisConfig: RedisConfig {<br>            Host: getEnv(&quot;REDIS_HOST&quot;, &quot;localhost&quot;),<br>            Port: getEnv(&quot;REDIS_PORT&quot;, &quot;6379&quot;),<br>            Password: getEnv(&quot;REDIS_PASSWORD&quot;, &quot;&quot;),<br>            DB: 0,<br>        },<br>        ServerConfig: ServerConfig {<br>            Port: getEnv(&quot;SERVER_PORT&quot;, &quot;8080&quot;),<br>        },<br>    }<br>}<br>func getEnv(key, defaultValue string) string {<br>    if value: = os.Getenv(key);<br>    value != &quot;&quot; {<br>        return value<br>    }<br>    return defaultValue<br>}</pre><p>This configuration system works seamlessly in both development (with defaults) and production (with environment variables).</p><h3>The Secret Sauce: Stress Testing Handler</h3><p>Here’s where it gets interesting. To demonstrate auto-scaling, we need a way to generate CPU load. Our backend/handlers/stress.go does exactly that:</p><pre>package handlers<br>import (<br>    &quot;encoding/json&quot;<br>    &quot;net/http&quot;<br>    &quot;k8s-autoscale-webapp/models&quot;<br>)<br>type StressHandler struct {}<br>func NewStressHandler() * StressHandler {<br>    return &amp;StressHandler {}<br>}<br>func(h * StressHandler) ServeHTTP(w http.ResponseWriter, r * http.Request) {<br>    // CPU intensive operation for testing HPA<br>    iterations: = 100000000<br>    result: = 0<br>    for i: = 0;i &lt; iterations;i++{<br>        result += i<br>    }<br>    response: = models.StressTestResponse {<br>        Message: &quot;Stress test completed&quot;,<br>        Result: result,<br>        Iterations: iterations,<br>    }<br>    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    json.NewEncoder(w).Encode(response)<br>}</pre><p>This endpoint deliberately consumes CPU cycles, which will trigger our auto-scaling mechanism. In a real application, you might see similar patterns during image processing, data analysis, or other CPU-intensive tasks.</p><h3>Smart Caching with Redis</h3><p>Our user handler demonstrates intelligent caching patterns:</p><pre>func(h * UserHandler) GetUsers(w http.ResponseWriter, r * http.Request) {<br>    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    cacheKey: = &quot;users:all&quot;<br>    cachedUsers, err: = h.RDB.Get(h.Ctx, cacheKey).Result()<br>    if err == nil {<br>            w.Write([] byte(cachedUsers))<br>            return<br>        }<br>        // Cache miss - fetch from database<br>    rows, err: = h.DB.Query(&quot;SELECT id, name, email, created_at FROM users ORDER BY created_at DESC&quot;)<br>        // ... database query logic ...<br>    usersJSON, _: = json.Marshal(users)<br>    h.RDB.Set(h.Ctx, cacheKey, usersJSON, 5 * time.Minute)<br>    json.NewEncoder(w).Encode(users)<br>}</pre><p>This pattern reduces database load and improves response times — crucial for a scalable application.</p><h3>Chapter 3: Building the React Frontend</h3><p>Our frontend is intentionally simple but demonstrates all the key concepts. Here’s our frontend/src/App.js:</p><pre>import React, { useState, useEffect } from &#39;react&#39;<br>import axios from &#39;axios&#39;<br>// Smart API URL detection for different environments<br>const API_URL = process.env.REACT_APP_API_URL || <br>  (window.location.hostname === &#39;localhost&#39; &amp;&amp; window.location.port === &#39;3000&#39; ? &#39;http://localhost:8080&#39; : &#39;&#39;)<br>function App() {<br>  const [users, setUsers] = useState([])<br>  const [newUser, setNewUser] = useState({ name: &#39;&#39;, email: &#39;&#39; })<br>  const [loading, setLoading] = useState(false)<br>  const [stressTestResult, setStressTestResult] = useState(&#39;&#39;)<br>  const runStressTest = async () =&gt; {<br>    setLoading(true)<br>    setStressTestResult(&#39;Running stress test...&#39;)<br>    try {<br>      const response = await axios.get(`${API_URL}/api/stress`)<br>      setStressTestResult(<br>        &#39;Stress test completed: &#39; + JSON.stringify(response.data)<br>      )<br>    } catch (error) {<br>      setStressTestResult(&#39;Stress test failed: &#39; + error.message)<br>    }<br>    setLoading(false)<br>  }<br>  return (<br>    &lt;div className=&#39;App&#39;&gt;<br>      &lt;h1&gt;Kubernetes Auto-Scaling Demo&lt;/h1&gt;<br>      <br>      &lt;div className=&#39;section&#39;&gt;<br>        &lt;h2&gt;Load Testing&lt;/h2&gt;<br>        &lt;button onClick={runStressTest} disabled={loading}&gt;<br>          {loading ? &#39;Running...&#39; : &#39;Run Stress Test&#39;}<br>        &lt;/button&gt;<br>        {stressTestResult &amp;&amp; &lt;p&gt;{stressTestResult}&lt;/p&gt;}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>The Magic of nginx Proxying</h3><p>Our frontend uses a clever nginx configuration that handles both serving the React app and proxying API calls:</p><pre>server {<br>    listen 80;<br>    server_name localhost;<br>    root /usr/share/nginx/html;<br>    <br>    location / {<br>        try_files $uri $uri/ /index.html;<br>    }<br><br>    location /api/ {<br>        proxy_pass http://backend-service:8080;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p>This configuration means users can access everything through a single URL, while nginx intelligently routes API calls to our backend service.</p><h3>Chapter 4: Containerization Strategy</h3><p>Our Dockerfiles are optimized for both development speed and production efficiency.</p><h3>Backend Dockerfile</h3><pre>FROM golang:1.24-alpine AS builder<br>WORKDIR /app<br>COPY go.mod go.sum ./<br>RUN go mod download<br>COPY . .<br>RUN CGO_ENABLED=0 GOOS=linux go build -o main .<br><br>FROM alpine:latest<br>RUN apk --no-cache add ca-certificates<br>WORKDIR /root/<br>COPY --from=builder /app/main .<br>EXPOSE 8080<br>CMD [&quot;./main&quot;]</pre><h3>Frontend Dockerfile</h3><pre>FROM node:18-alpine AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build<br><br>FROM nginx:alpine<br>COPY --from=builder /app/build /usr/share/nginx/html<br>COPY nginx.conf /etc/nginx/conf.d/default.conf<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>Both use multi-stage builds to keep the final images small and secure.</p><h3>Chapter 5: Kubernetes Orchestration</h3><p>Now comes the exciting part — deploying to Kubernetes with auto-scaling capabilities!</p><h3>The Heart of Auto-scaling: HPA Configuration</h3><p>This is where the magic happens. Our k8s/backend/hpa.yaml:</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: backend-hpa<br>  namespace: webapp<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: backend<br>  minReplicas: 2<br>  maxReplicas: 10<br>  metrics:<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target:<br>          type: Utilization<br>          averageUtilization: 50<br>    - type: Resource<br>      resource:<br>        name: memory<br>        target:<br>          type: Utilization<br>          averageUtilization: 70<br>  behavior:<br>    scaleDown:<br>      stabilizationWindowSeconds: 60<br>      policies:<br>        - type: Percent<br>          value: 10<br>          periodSeconds: 60<br>    scaleUp:<br>      stabilizationWindowSeconds: 30<br>      policies:<br>        - type: Percent<br>          value: 50<br>          periodSeconds: 30</pre><p>This configuration tells Kubernetes:</p><ul><li>Keep at least 2 backend pods running (for availability)</li><li>Scale up to a maximum of 10 pods</li><li>Scale up when CPU hits 50% or memory hits 70%</li><li>Be conservative when scaling down (60s wait, 10% reduction)</li><li>Be more aggressive when scaling up (30s wait, 50% increase)</li></ul><h3>Backend Deployment with Resource Limits</h3><p>The crucial part for HPA to work is setting resource requests:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: backend<br>  namespace: webapp<br>spec:<br>  replicas: 2<br>  template:<br>    spec:<br>      containers:<br>        - name: backend<br>          image: backend:latest<br>          resources:<br>            requests:<br>              memory: &#39;128Mi&#39;<br>              cpu: &#39;100m&#39;      # 0.1 CPU cores<br>            limits:<br>              memory: &#39;256Mi&#39;<br>              cpu: &#39;200m&#39;      # 0.2 CPU cores<br>          readinessProbe:<br>            httpGet:<br>              path: /health<br>              port: 8080<br>            initialDelaySeconds: 10<br>            periodSeconds: 5</pre><p>The resource requests are critical — HPA uses these to calculate CPU/memory percentages.</p><h3>Chapter 6: The Auto-scaling Architecture</h3><p>Here’s how the auto-scaling system works behind the scenes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nA-i7jScEovk42hJNcAl_Q.png" /></figure><h3>The Scaling Decision Algorithm</h3><p>The HPA uses this formula to determine the desired number of replicas:</p><pre>desiredReplicas = ceil[currentReplicas * (currentMetricValue / desiredMetricValue)]</pre><p>Example Calculation:</p><ul><li>Current pods: 2</li><li>Current CPU: 80%</li><li>Target CPU: 50%</li><li>Desired pods: ceil[2 * (80/50)] = ceil[3.2] = 4 pods</li></ul><h3>Conclusion</h3><p>Building auto-scaling applications doesn’t have to be complex. With the right architecture, clear separation of concerns, and solid automation, you can create systems that are both powerful and maintainable.</p><p>The combination of Go’s performance, React’s user experience, and Kubernetes’ orchestration creates a platform that can grow with your business. And the best part? Everything we’ve built here uses modern, production-tested technologies that you can confidently deploy to production.</p><p>Remember: the goal isn’t just to build something that works today, but something that will scale elegantly as your user base grows. This architecture gives you exactly that foundation.</p><p>Repository: <a href="https://github.com/sandeepkv93/kubernetes-autoscale-webapp">kubernetes-autoscale-webapp</a></p><p>Tags: #kubernetes #golang #react #autoscaling #docker #devops #cloudnative</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c8a8ce6343" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Streamlining API Development with OpenAPI and Spring Boot: A Hands-on Guide]]></title>
            <link>https://medium.com/@sandeepkv93/streamlining-api-development-with-openapi-and-spring-boot-a-hands-on-guide-fb0d61963e06?source=rss-e07cf368a458------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb0d61963e06</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[swagger-codegen]]></category>
            <category><![CDATA[codegen]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Sandeep Vishnu]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 18:49:25 GMT</pubDate>
            <atom:updated>2024-12-26T18:52:11.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you tired of maintaining API documentation that’s always out of sync with your code? Looking for a way to ensure your API implementation strictly follows your API specification? In this post, we’ll explore a powerful approach to API development using OpenAPI specifications and code generation in a Spring Boot application.</p><h3>Introduction: Putting Contracts First for Better APIs 📋</h3><p>Imagine starting an API project where the blueprint comes first, and everything else — implementation, client SDKs, and even documentation — flows naturally from there. That’s the beauty of contract-first API development.</p><p>By defining your API contract upfront, you unlock a wealth of benefits:</p><ul><li>Teams can work in parallel without stepping on each other’s toes.</li><li>The API behaves consistently across environments and versions.</li><li>You can auto-generate client SDKs, reducing manual effort.</li><li>Documentation stays accurate and up-to-date — effortlessly!</li></ul><p>This guide walks you through a practical example of contract-first development using a multi-module Maven project to build a user management API and see how OpenAPI brings it all together seamlessly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXqiWABu46SQS9YnIm7NXA.png" /></figure><h3>Project Structure 🏗️</h3><p>Our project consists of two main modules:</p><ol><li>user-management-api-spec: Houses the OpenAPI specification and generates interface code</li><li>user-management-service: Implements the API using the generated interfaces</li></ol><pre>├── user-management-api-spec<br>│   ├── src/main/resources<br>│   │   └── user-management-api.yaml<br>│   └── pom.xml<br>├── user-management-service<br>│   ├── src/main/java<br>│   │   └── com/example/usermanagement<br>│   └── pom.xml<br>└── pom.xml</pre><h3>The OpenAPI Specification: Defining Our Contract 📝</h3><p>Let’s start by examining our API specification in user-management-api.yaml:</p><pre>openapi: 3.0.3<br>info:<br>  title: User Management API<br>  description: REST API for User Management operations<br>  version: 1.0.0<br>servers:<br>  - url: &lt;http://localhost:8080/api/v1&gt;<br>    description: Local development server<br><br>paths:<br>  /users:<br>    get:<br>      tags:<br>        - Users<br>      summary: Retrieve users<br>      operationId: getUsers<br>      responses:<br>        &#39;200&#39;:<br>          description: Users retrieved successfully<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  $ref: &#39;#/components/schemas/User&#39;<br><br>components:<br>  schemas:<br>    User:<br>      type: object<br>      properties:<br>        id:<br>          type: integer<br>          format: int64<br>          readOnly: true<br>        name:<br>          type: string<br>          minLength: 1<br>          maxLength: 100<br>          pattern: &#39;^[a-zA-Z0-9\\s.-]+$&#39;<br>        email:<br>          type: string<br>          format: email<br>          pattern: &#39;^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$&#39;<br>      required:<br>        - name<br>        - email</pre><h3>Setting Up Code Generation 🛠️</h3><p>The user-management-api-spec/pom.xml configures the OpenAPI generator plugin:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.openapitools&lt;/groupId&gt;<br>    &lt;artifactId&gt;openapi-generator-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;${openapi-generator.version}&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;id&gt;generate-api&lt;/id&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;generate&lt;/goal&gt;<br>            &lt;/goals&gt;<br>            &lt;configuration&gt;<br>                &lt;inputSpec&gt;${project.basedir}/src/main/resources/user-management-api.yaml&lt;/inputSpec&gt;<br>                &lt;generatorName&gt;spring&lt;/generatorName&gt;<br>                &lt;apiPackage&gt;com.example.api&lt;/apiPackage&gt;<br>                &lt;modelPackage&gt;com.example.model&lt;/modelPackage&gt;<br>                &lt;configOptions&gt;<br>                    &lt;sourceFolder&gt;src/gen/java/main&lt;/sourceFolder&gt;<br>                    &lt;useSpringBoot3&gt;true&lt;/useSpringBoot3&gt;<br>                    &lt;interfaceOnly&gt;true&lt;/interfaceOnly&gt;<br>                    &lt;useTags&gt;true&lt;/useTags&gt;<br>                    &lt;documentationProvider&gt;none&lt;/documentationProvider&gt;<br>                    &lt;annotationLibrary&gt;none&lt;/annotationLibrary&gt;<br>                    &lt;useLombok&gt;true&lt;/useLombok&gt;<br>                &lt;/configOptions&gt;<br>            &lt;/configuration&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><h3>Implementing the Generated Interface 💻</h3><p>In the user-management-service module, we create a controller that implements the generated interface:</p><pre>@RestController<br>public class UsersController implements UsersApi {<br><br>    // Using CopyOnWriteArrayList for thread-safety in this demo<br>    private final List&lt;User&gt; users = new CopyOnWriteArrayList&lt;&gt;();<br><br>    @Override<br>    public ResponseEntity&lt;List&lt;User&gt;&gt; getUsers() {<br>        return ResponseEntity.ok(new ArrayList&lt;&gt;(users));<br>    }<br><br>    @Override<br>    public ResponseEntity&lt;User&gt; createUser(@Valid User user) {<br>        // Demo implementation of email uniqueness check<br>        if (users.stream().anyMatch(u -&gt; u.getEmail().equals(user.getEmail()))) {<br>            return ResponseEntity.badRequest().build();<br>        }<br><br>        user.setId((long) (users.size() + 1));<br>        users.add(user);<br>        return ResponseEntity.status(201).body(user);<br>    }<br>}</pre><h3>Unit Testing 🧪</h3><p>Our testing approach covers multiple aspects:</p><h3>1. Schema Validation Tests</h3><pre>@Test<br>@DisplayName(&quot;User schema should have required fields&quot;)<br>void shouldHaveRequiredFields() {<br>    Schema&lt;?&gt; userSchema = openAPI.getComponents().getSchemas().get(&quot;User&quot;);<br><br>    assertThat(userSchema.getRequired())<br>        .as(&quot;Required fields should be defined&quot;)<br>        .containsExactlyInAnyOrder(&quot;name&quot;, &quot;email&quot;);<br>}</pre><h3>2. Contract Tests</h3><pre>@Test<br>@DisplayName(&quot;Interface should define getUsers method&quot;)<br>void shouldDefineGetUsersMethod() throws NoSuchMethodException {<br>    Method getUsersMethod = UsersApi.class.getMethod(&quot;getUsers&quot;);<br><br>    assertThat(getUsersMethod.getReturnType())<br>        .as(&quot;Return type should be ResponseEntity&quot;)<br>        .isEqualTo(ResponseEntity.class);<br><br>    assertThat(getUsersMethod.getGenericReturnType().getTypeName())<br>        .as(&quot;Should return List of Users&quot;)<br>        .contains(&quot;java.util.List&lt;&quot; + User.class.getName() + &quot;&gt;&quot;);<br>}</pre><h3>3. Model Validation Tests</h3><pre>@Test<br>@DisplayName(&quot;Should accept valid email&quot;)<br>void shouldAcceptValidEmail() {<br>    User user = new User().name(&quot;John Doe&quot;).email(&quot;john.doe@example.com&quot;);<br>    var violations = validator.validateProperty(user, &quot;email&quot;);<br>    assertThat(violations).isEmpty();<br>}</pre><h3>Application Configuration ⚙️</h3><p>The application.yml in the service module configures the application:</p><pre>server:<br>  servlet:<br>    context-path: /api/v1<br><br>springdoc:<br>  api-docs:<br>    path: /api-docs<br>  swagger-ui:<br>    path: /swagger-ui.html<br><br>logging:<br>  level:<br>    com.example: INFO</pre><h3>Key Benefits of This Approach 🎯</h3><ul><li><strong>Type Safety and Compile-Time Checks</strong> — Our generated interfaces guarantee type-safe implementation while ensuring compilation fails immediately if any implementation deviates from the specified contract, providing robust safety guarantees throughout development.</li><li><strong>Clear Separation of Concerns</strong> — By maintaining API specifications separately from their implementation, we create a clean architectural boundary where all changes to the API contract must be explicitly defined and versioned, preventing accidental modifications to the interface.</li><li><strong>Automated Documentation</strong> — The system automatically maintains up-to-date documentation through generated Swagger UI and OpenAPI specifications, ensuring that our documentation always perfectly reflects the current API state without manual intervention.</li><li><strong>Development Workflow Improvements</strong> — Teams can work in parallel more effectively as frontend developers begin implementation using the API specification while backend teams work against the same stable interface, with all API changes explicitly tracked in version control for better collaboration.</li></ul><h3>Production Considerations 🚨</h3><p>When adapting this approach for production:</p><ul><li><strong>Persistence Layer</strong> — Replace the current in-memory storage implementation with a robust database integration system, ensuring proper transaction management to maintain data integrity and consistency across all operations.</li><li><strong>Security</strong> — Implement comprehensive security measures including authentication, authorization, rate limiting, and security headers to protect the API from unauthorized access and potential abuse while ensuring secure data transmission.</li><li><strong>Error Handling</strong> — Establish a robust error management system with global exception handling, detailed error responses, and clear validation messages to provide meaningful feedback and maintain system stability while helping developers quickly identify and resolve issues.</li><li><strong>Monitoring and Logging</strong> — Deploy a complete observability solution that combines a proper logging framework with metrics collection and health checks, enabling real-time system monitoring and proactive issue detection across the entire application stack.</li></ul><h3>Source Code 📦</h3><p>The complete source code for this example is available on GitHub: <a href="https://github.com/sandeepkv93/springboot-openapi-codegen-demo">springboot-openapi-codegen-demo</a></p><h3>Final Thoughts 💭</h3><p>This approach to API development combines the best practices of contract-first development with the type safety of generated code. It provides a robust foundation for building maintainable and scalable APIs while ensuring consistency between documentation and implementation.</p><p>The separation between API specification and implementation allows teams to work efficiently while maintaining a single source of truth for the API contract. The generated code provides compile-time safety, while the OpenAPI specification serves as both documentation and a development contract.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb0d61963e06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding OAuth 2.0 and OpenID Connect Step-by-Step]]></title>
            <link>https://medium.com/@sandeepkv93/understanding-oauth-2-0-and-openid-connect-a-complete-guide-46fe5d3ca7a6?source=rss-e07cf368a458------2</link>
            <guid isPermaLink="false">https://medium.com/p/46fe5d3ca7a6</guid>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Sandeep Vishnu]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 17:23:51 GMT</pubDate>
            <atom:updated>2024-11-12T20:23:19.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction 🌟</h3><p>Picture managing your digital services without secure authentication — it would be chaos. At the heart of modern auth systems are OAuth 2.0 and OpenID Connect (OIDC), two protocols that make secure access both possible and practical. 🔐 Let’s explore these protocols through a practical example: a calendar application called “CalendarBuddy” connecting with Google Calendar. By following this real-world scenario, you’ll understand how modern applications handle authentication and authorization securely.</p><h3>What is OAuth 2.0 and OIDC? 🤔</h3><p><strong>OAuth 2.0</strong> is an industry-standard authorization framework that enables applications to obtain limited access to user accounts on other services. Think of it as a secure valet key for your car — it provides restricted access without handing over the master key. It provides delegated authorization, allowing users to grant third-party applications access to their resources without sharing passwords. For example, when you click “Sign in with Google” to access a service, OAuth 2.0 lets that service access specific parts of your Google account without ever seeing your Google password.</p><p><strong>OpenID Connect (OIDC)</strong> is built on top of OAuth 2.0, adding an identity layer that allows applications to verify user identities and obtain basic profile information. While OAuth 2.0 handles the “can this app access this data?” question, OIDC handles the “who is this user?” question. It standardizes fields like name, email, and profile picture, making it easier for applications to handle user identity consistently. For instance, when you use your Google account to create a new account on a website, OIDC is what allows that website to receive your verified email address and name from Google.</p><p>Together, these protocols form the backbone of modern secure authentication and authorization on the internet, enabling the seamless and secure sharing of information between services while protecting user privacy and security.</p><h3>Step-by-Step Flow: CalendarBuddy Integration 🚀</h3><h4>1. Developer Registration 📝</h4><p>First, the developer needs to register their application with the authorization server (in this case, Google).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*dHYfilqz1pT-AGbxX4HYlw.png" /></figure><p>During this step:</p><ul><li>The developer registers CalendarBuddy with Google’s API Console</li><li>They specify app details and requested permissions</li><li>Google provides a client_id (public identifier) and client_secret (confidential)</li></ul><h4>2. User Access Attempt 🔑</h4><p>When you try to use CalendarBuddy to access your Google Calendar data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*4C_iocpz0mwBF7M1E4dv4Q.png" /></figure><h4>3. Authorization Server Redirect 🔄</h4><p>CalendarBuddy redirects you to Google’s authorization page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*XtO-aCDOhtHaLQfJprXNIw.png" /></figure><p>The authorization URL includes several important parameters:</p><pre>https://accounts.google.com/o/oauth2/v2/auth?<br>  client_id=123456789-abcdefghijklmnop.apps.googleusercontent.com&amp;<br>  redirect_uri=https://calendarbuddy.com/auth/google/callback&amp;<br>  response_type=code&amp;<br>  scope=https://www.googleapis.com/auth/calendar.readonly&amp;<br>  state=xyzABC123</pre><h4>4. User Authentication 👤</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*5x4vyQ_kW2hj2cqOHQ6j0w.png" /></figure><p>You log into your Google account and approve the requested permissions.</p><h4>5. Authorization Code Issuance 📨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*XW2EwsT1WDdxT-Ecatl3hg.png" /></figure><p>Google redirects back to CalendarBuddy with an authorization code:</p><pre>https://calendarbuddy.com/auth/google/callback?<br>  code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&amp;<br>  state=xyzABC123</pre><h4>6. Token Exchange 🔄</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*EhpvfXeppMbyz7pj1yRECw.png" /></figure><p>CalendarBuddy exchanges the authorization code for tokens:</p><pre>POST https://oauth2.googleapis.com/token<br>Content-Type: application/x-www-form-urlencoded</pre><pre>code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&amp;<br>client_id=123456789-abcdefghijklmnop.apps.googleusercontent.com&amp;<br>client_secret=CLIENTSECRETxxxxxxxxxxx&amp;<br>redirect_uri=https://calendarbuddy.com/auth/google/callback&amp;<br>grant_type=authorization_code</pre><h4>7. Token Response 🎁</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*LrTfw5x_ZXWqO16fPKzvIg.png" /></figure><p>Google returns three important tokens:</p><ol><li>ID Token (JWT format) containing user information:</li></ol><pre>{<br>  &quot;iss&quot;: &quot;https://accounts.google.com&quot;,<br>  &quot;azp&quot;: &quot;123456789-abcdefghijklmnop.apps.googleusercontent.com&quot;,<br>  &quot;aud&quot;: &quot;123456789-abcdefghijklmnop.apps.googleusercontent.com&quot;,<br>  &quot;sub&quot;: &quot;10769150350006150715113082367&quot;,<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;email_verified&quot;: true,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  // ... additional claims<br>}</pre><p>2. Access Token (for API access)</p><p>3. Refresh Token (for obtaining new access tokens)</p><h4>8. ID Token Processing 🔍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*zVCuLPKNrnhTa0gWWXiJxA.png" /></figure><p>CalendarBuddy decodes the ID token to get user information.</p><h4>9. Resource Request 📊</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*fmeOQdEXLRVWWVJltaB1-Q.png" /></figure><h4>10. Resource Response 📅</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*2U6DCbJcJhiFfhUo39ZOHA.png" /></figure><h4>11. Display Data 🎯</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*DpCM_ynmTsuYxUl7Kw2y5A.png" /></figure><h3>Conclusion 🎉</h3><p>OAuth 2.0 and OIDC give us a solid foundation for handling authentication and resource access. They’re battle-tested standards that help us build secure apps without reinventing the wheel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46fe5d3ca7a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Composition is Preferred Over Inheritance: A Deep Dive]]></title>
            <link>https://medium.com/@sandeepkv93/why-composition-is-preferred-over-inheritance-a-deep-dive-ea6911b1ad15?source=rss-e07cf368a458------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6911b1ad15</guid>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <dc:creator><![CDATA[Sandeep Vishnu]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 04:56:35 GMT</pubDate>
            <atom:updated>2024-11-06T16:46:55.709Z</atom:updated>
            <content:encoded><![CDATA[<p>In object-oriented programming, we often face the choice between inheritance and composition when designing our classes. While inheritance is a powerful feature, the phrase “favor composition over inheritance” has become increasingly popular. But why? Let’s dive deep into understanding this principle with practical examples.</p><h3>The Problem with Inheritance</h3><p>Inheritance is a mechanism that allows a class to inherit properties and methods from another class. At first glance, it seems like a perfect way to reuse code and establish relationships between classes. However, it comes with several pitfalls.</p><p>Let’s look at a classic example:</p><pre>class Animal {<br>    protected String name;<br>    protected int age;<br>    <br>    public void eat() {<br>        System.out.println(name + &quot; is eating&quot;);<br>    }<br>    <br>    public void sleep() {<br>        System.out.println(name + &quot; is sleeping&quot;);<br>    }<br>}</pre><pre>class Bird extends Animal {<br>    public void fly() {<br>        System.out.println(name + &quot; is flying&quot;);<br>    }<br>}<br><br>class Penguin extends Bird {  // Problem: Penguins can&#39;t fly!<br>    @Override<br>    public void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguins can&#39;t fly!&quot;);<br>    }<br>}</pre><p>This hierarchy seems logical at first: penguins are birds, and birds are animals. However, we’ve run into what’s known as the “LSP violation” (Liskov Substitution Principle). Our Penguin class inherits a behavior (flying) that it can’t actually perform!</p><h3>Problems with this Approach:</h3><ol><li><strong>Rigid Hierarchy</strong>: The inheritance hierarchy forces us into an “is-a” relationship that might not reflect reality perfectly.</li><li><strong>Fragile Base Class</strong>: Changes to the base class can unexpectedly break derived classes.</li><li><strong>Tight Coupling</strong>: Inheritance creates the tightest coupling possible between classes.</li><li><strong>Limited Runtime Flexibility</strong>: Behavior is fixed at compile time.</li></ol><h3>Enter Composition</h3><p>Composition offers a more flexible approach by favoring “has-a” relationships over “is-a” relationships. Let’s see how we can solve the same problem using composition:</p><pre>interface Movable {<br>    void move();<br>}</pre><pre>class Swimming implements Movable {<br>    public void move() {<br>        System.out.println(&quot;Swimming in the water&quot;);<br>    }<br>}<br><br>class Flying implements Movable {<br>    public void move() {<br>        System.out.println(&quot;Flying in the air&quot;);<br>    }<br>}<br><br>class Animal {<br>    private String name;<br>    private int age;<br>    private Movable movementBehavior;<br>    <br>    public Animal(String name, int age, Movable movementBehavior) {<br>        this.name = name;<br>        this.age = age;<br>        this.movementBehavior = movementBehavior;<br>    }<br>    <br>    public void move() {<br>        System.out.print(name + &quot; is &quot;);<br>        movementBehavior.move();<br>    }<br>    <br>    public void setMovementBehavior(Movable newMovementBehavior) {<br>        this.movementBehavior = newMovementBehavior;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxUltyEcriTleCb6XT7eDA.png" /></figure><h3>Benefits of Composition</h3><ol><li><strong>Flexible Behavior</strong></li></ol><pre>Animal duck = new Animal(&quot;Donald&quot;, 5, new Swimming());<br>duck.move();// Donald is Swimming in the water<br>duck.setMovementBehavior(new Flying());<br>duck.move();// Donald is Flying in the air</pre><pre>Animal penguin = new Animal(&quot;Pingu&quot;, 3, new Swimming());<br>penguin.move();// Pingu is Swimming in the water</pre><ol><li><strong>Runtime Behavior Changes</strong>: As shown above, we can change behaviors at runtime.</li><li><strong>Better Encapsulation</strong>: Implementation details are hidden behind interfaces.</li><li><strong>Loose Coupling</strong>: Classes are less dependent on each other.</li><li><strong>Easier Testing</strong>: Components can be tested in isolation.</li></ol><h3>When to Use Composition</h3><p>Favor composition when:</p><ul><li>You need runtime flexibility</li><li>A class needs to use behavior from multiple sources</li><li>You want to avoid the problems of deep inheritance hierarchies</li><li>You need to change behavior without affecting existing code</li></ul><h3>When to Use Inheritance</h3><p>Inheritance still has its place. Use it when:</p><ul><li>You have a genuine “is-a” relationship</li><li>The subclass is truly a specialized version of the base class</li><li>The base class is designed for inheritance</li><li>You’re creating frameworks or working with existing inheritance hierarchies</li></ul><h3>Best Practices</h3><ol><li><strong>Design for Composition First</strong>: Start with composition and only use inheritance when it truly makes sense.</li><li><strong>Keep Interfaces Small</strong>: Create focused interfaces that define specific behaviors.</li><li><strong>Use Dependency Injection</strong>: Pass behaviors through constructors or setters.</li><li><strong>Follow SOLID Principles</strong>: Especially the Single Responsibility and Open/Closed principles.</li></ol><h3>Conclusion</h3><ul><li>While inheritance is a powerful feature of object-oriented programming, composition often provides more flexibility and better design. By using composition, we can create more maintainable, flexible, and robust code that’s easier to test and modify.</li><li>Remember: Inheritance is about what something <em>is</em>, while composition is about what something <em>has</em> or what it can <em>do</em>. In the real world, capabilities often matter more than classifications, making composition a more practical choice in many situations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6911b1ad15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Load Balancer with Spring Boot: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@sandeepkv93/building-a-simple-load-balancer-with-spring-boot-a-step-by-step-guide-a8b0dfcfb103?source=rss-e07cf368a458------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8b0dfcfb103</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sandeep Vishnu]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 20:10:22 GMT</pubDate>
            <atom:updated>2024-11-19T16:23:11.024Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s microservices architecture, load balancers play a crucial role in distributing traffic across multiple service instances. This article will walk you through building a simple yet functional load balancer using Spring Boot, complete with health checking and round-robin load distribution.</p><h3>Project Overview</h3><p>Our load balancer implementation consists of three main components:</p><ol><li><strong>Load Balancer Service</strong>: The core component that handles request distribution</li><li><strong>API Service</strong>: Multiple instances of a demo service that will receive the distributed traffic</li><li><strong>Common Module</strong>: Shared DTOs and utilities</li></ol><p>The complete project uses Spring Boot 3.2.0 and Java 21, showcasing modern Java features and enterprise-grade patterns.</p><h3>Architecture</h3><p>Here’s a high-level view of our system architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSYnmkXzUz5jP03MB-wSWg.png" /></figure><p>The system works as follows:</p><ol><li>Clients send requests to the load balancer on port 8080</li><li>The load balancer maintains a pool of healthy API services</li><li>API services send heartbeat messages every 5 seconds to register themselves</li><li>The Health Check Service monitors service health and removes unresponsive instances</li><li>The Load Balancer Service distributes incoming requests across healthy instances using round-robin</li><li>Each API service runs on a different port (8081–8085) and processes the forwarded requests</li></ol><p>Let’s dive into each component in detail.</p><h3>Implementation</h3><h3>1. Common DTOs</h3><p>First, let’s look at our shared data structures. These are used for communication between services:</p><pre>// HeartbeatRequest.java<br>public record HeartbeatRequest(<br>        String serviceId,<br>        String host,<br>        int port,<br>        String status,<br>        long timestamp<br>) {}<br><br>// HeartbeatResponse.java<br>public record HeartbeatResponse(<br>        boolean acknowledged,<br>        String message,<br>        long timestamp<br>) {}</pre><h3>2. Service Node Model</h3><p>The load balancer keeps track of service instances using the ServiceNode record:</p><pre>public record ServiceNode(<br>        String serviceId,<br>        String host,<br>        int port,<br>        boolean healthy,<br>        Instant lastHeartbeat<br>) {}</pre><h3>3. Load Balancer Service</h3><p>The core load balancing logic is implemented in LoadBalancerService:</p><pre>@Service<br>public class LoadBalancerService {<br>    private final ConcurrentHashMap &lt; String, ServiceNode &gt; serviceNodes = new ConcurrentHashMap &lt; &gt; ();<br>    private final AtomicInteger currentNodeIndex = new AtomicInteger(0);<br>    public void registerNode(ServiceNode node) {<br>        serviceNodes.put(node.serviceId(), node);<br>    }<br>    public void removeNode(String serviceId) {<br>        serviceNodes.remove(serviceId);<br>    }<br>    public ServiceNode getNextAvailableNode() {<br>        List &lt; ServiceNode &gt; healthyNodes = serviceNodes.values().stream()<br>            .filter(ServiceNode::healthy)<br>            .toList();<br>        if (healthyNodes.isEmpty()) {<br>            throw new IllegalStateException(&quot;No healthy nodes available&quot;);<br>        }<br>        int index = currentNodeIndex.getAndIncrement() % healthyNodes.size();<br>        return healthyNodes.get(index);<br>    }<br>    public List &lt; ServiceNode &gt; getAllNodes() {<br>        return new ArrayList &lt; &gt; (serviceNodes.values());<br>    }<br>}</pre><h3>4. Health Check Service</h3><p>The HealthCheckService manages service registration and health monitoring:</p><pre>@Service<br>@Slf4j<br>public class HealthCheckService {<br>    private final LoadBalancerService loadBalancerService;<br>    private static final long HEALTH_CHECK_TIMEOUT_SECONDS = 30;<br>    <br>    public HealthCheckService(LoadBalancerService loadBalancerService) {<br>        this.loadBalancerService = loadBalancerService;<br>    }<br>    public HeartbeatResponse processHeartbeat(HeartbeatRequest request) {<br>        ServiceNode node = new ServiceNode(<br>            request.serviceId(),<br>            request.host(),<br>            request.port(),<br>            true,<br>            Instant.now()<br>        );<br>        loadBalancerService.registerNode(node);<br>        return new HeartbeatResponse(true, &quot;Heartbeat acknowledged&quot;,<br>            Instant.now().toEpochMilli());<br>    }<br>    @Scheduled(fixedRate = 10000) // Check every 10 seconds<br>    public void checkNodeHealth() {<br>        Instant threshold = Instant.now().minus(HEALTH_CHECK_TIMEOUT_SECONDS,<br>            ChronoUnit.SECONDS);<br>        loadBalancerService.getAllNodes().stream()<br>            .filter(node - &gt; node.lastHeartbeat().isBefore(threshold))<br>            .forEach(node - &gt; loadBalancerService.removeNode(node.serviceId()));<br>    }<br>}</pre><h3>5. Proxy Controller</h3><p>The ProxyController handles incoming requests and forwards them to the appropriate service:</p><pre>@Slf4j<br>@RestController<br>public class ProxyController {<br>    private final LoadBalancerService loadBalancerService;<br>    private final HealthCheckService healthCheckService;<br>    private final RestTemplate restTemplate;<br><br>    @PostMapping(&quot;/heartbeat&quot;)<br>    public HeartbeatResponse handleHeartbeat(@RequestBody HeartbeatRequest request) {<br>        return healthCheckService.processHeartbeat(request);<br>    }<br>    @RequestMapping(value = &quot;/**&quot;)<br>    public ResponseEntity &lt;&lt; ? &gt; proxyRequest(HttpServletRequest request)<br>    throws URISyntaxException, IOException {<br>        var node = loadBalancerService.getNextAvailableNode();<br>        String targetUrl = String.format(&quot;http://%s:%d%s&quot;,<br>            node.host(),<br>            node.port(),<br>            request.getRequestURI()<br>        );<br>        // Copy headers<br>        HttpHeaders headers = new HttpHeaders();<br>        Enumeration &lt; String &gt; headerNames = request.getHeaderNames();<br>        while (headerNames.hasMoreElements()) {<br>            String headerName = headerNames.nextElement();<br>            headers.addAll(headerName,<br>                Collections.list(request.getHeaders(headerName)));<br>        }<br>        // Forward the request<br>        ResponseEntity &lt; String &gt; response = restTemplate.exchange(<br>            new URI(targetUrl),<br>            HttpMethod.valueOf(request.getMethod()),<br>            new HttpEntity &lt; &gt; (StreamUtils.copyToByteArray(<br>                request.getInputStream()), headers),<br>            String.class<br>        );<br>        return new ResponseEntity &lt; &gt; (response.getBody(),<br>            response.getHeaders(),<br>            response.getStatusCode());<br>    }<br>}</pre><h3>6. API Service Implementation</h3><p>The API service includes a heartbeat configuration to register with the load balancer:</p><pre>@Slf4j<br>@Component<br>public class HeartbeatConfig {<br>    private final RestTemplate restTemplate;<br>    private final String serviceId = UUID.randomUUID().toString();<br><br>    @Value(&quot;${server.port}&quot;)<br>    private int serverPort;<br>    @Value(&quot;${loadbalancer.url}&quot;)<br>    private String loadBalancerUrl;<br>    @Scheduled(fixedRate = 5000) // Send heartbeat every 5 seconds<br>    public void sendHeartbeat() {<br>        try {<br>            String hostname = InetAddress.getLocalHost().getHostName();<br>            var request = new HeartbeatRequest(<br>                serviceId,<br>                hostname,<br>                serverPort,<br>                &quot;UP&quot;,<br>                Instant.now().toEpochMilli()<br>            );<br>            restTemplate.postForObject(<br>                loadBalancerUrl + &quot;/heartbeat&quot;,<br>                request,<br>                void.class<br>            );<br>            log.info(&quot;Heartbeat sent successfully to {}&quot;, loadBalancerUrl);<br>        } catch (Exception e) {<br>            log.error(&quot;Failed to send heartbeat: {}&quot;, e.getMessage());<br>        }<br>    }<br>}</pre><h3>Deployment with Docker Compose</h3><p>The project includes Docker support for easy deployment. Here’s a snippet from the docker-compose.yml:</p><pre>services:<br>  load-balancer:<br>    build:<br>      context: .<br>      dockerfile: load-balancer/Dockerfile<br>    container_name: load-balancer<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=docker<br>      - SERVER_PORT=8080<br>      - MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE=health,info,metrics<br>      - MANAGEMENT_ENDPOINT_HEALTH_SHOW_DETAILS=always<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;wget&quot;, &quot;--quiet&quot;, &quot;--tries=1&quot;, &quot;--spider&quot;, &quot;http://localhost:8080/actuator/health&quot;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 3<br>      start_period: 40s<br>    networks:<br>      - app-network<br>    restart: unless-stopped<br><br>  api-service-1:<br>    build:<br>      context: .<br>      dockerfile: api-service/Dockerfile<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=docker<br>      - SERVER_PORT=8081<br>      - LOADBALANCER_URL=http://load-balancer:8080<br>    depends_on:<br>      load-balancer:<br>        condition: service_healthy<br>    networks:<br>      - app-network<br>    restart: unless-stopped<br><br>  api-service-2:<br>    build:<br>      context: .<br>      dockerfile: api-service/Dockerfile<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=docker<br>      - SERVER_PORT=8082<br>      - LOADBALANCER_URL=http://load-balancer:8080<br>    depends_on:<br>      load-balancer:<br>        condition: service_healthy<br>    networks:<br>      - app-network<br>    restart: unless-stopped<br><br>  api-service-3:<br>    build:<br>      context: .<br>      dockerfile: api-service/Dockerfile<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=docker<br>      - SERVER_PORT=8083<br>      - LOADBALANCER_URL=http://load-balancer:8080<br>    depends_on:<br>      load-balancer:<br>        condition: service_healthy<br>    networks:<br>      - app-network<br>    restart: unless-stopped<br><br>  api-service-4:<br>    build:<br>      context: .<br>      dockerfile: api-service/Dockerfile<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=docker<br>      - SERVER_PORT=8084<br>      - LOADBALANCER_URL=http://load-balancer:8080<br>    depends_on:<br>      load-balancer:<br>        condition: service_healthy<br>    networks:<br>      - app-network<br>    restart: unless-stopped<br><br>  api-service-5:<br>    build:<br>      context: .<br>      dockerfile: api-service/Dockerfile<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=docker<br>      - SERVER_PORT=8085<br>      - LOADBALANCER_URL=http://load-balancer:8080<br>    depends_on:<br>      load-balancer:<br>        condition: service_healthy<br>    networks:<br>      - app-network<br>    restart: unless-stopped<br><br>networks:<br>  app-network:<br>    driver: bridge</pre><h3>Key Features</h3><ol><li><strong>Round-Robin Load Balancing</strong>: Requests are distributed evenly across healthy service instances</li><li><strong>Health Checking</strong>: Regular heartbeat monitoring ensures only healthy instances receive traffic</li><li><strong>Dynamic Service Registration</strong>: Services can join or leave the cluster at any time</li><li><strong>Request Forwarding</strong>: All HTTP methods and headers are properly forwarded</li><li><strong>Docker Support</strong>: Easy deployment with Docker Compose</li><li><strong>Modular Design</strong>: Clean separation of concerns with distinct modules</li></ol><h3>Testing the Load Balancer</h3><p>To test the load balancer:</p><ol><li>Start the system using Docker Compose:</li></ol><pre>docker-compose up --build</pre><ol><li>Send requests to the load balancer (port 8080):</li></ol><pre>curl &lt;http://localhost:8080/api/demo&gt;</pre><p>You should see responses from different service instances as the load balancer distributes the requests.</p><h3>Monitoring and Metrics</h3><p>The application includes Spring Boot Actuator endpoints for monitoring:</p><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: health,info,metrics<br>  endpoint:<br>    health:<br>      show-details: always</pre><h3>Conclusion</h3><p>This implementation demonstrates a simple but functional load balancer using Spring Boot. While it may not have all the features of production-grade load balancers like Nginx or HAProxy, it serves as an excellent learning tool and could be extended with additional features like:</p><ul><li>Weighted round-robin</li><li>Least connections algorithm</li><li>Sticky sessions</li><li>Circuit breakers</li><li>Rate limiting</li></ul><p>Remember that in production environments, you might want to use battle-tested solutions like Nginx, HAProxy, or cloud provider load balancers. However, understanding how load balancers work under the hood is valuable knowledge for any software engineer.</p><p>For reference, the entire code implementation can also be found at this Github Repository: <a href="https://github.com/sandeepkv93/SimpleLoadBalancer">https://github.com/sandeepkv93/SimpleLoadBalancer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8b0dfcfb103" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>