<?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 Vijayakumar Easwaran on Medium]]></title>
        <description><![CDATA[Stories by Vijayakumar Easwaran on Medium]]></description>
        <link>https://medium.com/@easwaranvijayakumar?source=rss-1063eb76fee4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Vijayakumar Easwaran on Medium</title>
            <link>https://medium.com/@easwaranvijayakumar?source=rss-1063eb76fee4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:57:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@easwaranvijayakumar/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[Agentic AI in Practice: From Alert to Approved Fix]]></title>
            <link>https://medium.com/@easwaranvijayakumar/agentic-ai-in-practice-from-alert-to-approved-fix-90dd2383bb2e?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/90dd2383bb2e</guid>
            <category><![CDATA[agentic-rl]]></category>
            <category><![CDATA[agentic-harness]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[institution-knowledge]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 23:01:02 GMT</pubDate>
            <atom:updated>2026-09-28T23:01:02.682Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How AI agents take on the investigation work that slows every engineering team down, and how to build one on a Java, Kafka and Azure stack.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrUZKSVMhj70EWPfNU9eLg.png" /></figure><h3>The investigation problem</h3><p>Every production incident follows a familiar pattern. An alert fires. Someone opens the dashboards, pulls the traces, checks what was deployed recently, and looks at the downstream systems. Eventually they find the cause.</p><p>The fix is often quick. Finding it is what takes the time.</p><p>Take a common example: consumer lag climbs on a Kafka topic. The cause turns out to be a recent pull request that added a synchronous database call inside the consumer loop. The investigation touched five different tools before anyone wrote a line of code.</p><p>This kind of work is repetitive and tool-heavy. It follows a pattern, but never exactly the same one twice. That makes it too messy for a script and too dull for your best engineers. It is exactly the kind of work agentic AI was built for.</p><h3>What agentic AI actually is</h3><p>A chatbot is like a brilliant consultant on the phone. You ask a question, you get an answer, and you still do all the work.</p><p>An agent is like a junior engineer you hand a ticket to. You give it a goal. It works out the steps, uses real tools, checks what happened, and adjusts when something fails. It comes back with the work done, or with a clear report of what it found.</p><p>Under the hood, every agent runs the same simple loop:</p><ol><li><strong>Plan</strong> — decide the next step toward the goal.</li><li><strong>Act</strong> — call a tool: query traces, read a PR, check a metric.</li><li><strong>Observe</strong> — read the result.</li><li><strong>Repeat</strong> — until the goal is met or a limit is hit.</li></ol><p>That loop is the whole shift. AI moves from <em>answering</em> to <em>doing</em>.</p><h3>The harness: the part nobody talks about</h3><p>The model is the brain. The <strong>harness</strong> is everything around the brain that lets it act safely in the real world.</p><p>Think of a racehorse. The horse has the power. The harness, the reins and the jockey keep that power on the track. A strong horse with no harness is useless, and dangerous.</p><p>On its own, a large language model only turns text into text. It cannot call an API, remember yesterday, retry a failed step or respect a permission. The harness adds all of that:</p><p>Job What the harness does Runs the loop Executes each tool call and feeds the result back to the model Connects tools Decides which tools the agent can see, usually through MCP Manages context Chooses what to keep, summarize or store for later Enforces guardrails Read-only access, approval gates, step and cost limits Handles failure Retries, fallbacks, timeouts Makes it observable Logs and traces every step</p><p>Here is why this matters. Models are becoming interchangeable; you can swap one for another. The harness is where your engineering decisions live: reliability, security, cost and compliance. Most teams will never build a model. Every team that uses agents will design a harness.</p><h3>The use case: an incident investigation agent</h3><p>Here is the same Kafka incident, with an agent as first responder.</p><p><em>The agent does the digging; a human still approves the fix.</em></p><p>The alert triggers the agent, not a person. Everything between the alert and the approval is the agent’s work:</p><ol><li><strong>Read the traces.</strong> The agent pulls OpenTelemetry traces for the lagging consumers. The OTel Java agent already instruments Kafka consumers and JDBC calls automatically.</li><li><strong>Check what changed.</strong> It lists pull requests merged and deployments shipped for that service recently.</li><li><strong>Look downstream.</strong> It checks Cassandra write latency over the same window.</li><li><strong>Form a hypothesis.</strong> “A recent PR added a synchronous Cassandra call inside the consumer loop. Throughput dropped and lag grew.”</li><li><strong>Draft the fix.</strong> It opens a pull request and writes a short incident summary with the evidence.</li><li><strong>Stop and ask.</strong> A human reviews and approves before anything touches production.</li></ol><p>The engineer who picks up the incident starts with a diagnosis and a proposed fix, not a blank dashboard.</p><h3>How to build it</h3><p>You do not need a Python rewrite or a research team. The pieces already exist for a Java and Azure shop.</p><p><strong>Harness: Spring AI 2.0.</strong> ChatClient, advisors, tool calling and structured outputs give you the agent loop in plain Spring Boot. Declarative MCP tools keep integrations clean. Java also brings mature concurrency, static analysis and a familiar deployment model on AKS.</p><p><strong>Tools: MCP servers behind a gateway.</strong> Wrap each system as an MCP server: traces, Git, Cassandra metrics, Kafka admin. Put them behind one gateway rather than letting the agent call each server directly. The gateway is where you enforce auth, rate limits and a single audit trail. Treat it as tier-1 infrastructure, with an SLA, a runbook and an on-call rotation. If it goes down, every agent goes dark.</p><p><strong>Observability: OTel GenAI conventions.</strong> Record every LLM call, tool call and retrieval step as a child span. You then get a full trace of the agent’s reasoning, not just its final answer. Put prompt content in span events rather than attributes, so personal data is not indexed.</p><p><strong>Roll it out in phases.</strong> Trust is earned, so widen the agent’s permissions only as it proves itself:</p><ol><li><strong>Shadow mode.</strong> The agent investigates in parallel with humans. Compare its diagnosis with theirs.</li><li><strong>Read-only first responder.</strong> The agent posts its diagnosis to the incident channel before an engineer picks it up.</li><li><strong>Draft fixes.</strong> The agent opens a pull request. It never merges.</li><li><strong>Narrow automation.</strong> For well-understood, low-risk fixes, allow automated action behind a feature flag. Humans still approve anything that touches production.</li></ol><h3>What can go wrong</h3><p><strong>Errors that compound.</strong> In a multi-step chain, one wrong conclusion early on quietly poisons every step after it. If the agent misreads a trace, its fix PR will be confidently wrong. Add checkpoints between steps: validate each finding before the next step builds on it.</p><p><strong>A new attack surface.</strong> An agent with write access is a new path into your systems, and many organizations secure the model while leaving the tool-call layer unmonitored. Give the agent the narrowest permissions possible, log every tool call, and treat anything it reads (logs, PR descriptions, tickets) as data, never as instructions.</p><p><strong>Compliance.</strong> Under the EU AI Act, high-risk AI systems must let you reconstruct the full decision chain. Scattered logs from each tool server will not satisfy that. A gateway-level trace will. If you handle EU data anywhere in your pipeline, map your agent usage to a risk register now.</p><h3>From assistant to institutional knowledge</h3><p>Today’s agents do the same quality of work on their first run and their thousandth. That is starting to change. With agentic reinforcement learning, agents improve from the outcomes of their own actions. An incident agent that has handled a hundred consumer-lag investigations can learn your system’s usual failure patterns.</p><p>That is the real prize. The knowledge that lives in your senior engineers’ heads (“lag on that topic is almost always Cassandra”) becomes something the whole organization keeps, even when people move on.</p><p>You do not need to start with the full vision. Pick one painful, repetitive investigation. Build a read-only agent for it. Measure how often it gets the diagnosis right. Let trust grow from there.</p><p>The goal is not to replace the engineer. It is to make sure that when they pick up an incident, the digging is already done.</p><p><em>What is the one investigation your team repeats most? That is where your first agent belongs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90dd2383bb2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Seam Problem: Why Four Great AI Tools Still Don’t Make a Platform]]></title>
            <link>https://medium.com/@easwaranvijayakumar/the-seam-problem-why-four-great-ai-tools-still-dont-make-a-platform-b6d839015218?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d839015218</guid>
            <category><![CDATA[thesis]]></category>
            <category><![CDATA[unified]]></category>
            <category><![CDATA[product-requirements]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 01:09:13 GMT</pubDate>
            <atom:updated>2026-09-21T01:09:13.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOhS1MjyKeQu65_p5kXKSQ.png" /></figure><p>Every stage of the software lifecycle now has credible AI tooling. Requirements have LLM summarizers and spec generators. Development has coding agents that can navigate a repository. Testing has evaluation frameworks that gate releases on quality scores. Deployment has agents that read a failing rollout and suggest the fix.</p><p>Each of these works. Put them side by side and you still don’t have a platform. You have four tools that each rebuild the same understanding of your system from scratch, in incompatible formats, and throw it away when the session ends.</p><p>That gap between the stages is where the actual cost lives. This article is about closing it.</p><h3>What we already have</h3><p>It’s worth being concrete about how good the individual pieces have gotten, because the argument isn’t that the tools are weak.</p><p>On the development side, code knowledge graphs have gone from research idea to daily driver. CodeGraph, an MIT-licensed local indexer, has gathered roughly <strong>68,700 </strong>GitHub stars and works across Claude Code, Cursor, Codex CLI, Gemini CLI, Copilot and others. Its August 2026 benchmark across seven repositories in seven languages measured 88% fewer tool calls, 53% faster completion, 62% fewer tokens and 44% lower cost compared to an agent reading files to orient itself. Graphify and code-review-graph attack the same problem from different angles, one with community detection and cross-file traversal, the other with a SQLite-backed AST graph and blast-radius analysis.</p><p>On the testing side, evaluation moved from research checkbox to production gate. DeepEval brings LLM-as-judge into a pytest suite. MLflow carries the broadest metric coverage and lets human labels train the automated judges. LangSmith does trace-level evaluation of tool calls and failure recovery.</p><p>On the deployment side, Kargo handles promotion between environments through a Warehouse, Freight and Stage model, writing the commit for you. Argo Rollouts and Flagger run canary and blue-green with metric analysis and automatic rollback. kagent, a CNCF Sandbox project, gives Kubernetes a native understanding of agent concerns, so a model change can be rolled back independently of a prompt change.</p><p>And underneath production, OpenTelemetry’s GenAI semantic conventions are becoming the shared vocabulary. Coding agents including VS Code Copilot, OpenAI Codex and Claude Code in beta already emit these traces.</p><p>Four healthy ecosystems. Four separate context stores.</p><h3>Where it leaks</h3><p>Watch a single change move through this stack and count how many times knowledge gets reconstructed.</p><p>As a product owner, writes a requirement in Jira. An engineer reads it and forms a mental model of which services it touches. A coding agent opens the repo and rediscovers the structure, possibly with a graph, possibly by burning twenty thousand tokens on file reads. A test gets written that encodes an assumption about intended behavior, but nothing links that assumption back to the requirement. The change deploys. A week later a canary fails on a latency metric, and the on-call engineer has no path from that metric back to the requirement that motivated the change.</p><p>Every arrow in that chain is a human carrying context across a boundary that the tooling doesn’t cross. Kubernetes is data-rich and cognitively demanding, and when a deployment breaks, the data connecting the failure to its cause already exists somewhere. It just requires an engineer to find it, across multiple tools, under pressure, often in the middle of the night.</p><p>Better dashboards haven’t fixed that. More runbooks haven’t fixed it. The problem is structural: the tools surface data and leave the reasoning to the human, because no tool can see across the whole chain.</p><h3>The thesis: extend the graph</h3><p>The code knowledge graph already solved this problem once, for one stage. It indexes symbols, call edges, imports and routes so an agent can query structure instead of rediscovering it.</p><p>The proposal is to stop treating that as a coding tool and start treating it as the platform’s spine. Four extensions:</p><p><strong>Requirements become nodes.</strong> A requirement, an acceptance criterion, a user story gets an identity in the graph, with edges to the modules and routes it’s expected to touch. This can be generated: give a model the requirement text and the existing code graph, and ask which subgraph it implicates. The output is reviewed, not trusted, but it’s a starting point no one has today.</p><p><strong>Tests become edges, not leaves.</strong> Today a test file is a node with an import edge. In the extended graph, a test carries an edge to the requirement it verifies and to the behavior it asserts. Coverage stops being a percentage of lines and becomes a question you can ask: which acceptance criteria have no verifying test?</p><p><strong>Deployment artifacts join the graph.</strong> A Kargo Freight, an Argo CD application, a Helm value, a feature flag. Each links to the commits it contains and through them to the requirements those commits implement. Kargo already writes the promotion commit; the graph just needs to record what that commit means.</p><p><strong>Runtime telemetry closes the loop.</strong> OpenTelemetry’s conventions give spans a standard shape. Attach a service and route identifier and those spans land on nodes that already exist. The latency regression on a canary is now three hops from the requirement that caused it.</p><h3>What this buys you</h3><p>Once the graph spans all four stages, questions that currently require a meeting become queries.</p><p>Before a change ships: which requirements does this PR touch, which tests verify them, and which of those tests are stale? Which downstream services sit in the blast radius?</p><p>During a rollout: this canary’s error rate is up, here are the three commits in the Freight, here is the requirement each implements, here is the one whose acceptance criteria mention the affected endpoint.</p><p>After an incident: this failure mode has no test. Here is the requirement it violates. Generate one and attach it.</p><p>And for the agents themselves, the payoff is the same one CodeGraph demonstrated for code, applied to the whole lifecycle. An agent that can query structure answers from one to four calls and stops. An agent without it burns its budget rediscovering what the graph already knew.</p><h3>How you’d actually build it</h3><p>Nothing here requires inventing a category. The pieces exist.</p><p>Use an existing code indexer as the base layer and extend its schema rather than writing your own parser. Expose the graph to agents over MCP, which is how Graphify and code-review-graph already publish themselves to Claude Code, Cursor, Gemini CLI and Windsurf. Keep the graph in the repository so it’s version-controlled and shared, and update it incrementally in a git hook rather than at agent runtime. Incremental updates run in under half a second on a thousand-file project, which is fast enough to sit in a pre-commit path.</p><p>For requirement linkage, start with a nightly job rather than a real-time one. For deployment linkage, parse what Kargo and Argo CD already emit. For runtime, instrument with OpenLLMetry, OpenInference or OpenLIT, which cover most frameworks in two or three lines without touching agent code.</p><p>Build it in that order: code, tests, deploy, requirements. The first three have machine-readable sources. Requirements are the hardest because they’re prose written by people who weren’t thinking about graphs.</p><h3>The honest limitations</h3><p>The requirements-to-code edge is the weak link, and pretending otherwise would be dishonest. It’s generated by a model reading prose, and it will be wrong often enough to need review. Treat it as a suggestion with a confidence score, not a fact.</p><p>The graph also needs a decay strategy. A link from a requirement to a module stays in the index long after a refactor moved the logic elsewhere. Stale edges are worse than missing ones because they’re confidently wrong.</p><p>And the multi-agent piece is genuinely unsolved. Effective patterns for testing systems where agents delegate to other agents are still emerging and will likely require new fixture structures that model inter-agent message flows. A platform built on this spine should assume that part will change.</p><h3>The larger shift</h3><p>There’s a reason this feels timely. The consensus forming across the industry is that models are commoditizing and differentiation is moving to the systems built around them. As one IBM architect put it, the competition in 2026 isn’t on models but on orchestration: combining models, tools and workflows.</p><p>An integrated lifecycle graph is exactly that kind of system. It isn’t a model, it isn’t a product feature, and no vendor can sell you a complete one. It’s the connective tissue that makes four good tools behave like one platform.</p><p>The tools are ready. The seams are where the work is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d839015218" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Detect and Auto-Heal a Down Instance in Production Using Spring Boot Actuator & Kubernetes…]]></title>
            <link>https://medium.com/@easwaranvijayakumar/how-to-detect-and-auto-heal-a-down-instance-in-production-using-spring-boot-actuator-kubernetes-b3ec524964a7?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ec524964a7</guid>
            <category><![CDATA[livenes]]></category>
            <category><![CDATA[spring-boot-actuator]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[readiness]]></category>
            <category><![CDATA[kubernetes-probes]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 03:21:09 GMT</pubDate>
            <atom:updated>2026-08-20T03:21:09.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLSdCMQcgcC5bMYJoF_Mqg.png" /></figure><h3>How to Detect and Auto-Heal a Down Instance in Production Using Spring Boot Actuator &amp; Kubernetes Probes</h3><h3>The Problem Nobody Talks About Enough</h3><p>Your production service is down. Users are seeing errors. Your load balancer is still cheerfully routing traffic to a pod that is silently broken — maybe it ran out of memory, maybe it deadlocked, maybe a downstream dependency took it out. You find out about it from a customer, not from your monitoring.</p><p>This is a solvable problem. And the solution is elegant: <strong>Spring Boot Actuator</strong> combined with <strong>Kubernetes liveness and readiness probes</strong>.</p><p>By the end of this article, you will understand:</p><ul><li>What Actuator health endpoints are and how to set them up</li><li>What liveness and readiness probes actually mean (they are not the same thing)</li><li>How to wire them together so your cluster heals itself</li><li>How to avoid concurrent failure — the dreaded scenario where a pod is restarting <em>and</em> still receiving traffic at the same time</li><li>How to take manual control of your instance’s health state from inside the application</li></ul><p>Let’s go.</p><h3>Part 1: Understanding the Moving Parts</h3><p>Before writing a single line of config, let us make sure the concepts are crystal clear.</p><h3>What is Spring Boot Actuator?</h3><p>Spring Boot Actuator is a sub-project of Spring Boot that adds <strong>production-ready features</strong> to your application — things like health checks, metrics, environment info, and thread dumps — all exposed as HTTP endpoints.</p><p>The most important one for us is /actuator/health.</p><p>When you hit that endpoint, Actuator internally checks a set of health indicators (database connectivity, disk space, custom checks you write) and returns a simple JSON response:</p><pre>{<br>  &quot;status&quot;: &quot;UP&quot;<br>}</pre><p>Or when something is wrong:</p><pre>{<br>  &quot;status&quot;: &quot;DOWN&quot;,<br>  &quot;components&quot;: {<br>    &quot;db&quot;: {<br>      &quot;status&quot;: &quot;DOWN&quot;,<br>      &quot;details&quot;: {<br>        &quot;error&quot;: &quot;Unable to acquire JDBC Connection&quot;<br>      }<br>    }<br>  }<br>}</pre><p>This is exactly the kind of signal Kubernetes needs to make intelligent decisions about your pods.</p><h3>What are Kubernetes Probes?</h3><p>Kubernetes does not inherently know if the application inside your pod is healthy. It only knows if the container process is running. A Java process can be running (from the OS perspective) while the application inside is completely deadlocked and unable to serve any request.</p><p>Probes are how you teach Kubernetes what “healthy” means for your specific app. There are three types:</p><p>Probe Question it answers Action on failure <strong>Startup</strong> Has the app finished starting up? Keep waiting (prevents other probes from firing too early) <strong>Liveness</strong> Is the app alive and not stuck? <strong>Restart the pod</strong> <strong>Readiness</strong> Is the app ready to serve traffic? <strong>Remove the pod from the load balancer</strong></p><p>The distinction between liveness and readiness is the most important thing in this entire article. Read it again.</p><ul><li><strong>Liveness failure</strong> → the pod gets killed and restarted. Use this for unrecoverable states like deadlocks.</li><li><strong>Readiness failure</strong> → the pod stays alive but gets pulled out of the load balancer. Use this for temporary unavailability like a DB reconnection or a cache warming up.</li></ul><h3>Part 2: Setting Up Spring Boot Actuator</h3><h3>Step 1: Add the Dependency</h3><pre>&lt;!-- pom.xml --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>Step 2: Configure the Health Endpoints</h3><pre># application.yml<br>management:<br>  endpoint:<br>    health:<br>      show-details: always          # show per-component breakdown<br>      probes:<br>        enabled: true               # enables /health/liveness and /health/readiness<br>  endpoints:<br>    web:<br>      exposure:<br>        include: health,info,metrics<br>  health:<br>    livenessstate:<br>      enabled: true<br>    readinessstate:<br>      enabled: true</pre><p>With probes.enabled: true, Spring Boot automatically exposes two dedicated endpoints:</p><ul><li>GET /actuator/health/liveness → responds {&quot;status&quot;: &quot;UP&quot;} or {&quot;status&quot;: &quot;DOWN&quot;}</li><li>GET /actuator/health/readiness → responds {&quot;status&quot;: &quot;UP&quot;} or {&quot;status&quot;: &quot;DOWN&quot;}</li></ul><p>These map to Spring’s internal LivenessState and ReadinessState enums, which you can control programmatically (more on that shortly).</p><h3>What Built-in Health Indicators Does Spring Auto-Configure?</h3><p>Spring Boot auto-configures health indicators based on what is on your classpath:</p><p>Indicator What it checks DataSourceHealthIndicator Can the app acquire a JDBC connection? RedisHealthIndicator Can the app reach Redis? MongoHealthIndicator Is MongoDB reachable? DiskSpaceHealthIndicator Is disk space above the threshold? CassandraHealthIndicator Is Cassandra available? ElasticsearchHealthIndicator Is Elasticsearch up?</p><p>All of these roll up into the /actuator/health response automatically. If any one of them goes DOWN, the aggregate status becomes DOWN.</p><h3>Part 3: Writing a Custom Health Indicator</h3><p>The built-in indicators cover infrastructure. But what about your own business-critical dependencies — an external payment API, a third-party data feed, an internal microservice?</p><p>You write a custom HealthIndicator:</p><pre>@Component<br>public class PaymentGatewayHealthIndicator implements HealthIndicator {<br>private final PaymentGatewayClient client;<br>    public PaymentGatewayHealthIndicator(PaymentGatewayClient client) {<br>        this.client = client;<br>    }<br>    @Override<br>    public Health health() {<br>        try {<br>            // Your own ping/check logic<br>            PingResponse response = client.ping();<br>            if (response.isSuccessful()) {<br>                return Health.up()<br>                    .withDetail(&quot;gateway&quot;, &quot;reachable&quot;)<br>                    .withDetail(&quot;latencyMs&quot;, response.getLatency())<br>                    .build();<br>            }<br>            return Health.down()<br>                .withDetail(&quot;gateway&quot;, &quot;returned error: &quot; + response.getErrorCode())<br>                .build();<br>        } catch (Exception e) {<br>            return Health.down()<br>                .withDetail(&quot;gateway&quot;, &quot;unreachable&quot;)<br>                .withException(e)<br>                .build();<br>        }<br>    }<br>}</pre><p>This automatically shows up under /actuator/health/paymentGateway and contributes to the overall health status. No extra wiring needed.</p><h3>Part 4: Wiring It All into Kubernetes</h3><p>Now comes the powerful part — connecting your Actuator endpoints to Kubernetes probes.</p><pre># deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: your-spring-app<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: your-spring-app<br>  template:<br>    spec:<br>      containers:<br>        - name: your-spring-app<br>          image: your-registry/your-app:1.0.0<br>          ports:<br>            - containerPort: 8080<br># PROBE 1: Startup<br>          # Gates everything. Liveness and readiness won&#39;t fire until this passes.<br>          # Gives slow-starting Spring apps time to fully initialize.<br>          startupProbe:<br>            httpGet:<br>              path: /actuator/health/liveness<br>              port: 8080<br>            failureThreshold: 30      # 30 attempts × 10s = 5 minutes max startup time<br>            periodSeconds: 10<br>          # PROBE 2: Readiness<br>          # Configured to fail FAST - pulls the pod from the load balancer quickly.<br>          # Does NOT restart the pod.<br>          readinessProbe:<br>            httpGet:<br>              path: /actuator/health/readiness<br>              port: 8080<br>            initialDelaySeconds: 0    # startupProbe already handled the delay<br>            periodSeconds: 5<br>            failureThreshold: 1       # just 1 failure = out of LB (5 seconds)<br>            timeoutSeconds: 3<br>          # PROBE 3: Liveness<br>          # Configured to fail SLOW - only restarts after readiness has already acted.<br>          # Restarts the pod as a last resort.<br>          livenessProbe:<br>            httpGet:<br>              path: /actuator/health/liveness<br>              port: 8080<br>            initialDelaySeconds: 0<br>            periodSeconds: 10<br>            failureThreshold: 3       # 3 failures = restart (30 seconds)<br>            timeoutSeconds: 5</pre><h3>The Critical Timing Gap</h3><p>Notice the deliberate difference in how fast each probe fires:</p><pre>Readiness: 1 failure × 5s  =  5 seconds to pull from LB<br>Liveness:  3 failures × 10s = 30 seconds to restart<br>Gap = ~25 seconds of drain time</pre><p>This 25-second window is where the magic happens. During this time:</p><ol><li>The pod is already removed from the load balancer (no new traffic)</li><li>In-flight requests that were already being processed can complete</li><li>Only <em>then</em> does Kubernetes restart the pod</li></ol><p>This is how you avoid concurrent failure — a pod restarting while still receiving requests.</p><h3>Part 5: Taking Manual Control from Inside the App</h3><p>What if your application itself detects that something is wrong — a memory threshold crossed, a critical background job failed, a deadlock detected? You do not have to wait for a probe timeout.</p><p>Spring Boot exposes the AvailabilityChangeEvent API to let you flip health states programmatically:</p><pre>@Component<br>public class InstanceHealthManager {<br>private final ApplicationContext context;<br>    private final ScheduledExecutorService scheduler =<br>        Executors.newSingleThreadScheduledExecutor();<br>    public InstanceHealthManager(ApplicationContext context) {<br>        this.context = context;<br>    }<br>    /**<br>     * Call this when you detect an unrecoverable internal problem.<br>     * Gracefully drains traffic before triggering a restart.<br>     */<br>    public void gracefullyRequestRestart(String reason) {<br>        log.warn(&quot;Instance health manager: initiating graceful restart. Reason: {}&quot;, reason);<br>        // Step 1: Tell Kubernetes we are not ready for new traffic<br>        AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC);<br>        // Step 2: Wait for in-flight requests to complete (drain window)<br>        scheduler.schedule(() -&gt; {<br>            log.warn(&quot;Drain window complete. Signaling liveness failure to trigger restart.&quot;);<br>            // Step 3: Tell Kubernetes the app is broken - triggers pod restart<br>            AvailabilityChangeEvent.publish(context, LivenessState.BROKEN);<br>        }, 15, TimeUnit.SECONDS);<br>    }<br>}</pre><h3>Hooking It into Your Error Handling</h3><pre>@Component<br>public class CriticalErrorHandler {<br>private final InstanceHealthManager healthManager;<br>    // Listen for a custom application event you publish when something critical breaks<br>    @EventListener<br>    public void onCriticalFailure(CriticalAppFailureEvent event) {<br>        healthManager.gracefullyRequestRestart(event.getReason());<br>    }<br>    // Or hook directly into uncaught exception handling<br>    @Bean<br>    public Thread.UncaughtExceptionHandler uncaughtExceptionHandler() {<br>        return (thread, throwable) -&gt; {<br>            log.error(&quot;Uncaught exception on thread {}&quot;, thread.getName(), throwable);<br>            if (isFatal(throwable)) {<br>                healthManager.gracefullyRequestRestart(&quot;Uncaught fatal exception: &quot;<br>                    + throwable.getMessage());<br>            }<br>        };<br>    }<br>    private boolean isFatal(Throwable t) {<br>        return t instanceof OutOfMemoryError<br>            || t instanceof StackOverflowError<br>            || t instanceof DeadlockException;<br>    }<br>}</pre><h3>Part 6: Graceful Shutdown (The Final Piece)</h3><p>Even with all the above in place, there is one more scenario: what happens to in-flight requests when Kubernetes sends a SIGTERM to shut down the pod (during a rolling deploy, for example)?</p><p>Spring Boot 2.3+ has graceful shutdown built in:</p><pre># application.yml<br>server:<br>  shutdown: graceful<br>spring:<br>  lifecycle:<br>    timeout-per-shutdown-phase: 20s   # wait up to 20s for in-flight requests</pre><p>And in your Kubernetes deployment, add a preStop hook to give the load balancer time to deregister the pod before the shutdown begins:</p><pre>lifecycle:<br>  preStop:<br>    exec:<br>      command: [&quot;sh&quot;, &quot;-c&quot;, &quot;sleep 10&quot;]   # wait 10s for LB deregistration</pre><p>The full shutdown sequence becomes:</p><pre>Kubernetes sends SIGTERM<br>        │<br>        ▼<br>preStop hook runs (sleep 10s) — LB removes the pod<br>        │<br>        ▼<br>Spring begins graceful shutdown — refuses new requests<br>        │<br>        ▼<br>Spring waits up to 20s for in-flight requests to complete<br>        │<br>        ▼<br>Pod exits cleanly</pre><h3>Part 7: Debugging Probe Failures in the Wild</h3><p>When something goes wrong in production, here are the commands you need:</p><pre># See recent probe failures and restarts<br>kubectl describe pod &lt;pod-name&gt; -n &lt;namespace&gt;<br># Look for: Liveness probe failed / Readiness probe failed in the Events section<br><br># Check liveness directly from inside the pod<br>kubectl exec -it &lt;pod-name&gt; -n &lt;namespace&gt; -- \<br>  curl -s localhost:8080/actuator/health/liveness | python3 -m json.tool<br># Check readiness<br>kubectl exec -it &lt;pod-name&gt; -n &lt;namespace&gt; -- \<br>  curl -s localhost:8080/actuator/health/readiness | python3 -m json.tool<br># Watch events in real time<br>kubectl get events -n &lt;namespace&gt; \<br>  --sort-by=&#39;.lastTimestamp&#39; \<br>  --watch | grep -i &quot;probe\|unhealthy\|killing&quot;<br># See restart count history<br>kubectl get pods -n &lt;namespace&gt; \<br>  -o custom-columns=&#39;NAME:.metadata.name,RESTARTS:.status.containerStatuses[0].restartCount,STATUS:.status.phase&#39;</pre><h3>The Complete Picture</h3><p>Here is how everything fits together end to end:</p><pre>App starts<br>    │<br>    ▼<br>startupProbe polling /health/liveness every 10s<br>    │  (liveness and readiness probes are paused)<br>    │<br>    ▼ startupProbe passes<br>    │<br>    ├──► readinessProbe starts polling /health/readiness every 5s<br>    │         │ passes → pod added to load balancer<br>    │<br>    └──► livenessProbe starts polling /health/liveness every 10s<br><br>During normal operation:<br>    Readiness UP + Liveness UP → traffic flows normally ✅<br><br>DB connection drops:<br>    Readiness DOWN (after 5s) → pod removed from LB 🚫<br>    App reconnects → Readiness UP → pod re-added to LB ✅<br>    (liveness never triggered - no restart needed)<br><br>App deadlocks / critical failure:<br>    App publishes ReadinessState.REFUSING_TRAFFIC → pod removed from LB 🚫<br>    15s drain window → in-flight requests complete<br>    App publishes LivenessState.BROKEN → liveness probe fails<br>    Kubernetes restarts pod 🔄<br>    startupProbe gates → readiness passes → pod re-enters LB ✅<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*zwjAtUUWfrYBjpEVNj8fzw.png" /></figure><p>The entire system is designed around one principle: <strong>never let a bad pod receive traffic, and never restart a pod that is still processing requests.</strong></p><p>When you get this right, production incidents go from “someone’s phone blowing up at any time” to “a pod restarted, healed itself, and the users never noticed.”</p><p><em>Written from real-world production experience with Spring Boot and Kubernetes. The patterns here are battle-tested and safe to apply to any Spring Boot 2.3+ application running on Kubernetes 1.18+.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ec524964a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Principal Engineer’s Toolkit: Best Open Source Tools for Java Teams in 2026]]></title>
            <link>https://medium.com/@easwaranvijayakumar/the-principal-engineers-toolkit-best-open-source-tools-for-java-teams-in-2026-87f4b4753a28?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f4b4753a28</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[innersource]]></category>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[devtools]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 13:02:52 GMT</pubDate>
            <atom:updated>2026-08-12T13:02:52.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWB77MmlvcABPydW58DUaw.png" /></figure><h3>A hands-on guide to performance testing, code quality, security, visualization, and observability — filtered for Spring Boot, Kafka, and Kubernetes stacks</h3><p><em>By a Principal Engineer who has lived the chaos of tool sprawl, legacy debt, and “we’ll add tests later.”</em></p><h3>Why This Guide Exists</h3><p>Every quarter, a new wave of tools promises to transform how engineering teams ship software. Most of them get added to a team wiki, starred on GitHub, and forgotten. A few become load-bearing infrastructure.</p><p>This guide is about the few.</p><p>After evaluating over 40 tools across a distributed Java stack — Spring Boot microservices, Kafka event streams, Cassandra, Redis, AKS on Azure — these are the ones that survived contact with production. Organized by the problem they solve, not by marketing category.</p><p>If you run a Java-heavy enterprise team and want a toolkit that covers <strong>performance, quality, security, architecture visibility, and observability</strong> without turning your CI pipeline into a 45-minute slog, this is for you.</p><h3>The Six Problem Areas</h3><ol><li><strong>Performance &amp; Load Testing</strong> — does it survive real traffic?</li><li><strong>Code Quality &amp; Static Analysis</strong> — does it meet your standards?</li><li><strong>Security Testing</strong> — is it safe to ship?</li><li><strong>Architecture Visualization</strong> — can you see what you’ve built?</li><li><strong>Testing Frameworks</strong> — do your tests actually test anything?</li><li><strong>Observability &amp; Engineering Intelligence</strong> — can you understand it in production?</li></ol><p>Let’s go through each.</p><h3>1. Performance &amp; Load Testing</h3><h3>The landscape</h3><p>Performance testing has split into two camps: <strong>developer-owned tests that live in the repo</strong>, and <strong>tester-owned scripts that live on a shared server nobody touches</strong>. The second camp produces stale tests. The first produces real feedback.</p><h3>The tools worth knowing</h3><p><strong>Grafana k6</strong> is the current gold standard for developer-led load testing. Written in Go, scripted in JavaScript, it treats performance tests as code — version controlled, reviewed, and run in CI. The killer feature is <strong>thresholds</strong>: declare p95 &lt; 400ms and k6 fails the build if you miss it. Native Grafana integration means your test results feed into the same dashboards your team already watches.</p><pre>// k6 threshold example — fails CI if P95 exceeds 400ms<br>export const options = {<br>  thresholds: {<br>    http_req_duration: [&#39;p(95)&lt;400&#39;],<br>  },<br>  vus: 100,<br>  duration: &#39;2m&#39;,<br>};</pre><p><strong>Gatling</strong> is the choice when your team writes Java for a living and doesn’t want to context-switch into JavaScript to write load tests. Its Scala DSL is close enough to JUnit that Java developers adapt quickly. More importantly, it handles <strong>massive concurrency on minimal resources</strong> — Gatling can simulate 100K users on hardware that would bring JMeter to its knees.</p><p><strong>Apache JMeter</strong> is the veteran. Its GUI makes it accessible to testers who aren’t comfortable writing code, and its plugin ecosystem is unmatched — there are JMeter plugins for Kafka producer testing, JDBC/Cassandra load, and Redis benchmarking. It’s not glamorous, but when you need to load test a Cassandra read path or a Kafka consumer group, JMeter’s plugin library often has exactly what you need.</p><p><strong>Artillery</strong> fills the gap for teams that need API and WebSocket load testing with minimal setup — YAML config, Prometheus output, and a growing library of scenarios.</p><h3>Recommended stack for Java/Kafka teams</h3><pre>Gatling   → developer-written perf tests, lives in the repo alongside feature code<br>k6        → CI gate, fails the build if latency SLOs are breached<br>JMeter    → tester-driven scenarios for Kafka + Cassandra + JDBC load</pre><h3>2. Code Quality &amp; Static Analysis</h3><h3>The problem with code reviews</h3><p>Code review catches logic bugs. It does not reliably catch architectural drift, security anti-patterns, unused imports in 1,800-line files, or the slow accumulation of technical debt across 30 microservices. That’s what static analysis is for.</p><h3>The tools worth knowing</h3><p><strong>SonarQube Community Edition</strong> is the anchor. Free, Java-first, and deeply integrated with Jenkins, GitHub Actions, and Azure Pipelines. It tracks code smells, coverage, duplication, and security hotspots across your entire codebase over time. The quality gate feature is what makes it a governance tool rather than just a reporting tool — configure it once to block merges that drop coverage below threshold or introduce new critical issues, and it enforces your standards automatically.</p><p><strong>ArchUnit</strong> is the tool most Java teams don’t know about but should. It lets you write your architecture rules as JUnit tests. This is the difference between a diagram that describes what your architecture <em>should</em> look like and a test that <em>fails the build</em> if it doesn’t. Want to ensure no controller class calls a repository directly? Write the test. Want to ensure all Kafka consumers are in the messaging package? Write the test.</p><pre>@Test<br>void controllers_must_not_access_repositories_directly() {<br>    noClasses()<br>        .that().resideInAPackage(&quot;..controller..&quot;)<br>        .should().accessClassesThat()<br>        .resideInAPackage(&quot;..repository..&quot;)<br>        .check(importedClasses);<br>}</pre><pre>@Test<br>void kafka_consumers_must_reside_in_messaging_package() {<br>    classes()<br>        .that().areAnnotatedWith(KafkaListener.class)<br>        .should().resideInAPackage(&quot;..messaging..&quot;)<br>        .check(importedClasses);<br>}</pre><p>These tests run with your unit tests. They catch violations at PR time, not in a quarterly architecture review.</p><p><strong>SpotBugs</strong> analyzes Java bytecode rather than source, catching a class of bugs that source-level tools miss: null pointer dereferences, resource leaks, incorrect synchronization, and more. It runs as a Maven or Gradle plugin with zero configuration changes to your build.</p><p><strong>PMD</strong> and <strong>Checkstyle</strong> cover the lower layer — style enforcement, unused variables, empty catch blocks, naming conventions. They’re the unsexy tools that prevent “we’ll clean this up later” from becoming “this codebase is a hazard.” Both run as pre-commit hooks via pre-commit or lefthook, giving developers immediate feedback before anything hits CI.</p><p><strong>ErrorProne</strong> (from Google) is a Java compiler plugin that catches bugs at compile time. It literally prevents certain classes of mistakes from compiling. Zero runtime cost, and it integrates into Maven builds with a single dependency.</p><h3>Recommended quality stack</h3><pre>SonarQube   → quality gate in CI (coverage, issues, security hotspots)<br>ArchUnit    → architecture rules as executable tests<br>SpotBugs    → bytecode analysis in Maven build<br>PMD         → pre-commit hook for Java rule violations<br>ErrorProne  → compile-time bug prevention</pre><h3>3. Security Testing</h3><h3>The shift-left reality</h3><p>Security testing used to mean a penetration test before a major release. In 2026, with EU AI Act enforcement live and CVEs dropping weekly in Spring dependencies, that model is broken. Security needs to run on every commit.</p><h3>The tools worth knowing</h3><p><strong>OWASP Dependency-Check</strong> is non-negotiable for Java teams. It scans your Maven or Gradle dependencies against the NVD CVE database and generates a report on every known vulnerability in your dependency tree. The Spring ecosystem’s history with Log4Shell and similar vulnerabilities makes this a critical gate. Run it in Jenkins weekly as a minimum; add it to your PR pipeline for critical services.</p><p><strong>Trivy</strong> from Aqua Security is the fastest way to scan Docker images, Kubernetes manifests, and IaC configurations for CVEs. For AKS-deployed services, the workflow is simple: scan every image before it’s pushed to ACR, fail the pipeline on HIGH or CRITICAL findings.</p><pre># GitHub Actions Trivy scan step<br>- name: Scan Docker image<br>  uses: aquasecurity/trivy-action@master<br>  with:<br>    image-ref: ${{ env.ACR_REGISTRY }}/myservice:${{ github.sha }}<br>    exit-code: &#39;1&#39;<br>    severity: &#39;HIGH,CRITICAL&#39;</pre><p><strong>Gitleaks</strong> prevents secrets from being committed to your repository. API keys, Entra ID credentials, connection strings — it scans git history and pre-commit hooks. One secret in a commit history, even if reverted, can mean a full credential rotation. The pre-commit hook approach prevents it from happening in the first place.</p><p><strong>OWASP ZAP</strong> (Zed Attack Proxy) is the open source DAST tool for scanning your running APIs for injection vulnerabilities, misconfigured headers, and authentication flaws. It runs against your staging AKS environment nightly — a passive scan that finds what static analysis misses.</p><p><strong>Semgrep OSS</strong> is worth adding for teams that want to write custom security rules. Out of the box it has rules for common Java security anti-patterns. The real value comes when you write your own rules that enforce your organization’s specific security standards across all your repos.</p><h3>Recommended security stack</h3><pre>OWASP Dep-Check  → Maven plugin, weekly CVE report on all dependencies<br>Trivy            → GitHub Actions image scan before every ACR push<br>Gitleaks         → pre-commit hook, blocks secrets before they hit the repo<br>OWASP ZAP        → nightly DAST scan against AKS staging environment</pre><h3>4. Architecture Visualization</h3><h3>The gap between diagrams and reality</h3><p>Every team has an architecture diagram. Almost no team has an architecture diagram that accurately reflects what’s actually running. Static diagrams are created once and drift immediately. What teams need is architecture visibility from their actual code and running systems.</p><h3>The tools worth knowing</h3><p><strong>jQAssistant</strong> is the least-known tool on this list and possibly the highest-leverage one for large Java teams. It scans your Maven multi-module project and loads the entire dependency graph into an embedded Neo4j database. You then query your architecture using Cypher — the graph query language.</p><pre>// Find classes that violate layering rules<br>MATCH (controller:Class)-[:DEPENDS_ON]-&gt;(repository:Class)<br>WHERE controller.name CONTAINS &#39;Controller&#39;<br>  AND repository.name CONTAINS &#39;Repository&#39;<br>RETURN controller.name, repository.name</pre><p>This is architecture analysis as data, not as a diagram. Combined with ArchUnit for enforcement and jQAssistant for exploration, you have a complete architecture governance system.</p><p><strong>Structurizr Lite</strong> implements the C4 model (Context, Container, Component, Code) as a DSL. You define your architecture in a text file, and Structurizr renders it as interactive diagrams. Because it’s code, it lives in your repo, gets reviewed in PRs, and stays synchronized with your actual architecture decisions.</p><p><strong>CodeCharta</strong> renders your codebase as a 3D “code city” where buildings represent files, height represents complexity, and color represents test coverage. It’s the fastest way to visualize where technical debt is concentrated across a large codebase — the skyscrapers with red roofs are your problem areas.</p><p><strong>Dependency-Track</strong> takes your Software Bill of Materials (SBOM) and renders it as a component graph overlaid with CVE risk data. For Principal Engineers who need to answer “what is our exposure to this new vulnerability?”, Dependency-Track gives you the answer in seconds.</p><p><strong>Mermaid</strong> and <strong>PlantUML</strong> are the practical tools for day-to-day architectural documentation. Both render diagrams from text, live natively in GitHub and GitLab markdown, and belong in every ADR (Architecture Decision Record) your team writes.</p><h3>Recommended visualization stack</h3><pre>jQAssistant     → graph-based architecture queries over your entire codebase<br>Structurizr     → C4 diagrams as code, version-controlled architecture docs<br>CodeCharta      → 3D technical debt visualization for teams and stakeholders<br>Dependency-Track → SBOM + CVE risk graph across all services<br>Mermaid         → inline diagrams in ADRs and GitHub markdown</pre><h3>5. Testing Frameworks &amp; Automation</h3><h3>The Testcontainers moment</h3><p>There is a before and after in Java integration testing, and the line is Testcontainers. Before: mocking Kafka, mocking Cassandra, writing integration tests that test your mocks rather than the real system. After: spinning up real containers in your JUnit tests with zero infrastructure setup required.</p><h3>The tools worth knowing</h3><p><strong>Testcontainers</strong> is the foundation. Real Kafka, real Cassandra, real Redis — in your CI pipeline, in Docker containers, torn down after every test run. For distributed systems teams, this is the tool that makes “it works in my environment” a solvable problem rather than an excuse.</p><pre>@Testcontainers<br>class OrderServiceIntegrationTest {<br><br>@Container<br>    static KafkaContainer kafka = new KafkaContainer(<br>        DockerImageName.parse(&quot;confluentinc/cp-kafka:7.6.0&quot;)<br>    );<br>    @Container<br>    static CassandraContainer&lt;?&gt; cassandra = new CassandraContainer&lt;&gt;(<br>        DockerImageName.parse(&quot;cassandra:4.1&quot;)<br>    );<br>    @Test<br>    void order_placed_event_is_processed_and_persisted() {<br>        // Test against real Kafka and real Cassandra<br>        // No mocks. No surprises in production.<br>    }<br>}</pre><p><strong>Awaitility</strong> solves the async assertion problem that every Kafka consumer test hits: how do you assert that a message was processed when processing is asynchronous? Awaitility provides a clean DSL for polling assertions until a condition is true or a timeout expires.</p><pre>await()<br>    .atMost(10, SECONDS)<br>    .pollInterval(500, MILLISECONDS)<br>    .until(() -&gt; orderRepository.findById(orderId).isPresent());</pre><p><strong>Pact JVM</strong> is consumer-driven contract testing for your Kafka topics and REST APIs. The consumer team defines what they expect, the provider team verifies they deliver it. Schema changes that break consumers are caught before deployment, not after.</p><p><strong>Chaos Monkey for Spring Boot</strong> injects latency, exceptions, and service unavailability at runtime to verify that your Resilience4j circuit breakers, retry policies, and fallbacks actually behave correctly under failure. Writing a circuit breaker is easy. Verifying it actually opens when it should is what Chaos Monkey tests.</p><p><strong>Pitest</strong> runs mutation testing — it introduces small mutations into your code (flipping a boolean, changing a comparison operator) and checks whether your tests catch them. A test suite with 80% coverage but 40% mutation score is telling you your tests pass when they should fail. Pitest surfaces this.</p><h3>Recommended test stack</h3><pre>Testcontainers  → real Kafka + Cassandra + Redis in integration tests<br>Awaitility      → async assertions for all Kafka consumer tests<br>Pact JVM        → contract tests between Kafka producers and consumers<br>Chaos Monkey    → resilience validation — verify circuit breakers work<br>Pitest          → mutation testing — verify test quality, not just coverage</pre><h3>6. Observability &amp; Engineering Intelligence</h3><h3>Beyond logs</h3><p>In 2026, observability for distributed Java systems means three things: structured traces across service boundaries (OpenTelemetry), metrics that surface in dashboards teams actually look at (Grafana + Prometheus), and a developer portal that makes the whole system discoverable (Backstage).</p><h3>The tools worth knowing</h3><p><strong>OpenTelemetry Java Agent</strong> is the zero-code instrumentation path. Attach -javaagent:opentelemetry-javaagent.jar to your JVM startup and it auto-instruments 120+ libraries including Spring MVC, Kafka consumers, JDBC, and Redis — producing traces, metrics, and logs without modifying application code. Measured overhead in typical Spring Boot services: 1.2–2.8ms added to P99 latency at 1,000 RPS. The overhead argument against instrumentation is over.</p><p><strong>Grafana + Prometheus</strong> is the de facto observability stack for Kubernetes-deployed Java services. Prometheus scrapes metrics, Grafana visualizes them, and the Alertmanager handles on-call routing. For Azure Monitor users, the Grafana Azure datasource brings AKS metrics into the same dashboards alongside your application metrics.</p><p><strong>Jaeger v2</strong> (upgraded this year) adds native support for MCP tool call traces and GenAI pipeline visualization alongside traditional distributed tracing. If you’re running AI agents alongside your Spring Boot services, Jaeger v2 gives you a single trace view that spans traditional microservice calls and agent tool invocations.</p><p><strong>Backstage</strong> is the highest-leverage infrastructure investment for Principal Engineers leading inner-source programs. Built by Spotify, now a CNCF project, it provides a developer portal where every service, API, library, documentation page, and internal tool is catalogued and discoverable. Instead of hunting through Confluence for which team owns the Orders service, or which version of the logging library is the standard, teams find it in Backstage.</p><p>For inner-source specifically, Backstage’s Software Catalog + TechDocs plugin turns your architecture standards, inner-source templates, and API documentation into a searchable, versioned, always-current portal.</p><p><strong>LinearB</strong> surfaces DORA metrics (deployment frequency, lead time, change failure rate, MTTR) from your Git and Jira data. For Principal Engineers who need to demonstrate engineering health to stakeholders, LinearB converts raw commit and ticket data into the metrics that matter.</p><h3>Recommended observability stack</h3><pre>OTel Java Agent → auto-instrument all services, zero code changes<br>Prometheus      → metrics scraping from AKS pods<br>Grafana         → dashboards + alerting (Azure datasource for AKS metrics)<br>Jaeger v2       → distributed tracing + MCP agent trace visualization<br>Backstage       → developer portal for inner-source governance and discovery<br>LinearB         → DORA metrics for engineering health reporting</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*l5UulOs7ngiMr5f9y6pSJw.png" /></figure><h3>Where to Start</h3><p>The instinct when reading a guide like this is to add all of it to a backlog and implement none of it. Resist that instinct. Pick one problem — the one that is causing the most pain right now — and solve it completely before moving to the next.</p><p><strong>If your team ships slow</strong>, start with k6 as a CI gate. A failing threshold is the fastest feedback loop for performance regressions.</p><p><strong>If your team ships bugs</strong>, start with Testcontainers and Pitest. Real integration tests and mutation scoring will surface gaps in your safety net within days.</p><p><strong>If your team is accumulating technical debt</strong>, start with SonarQube and ArchUnit. Quality gates and architecture tests enforce standards without requiring anyone to remember to check.</p><p><strong>If your team is flying blind in production</strong>, start with the OTel Java agent. Attach it, configure an OTLP endpoint, and you have distributed traces across all your services before lunch.</p><p><strong>If your team is building AI-powered features</strong>, start with Jaeger v2 and the MCP OTel pattern. Your agent tool calls need to be observable with the same rigor as your REST calls.</p><p>The tools exist. The patterns are proven. The only variable is whether your team adopts them systematically or continues adding complexity to a system nobody fully understands.</p><h3>Final Thought</h3><p>The best toolchain isn’t the most comprehensive one. It’s the one your team actually uses, trusts, and maintains. Start small, automate aggressively, and make each tool earn its place in your CI pipeline before adding the next one.</p><p>The goal isn’t a perfect developer experience on paper. It’s software that ships safely, performs reliably, and can be understood by the next engineer who inherits it.</p><p><em>If this was useful, follow for more guides on distributed systems, inner-source architecture, and engineering standards for Java teams. Questions or tool recommendations? Drop them in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f4b4753a28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CodeGraph + MCP: Turning Your Microservices Into a Living, Queryable Map]]></title>
            <link>https://medium.com/@easwaranvijayakumar/codegraph-mcp-turning-your-microservices-into-a-living-queryable-map-8f7d9e813f3e?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7d9e813f3e</guid>
            <category><![CDATA[codegraph]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 23:40:17 GMT</pubDate>
            <atom:updated>2026-08-09T23:40:17.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tfxzuzWd1vuHmfB36Ur-w.png" /></figure><p><em>How a local knowledge graph can show your AI agent — and you — every touch point between services, databases, and event streams.</em></p><h3>The problem nobody talks about</h3><p>Every team with more than three microservices eventually hits the same wall: nobody can answer “what breaks if I change this?” with confidence anymore.</p><p>The order service publishes an event. Something downstream consumes it — maybe billing, maybe notifications, maybe both. A shared library gets a minor version bump and three unrelated repos start failing in staging. The person who could once hold the whole system in their head left the company eighteen months ago.</p><p>AI coding agents don’t fix this by default — they make it worse in a subtle way. Ask an agent to trace a code path across services and it starts grepping, opening files, guessing at naming conventions, and burning your token budget rediscovering structure it should already know. It has no memory of the system between sessions.</p><p>This is the gap CodeGraph is built to close.</p><h3>What CodeGraph actually is</h3><p>CodeGraph is a local-first MCP (Model Context Protocol) server. It parses your codebase with tree-sitter, extracts functions, classes, imports, call chains, and HTTP routes, and stores all of it in a single SQLite database sitting next to your project. Once indexed, it exposes that structure through a set of typed MCP tools — search, callers, callees, impact analysis, route tracing — that any MCP-compatible agent (Claude Code, Cursor, Codex, and others) can query directly instead of reading files one by one.</p><p>Worth being precise about what it is <em>not</em>: CodeGraph is not a visualization dashboard out of the box. It’s a query layer. The graph exists as rows in SQLite, not as a picture on a screen. If you want a visual map — which is exactly what an IQ Agent setup needs — you build that layer on top, and that’s the part worth getting right.</p><h3>Why this matters more once you cross service boundaries</h3><p>Inside a single repo, tree-sitter parsing gets you most of the way there — it sees every function call and import directly in the syntax tree. The moment you cross a service boundary, the relationship stops being explicit in any one file. A few examples of what actually connects your systems:</p><ul><li><strong>Database tables.</strong> Service A writes to orders, Service B reads from it through a replica. Nothing in either repo&#39;s AST says so — the connection lives in a migration file, an ORM model, or a schema doc.</li><li><strong>Event topics and queues.</strong> A Kafka producer in the checkout service and three consumers scattered across billing, shipping, and analytics all reference the same topic name as a string literal.</li><li><strong>Shared internal packages.</strong> A common auth library, a proto file, an OpenAPI spec — these are the connective tissue tree-sitter can actually trace, because they’re literal shared references.</li></ul><p>A useful cross-system graph treats these as first-class edge types — WRITES_TO, PUBLISHES, CONSUMES, IMPORTS — not just function calls. That distinction is what turns &quot;a graph of my code&quot; into &quot;a map of my system.&quot;</p><h3>The shape of the setup</h3><p>For separate repos feeding one shared picture, the practical architecture looks like this:</p><ol><li><strong>Index each service independently.</strong> CodeGraph runs per-repo, indexing code into its own local SQLite file. This keeps indexing fast and keeps each service’s graph accurate to its own codebase.</li><li><strong>Extract the cross-cutting references.</strong> Alongside code, feed in your OpenAPI specs, proto files, and any schema or event-contract definitions. These become the nodes that let two otherwise-unconnected repos share an edge.</li><li><strong>Merge into one combined view.</strong> A small script — NetworkX in Python is enough — walks each service’s exported graph and stitches nodes together wherever they reference the same table name, topic name, or shared package. This combined graph is what actually answers “what touches what.”</li><li><strong>Re-run on every push.</strong> Since CodeGraph’s file watchers and incremental indexing keep each service’s graph current in seconds, chaining the merge step after a git hook keeps the combined view fresh without a full rebuild.</li></ol><h3>How to actually see it</h3><p>This is the part CodeGraph leaves to you, so here are the three realistic paths, in order of effort:</p><p><strong>1. Query it as text first.</strong> Before reaching for a visual, CodeGraph’s own tools — explore, impact, status — return structured results you can read directly. For a quick &quot;what does this touch,&quot; this is often faster than opening a graph at all.</p><p><strong>2. Export to GraphML or Neo4j for a real visual tool.</strong> This is the most reliable path to an actual picture. Export the combined graph to GraphML and open it in Gephi or yEd for exploratory analysis, or push it into a local Neo4j instance and use Neo4j Browser or the open-source NeoDash dashboard builder to click through nodes and relationships interactively. This is heavier to set up but gives you a genuinely mature visualization tool for free.</p><p><strong>3. Build a lightweight custom HTML viewer.</strong> For something an agent can link to directly, a single-page app using vis.js or D3, reading straight from the merged graph’s JSON export, is a few hours of work and gives you full control over how nodes are colored and grouped (by service, by node type — DB, event, code, external system). This is the option that fits an MCP-driven workflow best, because it’s just a static file your server can point to.</p><h3>Wiring it into your IQ Agent over MCP</h3><p>Once the combined graph and its HTML view exist, the last step is making the agent’s MCP interactions return something a human can open, not just JSON the agent consumes silently:</p><ul><li>Serve the HTML viewer from a small local endpoint (even python -m http.server works for local use).</li><li>Have MCP tool responses include a direct link into that view, anchored to the relevant node — something like <a href="http://localhost:8000/graph.html#node=OrderService.">http://localhost:8000/graph.html#node=OrderService.</a></li><li>Keep the merge-and-regenerate step tied to your git hook, so the link is never pointing at a stale picture.</li></ul><p>The agent gets precise, low-token structural answers through MCP’s query tools. You get a page you can actually open and look at. Neither side has to compromise.</p><h3>The bigger point</h3><p>The real shift here isn’t “add a graph.” It’s moving from an AI agent that rediscovers your system from scratch every session to one with a persistent, shared, visual memory of it — one that updates itself the moment someone pushes code. That’s the difference between an agent that answers questions about your system and one that actually understands it.</p><p><em>If you’re setting this up yourself: start with a single service pair (the two most tightly coupled ones you have) before wiring in the whole fleet. It’s much easier to validate that your cross-service edges are correct — table names, topic names, shared packages — on two services than to debug a tangled graph of twenty.</em></p><p>Reference: <a href="https://github.com/colbymchenry/codegraph">https://github.com/colbymchenry/codegraph</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7d9e813f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Test Framework I Want to Build: Fewer Lines, Fewer Seconds]]></title>
            <link>https://medium.com/@easwaranvijayakumar/the-test-framework-i-want-to-build-fewer-lines-fewer-seconds-87950d12e8f4?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/87950d12e8f4</guid>
            <category><![CDATA[unit-test-framework]]></category>
            <category><![CDATA[future-technology]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[future-of-work]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Thu, 28 May 2026 11:57:55 GMT</pubDate>
            <atom:updated>2026-05-28T11:57:55.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oII7__MPrG03sFpG5aSlgw.png" /></figure><h3>Why JUnit, Spock, and Cucumber all leave something on the table — and what a JVM testing framework looks like when “terse and fast” is the default, not a config flag.</h3><p>I started with what sounded like a clean idea: a test framework you write in plain English. Something more NLP-driven than Cucumber, where one sentence covers a dozen scenarios and you barely touch code.</p><p>The more I dug in, the more the idea inverted on me. The thing I actually wanted wasn’t natural language at all. It was <strong>less ceremony and less runtime weight</strong> — fewer lines to author a test, and fewer seconds to run the whole suite. Natural language was a symptom. The disease was boilerplate and startup cost.</p><p>This post is the design I landed on. Nothing here exists yet; it’s a target to build toward. But the principles are concrete enough to argue about, which is the point.</p><h3>Three pains that started it</h3><p>If you write tests on the JVM, you already know these.</p><p><strong>The Mockito spy dance.</strong> Declare the mock, declare the SUT, wire them with @InjectMocks, stub each dependency, verify the ones that matter. A twelve-line preamble before the test does anything interesting.</p><p><strong>Spock can’t mock everything.</strong> Spock’s Mock() is subclass-based, so final classes and static methods — half the JDK and plenty of libraries — slip through its fingers. You drop back to Mockito-inline anyway.</p><p><strong>@SpringBootTest starts a server per test class.</strong> Ten controllers, ten integration test classes, ten context startups. Philip Riecker, who has written more about Spring test performance than almost anyone, pegs context startup at <em>20 to 45 seconds per test class</em> and describes a real suite going from 25 minutes down to 9 once the context cache was actually hitting. That&#39;s not a micro-optimization. That&#39;s your CI bill.</p><p>None of these are language problems. They’re <strong>defaults</strong> problems. The fast path exists in every case — it’s just buried under configuration that most teams never get around to.</p><h3>The reframe: pay at build time, run at native speed</h3><p>Here’s the move that makes the whole thing work. Anything slow or clever — assertion introspection, data-table expansion, even an LLM translating English into a test — happens at <strong>build time</strong>. The runtime is plain, deterministic, compiled JVM code with zero magic in the hot path.</p><p>This is why “natural language testing” usually fails: tools like ZeroStep or Auto-Playwright call an LLM <em>during the test run</em>, which buys you flexibility and pays for it in flakiness, latency, and cost. Move that call to compile time — translate the English into a real test file, commit it, run it forever after with no model in the loop — and you keep the ergonomics while throwing away the non-determinism. Karate proved a milder version of this years ago: it killed Cucumber’s step-definition glue not with AI, but by shipping built-in steps so there was nothing to wire up.</p><p>So the framework’s spine is:</p><ul><li>Build on the <strong>JUnit Platform</strong> as a custom TestEngine. This is the path Spock, Kotest, and jqwik all took. You write a few hundred lines of engine code and inherit IDE integration, Gradle/Maven support, reporting, and coexistence with existing JUnit tests — all free.</li><li><strong>Power assertions always on</strong>, via a Kotlin compiler plugin, so a failing a == b diagrams every sub-expression&#39;s value with no assertThat ceremony.</li><li><strong>Auto-mocking by default</strong> — the SUT is constructed, its dependencies are auto-mocked as strict doubles, and you bind only the ones you care about.</li><li><strong>Spring slice and context-cache selection done for you</strong> — read the spec, pick the narrowest slice, share one cached context across everything that can share it.</li></ul><h3>What it would look like</h3><p>Proposed syntax — illustrating the design, not a shipping product.</p><p><strong>API level.</strong> OpenAPI grounds the oracle, so status, content-type, and response schema are asserted implicitly. You write only the delta:</p><pre>apiSpec(&quot;orders&quot;) {<br>    &quot;creating an order returns 201 and a valid body&quot; {<br>        post(&quot;/orders&quot;) body { customerId = 42; items = [&quot;sku-1&quot;] }<br>        expect { response.id != null }<br>    }<br>}</pre><p><strong>Unit level, as a property</strong> — one line, roughly a thousand generated cases, automatic shrinking on failure:</p><pre>property(&quot;reversing twice is identity&quot;) { forAll(strings) -&gt;<br>    it.reverse().reverse() == it<br>}</pre><p><strong>Component level with auto-mocking</strong> — the whole declare-mock-inject preamble collapses into autoSpec:</p><pre>componentSpec {<br>    val sut = autoSpec&lt;OrderService&gt;()   // deps auto-mocked, strict<br>    &quot;charges the customer when stock exists&quot; expect {<br>        given { sut.inventory.has(&quot;sku-1&quot;) returns true }<br>        sut.place(Order(&quot;sku-1&quot;))<br>        verify { sut.payments.charge(any()) }<br>    }<br>}</pre><p>The honest wrinkle: Kotlin can’t quite match Groovy’s a | b || c data tables for visual cleanliness, which is exactly why a Groovy front-door is worth keeping for the Spock crowd.</p><h3>The part that actually saves you money</h3><p>Terser unit tests are nice. The real win is at the integration layer, and it’s about resources, not characters.</p><p>Make the framework <strong>read the spec and pick the narrowest Spring slice automatically</strong> — controllers referenced means @WebMvcTest, repository calls mean @DataJpaTest, plain POJOs mean no Spring at all. Schwenke measured a slice at 3.7 seconds against 7.5 for a full context with MockMvc. Multiply across a suite and the difference is the whole point.</p><p>Then make resource sharing the default: one singleton Testcontainer per JVM started in a static initializer (not the per-class @Container annotation, which quietly breaks sharing), withReuse(true) so it survives across builds, and a hard rule against @DirtiesContext and per-test @MockBean combinations — the two things that silently blow up the context cache. The framework should <strong>fail the build</strong> the moment you introduce a cache-busting pattern, naming the offending bean, instead of letting you discover it as a slow wall-clock six months later.</p><h3>Where I’d start</h3><p>Not with unit tests. With <strong>API tests</strong> — the payoff per line is highest, the OpenAPI oracle does most of the asserting for you, and the per-test resource saving (one cached context instead of N servers) is enormous. Slice-level component tests come second. The compiler-plugin-heavy unit-level magic comes last, because it’s the hardest to build and the smallest per-test win.</p><h3>A few things I won’t pretend about</h3><ul><li>None of this exists yet. It’s a blueprint.</li><li>The dramatic Spring timing numbers come from experienced practitioners’ write-ups, not controlled benchmarks — directionally solid, not gospel.</li><li>jqwik, the obvious property-testing dependency, is in maintenance mode, so you’d plan to vendor in its core eventually.</li><li>LLM-generated tests are brittle under code changes; grounding them in a stable spec (OpenAPI, schemas) rather than the implementation is what keeps that manageable.</li><li>Mockito-inline still trips over some GraalVM and JDK combinations, so graceful degradation isn’t optional.</li></ul><p>The thesis underneath all of it is simple: every existing framework <em>can</em> be terse and fast. They just make you opt in, repeatedly, by hand. Flip the defaults — pay at build time, share resources unless told otherwise, let the spec own the boring assertions — and you get a framework that’s lighter to write and cheaper to run without inventing a new language to do it.</p><p>If you build it, send me the repo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87950d12e8f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable Enterprise MCP Server with Spring Boot AI]]></title>
            <link>https://medium.com/@easwaranvijayakumar/building-a-scalable-enterprise-mcp-server-with-spring-boot-ai-de7dd68bd2cd?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/de7dd68bd2cd</guid>
            <category><![CDATA[mcp-registry]]></category>
            <category><![CDATA[sse-stream]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 02:13:34 GMT</pubDate>
            <atom:updated>2026-04-23T02:13:34.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bymlp9-WbmaiSktS3eMsng.png" /></figure><blockquote><em>A production-grade Model Context Protocol server using Java 21 virtual threads, SSE streaming, dynamic tool registration, and a centralized MCP registry — built for enterprise teams.</em></blockquote><p><strong>Enterprise AI Engineering</strong> · Spring Boot AI Series · April 2026 · ⏱ 18 min read</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/0*eZVLdtKBpvoNudxo" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/58/0*vM38IBnGQm4UNtrb" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/0*mq60o6fcCCU_FD9z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/0*qjbACe_ZMWIfW7KK" /></figure><h3>Introduction</h3><p>The <strong>Model Context Protocol (MCP)</strong> is quickly becoming the standard interface between AI models and enterprise tools. Think of it as a universal adapter — Claude (or any MCP-compatible AI) connects to your MCP server, which exposes tools and resources, and the AI can then act on your internal systems in a secure, governed way.</p><p>In this post, we’ll build a <strong>production-grade MCP server</strong> from scratch using <strong>Spring Boot 3.4 + Spring AI</strong> and <strong>Java 21</strong>, featuring:</p><ul><li>SSE (Server-Sent Events) transport for seamless persistent connections</li><li>Dynamic tool and resource registration</li><li>Multi-tenant tool scoping with RBAC</li><li>A self-registering MCP Registry for discoverability</li><li>Virtual threads (Java 21) for massive I/O concurrency</li></ul><blockquote><em>“MCP turns your enterprise systems into an AI-native API surface — without rewriting anything. The server is the glue, and Spring Boot is the best glue in the Java ecosystem.”</em></blockquote><h3>Architecture Overview</h3><pre>┌─────────────┐     SSE      ┌────────────────────────────────────┐<br>│  Claude AI  │─────────────►│        Spring Boot MCP Server      │<br>│  MCP Client │◄─────────────│                                    │<br>└─────────────┘  streaming   │  ┌──────────────────────────────┐  │<br>                             │  │   SSE Transport Layer        │  │<br>                             │  ├──────────────────────────────┤  │<br>                             │  │   Tool Registry              │  │<br>                             │  ├──────────────────────────────┤  │<br>                             │  │   Resource Manager           │  │<br>                             │  ├──────────────────────────────┤  │<br>                             │  │   Auth / RBAC Filter         │  │<br>                             │  └──────────────────────────────┘  │<br>                             │  Java 21 Virtual Threads 🚀        │<br>                             └──────────────┬─────────────────────┘<br>                                            │ tool dispatch<br>                          ┌─────────────────┼─────────────────┐<br>                          │                 │                 │<br>                          ▼                 ▼                 ▼<br>                   ┌────────────┐   ┌────────────┐   ┌─────────────┐<br>                   │ DB Tool    │   │ REST Tool  │   │ Kafka Tool  │<br>                   │ JPA/JDBC   │   │ WebClient  │   │  Events     │<br>                   └────────────┘   └────────────┘   └─────────────┘<br>                          │                                   │<br>                          ▼                                   ▼<br>                   ┌────────────┐                   ┌─────────────┐<br>                   │ File Res.  │                   │ MCP Registry│<br>                   │ S3/Local   │                   │ Discovery   │<br>                   └────────────┘                   │ Heartbeat   │<br>                                                    └─────────────┘</pre><p><strong>Key design goals:</strong></p><ul><li>The MCP server is <strong>stateless</strong> — scale horizontally behind a load balancer</li><li>Each SSE connection runs on a <strong>Java 21 virtual thread</strong> (near-zero overhead)</li><li>All tool calls pass through an <strong>RBAC filter</strong> before execution</li><li>On startup, the server <strong>self-registers</strong> with a central MCP Registry</li></ul><h3>Why Java 21? Virtual Threads are a Game Changer</h3><p>Traditional Spring Boot servers use platform threads. Each SSE connection holds a thread open for its lifetime. With 10,000 concurrent Claude sessions, you’d need 10,000 platform threads — each consuming ~1MB of stack. That’s <strong>10GB just in threads</strong>.</p><p><strong>Java 21 Virtual Threads</strong> (Project Loom) solves this. A virtual thread is lightweight — thousands can run on a handful of carrier threads. SSE connections become essentially free.</p><h3>Java 17 vs Java 21 Comparison</h3><p>Feature Java 17 (LTS) Java 21 (LTS) Impact for MCP Virtual Threads Preview only ✅ GA (stable) Critical — SSE concurrency Structured Concurrency ❌ ✅ Preview Cleaner async tool chaining Pattern Matching (switch) Partial ✅ Full GA Cleaner resource routing Record Patterns ❌ ✅ GA Concise tool result destructuring String Templates ❌ Preview Cleaner tool descriptions Enterprise Support ✅ Wide adoption ✅ Growing fast Both viable; 21 preferred</p><blockquote><strong><em>✅ Recommendation:</em></strong><em> Use </em><strong><em>Java 21</em></strong><em>. Virtual threads alone justify the upgrade for an MCP server — they allow tens of thousands of simultaneous SSE connections without the memory overhead of platform threads. Java 21 is an LTS release with enterprise support from all major vendors.</em></blockquote><h3>Project Setup — Maven Dependencies</h3><pre>&lt;!-- pom.xml --&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.0&lt;/version&gt;<br>&lt;/parent&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;!-- Spring AI MCP Server --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-ai-mcp-server-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;!-- WebFlux for SSE (reactive SSE transport) --&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;!-- Security for OAuth2 / JWT --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-oauth2-resource-server&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;!-- Actuator + Micrometer for observability --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;!-- Redis for caching + dedup --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>SSE Transport — Seamless Persistent Connections</h3><p>MCP uses SSE as its transport layer. The client (Claude) opens a long-lived HTTP connection; the server pushes JSON-RPC messages over it. Spring AI’s MCP starter handles the SSE lifecycle automatically — you just configure the endpoint.</p><h3>application.yml</h3><pre>spring:<br>  threads:<br>    virtual:<br>      enabled: true   # Enables virtual threads globally — Java 21+<br><br>ai:<br>    mcp:<br>      server:<br>        enabled: true<br>        name: enterprise-mcp-server<br>        version: 1.0.0<br>        transport: SSE              # Server-Sent Events transport<br>        sse-endpoint: /mcp/sse<br>        message-endpoint: /mcp/message<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: https://auth.company.internal/oauth2/issuer<br>mcp:<br>  registry:<br>    url: https://mcp-registry.company.internal<br>  server:<br>    public-url: https://enterprise-mcp.company.internal</pre><h3>SSE Connection Lifecycle</h3><pre>Client (Claude)           Auth Filter          SSE Handler         Tool Dispatch<br>      │                        │                     │                     │<br>      │── GET /mcp/sse ───────►│                     │                     │<br>      │                        │── Validate JWT ────►│                     │<br>      │                        │                     │─Register session -► │<br>      │                        │                     │                     │<br>      │◄══════════════════════════ SSE stream open ════════════════════════│<br>      │                        │                     │                     │<br>      │── tools/call ─────────────────────────────────────────────────────►│<br>      │◄══════════════════════════ stream result as SSE event ═════════════│<br>      │                        │                     │                     │<br>      │   (connection stays open · virtual thread per session)             │</pre><h3>Main Application Entry Point</h3><pre>// EnterpriseMcpServerApplication.java<br>@SpringBootApplication<br>@EnableAsync<br>@EnableScheduling<br>public class EnterpriseMcpServerApplication {<br><br>public static void main(String[] args) {<br>        SpringApplication.run(EnterpriseMcpServerApplication.class, args);<br>    }<br>    /**<br>     * Enable Java 21 Virtual Threads for the async executor.<br>     * Each SSE session and tool execution gets a lightweight virtual thread.<br>     */<br>    @Bean<br>    public AsyncTaskExecutor applicationTaskExecutor() {<br>        SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();<br>        executor.setVirtualThreads(true);  // Java 21 🚀<br>        return executor;<br>    }<br>}</pre><h3>Defining MCP Tools — @Tool Annotation</h3><p>Spring AI MCP uses the @Tool annotation to expose methods as callable tools. Every tool gets a name, description, and JSON Schema generated automatically from its parameters. Claude uses the description field to decide when to call the tool — <strong>write it like documentation for an AI, not a human</strong>.</p><h3>Example 1 — Database Query Tool</h3><pre>// DatabaseQueryTool.java<br>@Component<br>public class DatabaseQueryTool {<br>private final EmployeeRepository employeeRepo;<br>    private final AuditLogger auditLogger;<br>    @Tool(<br>        name = &quot;get_employee_details&quot;,<br>        description = &quot;&quot;&quot;<br>            Fetch an employee&#39;s details by their ID or email.<br>            Returns name, department, role, location and manager.<br>            Use this when the user asks about a specific employee.<br>            &quot;&quot;&quot;<br>    )<br>    public EmployeeDetails getEmployeeDetails(<br>            @ToolParam(description = &quot;Employee ID or corporate email address&quot;)<br>            String identifier) {<br>        auditLogger.log(&quot;get_employee_details&quot;, identifier);<br>        return employeeRepo<br>            .findByIdOrEmail(identifier)<br>            .map(EmployeeDetails::from)<br>            .orElseThrow(() -&gt; new ToolExecutionException(<br>                &quot;Employee not found: &quot; + identifier));<br>    }<br>    @Tool(<br>        name = &quot;list_team_members&quot;,<br>        description = &quot;List all members of a team or department by name&quot;<br>    )<br>    public List&lt;EmployeeSummary&gt; listTeamMembers(<br>            @ToolParam(description = &quot;Team or department name&quot;)<br>            String teamName,<br>            @ToolParam(description = &quot;Include inactive members (default: false)&quot;, required = false)<br>            Boolean includeInactive) {<br>        boolean showAll = Boolean.TRUE.equals(includeInactive);<br>        return employeeRepo.findByDepartment(teamName, showAll)<br>                           .stream()<br>                           .map(EmployeeSummary::from)<br>                           .toList();<br>    }<br>}</pre><h3>Example 2 — REST API Tool with WebClient</h3><pre>// JiraIntegrationTool.java<br>@Component<br>public class JiraIntegrationTool {<br>private final WebClient jiraClient;<br>    @Tool(<br>        name = &quot;create_jira_ticket&quot;,<br>        description = &quot;Create a Jira ticket in the specified project with a title, description and priority&quot;<br>    )<br>    public JiraTicketResponse createTicket(<br>            @ToolParam(description = &quot;Jira project key e.g. ENG, INFRA, DATA&quot;)  String projectKey,<br>            @ToolParam(description = &quot;Short, descriptive ticket title&quot;)           String title,<br>            @ToolParam(description = &quot;Detailed description of the issue or task&quot;) String description,<br>            @ToolParam(description = &quot;Priority: LOW, MEDIUM, HIGH, CRITICAL&quot;)     String priority) {<br>        var payload = Map.of(<br>            &quot;fields&quot;, Map.of(<br>                &quot;project&quot;,     Map.of(&quot;key&quot;, projectKey),<br>                &quot;summary&quot;,     title,<br>                &quot;description&quot;, description,<br>                &quot;priority&quot;,    Map.of(&quot;name&quot;, priority),<br>                &quot;issuetype&quot;,   Map.of(&quot;name&quot;, &quot;Task&quot;)<br>            )<br>        );<br>        return jiraClient.post()<br>            .uri(&quot;/rest/api/3/issue&quot;)<br>            .bodyValue(payload)<br>            .retrieve()<br>            .bodyToMono(JiraTicketResponse.class)<br>            .block();  // safe - virtual thread, not blocking a carrier thread<br>    }<br>}</pre><h3>Example 3 — DevOps Tool with Audit + Idempotency</h3><pre>// DeploymentTool.java<br>@Component<br>public class DeploymentTool {<br>private final KubernetesClient k8sClient;<br>    private final RedisTemplate&lt;String, String&gt; redis;<br>    @Tool(<br>        name = &quot;deploy_service&quot;,<br>        description = &quot;&quot;&quot;<br>            Deploy a service to a Kubernetes namespace.<br>            Specify the service name, image tag and target environment.<br>            Only available to users with role: devops-engineer or sre.<br>            &quot;&quot;&quot;<br>    )<br>    public DeploymentResult deployService(<br>            @ToolParam(description = &quot;Service name e.g. payment-service&quot;)       String serviceName,<br>            @ToolParam(description = &quot;Docker image tag e.g. v1.4.2&quot;)            String imageTag,<br>            @ToolParam(description = &quot;Target environment: staging or production&quot;) String environment) {<br>        // Idempotency key - prevent double-deploy from duplicate tool calls<br>        String idempotencyKey = &quot;deploy:%s:%s:%s&quot;.formatted(serviceName, imageTag, environment);<br>        if (Boolean.TRUE.equals(redis.hasKey(idempotencyKey))) {<br>            return DeploymentResult.alreadyDeployed(serviceName, imageTag);<br>        }<br>        DeploymentResult result = k8sClient.deploy(serviceName, imageTag, environment);<br>        // Cache for 5 minutes to guard against duplicate calls<br>        redis.opsForValue().set(idempotencyKey, &quot;deployed&quot;, Duration.ofMinutes(5));<br>        return result;<br>    }<br>}</pre><h3>Exposing MCP Resources</h3><p>Beyond tools (actions), MCP also supports <strong>Resources</strong> — read-only data sources that Claude can access to enrich its context. Think runbooks, configuration files, documentation pages, or API specs.</p><pre>// EnterpriseResourceProvider.java<br>@Component<br>public class EnterpriseResourceProvider implements McpResourceProvider {<br>private final ConfluenceClient confluenceClient;<br>    private final S3Client s3;<br>    @Override<br>    public List&lt;McpResource&gt; listResources() {<br>        return List.of(<br>            McpResource.of(<br>                &quot;confluence://runbooks&quot;,<br>                &quot;Engineering Runbooks&quot;,<br>                &quot;All operational runbooks from Confluence&quot;,<br>                &quot;text/markdown&quot;<br>            ),<br>            McpResource.of(<br>                &quot;s3://company-docs/api-specs&quot;,<br>                &quot;API Specifications&quot;,<br>                &quot;OpenAPI specs for all internal services&quot;,<br>                &quot;application/json&quot;<br>            ),<br>            McpResource.of(<br>                &quot;confluence://architecture-decisions&quot;,<br>                &quot;Architecture Decision Records&quot;,<br>                &quot;ADRs documenting key system design decisions&quot;,<br>                &quot;text/markdown&quot;<br>            )<br>        );<br>    }<br>    @Override<br>    public McpResourceContent readResource(String uri) {<br>        return switch (uri) {<br>            case String u when u.startsWith(&quot;confluence://&quot;) -&gt; fetchFromConfluence(u);<br>            case String u when u.startsWith(&quot;s3://&quot;)         -&gt; fetchFromS3(u);<br>            default -&gt; throw new ResourceNotFoundException(uri);<br>        };<br>    }<br>    private McpResourceContent fetchFromConfluence(String uri) {<br>        String pageTitle = uri.replace(&quot;confluence://&quot;, &quot;&quot;);<br>        String markdown  = confluenceClient.getPageAsMarkdown(pageTitle);<br>        return McpResourceContent.text(uri, markdown);<br>    }<br>    private McpResourceContent fetchFromS3(String uri) {<br>        String[] parts  = uri.replace(&quot;s3://&quot;, &quot;&quot;).split(&quot;/&quot;, 2);<br>        String   bucket = parts[0];<br>        String   key    = parts[1];<br>        String   content = s3.getObjectAsString(bucket, key);<br>        return McpResourceContent.text(uri, content);<br>    }<br>}</pre><h3>MCP Registry — Service Discovery for AI Tools</h3><p>The MCP Registry is a centralized catalog that all MCP servers register with on startup. When Claude or another AI agent initializes, it queries the registry to discover <strong>what servers exist and what tools they expose</strong> — without hardcoding URLs.</p><blockquote><strong><em>Why a Registry?</em></strong><em> In a large enterprise, you may have dozens of MCP servers — one for HR, one for DevOps, one for Finance. Without a registry, every AI agent needs to know every server’s URL. The registry solves this with service discovery, exactly like Eureka/Consul does for microservices.</em></blockquote><h3>Architecture</h3><pre>MCP Server (HR)     ──register──►<br>MCP Server (DevOps) ──register──►  MCP Registry  ◄── Claude / AI Agent<br>MCP Server (Finance)──register──►  (Spring Boot)      &quot;which servers exist?&quot;<br>                                        │               &quot;what tools do they have?&quot;<br>                                   PostgreSQL            &quot;which server handles finance?&quot;<br>                                   (server catalog)</pre><h3>Registry Data Model</h3><pre>// McpServerRegistration.java<br>public record McpServerRegistration(<br>    String       serverId,       // &quot;hr-mcp-server&quot;<br>    String       name,<br>    String       version,<br>    String       sseEndpoint,    // &quot;https://hr-mcp.internal/mcp/sse&quot;<br>    List&lt;String&gt; teams,          // [&quot;hr-team&quot;, &quot;people-ops&quot;]<br>    List&lt;ToolMeta&gt; tools,<br>    Instant      registeredAt,<br>    Instant      lastHeartbeat,<br>    ServerStatus status          // ACTIVE, DEGRADED, OFFLINE<br>) {}<br><br>public record ToolMeta(<br>    String       name,<br>    String       description,<br>    List&lt;String&gt; requiredRoles   // [&quot;hr-admin&quot;, &quot;manager&quot;]<br>) {}</pre><h3>Self-Registration on Startup</h3><pre>// McpRegistryClient.java<br>@Component<br>@Slf4j<br>public class McpRegistryClient implements ApplicationRunner {<br>private final WebClient     registryClient;<br>    private final McpToolScanner toolScanner;<br>    @Value(&quot;${mcp.registry.url}&quot;)<br>    private String registryUrl;<br>    @Value(&quot;${mcp.server.public-url}&quot;)<br>    private String publicUrl;<br>    @Override<br>    public void run(ApplicationArguments args) {<br>        var registration = new McpServerRegistration(<br>            &quot;enterprise-mcp-server&quot;,<br>            &quot;Enterprise MCP Server&quot;,<br>            &quot;1.0.0&quot;,<br>            publicUrl + &quot;/mcp/sse&quot;,<br>            List.of(&quot;all-teams&quot;),<br>            toolScanner.discoverTools(),   // scans @Tool beans at runtime<br>            Instant.now(),<br>            Instant.now(),<br>            ServerStatus.ACTIVE<br>        );<br>        registryClient.post()<br>            .uri(&quot;/registry/servers&quot;)<br>            .bodyValue(registration)<br>            .retrieve()<br>            .toBodilessEntity()<br>            .subscribe(<br>                r  -&gt; log.info(&quot;✅ Registered with MCP Registry at {}&quot;, registryUrl),<br>                ex -&gt; log.error(&quot;❌ Registry registration failed: {}&quot;, ex.getMessage())<br>            );<br>        startHeartbeat();<br>    }<br>    @Scheduled(fixedDelay = 30_000)  // heartbeat every 30 seconds<br>    public void startHeartbeat() {<br>        registryClient.put()<br>            .uri(&quot;/registry/servers/enterprise-mcp-server/heartbeat&quot;)<br>            .retrieve()<br>            .toBodilessEntity()<br>            .subscribe(<br>                r  -&gt; log.debug(&quot;💓 Heartbeat sent&quot;),<br>                ex -&gt; log.warn(&quot;⚠️ Heartbeat failed: {}&quot;, ex.getMessage())<br>            );<br>    }<br>}</pre><h3>Registry Server — Tool Discovery API</h3><pre>// McpRegistryController.java<br>@RestController<br>@RequestMapping(&quot;/registry&quot;)<br>public class McpRegistryController { private final McpRegistryService registry;<br>    /** Register or update a server */<br>    @PostMapping(&quot;/servers&quot;)<br>    public ResponseEntity&lt;Void&gt; register(@RequestBody McpServerRegistration reg) {<br>        registry.register(reg);<br>        return ResponseEntity.ok().build();<br>    }<br>    /** Discover all servers accessible to a team */<br>    @GetMapping(&quot;/servers&quot;)<br>    public List&lt;McpServerRegistration&gt; discover(<br>            @RequestParam(&quot;team&quot;) String team,<br>            @RequestParam(value = &quot;status&quot;, defaultValue = &quot;ACTIVE&quot;) String status) {<br>        return registry.findByTeamAndStatus(team, ServerStatus.valueOf(status));<br>    }<br>    /** Search tools by keyword across all registered servers */<br>    @GetMapping(&quot;/tools&quot;)<br>    public List&lt;ToolWithServer&gt; searchTools(@RequestParam String query) {<br>        return registry.searchTools(query);<br>    }<br>    /** Health heartbeat from registered servers */<br>    @PutMapping(&quot;/servers/{id}/heartbeat&quot;)<br>    public void heartbeat(@PathVariable String id) {<br>        registry.updateHeartbeat(id);<br>    }<br>    /** Deregister on graceful shutdown */<br>    @DeleteMapping(&quot;/servers/{id}&quot;)<br>    public void deregister(@PathVariable String id) {<br>        registry.deregister(id);<br>    }<br>}</pre><h3>McpToolScanner — Auto-Discover @Tool Beans</h3><pre>// McpToolScanner.java<br>@Component<br>public class McpToolScanner {<br>private final ApplicationContext context;<br>    /**<br>     * Scans all Spring beans for @Tool annotated methods at runtime.<br>     * Returns metadata for registry registration.<br>     */<br>    public List&lt;ToolMeta&gt; discoverTools() {<br>        return context.getBeansWithAnnotation(Component.class)<br>            .values()<br>            .stream()<br>            .flatMap(bean -&gt; Arrays.stream(bean.getClass().getMethods()))<br>            .filter(method -&gt; method.isAnnotationPresent(Tool.class))<br>            .map(method -&gt; {<br>                Tool annotation = method.getAnnotation(Tool.class);<br>                return new ToolMeta(<br>                    annotation.name(),<br>                    annotation.description(),<br>                    resolveRequiredRoles(method)<br>                );<br>            })<br>            .toList();<br>    }<br>    private List&lt;String&gt; resolveRequiredRoles(Method method) {<br>        RequiresRole rolesAnnotation = method.getAnnotation(RequiresRole.class);<br>        return rolesAnnotation != null<br>            ? List.of(rolesAnnotation.value())<br>            : List.of();<br>    }<br>}</pre><h3>RBAC — Role-Scoped Tool Access</h3><p>Not all tools should be accessible to all users. A junior developer shouldn’t be able to trigger production deployments. RBAC is enforced as a filter in the MCP tool dispatch pipeline — <strong>before</strong> the tool method is ever invoked.</p><pre>// McpToolAuthorizationFilter.java<br>@Component<br>@Order(1)<br>public class McpToolAuthorizationFilter implements McpToolFilter {<br>private final ToolPermissionRepository permissions;<br>    private final AuditLogger auditLogger;<br>    @Override<br>    public void beforeToolExecution(<br>            McpToolContext context,<br>            String toolName,<br>            Map&lt;String, Object&gt; args) {<br>        UserPrincipal user    = context.getPrincipal();<br>        Set&lt;String&gt; required  = permissions.getRequiredRoles(toolName);<br>        boolean authorized = required.isEmpty()<br>            || user.getRoles().stream().anyMatch(required::contains);<br>        if (!authorized) {<br>            // Log the denied attempt<br>            auditLogger.recordDenied(user, toolName, args);<br>            throw new McpAccessDeniedException(<br>                &quot;User &#39;%s&#39; with roles %s cannot execute tool &#39;%s&#39; (requires: %s)&quot;<br>                    .formatted(user.getUsername(), user.getRoles(), toolName, required)<br>            );<br>        }<br>        // Log every authorized tool call<br>        auditLogger.record(AuditEvent.toolCall(user, toolName, args));<br>    }<br>}</pre><h3>Custom @RequiresRole Annotation</h3><pre>// Annotate tools directly with role requirements<br>@Tool(<br>    name = &quot;deploy_service&quot;,<br>    description = &quot;Deploy a service to Kubernetes&quot;<br>)<br>@RequiresRole({&quot;devops-engineer&quot;, &quot;sre&quot;})<br>public DeploymentResult deployService(String serviceName, String imageTag, String env) {<br>    // ...<br>}</pre><h3>Tool Permission Configuration (YAML)</h3><pre># tool-permissions.yml — loaded at startup<br>tool-permissions:<br>  get_employee_details:   []                         # all authenticated users<br>  list_team_members:      []<br>  deploy_service:         [devops-engineer, sre]     # restricted<br>  create_jira_ticket:     [developer, manager]<br>  approve_expense:        [manager, finance-admin]<br>  run_production_query:   [dba, data-engineer]<br>  delete_resource:        [admin]</pre><h3>Observability — Traces, Metrics, Audit Log</h3><pre>// McpMetricsConfig.java<br>@Configuration<br>public class McpMetricsConfig {<br>@Bean<br>    public ObservationHandler&lt;McpToolObservation&gt; mcpToolObservationHandler(<br>            MeterRegistry registry) {<br>        return observation -&gt; {<br>            String tool = observation.getToolName();<br>            String team = observation.getTeam();<br>            // Count total invocations per tool + team<br>            Counter.builder(&quot;mcp.tool.calls&quot;)<br>                .tag(&quot;tool&quot;, tool)<br>                .tag(&quot;team&quot;, team)<br>                .register(registry)<br>                .increment();<br>            // Track execution latency<br>            Timer.builder(&quot;mcp.tool.latency&quot;)<br>                .tag(&quot;tool&quot;, tool)<br>                .register(registry)<br>                .record(observation.getDuration(), TimeUnit.MILLISECONDS);<br>            // Track errors separately for alerting<br>            if (observation.hasError()) {<br>                Counter.builder(&quot;mcp.tool.errors&quot;)<br>                    .tag(&quot;tool&quot;, tool)<br>                    .tag(&quot;error&quot;, observation.getErrorType())<br>                    .register(registry)<br>                    .increment();<br>            }<br>        };<br>    }<br>}</pre><h3>Audit Log Schema</h3><pre>// AuditEvent.java<br>public record AuditEvent(<br>    String    eventId,        // UUID<br>    String    userId,<br>    String    userEmail,<br>    Set&lt;String&gt; userRoles,<br>    String    toolName,<br>    Map&lt;String, Object&gt; args, // sanitized — no secrets<br>    Instant   timestamp,<br>    Duration  executionTime,<br>    String    outcome,        // SUCCESS, DENIED, ERROR<br>    String    errorMessage<br>) {<br>    public static AuditEvent toolCall(UserPrincipal user, String tool, Map&lt;String, Object&gt; args) {<br>        return new AuditEvent(<br>            UUID.randomUUID().toString(),<br>            user.getId(), user.getEmail(), user.getRoles(),<br>            tool, sanitize(args),<br>            Instant.now(), null, &quot;IN_PROGRESS&quot;, null<br>        );<br>    }<br>}</pre><h3>Docker + Kubernetes Deployment</h3><h3>Dockerfile</h3><pre># Dockerfile<br>FROM eclipse-temurin:21-jre-alpine AS runtime<br><br>WORKDIR /app<br>COPY target/enterprise-mcp-server.jar app.jar<br># Enable virtual threads JVM flags<br>ENV JAVA_OPTS=&quot;-XX:+UseZGC -Xmx512m --enable-preview&quot;<br>EXPOSE 8080<br>ENTRYPOINT [&quot;sh&quot;, &quot;-c&quot;, &quot;java $JAVA_OPTS -jar app.jar&quot;]</pre><h3>Kubernetes Deployment</h3><pre># k8s/deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: enterprise-mcp-server<br>  namespace: ai-platform<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: enterprise-mcp-server<br>  template:<br>    spec:<br>      containers:<br>        - name: mcp-server<br>          image: company/enterprise-mcp-server:1.0.0<br>          ports:<br>            - containerPort: 8080<br>          env:<br>            - name: SPRING_PROFILES_ACTIVE<br>              value: production<br>            - name: MCP_REGISTRY_URL<br>              value: https://mcp-registry.company.internal<br>          resources:<br>            requests:<br>              memory: &quot;256Mi&quot;<br>              cpu: &quot;250m&quot;<br>            limits:<br>              memory: &quot;512Mi&quot;<br>              cpu: &quot;1000m&quot;<br>          readinessProbe:<br>            httpGet:<br>              path: /actuator/health/readiness<br>              port: 8080<br>            initialDelaySeconds: 10<br>            periodSeconds: 5<br>          livenessProbe:<br>            httpGet:<br>              path: /actuator/health/liveness<br>              port: 8080<br>            initialDelaySeconds: 30<br>            periodSeconds: 10<br><br>---<br># Horizontal Pod Autoscaler - scale on SSE connection count<br>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: mcp-server-hpa<br>  namespace: ai-platform<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: enterprise-mcp-server<br>  minReplicas: 2<br>  maxReplicas: 20<br>  metrics:<br>    - type: Pods<br>      pods:<br>        metric:<br>          name: mcp_sse_active_connections<br>        target:<br>          type: AverageValue<br>          averageValue: &quot;500&quot;   # scale up when avg &gt; 500 SSE conns per pod</pre><h3>Phased Rollout Plan</h3><h3>Phase 1 — Foundation (Week 1–2)</h3><p><strong>Goal:</strong> Get Claude talking to your first tool over SSE.</p><ul><li>Spring Boot MCP server with SSE transport configured</li><li>5–10 core tools (DB query, Jira, Confluence search)</li><li>JWT authentication filter</li><li>Basic audit logging to a database table</li><li>Local Docker Compose setup for development</li></ul><p><strong>Success metric:</strong> Claude successfully calls get_employee_details and returns real data.</p><h3>Phase 2 — Governance (Week 3–4)</h3><p><strong>Goal:</strong> Make it safe for enterprise use.</p><ul><li>RBAC filter with @RequiresRole annotation</li><li>Per-team tool scoping</li><li>Rate limiting per user and per tool (Bucket4j)</li><li>Dead-letter handling for failed tool calls</li><li>Micrometer metrics dashboard (Grafana)</li></ul><p><strong>Success metric:</strong> Unauthorized tool call is blocked, logged, and alerted.</p><h3>Phase 3 — Registry (Week 5–6)</h3><p><strong>Goal:</strong> Multi-server discoverability.</p><ul><li>Deploy MCP Registry service (separate Spring Boot app)</li><li>All MCP servers self-register on startup</li><li>30-second heartbeat + automatic OFFLINE marking</li><li>Claude discovers available servers via registry at session start</li></ul><p><strong>Success metric:</strong> Second MCP server (e.g., DevOps tools) appears in registry without touching the HR server.</p><h3>Phase 4 — Scale (Week 7–8)</h3><p><strong>Goal:</strong> Production-grade reliability.</p><ul><li>Kubernetes deployment with HPA</li><li>Redis cache for read-only tool responses (TTL per tool type)</li><li>OpenTelemetry distributed tracing (trace AI → MCP → tool → DB)</li><li>Chaos testing — verify graceful degradation when tools fail</li></ul><p><strong>Success metric:</strong> 1,000 concurrent SSE connections with &lt; 50ms p99 tool dispatch latency.</p><h3>Phase 5 — Self-Serve (Month 2+)</h3><p><strong>Goal:</strong> Every team can publish their own tools.</p><ul><li>Internal @McpTool SDK — teams drop a JAR dependency and annotate methods</li><li>Tool marketplace UI — browse all tools across all servers</li><li>Cost attribution per team per tool call</li><li>Auto-generated documentation portal from @Tool descriptions</li></ul><p><strong>Success metric:</strong> HR team ships a new tool without opening a ticket to the platform team.</p><h3>Complete Tech Stack</h3><p>Layer Technology Why <strong>Runtime</strong> Java 21 + Virtual Threads SSE concurrency at massive scale <strong>Framework</strong> Spring Boot 3.4 + Spring AI MCP server starter, mature ecosystem <strong>Transport</strong> SSE via WebFlux Persistent, real-time streaming to Claude <strong>Auth</strong> Spring Security + OAuth2/JWT Enterprise SSO integration (Okta, LDAP) <strong>Registry</strong> Spring Boot service + PostgreSQL Tool discovery, heartbeat, catalog <strong>Cache</strong> Redis (Spring Cache) Tool response caching, idempotency keys <strong>Observability</strong> Micrometer + OpenTelemetry Traces, metrics, audit log <strong>Container</strong> Docker + Kubernetes (EKS/GKE) Horizontal scaling, health checks <strong>Secrets</strong> HashiCorp Vault / AWS Secrets Manager Tool credentials at runtime <strong>Build</strong> Maven 3.9 + GraalVM (optional) Fast startup with native image</p><h3>Key Principles Summary</h3><pre>┌─────────────────────────────────────────────────────────┐<br>│              Enterprise MCP Server Principles            │<br>├─────────────────────────────────────────────────────────┤<br>│  1. STATELESS      Scale horizontally. No session state  │<br>│                    on the server — all state in Redis.   │<br>│                                                          │<br>│  2. IDEMPOTENT     Every tool call is safe to retry.     │<br>│                    Use idempotency keys in Redis.        │<br>│                                                          │<br>│  3. AUDITED        Every tool call logged with user,     │<br>│                    args (sanitized), outcome, duration.  │<br>│                                                          │<br>│  4. GOVERNED       RBAC before every tool execution.     │<br>│                    Deny by default, allow by role.       │<br>│                                                          │<br>│  5. OBSERVABLE     Metrics + traces on every tool call.  │<br>│                    Alert on errors, latency, rate spikes.│<br>│                                                          │<br>│  6. DISCOVERABLE   Self-register with MCP Registry.      │<br>│                    Clients find servers dynamically.     │<br>└─────────────────────────────────────────────────────────┘</pre><h3>Conclusion</h3><p>Building an enterprise MCP server isn’t just about writing @Tool methods. The <strong>SSE transport</strong> ensures Claude maintains a seamless persistent connection. <strong>Java 21 virtual threads</strong> make that scalable to thousands of concurrent sessions without tuning thread pools. The <strong>MCP Registry</strong> turns a single server into a discoverable, self-managing platform.</p><p>Most importantly, treating the MCP server as a <strong>platform product</strong> — with a registry, RBAC governance, observability, and a developer SDK — transforms it from a prototype into infrastructure your entire enterprise can build AI capabilities on top of.</p><blockquote><em>Start with one SSE endpoint and three tools. Add the registry in week two. By month two, every team in your org can publish their own tools without touching your core server.</em></blockquote><h3>References</h3><ul><li><a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html">Spring AI MCP Documentation</a></li><li><a href="https://modelcontextprotocol.io/specification">Model Context Protocol Specification</a></li><li><a href="https://openjdk.org/jeps/444">Java 21 Virtual Threads (JEP 444)</a></li><li><a href="https://spring.io/blog/2024/11/21/spring-boot-3-4-0-available-now">Spring Boot 3.4 Release Notes</a></li></ul><p><em>Enterprise AI Engineering · Scalable MCP Server with Spring Boot AI · April 2026</em><br> <em>All code targets Spring Boot 3.4+, Spring AI 1.0+, and Java 21. The MCP specification is evolving — check official docs for the latest API changes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de7dd68bd2cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fanout Design: One Event, Infinite Possibilities]]></title>
            <link>https://medium.com/@easwaranvijayakumar/fanout-design-one-event-infinite-possibilities-afb8a425850b?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/afb8a425850b</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[fanout-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 02:51:07 GMT</pubDate>
            <atom:updated>2026-04-22T02:51:07.700Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>How modern distributed systems broadcast a single message to thousands of consumers — without coupling, without chaos.</em></blockquote><h3>Introduction</h3><p>Imagine a busy airport departure board. When a flight is delayed, <em>every</em> screen updates — the gate, the lounges, the app, the check-in desk — all at once. Nobody waits for a chain of phone calls. The announcement goes out, and every interested party reacts independently. That is <strong>fanout</strong>.</p><p>In distributed systems, <strong>fanout</strong> is the pattern where a single published event is delivered simultaneously to multiple consumers. It is one of the foundational ideas behind event-driven architecture, and understanding it deeply separates junior engineers from senior ones.</p><blockquote><em>“A well-designed fanout system lets services evolve independently — the producer doesn’t need to know who’s listening, and listeners don’t need to coordinate with each other.”</em></blockquote><h3>The Core Mental Model</h3><p>At its heart, fanout answers one question: <strong>how do you go from 1 to N?</strong></p><p>Without fanout, you’d have a producer calling each consumer directly — tightly coupled, fragile, and slow. Add a new consumer? Modify the producer. Consumer goes down? Producer breaks. This is the anti-pattern fanout solves.</p><h3>❌ Without Fanout (Tightly Coupled)</h3><pre>Producer (Order Service)<br>    │<br>    ├──► Billing Service      (direct HTTP call)<br>    ├──► Inventory Service    (direct HTTP call)<br>    └──► Notifications Service (direct HTTP call)<br><br>Problems:<br>  ⚠ Producer knows every consumer<br>  ⚠ Sequential calls - slow<br>  ⚠ One failure can cascade<br>  ⚠ Adding consumer = modifying producer</pre><h3>✅ With Fanout (Decoupled via Broker)</h3><pre>Producer ──► [Message Broker] ──► Consumer A (own queue)<br>                              ──► Consumer B (own queue)<br>                              ──► Consumer C (own queue)<br>                              ──► Consumer D (own queue)<br><br>Benefits:<br>  ✓ Producer publishes once and forgets<br>  ✓ Consumers are fully independent<br>  ✓ Parallel processing<br>  ✓ Add new consumers with zero producer changes</pre><h3>A Real-World Example: E-Commerce Order Placed</h3><p>Let’s ground this in something concrete. You run an e-commerce platform. When a customer places an order, at least four things need to happen:</p><ol><li><strong>Charge the customer</strong> → Billing Service</li><li><strong>Reserve the item</strong> → Inventory Service</li><li><strong>Send a confirmation email</strong> → Notifications Service</li><li><strong>Record the conversion</strong> → Analytics Service</li></ol><p>These are all <em>independent reactions</em> to the same event. Fanout is the natural fit.</p><h3>Step 1 — The Order Service publishes one event</h3><pre>// Node.js — Publishing to AWS SNS<br>import { SNSClient, PublishCommand } from &quot;@aws-sdk/client-sns&quot;;<br><br>const sns = new SNSClient({ region: &quot;us-east-1&quot; });<br>async function onOrderPlaced(order) {<br>  const event = {<br>    eventType: &quot;ORDER_PLACED&quot;,<br>    orderId:   order.id,<br>    userId:    order.userId,<br>    items:     order.items,<br>    total:     order.total,<br>    timestamp: new Date().toISOString(),<br>  };<br>  await sns.send(new PublishCommand({<br>    TopicArn: process.env.ORDER_EVENTS_TOPIC_ARN,<br>    Message:  JSON.stringify(event),<br>  }));<br>  // Done. The broker handles the rest.<br>}</pre><h3>Step 2 — SNS fans out to multiple SQS queues</h3><pre># SNS Topic → SQS Subscriptions<br>OrderEventsTopic:<br>  subscribers:<br>    - BillingQueue        (SQS) → Billing Service<br>    - InventoryQueue      (SQS) → Inventory Service<br>    - NotificationsQueue  (SQS) → Email / SMS / Push<br>    - AnalyticsQueue      (SQS) → Data Warehouse</pre><p>Each service gets its own queue. A slow analytics pipeline <strong>never delays billing</strong>.</p><h3>Step 3 — Each consumer processes independently</h3><pre># Billing Service — SQS consumer (Python / boto3 style)<br>def handle_order_placed(event: dict) -&gt; None:<br>    order_id = event[&quot;orderId&quot;]<br>    total    = event[&quot;total&quot;]<br>    user_id  = event[&quot;userId&quot;]<br><br># Idempotent check - SNS may deliver more than once<br>    if billing_db.exists(order_id):<br>        return  # already charged, skip safely<br>    charge_customer(user_id, total)<br>    billing_db.record(order_id, status=&quot;charged&quot;)</pre><blockquote><strong><em>⚡ Key Principle:</em></strong><em> Every consumer must be </em><strong><em>idempotent</em></strong><em> — processing the same message twice must produce the same result as processing it once. SNS and most brokers guarantee </em>at-least-once<em> delivery, not exactly-once.</em></blockquote><h3>High-Level Design — Full E-Commerce Fanout System</h3><pre>┌─────────┐     ┌─────────────┐     ┌──────────────────┐<br>│  Client │────►│ API Gateway │────►│  Order Service   │<br>│ Browser │     │ Auth+Route  │     │  save → publish  │<br>└─────────┘     └─────────────┘     └────────┬─────────┘<br>                                             │ publish<br>                                             ▼<br>                                    ┌─────────────────┐<br>                                    │   SNS Topic     │<br>                                    │  order-events   │<br>                                    │ (fanout broker) │<br>                                    └────────┬────────┘<br>                          ┌──────────────────┼──────────────────┐<br>                          │                  │                  │                  │<br>                          ▼                  ▼                  ▼                  ▼<br>               ┌──────────────┐   ┌──────────────┐   ┌──────────────┐   ┌──────────────┐<br>               │SQS: billing  │   │SQS: inventory│   │SQS: notif   │   │SQS: analytics│<br>               │    queue     │   │    queue     │   │    queue    │   │    queue     │<br>               └──────┬───────┘   └──────┬───────┘   └──────┬──────┘   └──────┬───────┘<br>                      │                  │                  │                  │<br>                      ▼                  ▼                  ▼                  ▼<br>               ┌──────────┐      ┌──────────────┐   ┌──────────────┐   ┌──────────────┐<br>               │  Billing │      │  Inventory   │   │ Email/SMS/   │   │    Data      │<br>               │  Lambda  │      │  Service     │   │    Push      │   │  Warehouse   │<br>               └──────────┘      └──────────────┘   └──────────────┘   └──────────────┘<br><br>* Each queue has a Dead-Letter Queue (DLQ) for failed messages<br>* Orders DB (PostgreSQL) is written by Order Service before publishing</pre><h3>Three Flavors of Fanout</h3><h3>1. Push Fanout — AWS SNS → SQS</h3><p>The broker proactively <strong>pushes copies</strong> to all subscriber queues the instant a message arrives. Best for <strong>low-latency, event-driven workloads</strong> where each consumer needs its own durable buffer.</p><pre>SNS Topic<br>   ├──► SQS Queue A  (Billing)       ← each drains at its own pace<br>   ├──► SQS Queue B  (Inventory)<br>   └──► SQS Queue C  (Notifications)</pre><p><strong>Best for:</strong> Cloud-native microservices, AWS-centric architectures.</p><h3>2. Pull Fanout — Apache Kafka Consumer Groups</h3><p>The broker stores messages in <strong>durable, ordered partitions</strong>. Each consumer group independently tracks its own offset and reads at its own pace.</p><pre># Two consumer groups, one topic — both get ALL messages<br>Topic: order-events  (3 partitions)<br><br>Group: billing-service     → offsets [102, 98, 105]   (real-time)<br>Group: analytics-pipeline  → offsets [88,  76, 91]    (batch, slower)<br># Adding a new group = zero changes to topic or producer</pre><p><strong>Best for:</strong> Event sourcing, audit logs, replay, analytics pipelines.</p><h3>3. Ephemeral Fanout — Redis Pub/Sub</h3><p>Redis broadcasts to all <strong>currently connected</strong> subscribers. No queue, no persistence — if a subscriber is offline, it misses the message.</p><pre># Publisher<br>redis.publish(&quot;live-scores&quot;, json.dumps({&quot;match&quot;: &quot;LAL vs GSW&quot;, &quot;score&quot;: &quot;98-102&quot;}))<br><br># Subscriber (WebSocket server)<br>pubsub = redis.pubsub()<br>pubsub.subscribe(&quot;live-scores&quot;)<br>for message in pubsub.listen():<br>    broadcast_to_clients(message[&quot;data&quot;])</pre><p><strong>Best for:</strong> Live dashboards, chat apps, real-time game state, stock tickers.</p><h3>Comparison Table</h3><p>Technology Persistence Delivery Miss if Offline? Best For <strong>AWS SNS → SQS</strong> Queue buffer At-least-once No (queued) Cloud-native microservices <strong>Apache Kafka</strong> Log (days–∞) At-least-once No (offset) Event sourcing, replay, ETL <strong>RabbitMQ</strong> Queue (durable) At-least-once No (if durable) Task queues, RPC fanout <strong>Redis Pub/Sub</strong> None At-most-once Yes Live updates, chat, dashboards <strong>WebSocket</strong> None At-most-once Yes Browser real-time UI</p><h3>Tiered Fanout — Social Media Scale</h3><p>For massive scale (Twitter/X’s home timeline problem), a single broker can’t fan out to 50 million followers instantly. The solution is <strong>tiered fanout</strong>:</p><pre>Publisher (1 event)<br>     │<br>     ▼<br>Tier 1 Broker (Global Topic)<br>     │<br>     ├──► US-East Regional Broker ──► [User feeds × millions]<br>     ├──► EU-West Regional Broker ──► [User feeds × millions]<br>     └──► AP-South Regional Broker ──► [User feeds × millions]<br><br>Strategy: Fan out to regions first, then within each region to individual feeds.<br>High-follower accounts → pre-compute feeds (push model)<br>Low-follower accounts  → compute on-read (pull model)</pre><h3>Design Considerations You Must Get Right</h3><h3>1. Idempotency is Non-Negotiable</h3><p>All fanout brokers can deliver a message <strong>more than once</strong>. Every consumer must handle duplicates safely.</p><pre>def handle_event(event):<br>    # Always check before acting<br>    if already_processed(event[&quot;eventId&quot;]):<br>        return  # safe no-op<br><br>process(event)<br>    mark_as_processed(event[&quot;eventId&quot;])</pre><p>Use a Redis SET or DB unique constraint keyed on eventId + consumerId.</p><h3>2. Per-Consumer Queues Prevent Head-of-Line Blocking</h3><p>If all consumers share one queue, a slow consumer starves the fast ones.</p><pre>❌ Bad:  SNS → One shared queue → [Billing, Inventory, Analytics polling same queue]<br>✅ Good: SNS → Billing Queue    → Billing Service<br>              → Inventory Queue  → Inventory Service<br>              → Analytics Queue  → Analytics Service (can be slow — doesn&#39;t matter)</pre><h3>3. Dead-Letter Queues Catch Silent Failures</h3><pre>BillingQueue:<br>  maxReceiveCount: 3        # retry 3 times<br>  deadLetterTargetArn: BillingDLQ<br><br># After 3 failures, message lands in DLQ for alerting and inspection<br># Never lost, never stuck in infinite retry loop</pre><h3>4. Message Filtering Reduces Noise</h3><p>Not every consumer needs every event. Use <strong>SNS filter policies</strong> to route selectively:</p><pre>// Notifications queue only receives ORDER_PLACED, not ORDER_UPDATED<br>{<br>  &quot;eventType&quot;: [&quot;ORDER_PLACED&quot;, &quot;ORDER_CANCELLED&quot;]<br>}</pre><h3>When NOT to Use Fanout</h3><p>Fanout adds operational complexity. Don’t reach for it reflexively.</p><p>Scenario Why Fanout Doesn’t Fit Better Option Single consumer reacts Overkill Direct HTTP call Consumer B must wait for A Fanout parallelizes Pipeline / Saga Strong transaction needed No distributed tx 2PC or Outbox pattern Very low event volume Broker overhead not worth it Synchronous call Strict ordering across consumers Fanout doesn’t guarantee Single consumer + internal dispatch</p><h3>The Outbox Pattern — Reliable Fanout</h3><p>A common problem: what if the Order Service saves to DB but crashes before publishing to SNS?</p><pre>Order Service:<br>  1. BEGIN TRANSACTION<br>  2. INSERT INTO orders (...)<br>  3. INSERT INTO outbox (event_type, payload, status=&#39;pending&#39;)<br>  4. COMMIT<br><br>Outbox Worker (separate process):<br>  1. SELECT * FROM outbox WHERE status=&#39;pending&#39;<br>  2. Publish to SNS<br>  3. UPDATE outbox SET status=&#39;published&#39;<br>→ Guarantees: no event is lost even if the service crashes mid-flight</pre><h3>Summary</h3><p>Fanout is the pattern of broadcasting one event to many independent consumers through a broker. It <strong>decouples producers from consumers</strong>, enables <strong>parallel processing</strong>, and makes systems dramatically easier to extend — adding a new consumer requires zero changes to the producer.</p><p>Choose When <strong>SNS → SQS</strong> Cloud-native, AWS microservices <strong>Kafka</strong> Event replay, audit logs, big data <strong>RabbitMQ</strong> On-prem or hybrid, task queues <strong>Redis Pub/Sub</strong> Ephemeral real-time, live UI</p><p><strong>Non-negotiables in every fanout system:</strong></p><ul><li>✅ Idempotent consumers</li><li>✅ Per-consumer queues</li><li>✅ Dead-letter queues for failure handling</li><li>✅ Outbox pattern for reliable publishing</li><li>✅ Filter policies to reduce noise</li></ul><blockquote><em>Master fanout, and you have a superpower: the ability to add capabilities to a system without ever touching the thing that generates events.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb8a425850b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Windsurf’s Wave 13 Parallel Agents Eat Your Credits? The Honest Answer]]></title>
            <link>https://medium.com/@easwaranvijayakumar/does-windsurfs-wave-13-parallel-agents-eat-your-credits-the-honest-answer-ebd566381b87?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd566381b87</guid>
            <category><![CDATA[parallel-agent]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[wave-13]]></category>
            <category><![CDATA[windsurf]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 13:35:08 GMT</pubDate>
            <atom:updated>2026-04-01T13:35:08.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhbarbX4FAUVCELAL9dDaQ.png" /></figure><blockquote><em>“Parallel agents multiply your output. They also multiply your quota consumption. Here’s how to get the throughput without burning through your budget.”</em></blockquote><h3>The Feature Everyone’s Excited About</h3><p>Windsurf’s Wave 13 dropped in late December 2025 and the headline feature turned heads: <strong>true parallel multi-agent sessions</strong>. Run five Cascade agents simultaneously, each on a different bug or feature, all isolated via Git worktrees, monitored side-by-side in a multi-pane dashboard.</p><p>For engineers juggling multiple microservices — think Kafka consumers, Cassandra repositories, REST endpoints — this sounds like a dream. Spawn three agents, go grab coffee, come back to three pull requests ready for review.</p><p>But there’s a question nobody’s asking loudly enough:</p><p><strong>Does running agents in parallel cost you proportionally more quota?</strong></p><p>Yes. And the math matters.</p><h3>First, Understand How Quota Works Now</h3><p>In March 2026, Windsurf replaced its old credit system with a <strong>token-based quota model</strong>. Here’s the fundamental shift:</p><blockquote><em>Your plan includes a daily and weekly usage budget. That budget is measured in tokens — how much the model reads and writes per request. The cost per token varies by model.</em></blockquote><p>This means quota consumption is not flat per request. It scales with:</p><ul><li><strong>Model choice</strong> — SWE-1.5 (native) costs less than Claude Sonnet or GPT-5.4</li><li><strong>Context size</strong> — a few files costs less than an entire codebase scan</li><li><strong>Speed/priority mode</strong> — fast or priority processing costs 2x the standard rate</li><li><strong>Output length</strong> — generating a full service class costs more than a one-liner fix</li></ul><p>And crucially: <strong>Tab autocomplete is completely free on every plan, always.</strong> It never touches your quota. Only Cascade agent sessions and Chat with premium models draw from your daily allowance.</p><h3>So What Happens When You Run Parallel Agents?</h3><p>Simple answer: <strong>each agent burns quota independently and simultaneously.</strong></p><p>Three parallel Cascade agents = three simultaneous token streams drawing from the same daily budget.</p><p>Think of your quota like a water tank. One pipe draining it is manageable. Open three pipes at once and the tank empties three times as fast.</p><p>Scenario Quota Impact Tab autocomplete (any plan) ❌ Zero — completely free Single Cascade agent, SWE-1.5 ✅ Standard token rate Single Cascade agent, Claude Sonnet ✅ Higher token rate 3 parallel agents, all SWE-1.5 ✅ ~3x standard rate simultaneously 3 parallel agents, frontier models ✅ 3x higher rate — drains fast Priority / Fast mode on any agent ✅ 2x the standard rate on top</p><p>There is no “parallelism discount.” You are running real inference on real models, and each one costs tokens.</p><h3>The Daily Quota Problem: Burst Workers Beware</h3><p>Here’s where it gets frustrating for engineers who work in sprints.</p><p>The old credit system let you bank unused credits. Quiet day on Tuesday? Those credits rolled over. Heavy sprint on Thursday? You could burn deep into your reserve.</p><p>The new quota system resets daily and weekly regardless of what you used before. Community reaction has been blunt:</p><blockquote><em>“Daily quotas are strictly worse than credits for anyone who works in bursts. Some days I code for 14 hours straight, other days I don’t touch my editor. Credits let you bank unused time. Quotas just waste it.”</em></blockquote><p>For parallel agent workflows specifically, this is the real gotcha. A focused sprint day running three to five Cascade agents on large Spring Boot codebases — with multi-file context, Kafka schema analysis, Cassandra table design — can blow through your daily quota in a few hours. The rest of the day, you’re throttled or paying for extra usage at API list prices.</p><h3>Model Choice Is Your Most Powerful Lever</h3><p>Not all agents need frontier intelligence. This is the insight that makes parallel agent workflows financially viable.</p><p>Windsurf’s native models — <strong>SWE-1, SWE-1.5, SWE-1-mini</strong> — are purpose-built for agentic coding. They cost significantly less quota per request than third-party frontier models like Claude Sonnet or GPT-5.4, and they handle multi-file edits, test generation, and standard refactoring extremely well.</p><p>Claude Sonnet and GPT-5.4 shine when the task genuinely requires deep reasoning: complex architecture decisions, subtle concurrency bug analysis, cross-service design review. For mechanical tasks — scaffolding a new Kafka consumer, writing Spock test stubs, adding a Cassandra repository — SWE-1.5 is more than capable and costs a fraction of the quota.</p><p><strong>The strategic split for a three-agent session:</strong></p><pre>Agent 1 → SWE-1.5     Scaffold new Kafka consumer + DLQ routing<br>Agent 2 → SWE-1.5     Generate Spock test suite for the consumer<br>Agent 3 → Claude Sonnet   Architecture review + Resilience4j config</pre><p>Agents 1 and 2 do the heavy lifting at low quota cost. Agent 3 applies frontier reasoning where it actually matters. You get the throughput of parallelism without three frontier model bills running simultaneously.</p><h3>The Two-Agent Sweet Spot</h3><p>There is a cognitive argument that reinforces the financial one.</p><p>Reviewing one agent’s output requires focus. Reviewing two simultaneously is demanding but manageable — you’re essentially doing a code review across two branches. Reviewing three or more triggers real cognitive overhead: context switching between implementations, checking for inconsistencies, ensuring the eventual merge doesn’t create conflicts.</p><p>The practical recommendation that has emerged from teams using parallel agents at scale is to <strong>start with two agents, not five.</strong> Build comfort with the merge workflow. Learn where your quota goes on two sessions before adding a third.</p><p>Two parallel agents running SWE-1.5 on a standard Pro quota is a sustainable daily workflow. Five agents running frontier models is a budget event.</p><h3>What to Do When You Hit Your Daily Limit</h3><p>Windsurf’s quota system includes extra usage that kicks in after you exhaust your daily allowance. This extra usage is billed at API list prices for the model you’re using — which can add up fast if you’re in the middle of a heavy sprint.</p><p>A few practical mitigations:</p><p><strong>Use the context window indicator.</strong> Wave 13 added a visual indicator showing how much of your context window is currently in use. Longer context = more tokens per request. When the indicator climbs, consider starting a fresh Cascade session rather than continuing the same one with accumulated history.</p><p><strong>Scope your agents tightly.</strong> An agent given a specific, bounded task — “implement the DLQ routing logic in this class” — consumes far less quota than an agent given open-ended instructions on a large codebase. The more files Cascade pulls into context, the more tokens it uses before writing a single line.</p><p><strong>Reserve frontier models for review, not scaffolding.</strong> Use SWE-1.5 to generate the code. Use Claude Sonnet to review and refine it. You get the quality of frontier reasoning at a fraction of the generation cost.</p><p><strong>Lean on Cascade Hooks.</strong> Wave 13’s Cascade Hooks let you run custom commands at key points in the agent’s workflow — including after every model response. Use hooks to automatically commit working states, run tests, and log outputs. This reduces the need to re-run agents due to lost context or incomplete sessions.</p><h3>The Tier Reality Check</h3><p>Windsurf currently offers three paid tiers: $20, $40, and $200 per month.</p><p>For solo developers doing moderate parallel agent work — two agents running SWE-1.5 on bounded tasks — the $20 tier is workable but will feel tight on heavy sprint days. The $40 tier doubles the quota and unlocks SWE-1.5 Fast alongside premium model access, making it the more realistic choice for anyone treating parallel agents as a daily workflow rather than an occasional experiment.</p><p>The $200 Max tier exists for developers who run multi-hour Cascade sessions daily, regularly use frontier models on large context workloads, or were consistently buying add-on credits under the old system. For most principal engineers and senior developers using parallelism strategically rather than indiscriminately, it’s more than necessary.</p><p>One important note for existing subscribers: if you were on the $15 Pro plan before March 2026, your price is grandfathered indefinitely. You move to the new quota system but keep your original pricing.</p><h3>Applying This to a Real Microservice Sprint</h3><p>Here is how a quota-conscious parallel agent workflow looks in practice for a Spring Boot microservices team.</p><p><strong>Sprint goal:</strong> Implement a new loyalty bonus event consumer, write its full test suite, and fix an unrelated Cassandra query bug — three independent tasks.</p><p><strong>Without parallel agents (sequential):</strong></p><ul><li>Task 1 → Agent runs → Review → Merge → Task 2 → Agent runs → Review → Merge → Task 3</li><li>Total time: 3x single-task time</li><li>Quota: consumed sequentially, spread across the day</li></ul><p><strong>With parallel agents (Wave 13 workflow):</strong></p><pre>Worktree 1: feat/loyalty-bonus-consumer    → Agent: SWE-1.5<br>Worktree 2: test/loyalty-bonus-consumer    → Agent: SWE-1.5<br>Worktree 3: fix/cassandra-query-timeout    → Agent: Claude Sonnet (bug is subtle)</pre><ul><li>All three agents run simultaneously</li><li>Total time: ~1x single-task time</li><li>Quota: 3x consumed in the same window — plan accordingly</li></ul><p>The throughput gain is real. The quota cost is real. The key is knowing which tasks justify the parallel spend and which are better run sequentially on a quieter day.</p><h3>Key Takeaways</h3><p><strong>Parallel agents are not free.</strong> Each agent burns quota independently. Three agents running simultaneously is three times the token consumption in the same time window.</p><p><strong>Model selection is the biggest cost lever.</strong> SWE-1.5 for mechanical tasks. Frontier models only where reasoning depth genuinely matters.</p><p><strong>Daily quota resets hurt burst workers.</strong> If you have heavy sprint days and quiet days, the new quota system is structurally worse than the old credit system for your workflow. Plan your parallel agent sessions around your sprint calendar, not just your task list.</p><p><strong>Two agents is the practical sweet spot.</strong> Both from a quota management perspective and a cognitive review perspective. Scale up only when you have the quota headroom and the review bandwidth.</p><p><strong>Tab autocomplete is always free.</strong> Never count it against your quota math.</p><h3>What’s Coming Next</h3><p>Wave 13 is the foundation, not the ceiling. Parallel agents will become table stakes across all AI IDEs through 2026. The differentiation will shift from “can I run parallel agents” to “how well does the tool help me orchestrate them without blowing my budget.”</p><p>For engineers building on structured workflows — with skill-based archetypes, .windsurfrules contracts, and ArchUnit guardrails — parallel agents become a genuine force multiplier. The standards are already encoded. The agents follow them. The output is consistent. The only variable left to manage is quota.</p><p>And now you know exactly how to manage it.</p><p><em>Follow me for more articles on distributed systems engineering, Spring Boot architecture, and AI developer tooling. Previous articles in this series cover skill-based archetypes, Windsurf workflow automation, and engineering practices beyond AI coding tools.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd566381b87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skill-Based Archetypes in Windsurf: Your Golden Path for Features, Enhancements & Bug Fixes]]></title>
            <link>https://medium.com/@easwaranvijayakumar/skill-based-archetypes-in-windsurf-your-golden-path-for-features-enhancements-bug-fixes-f07813871ab3?source=rss-1063eb76fee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f07813871ab3</guid>
            <category><![CDATA[windsurf]]></category>
            <category><![CDATA[cascade]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vijayakumar Easwaran]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 02:10:19 GMT</pubDate>
            <atom:updated>2026-03-30T02:10:19.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BAKGP90FVKahM7sg7Biug.png" /></figure><blockquote><em>“The best engineers don’t just write good code. They build systems that make the right thing the easy thing — for themselves and their entire team.”</em></blockquote><h3>The Problem Nobody Talks About</h3><p>You’ve just been handed a new Kafka consumer story. Or a bug fix in a Cassandra repository. Or a new REST endpoint.</p><p>You open your IDE, and then… where do you start?</p><p>If you’re on a mature team, you probably have standards: package structure, naming conventions, resilience patterns, test coverage rules. But those standards live in a wiki nobody reads, or in the head of the most senior engineer who happens to be on vacation.</p><p>This is the problem that <strong>Skill-Based Archetypes in Windsurf</strong> solve.</p><h3>What Is a Skill-Based Archetype?</h3><p>In the traditional Java world, a <strong>Maven archetype</strong> is a project template — a pre-baked skeleton you stamp out when starting something new.</p><p>A <strong>Skill-Based Archetype</strong> in Windsurf takes this idea further. Instead of just generating files, it teaches the AI agent <em>how</em> your team thinks, <em>what</em> your standards are, and <em>why</em> certain decisions were made — and then applies that knowledge every time you work on a feature, enhancement, or bug fix.</p><p>Think of it as the difference between:</p><ul><li>❌ Giving someone a blank document and saying “follow our standards”</li><li>✅ Giving someone a senior engineer riding shotgun who <em>knows</em> all the standards</li></ul><p>A Skill file (.md) is that senior engineer, embedded in your workflow.</p><h3>The Architecture: How It Fits Together</h3><pre>.windsurf/<br>├── .windsurfrules                  ← Global workflow contract (9-step lifecycle)<br>└── skills/<br>    ├── microservice-archetype.md   ← Base Spring Boot service template<br>    ├── kafka-consumer-archetype.md ← Kafka consumer + DLQ + Resilience4j<br>    ├── cassandra-repo-archetype.md ← Query-driven table + repository pattern<br>    ├── rest-api-archetype.md       ← Controller + Service + OpenAPI<br>    ├── bugfix-archetype.md         ← Structured bug investigation + fix flow<br>    └── azure-integration.md        ← Key Vault + App Config + Entra ID wiring</pre><p>Each Skill file is a <strong>markdown document</strong> that Cascade reads and applies contextually. You reference it with @skill-name in your prompt, or Windsurf loads it automatically based on your .windsurfrules.</p><h3>Anatomy of a Skill File</h3><p>Every good archetype SKILL.md has five sections:</p><h3>1. Intent</h3><p><em>What problem does this archetype solve? When should it be used?</em></p><h3>2. Package &amp; File Structure</h3><p><em>The exact directory layout and naming conventions.</em></p><h3>3. Code Templates</h3><p><em>Base classes, annotations, and wiring patterns.</em></p><h3>4. Quality Gates</h3><p><em>Tests, coverage rules, architectural constraints.</em></p><h3>5. Decision Log</h3><p><em>Why these choices were made — the soul of an ADR embedded in the skill.</em></p><h3>Archetype 1: New Feature — Kafka Consumer Service</h3><p>Here’s a real-world SKILL.md for scaffolding a new Kafka consumer microservice.</p><h3>kafka-consumer-archetype.md</h3><pre># Skill: Kafka Consumer Service Archetype<br>## Intent<br>Use this skill when creating a new Kafka consumer service or adding a new<br>consumer to an existing service. Ensures consistency in error handling,<br>DLQ routing, resilience patterns, and observability across all consumers.<br>## Package Structure<br>com.company.{domain}/<br>├── consumer/<br>│   ├── {Feature}EventConsumer.java<br>│   └── {Feature}EventConsumerConfig.java<br>├── service/<br>│   └── {Feature}ProcessingService.java<br>├── model/<br>│   └── {Feature}Event.java<br>├── exception/<br>│   └── {Feature}ProcessingException.java<br>└── config/<br>    └── KafkaConsumerProperties.java<br>## Code Template<br>### Consumer Class<br>- Annotate with @KafkaListener(topics = &quot;${kafka.topic.{feature}}&quot;, groupId = &quot;${kafka.group.{feature}}&quot;)<br>- Wrap processing in Resilience4j @CircuitBreaker(name = &quot;{feature}-consumer&quot;)<br>- Use @Retry(name = &quot;{feature}-retry&quot;) for transient failures<br>- On max retries exhausted → publish to DLQ topic: {original-topic}.DLT<br>- Log MDC context: correlationId, eventType, partitionId, offset<br>### Dead Letter Queue Strategy<br>- DLQ topic naming: {original-topic}.DLT<br>- Retain original headers + add x-failure-reason, x-retry-count, x-original-timestamp<br>- DLQ consumer logs to Cassandra error_events table for replay capability<br>### Resilience4j Config (application.yml)<br>resilience4j:<br>  circuitbreaker:<br>    instances:<br>      {feature}-consumer:<br>        slidingWindowSize: 10<br>        failureRateThreshold: 50<br>        waitDurationInOpenState: 30s<br>  retry:<br>    instances:<br>      {feature}-retry:<br>        maxAttempts: 3<br>        waitDuration: 1s<br>        exponentialBackoffMultiplier: 2<br>## Quality Gates<br>- Unit tests: mock KafkaTemplate, verify DLQ publish on exception (Spock)<br>- Integration test: Testcontainers Kafka - verify full consume → process → DLQ flow<br>- ArchUnit: consumers must not directly call repositories (must go via service layer)<br>- Coverage: minimum 85% line coverage on consumer + service classes<br>## Decision Log<br>- Why Resilience4j over manual retry? Consistent circuit breaker state across all consumers.<br>- Why DLQ over discard? Enables replay without data loss for compliance-sensitive events.<br>- Why MDC logging? Distributed tracing correlation across microservice boundaries.</pre><h3>Archetype 2: Enhancement — Adding to an Existing Feature</h3><p>Enhancements are trickier than new features. You’re modifying something that already works — the risk of regression is real.</p><h3>enhancement-archetype.md</h3><pre># Skill: Feature Enhancement Archetype<br>## Intent<br>Use when modifying an existing feature - adding a field, changing business logic,<br>extending an API, or adding a new Kafka topic to an existing consumer.<br>## Pre-Enhancement Checklist (ask Cascade to verify before coding)<br>1. Identify all consumers of the class/API being modified<br>2. Check if OpenAPI spec needs updating<br>3. Check if Kafka schema (Avro/JSON Schema) needs a backward-compatible change<br>4. Identify downstream services that may be affected<br>5. Confirm database migration is backward-compatible (no column drops)<br>## Code Change Strategy<br>### For REST API Enhancement<br>- Never remove fields from response DTOs (backward compatibility)<br>- Add new fields as Optional&lt;&gt; or with sensible defaults<br>- Version the endpoint if behavior changes: /v2/{resource}<br>- Update OpenAPI @Operation and @Schema annotations<br>- Add @Deprecated on old endpoint - do not delete yet<br>### For Kafka Schema Enhancement<br>- Avro: add new field with default value (backward compatible)<br>- JSON Schema: use additionalProperties: true<br>- Test both old and new consumer versions against new schema<br>### For Cassandra Enhancement<br>- New query pattern? Add a new table (query-driven design - do not alter existing)<br>- New field? Add to UDT or as a new column with null default<br>- Run migration script in dry-run mode first<br>## Regression Safety Net<br>- Before coding: run existing test suite, capture baseline<br>- After coding: run same suite + new tests for enhancement<br>- Use @Tag(&quot;regression&quot;) on existing tests for targeted CI runs<br>## Quality Gates<br>- No reduction in existing test coverage<br>- Contract tests (Pact) pass for all downstream consumers<br>- Load test: enhancement does not degrade P99 latency by more than 5%</pre><h3>Archetype 3: Bug Fix — Structured Investigation to Resolution</h3><p>Bug fixes are where standards matter most — and are most often ignored under time pressure.</p><h3>bugfix-archetype.md</h3><pre># Skill: Bug Fix Archetype<br>## Intent<br>Ensure every bug fix follows a structured root cause → fix → verify → prevent cycle.<br>Prevents &quot;fix the symptom, miss the disease&quot; anti-pattern.<br>## Phase 1: Reproduce First (Never Skip This)<br>- Write a failing test that reproduces the bug BEFORE touching production code<br>- This becomes your permanent regression guard<br>- If you cannot write a failing test, you don&#39;t yet understand the bug<br>## Phase 2: Root Cause Investigation<br>Ask Cascade to:<br>1. Trace the call chain from symptom to origin<br>2. Check if the bug exists in multiple places (not just the reported one)<br>3. Identify if it&#39;s a data bug, logic bug, or integration bug<br>## Phase 3: Fix Strategy by Bug Type<br>### Logic Bug (wrong calculation, wrong condition)<br>- Fix in the service layer<br>- Do NOT fix in the controller or repository - wrong layer<br>- Add boundary condition tests: null, empty, max value, min value<br>### Data Bug (bad data in DB causing NPE / wrong result)<br>- Write a data migration script - fix the data, not just the code<br>- Add a validator that prevents bad data from entering again<br>- Log a warning if bad data is detected at runtime (don&#39;t silently swallow)<br>### Integration Bug (wrong Kafka message, wrong API contract)<br>- Dump the actual vs expected payload in the failing test<br>- Fix the serialization/deserialization, not the downstream handler<br>- Update Pact contract test to codify the correct contract<br>### Concurrency Bug (race condition, duplicate processing)<br>- Reproduce with a concurrent test (use CountDownLatch in JUnit)<br>- Fix with optimistic locking (@Version in JPA) or Redis distributed lock<br>- Never fix concurrency bugs with Thread.sleep() - ever<br>## Phase 4: Verification<br>- Failing test now passes ✅<br>- All existing tests still pass ✅<br>- Manually verify in dev environment with real data ✅<br>## Phase 5: Prevention<br>- Add the root cause to the team&#39;s runbook<br>- Consider adding an ArchUnit or custom lint rule to prevent recurrence<br>- If it was a data issue, add a health check endpoint that monitors for it<br>## PR Description Template<br>**Bug:** [One-line description]<br>**Root Cause:** [What actually caused it]<br>**Fix:** [What was changed and why]<br>**Tests Added:** [List new tests]<br>**Regression Risk:** [Low / Medium - explain]</pre><h3>Wiring It All Together: The .windsurfrules Contract</h3><p>Your skills become truly powerful when your .windsurfrules file auto-loads the right archetype based on what you&#39;re working on:</p><pre>WINDSURF WORKFLOW RULES<br>## Story Intake<br>When a new story/task is described:<br>1. Classify as: NEW_FEATURE | ENHANCEMENT | BUG_FIX | REFACTOR<br>2. Load the corresponding skill:<br>   - NEW_FEATURE → @microservice-archetype or @kafka-consumer-archetype<br>   - ENHANCEMENT → @enhancement-archetype<br>   - BUG_FIX → @bugfix-archetype<br>3. Generate a pre-flight checklist based on the loaded skill<br>4. Do not write any code until the checklist is reviewed<br>## Code Generation Rules<br>- Always follow the package structure defined in the active archetype skill<br>- Always generate the Spock test class alongside the implementation class<br>- Always add OpenTelemetry tracing spans to new service methods<br>- Always wire Azure App Config feature flag for new features<br>## Quality Gate Rules<br>- Before marking a task complete, verify:<br>  - ArchUnit tests pass<br>  - JaCoCo coverage ≥ 85%<br>  - No SonarQube critical issues introduced<br>  - PR description follows the template in the active archetype</pre><h3>Real-World Workflow: End to End</h3><p>Here’s how this plays out on a real story:</p><p><strong>Story:</strong> <em>“As a user, I want the loyalty points calculation to handle bonus multiplier events from the new Kafka topic </em><em>loyalty.bonus.events&quot;</em></p><p><strong>Step 1 — Cascade classifies:</strong> NEW_FEATURE → loads kafka-consumer-archetype.md</p><p><strong>Step 2 — Pre-flight checklist generated:</strong></p><ul><li>[ ] Is loyalty.bonus.events topic created in Azure Event Hubs?</li><li>[ ] Is Avro schema registered in Schema Registry?</li><li>[ ] Does this affect existing loyalty.points.events consumer?</li><li>[ ] Feature flag name for this consumer: ff.loyalty.bonus.consumer.enabled</li></ul><p><strong>Step 3 — Scaffold generated:</strong></p><pre>LoyaltyBonusEventConsumer.java<br>LoyaltyBonusEventConsumerConfig.java<br>LoyaltyBonusProcessingService.java<br>LoyaltyBonusEvent.java (Avro-generated or manual)<br>LoyaltyBonusEventConsumerSpec.groovy  ← Spock test<br>LoyaltyBonusProcessingServiceSpec.groovy</pre><p><strong>Step 4 — All Resilience4j config, DLQ routing, MDC logging, feature flag wiring applied automatically.</strong></p><p><strong>Step 5 — Quality gates verified before PR is raised.</strong></p><p>What used to take a day of setup now takes minutes — with zero standards drift.</p><h3>The Hidden Benefit: Onboarding</h3><p>Imagine joining a new team and having access to these skill files on day one.</p><p>Instead of shadowing a senior engineer for two weeks to learn “how we do things here,” you read three markdown files and you’re producing team-standard code by your second commit.</p><p>Skill-based archetypes are <strong>living documentation</strong> that actually stays current — because they’re used every day, not written once and forgotten in Confluence.</p><h3>Key Takeaways</h3><p>Traditional Approach Skill-Based Archetype Approach Standards in a wiki nobody reads Standards embedded in daily workflow Senior engineer reviews catch drift ArchUnit + Cascade prevent drift New features start from scratch New features start from a proven template Bug fixes vary by engineer Bug fixes follow a structured RCA cycle Onboarding takes weeks Onboarding takes days</p><h3>Getting Started: Your First Skill File</h3><ol><li>Pick your most common task type (Kafka consumer? REST endpoint?)</li><li>Look at your three best implementations of that pattern in your codebase</li><li>Extract the common structure, annotations, and decisions into a SKILL.md</li><li>Place it in .windsurf/skills/</li><li>Reference it in .windsurfrules for auto-loading</li><li>Iterate — let the team improve it through pull requests</li></ol><p>Start with one skill. One archetype. One golden path.</p><p>The rest follows naturally.</p><h3>What’s Next</h3><p>In the next article, I’ll walk through how to combine skill-based archetypes with <strong>Windsurf’s new parallel multi-agent feature (Wave 13)</strong> — where one agent scaffolds your feature while another simultaneously writes the full Spock test suite.</p><p>The future of engineering isn’t AI replacing engineers. It’s engineers who know how to build systems — including systems that guide AI.</p><p><em>If this resonated, follow me for more articles on distributed systems, Spring Boot architecture, and engineering at scale. The full series on system design is available on my profile.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07813871ab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>