<?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 Kishore Hebbar on Medium]]></title>
        <description><![CDATA[Stories by Kishore Hebbar on Medium]]></description>
        <link>https://medium.com/@hebbar.kishore?source=rss-462a131a2245------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BmhjIuM8o_5E8dn7</url>
            <title>Stories by Kishore Hebbar on Medium</title>
            <link>https://medium.com/@hebbar.kishore?source=rss-462a131a2245------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:59:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hebbar.kishore/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[FinChat-Local: A 100% Free AI Chatbot for Finance Learners]]></title>
            <link>https://medium.com/@hebbar.kishore/finchat-local-a-100-free-ai-chatbot-for-finance-learners-88c8d18bc242?source=rss-462a131a2245------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c8d18bc242</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Kishore Hebbar]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 23:23:03 GMT</pubDate>
            <atom:updated>2025-10-20T20:04:49.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeadqjGGHRGc7KUl3UIXPw.png" /></figure><h3>Introduction</h3><p>Most AI chatbots of the day depend on paid APIs as well as internet connection. But imagine having an intelligent financial assistant built from scratch that would run offline, cost nothing and still be able to explain the financial concepts like APR, ETFs or compound interest? In this paper, I am going to demonstrate the way I created FinChat-Local, a totally free AI chatbot which is based on Hugging Face Transformers and Streamlit. It employs a tiny local LLM (flan-t5-base) along with a personalized finance glossary in order to provide quick, domain-specific replies no OpenAI keys needed.</p><h3>Architecture Overview</h3><p>Simple Flow diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1Y--Hf0dO17fJjPiUJD_g.png" /></figure><p>The chatbot is made up of two parts:<br>• An upper layer that gets the most relevant words from a finance_glossary.json, and<br>• FLAN-T5, a small language model that provides real-sounding replies via the context obtained.<br>This mixed-based arrangement permits tiny offline models to produce more exact, finance domain based answers.</p><h3>Tools &amp; Libraries Used</h3><p><strong>Streamlit → </strong>Interactive web UI</p><p><strong>Transformers (Hugging Face) → </strong>Load local LLM</p><p><strong>Scikit-learn → </strong>TF-IDF retriever</p><p><strong>Python 3.9+ → </strong>Core runtime</p><p><strong>JSON → </strong>Glossary data storage</p><h3>Step-by-Step Implementation</h3><h4>1. Setup environment</h4><pre>python3 -m venv .venv<br>source .venv/bin/activate<br>pip install streamlit transformers torch scikit-learn</pre><h4>2. Create finance_glossary.json</h4><p>Paste a few finance definitions (APR, ETF, compound interest, etc.)</p><h4>3. Build app.py</h4><pre># -----------------------------<br># Config<br># -----------------------------<br>MODEL_NAME = &quot;google/flan-t5-base&quot;  # ~77M params, good for CPU<br>MAX_INPUT_TOKENS = 512<br>MAX_NEW_TOKENS = 256<br><br>st.set_page_config(page_title=&quot;Finance Q&amp;A&quot;, layout=&quot;centered&quot;)<br>st.title(&quot;💬 FinChat-Local — Offline Finance Chatbot&quot;)<br>st.caption(&quot;Runs 100% locally on CPU. No API keys. Ask finance questions (e.g., APR, ETF vs mutual fund, compound interest).&quot;)<br><br><br># -----------------------------<br># Utilities<br># -----------------------------<br>@st.cache_resource(show_spinner=True)<br>def load_model_and_tokenizer(model_name: str):<br>    &quot;&quot;&quot;<br>    Downloads on first run, then cached locally.<br>    &quot;&quot;&quot;<br>    tok = AutoTokenizer.from_pretrained(model_name)<br>    mdl = AutoModelForSeq2SeqLM.from_pretrained(model_name)<br>    return tok, mdl<br>:<br>:<br>:</pre><p>You can check the github repo <a href="https://github.com/hebbarkishore/finance-chat"><strong><em>here</em></strong></a></p><h4>4. Run the app</h4><p>streamlit run app.py</p><p>Opens <a href="http://localhost:8501/">http://localhost:8501</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRR6Czh47KnWrUxAeRqv6A.png" /></figure><h3><strong>Improving Quality</strong></h3><p>Small models like Flan-T5-Small are light but reasoning is minimal. The results can be made better by:<br>• Opting for Flan-T5-Base (more reasoning, still CPU-friendly)<br>• Increasing the number of glossary terms for richer retrieval<br>• Using Ollama with Mistral 7B for ChatGPT-like quality free and offline still</p><h3><strong>What I Learned</strong></h3><p>• When combined with retrieval, local language models can manage surprisingly well domain-specific tasks.<br>• Factual accuracy can be enhanced by a small glossary and prompt tuning.<br>• An API key or GPU is not always necessary for experimenting with AI.</p><blockquote><em>The full source code is open-sourced on </em><a href="https://github.com/hebbarkishore/finance-chat"><em>GitHub</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c8d18bc242" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why GraphQL Beats REST for Modern Microservices in Spring Boot]]></title>
            <link>https://medium.com/@hebbar.kishore/why-graphql-beats-rest-for-modern-microservices-in-spring-boot-76e0f920a729?source=rss-462a131a2245------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e0f920a729</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Kishore Hebbar]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 14:44:11 GMT</pubDate>
            <atom:updated>2025-07-30T22:11:09.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QpEMbwTozZsqWNvyfKk4Q.png" /></figure><h3><strong>Introduction</strong></h3><p>Have you ever had to make <strong>multiple REST API calls</strong> just to load one dashboard screen? Or struggled with versioning your backend because the frontend needed “just one more field”? You’re not alone. Since microservices grow in complexity, traditional REST APIs begin to show their age — leading to <strong>over-fetching, under-fetching, and tight coupling</strong> between services and clients.</p><p>In today’s fast-paced development environments, especially in <strong>financial, e-commerce, and data-driven platforms</strong>, we need APIs that are <strong>flexible, efficient, and future-proof</strong>. That’s where <strong>GraphQL</strong> comes in.</p><p>GraphQL isn’t just a “REST alternative.” It’s a paradigm shift. By allowing clients to <strong>ask for exactly the data they need</strong>, GraphQL reduces the need for backend versioning, minimizes network chatter, and improves developer productivity.</p><p>In this article, I’ll walk you through:</p><ul><li>Why REST struggles with microservices at scale</li><li>What makes GraphQL a better fit for modern backend systems</li><li>How to integrate GraphQL into a <strong>Spring Boot</strong> application with ease</li><li>The trade-offs, best practices, and real-world insights from my experience</li></ul><p>Let’s explore how GraphQL can help you build <strong>smarter, more flexible microservices</strong>, without rewriting your whole stack.</p><h3>REST in Microservices</h3><p>REST is the go to standard for creating APIs for over a decade. It’s simple, predictable, and aligns well with the HTTP protocol — making it easy to build, consume, and debug.<br>In a typical Spring Boot microservice, a REST controller might expose endpoints like:</p><pre>@GetMapping(&quot;/orders/{id}&quot;)<br>public Order getOrderById(@PathVariable Long id) {<br>    return orderService.findById(id);<br>}</pre><p>While this works well for independent resources, but this will be the issue when:<br>The UI needs in-depth data (e.g., order → customer → shipping), in that case<br>you have to make multiple HTTP calls to different APIs just to assemble one screen.<br>You will end up creating multiple of endpoints to serve bit different frontend use cases.</p><p>Example: A Common REST Problem<br>Let’s say your frontend needs to display:<br>Order details<br>Associated customer profile<br>List of items in the order<br>Shipping address</p><p>With REST, you might need to hit:<br>/orders/{id}<br>/orders/{id}/items<br>/customers/{customerId}<br>/shipping/{shippingId}</p><p>Each endpoint requires a <strong>round-trip</strong> to the backend, increasing latency and complexity — especially on slow mobile networks or in high-traffic environments.</p><h4>So in these cases REST in Microservices = Over-Fetching + Under-Fetching</h4><ul><li>Over-fetching: Getting more data than needed (e.g., entire customer profile when only the name is needed)<br>Under-fetching: Getting less than needed and having to make another call (e.g., order API returns order but not items)</li><li>REST also ties the backend design tightly to the frontend, leading to constant versioning challenges.</li></ul><h4>Bottom Line:</h4><p>While REST has served us well, it’s becoming clear that microservices architectures and rich client applications demand more flexibility and control — and that’s exactly where GraphQL shines.</p><h3>Introducing GraphQL — The Frontend-Friendly API</h3><p>GraphQL was created by Facebook to solve exactly the kinds of problems REST facing. Unlike REST, where each resource has its own endpoint, <strong>GraphQL exposes a single, unified endpoint</strong> that allows clients to ask for exactly the data they need — and nothing more.</p><p>At its core, GraphQL is:</p><ul><li><strong>Declarative:</strong> The client mentions what it wants</li><li><strong>Efficient:</strong> Only one request is needed to retrieve all data</li><li><strong>Strongly typed:</strong> The schema defines what’s possible and how to query it</li></ul><h4>Example: The Power of One Query</h4><p>Instead of calling 4 separate REST endpoints, here’s what a GraphQL query might look like:</p><pre>query {<br>  order(id: 123) {<br>    id<br>    totalAmount<br>    customer {<br>      name<br>      email<br>    }<br>    items {<br>      productName<br>      quantity<br>    }<br>    shippingAddress {<br>      city<br>      zipCode<br>    }<br>  }<br>}</pre><p><strong>Result:</strong> One HTTP request, one response — fully customized to the frontend’s needs.</p><h4>Why It Matters for Microservices</h4><p>In microservices, <strong>data lives in multiple services</strong>. GraphQL acts as a <strong>gateway layer</strong> (also called a “federated graph” or BFF — Backend for Frontend) that:</p><ul><li>Aggregates data from multiple sources</li><li>Provides a consistent schema to consumers</li><li>Decouples frontend from backend implementation details</li></ul><p>This means your UI team can evolve independently — It can switch to old version or new version of an API or data that it expects.</p><h4>GraphQL + Spring Boot = A Perfect Match</h4><p>With libraries like <a href="https://github.com/graphql-java-kickstart/graphql-spring-boot">graphql-spring-boot-starter</a>, integrating GraphQL into a Spring Boot app is surprisingly easy. You define your schema in a .graphqls file, write resolvers for the queries, and Spring Boot handles the rest.</p><h3>GraphQL in a Spring Boot Microservice — Quick Setup</h3><p>Adding GraphQL to a Spring Boot microservice is easier than you might think. With just a few dependencies and a schema file, you can turn your backend into a flexible, client-controlled API.</p><p>Let’s walk through a basic example: building a <strong>GraphQL API to fetch orders and related customer details</strong>.</p><h4>Step 1: Add Dependencies (Maven)</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.graphql-java-kickstart&lt;/groupId&gt;<br>    &lt;artifactId&gt;graphql-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;11.1.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.graphql-java-kickstart&lt;/groupId&gt;<br>    &lt;artifactId&gt;graphiql-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;11.1.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.graphql-java-kickstart&lt;/groupId&gt;<br>    &lt;artifactId&gt;graphql-java-tools&lt;/artifactId&gt;<br>    &lt;version&gt;11.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>You can also use Gradle with the corresponding dependencies.</p><h4>Step 2: Define Your GraphQL Schema</h4><p>Create a file:</p><p>src/main/resources/graphql/schema.graphqls</p><pre>type Query {<br>  order(id: ID!): Order<br>}<br><br>type Order {<br>  id: ID!<br>  totalAmount: Float<br>  customer: Customer<br>  items: [Item]<br>}<br><br>type Customer {<br>  id: ID!<br>  name: String<br>  email: String<br>}<br><br>type Item {<br>  id: ID!<br>  productName: String<br>  quantity: Int<br>}</pre><h4>Step 3: Create Java Models</h4><pre>public class Order {<br>    private Long id;<br>    private Double totalAmount;<br>    private Customer customer;<br>    private List&lt;Item&gt; items;<br>    // Getters and Setters<br>}</pre><p>Do the same for Customer and Item.</p><h4>Step 4: Create a GraphQL Resolver</h4><pre>@Component<br>public class OrderQueryResolver implements GraphQLQueryResolver {<br>    public Order order(Long id) {<br>        // Simulate DB fetch<br>        Customer customer = new Customer(1L, &quot;Michael Doe&quot;, &quot;michael@example.com&quot;);<br>        List&lt;Item&gt; items = List.of(<br>            new Item(101L, &quot;Laptop&quot;, 1),<br>            new Item(102L, &quot;Mouse&quot;, 2)<br>        );<br>        return new Order(id, 299.99, customer, items);<br>    }<br>}</pre><p>Each resolver maps a part of the schema to a Java method.</p><h4>Step 5: Test with GraphiQL UI</h4><p>Once your app runs, open:</p><p><a href="http://localhost:8080/graphiql">http://localhost:8080/graphiql</a></p><p>Try the query:</p><pre>query {<br>  order(id: 1) {<br>    totalAmount<br>    customer {<br>      name<br>    }<br>    items {<br>      productName<br>      quantity<br>    }<br>  }<br>}</pre><p>You’ll get a response customized exactly to what you asked for — no more, no less.</p><p>You Now Have a Functional GraphQL Microservice!</p><p>This simple setup demonstrates how <strong>Spring Boot + GraphQL</strong> makes it easy to:</p><ul><li>Expose nested data</li><li>Avoid multiple REST endpoints</li><li>Empower clients with flexible querying</li></ul><h3>Why GraphQL Beats REST for Microservices</h3><p>Now that you’ve seen how easy it is to integrate GraphQL into a Spring Boot microservice, let’s get to the real question:</p><p><strong><em>Why is GraphQL a better fit than REST for microservices?</em></strong></p><p>Below is a breakdown of <strong>key architectural pain points</strong> in REST — and how GraphQL overcomes them.</p><h4>1. Over-fetching &amp; Under-fetching</h4><p><strong>The REST Problem:</strong></p><p>You often get either too much or too little data. For example, hitting /customers/1 might return 30 fields when you only need 2. Or you might get only an orderId, requiring a second request to fetch customer details.</p><p><strong>GraphQL Fix:</strong></p><p>Clients specify exactly what fields they want, nothing more or less.</p><pre>query {<br>  customer(id: 1) {<br>    name<br>    email<br>  }<br>}</pre><h4>2. Multiple Network Calls</h4><p><strong>The REST Problem:</strong></p><p>For a rich frontend view, you might call /orders/1, /orders/1/items, and /customers/2. In microservices, these endpoints may live in different services — increasing latency and complexity.</p><p><strong>GraphQL Fix:</strong></p><p>All data is fetched in <strong>a single HTTP request</strong>, even across services, via resolvers and data loaders.</p><h4>3. Schema Evolution &amp; Versioning</h4><p><strong>The REST Problem:</strong></p><p>Adding fields often requires creating /v2 or breaking existing clients — making versioning a messy necessity.</p><p><strong>GraphQL Fix:</strong></p><p>GraphQL is inherently versionless. You can add new fields to types without breaking existing queries.</p><h4>4. UI Flexibility &amp; Developer Velocity</h4><p><strong>The REST Problem:</strong></p><p>Backend developers often have to update APIs for each new frontend screen, slowing teams down.</p><p><strong>GraphQL Fix:</strong></p><p>The <strong>frontend team has full control</strong> over the structure of the response. Backend changes are minimal or even unnecessary.</p><h4>5. Type Safety and Auto-Documentation</h4><p><strong>The REST Problem:</strong></p><p>You rely on Swagger or manually written docs. Errors like missing fields or wrong types often go unnoticed until runtime.</p><p><strong>GraphQL Fix:</strong></p><p>The schema defines types explicitly. Tools like GraphiQL or Voyager let you explore the API interactively and safely.</p><h3>Real-World Wins</h3><p>In my own experience modernizing microservices for fintech and e-commerce platforms:</p><ul><li>Switching to GraphQL cut <strong>frontend-backend coordination time by 40%</strong></li><li>Reduced the number of <strong>REST endpoints by 60–70%</strong></li><li>Helped us ship new features to production <strong>twice as fast</strong></li></ul><h3>Challenges of Using GraphQL in Microservices</h3><p>GraphQL is powerful, but it’s not a silver bullet. Like any tool, it comes with trade-offs — especially when integrated into <strong>distributed systems</strong> or scaled across multiple microservices. Let’s explore the most common challenges and how to address them.</p><h4>1. The N+1 Query Problem</h4><p><strong>The Issue:</strong></p><p>When querying nested data (e.g., order → items → product), your backend may issue a separate database query for each nested object — leading to performance issues in large datasets.</p><p><strong>The Fix:</strong></p><p>Use <a href="https://github.com/graphql-java/java-dataloader"><strong>DataLoader</strong></a> (in Java) to batch and cache nested queries, reducing them to a single database call per level.</p><pre>DataLoader&lt;Long, Product&gt; productLoader = DataLoader.newMappedDataLoader(keys -&gt; {<br>    return CompletableFuture.supplyAsync(() -&gt; productService.getProductsByIds(keys));<br>});</pre><h4>2. Security Concerns: Query Depth &amp; Complexity</h4><p><strong>The Issue:</strong></p><p>Since clients can craft complex and deeply nested queries, a malicious query could overload your system.</p><p><strong>The Fix:</strong></p><ul><li>Set a <strong>query depth limit</strong></li><li>Use libraries like graphql-java-servlet or graphql-java-kickstart to enforce complexity limits</li><li>Enable <strong>timeout thresholds</strong> and <strong>rate limiting</strong> on the API gateway</li></ul><h4>3. Caching Is More Complex</h4><p><strong>The Issue:</strong></p><p>With REST, you can easily cache responses using URLs. But with GraphQL, all queries go to the same endpoint (/graphql) with varying payloads.</p><p><strong>The Fix:</strong></p><ul><li>Use <strong>query hashes</strong> to cache responses (e.g., Apollo, GraphQL clients support this)</li><li>Use <strong>per-field or data-level caching</strong> in resolvers</li><li>Use server-side response caching for frequently accessed queries</li></ul><h4>4. Learning Curve for Teams</h4><p><strong>The Issue:</strong></p><p>Backend teams used to REST may struggle with:</p><ul><li>Writing schema definitions</li><li>Implementing resolvers</li><li>Managing query performance</li></ul><p><strong>The Fix:</strong></p><ul><li>Invest in short team workshops</li><li>Use auto-generators or schema-first tools (graphql-java-tools)</li><li>Start small (a hybrid approach with REST + GraphQL)</li></ul><h4>5. Federation and Service Composition</h4><p><strong>The Issue:</strong></p><p>In a microservices setup, each service owns its data. Composing a unified GraphQL schema across services can be challenging.</p><p><strong>The Fix:</strong></p><ul><li>Use <strong>GraphQL Federation</strong> (e.g., Apollo Federation) to stitch schemas</li><li>Or implement a <strong>Gateway service</strong> that aggregates data from underlying REST/GraphQL microservices</li></ul><p>GraphQL is powerful, but like any flexible system, <strong>it demands thoughtful engineering</strong> to scale. With best practices in place, these challenges become opportunities to build robust, future-ready APIs.</p><h3>When You Should Still Use REST</h3><p>GraphQL is powerful and flexible — but that doesn’t mean REST is dead. In fact, there are still many valid scenarios where REST remains the better tool for the job. Let’s take a look at when sticking with REST might make more sense.</p><h4>1. Simple CRUD APIs</h4><p><strong>Why REST wins:</strong></p><p>For basic Create-Read-Update-Delete operations (e.g., managing internal user preferences or configuration data), REST is straightforward and well-supported by almost every toolchain.</p><p><strong>When to use:</strong></p><ul><li>Admin panels</li><li>Internal services</li><li>No need for nested data or custom queries</li></ul><h4>2. File Uploads &amp; Downloads</h4><p><strong>Why REST wins:</strong></p><p>GraphQL doesn’t handle multipart file uploads natively. REST endpoints using multipart/form-data are simpler and more efficient for large file transfers.</p><p><strong>When to use:</strong></p><ul><li>Media uploads (e.g., invoices, profile pictures)</li><li>Downloading reports or binary files</li></ul><h4>3. Streaming &amp; Webhooks</h4><p><strong>Why REST (or other protocols) win:</strong></p><p>GraphQL subscriptions (real-time via WebSockets) are still evolving and can be hard to scale. REST with webhooks, or even gRPC and Kafka, might be more appropriate.</p><p><strong>When to use:</strong></p><ul><li>Asynchronous callbacks</li><li>Notifications, event tracking, or background job responses</li></ul><h4>4. CDN-Optimized Data</h4><p><strong>Why REST wins:</strong></p><p>REST APIs with cacheable URLs are ideal for integration with CDNs like CloudFront or Akamai.</p><p><strong>When to use:</strong></p><ul><li>Public product catalogs</li><li>Static data that rarely changes</li></ul><h4>5. Existing REST-Heavy Ecosystems</h4><p><strong>Why REST wins:</strong></p><p>If you’re working in a system that’s already REST-heavy, adopting GraphQL may add unnecessary complexity without significant gains.</p><p><strong>When to use:</strong></p><ul><li>Systems with well-established REST contracts</li><li>Where dev teams lack experience with GraphQL</li></ul><p><strong>REST and GraphQL aren’t enemies </strong>— they can coexist. In fact, many modern architectures use both:</p><ul><li><strong>GraphQL for frontend flexibility and data aggregation</strong></li><li><strong>REST for edge cases, integrations, or internal tooling</strong></li></ul><h3>Conclusion: GraphQL Is the Future-Friendly API</h3><p>As microservices architectures continue to evolve, so do the challenges of building efficient, scalable, and flexible APIs. While REST has been the backbone of service communication for years, it begins to crack under the pressure of modern frontend demands, tight iteration cycles, and complex data relationships.</p><p><strong>GraphQL addresses these challenges head-on</strong>, offering:</p><ul><li>Fine-grained control over data fetching</li><li>Fewer endpoints, more capability</li><li>A better developer experience for both frontend and backend teams</li><li>A more maintainable and future-ready API layer</li></ul><p>With <strong>Spring Boot</strong>, integrating GraphQL is smooth and production-ready. Whether you’re building fintech apps, e-commerce systems, or enterprise backends, GraphQL offers a powerful alternative to REST — one that encourages collaboration, reduces redundant code, and helps deliver features faster.</p><p>You don’t need to abandon REST entirely. But embracing GraphQL — even gradually — can make your microservices more agile, your frontends more expressive, and your teams more productive.</p><p>So go ahead — try building your next API with GraphQL and Spring Boot.</p><p>You might be surprised at how much smoother things can get.</p><h4>Found this helpful?</h4><p>Follow me for more articles on backend architecture, microservices, Spring Boot, and API design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e0f920a729" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How AI-Driven Circuit Breakers Can Make Microservices Smarter and More Resilient]]></title>
            <link>https://medium.com/@hebbar.kishore/how-ai-driven-circuit-breakers-can-make-microservices-smarter-and-more-resilient-d364e1ef9c9c?source=rss-462a131a2245------2</link>
            <guid isPermaLink="false">https://medium.com/p/d364e1ef9c9c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[resilient]]></category>
            <dc:creator><![CDATA[Kishore Hebbar]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 22:24:56 GMT</pubDate>
            <atom:updated>2025-07-10T22:24:56.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fW5nMw3pKZzuavHh-URsmQ.png" /><figcaption>AI-Driven Circuit Breaker</figcaption></figure><h3>Introduction: The Limits of Traditional Circuit Breakers</h3><p>Let’s say your microservices are handling thousands of transactions every second on Black Friday. One dependent service, a payment processor, unexpectedly starts to lag. Your traditional circuit breaker trips in a matter of minutes, completely shutting off service in order to “protect” the system. The results? Even though the payment processor was only slightly delayed and not completely unavailable, this led to upset customers, failed checkouts, and lost revenue.</p><p>This is the reality for many microservices systems today. Traditional circuit breakers like <strong>Hystrix</strong> or <strong>Resilience4j</strong> use <strong>static thresholds</strong>: they trip if error rates or latencies exceed predefined limits. But static thresholds are <strong>blind</strong> to the <strong>context</strong> of the failure:</p><ul><li>Is the slowdown temporary or catastrophic?</li><li>Is the transaction low-value or high-value?</li><li>Is the spike in errors part of normal seasonal traffic?</li></ul><p>In a world where <strong>distributed systems</strong> must handle <strong>volatile traffic patterns</strong>, <strong>SLA commitments</strong>, and <strong>customer segmentation</strong>, a <strong>one-size-fits-all circuit breaker</strong> is simply not smart enough.</p><h3>Why Microservices Need Smarter Circuit Breakers</h3><p>Microservices offer enormous benefits in terms of <strong>scalability, agility, and resilience</strong>, but they also introduce <strong>new failure modes</strong>:</p><ul><li><strong>Service dependencies</strong> can fail unpredictably.</li><li><strong>Partial failures</strong> can cause cascading outages.</li><li><strong>Network partitions</strong> can lead to inconsistent service states.</li></ul><p>The traditional <strong>circuit breaker pattern</strong> helps mitigate this by:</p><ol><li><strong>Monitoring error rates and latencies</strong> of downstream calls.</li><li><strong>Opening the circuit</strong> to stop traffic when failures spike.</li><li><strong>Closing the circuit</strong> after a cool-down period.</li></ol><p>Traditional circuit breakers work on <strong>fixed rules</strong>: they open the circuit when failures cross a predefined threshold (for example, when more than <strong>50% of requests fail within a given time window</strong>). While this approach can protect systems from cascading failures, it has <strong>critical blind spots</strong>:</p><ol><li><strong>Lack of Business Awareness: </strong>The circuit breaker treats all requests as <strong>equally valuable</strong>. A failed <strong>high-value transaction</strong> (e.g., processing a mortgage approval or handling a large financial trade) is treated the same as a failed <strong>low-priority background task</strong>. There’s no differentiation based on <strong>transaction value, customer tier, or SLA importance</strong>.</li><li><strong>No Sensitivity to Changing Conditions: </strong>Fixed thresholds don’t account for <strong>dynamic traffic patterns</strong>, <strong>seasonal peaks</strong>, or <strong>auto-scaling cloud behavior</strong>. A spike in errors during high load might be tolerable for the business if it’s within historical norms, but the static circuit will still open, potentially blocking legitimate traffic.</li><li><strong>Poor Adaptability to Degradation vs. Failure: </strong>Not all performance issues are equal. A <strong>mild slowdown</strong> doesn’t always warrant cutting off an entire downstream service. Fixed thresholds can’t distinguish between <strong>graceful degradation</strong> and <strong>hard failure</strong>.</li></ol><p><strong>This will impact</strong>,</p><ul><li><strong>False Positives:</strong> The circuit opens too early, causing unnecessary outages and poor user experience.</li><li><strong>False Negatives:</strong> The circuit stays closed even when it should trip, allowing failures to cascade.</li></ul><p>In modern <strong>high-frequency, customer-sensitive microservices</strong>, this <strong>rigid behavior</strong> leads to <strong>avoidable downtime</strong>, <strong>revenue loss</strong>, and <strong>SLA breaches</strong>.</p><h3>How AI-Driven Circuit Breakers Make Smarter Decisions</h3><p>To overcome the limitations of rigid, one-size-fits-all circuit breakers, we can introduce <strong>AI-driven adaptive circuit breakers</strong> — a new approach that uses <strong>machine learning models</strong> to make <strong>context-aware, real-time decisions</strong> on when to open, close, or bypass circuits.</p><p>Instead of relying on <strong>fixed error rate thresholds or timeout values</strong>, an AI-driven circuit breaker can consider:</p><ul><li><strong>Real-time system telemetry:</strong> CPU, memory, response times, and downstream error rates.</li><li><strong>Business context:</strong> Transaction type, customer priority (e.g., VIP vs. guest user), financial value.</li><li><strong>Historical patterns:</strong> How similar system behaviors have played out in the past — did they self-heal or lead to outages?</li></ul><h3>How It Works: The AI-Driven Decision Loop</h3><ol><li><strong>Telemetry Collection: </strong>Your microservices continuously emit metrics like:</li></ol><ul><li>Request latency</li><li>Error rates (HTTP 5xx, timeouts)</li><li>CPU, memory, thread pool saturation</li></ul><p>This is typically already available via <strong>Prometheus, Micrometer, or New Relic</strong>.</p><p>2. <strong>Feature Extraction: </strong>Combine <strong>technical signals</strong> with <strong>business metadata</strong>:</p><ul><li>Transaction amount</li><li>Customer type (Gold, Silver, Bronze)</li><li>Criticality of service (payment vs. logging)</li></ul><p>3. <strong>ML Model Inference: </strong>Feed this <strong>feature vector</strong> into a <strong>pre-trained machine learning model — </strong>this could be</p><ul><li>A simple <strong>classification model</strong> (trip circuit vs. not)</li><li>A <strong>regression model</strong> predicting failure probability</li></ul><p>Models could be hosted via:</p><ul><li><strong>AWS SageMaker Endpoint</strong></li><li><strong>TensorFlow Serving</strong></li><li><strong>ONNX in Java or Python microservices</strong></li></ul><p><strong>4. Adaptive Circuit Breaker Action: </strong>The AI model returns:</p><ul><li>A <strong>risk score</strong> or <strong>recommended action</strong>.</li><li>The circuit breaker adjusts: Thresholds, Retry timing and Selective degradation (serve VIPs, shed background jobs)</li></ul><p><strong>5. Continuous Learning: </strong>Models can <strong>retrain periodically</strong> based on new failure events, improving over time.</p><p>Example: Let’s say you’re handling <strong>payment transactions</strong> in an e-commerce system:</p><p>Let’s say you’re handling <strong>payment transactions</strong> in an e-commerce system:</p><ul><li>The <strong>payment gateway</strong> shows slightly increased latency, but it’s handling <strong>99% of transactions successfully</strong>.</li><li>It’s also <strong>Black Friday</strong>, and you’re processing <strong>high-value transactions</strong> for your top-tier customers.</li><li>Traditional circuit breaker → might trip too early → revenue loss.</li></ul><p>AI-driven breaker:</p><ul><li>Recognizes the <strong>time of day</strong>, <strong>expected load</strong>, <strong>transaction value</strong>.</li><li>Decides to <strong>keep the circuit closed</strong> for <strong>high-value users</strong> while perhaps <strong>shedding low-priority background tasks</strong>.</li><li>The system continues to operate under pressure without catastrophic failure.</li><li><strong>Not every failure is equal</strong>: context matters.</li><li>AI allows systems to make <strong>smarter trade-offs</strong> between <strong>availability</strong> and <strong>consistency</strong>.</li><li>AI-driven resilience is not about eliminating circuit breakers — it’s about <strong>making them intelligent</strong>.</li></ul><h3>How to build AI-Driven Circuit Breakers</h3><h4>Step 1: Collect the Right Telemetry</h4><ul><li>System: CPU, latency, memory</li><li>App: Error rates, retries</li><li>Business: Transaction type, value, user class</li></ul><p>Tools: Prometheus, Grafana, Micrometer</p><h4>Step 2: Train an ML Model</h4><ul><li>Classification: Should we trip the circuit? Yes/No.</li><li>Regression: Predict latency or error probability.</li></ul><p>Tools: scikit-learn, XGBoost, TensorFlow</p><h4>Step 3: Deploy the Model</h4><ul><li>Options: Flask microservice, TensorFlow Serving, SageMaker Endpoint.</li></ul><h4>Step 4: Integrate AI with Circuit Breaker</h4><ul><li>Use <strong>Resilience4j</strong> in Spring Boot.</li><li>Call the model for real-time decisions.</li></ul><h4>Step 5: Continuous Monitoring &amp; Learning</h4><ul><li>Automate model retraining.</li><li>Measure improvements: fewer false trips, better SLAs.</li></ul><h3>Challenges, Limitations, and Future Trends</h3><p>While <strong>AI-driven circuit breakers</strong> offer powerful advantages, they also introduce new challenges that architects and engineers must consider carefully.</p><ol><li><strong>Model Accuracy and False Predictions:</strong></li></ol><ul><li>Machine learning models can <strong>misclassify failure risks</strong>—leading to incorrect decisions.</li><li>False positives (unnecessary tripping) or false negatives (missing actual failures) could still occur if the model isn’t trained on enough diverse data.</li></ul><p>Start with <strong>simple models</strong> and <strong>gradually refine</strong> them based on live feedback.</p><p>2. <strong>Model Latency and Real-Time Requirements:</strong></p><ul><li>AI models must deliver predictions <strong>within milliseconds</strong> to avoid adding latency to critical paths.</li><li>In high-frequency transactional systems, even small delays can hurt responsiveness.</li></ul><p>Use <strong>lightweight models</strong> (Random Forests, XGBoost) and deploy them <strong>close to the application</strong> (on the same cloud region or even in-process via ONNX).</p><p>3. <strong>Complexity and Operational Overhead</strong></p><ul><li>Adding ML introduces new <strong>dependencies</strong> (model training, serving, monitoring).</li><li>Engineers may need <strong>cross-disciplinary skills</strong> in both software engineering and data science.</li></ul><p>Start small — apply AI-driven decisions to <strong>non-critical paths first</strong>. Use <strong>MLOps pipelines</strong> for automation.</p><p>4. <strong>Security and Compliance Risks</strong></p><ul><li>Financial or healthcare systems must ensure that <strong>AI-driven resilience does not compromise compliance</strong> or introduce unpredictable behavior.</li></ul><p>Apply <strong>AI decisioning as an advisor</strong> initially (suggestive mode). before giving it full control.</p><h3>How to update your code in Java/Spring Boot:</h3><h4>1. Basic Setup: Spring Boot + Resilience4j</h4><p>Add these dependencies in your pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;resilience4j-spring-boot2&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br><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;</pre><h4>2. Create the AI Model Client (Calling the AI Service)</h4><p>This calls an AI microservice endpoint that returns a <strong>risk score</strong>.</p><pre>@Service<br>public class PredictionAiService {<br><br>    private final WebClient webClient = WebClient.create(&quot;http://aimodel-service/dev1&quot;);<br><br>    public Mono&lt;Boolean&gt; shouldTripCircuit(TransactionContext context) {<br>        return webClient.post()<br>            .uri(&quot;/predict&quot;)<br>            .bodyValue(context)<br>            .retrieve()<br>            .bodyToMono(AiPredictionResponse.class)<br>            .map(response -&gt; response.getRiskScore() &gt; 0.7);  //configurable risk score 0 to 1<br>    }<br><br>    static class PredictionAiResponse {<br>        private double riskScore;<br><br>        public double getRiskScore() {<br>            return riskScore;<br>        }<br><br>        public void setRiskScore(double riskScore) {<br>            this.riskScore = riskScore;<br>        }<br>    }<br>}</pre><h4>3. Define the Transaction Context (Feature Set for AI)</h4><p>This is the <strong>input to your AI model</strong>.</p><pre>public class TransactionContext {<br>    private double averageLatency;<br>    private double errorRate;<br>    private String userTier;<br>    private double transactionAmount;<br><br>    // Getters and Setters<br>}</pre><h4>4. Adaptive Circuit Breaker Using Resilience4j + AI</h4><ul><li>The AI model <strong>decides dynamically</strong> whether to trip the circuit.</li><li>You still use Resilience4j for execution, retries, and fallback.</li><li>Decisions are now <strong>context-aware</strong>.</li></ul><pre>@Service<br>public class PaymentInfoService {<br><br>    private final PredictionAiService predictionAiService;<br>    private final CircuitBreaker circuitBreaker;<br><br>    public PaymentInfoService(PredictionAiService predictionAiService) {<br>        this.predictionAiService = predictionAiService;<br>        this.circuitBreaker = CircuitBreaker.ofDefaults(&quot;paymentServiceCircuit&quot;);<br>    }<br><br>    public Mono&lt;String&gt; processPayment(TransactionContext context) {<br>        return predictionAiService.shouldTripCircuit(context)<br>            .flatMap(shouldTrip -&gt; {<br>                if (shouldTrip) {<br>                    circuitBreaker.transitionToOpenState();<br>                    return Mono.error(new RuntimeException(&quot;Circuit tripped by AI&quot;));<br>                } else {<br>                    return Mono.fromCallable(() -&gt; circuitBreaker.executeCallable(() -&gt; doPaymentOperation()));<br>                }<br>            });<br>    }<br><br>    private String doPaymentOperation() {<br>        // Simulate calling downstream service<br>        return &quot;Payment Successful&quot;;<br>    }<br>}</pre><h4>5. Sample AI Model Response (Mock JSON)</h4><pre>{<br>  &quot;riskScore&quot;: 0.95<br>}</pre><p>A <strong>high score (e.g., &gt;0.7)</strong> leads to <strong>circuit trip</strong>.</p><h3>Conclusion: Toward Smarter, Safer Microservices</h3><p>Resilience can no longer be static.</p><p><strong>AI-driven circuit breakers</strong> bring adaptive, intelligent protection to microservices — balancing technical reliability with business priorities.</p><ul><li>Protect what matters most.</li><li>Reduce downtime.</li><li>Move toward <strong>self-healing, adaptive architectures.</strong></li></ul><p><em>If you found this valuable, share it or follow for more insights on microservices, AI, and resilient system design.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d364e1ef9c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>