<?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 Akshat Vashishtha on Medium]]></title>
        <description><![CDATA[Stories by Akshat Vashishtha on Medium]]></description>
        <link>https://medium.com/@akshat.available?source=rss-e18b6b8712fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KXfyTU2Xc61Gm8banEjxDw.png</url>
            <title>Stories by Akshat Vashishtha on Medium</title>
            <link>https://medium.com/@akshat.available?source=rss-e18b6b8712fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:48:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akshat.available/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[Spring Boot Developer’s Guide to Next.js]]></title>
            <link>https://medium.com/@akshat.available/spring-boot-developers-guide-to-next-js-5a91d35c7c17?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a91d35c7c17</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 13:43:10 GMT</pubDate>
            <atom:updated>2026-10-08T13:43:10.468Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Spring Boot Developer’s Guide to Next.js + TypeScript — From Clean Architecture to 3-Tier Kubernetes Deployment</em></h3><blockquote><strong>Note on this guide:</strong> You know Spring Boot. You understand @Service, @RestController, DTOs, and layered architecture. This blog does one thing — it maps every concept you already know in Java to its <strong>Next.js + TypeScript equivalent</strong>, and then shows you how the entire stack: Spring Boot backend, Next.js frontend, and MongoDB — gets deployed together as a <strong>3-tier application on Kubernetes</strong>.</blockquote><blockquote>We won’t go line-by-line through every file. The full implementation lives in the companion GitHub repository. Think of this as the mental bridge — the stuff no frontend tutorial ever explains to a backend developer.</blockquote><blockquote>📦 <strong>GitHub:</strong> <a href="https://github.com/akshat-vashishtha/nextjs-springboot-k8s-starter">https://github.com/akshat-vashishtha/nextjs-springboot-k8s-starter</a></blockquote><h3>Part 1: The Frontend Story — From API to UI</h3><h3>Act I: The 400-Line Nightmare</h3><p><em>You are a seasoned Spring Boot developer.</em></p><p><em>Your world is neat, disciplined, and beautifully partitioned:</em></p><pre>@RestController ──► @Service ──► @Repository ──► MongoDB<br>        │                  │<br>        ▼                  ▼<br>    UserDTO             @Valid</pre><p><em>One afternoon, you decide it is finally time to build a frontend for your REST APIs. You pick Next.js. You open a trending tutorial. You are excited.</em></p><p><em>Thirty seconds in, your enthusiasm hits a wall.</em></p><p><em>The instructor creates a single file called </em><em>page.tsx and proceeds to cram </em><strong><em>everything</em></strong><em> inside it — raw </em><em>fetch() calls sitting inside click handlers, untyped </em><em>any variables scattered like landmines, and 50 lines of JSX layout wrapping raw JSON responses that may or may not even be correct.</em></p><p><em>It looks like someone took a Spring Boot </em><em>@RestController, a JPA </em><em>@Entity, a raw JDBC SQL query, and a JSP file — threw them all into a blender and hit </em><strong><em>pulse</em></strong><em>.You close the tab.</em></p><p><em>“Is frontend really this chaotic? Is there no concept of Clean Architecture here?”</em></p><p><strong><em>There is.</em></strong><em> You just need to look at it from the </em><strong><em>right direction</em></strong><em> — from the API outward, not from </em><em>&lt;div&gt; inward.</em></p><h3>Act II: Breaking the Language Barrier</h3><p><em>Before we look at architecture, let’s kill the fear around TypeScript syntax with real side-by-side comparisons. <br>Spoiler: TypeScript is just Java wearing a modern jacket.</em></p><h3>1. Variables &amp; Types: “Put the Type on the Right”</h3><p><strong><em>Java:</em></strong><em> You announce the type first.</em></p><pre>String username = &quot;Akshat&quot;;</pre><p><strong><em>TypeScript:</em></strong><em> You name the variable first, then attach the type after a colon.</em></p><pre>const username: string = &quot;Akshat&quot;;</pre><p><em>That is it. TypeScript can also infer the type automatically — </em><em>const username = &quot;Akshat&quot; works the same way, just like </em><em>var in Java 10+.</em></p><h3>2. DTOs: Java record vs TypeScript interface</h3><p><em>In Spring Boot, you define a clean data transfer record:</em></p><pre>// UserResponse.java<br>public record UserResponse(<br>    String id, String name, String email,<br>    UserRole role, UserStatus status,<br>    String createdAt, String updatedAt<br>) {}</pre><p><em>In TypeScript, the same contract is an </em><em>interface. Here is the real file from our project:</em></p><pre>// UserResponseDto.ts<br>import { UserRole } from &quot;@/core/types/UserRole&quot;;<br>import { UserStatus } from &quot;@/core/types/UserStatus&quot;;<br><br>export interface UserResponseDto {<br>    id: string;<br>    name: string;<br>    email: string;<br>    role: UserRole;<br>    status: UserStatus;<br>    createdAt: string;<br>    updatedAt: string;<br>}</pre><p><em>No Lombok </em><em>@Data. No getters or setters. Just a pure </em><strong><em>compile-time contract</em></strong><em> — exactly like a Java record. If your API returns a field that is not declared here, TypeScript will catch it before it ever reaches the browser.</em></p><h3>3. Async Code: CompletableFuture vs Promise</h3><p><strong><em>Java:</em></strong><em> An async operation returns a </em><em>CompletableFuture&lt;T&gt;. To unwrap the value, you call </em><em>.join().</em></p><pre>CompletableFuture&lt;UserResponse&gt; future = userService.getUserAsync(id);<br>UserResponse user = future.join(); // blocks until resolved</pre><p><strong><em>TypeScript:</em></strong><em> An async operation returns a </em><em>Promise&lt;T&gt;. <br>You unwrap it with </em><em>await — non-blocking, and reads like synchronous code.</em></p><p><em>From our real project service interface:</em></p><pre>// UserService.ts<br>export interface UserService {<br>    getAllUsers(): Promise&lt;UserResponseDto[]&gt;;      // like CompletableFuture&lt;List&lt;UserResponse&gt;&gt;<br>    getUserById(id: string): Promise&lt;UserResponseDto&gt;;<br>    createUser(userDto: UserCreateRequestDto): Promise&lt;UserResponseDto&gt;;<br>    updateUser(id: string, userDto: UserUpdateRequestDto): Promise&lt;UserResponseDto&gt;;<br>    deleteUser(id: string): Promise&lt;void&gt;;<br>}</pre><p><em>And calling it with </em><em>await:</em></p><pre>// Instead of future.join()<br>const users: UserResponseDto[] = await userService.getAllUsers();</pre><p><em>Promise&lt;UserResponseDto[]&gt; reads exactly like </em><em>CompletableFuture&lt;List&lt;UserResponse&gt;&gt;. <br>The parallel is precise and intentional.</em></p><h3>4. Lambdas: -&gt; vs =&gt;</h3><p><em>Java’s arrow </em><em>-&gt; becomes </em><em>=&gt; in TypeScript. That is the only difference.</em></p><pre>// Java<br>users.stream().map(user -&gt; user.getName()).toList();<br><br>// TypeScript<br>users.map(user =&gt; user.name);</pre><h3>5. .ts vs .tsx — Which File Do I Use?</h3><ul><li><strong><em>.ts</em></strong><em> = A standard like</em><em>.java file. Pure logic — Services, Clients, DTOs, Validators, Types.</em></li><li><strong><em>.tsx</em></strong><em> = A file that is also allowed to return HTML markup directly. <br>Used for UI components.</em></li></ul><p><em>If it renders something on screen → </em><em>.tsx. If it is pure business logic → </em><em>.ts.</em></p><h3>Act III: React Hooks Through a Spring Boot Lens</h3><p><em>React has things called </em><strong><em>Hooks</em></strong><em> — functions that start with </em><em>use. They sound cryptic until you map them to Spring Boot patterns you already know:</em></p><p><em>React Hook / ConceptSpring Boot / Java Analogy</em><em>useStatePrivate field + Observable Setter that triggers a UI re-render</em><em>useEffect@PostConstruct &amp; </em><em>ApplicationEventListeneruseCallbackStable method reference — prevents garbage recreation on every render</em><em>propsMethod parameters &amp; Constructor Dependency Injection</em></p><h3>useState — Why Can&#39;t I Just Change a Variable?</h3><p><em>In Java, modifying </em><em>this.count = 5 updates memory and your logic continues. Nobody is watching.</em></p><p><em>In the browser, changing a plain variable does </em><strong><em>nothing</em></strong><em> to the screen. React’s </em><em>useState gives you two things: the current value, and a </em><strong><em>trigger setter</em></strong><em> that tells React: &quot;The data changed — re-render now.&quot;</em></p><pre>const [users, setUsers] = useState&lt;UserResponseDto[]&gt;([]);<br>// Calling setUsers(data) updates the value AND schedules a UI refresh</pre><h3>useEffect — Your Frontend @PostConstruct</h3><p><em>In Spring Boot:</em></p><pre>@PostConstruct<br>public void init() {<br>    this.cachedUsers = userService.loadAll();<br>}</pre><p><em>In React, </em><em>useEffect with an empty </em><em>[] does exactly that — runs once when the component appears on screen:</em></p><pre>useEffect(() =&gt; {<br>    fetchUsers(); // Called exactly once on component mount<br>}, []);</pre><p><em>Pass a variable like </em><em>[userId] inside the array and it becomes an event listener: &quot;Re-run this block every time </em><em>userId changes.&quot;</em></p><h3>useCallback — Stable Method References</h3><p><em>In Java, a method on a </em><em>@Service bean exists once in memory. Calling it is just a pointer lookup.</em></p><p><em>In React, every time the UI re-renders, functions inside the component are </em><strong><em>recreated from scratch</em></strong><em>. </em><em>useCallback tells React: &quot;Cache this function reference. Only recreate it if its inputs change.&quot; This prevents unnecessary child component re-renders caused by a brand-new function reference on every cycle.</em></p><h3>Act IV: The Real Architecture — Reverse Engineering the Starter Project</h3><p><em>Let’s trace how data flows from the Spring Boot </em><em>@RestController all the way up to the browser, using real code from the repository.</em></p><pre>[ Spring Boot Controller ]    UserController.java  →  GET /api/v1/users<br>              │<br>              ▼<br>[ Frontend HTTP Client ]      HttpClient.ts  (Fetch wrapper)<br>              │<br>              ▼<br>[ Service Interface + Impl ]  UserService.ts  +  UserServiceImpl.ts<br>              │<br>              ▼<br>[ Validator Layer ]           UserValidator.ts  (Client-side @Valid equivalent)<br>              │<br>              ▼<br>[ Controller Hook ]           useUsers.ts  (State, loading, error, actions)<br>              │<br>              ▼<br>[ Presentation View ]         UserDashboardHeader.tsx  (Dumb, clean UI)</pre><h3>Step 1: The Spring Boot Side — The Source of Truth</h3><pre>// UserController.java<br>@RestController<br>@RequestMapping(&quot;/api/v1/users&quot;)<br>public class UserController {<br><br>    private final UserService userService;<br>    <br>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>    @GetMapping<br>    public ResponseEntity&lt;List&lt;UserResponse&gt;&gt; getAllUsers() {<br>        return ResponseEntity.ok(userService.getAllUsers());<br>    }<br>    @PostMapping<br>    public ResponseEntity&lt;UserResponse&gt; createUser(@Valid @RequestBody UserCreateRequest request) {<br>        return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(request));<br>    }<br>    @PutMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;UserResponse&gt; updateUser(<br>            @PathVariable String id, @Valid @RequestBody UserUpdateRequest request) {<br>        return ResponseEntity.ok(userService.updateUser(id, request));<br>    }<br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Void&gt; deleteUser(@PathVariable String id) {<br>        userService.deleteUser(id);<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><p><em>This is your contract. Every endpoint, every request body, every response shape this defines what the frontend needs to mirror.</em></p><h3>Step 2: The Service Layer — Interface + Implementation (Exactly Like Java!)</h3><pre>// UserService.ts — the contract (your @Service interface)<br>export interface UserService {<br>    getAllUsers(): Promise&lt;UserResponseDto[]&gt;;<br>    getUserById(id: string): Promise&lt;UserResponseDto&gt;;<br>    createUser(userDto: UserCreateRequestDto): Promise&lt;UserResponseDto&gt;;<br>    updateUser(id: string, userDto: UserUpdateRequestDto): Promise&lt;UserResponseDto&gt;;<br>    deleteUser(id: string): Promise&lt;void&gt;;<br>}</pre><pre>// UserServiceImpl.ts — the implementation (your UserServiceImpl.java)<br>export class UserServiceImpl implements UserService {<br>    private readonly endpoint = &quot;/api/v1/users&quot;;<br>    private readonly client: HttpClient;<br><br>    constructor(client: HttpClient = httpClient) {<br>        this.client = client;<br>    }<br>    public async getAllUsers(): Promise&lt;UserResponseDto[]&gt; {<br>        return this.client.get&lt;UserResponseDto[]&gt;(this.endpoint);<br>    }<br>    public async createUser(userDto: UserCreateRequestDto): Promise&lt;UserResponseDto&gt; {<br>        return this.client.post&lt;UserResponseDto, UserCreateRequestDto&gt;(this.endpoint, userDto);<br>    }<br>    public async updateUser(id: string, userDto: UserUpdateRequestDto): Promise&lt;UserResponseDto&gt; {<br>        return this.client.put&lt;UserResponseDto, UserUpdateRequestDto&gt;(`${this.endpoint}/${id}`, userDto);<br>    }<br>    public async deleteUser(id: string): Promise&lt;void&gt; {<br>        return this.client.delete&lt;void&gt;(`${this.endpoint}/${id}`);<br>    }<br>}<br>// Singleton export - like Spring&#39;s @Bean managed instance<br>export const userService: UserService = new UserServiceImpl();</pre><p><em>If you are a Spring Boot developer and this does not feel like home, read it again. It is the same structure.</em></p><h3>Step 3: The Validator — Client-Side @Valid</h3><pre>// UserValidator.ts<br>export class UserValidator {<br><br>public validateCreateUser(userDto: UserCreateRequestDto): ValidationResult {<br>        const errors: Record&lt;string, string&gt; = {};<br>        if (!userDto.name || userDto.name.trim().length === 0) {<br>            errors.name = &quot;Name is required&quot;;<br>        }<br>        if (!userDto.email || userDto.email.trim().length === 0) {<br>            errors.email = &quot;Email is required&quot;;<br>        }<br>        if (!userDto.role) {<br>            errors.role = &quot;Role is required&quot;;<br>        }<br>        return {<br>            isValid: Object.keys(errors).length === 0,<br>            errors<br>        };<br>    }<br>}</pre><p><em>@NotBlank, </em><em>@NotNull — same concept, different syntax.</em></p><h3>Step 4: The Custom Hook — The Frontend Controller</h3><pre>// useUsers.ts<br>&quot;use client&quot;;<br><br>import { UserResponseDto } from &quot;@/core/dto/UserResponseDto&quot;;<br>import { useState, useEffect, useCallback } from &quot;react&quot;;<br>import { userService } from &quot;@/core/service/UserServiceImpl&quot;;<br><br>export function useUsers() {<br><br>    const [users, setUsers] = useState&lt;UserResponseDto[]&gt;([]);<br>    const [isLoading, setIsLoading] = useState(false);<br>    const [error, setError] = useState&lt;string | null&gt;(null);<br><br>    const fetchUsers = useCallback(async () =&gt; {<br>        setIsLoading(true);<br>        setError(null);<br>        try {<br>            const usersData = await userService.getAllUsers();<br>            setUsers(usersData);<br>        } catch (err) {<br>            const errorMessage = err instanceof Error ? err.message : &quot;Failed to load users&quot;;<br>            setError(errorMessage);<br>        } finally {<br>            setIsLoading(false);<br>        }<br>    }, []);<br><br>    // @PostConstruct equivalent - fetch data once on component load<br>    useEffect(() =&gt; {<br>        fetchUsers();<br>    }, [fetchUsers]);<br><br>    return { users, isLoading, error, refreshUsers: fetchUsers };<br>}</pre><p><em>The hook returns </em><em>{ users, isLoading, error, refreshUsers } — a clean, typed API that any UI component can consume without knowing anything about HTTP or state management underneath.</em></p><h3>Step 5: The Presentation Component — The Dumb View</h3><pre>// UserDashboardHeader.tsx<br>import React from &quot;react&quot;;<br>import { Button } from &quot;@/ui/components/Button&quot;;<br><br>export interface UserDashboardHeaderProps {<br>    onAddUser: () =&gt; void;<br>}<br><br>export function UserDashboardHeader(props: UserDashboardHeaderProps) {<br>    const onAddUser = props.onAddUser;<br><br>    return (<br>        &lt;header className=&quot;app-header&quot;&gt;<br>            &lt;div className=&quot;app-title-group&quot;&gt;<br>                &lt;h1 className=&quot;app-title&quot;&gt;User Management&lt;/h1&gt;<br>                &lt;p className=&quot;app-subtitle&quot;&gt;<br>                    View, create, update, and manage system users with strict type safety.<br>                &lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;Button variant=&quot;primary&quot; onClick={onAddUser}&gt;<br>                + Add New User<br>            &lt;/Button&gt;<br>        &lt;/header&gt;<br>    );<br>}</pre><p><em>Clean. Declarative. No business logic in sight. Exactly how your </em><em>@RestController should look — thin, delegating everything downward.</em></p><h3>Part 2: The Kubernetes Story — One Cluster, Three Services</h3><h3>The New Problem: “It Works on My Machine”</h3><p><em>You have your Spring Boot API running on port </em><em>8080. <br>Your Next.js UI is on port </em><em>3000. MongoDB is on </em><em>27017. Life is good.</em></p><p><em>Then your team lead says: “Great. Now deploy this to the shared dev environment.”</em></p><p><em>You zip up your project, SSH into a server, and spend the next three hours debugging environment variables, conflicting ports, and missing connection strings.</em></p><p><em>There is a better way. It is called </em><strong><em>Kubernetes</em></strong><em>.</em></p><h3>The Mental Model: Spring Boot Concepts in K8s Clothing</h3><p><em>Kubernetes ConceptSpring Boot / Java Analogy</em><em>PodA running JVM process / container instance</em><em>DeploymentApplication packaged with a restart policy and replica count</em><em>StatefulSetA Deployment for stateful services (databases) that need stable identity</em><em>ServiceService Registry — stable DNS name that routes traffic to Pods</em><em>ConfigMapapplication.properties — externalised configuration</em><em>IngressAPI Gateway / Nginx Reverse Proxy</em></p><pre>             Internet<br>                │<br>                ▼<br>     [ Ingress Controller ]          ← ingress.yaml (The API Gateway)<br>        │              │<br>      /api/*           /*<br>        │              │<br>        ▼              ▼<br> [ Spring Boot ]  [ Next.js ]<br>  Service:8080    Service:3000<br>        │<br>        ▼<br>   [ MongoDB ]<br>   Service:27017</pre><h3>Scene 1: The ConfigMap — application.properties for the Cluster</h3><p><em>In Spring Boot:</em></p><pre>spring.data.mongodb.uri=mongodb://localhost:27017/user_db<br>server.port=8080</pre><p><em>In Kubernetes, the same thing lives in a </em><em>ConfigMap:</em></p><pre># 00-config/configmap.yaml<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: app-config<br>data:<br>  SPRING_DATA_MONGODB_URI: &quot;mongodb://mongodb-service:27017/user_db&quot;<br>  PORT: &quot;3000&quot;<br>  NEXT_PUBLIC_API_URL: &quot;&quot;</pre><p><em>Notice </em><em>mongodb-service — not </em><em>localhost. Inside Kubernetes, services talk to each other using </em><strong><em>service names as DNS hostnames</em></strong><em>. No IPs. No hardcoded addresses in code.</em></p><h3>Scene 2: MongoDB — The StatefulSet</h3><p><em>In a standard Kubernetes </em><em>Deployment, Pods are ephemeral — if a Pod crashes, it gets a fresh start with no memory of what came before.</em></p><p><em>For a </em><strong><em>database</em></strong><em>, that is catastrophic. A </em><em>StatefulSet solves this — a Deployment with memory:</em></p><pre># 01-database/mongodb-statefulset.yaml<br>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: mongodb<br>spec:<br>  serviceName: &quot;mongodb-service&quot;<br>  replicas: 1<br>  template:<br>    spec:<br>      containers:<br>        - name: mongodb<br>          image: mongo:7.0<br>          ports:<br>            - containerPort: 27017<br>          resources:<br>            requests:<br>              cpu: 50m<br>              memory: 128Mi<br>            limits:<br>              cpu: 250m<br>              memory: 512Mi<br>          livenessProbe:<br>            exec:<br>              command:<br>                - mongosh<br>                - --eval<br>                - &quot;db.adminCommand(&#39;ping&#39;)&quot;<br>            initialDelaySeconds: 20<br>            periodSeconds: 10<br>  volumeClaimTemplates:<br>    - metadata:<br>        name: mongodb-data<br>      spec:<br>        accessModes: [ &quot;ReadWriteOnce&quot; ]<br>        resources:<br>          requests:<br>            storage: 100Mi</pre><p><em>Two things to notice:</em></p><ol><li><strong><em>livenessProbe</em></strong><em>: Kubernetes runs </em><em>mongosh --eval &quot;db.adminCommand(&#39;ping&#39;)&quot; periodically. If MongoDB does not respond, the Pod is automatically restarted. This is your </em><em>@HealthIndicator from Spring Actuator, but enforced at the infrastructure level.</em></li><li><strong><em>volumeClaimTemplates</em></strong><em>: Kubernetes carves out 100MB of persistent disk mounted at </em><em>/data/db. Even if the Pod dies, the data survives.</em></li></ol><p><em>MongoDB’s headless Service gives the StatefulSet a stable DNS name:</em></p><pre># 01-database/mongodb-service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mongodb-service<br>spec:<br>  clusterIP: None   # Headless — direct DNS to Pod, no virtual IP<br>  ports:<br>    - port: 27017<br>      targetPort: 27017<br>  selector:<br>    app: mongodb</pre><h3>Scene 3: The Spring Boot Deployment</h3><pre># 02-backend/backend-deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: backend<br>spec:<br>  replicas: 1<br>  template:<br>    spec:<br>      containers:<br>        - name: backend<br>          image: backend:latest<br>          ports:<br>            - containerPort: 8080<br>          env:<br>            - name: SPRING_DATA_MONGODB_URI<br>              valueFrom:<br>                configMapKeyRef:<br>                  name: app-config<br>                  key: SPRING_DATA_MONGODB_URI    # ← Reads from ConfigMap<br>          resources:<br>            requests:<br>              cpu: 50m<br>              memory: 256Mi<br>            limits:<br>              cpu: 250m<br>              memory: 512Mi<br>          livenessProbe:<br>            httpGet:<br>              path: /actuator/health/liveness     # ← Spring Boot Actuator<br>              port: 8080<br>            initialDelaySeconds: 20<br>            periodSeconds: 15<br>          readinessProbe:<br>            httpGet:<br>              path: /actuator/health/readiness    # ← Spring Boot Actuator<br>              port: 8080<br>            initialDelaySeconds: 10<br>            periodSeconds: 5</pre><p><em>Spring Boot Actuator’s liveness and readiness endpoints become first-class citizens here. Kubernetes uses them to decide:</em></p><ul><li><strong><em>Liveness:</em></strong><em> Is this Pod healthy? If not, restart it.</em></li><li><strong><em>Readiness:</em></strong><em> Is this Pod ready to receive traffic? If not, remove it from the load balancer.</em></li></ul><h3>Scene 4: The Next.js Frontend Deployment</h3><pre># 03-frontend/frontend-deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: frontend<br>spec:<br>  replicas: 1<br>  template:<br>    spec:<br>      containers:<br>        - name: frontend<br>          image: frontend:latest<br>          ports:<br>            - containerPort: 3000<br>          env:<br>            - name: PORT<br>              valueFrom:<br>                configMapKeyRef:<br>                  name: app-config<br>                  key: PORT<br>            - name: NEXT_PUBLIC_API_URL<br>              valueFrom:<br>                configMapKeyRef:<br>                  name: app-config<br>                  key: NEXT_PUBLIC_API_URL       # ← Empty: Ingress handles routing<br>          resources:<br>            requests:<br>              cpu: 50m<br>              memory: 128Mi<br>            limits:<br>              cpu: 150m<br>              memory: 256Mi<br>          livenessProbe:<br>            httpGet:<br>              path: /<br>              port: 3000<br>            initialDelaySeconds: 15<br>            periodSeconds: 15</pre><p><em>NEXT_PUBLIC_API_URL is intentionally empty — the frontend calls relative paths like </em><em>/api/v1/users and the Ingress routes them to Spring Boot. No CORS configuration needed anywhere.</em></p><p><em>One more win: using </em><em>output: &#39;standalone&#39; in </em><em>next.config.js compresses the Docker image from over 1 GB down to under 100 MB — exactly like building a slim JAR instead of shipping your entire local Maven repository.</em></p><h3>Scene 5: The Ingress — Your API Gateway</h3><pre># 04-ingress/ingress.yaml<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: app-ingress<br>spec:<br>  rules:<br>    - http:<br>        paths:<br>          - path: /api<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: backend-service      # ← /api/* → Spring Boot<br>                port:<br>                  number: 8080<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: frontend-service     # ← /* → Next.js<br>                port:<br>                  number: 3000</pre><p><em>This single file eliminates CORS completely. The browser sees one origin. Requests to </em><em>/api/v1/users flow to Spring Boot. Requests to </em><em>/ flow to Next.js. No </em><em>@CrossOrigin. No </em><em>CorsConfig.java. The infrastructure handles it.</em></p><h3>The Deployment Order: Sequence Matters</h3><p><em>Just like Spring’s </em><em>@DependsOn controls bean initialisation order, the K8s deployment order matters:</em></p><pre>1. ConfigMap       →  Config must exist before anything reads it<br>2. MongoDB         →  Database must be healthy before the backend starts<br>3. Spring Boot     →  Backend must be running before the frontend calls APIs<br>4. Next.js         →  Frontend comes last<br>5. Ingress         →  Gateway wires everything together</pre><pre>kubectl apply -f deployment/k8s/00-config/<br>kubectl apply -f deployment/k8s/01-database/<br>kubectl apply -f deployment/k8s/02-backend/<br>kubectl apply -f deployment/k8s/03-frontend/<br>kubectl apply -f deployment/k8s/04-ingress/</pre><h3>Final Thoughts: Your New Mental Map</h3><p>You started this article as a Spring Boot developer staring at 400 lines of chaotic frontend code. You are leaving with a <strong>mental map</strong> that connects every concept you already know to a clean frontend and cloud equivalent.</p><p>You Already KnewNow You Also KnowJava record / DTOTypeScript interfaceCompletableFuture&lt;T&gt;Promise&lt;T&gt; + await@PostConstructuseEffect(() =&gt; {}, [])@Service + ServiceImplUserService.ts + UserServiceImpl.ts@Valid + Bean ValidationUserValidator.ts@RestController orchestrationCustom Hook (useUsers.ts)application.propertiesKubernetes ConfigMapStateless Spring Boot containerKubernetes DeploymentStateful DB (JPA + MongoDB)Kubernetes StatefulSet + Persistent Volume ClaimNginx / API GatewayKubernetes Ingress</p><p>The architecture was never different. The vocabulary just changed.</p><blockquote><em>📦 </em><strong><em>Full source code, all layers, all YAML:</em></strong><em><br></em><a href="https://github.com/akshat-vashishtha/nextjs-springboot-k8s-starter"><em>https://github.com/akshat-vashishtha/nextjs-springboot-k8s-starter</em></a></blockquote><blockquote><em>The repository contains the complete implementation — every TypeScript layer, the Spring Boot controllers, MongoDB integration, Dockerfiles, and every Kubernetes manifest shown in this guide. Dig in, break things, and build your own.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a91d35c7c17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring AI in Practice: A Code-Level Walkthrough of Chat, RAG, Chat Memory, and Streaming]]></title>
            <link>https://medium.com/@akshat.available/spring-ai-in-practice-a-code-level-walkthrough-of-chat-rag-chat-memory-and-streaming-5dd920b2f61c?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd920b2f61c</guid>
            <category><![CDATA[spring-ai-tutorial]]></category>
            <category><![CDATA[vector-database-qdrant]]></category>
            <category><![CDATA[openai-with-spring-boot]]></category>
            <category><![CDATA[java-ai-chatbot]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 09:37:34 GMT</pubDate>
            <atom:updated>2026-09-04T13:41:45.790Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn Spring AI in the most practical order. First understand core AI concepts with diagrams, then connect each API sequence diagram to the exact concept and code snippet in the repository.</p><ul><li><strong><em>OpenAI chat and embeddings</em></strong></li><li><strong><em>MongoDB-backed chat memory</em></strong></li><li><strong><em>Qdrant vector store for RAG</em></strong></li><li><strong><em>Advisor chain for observability, safety, and cross-cutting behaviour</em></strong></li><li><strong><em>Dynamic prompt templates</em></strong></li><li><strong><em>Server-Sent Events (SSE) streaming</em></strong></li></ul><h4>Complete Code Base</h4><p>Repository: <a href="https://github.com/akshat-vashishtha/spring-ai"><strong><em>https://github.com/akshat-vashishtha/spring-ai</em></strong></a></p><blockquote><strong>Note: Codebase has additional code for (ETL Pipeline (JSON, PDF, HTML), Tool Calling, Audio Transcription API, Model Context Protocol (Internal/External Server, Client) and AI Image Generation &amp; Download</strong> <strong>which is not part of this blog.</strong></blockquote><p>If you are new to Spring AI, the hardest part is not writing code. <br>The hardest part is connecting ideas. You see words like embeddings, RAG, memory, advisor chain, and streaming. Then you see many endpoints. It can feel like separate topics.</p><h4>This article fixes that. You will learn in one clean path:</h4><ol><li><strong><em>AI concepts first, in simple language</em></strong></li><li><strong><em>API sequence diagrams second, only as concept connectors</em></strong></li><li><strong><em>Small code snippets in every section so you can relate diagram to implementation</em></strong></li></ol><h4>How To Read This Article</h4><p>For each AI concept diagram section, follow this mini pattern:</p><ul><li><em>Meaning in plain language</em></li><li><em>Why it exists</em></li><li><em>Tiny code proof</em></li><li><em>Where to read more in the repo</em></li></ul><p>This pattern helps readers connect dots fast.</p><h3>Part 1: AI Concepts Diagrams in Simple Language</h3><h3>Concept 1: Vector Embeddings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JTM_-T3BVZ3gfWlkf33LA.png" /><figcaption>Text becomes vectors so the system can compare meaning, not only keywords.</figcaption></figure><p><strong>Simple meaning:</strong> A model cannot compare plain sentences mathematically. It first converts text into numbers called vectors. Similar meaning gives nearby vectors.</p><p><strong>Why this matters: </strong>This is the base of semantic search. Without embeddings, RAG quality drops quickly.</p><p><strong>Tiny code proof:</strong></p><pre>spring:<br>  ai:<br>    openai:<br>      embedding:<br>        options:<br>          model: text-embedding-3-small</pre><p><strong>Where in repo: <br></strong><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/resources/application.yaml">https://github.com/akshat-vashishtha/spring-ai/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">blob/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/resources/application.yaml">main/src/main/resources/application.yaml</a></p><p><strong>What to remember: </strong><em>Embeddings are not optional in RAG. They are the meaning layer.</em></p><h3>Concept 2: Knowledge Ingestion Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsiAlxBceD4XE8axv8k90A.png" /><figcaption>Ingestion prepares your data so retrieval can work later.</figcaption></figure><p><strong>Simple meaning:</strong> Before asking questions, your documents must enter the vector store. This is the feed step.</p><p><strong>Why this matters:</strong> No ingestion means no retrieval corpus. Then RAG has nothing useful to ground answers.</p><p><strong>Tiny code proof:</strong></p><pre>Document document = Document.builder()<br>        .text(request.content())<br>        .metadata(metadata)<br>        .build();<br><br>vectorStore.add(List.of(document));</pre><p><strong>Where in repo:</strong> <br><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/KnowledgeService.java">https://github.com/akshat-vashishtha/spring-ai/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">blob/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/KnowledgeService.java">main/src/main/java/com/learning/service/KnowledgeService.java</a></p><p><strong>What to remember:</strong> <em>RAG quality starts at ingestion quality.</em></p><h3>Concept 3: Basic RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w09hBrBGq7odup102R2rWA.png" /><figcaption>Basic RAG retrieves relevant context and then asks the model to answer.</figcaption></figure><p><strong>Simple meaning:</strong> The app finds relevant chunks from Qdrant and adds them to the prompt so the answer is grounded.</p><p><strong>Why this matters:</strong> This shifts from generic model answers to data-aware answers.</p><p><strong>Tiny code proof:</strong></p><pre>spring:<br>  ai:<br>    vectorstore:<br>      qdrant:<br>        host: localhost<br>        port: 6334<br>        collection-name: spring_ai_documents<br>        use-tls: false<br>        initialize-schema: true<br><br>@Bean<br>    public QuestionAnswerAdvisor questionAnswerAdvisor(VectorStore vectorStore) {<br>        return QuestionAnswerAdvisor.builder(vectorStore)<br>                .searchRequest(SearchRequest.builder()<br>                        .topK(3)<br>                        .similarityThreshold(0.5)<br>                        .build())<br>                .build();<br>    }<br><br>ChatResponse response = chatClient.prompt()<br>        .advisors(questionAnswerAdvisor)<br>        .user(prompt)<br>        .call()<br>        .chatResponse();</pre><p><strong>Where in repo:</strong> <br><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">https://github.com/akshat-vashishtha/spring-ai/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">blob/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">main/src/main/java/com/learning/config/RagConfig.java</a></p><p><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/ChatService.java">https://github.com/akshat-vashishtha/spring-ai/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">blob/</a><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/ChatService.java">main/src/main/java/com/learning/service/ChatService.java</a></p><p><strong>What to remember: </strong><em>Basic RAG equals retrieve first, generate second.</em></p><h3>Concept 4: Advanced RAG with Query Rewriting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FKY83YREvbkYyyg9TJPYA.png" /><figcaption>Advanced RAG improves retrieval by rewriting vague queries before search.</figcaption></figure><p><strong>Simple meaning:</strong> If the user asks a vague question, the system rewrites it into a clearer search query, then retrieves better context.</p><p><strong>Why this matters:</strong> Most RAG failures happen before generation, at retrieval quality.</p><p><strong>Tiny code proof:</strong></p><pre>spring:<br>  ai:<br>    vectorstore:<br>      qdrant:<br>        host: localhost<br>        port: 6334<br>        collection-name: spring_ai_documents<br>        use-tls: false<br>        initialize-schema: true<br><br>@Bean<br>    public RetrievalAugmentationAdvisor retrievalAugmentationAdvisor(VectorStore vectorStore,<br>                                                                      ChatClient.Builder chatClientBuilder) {<br>        return RetrievalAugmentationAdvisor.builder()<br>                .queryTransformers(RewriteQueryTransformer.builder()<br>                        .chatClientBuilder(chatClientBuilder.build().mutate())<br>                        .build())<br>                .documentRetriever(VectorStoreDocumentRetriever.builder()<br>                        .vectorStore(vectorStore)<br>                        .similarityThreshold(0.5)<br>                        .topK(3)<br>                        .build())<br>                .queryAugmenter(ContextualQueryAugmenter.builder()<br>                        .allowEmptyContext(true)<br>                        .build())<br>                .build();<br>    }<br><br>RetrievalAugmentationAdvisor.builder()<br>    .queryTransformers(RewriteQueryTransformer.builder()<br>        .chatClientBuilder(chatClientBuilder.build().mutate())<br>        .build())<br>    .build();</pre><p><strong>Where in repo: </strong><br><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java">https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/RagConfig.java</a></p><p><strong>What to remember: </strong><em>Better question in means better retrieval out.</em></p><h3>Concept 5: Chat Memory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh72C8jpSyJRfil0gwJO4A.png" /><figcaption>Memory keeps conversation continuity by injecting earlier turns.</figcaption></figure><p><strong>Simple meaning:</strong> The app uses conversationId to load previous messages, so follow-up questions keep context.</p><p><strong>Why this matters:</strong> Without memory, every question behaves like a new chat.</p><p><strong>Tiny code proof:</strong></p><pre>spring:<br>  mongodb:<br>    uri: mongodb://localhost:27017/spring-ai<br>  ai:<br>    chat:<br>      memory:<br>        repository:<br>          mongo:<br>            create-indices: true<br><br>@Bean<br>    public MessageChatMemoryAdvisor messageChatMemoryAdvisor(ChatMemory chatMemory) {<br>        return MessageChatMemoryAdvisor.builder(chatMemory).build();<br>    }<br><br>ChatResponse response = chatClient.prompt()<br>    .advisors(advisor -&gt; advisor.param(ChatMemory.CONVERSATION_ID, conversationId))<br>    .user(prompt)<br>    .call();</pre><p><strong>Where in repo: </strong><br><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/ChatService.java">https://github.com/akshat-vashishtha/spring-ai/main/src/main/java/com/learning/service/ChatService.java</a></p><p><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/AiConfig.java">https://github.com/akshat-vashishtha/spring-ai/main/src/main/java/com/learning/config/AiConfig.java</a></p><p><strong>What to remember: </strong><em>conversationId is the key that ties turns together.</em></p><h3>Concept 6: Advisor Chain</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XezJlSYU2kuuu5M3BpXSlA.png" /><figcaption>Advisors act like middleware around model calls for memory, safety, logs, and audit.</figcaption></figure><p><strong>Simple meaning:</strong> Advisors wrap each model call and add reusable behaviours like safeguards, memory injection, and audit logging.</p><p><strong>Why this matters:</strong> You keep service logic simple and move cross-cutting concerns to one pipeline.</p><p><strong>Tiny code proof:</strong></p><pre>@Bean<br>    public ChatClient chatClient(ChatModel chatModel,<br>                                 MessageChatMemoryAdvisor messageChatMemoryAdvisor,<br>                                 SimpleLoggerAdvisor simpleLoggerAdvisor,<br>                                 SafeGuardAdvisor safeGuardAdvisor,<br>                                 ExecutionAuditAdvisor executionAuditAdvisor) {<br>      <br><br>        return ChatClient.builder(chatModel)<br>                .defaultAdvisors(<br>                        messageChatMemoryAdvisor,<br>                        simpleLoggerAdvisor,<br>                        safeGuardAdvisor,<br>                        executionAuditAdvisor)<br>                .build();<br>    }</pre><p><strong>Where in repo: </strong><br><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/AiConfig.java">https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/config/AiConfig.java</a><br> <br><a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/advisor/ExecutionAuditAdvisor.java">https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/advisor/ExecutionAuditAdvisor.java</a></p><p><strong>What to remember: </strong><em>Advisor chain is the control plane of this backend.</em></p><h3>Bonus Concept: SSE Streaming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAo-Rwj9kldr3eln1GBheQ.png" /><figcaption>Streaming sends partial output quickly so users see progress in real time.</figcaption></figure><p><strong>Simple meaning: </strong>Instead of waiting for full text, the client receives tokens progressively.</p><p><strong>Why this matters:</strong> Perceived speed improves a lot, even with the same model.</p><p><strong>Tiny code proof:</strong></p><pre>public Flux&lt;ChatResponseDto&gt; stream(String prompt, String conversationId) {<br>        return chatClient.prompt()<br>                .advisors(advisor -&gt; advisor.param(ChatMemory.CONVERSATION_ID, conversationId))<br>                .user(prompt)<br>                .stream()<br>                .chatResponse()<br>                .map(chatResponseMapper::map);<br>    }</pre><p><strong>Where in repo:<br></strong> <a href="https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/StreamingChatService.java">https://github.com/akshat-vashishtha/spring-ai/blob/main/src/main/java/com/learning/service/StreamingChatService.java</a></p><p><strong>What to remember:</strong> <em>Streaming is a UX multiplier.</em></p><h3>Part 2: API Sequence Diagrams as Concept Connectors</h3><h3>API Sequence 1: GET /api/chat/ask</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFIfvf37jbKIs0PHwNAbZg.png" /><figcaption>This endpoint is the baseline AI call with memory and advisor support.</figcaption></figure><p><strong>Simple behaviour it mimics:</strong> Like a helpful assistant that remembers your ongoing conversation and responds in context.</p><p><strong>Concept connection in one line:</strong> This API combines chat memory with the advisor chain to produce safe, context-aware answers.</p><p><strong>Simple use case:</strong> Product FAQ chatbot where users ask follow-up questions in the same session.</p><h3>API Sequence 2: GET /api/chat/rag</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLVYirDUqrvQQZ3APL_-bw.png" /><figcaption>Retrieval-augmented answering using your own knowledge base.</figcaption></figure><p><strong>Simple behaviour it mimics:</strong> Like an assistant that quickly checks your internal notes before replying.</p><p><strong>Concept connection in one line: </strong>This API connects embeddings, stored knowledge, and basic RAG to ground answers in your data.</p><p><strong>Simple use case:</strong> Company policy assistant that answers based on internal documentation.</p><h3>API Sequence 3: GET /api/chat/rag/advance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeUMQB_80wS6B6rUP-CS-w.png" /><figcaption>Better answers by improving the question before retrieval.</figcaption></figure><p><strong>Simple behavior it mimics:</strong> Like an expert who first clarifies your question mentally, then searches for the best material.</p><p><strong>Concept connection in one line:</strong> This API uses advanced RAG with query rewriting to improve retrieval precision and final answer quality.</p><p><strong>Simple use case:</strong> Support bot handling vague user queries such as short or ambiguous questions.</p><h3>API Sequence 4: POST /api/chat/dynamic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-SeOr6jYu-0VYUbhT1Q6g.png" /><figcaption>Same AI engine, different behavior through dynamic prompt templates.</figcaption></figure><p><strong>Simple behaviour it mimics:</strong> Like giving the same assistant a different role, tone, and format for each task.</p><p><strong>Concept connection in one line:</strong> This API links prompt-template design with runtime chat behaviour while preserving memory and advisor safeguards.</p><p><strong>Simple use case:</strong> One endpoint serving multiple modes: teacher mode, reviewer mode, and architect mode.</p><h3>API Sequence 5: GET /api/chat/streaming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_0gyxR6U6LCbFI43QCWSQ.png" /><figcaption>Live token-by-token response for a faster user experience.</figcaption></figure><p><strong>Simple behaviour it mimics:</strong> Like watching someone type the answer live instead of waiting for the full paragraph.</p><p><strong>Concept connection in one line: </strong>This API applies the streaming concept so users see progressive output without waiting for completion.</p><p><strong>Simple use case: </strong>Interactive copilots and chat UIs where instant feedback improves user trust.</p><h3>API Sequence 6: POST /api/knowledge/documents and GET /api/knowledge/search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDD0rFJkTsAwoIgGVr-Qkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*-TUWGinURh559OX3fLYgIQ.png" /></figure><p><strong>Simple behaviour it mimics:</strong> Like building a searchable brain and then asking it for the most relevant memories.</p><p><strong>Concept connection in one line:</strong> These APIs connect ingestion and semantic retrieval, which are the core inputs behind all RAG answers.</p><p><strong>Simple use case:</strong> Uploading product manuals and then searching them for instant support answers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd920b2f61c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Writes Code, Multi-Agent Engineering Builds Products…]]></title>
            <link>https://medium.com/@akshat.available/ai-writes-code-multi-agent-engineering-builds-products-70aa22782a0c?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/70aa22782a0c</guid>
            <category><![CDATA[aidlc]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 11:10:47 GMT</pubDate>
            <atom:updated>2026-06-07T11:10:47.101Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A few months ago, I was doing what most developers are doing today, using AI to generate APIs, write tests, review code, and fix issues. It felt like a superpower. Tasks that once took hours were getting done in minutes, and every new model promised even more speed.</em></p><p><em>But as I worked on larger projects, I noticed something surprising. The biggest delays weren’t happening during coding. They came from unclear requirements, changing business rules, architectural rework, and production surprises. The code wasn’t creating these problems, it was simply exposing them.</em></p><p><em>That’s when my perspective changed. AI was helping me write software faster, but it wasn’t helping me make better decisions before development began. It led me to a simple question: if AI is getting better at writing code, why are software projects still struggling with the same problems they’ve always had?</em></p><h3>The Problem With How We Use AI Today</h3><p><em>Most teams bring AI into the process very late. Product discussions happen without it. Requirements are written without it. Architecture decisions are made without it. Once everything has been decided, AI is finally asked to generate code.</em></p><p><em>This approach works, but it also limits AI to the phase where uncertainty is already low. By the time development begins, many important decisions have already been made, and many expensive mistakes are already part of the project.</em></p><p><em>Software engineering is rarely limited by coding. Most challenges come from understanding the problem, defining requirements, evaluating trade-offs, and aligning people around the same vision. That’s where projects usually succeed or fail.</em></p><h3>The 12 Stages Most Teams Compress Into One</h3><p><em>For a long time, I believed software development was mostly about coding. The more projects I worked on, the more I realised coding is only one step in a much larger journey.</em></p><p><em>Before development begins, teams need to understand the problem, define outcomes, refine requirements, model the domain, break down features, design the solution, establish standards, and plan execution. After development, they still need to think about reliability, security, monitoring, operations, and launch readiness.</em></p><p><em>These activities form a journey that typically includes </em><strong><em>Product Discovery, Product Definition, Requirements Engineering, Domain Modelling, Feature Decomposition, Solution Architecture, Engineering Standards, Implementation Planning, Implementation Ready, Development, Production Hardening, and Launch Ready.</em></strong></p><p><em>Most teams go through these stages whether they realise it or not. The difference is that successful teams make them visible, while struggling teams compress everything into a single activity called development and try to solve every problem while writing code.</em></p><h3>When AI Stopped Being a Coding Assistant</h3><p><em>As I started looking at software delivery differently, I noticed that every stage required a different perspective. Product discovery needed product thinking. Requirements needed analysis. Architecture needed technical trade-offs. Production readiness needed operational thinking around reliability and resilience.</em></p><p><em>No single person naturally excels at every stage of delivery. Even experienced engineers have strengths in some areas and blind spots in others, yet successful products depend on having these perspectives available at the right time.</em></p><p><em>That’s when I stopped asking AI to behave only like a developer. Instead, I started asking it to think like different specialists throughout the journey. The same model that could generate code could also challenge assumptions, uncover risks, identify missing requirements, and expose operational concerns.</em></p><p><em>The model remained the same, but changing the perspective completely changed the quality of the conversations.</em></p><h3>The Rise of Multi-Agent Engineering</h3><p><em>This realisation completely changed how I viewed AI. For years, we treated AI as a single assistant sitting beside a developer. Multi-Agent Engineering introduces a different idea where multiple specialized agents collaborate throughout the delivery process.</em></p><p><strong><em>One agent focuses on customer value. Another validates requirements. Another explores domain boundaries. Another evaluates architecture. Others focus on testing, security, reliability, and operations. Each agent contributes insights from a different angle.</em></strong></p><p><em>The biggest value isn’t automation but perspective. What previously required multiple specialists can now be simulated much earlier, helping teams challenge assumptions and make better decisions before implementation begins.</em></p><p><em>For developers working on greenfield projects, this is a significant shift. Access to different viewpoints no longer depends entirely on team size. I</em><strong><em>t becomes possible to think through product, architecture, quality, and operational concerns much earlier than before.</em></strong></p><h3>From SDLC to AI-DLC</h3><p><em>Most of us learned software development through SDLC. We gather requirements, design solutions, write code, test features, and deploy applications. That process has served the industry well for decades and remains the foundation of software delivery.</em></p><p><em>What changes with AI-DLC is not the lifecycle itself but how intelligence is applied throughout it. Instead of using AI only during development, AI becomes part of discovery, planning, architecture, validation, and production readiness.</em></p><p><em>During discovery, AI can challenge assumptions. During requirements, it can identify ambiguity. During architecture, it can evaluate trade-offs. During planning, it can uncover risks. During production readiness, it can highlight concerns before they become incidents.</em></p><p><em>The result is not just faster development. Teams gain better visibility, stronger decisions, and fewer surprises throughout the journey.</em></p><h3>Where BMAD Fits In</h3><p><em>While exploring these ideas, I came across the BMAD Method. What immediately stood out wasn’t the tooling but the mindset. BMAD encourages teams to spend more time understanding the problem before rushing into implementation.</em></p><p><em>Instead of treating AI as a generic assistant, BMAD introduces specialized agents aligned to delivery roles. Product Managers, Architects, Analysts, Developers, QA specialists, and other roles contribute when their expertise is needed most.</em></p><p><em>This approach fits naturally with Multi-Agent Engineering. Different perspectives participate throughout the lifecycle, helping teams reduce uncertainty long before development begins.</em></p><p><em>In many ways, BMAD provides the structure while AI-DLC provides the intelligence. Together, they create a workflow focused on making better decisions, not just writing code faster.</em></p><h3>Bringing BMAD Into Your IDE</h3><p><em>One reason BMAD is gaining attention is because getting started is surprisingly simple. It supports modern AI development tools such as Cursor, Claude Code, Windsurf, and VS Code, making it easy to integrate into existing workflows.</em></p><p><em>The setup process is straightforward. Clone the repository, follow the installation guide, import the agents into your preferred environment, and start experimenting with role-based workflows. The project includes templates, workflows, examples, and ready-to-use agents.</em></p><p><strong><em>BMAD Repository: </em></strong><a href="https://github.com/bmad-code-org/bmad-method"><strong><em>https://github.com/bmad-code-org/bmad-method</em></strong></a></p><p><em>If you’re interested in the broader Multi-Agent ecosystem, Microsoft AutoGen, CrewAI, and the OpenAI Agents SDK are also worth exploring. Each project offers a different approach to building collaborative AI systems.</em></p><p><em>More importantly, they all encourage the same shift in thinking. AI is no longer just an assistant helping with code. It becomes a collection of specialists helping teams think through problems from multiple perspectives.</em></p><h3>The Future Developer</h3><p><em>The biggest lesson from this journey wasn’t that AI can generate code. We already know that. The more important lesson was realizing that software engineering has never been primarily about code. Code is simply the final output of a long chain of decisions.</em></p><p><em>Every requirement, business rule, architectural trade-off, and operational concern eventually finds its way into the codebase. As AI continues reducing the effort required to implement software, the value of making better decisions becomes even more important.</em></p><p><em>Future developers will still write code, but their biggest advantage may come from understanding problems better, asking better questions, and bringing the right perspectives into the conversation at the right time.</em></p><p><em>That’s what makes AI-DLC interesting to me. </em><strong><em>It isn’t about replacing developers or eliminating teams. It’s about helping engineers think with the depth, structure, and diversity of an entire engineering organisation before implementation even begins.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70aa22782a0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise Integration Patterns in Aviation Systems: Building Scalable and Future-Ready…]]></title>
            <link>https://medium.com/@akshat.available/enterprise-integration-patterns-in-aviation-systems-building-scalable-and-future-ready-1bd50491d4ef?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd50491d4ef</guid>
            <category><![CDATA[enterprise-integration]]></category>
            <category><![CDATA[eip-4844]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Thu, 21 May 2026 06:25:05 GMT</pubDate>
            <atom:updated>2026-05-21T06:25:05.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enterprise Integration Patterns in Aviation Systems: Building Scalable and Future-Ready Architectures</h3><h3>Preface</h3><p><em>While working on enterprise integration systems, one thing became very clear, building integrations is easy, but maintaining them as systems grow is the real challenge. Modern airlines continuously exchange operational events between scheduling systems, airport operations, baggage platforms, engineering services, crew workflows, and passenger systems in real time. Initially direct integrations feel manageable, but over time systems become tightly coupled, difficult to debug, and increasingly complex whenever new business features or operational workflows are introduced.</em></p><p><em>As architects and developers, scaling infrastructure alone is never enough. Systems should also be designed to scale functionally, operationally, and architecturally for the next 3–5 years without creating logical coupling between enterprise platforms. This is where Enterprise Integration Patterns (EIP) become extremely valuable because they provide standardized ways to route messages, orchestrate workflows, coordinate distributed systems, and build integrations that remain scalable, maintainable, and future-ready as enterprise ecosystems continue evolving.</em></p><h3>Problem Scope</h3><p><em>Traditional enterprise systems mostly grow through point-to-point integrations where every application directly communicates with multiple downstream systems. Initially this feels simple, but as operational platforms increase, integration complexity grows rapidly.</em></p><blockquote>The Complexity Formula Connections = N(N-1)/2</blockquote><p><em>If an airline operates 10 enterprise systems, the architecture may already require 45 direct integrations. Now imagine handling flight delays, baggage updates, crew notifications, maintenance alerts, and airport operations through this tightly connected ecosystem. Over time, routing logic gets duplicated, workflows become difficult to trace, retries become inconsistent, and small downstream failures start impacting multiple systems together. A simple operational message slowly turns into integration chaos, making enterprise systems difficult to scale, maintain, and evolve.</em></p><h3>Solution Approach</h3><p><em>Instead of directly connecting every enterprise system together, modern architectures introduce an integration layer using the </em><strong><em>Hub-and-Spoke</em></strong><em> model where the integration hub becomes the central communication backbone between operational systems. Rather than every application maintaining separate integrations, systems simply publish and consume messages through the hub, making the architecture cleaner and easier to manage.</em></p><p><em>This integration layer becomes responsible for routing messages, filtering unnecessary events, orchestrating workflows, transforming payloads, and coordinating communication between distributed systems. A flight scheduling system can publish operational updates, airport systems can consume relevant events, maintenance services can react to engineering notifications, and passenger workflows can independently trigger downstream processes without tightly coupling integrations together.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*pN5cLbEmZOy1vf987qG6rQ@2x.jpeg" /></figure><p><em>This is where Enterprise Integration Patterns (EIP) become important. They provide standardised ways to solve real integration problems like message routing, workflow coordination, payload processing, and distributed communication between enterprise systems. In simple terms, EIPs help organisations understand where a message should go, who should consume it, and how systems should coordinate reliably inside large-scale enterprise architectures.</em></p><h3>Enterprise Integration Pattern (Message Routing)</h3><h4>1. Content-Based Router</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*gOJG2efYl4i1-qJQC_qzCg@2x.jpeg" /></figure><p><em>Enterprise systems often receive operational events that require different downstream workflows depending on business conditions. Instead of forwarding every message into the same workflow, the integration layer first evaluates the payload and decides where the message should go next.</em></p><p><strong><em>Technical Concept: </em></strong><em>A Content-Based Router inspects message content, headers, metadata, or business attributes and dynamically routes the message toward the correct downstream destination. Routing decisions are usually based on business rules, conditions, or operational priorities.</em></p><p><strong><em>Aviation Use Case: </em></strong><em>An aircraft engineering platform may publish fault events where critical Aircraft-on-Ground failures require emergency maintenance handling while minor warnings only need routine operational processing.</em></p><p><strong><em>System Integration Understanding: </em></strong><em>The integration hub receives operational events from upstream systems, applies routing rules based on payload content, and forwards the message toward the correct downstream queue, API, topic, workflow engine, or operational service without tightly coupling systems together.</em></p><p><strong><em>Original EIP Reference: </em></strong><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/ContentBasedRouter.html"><em>Content-Based Router Pattern</em></a></p><h3>2. Message Filter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Q8fRu2SxH9LQnV0A0CIOrg@2x.jpeg" /></figure><p><em>Enterprise systems continuously generate large amounts of operational traffic, but not every event is useful for downstream processing. Forwarding unnecessary events downstream only creates operational noise and increases system overhead.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Message Filter validates incoming messages against predefined business conditions and removes irrelevant, duplicate, noisy, or low-priority events before they enter downstream workflows.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> Airport monitoring systems may continuously send heartbeat signals, telemetry logs, and device status updates simply to confirm systems remain active, while only operational alerts like equipment failures or runway warnings actually require downstream processing.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> Incoming operational events first enter the integration hub where validation and filtering rules remove unnecessary records before forwarding only meaningful business messages toward downstream systems, dashboards, operational workflows, or notification services.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/Filter.html"><em>Message Filter Pattern</em></a></p><h3>3. Dynamic Router</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*1u9USuB6k_mA0uzec7DwdQ@2x.jpeg" /></figure><p><em>Operational workflows continuously change in real time, making static routing difficult to maintain in enterprise environments.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Dynamic Router evaluates live runtime conditions, operational context, external rules, or system states before deciding where a message should move next. Unlike static routing, routing decisions evolve dynamically during execution.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> A flight-arrival event may move toward different gate-management workflows depending on airport congestion, weather conditions, or runway availability at that exact moment.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> The integration hub combines operational events with runtime business conditions and dynamically redirects workflows toward the correct downstream systems without modifying application-level integrations.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/DynamicRouter.html"><em>Dynamic Router Pattern</em></a></p><h3>4. Recipient List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*YX-akZRlMe3VjX3b1vi8Ew@2x.jpeg" /></figure><p><em>Some operational events are important for multiple systems simultaneously, and every downstream system may independently process the same business event.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Recipient List distributes copies of the same message toward multiple downstream consumers based on predefined recipient rules or subscription conditions.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> The moment a flight lands, airport operations, baggage systems, passenger notification services, analytics platforms, and crew systems may all require the same operational update.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> One operational event enters the integration hub, recipient rules identify all interested downstream systems, and message copies are distributed toward queues, APIs, topics, or operational services where every consumer independently processes the same event.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/RecipientList.html"><em>Recipient List Pattern</em></a></p><h3>5. Splitter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*lQQUUPtEuzci0I1yWCDODA@2x.jpeg" /></figure><p><em>Large operational payloads are difficult to process efficiently in distributed environments because one large message may contain hundreds of independent business records.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Splitter breaks one large payload into multiple smaller independent messages so that downstream systems can process records individually and in parallel.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> A cargo manifest file may contain hundreds of airway bills or shipment records inside one payload, where every record needs separate processing across customs, logistics, and tracking systems.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> File ingestion services receive large payloads, splitter processors divide the content into smaller business events, and independent records move separately through downstream workflows like tracking systems, compliance validation, customs processing, or operational services.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/Sequencer.html"><em>Splitter Pattern</em></a></p><h3>6. Aggregator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*prV7pOd3v3LFP3W5wagfnQ@2x.jpeg" /></figure><p><em>Some operational decisions depend on multiple distributed events arriving successfully from different enterprise systems.</em></p><p><strong><em>Technical Concept:</em></strong><em> An Aggregator collects related messages, correlates them using business identifiers, and combines them into one final business outcome once all required conditions are satisfied.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> Aircraft departure readiness depends on fueling updates, boarding closure events, baggage loading confirmations, and engineering clearances arriving from different operational systems.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> The integration hub continuously listens to related operational events, correlates them using identifiers like Flight-ID or Aircraft-ID, and publishes a final aggregated operational status once all required activities complete successfully.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/Aggregator.html"><em>Aggregator Pattern</em></a></p><h3>7. Resequencer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*jGkMBBk0e25SsrhtNPcNHw@2x.jpeg" /></figure><p><em>Distributed systems do not always deliver events in the correct operational order because of asynchronous communication and network delays.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Resequencer temporarily stores incoming messages, validates sequence order, and forwards events only after restoring the correct processing sequence.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> Because of network latency, “Boarding Closed” events may sometimes arrive before “Boarding Started,” creating invalid workflow states downstream.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> The integration layer buffers incoming operational messages, validates sequencing rules using event identifiers or timestamps, and forwards events downstream only after restoring the correct operational order.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/Resequencer.html"><em>Resequencer Pattern</em></a></p><h3>8. Composed Message Processor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*p7pig7nT_jaalvg5B6L-Qw@2x.jpeg" /></figure><p><em>Complex operational workflows often require multiple enterprise systems to participate together before generating one final business outcome.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Composed Message Processor breaks large workflows into smaller processing steps, distributes requests across multiple systems, and later combines downstream responses into one final operational result.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> A route-change request may require weather validation, engineering approval, fuel optimization analysis, and airport operational clearance before execution.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> The integration hub orchestrates communication between multiple downstream systems, collects processing responses independently, and combines the results into one final operational decision before forwarding workflows downstream.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/DistributionAggregate.html"><em>Composed Message Processor Pattern</em></a></p><h3>9. Scatter-Gather</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*EwO9yKV35MRsRjdUsWRBOw@2x.jpeg" /></figure><p><em>Some operational decisions require responses from multiple systems simultaneously before business processing can continue.</em></p><p><strong><em>Technical Concept:</em></strong><em> Scatter-Gather broadcasts requests toward multiple downstream systems in parallel and later gathers all responses into one final result.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> Airlines may need real-time fuel pricing from several airport vendors before selecting the most optimized operational option.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> The integration hub distributes requests simultaneously toward multiple downstream systems, independently collects responses, and combines all operational results into one final business response for decision-making systems.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/BroadcastAggregate.html"><em>Scatter-Gather Pattern</em></a></p><h3>10. Routing Slip</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*b69rviXY4wKnxyKAr55xag@2x.jpeg" /></figure><p><em>Not every operational workflow follows the same processing path because workflows may dynamically change depending on business requirements.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Routing Slip stores workflow instructions inside the message itself so downstream systems can dynamically determine the next processing step during execution.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> A VIP passenger workflow may require lounge access, baggage prioritisation, premium transport coordination, and priority boarding services.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> Workflow instructions travel together with the operational message, and every downstream service reads the next processing step before forwarding the event toward the next operational workflow dynamically.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/RoutingTable.html"><em>Routing Slip Pattern</em></a></p><h3>11. Process Manager</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*kgXvTthLgzDj5szVaaDxpA@2x.jpeg" /></figure><p><em>Enterprise workflows often involve long-running operational activities that require coordination between multiple teams and systems.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Process Manager maintains workflow state, monitors operational progress, coordinates activities between systems, and controls execution flow across distributed workflows.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> Aircraft turnaround operations require fueling, baggage handling, catering, engineering inspections, passenger boarding, and cleaning activities to complete in coordination before departure.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> The integration hub continuously tracks operational workflow state, monitors downstream processing activities, and automatically triggers the next operational step as systems complete their assigned responsibilities.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/ProcessManager.html"><em>Process Manager Pattern</em></a></p><h3>12. Message Broker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*vCK_NdhYNDkHJC5vYr7jYQ@2x.jpeg" /></figure><p><em>Modern enterprise systems cannot scale efficiently using direct point-to-point integrations forever because tightly coupled communication becomes difficult to maintain.</em></p><p><strong><em>Technical Concept:</em></strong><em> A Message Broker acts as the centralized communication backbone that enables asynchronous message exchange between producers and consumers without requiring direct system dependencies.</em></p><p><strong><em>Aviation Use Case:</em></strong><em> Airport operations, maintenance systems, crew platforms, passenger services, and operational dashboards may all independently exchange real-time operational events through a centralised messaging backbone.</em></p><p><strong><em>System Integration Understanding:</em></strong><em> Producers publish operational events into the integration backbone while downstream systems independently consume messages through queues, topics, event streams, or messaging channels based on business requirements.</em></p><p><strong><em>Original EIP Reference:</em></strong><em> </em><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/MessageBroker.html"><em>Message Broker Pattern</em></a></p><h3>Final Thoughts</h3><p><em>Enterprise Integration Patterns are not just theoretical architecture concepts, they are practical solutions for solving real integration problems inside modern enterprise systems. Whether it is routing operational events, filtering unnecessary messages, orchestrating workflows, or coordinating distributed systems, EIPs help organisations build integrations that are scalable, maintainable, and easier to understand.</em></p><p><em>If we observe closely, most enterprise workflows already follow these patterns unknowingly. A message arrives, business rules evaluate it, systems consume relevant events, workflows coordinate across services, and operational decisions move forward automatically. That entire journey is Enterprise Integration Patterns working silently behind modern enterprise architectures.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd50491d4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Real-Time Aviation Data Pipeline(ETLQ) Using Kafka, GraphQL, MongoDB, and Domain-Driven…]]></title>
            <link>https://medium.com/@akshat.available/designing-a-real-time-aviation-data-pipeline-etlq-using-kafka-graphql-mongodb-and-domain-driven-55c4e2400143?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/55c4e2400143</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[extract-transform-load]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Fri, 15 May 2026 16:13:23 GMT</pubDate>
            <atom:updated>2026-05-15T16:13:23.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a Real-Time Aviation Data Pipeline(ETLQ) Using Kafka, GraphQL, MongoDB, and Domain-Driven Architecture</h3><h3>Preface</h3><p><em>Before designing this platform, I spent a lot of time understanding how flight plans actually behave from a domain perspective. Aviation systems look simple from outside, but operationally they behave like continuously evolving state machines involving routing, fuel calculations, weather overlays, ETOPS validations, redispatch scenarios, and operational constraints. I had written about this domain perspective earlier in my blog, </em><a href="https://medium.com/@akshat.available/when-a-flight-plan-becomes-code-understanding-domain-driven-design-through-aviation-806431d48b56?utm_source=chatgpt.com"><em>When a Flight Plan Becomes Code — Understanding Domain-Driven Design Through Aviation</em></a><em>, and that understanding eventually became the foundation for designing this platform.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0ioa8q-hPxYqQF3tSpz8g.png" /></figure><p><em>Most backend systems process data, but aviation systems process operational decisions. A flight plan may appear as a simple XML file, yet internally it contains routing information, fuel calculations, weather overlays, alternate airports, ETOPS validations, redispatch logic, and operational restrictions. More importantly, the same flight plan keeps evolving throughout the day as operational conditions change. Initially, the platform treated these XMLs like ordinary enterprise documents, but very quickly it became clear that the challenge was not XML parsing, it was continuously managing evolving operational state in real time. That realisation completely changed the architecture.</em></p><h3>Problem Scope</h3><p><em>The initial version of the system followed a traditional enterprise design where XML files arrived, JAXB parsed them, services processed them, and entities were stored in databases. On paper, the architecture looked clean, but real operational traffic exposed the limitations quickly. Flight plans became deeply nested operational structures containing weather overlays, fuel sections, redispatch logic, alternate airport chains, and route expansions. Different consumers needed completely different views of the same flight plan, while Kafka retries started introducing duplicate processing scenarios. The biggest issue, however, was conceptual the system was treating flight plans as static documents instead of continuously evolving operational aggregates.</em></p><h3>Solution Approach</h3><p><em>Instead of building one large processing engine, the platform was redesigned around operational responsibilities. The architecture naturally separated into four stages: Extract, Transform, Load, and Query. Each layer solved a completely different engineering problem. The Extract layer focused on ingestion reliability, the Transform layer handled domain interpretation, the Load layer managed distributed persistence consistency, and the Query layer optimized operational access patterns. Once these responsibilities became isolated, the system became significantly easier to scale, maintain, and evolve.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-Ot8iIYBKb_-QR29DvN3g.png" /></figure><h3>Extract Layer — Building the Streaming Ingestion Pipeline</h3><p><em>One of the most important decisions in the platform was intentionally keeping the Extract layer free from business logic. The service simply polls XML flight plans from Azure File Share using Apache Camel, compresses them into GZIP byte arrays, publishes them into Kafka, and archives the original XML into Azure Blob Storage. No parsing or operational interpretation happens here because aviation schemas evolve constantly, and tightly coupling ingestion with domain logic eventually creates long-term maintenance issues. By treating XML as an immutable operational event rather than a business object, the ingestion pipeline remained lightweight and stable even as upstream formats evolved.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lufkPQYFNOlHUgchZRRaqw.png" /></figure><p><em>Apache Camel fit naturally into this layer because the problem itself was fundamentally an integration problem involving streaming ingestion, retry handling, multicast routing, and Azure integration. Compressing XML before Kafka publishing significantly reduced broker storage overhead and network traffic because aviation XMLs become extremely large once weather overlays and operational sections are included. The archive strategy became equally important because every original XML stored in Blob Storage enabled replayability, disaster recovery, audit traceability, and schema migration flexibility. Over time, the original XML effectively became the operational source of truth.</em></p><h3>Transform Layer — Converting XML Into Operational Intelligence</h3><p><em>If the Extract layer handles transportation, the Transform layer handles interpretation. The service consumes compressed Kafka events, decompresses them, unmarshals the XML using JAXB, and translates operational sections into domain behavior. However, JAXB objects were intentionally prevented from becoming business models because external schemas should never dictate internal architecture. Instead of directly generating entities, the platform transforms XML sections into isolated domain commands such as </em><em>FuelCommand, </em><em>RouteCommand, </em><em>AlternateCommand, and </em><em>MELCommand.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbFM31xVJ6Z3tSA6n6o6DA.png" /></figure><p><em>The Command Pattern significantly improved maintainability because each operational concern evolved independently. Fuel logic remained isolated from routing logic, while redispatch processing stayed modular and easier to extend. The system slowly stopped behaving like middleware and started behaving like aviation software. But eventually Kafka retries introduced another distributed systems challenge. Kafka guarantees delivery, not uniqueness, which meant duplicate events could appear during retries and rebalance scenarios. That is where the </em><em>FlightPlanAggregate became the operational consistency boundary of the platform. Every mutation flows through the aggregate, while Caffeine Cache ensures idempotent processing behind the scenes so that duplicate events cannot corrupt operational state.</em></p><h3>Load Layer — Solving Distributed Persistence</h3><p><em>Once the operational aggregate becomes fully assembled, persistence begins. Initially, persistence looked simple store the aggregate in MongoDB and cache it in Redis. But operational systems usually serve two completely different workloads simultaneously. Operational dashboards require extremely fast access to active-day flight plans, while analytical systems need flexible querying over historical operational data. MongoDB became the operational memory layer because flight plans are deeply nested and schema-flexible, while Redis became the operational speed layer optimised for low-latency operational access.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gae_pQww8FljRnjnwz9JOA.png" /></figure><p><em>The Observer Pattern helped decouple persistence orchestration cleanly, allowing MongoDB and Redis to behave as independent persistence strategies instead of tightly coupled operations. Both writes execute concurrently using </em><em>CompletableFuture, significantly reducing persistence latency during operational spikes. The most important reliability guarantee here was that Kafka acknowledgment happens only after both MongoDB and Redis succeed. That single decision provided proper at-least-once delivery semantics while preventing partial persistence failures.</em></p><h3>Query Layer — Building the Operational Read Model</h3><p><em>The final challenge appeared while exposing flight plans to downstream systems. Pilots needed route and fuel information, dispatch systems required complete operational visibility, airport operations cared about ETA and gate details, and analytics systems needed historical operational trends. REST APIs quickly became difficult to scale because endpoint counts increased while payloads became oversized and inefficient. GraphQL solved this naturally by allowing consumers to request only the fields they actually needed. </em><strong><em>The Query layer uses Netflix DGS GraphQL with a smart cache-decision layer underneath.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ps34AxXOyt7Hrb98kxFuwg.png" /></figure><p><em>Queries targeting active-day operational flights hit Redis first, while historical queries directly access MongoDB. This simple routing strategy significantly improved read performance. The most elegant optimisation was dynamic MongoDB projection generation using GraphQL </em><em>selectionSet. If a consumer requests only flight number, route, and fuel summary, MongoDB fetches only those fields instead of the complete operational aggregate. Because flight plans are extremely large operational documents, reducing unnecessary payload retrieval dramatically improved query efficiency and memory utilisation.</em></p><h3>Final Thoughts</h3><p><em>The most important lesson from this platform had very little to do with Kafka, MongoDB, Redis, GraphQL, or Apache Camel individually. The real lesson was understanding that operational domains already contain the architecture within them. Once the system started modelling operational events, aggregates, command flows, and evolving operational state, the technology choices became much clearer naturally. The Extract layer solved streaming reliability, the Transform layer solved domain interpretation, the Load layer solved consistency and distributed persistence, and the Query layer solved operational data access. Together, these layers formed a continuous real-time operational pipeline for evolving flight state, where distributed systems, domain modelling, and data engineering finally started behaving like one coherent platform instead of separate technologies stitched together.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55c4e2400143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a Flight Plan Becomes Code: Understanding Domain-Driven Design Through Aviation]]></title>
            <link>https://medium.com/@akshat.available/when-a-flight-plan-becomes-code-understanding-domain-driven-design-through-aviation-806431d48b56?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/806431d48b56</guid>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aviation]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 11:29:39 GMT</pubDate>
            <atom:updated>2026-03-08T11:29:39.246Z</atom:updated>
            <content:encoded><![CDATA[<h4>“Software is not just code. It is a conversation between the machine and the problem it solves.”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmReX4U71jKuBU1Os_EnMw.png" /></figure><h4>Preface: The Afternoon at Mumbai ATC</h4><p>Picture this: You’re sitting in a glass-walled room at Mumbai’s Air Traffic Control center. Outside, aircraft are lining up on Runway 27L and 27R. On your screen, dozens of flight plans are flowing in each one a dense XML file, thousands of lines deep, packed with waypoints, fuel calculations, route legs, ETOPS constraints, and revision histories.</p><p>Now imagine you’re a software engineer tasked with building the system that <strong>ingests, parses, validates, and serves</strong> those flight plans as a clean, reliable API for dispatch managers and pilots.</p><p><strong><em>Where do you even begin?</em></strong></p><p><strong>Most engineers would say:</strong> “Let’s look at the XML schema and design a database to match it.”</p><p><strong>But a seasoned architect would pause and say:</strong> “No. Let’s understand the domain first.”<strong> </strong>And that, right there, is the philosophical heart of <strong>Domain-Driven Design</strong> (DDD).</p><h4>What Is Domain-Driven Design? (And Why It Matters in Aviation)</h4><p>Domain-Driven Design is an approach to software development introduced by <strong>Eric Evans</strong> in his legendary blue book. At its core, DDD argues that:</p><blockquote><strong>The structure and language of your code should match the structure and language of the business problem you’re solving.</strong></blockquote><p>In the aviation world, this is not a luxury it’s a necessity. Pilots don’t talk about row_id or xml_element_ref. They talk about:</p><blockquote><strong>-Flight Plan:</strong> The master document authorising a flight.<br><strong>-Route:</strong> The sequence of airways and fixes connecting origin to destination.<br><strong>-Waypoint:</strong> A geographical fix (a point in the sky defined by latitude/longitude or a radio navaid).<br><strong>-Leg:</strong> Asegment of the route between two waypoints.<br><strong>-ETOPS:</strong> Extended-range Twin-engine Operational Performance Standards governing how far a twin-engine plane can fly from a diversion airport.<br><strong>-Fuel Plan:</strong> Taxi fuel, Trip fuel, Contingency fuel, Reserve fuel.<br><strong>-Revision:</strong> A formal amendment to an already-approved flight plan.</blockquote><p>If your code does not speak this language, your system will fail to communicate with domain experts, leading to bugs that are hard to find and even harder to fix.</p><h4>Part 1: Establishing the Ubiquitous Language (Aviation’s Shared Dictionary)</h4><p>Imagine a standup meeting where an Aviation Subject Matter Expert (SME) says:</p><blockquote>&quot;We need to compare the current revision of <strong>FPL-AI101–23-VABB-VIDP</strong> with the previous one to check if the fuel summary has changed.”</blockquote><p>Now imagine a developer responding:</p><blockquote>“Sure, I’ll query <strong>fp_table where rev_flag = 1</strong> and compare the fuel_xml_blob.”</blockquote><p>That gap between how the business talks and how the code thinks is where bugs are born and trust is eroded.</p><p>DDD’s antidote is the <strong>Ubiquitous Language</strong>: a shared vocabulary used by everyone business analysts, product managers, and engineers both in conversation and in code.</p><p>In Java, this might look as simple as:</p><pre>//BAD - Disconnected from the domain<br>public class FpData {<br>    private String fpId;<br>    private int revNum;<br>    private String xmlBlob;<br>}<br><br>//GOOD - Speaks the domain language<br>public class FlightPlan {<br>    private FlightPlanId flightPlanId;  // e.g., FPL-AI101-23-VABB-VIDP<br>    private RevisionInfo revision;       // current revision details<br>    private FuelSummary fuelSummary;     // structured fuel breakdown<br>    private Route route;                 // the actual flight path<br>    private FlightPlanStatus status;     // FILED, APPROVED, CANCELLED<br>}</pre><p>Every class name, every method name, every variable they all echo what a dispatcher or pilot would immediately recognise.</p><h4>Part 2: Building the Domain Model (Entities, Value Objects &amp; Aggregates)</h4><p>Here’s where DDD gets beautifully structured. Not all domain objects are created equal.</p><p><strong>Entities — </strong>Objects with Identity</p><p>An Entity has a unique identity that persists over time. Two entities are different even if all their attributes are the same, because they are <em>different things.</em></p><pre>// FlightPlan is an Entity - identified by its FlightPlanId<br>@Entity<br>public class FlightPlan {<br><br>    @EmbeddedId<br>    private FlightPlanId flightPlanId; // e.g., &quot;FPL-AI101-23-VABB-VIDP&quot;<br><br>    private AircraftInfo aircraftInfo; // e.g., Boeing 787, VT-ANB<br>    private Route route;<br>    private FuelSummary fuelSummary;<br>    private RevisionInfo revisionInfo;<br>    private FlightPlanStatus status;<br><br>    public void revise(FuelSummary newFuelSummary, Route newRoute) {<br>        // Domain behavior lives HERE, not in a service class<br>        this.revisionInfo = this.revisionInfo.increment();<br>        this.fuelSummary = newFuelSummary;<br>        this.route = newRoute;<br>    }<br>}</pre><pre>// Route is also an Entity — it has identity, it has legs<br>public class Route {<br>    private RouteId routeId;<br>    private List&lt;Leg&gt; legs;<br><br>    public Leg getLegBySequence(int sequence) {<br>        return legs.stream()<br>            .filter(leg -&gt; leg.getSequence() == sequence)<br>            .findFirst()<br>            .orElseThrow(() -&gt; new LegNotFoundException(<br>                &quot;Leg not found for sequence: &quot; + sequence));<br>    }<br>}</pre><p><strong>Value Objects — </strong>Objects Without Identity</p><p>A Value Object has no identity of its own it is defined entirely by its attributes. Two Waypoint objects with the same coordinates ARE the same waypoint. Value Objects must always be immutable.</p><pre>// Waypoint is a Value Object — two waypoints at same lat/lon ARE the same<br>@Embeddable<br>public final class Waypoint {<br>    private final String identifier; // e.g., &quot;IGARI&quot;, &quot;DUMBO&quot;<br>    private final double latitude;<br>    private final double longitude;<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (!(o instanceof Waypoint)) return false;<br>        Waypoint w = (Waypoint) o;<br>        return Double.compare(w.latitude, latitude) == 0<br>            &amp;&amp; Double.compare(w.longitude, longitude) == 0<br>            &amp;&amp; identifier.equals(w.identifier);<br>    }<br>}</pre><pre>// FuelSummary is a Value Object — a snapshot of fuel quantities<br>@Embeddable<br>public final class FuelSummary {<br>    private final double taxiFuel;        // in kg<br>    private final double tripFuel;        // fuel to destination<br>    private final double contingencyFuel; // extra 5% for unknowns<br>    private final double reserveFuel;     // alternate + final reserve<br><br>    public double totalFuel() {<br>        return taxiFuel + tripFuel + contingencyFuel + reserveFuel;<br>    }<br>}</pre><p><strong>Aggregate Root — </strong>The Consistency Boundary</p><p>The Aggregate Root is the single point of entry into a cluster of related objects. In aviation, FlightPlan is the Aggregate Root. You never modify a Leg or FuelSummary directly you always go through the FlightPlan:</p><pre>// WRONG — bypassing the aggregate root<br>legRepository.save(someNewLeg); // This violates consistency!<br><br>// CORRECT — always operate through the Aggregate Root<br>FlightPlan fp = flightPlanRepository.findById(flightPlanId)<br>    .orElseThrow(FlightPlanNotFoundException::new);<br><br>fp.revise(newFuelSummary, newRoute); // All business rules enforced here!<br><br>flightPlanRepository.save(fp);       // Only the aggregate root is saved</pre><h4>Part 3: Bounded Contexts (Micro-Services Born from Domain Boundaries)</h4><p>Here’s where DDD connects directly to micro-services architecture. In a large aviation system, different teams need to think about flight plans in completely different ways:</p><blockquote><strong>Ingestion Context: </strong>Receiving and storing raw XML from Navblue. (Integration Team)<br><strong>Flight Planning Context: </strong>Creating, revising, approving flight plans. (Ops Team)<br><strong>Validation Context:</strong> ETOPS compliance, fuel regulation checks. (Safety Team)<br><strong>Revision Management Context: </strong>Comparing revisions, change audit trail. (Dispatch Team)</blockquote><p>Each context becomes a separate Spring Boot microservice. These services don’t share databases. Each owns its data. They communicate via Domain <strong>Events published on Kafka</strong>.</p><pre>aviation-system/<br>├── ingestion-service/        # Receives XML, stores raw blobs<br>├── flight-planning-service/  # Core domain — FlightPlan aggregate<br>├── validation-service/       # Compliance and rule checking<br>└── revision-service/         # Diff and audit trail</pre><pre>// Domain Event — published when a FlightPlan is revised<br>public class FlightPlanRevisedEvent {<br>    private final String flightPlanId;<br>    private final int oldRevision;<br>    private final int newRevision;<br>    private final Instant occurredAt;<br>    private final String changedBy;<br>}<br><br>// In FlightPlan entity, when revision happens:<br>public void revise(FuelSummary newFuelSummary, Route newRoute) {<br>    int oldRev = this.revisionInfo.getRevisionNumber();<br>    this.revisionInfo = this.revisionInfo.increment();<br>    this.fuelSummary = newFuelSummary;<br>    this.route = newRoute;<br><br>    // Register domain event — infrastructure will publish it<br>    this.registerDomainEvent(new FlightPlanRevisedEvent(<br>        this.flightPlanId.toString(),<br>        oldRev,<br>        this.revisionInfo.getRevisionNumber(),<br>        Instant.now(),<br>        &quot;SYSTEM&quot;<br>    ));<br>}</pre><h4><strong>Part 4: The Architecture (Layered Structure)</strong></h4><p>The full system uses a clean layered architecture. Every request flows top to bottom, every layer depends only on what’s below it, and the domain layer depends on nothing external:</p><pre>Raw XML File (from Navblue FTP)<br>        ↓<br>[INGESTION LAYER]  - ingestion-service<br>        ↓<br>[PARSING LAYER]    -  SAX/JAXB XML Parser<br>        ↓<br>[ASSEMBLER LAYER]  - XML DTO → Domain Model<br>        ↓<br>[DOMAIN LAYER]     - FlightPlan, Route, Leg<br>        ↓<br>[REPOSITORY LAYER] - Persistence<br>        ↓<br>    [API LAYER]    - REST Controllers<br>        ↓<br>     [CLIENT]      - Dispatch Manager / Pilot</pre><h4>Application Layer</h4><pre>@Service<br>@Transactional<br>public class FlightPlanApplicationService {<br><br>    private final FlightPlanRepository flightPlanRepository;<br>    private final FlightPlanAssembler assembler;<br>    private final DomainEventPublisher eventPublisher;<br><br>    // Orchestrates: parse → assemble → save → publish<br>    public FlightPlanId ingestFlightPlan(byte[] rawXml, String ingestionId) {<br><br>        // 1. Store raw XML — immutable audit record<br>        rawXmlStore.store(ingestionId, rawXml);<br><br>        // 2. Parse XML to DTO<br>        FlightPlanXmlDto dto = xmlParser.parse(rawXml);<br><br>        // 3. Assemble domain model (Anti-Corruption Layer)<br>        FlightPlan flightPlan = assembler.toDomain(dto);<br><br>        // 4. Persist the domain aggregate<br>        flightPlanRepository.save(flightPlan);<br><br>        // 5. Publish domain event<br>        eventPublisher.publish(<br>            new FlightPlanIngestedEvent(flightPlan.getFlightPlanId()));<br><br>        return flightPlan.getFlightPlanId();<br>    }<br>}</pre><h4><strong>Part 5: Design Patterns in Action (Design Thinking Reference)</strong></h4><p>Complex <strong>domain objects</strong> shouldn’t be created with new scattered everywhere. A Factory centralises creation logic and enforces all business invariants at birth:</p><pre>public class FlightPlanFactory {<br><br>    public static FlightPlan create(<br>        FlightPlanId id,<br>        AircraftInfo aircraft,<br>        Route route,<br>        FuelSummary fuel<br>    ) {<br>        // Business invariant: A route must have at least one leg<br>        if (route.getLegs().isEmpty()) {<br>            throw new InvalidFlightPlanException(<br>                &quot;A route must contain at least one leg.&quot;);<br>        }<br>        // Business invariant: Fuel must be positive<br>        if (fuel.totalFuel() &lt;= 0) {<br>            throw new InvalidFlightPlanException(<br>                &quot;Fuel quantity must be positive.&quot;);<br>        }<br>        return new FlightPlan(id, aircraft, route, fuel,<br>            RevisionInfo.initial(), FlightPlanStatus.FILED);<br>    }<br>}</pre><p>The <strong>Repository pattern</strong> abstracts the data store. The domain doesn’t know or care whether data lives in Oracle, Postgres, or MongoDB. The interface is owned by the domain; the implementation is owned by infrastructure:</p><pre>// Domain layer — owns this contract<br>public interface FlightPlanRepository {<br>    Optional&lt;FlightPlan&gt; findById(FlightPlanId id);<br>    Optional&lt;FlightPlan&gt; findLatestRevision(FlightPlanId id);<br>    List&lt;FlightPlan&gt; findByDateAndRoute(<br>        LocalDate date, String origin, String destination);<br>    void save(FlightPlan flightPlan);<br>}<br><br>// Infrastructure layer — Spring Data JPA implementation<br>@Repository<br>public class JpaFlightPlanRepository implements FlightPlanRepository {<br><br>    private final SpringDataFlightPlanRepository jpaRepo;<br>    private final FlightPlanMapper mapper;<br><br>    @Override<br>    public Optional&lt;FlightPlan&gt; findById(FlightPlanId id) {<br>        return jpaRepo.findByFlightPlanIdValue(id.getValue())<br>                      .map(mapper::toDomain);<br>    }<br><br>    @Override<br>    public void save(FlightPlan flightPlan) {<br>        jpaRepo.save(mapper.toJpaEntity(flightPlan));<br>    }<br>}</pre><p><strong>Anti-Corruption Layer</strong> (ACL) Protecting the Domain from the XML</p><p>This is the most critical pattern in aviation integration. The Navblue XML schema can change at any time. Your domain model must not change just because an XML attribute was renamed. The Assembler acts as the ACL — translating external XML DTOs into your stable internal domain model:</p><pre>@Component<br>public class FlightPlanAssembler {<br><br>    public FlightPlan toDomain(FlightPlanXmlDto dto) {<br><br>        FlightPlanId id = FlightPlanId.of(dto.getMessageId());<br><br>        AircraftInfo aircraft = new AircraftInfo(<br>            dto.getAircraftSection().getAircraftType(),  // XML: &lt;AircraftType&gt;<br>            dto.getAircraftSection().getRegistration()   // XML: &lt;AircraftRegistration&gt;<br>        );<br><br>        List&lt;Leg&gt; legs = dto.getRouteSection()<br>            .getLegGroups()                               // XML: &lt;LegGroup&gt; elements<br>            .stream()<br>            .map(this::toLeg)<br>            .collect(Collectors.toList());<br><br>        FuelSummary fuel = new FuelSummary(<br>            dto.getFuelSection().getTaxiFuel(),<br>            dto.getFuelSection().getTripFuel(),<br>            dto.getFuelSection().getContingencyFuel(),<br>            dto.getFuelSection().getReserveFuel()<br>        );<br><br>        return FlightPlanFactory.create(<br>            id, aircraft, new Route(RouteId.generate(), legs), fuel);<br>    }<br><br>    private Leg toLeg(LegGroupDto legDto) {<br>        Waypoint from = new Waypoint(<br>            legDto.getFromFix(), legDto.getFromLat(), legDto.getFromLon());<br>        Waypoint to = new Waypoint(<br>            legDto.getToFix(), legDto.getToLat(), legDto.getToLon());<br>        return new Leg(from, to, legDto.getAirway(), legDto.getSequence());<br>    }<br>}</pre><p>If tomorrow Navblue renames <strong>&lt;AircraftType&gt; to &lt;AcType&gt;,</strong> only the DTO and Assembler change. The domain model stays completely untouched. That is the power of the ACL.</p><p><strong>Observer / Domain Events </strong>Decoupled Microservice Communication</p><pre>// Validation Service listens for ingestion events via Kafka<br>@Service<br>public class ValidationEventListener {<br><br>    private final FlightPlanValidationService validationService;<br><br>    @KafkaListener(topics = &quot;flight-plan.ingested&quot;, groupId = &quot;validation-service&quot;)<br>    public void onFlightPlanIngested(FlightPlanIngestedEvent event) {<br>        log.info(&quot;Received ingestion event: {}&quot;, event.getFlightPlanId());<br><br>        ValidationResult result =<br>            validationService.validate(event.getFlightPlanId());<br><br>        if (result.hasViolations()) {<br>            log.warn(&quot;Validation failed: {}&quot;, result.getViolations());<br>            // Publish validation-failed event — dispatch system reacts<br>        }<br>    }<br>}</pre><h4>Part 6: The Raw XML Strategy — Don’t Map the Schema, Save It</h4><blockquote>The XML is a transport contract, not your data model. Store it as a versioned, immutable blob.</blockquote><p>The XML is a transport contract, not your data model. Store it as a versioned, immutable blob.</p><pre>@Entity<br>@Table(name = &quot;raw_ingestion&quot;)<br>public class RawIngestionRecord {<br><br>    @Id<br>    private String ingestionId;          // UUID<br><br>    @Column(columnDefinition = &quot;BYTEA&quot;)<br>    private byte[] rawXml;               // Original XML — never modified<br><br>    private String sourceFileName;<br>    private Instant receivedAt;<br>    private String checksum;             // SHA-256 for integrity verification<br>    private String processingStatus;     // PENDING | PROCESSED | FAILED<br><br>    // Immutable audit record — never updated after creation<br>}</pre><blockquote><strong>Regulatory Compliance</strong> — Aviation regulators may require you to reproduce the exact data you operated on.<br><strong>Debugging</strong> — When a flight plan behaves unexpectedly, re-run parsing against the original XML.<br><strong>Schema Evolution</strong> — When the XML schema version changes, reprocess old XMLs with the new parser without data loss.</blockquote><h4>Part 7: Observability — Because Aviation Doesn’t Tolerate Blind Spots</h4><p>Every ingestion event must be measurable and traceable across micro-services. Use Micrometer for metrics and structured logging with correlation IDs:</p><pre>@Aspect<br>@Component<br>public class IngestionObservabilityAspect {<br><br>    private final MeterRegistry meterRegistry;<br><br>    @Around(&quot;execution(* com.aviation.ingestion.*.ingest*(..))&quot;)<br>    public Object measureIngestion(ProceedingJoinPoint pjp) throws Throwable {<br>        Timer.Sample sample = Timer.start(meterRegistry);<br>        try {<br>            Object result = pjp.proceed();<br>            meterRegistry.counter(&quot;flight_plan.ingested&quot;,<br>                &quot;status&quot;, &quot;success&quot;).increment();<br>            return result;<br>        } catch (XmlParseException e) {<br>            meterRegistry.counter(&quot;flight_plan.ingested&quot;,<br>                &quot;status&quot;, &quot;parse_failure&quot;).increment();<br>            throw e;<br>        } finally {<br>            sample.stop(meterRegistry.timer(&quot;flight_plan.ingestion.duration&quot;));<br>        }<br>    }<br>}</pre><pre>log.info(&quot;FlightPlan ingestion complete | id={} | ingestionId={} | revision={} | ms={}&quot;,<br>    flightPlan.getFlightPlanId(),<br>    ingestionId,<br>    flightPlan.getRevisionInfo().getRevisionNumber(),<br>    processingTime);</pre><h4>Part 8: Incremental Implementation (Building an Airplane While Flying)</h4><p><strong>Iteration 1</strong> The Foundation (Weeks 1–4)<br>“Store everything. Parse the minimum. Trust nothing yet.”</p><blockquote>Stable ingestion pipeline receive XML, store raw blob.<br>Extract only FlightPlanId and RevisionNumber.<br>No complex domain logic. Just reliable ingestion.</blockquote><p><strong>Iteration 2</strong> The Core Domain (Weeks 5–10)<br>“Now let’s talk business.”</p><blockquote>Add Route, Leg, Waypoint parsing via the Assembler.<br>Add FuelSummary extraction.<br>Expose basic REST API to retrieve flight plan details.</blockquote><p><strong>Iteration 3</strong> The Intelligence (Weeks 11–16)<br>“Now let’s speak aviation.”</p><blockquote>Add revision comparison, what changed between revision 1 and revision 2?<br>Add ETOPS compliance validation.<br>Expand domain model with OperationalConstraints and WeatherReference.<br>Cross-service events via Kafka.</blockquote><h4>Landing: What DDD Gives You That No Framework Can</h4><p>As the aircraft lined up on Runway 27L, I thought about what makes aviation software genuinely reliable. It’s not the XML parser. It’s not the database schema. It’s not even micro-service. It’s the <strong>alignment between the mental models of the domain experts and the structure of the code</strong>.</p><p>When a dispatcher says, “The fuel summary for the revised FPL-AI101–23-VABB-VIDP looks wrong,” and a developer can immediately open FlightPlan.getFuelSummary() and understand exactly what they’re looking at that is the promise of Domain-Driven Design fulfilled.</p><h3>Key Takeaways</h3><blockquote><strong>Domain First, Technology Second — </strong>Understand what a Flight Plan is before writing a single line of JAXB code.</blockquote><blockquote><strong>Protect Your Domain — </strong>The Navblue XML is volatile. Your domain model must be stable. Use the ACL.</blockquote><blockquote><strong>Boundaries Create Freedom — </strong>Bounded Contexts give each team ownership without interference.</blockquote><blockquote><strong>Events Decouple Micro-Services — </strong>Publish FlightPlanIngestedEvent, let services react. No direct coupling.</blockquote><blockquote><strong>Store Raw, Serve Clean — </strong>Never discard the original XML. Always serve clean domain objects.</blockquote><blockquote><strong>Incrementally Enrich — </strong>Don’t model everything on Day 1. Start with identity, add richness iteratively.</blockquote><h4>Further Reading</h4><blockquote>Domain-Driven Design by Eric Evans (The Blue Book)</blockquote><blockquote>The original text Implementing Domain-Driven Design by Vaughn Vernon (The Red Book): Practical implementation</blockquote><blockquote>Building Micro-Services by Sam Newman: How DDD shapes service boundaries</blockquote><blockquote>Enterprise Integration Patterns by Gregor Hohpe: For XML and Kafka integration patterns</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806431d48b56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns in Action: Building a Real-World Flight Booking System using creational design…]]></title>
            <link>https://medium.com/@akshat.available/design-patterns-in-action-building-a-real-world-flight-booking-system-using-creational-design-7836aa7a5e4a?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7836aa7a5e4a</guid>
            <category><![CDATA[flight-booking-system]]></category>
            <category><![CDATA[java-design-patterns-demo]]></category>
            <category><![CDATA[java-design-demo]]></category>
            <category><![CDATA[java-creational-patterns]]></category>
            <category><![CDATA[design-patterns-in-java]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 10:25:14 GMT</pubDate>
            <atom:updated>2025-12-26T10:25:14.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns in Action: Building a Real-World Flight Booking System using creational design pattern Java</h3><p>Design patterns are often introduced using abstract examples that feel disconnected from real-world systems. While those examples are useful for learning syntax, they rarely show how patterns naturally emerge from business requirements. In this article, we will build a <strong>Flight Booking System</strong> using Java and see how multiple <strong>creational design patterns</strong> work together to solve practical airline-domain problems. The discussion is driven directly by the codebase, making it suitable for readers who prefer learning through implementation rather than theory alone.</p><h3>Introduction</h3><p>A flight booking system is a classic enterprise problem. It involves creating different kinds of flights, handling multiple booking classes, managing optional booking features, reusing recurring schedules, and maintaining centralized configuration. If all of this logic is implemented using plain constructors and conditional statements, the system quickly becomes rigid and difficult to extend.</p><p>The provided codebase demonstrates how these problems can be addressed cleanly using creational design patterns. Each pattern appears not because it is fashionable, but because the domain demands it. Let us walk through the system from top to bottom and understand how each design choice fits the airline use case.</p><h3>System Entry Point and High-Level Flow</h3><p>The UseCaseExample class acts as the orchestration layer. It simulates how different parts of the system interact during a typical booking flow.</p><pre>public class UseCaseExample {<br>    public static void main(String[] args) throws CloneNotSupportedException {<br><br>        AirlineConfig config = AirlineConfig.getInstance();<br>        System.out.println(&quot;Airline: &quot; + config.getAirlineName());<br><br>        FlightFactory flightFactory = new DomesticFlightFactory();<br>        Flight flight1 = flightFactory.createFlight(&quot;SH123&quot;, &quot;NYC&quot;, &quot;LAX&quot;);<br>        flight1.getFlightDetails();<br><br>        BookingFactory bookingFactory = new BusinessBookingFactory();<br>        Seat seat = bookingFactory.createSeat();<br>        seat.seatInfo();<br><br>        Booking booking = new Booking.Builder()<br>                .passengerName(&quot;Alice&quot;)<br>                .flightNumber(&quot;SH123&quot;)<br>                .seatType(&quot;Business&quot;)<br>                .meal(true)<br>                .extraBaggage(true)<br>                .build();<br>        System.out.println(booking);<br><br>        FlightSchedule schedule = new DailyFlightSchedule(&quot;SH123&quot;, &quot;08:00 AM&quot;);<br>        FlightSchedule clonedSchedule = schedule.clone();<br>        clonedSchedule.showSchedule();<br>    }<br>}</pre><p>This single flow already touches configuration management, flight creation, booking customisation, and schedule reuse. Each of these concerns is handled by a specific pattern.</p><h3>Singleton Pattern for Airline Configuration</h3><p>Every airline system needs configuration values such as airline name, airline code, pricing rules, or integration settings. These values must remain consistent throughout the application lifecycle. Creating multiple configuration objects would risk inconsistencies and bugs.</p><p>The AirlineConfig class uses the Singleton pattern to guarantee a single instance.</p><pre>class AirlineConfig {<br>    private static AirlineConfig instance;<br>    private String airlineName;<br>    private String code;<br><br>    private AirlineConfig() {<br>        this.airlineName = &quot;Indigo Airlines&quot;;<br>        this.code = &quot;6E&quot;;<br>    }<br><br>    public static AirlineConfig getInstance() {<br>        if (instance == null) {<br>            instance = new AirlineConfig();<br>        }<br>        return instance;<br>    }<br><br>    public String getAirlineName() { return airlineName; }<br>    public String getCode() { return code; }<br>}</pre><p>This approach ensures that configuration is lazily initialized and globally accessible. In a real enterprise system, this class could later be extended to load values from environment variables, databases, or configuration servers without changing client code.</p><h3>Factory Method Pattern for Flight Creation</h3><p>Flights can vary based on geography, regulations, and operational rules. A domestic flight is fundamentally different from an international flight, and more variations may appear in the future. Hardcoding object creation would tightly couple the system to specific implementations.</p><p>The Factory Method pattern cleanly separates the creation logic.</p><pre>abstract class Flight {<br>    protected String flightNumber;<br>    protected String origin;<br>    protected String destination;<br>    public abstract void getFlightDetails();<br>}</pre><p>Concrete flight implementations define their own behaviour.</p><pre>class DomesticFlight extends Flight {<br>    public DomesticFlight(String flightNumber, String origin, String destination) {<br>        this.flightNumber = flightNumber;<br>        this.origin = origin;<br>        this.destination = destination;<br>    }<br><br>    @Override<br>    public void getFlightDetails() {<br>        System.out.println(&quot;Domestic Flight: &quot; + flightNumber);<br>    }<br>}</pre><p>The factory hierarchy encapsulates object creation.</p><pre>abstract class FlightFactory {<br>    public abstract Flight createFlight(String flightNumber, String origin, String destination);<br>}<br><br>class DomesticFlightFactory extends FlightFactory {<br>    @Override<br>    public Flight createFlight(String flightNumber, String origin, String destination) {<br>        return new DomesticFlight(flightNumber, origin, destination);<br>    }<br>}</pre><p>This design allows the system to introduce new flight types without modifying existing client logic, which is critical in large-scale airline platforms.</p><h3>Abstract Factory for Booking Classes</h3><p>Booking options such as Economy, Business, and First Class represent families of related services. A Business booking may include premium seating, lounge access, and meals, while Economy does not. These components should be created consistently.</p><p>The Abstract Factory pattern models this requirement.</p><pre>interface Seat {<br>    void seatInfo();<br>}<br><br>class BusinessSeat implements Seat {<br>    public void seatInfo() {<br>        System.out.println(&quot;Business Seat&quot;);<br>    }<br>}</pre><p>Factories create related objects without exposing concrete implementations.</p><pre>interface BookingFactory {<br>    Seat createSeat();<br>}<br><br>class BusinessBookingFactory implements BookingFactory {<br>    public Seat createSeat() {<br>        return new BusinessSeat();<br>    }<br>}</pre><p>This ensures that when a Business booking is selected, all associated services belong to the same category, maintaining domain consistency.</p><h3>Builder Pattern for Complex Booking Construction</h3><p>A booking object contains multiple optional attributes. Using a traditional constructor would lead to unreadable code or dozens of overloaded constructors. The Builder pattern provides a fluent and expressive solution.</p><pre>class Booking {<br>    private String passengerName;<br>    private String flightNumber;<br>    private String seatType;<br>    private boolean meal;<br>    private boolean extraBaggage;<br><br>    private Booking(Builder builder) {<br>        this.passengerName = builder.passengerName;<br>        this.flightNumber = builder.flightNumber;<br>        this.seatType = builder.seatType;<br>        this.meal = builder.meal;<br>        this.extraBaggage = builder.extraBaggage;<br>    }</pre><p>The builder allows step-by-step construction.</p><pre>public static class Builder {<br>    private String passengerName;<br>    private String flightNumber;<br>    private String seatType;<br>    private boolean meal;<br>    private boolean extraBaggage;<br><br>    public Builder passengerName(String name) {<br>        this.passengerName = name;<br>        return this;<br>    }<br><br>    public Builder flightNumber(String flightNumber) {<br>        this.flightNumber = flightNumber;<br>        return this;<br>    }<br><br>    public Builder seatType(String seatType) {<br>        this.seatType = seatType;<br>        return this;<br>    }<br><br>    public Builder meal(boolean meal) {<br>        this.meal = meal;<br>        return this;<br>    }<br><br>    public Builder extraBaggage(boolean extraBaggage) {<br>        this.extraBaggage = extraBaggage;<br>        return this;<br>    }<br><br>    public Booking build() {<br>        return new Booking(this);<br>    }<br>}</pre><p>This pattern improves readability, prevents partially constructed objects, and closely matches how users think when booking flights.</p><h3>Prototype Pattern for Flight Schedules</h3><p>Airlines often reuse flight schedules daily or weekly with minimal changes. Creating each schedule from scratch is inefficient. The Prototype pattern solves this by allowing object cloning.</p><pre>abstract class FlightSchedule implements Cloneable {<br>    protected String flightNumber;<br>    protected String departureTime;<br><br>    public FlightSchedule clone() throws CloneNotSupportedException {<br>        return (FlightSchedule) super.clone();<br>    }<br><br>    public void showSchedule() {<br>        System.out.println(&quot;Flight &quot; + flightNumber + &quot; departs at &quot; + departureTime);<br>    }<br>}</pre><p>A concrete implementation can now be cloned easily.</p><pre>class DailyFlightSchedule extends FlightSchedule {<br>    public DailyFlightSchedule(String flightNumber, String departureTime) {<br>        super(flightNumber, departureTime);<br>    }<br>}</pre><p>This approach is ideal for templated operational data that repeats frequently in airline systems.</p><h3>Conclusion</h3><p>This flight booking system demonstrates how design patterns emerge naturally from domain complexity. Each pattern addresses a real operational concern rather than serving as an academic exercise. When combined, these patterns produce a system that is flexible, extensible, and aligned with enterprise-grade software design.</p><p>For developers preparing for system design interviews or building real-world Java applications, understanding patterns through such domain-driven examples provides far more value than memorizing definitions. The true power of design patterns lies not in knowing them individually, but in knowing when and why to apply them together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7836aa7a5e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns + Spring AI + Apache Camel: Building Configurable, Generic Java Workflows]]></title>
            <link>https://medium.com/@akshat.available/design-patterns-spring-ai-apache-camel-building-configurable-generic-java-workflows-a55d84a7f1f1?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55d84a7f1f1</guid>
            <category><![CDATA[apache-camel-integrations]]></category>
            <category><![CDATA[ai-workflow-engine]]></category>
            <category><![CDATA[configurable-java-flows]]></category>
            <category><![CDATA[design-patterns-in-action]]></category>
            <category><![CDATA[spring-ai-agents]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 07:56:03 GMT</pubDate>
            <atom:updated>2025-12-25T07:56:03.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6sTqqVV6eqUPCEVmu5eGA.jpeg" /></figure><p>Whether you are an architect, a senior Java developer, or an integration engineer, this blog walks you through building a <strong>Java-based, configuration-driven workflow framework</strong> powered by <strong>Spring Boot, Spring AI, Apache Camel, and MongoDB</strong>. Leveraging classic design patterns like <strong>Template Method, Strategy, Chain of Responsibility, FSM, Adapter, and Command</strong>, this framework allows you to define <strong>generic workflows</strong> where each stage is executed by pluggable, stateless agents. The result? A lightweight, future-proof engine that lets you add new workflows, agents, or strategies <strong>at runtime</strong>, keeping your business agile while your core remains untouched.</p><h3><strong>Background</strong></h3><blockquote>Modern enterprise systems require the ability to <strong>define and execute custom workflows without code changes</strong>. Different teams need to integrate with <strong>multiple external systems</strong>, process <strong>heterogeneous data formats</strong>, apply <strong>validations and transformations</strong>, and load results into <strong>diverse targets</strong>. Hardcoding these workflows introduces <strong>tight coupling</strong>, limits <strong>scalability</strong>, increases <strong>maintenance overhead</strong>, and slows the <strong>onboarding of new use cases</strong>.</blockquote><h3><strong>Problem Scope</strong></h3><blockquote>Need an architecture that defines a <strong>Java-based, configuration-driven workflow framework</strong> where workflows are composed of <strong>ordered stages</strong> with <strong>pluggable implementations</strong>. The framework orchestrates execution, manages stage transitions, and handles errors, while <strong>business logic remains fully externalised</strong> in agents. All behaviour is resolved at runtime through configuration, enabling new workflows, agents, or strategies <strong>without code changes</strong>. This design delivers a <strong>lightweight, extensible core framework</strong>, not an application.</blockquote><h3><strong>Non-Negotiable Design Constraints</strong></h3><blockquote>The framework enforces a <strong>fixed execution flow</strong> controlled exclusively by an <strong>FSM</strong>, with <strong>pluggable behaviour</strong> resolved at runtime. A shared <strong>context</strong> is the only state passed across stages. <strong>Agents remain passive</strong>, executing logic without influencing control flow or transitions. The design must strictly comply with the <strong>Open/Closed Principle</strong>, allowing extension through configuration without modification of core framework code.</blockquote><h3><strong>Core Design Patterns</strong></h3><blockquote>The framework applies <strong>Template Method</strong> to define the execution skeleton, <strong>FSM</strong> to enforce stage legality, and an <strong>Orchestrator</strong> to control flow. <strong>Strategy</strong> enables runtime behaviour selection, while <strong>Chain of Responsibility</strong> supports multiple handlers per stage. External integrations are isolated via the <strong>Adapter</strong> pattern. Each execution step is modelled as a <strong>Command</strong>, shared state is carried through a <strong>Context Object</strong>, and extensibility is achieved using a <strong>Registry</strong>.</blockquote><h3><strong>Sample Workflow Execution Walkthrough</strong></h3><blockquote>A workflow progresses through the stages <strong>START, SYSTEM_INTEGRATION, DATA_EXTRACTION, DATA_MAPPING, DATA_VALIDATION, DATA_TRANSFORMATION, DATA_LOAD, COMPLETED, FAILED</strong>, with each stage supporting multiple implementation types resolved at runtime. At execution time, the engine loads the workflow definition, initialises the shared context, and enters the FSM-controlled orchestration loop. For each stage, the orchestrator resolves the appropriate agent from the registry, executes it, updates the context, and advances the FSM. Execution terminates in either a <strong>COMPLETED</strong> or <strong>FAILED</strong> state. Individual stages remain unaware of subsequent stages, <strong>flow control is owned exclusively by the orchestrator</strong>.</blockquote><h3><strong>Mental Model (Pre-Architecture)</strong></h3><blockquote>The workflow is modelled as a <strong>Finite State Machine</strong>, where each stage represents a state and transitions are driven by execution outcomes. Business logic is executed by <strong>autonomous agents</strong>, with all shared data flowing through a <strong>context object</strong>. Conceptually, this aligns with patterns seen in <strong>Servlet filters</strong>, <strong>Spring Boot</strong>, <strong>Apache Camel</strong>, and <strong>Spring AI DAGs</strong>. A workflow is defined via UI, persisted in <strong>NoSQL</strong>, executed by the <strong>workflow runtime engine</strong>, coordinated by a <strong>stage orchestrator</strong>, and processed through <strong>agent execution per stage</strong>, resulting in a final outcome.</blockquote><h3><strong>Concept Design: Agent</strong></h3><blockquote>Each stage is executed by a dedicated <strong>agent</strong>. An agent is <strong>autonomous</strong>, <strong>single-responsibility</strong>, <strong>configuration-driven</strong>, and <strong>stateless</strong>, operating exclusively on the shared execution context. Agents encapsulate domain-specific work such as integration, extraction, validation, transformation, or loading. Example agents include <strong>RestIntegrationAgent</strong>, <strong>KafkaIntegrationAgent</strong>, <strong>JsonExtractionAgent</strong>, <strong>RuleValidationAgent</strong>, <strong>ScriptTransformationAgent</strong>, <strong>MongoLoadAgent</strong>, and <strong>S3LoadAgent</strong>.</blockquote><blockquote>Here, <strong>agent ≠ thread ≠ AI agent</strong>. An agent is simply a <strong>domain worker</strong> invoked by the framework.</blockquote><h3>High Level Visual Understanding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*WB3doUwZnDqqADTtfDe4Eg.png" /></figure><h3><strong>Core Domain Concepts Code Draft</strong></h3><h4><strong>(Framework-Level, Pre-Code Abstraction)</strong></h4><blockquote>Below is a <strong>high-level conceptual code flow</strong> to illustrate the framework’s core domain concepts. This is <strong>not actual implementation </strong>rather, it’s an <strong>abstraction of abstractions</strong> to help visualise how components interact and form the architecture. Think of it as <strong>conceptual coding</strong> to build a mental model for implementation.</blockquote><pre>Stage (FSM States)<br><br>public enum Stage {<br>    START,<br>    SYSTEM_INTEGRATION,<br>    DATA_EXTRACTION,<br>    DATA_MAPPING,<br>    DATA_VALIDATION,<br>    DATA_TRANSFORMATION,<br>    DATA_LOAD,<br>    COMPLETED,<br>    FAILED<br>}<br><br>Execution Context (Context Object Pattern)<br><br>Rule: If something matters → it goes in WorkflowContext.<br><br>public class WorkflowContext {<br><br>    private String workflowId;<br>    private Stage currentStage;<br>    private final Map&lt;String, Object&gt; data = new HashMap&lt;&gt;();<br>    private final List&lt;String&gt; errors = new ArrayList&lt;&gt;();<br><br>    public WorkflowContext(String workflowId) {<br>        this.workflowId = workflowId;<br>        this.currentStage = Stage.START;<br>    }<br><br>    public Stage getCurrentStage() {<br>        return currentStage;<br>    }<br><br>    public void setCurrentStage(Stage stage) {<br>        this.currentStage = stage;<br>    }<br><br>    public Map&lt;String, Object&gt; data() {<br>        return data;<br>    }<br><br>    public List&lt;String&gt; errors() {<br>        return errors;<br>    }<br>}<br><br>Agent Outcome (Command Result)<br><br>public enum AgentStatus {<br>    SUCCESS,<br>    FAILURE<br>}<br><br>public class AgentResult {<br><br>    private final AgentStatus status;<br><br>    private AgentResult(AgentStatus status) {<br>        this.status = status;<br>    }<br><br>    public static AgentResult success() {<br>        return new AgentResult(AgentStatus.SUCCESS);<br>    }<br><br>    public static AgentResult failure() {<br>        return new AgentResult(AgentStatus.FAILURE);<br>    }<br><br>    public boolean isSuccess() {<br>        return status == AgentStatus.SUCCESS;<br>    }<br>}<br><br>Agent Contract (Strategy + Command)<br><br>Important: Agent cannot decide next stage and Agent only mutates context<br><br>public interface WorkflowAgent {<br><br>    boolean supports(Stage stage, String strategy);<br><br>    AgentResult execute(WorkflowContext context);<br>}<br><br>Agent Registry (Extension Point)<br><br>Adding new behavior = register new agent.<br><br>public class AgentRegistry {<br><br>    private final List&lt;WorkflowAgent&gt; agents = new ArrayList&lt;&gt;();<br><br>    public void register(WorkflowAgent agent) {<br>        agents.add(agent);<br>    }<br><br>    public WorkflowAgent resolve(Stage stage, String strategy) {<br>        return agents.stream()<br>                .filter(a -&gt; a.supports(stage, strategy))<br>                .findFirst()<br>                .orElseThrow(() -&gt;<br>                        new IllegalStateException(&quot;No agent for stage &quot; + stage));<br>    }<br>}<br><br>Finite State Machine (FSM) : FSM knows legality, not logic.<br><br>public class WorkflowStateMachine {<br><br>    public Stage next(Stage current, AgentResult result) {<br><br>        if (!result.isSuccess()) {<br>            return Stage.FAILED;<br>        }<br><br>        return switch (current) {<br>            case START -&gt; Stage.SYSTEM_INTEGRATION;<br>            case SYSTEM_INTEGRATION -&gt; Stage.DATA_EXTRACTION;<br>            case DATA_EXTRACTION -&gt; Stage.DATA_MAPPING;<br>            case DATA_MAPPING -&gt; Stage.DATA_VALIDATION;<br>            case DATA_VALIDATION -&gt; Stage.DATA_TRANSFORMATION;<br>            case DATA_TRANSFORMATION -&gt; Stage.DATA_LOAD;<br>            case DATA_LOAD -&gt; Stage.COMPLETED;<br>            default -&gt; Stage.FAILED;<br>        };<br>    }<br><br>    public boolean isTerminal(Stage stage) {<br>        return stage == Stage.COMPLETED || stage == Stage.FAILED;<br>    }<br>}<br><br>Orchestrator (Flow Control Brain): Only place where execution flow exists.<br><br>public class WorkflowOrchestrator {<br><br>    private final AgentRegistry registry;<br>    private final WorkflowStateMachine fsm;<br><br>    public WorkflowOrchestrator(AgentRegistry registry,<br>                                WorkflowStateMachine fsm) {<br>        this.registry = registry;<br>        this.fsm = fsm;<br>    }<br><br>    public void orchestrate(WorkflowContext context,<br>                             Map&lt;Stage, String&gt; strategyMap) {<br><br>        while (!fsm.isTerminal(context.getCurrentStage())) {<br><br>            Stage stage = context.getCurrentStage();<br>            String strategy = strategyMap.get(stage);<br><br>            WorkflowAgent agent = registry.resolve(stage, strategy);<br><br>            AgentResult result = agent.execute(context);<br><br>            Stage next = fsm.next(stage, result);<br>            context.setCurrentStage(next);<br>        }<br>    }<br>}<br><br>Workflow Engine (Template Method): Execution skeleton is locked.<br><br>public abstract class WorkflowEngine {<br><br>    public final void run(String workflowId) {<br><br>        WorkflowContext context = new WorkflowContext(workflowId);<br><br>        Map&lt;Stage, String&gt; strategyMap = loadStrategyMap(workflowId);<br><br>        WorkflowOrchestrator orchestrator = buildOrchestrator();<br><br>        orchestrator.orchestrate(context, strategyMap);<br><br>        afterCompletion(context);<br>    }<br><br>    protected abstract Map&lt;Stage, String&gt; loadStrategyMap(String workflowId);<br><br>    protected abstract WorkflowOrchestrator buildOrchestrator();<br><br>    protected void afterCompletion(WorkflowContext context) {<br>        // audit / logging / metrics<br>    }<br>}<br><br>Sample Agent Implementations<br><br>Integration Agent (Adapter style)<br><br>public class RestIntegrationAgent implements WorkflowAgent {<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.SYSTEM_INTEGRATION<br>                &amp;&amp; &quot;REST&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        context.data().put(&quot;rawResponse&quot;, &quot;data-from-rest&quot;);<br>        return AgentResult.success();<br>    }<br>}<br><br>Validation Agent (Chain-ready)<br><br>public class ValidationAgent implements WorkflowAgent {<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_VALIDATION;<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br><br>        if (!context.data().containsKey(&quot;rawResponse&quot;)) {<br>            context.errors().add(&quot;Missing data&quot;);<br>            return AgentResult.failure();<br>        }<br>        return AgentResult.success();<br>    }<br>}</pre><h3><strong>End-to-End Execution &amp; Framework Integrity</strong></h3><blockquote>The <strong>engine initialises execution</strong> by creating the shared <strong>context</strong> and delegating control to the <strong>orchestrator</strong>, which enters a loop governed by the <strong>FSM</strong>. For each stage, the FSM validates legality, the <strong>registry resolves the appropriate agent</strong>, and the agent executes, mutating the context as needed. The FSM then determines the next state, and the loop continues until reaching <strong>COMPLETED</strong> or <strong>FAILED</strong>.</blockquote><blockquote>This design ensures <strong>strict separation of concerns</strong>, avoids <strong>if-else complexity</strong>, and adheres to the <strong>Open/Closed Principle</strong>. Agents are <strong>independently testable</strong>, execution is <strong>deterministic</strong>, and new workflows or behaviours can be introduced <strong>without code changes</strong>. This is <strong>not a simple pipeline</strong> — it is a <strong>behaviour-driven execution framework</strong> with extensible, configurable, and predictable workflow orchestration.</blockquote><h3>Real Codebase in Single File</h3><p>POM.XML</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br>         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 <br>         http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;parent&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>        &lt;version&gt;3.2.0&lt;/version&gt;<br>        &lt;relativePath/&gt;<br>    &lt;/parent&gt;<br><br>    &lt;groupId&gt;com.workflow&lt;/groupId&gt;<br>    &lt;artifactId&gt;workflow-framework&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt;<br>    &lt;name&gt;Workflow Framework&lt;/name&gt;<br>    &lt;description&gt;Configuration-driven workflow framework with Spring Boot, MongoDB, Apache Camel, and Spring AI&lt;/description&gt;<br><br>    &lt;properties&gt;<br>        &lt;java.version&gt;17&lt;/java.version&gt;<br>        &lt;spring-ai.version&gt;1.0.0-M4&lt;/spring-ai.version&gt;<br>        &lt;camel.version&gt;4.3.0&lt;/camel.version&gt;<br>    &lt;/properties&gt;<br><br>    &lt;dependencies&gt;<br>        &lt;!-- Spring Boot Starters --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        <br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Spring AI - OpenAI --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-ai-openai-spring-boot-starter&lt;/artifactId&gt;<br>            &lt;version&gt;${spring-ai.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Apache Camel --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.camel.springboot&lt;/groupId&gt;<br>            &lt;artifactId&gt;camel-spring-boot-starter&lt;/artifactId&gt;<br>            &lt;version&gt;${camel.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.camel.springboot&lt;/groupId&gt;<br>            &lt;artifactId&gt;camel-http-starter&lt;/artifactId&gt;<br>            &lt;version&gt;${camel.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.camel.springboot&lt;/groupId&gt;<br>            &lt;artifactId&gt;camel-kafka-starter&lt;/artifactId&gt;<br>            &lt;version&gt;${camel.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.camel.springboot&lt;/groupId&gt;<br>            &lt;artifactId&gt;camel-aws2-s3-starter&lt;/artifactId&gt;<br>            &lt;version&gt;${camel.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Lombok (Optional but useful) --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>            &lt;optional&gt;true&lt;/optional&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Validation --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Testing --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;de.flapdoodle.embed&lt;/groupId&gt;<br>            &lt;artifactId&gt;de.flapdoodle.embed.mongo&lt;/artifactId&gt;<br>            &lt;version&gt;4.9.2&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>                &lt;configuration&gt;<br>                    &lt;excludes&gt;<br>                        &lt;exclude&gt;<br>                            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>                            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>                        &lt;/exclude&gt;<br>                    &lt;/excludes&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br><br>    &lt;repositories&gt;<br>        &lt;repository&gt;<br>            &lt;id&gt;spring-milestones&lt;/id&gt;<br>            &lt;name&gt;Spring Milestones&lt;/name&gt;<br>            &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;<br>            &lt;snapshots&gt;<br>                &lt;enabled&gt;false&lt;/enabled&gt;<br>            &lt;/snapshots&gt;<br>        &lt;/repository&gt;<br>    &lt;/repositories&gt;<br>&lt;/project&gt;<br></pre><p>application.yml</p><pre>spring:<br>  application:<br>    name: workflow-framework<br><br>  # MongoDB Configuration<br>  data:<br>    mongodb:<br>      uri: mongodb://localhost:27017/workflow_db<br>      auto-index-creation: true<br><br>  # Spring AI - OpenAI Configuration<br>  ai:<br>    openai:<br>      api-key: ${OPENAI_API_KEY:your-api-key-here}<br>      chat:<br>        options:<br>          model: gpt-4<br>          temperature: 0.7<br>          max-tokens: 2000<br><br># Apache Camel Configuration<br>camel:<br>  springboot:<br>    main-run-controller: true<br>    name: workflow-camel-context<br>  component:<br>    http:<br>      connection-timeout: 5000<br>      socket-timeout: 10000<br>    kafka:<br>      brokers: localhost:9092<br>    aws-s3:<br>      access-key: ${AWS_ACCESS_KEY:}<br>      secret-key: ${AWS_SECRET_KEY:}<br>      region: ${AWS_REGION:us-east-1}<br><br># Server Configuration<br>server:<br>  port: 8080<br>  servlet:<br>    context-path: /api<br><br># Logging Configuration<br>logging:<br>  level:<br>    com.workflow: DEBUG<br>    org.apache.camel: INFO<br>    org.springframework.ai: INFO<br>  pattern:<br>    console: &quot;%d{yyyy-MM-dd HH:mm:ss} - %msg%n&quot;<br><br># Workflow Framework Configuration<br>workflow:<br>  execution:<br>    max-retries: 3<br>    retry-delay-ms: 1000<br>  persistence:<br>    enabled: true<br>    save-intermediate-states: true<br></pre><p>SpringBootApplication</p><pre>package com.workflow.framework;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.data.annotation.Id;<br>import org.springframework.data.mongodb.core.MongoTemplate;<br>import org.springframework.data.mongodb.core.mapping.Document;<br>import org.springframework.data.mongodb.repository.MongoRepository;<br>import org.springframework.ai.chat.client.ChatClient;<br>import org.springframework.ai.chat.model.ChatResponse;<br>import org.springframework.ai.openai.OpenAiChatModel;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Component;<br>import org.springframework.stereotype.Service;<br>import org.apache.camel.CamelContext;<br>import org.apache.camel.ProducerTemplate;<br>import org.apache.camel.builder.RouteBuilder;<br>import org.apache.camel.spring.boot.CamelSpringBootApplicationController;<br>import org.apache.camel.spring.boot.CamelContextConfiguration;<br><br>import java.util.*;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.function.Consumer;<br>import java.util.stream.Collectors;<br><br>/**<br> * ===================================================================<br> * WORKFLOW FRAMEWORK - COMPREHENSIVE SINGLE-FILE IMPLEMENTATION<br> * ===================================================================<br> * <br> * Design Patterns Implemented:<br> * - Template Method: WorkflowEngine defines execution skeleton<br> * - FSM: WorkflowStateMachine enforces stage legality<br> * - Strategy: Runtime agent selection via AgentRegistry<br> * - Chain of Responsibility: Multiple handlers per stage<br> * - Adapter: External system integrations (REST, Kafka, etc.)<br> * - Command: Each execution step as AgentResult<br> * - Context Object: WorkflowContext carries shared state<br> * - Registry: AgentRegistry for extensibility<br> * - Orchestrator: WorkflowOrchestrator controls flow<br> * - Factory: AgentFactory for agent creation<br> * - Observer: WorkflowExecutionListener for events<br> * <br> * Technologies:<br> * - Spring Boot: Application framework<br> * - MongoDB: Workflow persistence<br> * - Apache Camel: Enterprise integration patterns<br> * - Spring OpenAI: Agentic capabilities<br> * <br> * ===================================================================<br> */<br><br>// ===================================================================<br>// SPRING BOOT APPLICATION<br>// ===================================================================<br><br>@SpringBootApplication<br>public class WorkflowFramework {<br>    public static void main(String[] args) {<br>        SpringApplication.run(WorkflowFramework.class, args);<br>    }<br>}<br><br>// ===================================================================<br>// DOMAIN MODEL - STAGE ENUM (FSM States)<br>// ===================================================================<br><br>enum Stage {<br>    START,<br>    SYSTEM_INTEGRATION,<br>    DATA_EXTRACTION,<br>    DATA_MAPPING,<br>    DATA_VALIDATION,<br>    DATA_TRANSFORMATION,<br>    DATA_LOAD,<br>    COMPLETED,<br>    FAILED<br>}<br><br>// ===================================================================<br>// DOMAIN MODEL - AGENT STATUS (Command Result)<br>// ===================================================================<br><br>enum AgentStatus {<br>    SUCCESS,<br>    FAILURE,<br>    RETRY<br>}<br><br>// ===================================================================<br>// DOMAIN MODEL - AGENT RESULT (Command Pattern)<br>// ===================================================================<br><br>class AgentResult {<br>    private final AgentStatus status;<br>    private final String message;<br>    private final Map&lt;String, Object&gt; metadata;<br>    private final Throwable error;<br><br>    private AgentResult(AgentStatus status, String message, Map&lt;String, Object&gt; metadata, Throwable error) {<br>        this.status = status;<br>        this.message = message;<br>        this.metadata = metadata != null ? metadata : new HashMap&lt;&gt;();<br>        this.error = error;<br>    }<br><br>    public static AgentResult success() {<br>        return new AgentResult(AgentStatus.SUCCESS, &quot;Execution successful&quot;, null, null);<br>    }<br><br>    public static AgentResult success(String message) {<br>        return new AgentResult(AgentStatus.SUCCESS, message, null, null);<br>    }<br><br>    public static AgentResult success(String message, Map&lt;String, Object&gt; metadata) {<br>        return new AgentResult(AgentStatus.SUCCESS, message, metadata, null);<br>    }<br><br>    public static AgentResult failure(String message) {<br>        return new AgentResult(AgentStatus.FAILURE, message, null, null);<br>    }<br><br>    public static AgentResult failure(String message, Throwable error) {<br>        return new AgentResult(AgentStatus.FAILURE, message, null, error);<br>    }<br><br>    public static AgentResult retry(String message) {<br>        return new AgentResult(AgentStatus.RETRY, message, null, null);<br>    }<br><br>    public boolean isSuccess() {<br>        return status == AgentStatus.SUCCESS;<br>    }<br><br>    public boolean isFailure() {<br>        return status == AgentStatus.FAILURE;<br>    }<br><br>    public boolean isRetry() {<br>        return status == AgentStatus.RETRY;<br>    }<br><br>    public AgentStatus getStatus() { return status; }<br>    public String getMessage() { return message; }<br>    public Map&lt;String, Object&gt; getMetadata() { return metadata; }<br>    public Throwable getError() { return error; }<br>}<br><br>// ===================================================================<br>// DOMAIN MODEL - WORKFLOW CONTEXT (Context Object Pattern)<br>// ===================================================================<br><br>class WorkflowContext {<br>    private String workflowId;<br>    private String executionId;<br>    private Stage currentStage;<br>    private final Map&lt;String, Object&gt; data = new ConcurrentHashMap&lt;&gt;();<br>    private final List&lt;String&gt; errors = new ArrayList&lt;&gt;();<br>    private final List&lt;String&gt; warnings = new ArrayList&lt;&gt;();<br>    private final Map&lt;String, Object&gt; metadata = new HashMap&lt;&gt;();<br>    private long startTime;<br>    private long endTime;<br><br>    public WorkflowContext(String workflowId) {<br>        this.workflowId = workflowId;<br>        this.executionId = UUID.randomUUID().toString();<br>        this.currentStage = Stage.START;<br>        this.startTime = System.currentTimeMillis();<br>    }<br><br>    public String getWorkflowId() { return workflowId; }<br>    public String getExecutionId() { return executionId; }<br>    public Stage getCurrentStage() { return currentStage; }<br>    public void setCurrentStage(Stage stage) { this.currentStage = stage; }<br>    public Map&lt;String, Object&gt; data() { return data; }<br>    public List&lt;String&gt; errors() { return errors; }<br>    public List&lt;String&gt; warnings() { return warnings; }<br>    public Map&lt;String, Object&gt; getMetadata() { return metadata; }<br>    public long getStartTime() { return startTime; }<br>    public long getEndTime() { return endTime; }<br>    public void setEndTime(long endTime) { this.endTime = endTime; }<br>    public long getDuration() { return endTime &gt; 0 ? endTime - startTime : System.currentTimeMillis() - startTime; }<br><br>    public void addError(String error) {<br>        this.errors.add(error);<br>    }<br><br>    public void addWarning(String warning) {<br>        this.warnings.add(warning);<br>    }<br><br>    public &lt;T&gt; T getData(String key, Class&lt;T&gt; type) {<br>        Object value = data.get(key);<br>        return type.isInstance(value) ? type.cast(value) : null;<br>    }<br><br>    public void putData(String key, Object value) {<br>        data.put(key, value);<br>    }<br>}<br><br>// ===================================================================<br>// DOMAIN MODEL - WORKFLOW DEFINITION (MongoDB Document)<br>// ===================================================================<br><br>@Document(collection = &quot;workflows&quot;)<br>class WorkflowDefinition {<br>    @Id<br>    private String id;<br>    private String workflowId;<br>    private String name;<br>    private String description;<br>    private Map&lt;Stage, String&gt; strategyMap;<br>    private Map&lt;String, Object&gt; configuration;<br>    private boolean active;<br>    private long createdAt;<br>    private long updatedAt;<br><br>    public WorkflowDefinition() {<br>        this.strategyMap = new HashMap&lt;&gt;();<br>        this.configuration = new HashMap&lt;&gt;();<br>        this.active = true;<br>        this.createdAt = System.currentTimeMillis();<br>        this.updatedAt = System.currentTimeMillis();<br>    }<br><br>    // Getters and Setters<br>    public String getId() { return id; }<br>    public void setId(String id) { this.id = id; }<br>    public String getWorkflowId() { return workflowId; }<br>    public void setWorkflowId(String workflowId) { this.workflowId = workflowId; }<br>    public String getName() { return name; }<br>    public void setName(String name) { this.name = name; }<br>    public String getDescription() { return description; }<br>    public void setDescription(String description) { this.description = description; }<br>    public Map&lt;Stage, String&gt; getStrategyMap() { return strategyMap; }<br>    public void setStrategyMap(Map&lt;Stage, String&gt; strategyMap) { this.strategyMap = strategyMap; }<br>    public Map&lt;String, Object&gt; getConfiguration() { return configuration; }<br>    public void setConfiguration(Map&lt;String, Object&gt; configuration) { this.configuration = configuration; }<br>    public boolean isActive() { return active; }<br>    public void setActive(boolean active) { this.active = active; }<br>    public long getCreatedAt() { return createdAt; }<br>    public void setCreatedAt(long createdAt) { this.createdAt = createdAt; }<br>    public long getUpdatedAt() { return updatedAt; }<br>    public void setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; }<br>}<br><br>// ===================================================================<br>// DOMAIN MODEL - WORKFLOW EXECUTION (MongoDB Document)<br>// ===================================================================<br><br>@Document(collection = &quot;workflow_executions&quot;)<br>class WorkflowExecution {<br>    @Id<br>    private String id;<br>    private String workflowId;<br>    private String executionId;<br>    private Stage currentStage;<br>    private Stage finalStage;<br>    private Map&lt;String, Object&gt; contextData;<br>    private List&lt;String&gt; errors;<br>    private List&lt;String&gt; warnings;<br>    private long startTime;<br>    private long endTime;<br>    private String status;<br><br>    public WorkflowExecution() {<br>        this.contextData = new HashMap&lt;&gt;();<br>        this.errors = new ArrayList&lt;&gt;();<br>        this.warnings = new ArrayList&lt;&gt;();<br>    }<br><br>    // Getters and Setters<br>    public String getId() { return id; }<br>    public void setId(String id) { this.id = id; }<br>    public String getWorkflowId() { return workflowId; }<br>    public void setWorkflowId(String workflowId) { this.workflowId = workflowId; }<br>    public String getExecutionId() { return executionId; }<br>    public void setExecutionId(String executionId) { this.executionId = executionId; }<br>    public Stage getCurrentStage() { return currentStage; }<br>    public void setCurrentStage(Stage currentStage) { this.currentStage = currentStage; }<br>    public Stage getFinalStage() { return finalStage; }<br>    public void setFinalStage(Stage finalStage) { this.finalStage = finalStage; }<br>    public Map&lt;String, Object&gt; getContextData() { return contextData; }<br>    public void setContextData(Map&lt;String, Object&gt; contextData) { this.contextData = contextData; }<br>    public List&lt;String&gt; getErrors() { return errors; }<br>    public void setErrors(List&lt;String&gt; errors) { this.errors = errors; }<br>    public List&lt;String&gt; getWarnings() { return warnings; }<br>    public void setWarnings(List&lt;String&gt; warnings) { this.warnings = warnings; }<br>    public long getStartTime() { return startTime; }<br>    public void setStartTime(long startTime) { this.startTime = startTime; }<br>    public long getEndTime() { return endTime; }<br>    public void setEndTime(long endTime) { this.endTime = endTime; }<br>    public String getStatus() { return status; }<br>    public void setStatus(String status) { this.status = status; }<br>}<br><br>// ===================================================================<br>// REPOSITORY INTERFACES (MongoDB)<br>// ===================================================================<br><br>interface WorkflowDefinitionRepository extends MongoRepository&lt;WorkflowDefinition, String&gt; {<br>    Optional&lt;WorkflowDefinition&gt; findByWorkflowId(String workflowId);<br>    List&lt;WorkflowDefinition&gt; findByActiveTrue();<br>}<br><br>interface WorkflowExecutionRepository extends MongoRepository&lt;WorkflowExecution, String&gt; {<br>    Optional&lt;WorkflowExecution&gt; findByExecutionId(String executionId);<br>    List&lt;WorkflowExecution&gt; findByWorkflowId(String workflowId);<br>}<br><br>// ===================================================================<br>// EXCEPTION HANDLING DESIGN<br>// ===================================================================<br><br>// Base Exception<br>class WorkflowException extends RuntimeException {<br>    private final String workflowId;<br>    private final Stage stage;<br>    private final String errorCode;<br><br>    public WorkflowException(String message, String workflowId, Stage stage, String errorCode) {<br>        super(message);<br>        this.workflowId = workflowId;<br>        this.stage = stage;<br>        this.errorCode = errorCode;<br>    }<br><br>    public WorkflowException(String message, Throwable cause, String workflowId, Stage stage, String errorCode) {<br>        super(message, cause);<br>        this.workflowId = workflowId;<br>        this.stage = stage;<br>        this.errorCode = errorCode;<br>    }<br><br>    public String getWorkflowId() { return workflowId; }<br>    public Stage getStage() { return stage; }<br>    public String getErrorCode() { return errorCode; }<br>}<br><br>// Specific Exceptions<br>class WorkflowConfigurationException extends WorkflowException {<br>    public WorkflowConfigurationException(String message, String workflowId) {<br>        super(message, workflowId, null, &quot;CONFIG_ERROR&quot;);<br>    }<br>}<br><br>class AgentNotFoundException extends WorkflowException {<br>    public AgentNotFoundException(String message, String workflowId, Stage stage) {<br>        super(message, workflowId, stage, &quot;AGENT_NOT_FOUND&quot;);<br>    }<br>}<br><br>class AgentExecutionException extends WorkflowException {<br>    public AgentExecutionException(String message, Throwable cause, String workflowId, Stage stage) {<br>        super(message, cause, workflowId, stage, &quot;AGENT_EXECUTION_ERROR&quot;);<br>    }<br>}<br><br>class WorkflowStateException extends WorkflowException {<br>    public WorkflowStateException(String message, String workflowId, Stage stage) {<br>        super(message, workflowId, stage, &quot;STATE_ERROR&quot;);<br>    }<br>}<br><br>// Exception Handler Service<br>@Service<br>class WorkflowExceptionHandler {<br>    <br>    public AgentResult handleException(Throwable exception, WorkflowContext context) {<br>        if (exception instanceof WorkflowException) {<br>            WorkflowException we = (WorkflowException) exception;<br>            context.addError(String.format(&quot;[%s] %s: %s&quot;, we.getErrorCode(), we.getStage(), we.getMessage()));<br>            <br>            if (exception.getCause() != null) {<br>                context.addError(&quot;Root cause: &quot; + exception.getCause().getMessage());<br>            }<br>            <br>            return AgentResult.failure(we.getMessage(), we);<br>        } else {<br>            context.addError(&quot;Unexpected error: &quot; + exception.getMessage());<br>            return AgentResult.failure(&quot;Unexpected error occurred&quot;, exception);<br>        }<br>    }<br><br>    public AgentResult handleRetryableException(Throwable exception, WorkflowContext context, int retryCount, int maxRetries) {<br>        if (retryCount &lt; maxRetries) {<br>            context.addWarning(String.format(&quot;Retryable error (attempt %d/%d): %s&quot;, retryCount + 1, maxRetries, exception.getMessage()));<br>            return AgentResult.retry(&quot;Retrying after error&quot;);<br>        } else {<br>            return handleException(exception, context);<br>        }<br>    }<br>}<br><br>// ===================================================================<br>// AGENT CONTRACT (Strategy + Command Pattern)<br>// ===================================================================<br><br>interface WorkflowAgent {<br>    <br>    boolean supports(Stage stage, String strategy);<br><br>    <br>    AgentResult execute(WorkflowContext context);<br><br>    <br>    default String getName() {<br>        return this.getClass().getSimpleName();<br>    }<br><br>    default String getDescription() {<br>        return &quot;Workflow agent&quot;;<br>    }<br>}<br><br>// ===================================================================<br>// AGENT REGISTRY (Registry Pattern)<br>// ===================================================================<br><br>@Component<br>class AgentRegistry {<br>    private final List&lt;WorkflowAgent&gt; agents = new ArrayList&lt;&gt;();<br>    private final Map&lt;String, WorkflowAgent&gt; agentCache = new ConcurrentHashMap&lt;&gt;();<br><br>    @Autowired(required = false)<br>    public void setAgents(List&lt;WorkflowAgent&gt; agents) {<br>        this.agents.clear();<br>        this.agents.addAll(agents);<br>        this.agentCache.clear();<br>    }<br><br>    public void register(WorkflowAgent agent) {<br>        agents.add(agent);<br>        agentCache.clear();<br>    }<br><br>    public WorkflowAgent resolve(Stage stage, String strategy) {<br>        String key = stage.name() + &quot;:&quot; + strategy;<br>        return agentCache.computeIfAbsent(key, k -&gt; <br>            agents.stream()<br>                .filter(a -&gt; a.supports(stage, strategy))<br>                .findFirst()<br>                .orElseThrow(() -&gt; new AgentNotFoundException(<br>                    String.format(&quot;No agent found for stage %s with strategy %s&quot;, stage, strategy),<br>                    null, stage))<br>        );<br>    }<br><br>    public List&lt;WorkflowAgent&gt; getAllAgents() {<br>        return new ArrayList&lt;&gt;(agents);<br>    }<br>}<br><br>// ===================================================================<br>// FINITE STATE MACHINE (FSM Pattern)<br>// ===================================================================<br><br>@Component<br>class WorkflowStateMachine {<br>    <br>    private static final Map&lt;Stage, Stage&gt; SUCCESS_TRANSITIONS = Map.of(<br>        Stage.START, Stage.SYSTEM_INTEGRATION,<br>        Stage.SYSTEM_INTEGRATION, Stage.DATA_EXTRACTION,<br>        Stage.DATA_EXTRACTION, Stage.DATA_MAPPING,<br>        Stage.DATA_MAPPING, Stage.DATA_VALIDATION,<br>        Stage.DATA_VALIDATION, Stage.DATA_TRANSFORMATION,<br>        Stage.DATA_TRANSFORMATION, Stage.DATA_LOAD,<br>        Stage.DATA_LOAD, Stage.COMPLETED<br>    );<br><br>    public Stage next(Stage current, AgentResult result) {<br>        if (result.isFailure()) {<br>            return Stage.FAILED;<br>        }<br><br>        if (result.isRetry()) {<br>            return current; // Stay in current stage for retry<br>        }<br><br>        Stage next = SUCCESS_TRANSITIONS.get(current);<br>        return next != null ? next : Stage.FAILED;<br>    }<br><br>    public boolean isTerminal(Stage stage) {<br>        return stage == Stage.COMPLETED || stage == Stage.FAILED;<br>    }<br><br>    public boolean isValidTransition(Stage from, Stage to) {<br>        if (to == Stage.FAILED) {<br>            return true; // Can always transition to FAILED<br>        }<br>        return SUCCESS_TRANSITIONS.get(from) == to;<br>    }<br><br>    public List&lt;Stage&gt; getValidNextStages(Stage current) {<br>        if (isTerminal(current)) {<br>            return Collections.emptyList();<br>        }<br>        Stage next = SUCCESS_TRANSITIONS.get(current);<br>        return next != null ? List.of(next, Stage.FAILED) : List.of(Stage.FAILED);<br>    }<br>}<br><br>// ===================================================================<br>// WORKFLOW ORCHESTRATOR (Orchestrator Pattern)<br>// ===================================================================<br><br>@Component<br>class WorkflowOrchestrator {<br>    private final AgentRegistry registry;<br>    private final WorkflowStateMachine fsm;<br>    private final WorkflowExceptionHandler exceptionHandler;<br>    private final List&lt;WorkflowExecutionListener&gt; listeners = new ArrayList&lt;&gt;();<br>    private static final int MAX_RETRIES = 3;<br><br>    @Autowired<br>    public WorkflowOrchestrator(AgentRegistry registry, <br>                                WorkflowStateMachine fsm,<br>                                WorkflowExceptionHandler exceptionHandler) {<br>        this.registry = registry;<br>        this.fsm = fsm;<br>        this.exceptionHandler = exceptionHandler;<br>    }<br><br>    public void addListener(WorkflowExecutionListener listener) {<br>        listeners.add(listener);<br>    }<br><br>    public void orchestrate(WorkflowContext context, Map&lt;Stage, String&gt; strategyMap) {<br>        notifyListeners(l -&gt; l.onExecutionStart(context));<br><br>        while (!fsm.isTerminal(context.getCurrentStage())) {<br>            Stage stage = context.getCurrentStage();<br>            String strategy = strategyMap.get(stage);<br><br>            if (strategy == null) {<br>                throw new WorkflowConfigurationException(<br>                    String.format(&quot;No strategy defined for stage %s in workflow %s&quot;, stage, context.getWorkflowId()),<br>                    context.getWorkflowId());<br>            }<br><br>            notifyListeners(l -&gt; l.onStageStart(context, stage));<br><br>            AgentResult result = executeStage(context, stage, strategy);<br><br>            Stage next = fsm.next(stage, result);<br>            <br>            if (!fsm.isValidTransition(stage, next)) {<br>                throw new WorkflowStateException(<br>                    String.format(&quot;Invalid transition from %s to %s&quot;, stage, next),<br>                    context.getWorkflowId(), stage);<br>            }<br><br>            context.setCurrentStage(next);<br>            notifyListeners(l -&gt; l.onStageComplete(context, stage, result));<br><br>            if (result.isRetry() &amp;&amp; next == stage) {<br>                // Retry logic - wait before retry<br>                try {<br>                    Thread.sleep(1000); // Simple retry delay<br>                } catch (InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                    break;<br>                }<br>            }<br>        }<br><br>        context.setEndTime(System.currentTimeMillis());<br>        notifyListeners(l -&gt; l.onExecutionComplete(context));<br>    }<br><br>    private AgentResult executeStage(WorkflowContext context, Stage stage, String strategy) {<br>        int retryCount = 0;<br>        <br>        while (retryCount &lt;= MAX_RETRIES) {<br>            try {<br>                WorkflowAgent agent = registry.resolve(stage, strategy);<br>                AgentResult result = agent.execute(context);<br>                <br>                if (!result.isRetry() || retryCount &gt;= MAX_RETRIES) {<br>                    return result;<br>                }<br>                <br>                retryCount++;<br>            } catch (WorkflowException e) {<br>                return exceptionHandler.handleRetryableException(e, context, retryCount, MAX_RETRIES);<br>            } catch (Exception e) {<br>                return exceptionHandler.handleException(e, context);<br>            }<br>        }<br>        <br>        return AgentResult.failure(&quot;Max retries exceeded&quot;);<br>    }<br><br>    private void notifyListeners(java.util.function.Consumer&lt;WorkflowExecutionListener&gt; action) {<br>        listeners.forEach(listener -&gt; {<br>            try {<br>                action.accept(listener);<br>            } catch (Exception e) {<br>                // Log but don&#39;t fail execution<br>                System.err.println(&quot;Listener error: &quot; + e.getMessage());<br>            }<br>        });<br>    }<br>}<br><br>// ===================================================================<br>// OBSERVER PATTERN - EXECUTION LISTENERS<br>// ===================================================================<br><br>interface WorkflowExecutionListener {<br>    default void onExecutionStart(WorkflowContext context) {}<br>    default void onStageStart(WorkflowContext context, Stage stage) {}<br>    default void onStageComplete(WorkflowContext context, Stage stage, AgentResult result) {}<br>    default void onExecutionComplete(WorkflowContext context) {}<br>}<br><br>// ===================================================================<br>// WORKFLOW ENGINE (Template Method Pattern)<br>// ===================================================================<br><br>@Service<br>abstract class WorkflowEngine {<br>    protected final WorkflowOrchestrator orchestrator;<br>    protected final WorkflowDefinitionRepository definitionRepository;<br>    protected final WorkflowExecutionRepository executionRepository;<br>    protected final MongoTemplate mongoTemplate;<br><br>    @Autowired<br>    public WorkflowEngine(WorkflowOrchestrator orchestrator,<br>                         WorkflowDefinitionRepository definitionRepository,<br>                         WorkflowExecutionRepository executionRepository,<br>                         MongoTemplate mongoTemplate) {<br>        this.orchestrator = orchestrator;<br>        this.definitionRepository = definitionRepository;<br>        this.executionRepository = executionRepository;<br>        this.mongoTemplate = mongoTemplate;<br>    }<br><br>    /**<br>     * Template method - defines the execution skeleton<br>     */<br>    public final void run(String workflowId) {<br>        WorkflowContext context = null;<br>        try {<br>            // Load workflow definition<br>            WorkflowDefinition definition = loadWorkflowDefinition(workflowId);<br>            if (definition == null || !definition.isActive()) {<br>                throw new WorkflowConfigurationException(<br>                    &quot;Workflow not found or inactive: &quot; + workflowId, workflowId);<br>            }<br><br>            // Initialize context<br>            context = new WorkflowContext(workflowId);<br>            context.getMetadata().putAll(definition.getConfiguration());<br><br>            // Persist execution start<br>            persistExecutionStart(context);<br><br>            // Load strategy map<br>            Map&lt;Stage, String&gt; strategyMap = definition.getStrategyMap();<br>            if (strategyMap == null || strategyMap.isEmpty()) {<br>                throw new WorkflowConfigurationException(<br>                    &quot;No strategy map defined for workflow: &quot; + workflowId, workflowId);<br>            }<br><br>            // Build orchestrator (already injected, but can be customized)<br>            WorkflowOrchestrator executor = buildOrchestrator();<br><br>            // Execute workflow<br>            executor.orchestrate(context, strategyMap);<br><br>            // Persist execution completion<br>            persistExecutionEnd(context);<br><br>            // Post-execution hook<br>            afterCompletion(context);<br><br>        } catch (WorkflowException e) {<br>            if (context != null) {<br>                context.setCurrentStage(Stage.FAILED);<br>                context.addError(e.getMessage());<br>                persistExecutionEnd(context);<br>                afterFailure(context, e);<br>            }<br>            throw e;<br>        } catch (Exception e) {<br>            if (context != null) {<br>                context.setCurrentStage(Stage.FAILED);<br>                context.addError(&quot;Unexpected error: &quot; + e.getMessage());<br>                persistExecutionEnd(context);<br>                afterFailure(context, e);<br>            }<br>            throw new WorkflowException(&quot;Workflow execution failed&quot;, e, <br>                workflowId != null ? workflowId : &quot;unknown&quot;, null, &quot;EXECUTION_ERROR&quot;);<br>        }<br>    }<br><br>    protected WorkflowDefinition loadWorkflowDefinition(String workflowId) {<br>        return definitionRepository.findByWorkflowId(workflowId)<br>            .orElse(null);<br>    }<br><br>    protected WorkflowOrchestrator buildOrchestrator() {<br>        return orchestrator;<br>    }<br><br>    protected void persistExecutionStart(WorkflowContext context) {<br>        WorkflowExecution execution = new WorkflowExecution();<br>        execution.setExecutionId(context.getExecutionId());<br>        execution.setWorkflowId(context.getWorkflowId());<br>        execution.setCurrentStage(context.getCurrentStage());<br>        execution.setStartTime(context.getStartTime());<br>        execution.setStatus(&quot;RUNNING&quot;);<br>        executionRepository.save(execution);<br>    }<br><br>    protected void persistExecutionEnd(WorkflowContext context) {<br>        WorkflowExecution execution = executionRepository<br>            .findByExecutionId(context.getExecutionId())<br>            .orElse(new WorkflowExecution());<br>        <br>        execution.setCurrentStage(context.getCurrentStage());<br>        execution.setFinalStage(context.getCurrentStage());<br>        execution.setContextData(new HashMap&lt;&gt;(context.data()));<br>        execution.setErrors(new ArrayList&lt;&gt;(context.errors()));<br>        execution.setWarnings(new ArrayList&lt;&gt;(context.warnings()));<br>        execution.setEndTime(context.getEndTime());<br>        execution.setStatus(context.getCurrentStage() == Stage.COMPLETED ? &quot;COMPLETED&quot; : &quot;FAILED&quot;);<br>        <br>        executionRepository.save(execution);<br>    }<br><br>    protected void afterCompletion(WorkflowContext context) {<br>        // Override for custom post-execution logic<br>        System.out.println(String.format(&quot;Workflow %s completed in %d ms&quot;, <br>            context.getWorkflowId(), context.getDuration()));<br>    }<br><br>    protected void afterFailure(WorkflowContext context, Throwable error) {<br>        // Override for custom failure handling<br>        System.err.println(String.format(&quot;Workflow %s failed: %s&quot;, <br>            context.getWorkflowId(), error.getMessage()));<br>    }<br>}<br><br>// ===================================================================<br>// AGENT IMPLEMENTATIONS<br>// ===================================================================<br><br>// ===================================================================<br>// INTEGRATION AGENTS (Adapter Pattern)<br>// ===================================================================<br><br>@Component<br>class RestIntegrationAgent implements WorkflowAgent {<br>    private final ProducerTemplate camelTemplate;<br><br>    @Autowired(required = false)<br>    public RestIntegrationAgent(ProducerTemplate camelTemplate) {<br>        this.camelTemplate = camelTemplate;<br>    }<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.SYSTEM_INTEGRATION &amp;&amp; &quot;REST&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            String endpoint = context.getMetadata().getOrDefault(&quot;rest.endpoint&quot;, &quot;&quot;).toString();<br>            if (endpoint.isEmpty()) {<br>                return AgentResult.failure(&quot;REST endpoint not configured&quot;);<br>            }<br><br>            // Use Apache Camel for REST integration<br>            if (camelTemplate != null) {<br>                Object response = camelTemplate.requestBody(&quot;direct:rest-integration&quot;, endpoint);<br>                context.putData(&quot;rawResponse&quot;, response);<br>                context.putData(&quot;integrationType&quot;, &quot;REST&quot;);<br>                return AgentResult.success(&quot;REST integration completed&quot;, <br>                    Map.of(&quot;endpoint&quot;, endpoint));<br>            } else {<br>                // Fallback simulation<br>                context.putData(&quot;rawResponse&quot;, &quot;simulated-rest-data&quot;);<br>                context.putData(&quot;integrationType&quot;, &quot;REST&quot;);<br>                return AgentResult.success(&quot;REST integration completed (simulated)&quot;);<br>            }<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;REST integration failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return &quot;REST API integration agent using Apache Camel&quot;;<br>    }<br>}<br><br>@Component<br>class KafkaIntegrationAgent implements WorkflowAgent {<br>    private final ProducerTemplate camelTemplate;<br><br>    @Autowired(required = false)<br>    public KafkaIntegrationAgent(ProducerTemplate camelTemplate) {<br>        this.camelTemplate = camelTemplate;<br>    }<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.SYSTEM_INTEGRATION &amp;&amp; &quot;KAFKA&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            String topic = context.getMetadata().getOrDefault(&quot;kafka.topic&quot;, &quot;&quot;).toString();<br>            if (topic.isEmpty()) {<br>                return AgentResult.failure(&quot;Kafka topic not configured&quot;);<br>            }<br><br>            if (camelTemplate != null) {<br>                Object message = camelTemplate.requestBody(&quot;direct:kafka-consumer&quot;, topic);<br>                context.putData(&quot;kafkaMessage&quot;, message);<br>                context.putData(&quot;integrationType&quot;, &quot;KAFKA&quot;);<br>                return AgentResult.success(&quot;Kafka integration completed&quot;);<br>            } else {<br>                context.putData(&quot;kafkaMessage&quot;, &quot;simulated-kafka-data&quot;);<br>                context.putData(&quot;integrationType&quot;, &quot;KAFKA&quot;);<br>                return AgentResult.success(&quot;Kafka integration completed (simulated)&quot;);<br>            }<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;Kafka integration failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return &quot;Kafka message integration agent using Apache Camel&quot;;<br>    }<br>}<br><br>// ===================================================================<br>// DATA EXTRACTION AGENTS<br>// ===================================================================<br><br>@Component<br>class JsonExtractionAgent implements WorkflowAgent {<br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_EXTRACTION &amp;&amp; &quot;JSON&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            Object rawData = context.getData(&quot;rawResponse&quot;, Object.class);<br>            if (rawData == null) {<br>                rawData = context.getData(&quot;kafkaMessage&quot;, Object.class);<br>            }<br><br>            if (rawData == null) {<br>                return AgentResult.failure(&quot;No raw data found for extraction&quot;);<br>            }<br><br>            // Simulate JSON extraction<br>            Map&lt;String, Object&gt; extracted = Map.of(<br>                &quot;extractedData&quot;, rawData,<br>                &quot;format&quot;, &quot;JSON&quot;,<br>                &quot;timestamp&quot;, System.currentTimeMillis()<br>            );<br><br>            context.putData(&quot;extractedData&quot;, extracted);<br>            return AgentResult.success(&quot;JSON extraction completed&quot;);<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;JSON extraction failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br>}<br><br>@Component<br>class XmlExtractionAgent implements WorkflowAgent {<br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_EXTRACTION &amp;&amp; &quot;XML&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            Object rawData = context.getData(&quot;rawResponse&quot;, Object.class);<br>            if (rawData == null) {<br>                return AgentResult.failure(&quot;No raw data found for extraction&quot;);<br>            }<br><br>            // Simulate XML extraction<br>            Map&lt;String, Object&gt; extracted = Map.of(<br>                &quot;extractedData&quot;, rawData,<br>                &quot;format&quot;, &quot;XML&quot;,<br>                &quot;timestamp&quot;, System.currentTimeMillis()<br>            );<br><br>            context.putData(&quot;extractedData&quot;, extracted);<br>            return AgentResult.success(&quot;XML extraction completed&quot;);<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;XML extraction failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br>}<br><br>// ===================================================================<br>// DATA MAPPING AGENT<br>// ===================================================================<br><br>@Component<br>class DataMappingAgent implements WorkflowAgent {<br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_MAPPING;<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; extracted = context.getData(&quot;extractedData&quot;, Map.class);<br>            if (extracted == null) {<br>                return AgentResult.failure(&quot;No extracted data found for mapping&quot;);<br>            }<br><br>            // Apply mapping rules from configuration<br>            Map&lt;String, Object&gt; mapped = new HashMap&lt;&gt;();<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, String&gt; mappingRules = (Map&lt;String, String&gt;) <br>                context.getMetadata().getOrDefault(&quot;mappingRules&quot;, Map.of());<br><br>            if (mappingRules.isEmpty()) {<br>                // Default mapping - pass through<br>                mapped.putAll(extracted);<br>            } else {<br>                // Apply configured mapping rules<br>                mappingRules.forEach((source, target) -&gt; {<br>                    Object value = extracted.get(source);<br>                    if (value != null) {<br>                        mapped.put(target, value);<br>                    }<br>                });<br>            }<br><br>            context.putData(&quot;mappedData&quot;, mapped);<br>            return AgentResult.success(&quot;Data mapping completed&quot;);<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;Data mapping failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br>}<br><br>// ===================================================================<br>// VALIDATION AGENTS (Chain of Responsibility)<br>// ===================================================================<br><br>@Component<br>class RuleValidationAgent implements WorkflowAgent {<br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_VALIDATION &amp;&amp; &quot;RULE&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; mapped = context.getData(&quot;mappedData&quot;, Map.class);<br>            if (mapped == null) {<br>                context.addError(&quot;No mapped data found for validation&quot;);<br>                return AgentResult.failure(&quot;Validation failed: missing data&quot;);<br>            }<br><br>            // Apply validation rules<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            List&lt;Map&lt;String, Object&gt;&gt; rules = (List&lt;Map&lt;String, Object&gt;&gt;) <br>                context.getMetadata().getOrDefault(&quot;validationRules&quot;, List.of());<br><br>            List&lt;String&gt; validationErrors = new ArrayList&lt;&gt;();<br>            for (Map&lt;String, Object&gt; rule : rules) {<br>                String field = (String) rule.get(&quot;field&quot;);<br>                String condition = (String) rule.get(&quot;condition&quot;);<br>                Object expected = rule.get(&quot;expected&quot;);<br><br>                Object actual = mapped.get(field);<br>                if (!validateRule(actual, condition, expected)) {<br>                    validationErrors.add(String.format(&quot;Validation failed for field %s: %s&quot;, field, condition));<br>                }<br>            }<br><br>            if (!validationErrors.isEmpty()) {<br>                validationErrors.forEach(context::addError);<br>                return AgentResult.failure(&quot;Validation failed: &quot; + validationErrors.size() + &quot; errors&quot;);<br>            }<br><br>            context.putData(&quot;validatedData&quot;, mapped);<br>            return AgentResult.success(&quot;Rule validation completed&quot;);<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;Validation failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br><br>    private boolean validateRule(Object actual, String condition, Object expected) {<br>        if (actual == null) {<br>            return &quot;NULL&quot;.equals(condition);<br>        }<br>        switch (condition) {<br>            case &quot;EQUALS&quot;:<br>                return actual.equals(expected);<br>            case &quot;NOT_NULL&quot;:<br>                return actual != null;<br>            case &quot;NOT_EMPTY&quot;:<br>                return actual.toString().trim().length() &gt; 0;<br>            default:<br>                return true;<br>        }<br>    }<br>}<br><br>@Component<br>class AiValidationAgent implements WorkflowAgent {<br>    private final ChatClient chatClient;<br><br>    @Autowired(required = false)<br>    public AiValidationAgent(ChatClient chatClient) {<br>        this.chatClient = chatClient;<br>    }<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_VALIDATION &amp;&amp; &quot;AI&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; mapped = context.getData(&quot;mappedData&quot;, Map.class);<br>            if (mapped == null) {<br>                return AgentResult.failure(&quot;No mapped data found for AI validation&quot;);<br>            }<br><br>            if (chatClient != null) {<br>                // Use Spring AI for intelligent validation<br>                String prompt = String.format(<br>                    &quot;Validate the following data and provide feedback: %s. &quot; +<br>                    &quot;Check for data quality, completeness, and business rule compliance.&quot;,<br>                    mapped<br>                );<br><br>                String response = chatClient.prompt(prompt)<br>                    .call()<br>                    .content();<br><br>                // Parse AI response (simplified)<br>                if (response.toLowerCase().contains(&quot;valid&quot;) || <br>                    response.toLowerCase().contains(&quot;pass&quot;)) {<br>                    context.putData(&quot;validatedData&quot;, mapped);<br>                    context.putData(&quot;aiValidationFeedback&quot;, response);<br>                    return AgentResult.success(&quot;AI validation completed: &quot; + response);<br>                } else {<br>                    context.addError(&quot;AI validation failed: &quot; + response);<br>                    return AgentResult.failure(&quot;AI validation failed&quot;);<br>                }<br>            } else {<br>                // Fallback to basic validation<br>                context.putData(&quot;validatedData&quot;, mapped);<br>                return AgentResult.success(&quot;AI validation completed (fallback mode)&quot;);<br>            }<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;AI validation failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return &quot;AI-powered validation agent using Spring OpenAI&quot;;<br>    }<br>}<br><br>// ===================================================================<br>// TRANSFORMATION AGENTS<br>// ===================================================================<br><br>@Component<br>class ScriptTransformationAgent implements WorkflowAgent {<br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_TRANSFORMATION &amp;&amp; &quot;SCRIPT&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; validated = context.getData(&quot;validatedData&quot;, Map.class);<br>            if (validated == null) {<br>                return AgentResult.failure(&quot;No validated data found for transformation&quot;);<br>            }<br><br>            // Apply transformation script (simplified - in real implementation, use script engine)<br>            String script = context.getMetadata().getOrDefault(&quot;transformationScript&quot;, &quot;&quot;).toString();<br>            <br>            Map&lt;String, Object&gt; transformed = new HashMap&lt;&gt;(validated);<br>            if (!script.isEmpty()) {<br>                // In real implementation, execute script here<br>                transformed.put(&quot;transformed&quot;, true);<br>                transformed.put(&quot;transformationTimestamp&quot;, System.currentTimeMillis());<br>            }<br><br>            context.putData(&quot;transformedData&quot;, transformed);<br>            return AgentResult.success(&quot;Script transformation completed&quot;);<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;Transformation failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br>}<br><br>@Component<br>class AiTransformationAgent implements WorkflowAgent {<br>    private final ChatClient chatClient;<br><br>    @Autowired(required = false)<br>    public AiTransformationAgent(ChatClient chatClient) {<br>        this.chatClient = chatClient;<br>    }<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_TRANSFORMATION &amp;&amp; &quot;AI&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; validated = context.getData(&quot;validatedData&quot;, Map.class);<br>            if (validated == null) {<br>                return AgentResult.failure(&quot;No validated data found for AI transformation&quot;);<br>            }<br><br>            if (chatClient != null) {<br>                String prompt = String.format(<br>                    &quot;Transform the following data according to best practices: %s. &quot; +<br>                    &quot;Apply data enrichment, normalization, and business logic transformations.&quot;,<br>                    validated<br>                );<br><br>                String transformedJson = chatClient.prompt(prompt)<br>                    .call()<br>                    .content();<br><br>                // In real implementation, parse JSON response<br>                Map&lt;String, Object&gt; transformed = new HashMap&lt;&gt;(validated);<br>                transformed.put(&quot;aiTransformed&quot;, true);<br>                transformed.put(&quot;aiTransformationResult&quot;, transformedJson);<br>                transformed.put(&quot;transformationTimestamp&quot;, System.currentTimeMillis());<br><br>                context.putData(&quot;transformedData&quot;, transformed);<br>                return AgentResult.success(&quot;AI transformation completed&quot;);<br>            } else {<br>                // Fallback<br>                context.putData(&quot;transformedData&quot;, validated);<br>                return AgentResult.success(&quot;AI transformation completed (fallback mode)&quot;);<br>            }<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;AI transformation failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return &quot;AI-powered transformation agent using Spring OpenAI&quot;;<br>    }<br>}<br><br>// ===================================================================<br>// DATA LOAD AGENTS<br>// ===================================================================<br><br>@Component<br>class MongoLoadAgent implements WorkflowAgent {<br>    private final MongoTemplate mongoTemplate;<br><br>    @Autowired(required = false)<br>    public MongoLoadAgent(MongoTemplate mongoTemplate) {<br>        this.mongoTemplate = mongoTemplate;<br>    }<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_LOAD &amp;&amp; &quot;MONGO&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; transformed = context.getData(&quot;transformedData&quot;, Map.class);<br>            if (transformed == null) {<br>                return AgentResult.failure(&quot;No transformed data found for loading&quot;);<br>            }<br><br>            String collection = context.getMetadata().getOrDefault(&quot;mongo.collection&quot;, &quot;workflow_results&quot;).toString();<br><br>            if (mongoTemplate != null) {<br>                Map&lt;String, Object&gt; document = new HashMap&lt;&gt;(transformed);<br>                document.put(&quot;workflowId&quot;, context.getWorkflowId());<br>                document.put(&quot;executionId&quot;, context.getExecutionId());<br>                document.put(&quot;loadedAt&quot;, System.currentTimeMillis());<br>                <br>                mongoTemplate.save(document, collection);<br>                context.putData(&quot;loadTarget&quot;, &quot;MongoDB&quot;);<br>                context.putData(&quot;loadCollection&quot;, collection);<br>                return AgentResult.success(&quot;Data loaded to MongoDB: &quot; + collection);<br>            } else {<br>                context.putData(&quot;loadTarget&quot;, &quot;MongoDB (simulated)&quot;);<br>                return AgentResult.success(&quot;Data load to MongoDB completed (simulated)&quot;);<br>            }<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;MongoDB load failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br>}<br><br>@Component<br>class S3LoadAgent implements WorkflowAgent {<br>    private final ProducerTemplate camelTemplate;<br><br>    @Autowired(required = false)<br>    public S3LoadAgent(ProducerTemplate camelTemplate) {<br>        this.camelTemplate = camelTemplate;<br>    }<br><br>    @Override<br>    public boolean supports(Stage stage, String strategy) {<br>        return stage == Stage.DATA_LOAD &amp;&amp; &quot;S3&quot;.equals(strategy);<br>    }<br><br>    @Override<br>    public AgentResult execute(WorkflowContext context) {<br>        try {<br>            @SuppressWarnings(&quot;unchecked&quot;)<br>            Map&lt;String, Object&gt; transformed = context.getData(&quot;transformedData&quot;, Map.class);<br>            if (transformed == null) {<br>                return AgentResult.failure(&quot;No transformed data found for S3 loading&quot;);<br>            }<br><br>            String bucket = context.getMetadata().getOrDefault(&quot;s3.bucket&quot;, &quot;&quot;).toString();<br>            String key = context.getMetadata().getOrDefault(&quot;s3.key&quot;, &quot;&quot;).toString();<br><br>            if (camelTemplate != null &amp;&amp; !bucket.isEmpty()) {<br>                camelTemplate.sendBody(&quot;aws-s3://&quot; + bucket + &quot;?key=&quot; + key, transformed);<br>                context.putData(&quot;loadTarget&quot;, &quot;S3&quot;);<br>                context.putData(&quot;s3Bucket&quot;, bucket);<br>                context.putData(&quot;s3Key&quot;, key);<br>                return AgentResult.success(&quot;Data loaded to S3: &quot; + bucket + &quot;/&quot; + key);<br>            } else {<br>                context.putData(&quot;loadTarget&quot;, &quot;S3 (simulated)&quot;);<br>                return AgentResult.success(&quot;S3 load completed (simulated)&quot;);<br>            }<br>        } catch (Exception e) {<br>            return AgentResult.failure(&quot;S3 load failed: &quot; + e.getMessage(), e);<br>        }<br>    }<br>}<br><br>// ===================================================================<br>// APACHE CAMEL CONFIGURATION<br>// ===================================================================<br><br>@Configuration<br>class CamelConfiguration implements CamelContextConfiguration {<br>    <br>    @Override<br>    public void beforeApplicationStart(CamelContext context) {<br>        try {<br>            // REST Integration Route<br>            context.addRoutes(new RouteBuilder() {<br>                @Override<br>                public void configure() {<br>                    from(&quot;direct:rest-integration&quot;)<br>                        .log(&quot;REST Integration: ${body}&quot;)<br>                        .to(&quot;http://${body}?bridgeEndpoint=true&quot;)<br>                        .log(&quot;REST Response: ${body}&quot;);<br>                }<br>            });<br><br>            // Kafka Consumer Route<br>            context.addRoutes(new RouteBuilder() {<br>                @Override<br>                public void configure() {<br>                    from(&quot;direct:kafka-consumer&quot;)<br>                        .log(&quot;Consuming from Kafka topic: ${body}&quot;)<br>                        .to(&quot;kafka:${body}?brokers=localhost:9092&quot;)<br>                        .log(&quot;Kafka message received: ${body}&quot;);<br>                }<br>            });<br>        } catch (Exception e) {<br>            throw new RuntimeException(&quot;Failed to configure Camel routes&quot;, e);<br>        }<br>    }<br><br>    @Override<br>    public void afterApplicationStart(CamelContext context) {<br>        // Post-startup configuration if needed<br>    }<br>}<br><br>// ===================================================================<br>// SPRING AI CONFIGURATION<br>// ===================================================================<br><br>@Configuration<br>class SpringAiConfiguration {<br>    <br>    @Bean<br>    public ChatClient chatClient(OpenAiChatModel chatModel) {<br>        return ChatClient.builder(chatModel)<br>            .defaultSystem(&quot;You are a helpful assistant for data validation and transformation.&quot;)<br>            .build();<br>    }<br>}<br><br>// ===================================================================<br>// WORKFLOW EXECUTION LISTENER IMPLEMENTATIONS<br>// ===================================================================<br><br>@Component<br>class LoggingExecutionListener implements WorkflowExecutionListener {<br>    @Override<br>    public void onExecutionStart(WorkflowContext context) {<br>        System.out.println(String.format(&quot;[WORKFLOW START] %s (execution: %s)&quot;, <br>            context.getWorkflowId(), context.getExecutionId()));<br>    }<br><br>    @Override<br>    public void onStageStart(WorkflowContext context, Stage stage) {<br>        System.out.println(String.format(&quot;[STAGE START] %s -&gt; %s&quot;, <br>            context.getWorkflowId(), stage));<br>    }<br><br>    @Override<br>    public void onStageComplete(WorkflowContext context, Stage stage, AgentResult result) {<br>        System.out.println(String.format(&quot;[STAGE COMPLETE] %s -&gt; %s [%s]&quot;, <br>            context.getWorkflowId(), stage, result.getStatus()));<br>    }<br><br>    @Override<br>    public void onExecutionComplete(WorkflowContext context) {<br>        System.out.println(String.format(&quot;[WORKFLOW COMPLETE] %s -&gt; %s (duration: %d ms)&quot;, <br>            context.getWorkflowId(), context.getCurrentStage(), context.getDuration()));<br>    }<br>}<br><br>@Component<br>class MetricsExecutionListener implements WorkflowExecutionListener {<br>    private final Map&lt;String, Long&gt; stageDurations = new ConcurrentHashMap&lt;&gt;();<br>    private final Map&lt;String, Integer&gt; stageCounts = new ConcurrentHashMap&lt;&gt;();<br><br>    @Override<br>    public void onStageComplete(WorkflowContext context, Stage stage, AgentResult result) {<br>        String key = stage.name();<br>        stageCounts.put(key, stageCounts.getOrDefault(key, 0) + 1);<br>    }<br><br>    public Map&lt;String, Integer&gt; getStageCounts() {<br>        return new HashMap&lt;&gt;(stageCounts);<br>    }<br>}<br><br>// ===================================================================<br>// CONCRETE WORKFLOW ENGINE IMPLEMENTATION<br>// ===================================================================<br><br>@Service<br>class DefaultWorkflowEngine extends WorkflowEngine {<br>    <br>    @Autowired<br>    public DefaultWorkflowEngine(WorkflowOrchestrator orchestrator,<br>                                WorkflowDefinitionRepository definitionRepository,<br>                                WorkflowExecutionRepository executionRepository,<br>                                MongoTemplate mongoTemplate) {<br>        super(orchestrator, definitionRepository, executionRepository, mongoTemplate);<br>    }<br>}<br><br>// ===================================================================<br>// WORKFLOW SERVICE (Facade Pattern)<br>// ===================================================================<br><br>@Service<br>class WorkflowService {<br>    private final DefaultWorkflowEngine engine;<br>    private final WorkflowDefinitionRepository definitionRepository;<br>    private final WorkflowExecutionRepository executionRepository;<br><br>    @Autowired<br>    public WorkflowService(DefaultWorkflowEngine engine,<br>                          WorkflowDefinitionRepository definitionRepository,<br>                          WorkflowExecutionRepository executionRepository) {<br>        this.engine = engine;<br>        this.definitionRepository = definitionRepository;<br>        this.executionRepository = executionRepository;<br>    }<br><br>    public void executeWorkflow(String workflowId) {<br>        engine.run(workflowId);<br>    }<br><br>    public WorkflowDefinition createWorkflow(WorkflowDefinition definition) {<br>        definition.setCreatedAt(System.currentTimeMillis());<br>        definition.setUpdatedAt(System.currentTimeMillis());<br>        return definitionRepository.save(definition);<br>    }<br><br>    public WorkflowDefinition updateWorkflow(String workflowId, WorkflowDefinition definition) {<br>        WorkflowDefinition existing = definitionRepository.findByWorkflowId(workflowId)<br>            .orElseThrow(() -&gt; new WorkflowConfigurationException(<br>                &quot;Workflow not found: &quot; + workflowId, workflowId));<br>        <br>        existing.setName(definition.getName());<br>        existing.setDescription(definition.getDescription());<br>        existing.setStrategyMap(definition.getStrategyMap());<br>        existing.setConfiguration(definition.getConfiguration());<br>        existing.setActive(definition.isActive());<br>        existing.setUpdatedAt(System.currentTimeMillis());<br>        <br>        return definitionRepository.save(existing);<br>    }<br><br>    public Optional&lt;WorkflowExecution&gt; getExecution(String executionId) {<br>        return executionRepository.findByExecutionId(executionId);<br>    }<br><br>    public List&lt;WorkflowExecution&gt; getExecutions(String workflowId) {<br>        return executionRepository.findByWorkflowId(workflowId);<br>    }<br>}<br><br>// ===================================================================<br>// REST CONTROLLER (Optional - for API access)<br>// ===================================================================<br><br>@RestController<br>@RequestMapping(&quot;/api/workflows&quot;)<br>class WorkflowController {<br>    private final WorkflowService workflowService;<br><br>    @Autowired<br>    public WorkflowController(WorkflowService workflowService) {<br>        this.workflowService = workflowService;<br>    }<br><br>    @PostMapping(&quot;/{workflowId}/execute&quot;)<br>    public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; executeWorkflow(@PathVariable String workflowId) {<br>        try {<br>            workflowService.executeWorkflow(workflowId);<br>            return ResponseEntity.ok(Map.of(&quot;status&quot;, &quot;success&quot;, &quot;workflowId&quot;, workflowId));<br>        } catch (Exception e) {<br>            return ResponseEntity.status(500)<br>                .body(Map.of(&quot;status&quot;, &quot;error&quot;, &quot;message&quot;, e.getMessage()));<br>        }<br>    }<br><br>    @PostMapping<br>    public ResponseEntity&lt;WorkflowDefinition&gt; createWorkflow(@RequestBody WorkflowDefinition definition) {<br>        return ResponseEntity.ok(workflowService.createWorkflow(definition));<br>    }<br><br>    @GetMapping(&quot;/executions/{executionId}&quot;)<br>    public ResponseEntity&lt;WorkflowExecution&gt; getExecution(@PathVariable String executionId) {<br>        return workflowService.getExecution(executionId)<br>            .map(ResponseEntity::ok)<br>            .orElse(ResponseEntity.notFound().build());<br>    }<br>}<br><br>// ===================================================================<br>// END OF FRAMEWORK<br>// ===================================================================<br><br></pre><p><strong>A truly future-ready workflow framework isn’t about code it’s about orchestrating behavior, enforcing design, and letting agents do the work.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55d84a7f1f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Application Scaling from Single Server to Global Architecture]]></title>
            <link>https://medium.com/@akshat.available/system-design-application-scaling-from-single-server-to-global-architecture-1bd396b666bc?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd396b666bc</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 10:00:45 GMT</pubDate>
            <atom:updated>2025-08-26T10:00:45.650Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog walks through the journey of scaling a web application from a simple single-server setup to a globally distributed architecture serving millions of users. We’ll start with the core limitations of a monolithic design and progressively introduce load balancers, caching, replication, CDNs, stateless authentication, and multi-region deployment. Each step addresses a real-world bottleneck, helping architects design resilient, high-performance systems at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbykVfI8LPmncjPd8QaugA.png" /></figure><p>When you first looked at the final architecture diagram, it felt overwhelming so many layers, so many “fancy” components stacked together. But you didn’t want to just accept it blindly or build something over-engineered from day one. You wanted to <strong>understand the process</strong> of how such an architecture actually forms.</p><p>So instead of jumping straight to the end state, I broke it down step by step starting with a single server and gradually adding each layer only when the system demanded it. A database for persistence, a load balancer for distribution, replication for scale, Redis for performance, a CDN for speed, stateless sessions for elasticity, multi-region for resilience, and observability for control. This blog is that journey a clear walkthrough of <strong>when, where, and why</strong> each piece fits in, until the complex finally feels simple.</p><h3>Problem Statement: Why Scaling Beyond a Single Server Matters</h3><blockquote>In today’s digital landscape, applications face highly dynamic and often unpredictable user demand. While beginning with a simple monolithic server is practical for initial development, this approach quickly reveals fundamental shortcomings as usage grows. A single server handles all responsibilities serving web requests, running business logic, and managing data storage so any failure leads to complete downtime and a poor user experience.</blockquote><blockquote>As demand increases, resource bottlenecks surface CPU, memory, and network capacity are quickly exhausted under heavy registrations, queries, or spikes in traffic. Because the system cannot scale horizontally, adding capacity is not straightforward. Latency also grows for users further from the server’s location, with no resilience against regional outages. On top of this, storing sessions, caches, and the database state on one machine tightly couples every component, making it difficult to scale parts independently or recover gracefully from partial failures. These limitations make the single-server design unsuitable for scaling to millions of users.</blockquote><h3>Solution:</h3><blockquote>To address these challenges, the architecture must evolve step by step beyond the single-server model. This starts with introducing a dedicated database for persistence, followed by load balancers to distribute requests across multiple web servers, and database replication to separate reads from writes. Caching layers and CDNs are then added to improve performance, reduce latency, and offload pressure from the origin servers.</blockquote><blockquote>The system further scales by adopting stateless authentication (e.g., Azure AD with JWTs) so that user sessions are not tied to individual servers, and by replicating the entire stack across multiple data centers to achieve geo-resilience and global availability. Finally, observability tools monitoring, logging, and metrics ensure the complex ecosystem can be managed effectively. Together, these enhancements transform a fragile setup into a robust, globally scalable architecture capable of serving millions of users.</blockquote><h3>Step 1: Single Server Setup</h3><blockquote>We start with the simplest setup, one web server (monolithic) that handles all traffic. In this design, the domain name’s DNS record points to a single IP address, so every user request hits that one machine. For example, a user visits <em>example.com</em>, DNS resolves to the server’s IP, and that server processes the request (serving HTML, running application logic, etc.). This basic architecture works for very small loads, but it has serious limitations. With no redundancy, the server is a single point of failure if it crashes or needs maintenance, the entire site is down. It also cannot scale well under high load a sudden traffic spike or viral campaign can <strong>crash the site</strong> if the server is overwhelmed . In fact, a non-scalable single-server design “can become a bottleneck, hindering growth” and will <strong>fail to serve millions of users</strong> . There’s also no way to distribute load or improve latency geographically. In short, a single-server web app quickly hits resource limits (CPU, memory, I/O) and makes high availability impossible.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*QGIDbl1NFV5Auq6n26D-jQ.png" /></figure><h3>Step 2: Database Introduction</h3><blockquote>Next, we add a dedicated database backend for persistent data. The web server continues to handle incoming HTTP requests, but all data (user profiles, content, state) is stored in a database. Initially this might still be on the same machine or on a separate VM/instance. This separation ensures data durability and ACID consistency, which a basic file-based or in-memory system could not guarantee. However, <strong>one database is still a single point of failure</strong> if it goes down or runs out of capacity, the entire application stalls. As usage grows, the data volume will explode, and even a large single database “can’t handle” arbitrarily large load forever. In practice, you often start with a single RDBMS (or NoSQL store) and plan for future scaling. Even at this stage, it’s wise to think about data partitioning or sharding. For example, you might design your schema so that users can later be split by region or ID range . The database will eventually be replicated or sharded (in a later step), but for now it serves as the single source of truth for the app.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*MuBwkr_4Icyvu3UrZFtt4g.png" /></figure><h3>Step 3: Load Balancer Setup</h3><blockquote>To support more traffic, we duplicate the web tier and introduce a load balancer. The DNS entry now points to the load balancer (instead of one server), and the load balancer distributes incoming HTTP requests across multiple identical web server instances. These servers run the same application code and connect to the database. This horizontal scaling means no single web server becomes a bottleneck “load balancers evenly distribute incoming traffic across your servers to prevent any one server from getting overwhelmed”. In practice, you might use an AWS Elastic Load Balancer, Azure Load Balancer, or an Nginx/HAProxy cluster. Health checks ensure that if a server instance fails, the balancer stops sending traffic to it. Now the system can grow by adding more servers behind the balancer. Note that the database remains a single write-master (for now), so the database may become the next bottleneck. But the web layer is now <strong>stateless and elastic </strong>you can scale it out to match demand, providing both higher throughput and redundancy.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*WzV0oBEzFOdHCG3K8uR83g.png" /></figure><h3>Step 4: Database Replication</h3><blockquote>With multiple web servers, the single master database may struggle under read and write load. The next step is to replicate the database. We configure a master (primary) database that accepts all writes, and one or more read-only replicas (slaves). The primary asynchronously pushes changes to each replica. All user sessions or writes go to the master, while read-heavy operations (SELECTs, analytics, reporting) are directed to the replicas. This read/write separation greatly reduces load on the master. For example, Amazon RDS allows creating read replicas: “A read replica is a read-only copy of a DB instance. You can reduce the load on your primary DB instance by routing queries… to the read replica. In this way, you can elastically scale out beyond the capacity constraints of a single DB instance” . In AWS, the RDS service asynchronously copies updates to replicas in another AZ or region . Azure and other cloud databases offer similar features (readable secondary databases or geo-replication). After this step, most user reads (page loads, queries) are served by one of the replicas, while only writes hit the master. This provides both <strong>higher read throughput</strong> and some fault tolerance if a replica fails, others can pick up the load, and a replica can even be promoted to master in a failure scenario.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*PfuNfyRhTHRF6fATpQotGQ.png" /></figure><h3>Step 5: Cache Layer</h3><blockquote>Even with replicated databases, many requests involve data that doesn’t change often (e.g. user profiles, popular queries). We add a distributed cache (e.g. Redis or Memcached) between the web servers and the database. When a server needs some data, it first checks the cache if the data is present (cache hit), it returns it from memory if not, it loads from the database and stores it in the cache for future use. Caching dramatically improves read performance. For instance, Redis is an in-memory store capable of <strong>sub-millisecond response times</strong>, so data that otherwise required a DB trip can be served much faster. As one example notes, in-memory caching “stores frequently accessed data in memory, so your system doesn’t have to fetch the same data from the database repeatedly”. Common things to cache include rendered HTML fragments, query results, session tokens, or any data read by many users. The trade-off is complexity, you must manage cache invalidation (through TTLs or explicit refresh) to keep data consistent. But overall, a caching layer <strong>offloads repetitive reads</strong> from the database and greatly reduces load, especially under high concurrency.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Db8tWlPFnc8GV_NChBWA1A.png" /></figure><h3>Step 6: CDN Integration</h3><blockquote>Static assets images, CSS, JavaScript files, videos can still create load and latency if served from your origin servers. To optimise global delivery, we introduce a Content Delivery Network (CDN). A CDN is a globally distributed network of edge servers that cache static (and some dynamic) content close to users. When a browser requests a static file, it is fetched from the nearest edge node rather than the origin server. This drastically lowers latency and bandwidth costs. Azure’s guidance explains that CDNs “store cached content on edge servers that are close to end users to minimize latency… lower latency and faster delivery of content to users, regardless of their geographical location”. Another advantage is reduced origin load, since the CDN handles the bulk of static file delivery, your web servers focus only on dynamic requests. As noted, CDNs can “help to reduce load on a web application, because the application does not have to service requests for content that is hosted in the CDN”. In practice, we configure our asset URLs (or a CDN endpoint) so that browsers automatically pull images and scripts from the CDN (e.g. Azure CDN, AWS CloudFront, or Cloudflare). This results in faster page loads for users worldwide and lower traffic on our own servers.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*FuS3q0Z9Fv6D2W6RmjvKLQ.png" /></figure><h3>Step 7: Stateless Authentication Architecture</h3><blockquote>To support truly scalable web servers, we must make the application stateless. We integrate an external identity provider (Azure Active Directory) so that servers don’t hold any user session in memory. In this design, when a user signs in, Azure AD issues a signed token (typically an OAuth2 access token or OpenID Connect ID token) that encodes the user’s identity and claims. These are JSON Web Tokens (JWTs) containing all needed session information . On each request, the application servers validate the token and extract user info locally. No server needs to store the session or know any “current state” the token itself is the state. This has major scalability benefits, as one source explains, “tokens, like JWTs, are self-contained and don’t need a central store… This makes the system simpler”. Each stateless server can handle any authenticated request, allowing independent horizontal scaling. In practice we use Azure AD (Microsoft Entra) with OpenID Connect, each token is checked against the Azure AD signing keys. Because there is no sticky session, any web instance in any region can serve the request. As Dev Cookies notes, this stateless design “allows servers to process requests independently of one another, making it easier to horizontally scale your system”. The result is a scalable auth system, servers trust Azure AD’s tokens and do not need to communicate with each other about sessions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*hI69aCKImdP_DLTdWYezmw.png" /></figure><h3>Step 8: Multi-Region Deployment</h3><blockquote>To achieve global scale and high availability, we replicate the entire architecture into a second (and more) geographic region. In this stage, we duplicate the web servers, caches, and databases in another data center or cloud region. We then use DNS-based or global load balancing to direct users to the nearest healthy region. For example, Azure Traffic Manager or AWS Route 53 (with latency-based routing) can resolve the app’s domain to endpoints in Region A or B. This multi-region architecture ensures that even a critical failure regional outage won’t take the service down, “By deploying an application across multiple regions, we can minimize the impact of natural disasters, regional outages, or infrastructure failures… If one region becomes unavailable, traffic is automatically routed to the functioning regions, reducing or fully avoiding downtime”. In each region, the stack looks like our Step 7 setup. Data consistency across regions must be handled for example using a globally distributed database (such as Azure Cosmos DB or AWS DynamoDB global tables) or active-passive replication. Microsoft’s guidance suggests using a “globally distributed data store” or read-only replicas for relational data in multi-region designs. In practice, you might write mostly to one region and asynchronously replicate to the other(s). The key benefit is resilience, users get lower latency (served from the closest region) and the system survives a regional failure. As a multi-region architecture “distributes multiple instances of an application and its database across cloud provider regions… ensuring the highest availability possible”. This completes the journey from a single-server monolith to a robust, multi-region infrastructure that can serve millions of global users.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbP-JPLNi5h1B_yXbSnmmw.png" /></figure><h3>Step 9: Observability Tools</h3><blockquote>With this scale of architecture, monitoring and troubleshooting become critical. We integrate comprehensive observability tools across all components. Centralized logging aggregates logs from all web servers, databases, and networking devices (using tools like the ELK/EFK stack, Splunk, or cloud logging services). Metrics are collected (e.g. request rates, error rates, latencies, CPU/memory usage) using systems like Prometheus, Grafana, Azure Monitor or Datadog. In a modern observability practice, you rely on the “three pillars” of logs, metrics, and traces . For example, you might emit traces (via OpenTelemetry, Zipkin, or Jaeger) to follow a user request across services. Monitoring tools (Prometheus, Grafana, New Relic, etc.) then track these metrics and send alerts when thresholds are crossed “alert you when something goes wrong”. Dashboards show real-time health (e.g. cache hit ratios, DB replication lag, request latency percentiles). This step doesn’t change the architecture diagram, but it ensures the architecture can be operated at scale. Proper monitoring and alerts allow you to <strong>detect anomalies</strong> (saturation, errors, slowdowns) early and debug issues before they impact users. In short, integrating logging, metrics, and tracing completes the platform, giving system architects the visibility needed to maintain performance and reliability.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXjnInIehOP5B_xMa-gnug.png" /></figure><p><em>Scaling an application isn’t about throwing all the components in from day one it’s about evolving the architecture step by step as the system demands it. Each layer addressed a real bottleneck, transforming complexity into clarity.</em></p><p><strong><em>But the journey doesn’t stop here. As applications continue to grow, architects extend this foundation with API Gateways for managing traffic, service meshes for inter-service communication, infrastructure as code for consistency, network segmentation for resilience, security and compliance frameworks for protection, and DevOps automation for faster delivery. Every new layer is driven by scale, reliability, and trust.</em></strong></p><h4><em>Great architectures aren’t built overnight they are earned in production, one problem at a time, until what once felt complex becomes the new normal…</em></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd396b666bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Event-Driven Architecture with Kafka, WebSockets and React]]></title>
            <link>https://medium.com/@akshat.available/real-time-event-driven-architecture-with-kafka-websockets-and-react-b4698361e68a?source=rss-e18b6b8712fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4698361e68a</guid>
            <category><![CDATA[java-to-react]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[kafka-to-websocket]]></category>
            <category><![CDATA[client-to-server]]></category>
            <dc:creator><![CDATA[Akshat Vashishtha]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 16:16:30 GMT</pubDate>
            <atom:updated>2025-05-18T06:13:17.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SF2yBNye7qfKV65oxAWxeQ.png" /></figure><blockquote><strong>Reference System:</strong> The architecture follows an event-driven and microservices-based approach designed for data ingestion, aggregation, and real-time streaming. It consists of two main components: DataIngestor and DataAggregator.</blockquote><blockquote><strong>DataIngestor </strong>is responsible for ingesting data from external systems such as Order, Payment, Dispatch, and Products. It queries data sources through APIs, using specialized REST clients that periodically poll data. The ingested data is persisted in an in-memory cache, where it undergoes a state comparison to detect changes. If any differences are found between the new and cached states, an event is triggered and published to Kafka topics through the Event Producer.</blockquote><blockquote><strong>DataAggregator</strong> focuses on aggregating event streams and providing real-time data updates. It consumes data change events from Kafka topics, aggregates the streams, and generates delta updates. These updates are processed through an Event State Aggregator to maintain consistency. The aggregated data is then stored and compared with the cached state to ensure accurate representation. Real-time updates are communicated to the client using WebSocket, facilitated by components such as the WebSocket Handler, Registry, and Endpoint.</blockquote><blockquote>The architecture is event-driven and resilient, leveraging caching and real-time communication for efficient and consistent data processing while maintaining modularity for scalability and ease of maintenance.</blockquote><p><strong><em>To Keep It Simple Stupid, let’s make it simple by using below use case.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xg_oQUjcImIjSauQrUKR8Q.png" /></figure><blockquote><strong>The architecture enables real-time server-to-client communication using Kafka and WebSockets for event-driven data streaming. The backend ingests data through a scheduler, pushing updates to a Kafka producer, which streams events to a consumer for processing. The middleware handles real-time distribution via a WebSocket handler, registry, and endpoint, ensuring efficient client subscriptions. On the frontend, a WebSocket event listener processes incoming events, dynamically updating the UI. This setup ensures low-latency, scalable, and reactive data delivery for a seamless real-time experience.</strong></blockquote><h3>Problem Statement</h3><p>Traditional client-server models rely on polling, leading to delays and unnecessary resource usage. For real-time applications like live dashboards and monitoring systems, instant data updates are crucial.</p><h3>Solution</h3><p><strong>Kafka</strong> plays a key role in solving these challenges by acting as the backbone of real-time event streaming. <strong>You can refer to my previous blogs to understand Kafka in depth</strong>. Here, the focus is on high-level system integration — how different components work together to achieve real-time communication. <strong>I will share the codebase, but this blog is more about integrating the system rather than writing code</strong>. Once you understand the architecture, implementing it becomes much easier.</p><h3><strong>Step-by-Step Solution:</strong></h3><p>To achieve real-time server-to-client communication, we will solve the problem in three key layers: <strong>backend, middleware, and frontend</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*dsxXc16c-MZIxguWvXnu9w.png" /><figcaption><strong>Backend Package Structure</strong></figcaption></figure><h4><strong>Backend — Data Ingestion &amp; Scheduling:</strong></h4><p>The backend is responsible for fetching data from an external source. In this case, it interacts with an API, but the data source could also be a database, a third-party service, or any other system. A <strong>scheduler service</strong> periodically retrieves this data, enabling non-Kafka systems to integrate with Kafka. This is crucial for legacy systems that store historical data in traditional storage formats. To demonstrate, I have used <strong>sample crew data</strong> and posted it on a <strong>mock API</strong> for reference. The data remains flat and structured for simplicity.</p><p><a href="https://run.mocky.io/v3/5c1e0136-2f66-4f16-8584-4c2b5aa8ec3c"><strong>https://run.mocky.io/v3/5c1e0136-2f66-4f16-8584-4c2b5aa8ec3c</strong></a></p><p><strong>There is a possibility that this API may become unavailable after some time. Therefore, you can refer to the JSON response below as a reference.</strong></p><pre>[<br>{<br>  &quot;crewId&quot;: &quot;C12345&quot;,<br>  &quot;onTimePerformance&quot;: 85,<br>  &quot;flightHours&quot;: 1200,<br>  &quot;aircraftType&quot;: &quot;320/321&quot;,<br>  &quot;openTripsFD&quot;: 5,<br>  &quot;unpairedLegsFD&quot;: 3,<br>  &quot;standbyAvailableFD&quot;: 2,<br>  &quot;openTripsCC&quot;: 4,<br>  &quot;unpairedLegsCC&quot;: 2,<br>  &quot;standbyAvailableCC&quot;: 1,<br>  &quot;unfinalizedRoutes&quot;: 6,<br>  &quot;timeInterval&quot;: &quot;0-3&quot;<br>}<br>]</pre><p>Model Class for above JSON</p><pre>package com.learning.model;<br><br>import lombok.*;<br>import lombok.Data;<br><br>/**<br> * Crew Metric Model<br> */<br><br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class CrewMetric {<br>    private String crewId;<br>    private int onTimePerformance;<br>    private int flightHours;<br>    private String aircraftType; <br>    private int openTripsFD;<br>    private int unpairedLegsFD;<br>    private int standbyAvailableFD;<br>    private int openTripsCC;<br>    private int unpairedLegsCC;<br>    private int standbyAvailableCC;<br>    private int unfinalizedRoutes;<br>    private String timeInterval;<br><br>    @Override<br>    public String toString() {<br>        return &quot;CrewMetric{&quot; +<br>                &quot;crewId=&#39;&quot; + crewId + &#39;\&#39;&#39; +<br>                &quot;, onTimePerformance=&quot; + onTimePerformance +<br>                &quot;, flightHours=&quot; + flightHours +<br>                &quot;, aircraftType=&#39;&quot; + aircraftType + &#39;\&#39;&#39; +<br>                &quot;, openTripsFD=&quot; + openTripsFD +<br>                &quot;, unpairedLegsFD=&quot; + unpairedLegsFD +<br>                &quot;, standbyAvailableFD=&quot; + standbyAvailableFD +<br>                &quot;, openTripsCC=&quot; + openTripsCC +<br>                &quot;, unpairedLegsCC=&quot; + unpairedLegsCC +<br>                &quot;, standbyAvailableCC=&quot; + standbyAvailableCC +<br>                &quot;, unfinalizedRoutes=&quot; + unfinalizedRoutes +<br>                &quot;, timeInterval=&#39;&quot; + timeInterval + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>You can refer to the following pom.xml dependencies, which will help you with integrating <strong>WebFlux, Kafka, Lombok, and WebSockets</strong> in your Spring Boot project:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>   xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br> &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br> &lt;parent&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>  &lt;version&gt;3.4.4&lt;/version&gt;<br>  &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;<br> &lt;/parent&gt;<br> &lt;groupId&gt;com.learning&lt;/groupId&gt;<br> &lt;artifactId&gt;demo&lt;/artifactId&gt;<br> &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br> &lt;name&gt;demo&lt;/name&gt;<br> &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;<br> &lt;url/&gt;<br> &lt;licenses&gt;<br>  &lt;license/&gt;<br> &lt;/licenses&gt;<br> &lt;developers&gt;<br>  &lt;developer/&gt;<br> &lt;/developers&gt;<br> &lt;scm&gt;<br>  &lt;connection/&gt;<br>  &lt;developerConnection/&gt;<br>  &lt;tag/&gt;<br>  &lt;url/&gt;<br> &lt;/scm&gt;<br> &lt;properties&gt;<br>  &lt;java.version&gt;21&lt;/java.version&gt;<br> &lt;/properties&gt;<br> &lt;dependencies&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-websocket&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.projectreactor&lt;/groupId&gt;<br>   &lt;artifactId&gt;reactor-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-kafka-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br><br> &lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>     &lt;annotationProcessorPaths&gt;<br>      &lt;path&gt;<br>       &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>       &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;/path&gt;<br>     &lt;/annotationProcessorPaths&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>     &lt;excludes&gt;<br>      &lt;exclude&gt;<br>       &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>       &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;/exclude&gt;<br>     &lt;/excludes&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br> &lt;/build&gt;<br><br>&lt;/project&gt;</pre><h4>Calling Data Source API for Data Ingestion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*tfZyyrHnaTcjj6E0eDI60A.png" /></figure><p>The <strong>CrewMetricService</strong> leverages Spring WebFlux’s <strong>WebClient</strong> to asynchronously fetch crew metric data from an external API. The WebClientConfig class defines a reusable WebClient bean with a base URL pointing to the mock API. The service method getCrewMetrics() performs a non-blocking GET request to the specified API endpoint, retrieving the data as a <strong>Mono</strong> of CrewMetric[]. This ensures efficient, reactive data ingestion, making the system scalable and responsive for real-time applications.</p><pre>// Reactive Web client class<br><br>package com.learning.config;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.reactive.function.client.WebClient;<br><br>@Configuration<br>public class WebClientConfig {<br><br>    @Bean<br>    public WebClient webClient() {<br>        return WebClient.builder().baseUrl(&quot;https://run.mocky.io&quot;).build();<br>    }<br>}<br><br>// Service class<br><br>package com.learning.service;<br><br>import com.learning.model.CrewMetric;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.reactive.function.client.WebClient;<br>import reactor.core.publisher.Mono;<br><br>@Service<br>public class CrewMetricService {<br><br>    private final WebClient webClient;<br><br>    @Autowired<br>    public CrewMetricService(WebClient webClient) {<br>        this.webClient = webClient;<br>    }<br><br>    public Mono&lt;CrewMetric[]&gt; getCrewMetrics() {<br>        return webClient.get()<br>                .uri(&quot;v3/5c1e0136-2f66-4f16-8584-4c2b5aa8ec3c&quot;)<br>                .retrieve()<br>                .bodyToMono(CrewMetric[].class);<br>    }<br>}</pre><h4><strong>Scheduler Service for Kafka Integration</strong></h4><p>The <strong>SchedulerService</strong> acts as a bridge between non-Kafka systems and Kafka by periodically fetching crew metric data from an external API. Using <strong>Spring’s @Scheduled annotation</strong>, it runs every <strong>30 seconds</strong>, retrieving data via the CrewMetricService. The fetched data is then transformed into <strong>Kafka events</strong> using the EventTransformer and published to Kafka through the EventProvider. This enables seamless integration of legacy or non-Kafka systems with a real-time event-driven architecture. <strong>Note:</strong> Make sure you use @EnableScheduling in your main application class to enable scheduler.</p><pre>package com.learning;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.scheduling.annotation.EnableScheduling;<br><br>@EnableScheduling<br>@SpringBootApplication<br>public class DemoApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(DemoApplication.class, args);<br> }<br><br>}</pre><pre>package com.learning.service;<br><br>import com.learning.design.Scheduler;<br>import com.learning.kafka.EventProvider;<br>import com.learning.model.CrewMetric;<br>import com.learning.model.CrewResponse;<br>import com.learning.model.Event;<br>import com.learning.transform.EventTransformer;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.scheduling.annotation.Scheduled;<br>import org.springframework.stereotype.Service;<br>import reactor.core.publisher.Mono;<br><br>import java.time.LocalDateTime;<br><br>@Service<br>public class SchedulerService implements Scheduler {<br><br>    private final EventProvider eventProvider;<br><br>    @Autowired<br>    private CrewMetricService crewMetricService;<br>    @Autowired<br>    private EventTransformer transformer;<br><br>    public SchedulerService(EventProvider eventProvider) {<br>        this.eventProvider = eventProvider;<br>    }<br><br>    @Override<br>    @Scheduled(fixedRate = 30000) // 30 seconds interval<br>    public void scheduleTask() {<br>        // Example event data<br>        System.out.println(&quot;Scheduler task executed starts :: &quot; + LocalDateTime.now());<br>        generateCrewMetric();<br>        System.out.println(&quot;Scheduler task executed ends :: &quot; + LocalDateTime.now());<br>    }<br><br>    private void generateCrewMetric() {<br>        Mono&lt;CrewMetric[]&gt; crewMetricsMono = crewMetricService.getCrewMetrics();<br>        CrewMetric[] crewMetrics = crewMetricsMono.block(); // Blocking for simplicity in this example<br><br>        if (crewMetrics != null) {<br>            for (CrewMetric crewMetric : crewMetrics) {<br>                Event event = transformer.transform(crewMetric);<br>                eventProvider.produce(event);<br>            }<br>            System.out.println(&quot;Event produced  :: &quot; + crewMetrics.length);<br>        } else {<br>            System.out.println(&quot;No crew metrics found.&quot;);<br>        }<br>    }<br>}</pre><pre>package com.learning.transform;<br><br>import com.learning.model.CrewMetric;<br>import com.learning.model.Event;<br>import org.springframework.stereotype.Component;<br><br>import java.time.LocalDateTime;<br><br>@Component<br>public class EventTransformer {<br><br>    public Event transform(CrewMetric crewMetric) {<br>        return new Event(<br>                &quot;defaultId&quot;,<br>                &quot;CrewMetricEvent&quot;,<br>                crewMetric.toString(),<br>                LocalDateTime.now(),<br>                &quot;CrewMetricSource&quot;,<br>                &quot;defaultStatus&quot;,<br>                crewMetric<br>        );<br>    }<br>}</pre><pre>package com.learning.model;<br><br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br>import lombok.AllArgsConstructor;<br>import java.time.LocalDateTime;<br><br>/**<br> * Event Model<br> */<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class Event {<br>    private String eventId;<br>    private String eventType;<br>    private String eventData;<br>    private LocalDateTime eventProduceTime;<br>    private String eventSource;<br>    private String eventStatus;<br>    private CrewMetric crewMetric;<br><br>    public Event(CrewMetric crewMetric) {<br>        this.eventId = &quot;defaultId&quot;;<br>        this.eventType = &quot;defaultType&quot;;<br>        this.eventData = &quot;defaultData&quot;;<br>        this.eventProduceTime = LocalDateTime.now();<br>        this.eventSource = &quot;defaultSource&quot;;<br>        this.eventStatus = &quot;defaultStatus&quot;;<br>        this.crewMetric = crewMetric;<br>    }<br>}</pre><h4>Middleware — Kafka &amp; WebSocket Integration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EELEuufD2O0kGS70nS91g.png" /></figure><h4><strong>1. Kafka Integration (Producer &amp; Consumer)</strong></h4><p>Once the scheduler fetches the data, it is sent to a <strong>Kafka producer</strong> which publishes the data to a Kafka topic. This Kafka topic serves as a message stream that can be consumed by different systems or components. The <strong>Kafka consumer</strong> listens to this topic, processes the events, and handles the data in real-time. This event-driven architecture ensures that data is streamed efficiently and asynchronously, facilitating seamless integration between traditional systems and modern real-time architectures. For simplicity I have written both producer and consumer in same project, but in real system these are two different micro-services with SSL configurations, and instead on traditional Kafka it can be Kafka streams.</p><pre>server:<br>  port: 8080<br>spring:<br>  kafka:<br>    bootstrap-servers: localhost:29092<br>    producer:<br>      acks: 1<br>      batch-size: 64000<br>      compression-type: snappy<br>      key-serializer: org.apache.kafka.common.serialization.StringSerializer<br>      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer<br>      properties:<br>        delivery.timeout.ms: 180000<br>        request.timeout.ms: 120000<br>        linger.ms: 10<br>    consumer:<br>          auto-offset-reset: earliest<br>          key-deserializer: org.apache.kafka.common.serialization.StringDeserializer<br>          value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer<br>          properties:<br>            spring.json.trusted.packages: com.learning.model</pre><pre>package com.learning.kafka;<br><br>import com.learning.model.Event;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.kafka.core.KafkaTemplate;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class EventProvider {<br>    private final KafkaTemplate&lt;String, Event&gt; kafkaTemplate;<br>    private static final String TOPIC = &quot;crew_metrics&quot;;<br><br>    @Autowired<br>    public EventProvider(KafkaTemplate&lt;String, Event&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }<br><br>    public void produce(Event event) {<br>        //System.out.println(&quot;Producing Event: &quot; + event);<br>        kafkaTemplate.send(TOPIC, event);<br>    }<br>}</pre><pre>package com.learning.kafka;<br><br>import com.learning.model.CrewMetric;<br>import com.learning.model.Event;<br>import com.learning.websocket.WebSocketHandler;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.kafka.annotation.KafkaListener;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>@RequiredArgsConstructor<br>public class EventHandler {<br><br>    private final WebSocketHandler webSocketHandler;<br><br>    @KafkaListener(topics = &quot;crew_metrics&quot;, groupId = &quot;test_group&quot;)<br>    public void handle(Event event) {<br>        System.out.println(&quot;Handling Event: &quot; + event);<br>        CrewMetric crewMetric = event.getCrewMetric();<br>        webSocket(crewMetric);<br>        //<br>    }<br><br>    void webSocket(CrewMetric crewMetric ) {<br>        webSocketHandler.sendMessage(crewMetric);<br>    }<br><br>}</pre><h4><strong>2. WebSocket Integration</strong></h4><p>The <strong>WebSocketHandler</strong> class manages real-time communication between the server and clients using WebSockets. It establishes and maintains a <strong>WebSocket session</strong>, ensuring that clients receive live updates. When a new connection is established, it stores the session and logs the event. If the connection closes, it resets the session reference. The <strong>sendMessage</strong> method serializes a <strong>CrewMetric</strong> object into JSON and sends it as a <strong>WebSocket message</strong> to the connected client, ensuring real-time data delivery. The handler also performs checks to ensure messages are only sent when the session is active, preventing unnecessary errors.</p><pre>package com.learning.websocket;<br><br>import com.learning.model.CrewMetric;<br>import com.learning.utils.Mapper;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Component;<br><br>import org.springframework.web.socket.TextMessage;<br>import org.springframework.web.socket.WebSocketSession;<br>import org.springframework.web.socket.CloseStatus;<br>import org.springframework.web.socket.handler.AbstractWebSocketHandler;<br><br>import java.io.IOException;<br><br>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class WebSocketHandler extends AbstractWebSocketHandler {<br><br>    private WebSocketSession session;<br>    private final Mapper mapper;<br><br>    @Override<br>    public void afterConnectionEstablished(WebSocketSession session) throws Exception {<br>        // Handle the connection established event<br>        // You can write a handshake logic while connect it may be load initial data<br>        log.info(&quot;WebSocket connection established: {}&quot;, session.getId());<br>        this.session = session;<br>    }<br><br>    @Override<br>    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {<br>        // Handle the connection closed event<br>        this.session = null;<br>        log.info(&quot;WebSocket connection closed: {} with status {}&quot;, session.getId(), status);<br>    }<br><br>    public void sendMessage(CrewMetric crewMetric) {<br>        if (session != null &amp;&amp; session.isOpen()) {<br>            try {<br>                String message = mapper.convertObjectToString(crewMetric);<br>                if (message!= null) {<br>                    session.sendMessage(new TextMessage(message));<br>                }<br>            } catch (IOException e) {<br>                log.error(&quot;Error sending message: {}&quot;, e.getMessage());<br>            }<br>        } else {<br>            log.warn(&quot;WebSocket session is not open. Cannot send message.&quot;);<br>        }<br>    }<br>}</pre><pre>package com.learning.utils;<br><br>import com.fasterxml.jackson.core.JsonProcessingException;<br>import com.fasterxml.jackson.databind.DeserializationFeature;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;<br>import org.springframework.stereotype.Component;<br>import com.fasterxml.jackson.databind.SerializationFeature;<br><br>@Component<br>public class Mapper {<br><br>    private final ObjectMapper objectMapper = new ObjectMapper();{<br>        objectMapper.registerModule(new JavaTimeModule());<br>        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);<br>        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);<br>    }<br><br>    public String convertObjectToString(Object obj) throws JsonProcessingException {<br>        if (obj == null) return null;<br>        try {<br>            return objectMapper.writeValueAsString(obj);<br>        } catch (Exception e) {<br>            return null;<br>        }<br>    }<br>}</pre><p>The WebSocketRegistry configures a WebSocket endpoint (/crew-metrics), allowing React clients to establish a real-time connection and receive live crew metric updates.</p><pre>package com.learning.config;<br><br>import com.learning.websocket.WebSocketHandler;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.socket.config.annotation.EnableWebSocket;<br>import org.springframework.web.socket.config.annotation.WebSocketConfigurer;<br>import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;<br><br>@Configuration<br>@EnableWebSocket<br>@RequiredArgsConstructor<br>public class WebSocketRegistry implements WebSocketConfigurer {<br><br>    private final WebSocketHandler webSocketHandler;<br><br>    @Override<br>    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {<br><br>        registry.addHandler(webSocketHandler, &quot;/crew-metrics&quot;).setAllowedOrigins(&quot;*&quot;);<br>        // Add more handlers as needed<br><br>    }<br>}</pre><h4><strong>Frontend — Real-Time Updates</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*UfwMAItb2pngBaqOZHto6A.png" /></figure><blockquote><strong>In the frontend, a WebSocket connection is established with the backend to receive real-time updates. Instead of relying on traditional polling mechanisms, which frequently request data and cause unnecessary server load, the WebSocket event listener remains active, continuously receiving new updates as soon as they are available.</strong></blockquote><blockquote><strong>When an event is received, the frontend dynamically updates the UI without requiring a manual refresh, ensuring a seamless and highly responsive user experience. This event-driven approach is particularly useful for real-time dashboards, live monitoring systems, and any application that requires instant data updates.</strong></blockquote><p>This <strong>package.json</strong> sets up a React project with TypeScript and Vite, including WebSocket support. It uses React 19 for UI, React Router DOM (optional) for routing, and react-use-websocket for real-time updates. The setup includes ESLint for linting, TypeScript for static typing, and Vite for fast builds.</p><pre>{<br>  &quot;name&quot;: &quot;learning&quot;,<br>  &quot;private&quot;: true,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;tsc -b &amp;&amp; vite build&quot;,<br>    &quot;lint&quot;: &quot;eslint .&quot;,<br>    &quot;preview&quot;: &quot;vite preview&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;react&quot;: &quot;^19.0.0&quot;,<br>    &quot;react-dom&quot;: &quot;^19.0.0&quot;,<br>    &quot;react-router-dom&quot;: &quot;^7.4.1&quot;,<br>    &quot;react-use-websocket&quot;: &quot;^4.13.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@eslint/js&quot;: &quot;^9.21.0&quot;,<br>    &quot;@types/react&quot;: &quot;^19.0.10&quot;,<br>    &quot;@types/react-dom&quot;: &quot;^19.0.4&quot;,<br>    &quot;@vitejs/plugin-react&quot;: &quot;^4.3.4&quot;,<br>    &quot;eslint&quot;: &quot;^9.21.0&quot;,<br>    &quot;eslint-plugin-react-hooks&quot;: &quot;^5.1.0&quot;,<br>    &quot;eslint-plugin-react-refresh&quot;: &quot;^0.4.19&quot;,<br>    &quot;globals&quot;: &quot;^15.15.0&quot;,<br>    &quot;typescript&quot;: &quot;~5.7.2&quot;,<br>    &quot;typescript-eslint&quot;: &quot;^8.24.1&quot;,<br>    &quot;vite&quot;: &quot;^6.2.0&quot;<br>  }<br>}</pre><p>This React hook (useWs) acts like a real-time event listener, similar to how a backend service consumes Kafka messages. It establishes a WebSocket connection, listens for updates, and maintains state dynamically without polling.</p><p>The CrewData interface defines the structure of incoming messages, ensuring type safety, similar to a Java DTO. useState stores received messages, while useRef holds a reference to the WebSocket instance, preventing unnecessary re-renders. The useWebSocket hook manages connection lifecycle events like open, close, error handling, and automatic reconnection.</p><p>The useEffect hook initialises socketRef once the connection is ready and triggers pingServer, which periodically sends pings to keep the WebSocket alive, much like a heartbeat mechanism in backend systems. This setup ensures seamless real-time updates, reducing latency and improving UI responsiveness, similar to an event-driven backend architecture.</p><pre><br>import { useState, useEffect, useRef } from &quot;react&quot;;<br>import useWebSocket, { ReadyState } from &quot;react-use-websocket&quot;;<br><br><br>// Define the TypeScript interface for the WebSocket data model<br>export interface CrewData {<br>  crewId: string;<br>  onTimePerformance: number;<br>  flightHours: number;<br>  aircraftType: string;<br>  openTripsFD: number;<br>  unpairedLegsFD: number;<br>  standbyAvailableFD: number;<br>  openTripsCC: number;<br>  unpairedLegsCC: number;<br>  standbyAvailableCC: number;<br>  unfinalizedRoutes: number;<br>  timeInterval: string;<br>}<br><br><br>export const useWs = (url: string): any =&gt; {<br>    const [messages, setMessages] = useState&lt;CrewData[]&gt;([]);<br><br>    const socketRef = useRef&lt;any&gt;(null);<br><br>    const { readyState, sendJsonMessage } = useWebSocket(url, {<br>        onOpen: () =&gt; {<br>            console.log(&quot;WebSocket connection opened&quot;);<br>        },<br>        onClose: () =&gt; {<br>            console.log(&quot;WebSocket connection closed&quot;);<br>        },<br>        onError: (event: Event) =&gt; {<br>         console.error(&quot;WebSocket error:&quot;, event);<br>        },<br>        shouldReconnect: () =&gt; true,<br>        reconnectAttempts: 2,<br>        reconnectInterval: 5000,<br>        onMessage: (event: MessageEvent) =&gt; {<br>            const data = JSON.parse(event.data);<br>            console.log(&quot;WebSocket message received:&quot;, data);<br>            setMessages((prevMessages) =&gt; [data, ...prevMessages]);<br>            <br>        },<br>    });<br><br>    useEffect(() =&gt; {<br>        if (!socketRef.current) {<br>            socketRef.current = { readyState, sendJsonMessage };<br>        }<br>    }, [readyState, sendJsonMessage]);<br><br>    useEffect(() =&gt; {<br>        pingServer(readyState);<br>    }, [readyState, sendJsonMessage]);<br><br>    console.log(&quot;WebSocket connection state messages :&quot;, messages);<br><br>    return [readyState, messages];<br>};<br><br>const pingServer = (readyState: ReadyState) =&gt; {<br>    try {<br>        const pingAtInterval = 10000;<br>        if (readyState === WebSocket.OPEN) {<br>            const pingInterval = setInterval(() =&gt; {<br>                console.log(&quot;Ping sent to keep the connection alive&quot;);<br>            }, pingAtInterval);<br><br>            return () =&gt; clearInterval(pingInterval);<br>        }<br>    } catch (error) {<br>        throw error;<br>    }<br>};<br></pre><p>The component (CrewDataDisplay) uses the useWs hook to establish a WebSocket connection to “ws://localhost:8080/crew-metrics”, which continuously listens for incoming messages. The received data is stored in the messages state and displayed in a structured table format. I have created a simple data table that dynamically displays real-time crew metrics from a WebSocket connection, updating automatically without page refresh, and presenting structured crew details like ID, performance, flight hours, and other metrics in a readable format.</p><pre>import React from &quot;react&quot;;<br>import { useWs, CrewData } from &quot;../../service/WebSocket&quot;;<br><br>const CrewDataDisplay: React.FC = () =&gt; {<br>  const [readyState, messages] = useWs(&quot;ws://localhost:8080/crew-metrics&quot;);<br><br>  console.log(&quot;Crew Data:&quot;, messages);<br><br>  if (!messages) {<br>    return &lt;div&gt;Loading crew data...&lt;/div&gt;;<br>  }<br><br>  return (<br>    &lt;table className=&quot;crew-data-table&quot; style={{ border: &quot;1px solid black&quot;, borderCollapse: &quot;collapse&quot;, width: &quot;100%&quot; }}&gt;<br>      &lt;thead&gt;<br>        &lt;tr style={{ backgroundColor: &quot;lightblue&quot; }}&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Crew ID&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;On-Time Performance&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Flight Hours&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Aircraft Type&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Open Trips (FD)&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Unpaired Legs (FD)&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Standby Available (FD)&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Open Trips (CC)&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Unpaired Legs (CC)&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Standby Available (CC)&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Unfinalized Routes&lt;/th&gt;<br>          &lt;th style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;Time Interval&lt;/th&gt;<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;<br>      &lt;tbody&gt;<br>        {messages.map((crewData: CrewData, index: number) =&gt; (<br>          &lt;tr key={index}&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.crewId}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.onTimePerformance}%&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.flightHours}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.aircraftType}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.openTripsFD}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.unpairedLegsFD}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.standbyAvailableFD}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.openTripsCC}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.unpairedLegsCC}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.standbyAvailableCC}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.unfinalizedRoutes}&lt;/td&gt;<br>            &lt;td style={{ border: &quot;1px solid black&quot;, padding: &quot;8px&quot; }}&gt;{crewData.timeInterval}&lt;/td&gt;<br>          &lt;/tr&gt;<br>        ))}<br>      &lt;/tbody&gt;<br>    &lt;/table&gt;<br>  );<br>};<br><br>export default CrewDataDisplay;</pre><p>The AppRoutes component sets up routing using react-router-dom, defining paths for the home page (App component) and the /crew page (CrewDataDisplay component). However, routing is optional, and the CrewDataDisplay component can be directly included in the App component without using routing if navigation between pages isn’t required.</p><pre>import React from &quot;react&quot;;<br>import { BrowserRouter as Router, Routes, Route } from &quot;react-router-dom&quot;;<br>import App from &quot;../App&quot;;<br>import CrewDataDisplay from &quot;../components/template/CrewDataDisplay&quot;;<br><br><br>const AppRoutes: React.FC = () =&gt; {<br>  return (<br>    &lt;Router&gt;<br>      &lt;Routes&gt;<br>        {/* Home Page */}<br>        &lt;Route path=&quot;/&quot; element={&lt;App /&gt;} /&gt;<br><br>        {/* Crew Data Display Page */}<br>        &lt;Route path=&quot;/crew&quot; element={&lt;CrewDataDisplay /&gt;} /&gt;<br><br>      &lt;/Routes&gt;<br>    &lt;/Router&gt;<br>  );<br>};<br><br>export default AppRoutes;</pre><p>This UI screen is a real-time monitoring dashboard displaying crew performance metrics received from a WebSocket server. It presents structured data in a tabular format, dynamically updating as new messages arrive from the backend. The developer console shows WebSocket messages being logged, confirming continuous data transmission between the server and client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsFbIPxV01iDb3KH5apFew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4698361e68a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>