<?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 Sai Narsimha Gupta Thammana on Medium]]></title>
        <description><![CDATA[Stories by Sai Narsimha Gupta Thammana on Medium]]></description>
        <link>https://medium.com/@venkatsai0398?source=rss-74b29762383a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Sai Narsimha Gupta Thammana on Medium</title>
            <link>https://medium.com/@venkatsai0398?source=rss-74b29762383a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:39:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@venkatsai0398/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[‍Building a Dynamic Rules Engine in Spring Boot — Advanced Features]]></title>
            <link>https://medium.com/@venkatsai0398/building-a-dynamic-rules-engine-in-spring-boot-advanced-features-80f3b144bee0?source=rss-74b29762383a------2</link>
            <guid isPermaLink="false">https://medium.com/p/80f3b144bee0</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Sai Narsimha Gupta Thammana]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 03:20:04 GMT</pubDate>
            <atom:updated>2025-08-22T03:20:04.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>👨‍💻Building a Dynamic Rules Engine in Spring Boot — Advanced Features</h3><blockquote>⚡ Parallel Execution | 🛠 Failure Reporting | 🔗 Rule Chaining | 🌍 Real-World Systems</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1Oe7SveP3pBlPHCoc3qJQ.png" /></figure><p>In my 👉<a href="https://medium.com/@venkatsai0398/c8bafacc1031"><strong>[previous article]</strong></a>, I introduced a lightweight rules engine in Spring Boot using the <strong>Strategy + Registry pattern</strong>. It helped me tame <strong>150+ business rules</strong> for telecom bill auditing without drowning in if-else statements or switch-case blocks.</p><p>That design worked well in production, but as data volume grew, I ran into three real-world challenges:</p><ol><li><strong>Performance bottlenecks</strong> → 150+ rules running sequentially slowed down audits</li><li><strong>Lack of error visibility</strong> → Boolean results (true/false) weren’t enough to explain <em>why</em> rules failed</li><li><strong>Dependent execution needs</strong> → Some rules only made sense if others passed</li></ol><p>This article dives deeper into solving these problems — without introducing heavyweight rule engines like Drools.</p><p>We’ll upgrade the rules engine to support:<br> ✅ <strong>Parallel execution</strong> (faster audits)<br> ✅ <strong>Structured failure reporting</strong> (better debugging)<br> ✅ <strong>Rule chaining</strong> (dependency-aware execution)</p><h3>⚡ 1. Parallelizing Rule Execution</h3><p>In the first version, all rules ran <strong>sequentially</strong> inside a loop. With 150+ rules, this soon became a performance bottleneck.</p><p>We can fix this with <strong>Java’s </strong><strong>CompletableFuture</strong> and a managed <strong>thread pool</strong>. Each rule runs independently in its own task, results are collected in parallel, and the engine aggregates them.</p><pre>@Component<br>public class RuleEngine {<br><br>    private final Map&lt;String, BillingRule&gt; ruleMap = new HashMap&lt;&gt;();<br><br>    @Autowired<br>    private List&lt;BillingRule&gt; rules;<br><br>    @PostConstruct<br>    public void init() {<br>        for (BillingRule rule : rules) {<br>            ruleMap.put(rule.getRuleId(), rule);<br>        }<br>    }<br><br>    public Map&lt;String, Boolean&gt; applyAllRulesParallel(Bill bill) {<br>        ExecutorService executor = Executors.newFixedThreadPool(10);<br><br>        try {<br>            List&lt;CompletableFuture&lt;Map.Entry&lt;String, Boolean&gt;&gt;&gt; futures =<br>                ruleMap.entrySet().stream()<br>                    .map(entry -&gt; CompletableFuture.supplyAsync(() -&gt;<br>                        Map.entry(entry.getKey(), entry.getValue().validate(bill)),<br>                        executor<br>                    ))<br>                    .toList();<br><br>            return futures.stream()<br>                .map(CompletableFuture::join)<br>                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));<br><br>        } finally {<br>            executor.shutdown();<br>        }<br>    }<br>}</pre><p>✅ Benefits</p><ul><li>Exploits multiple CPU cores</li><li>Handles slow rules (e.g., DB lookups, API calls) without blocking others</li><li>Configurable thread pool size for scaling</li></ul><h3>🧯 2. Structured Failure Reporting</h3><p>Returning just true/false is like saying:</p><blockquote>“The bill failed validation.”</blockquote><p>…without telling <strong>why</strong>.</p><p>Instead, let’s introduce a richer <strong>RuleResult</strong> object:</p><pre>public class RuleResult {<br>    private final String ruleId;<br>    private final boolean passed;<br>    private final String message;  // failure reason<br><br>    public RuleResult(String ruleId, boolean passed, String message) {<br>        this.ruleId = ruleId;<br>        this.passed = passed;<br>        this.message = message;<br>    }<br><br>    // getters...<br>}</pre><p>Updated interface:</p><pre>public interface BillingRule {<br>    String getRuleId();<br>    RuleResult validate(Bill bill);<br>}</pre><p>Example rule:</p><pre>@Component<br>public class OverLimitCallRule implements BillingRule {<br>    @Override<br>    public String getRuleId() {<br>        return &quot;OVER_LIMIT_CALL&quot;;<br>    }<br><br>    @Override<br>    public RuleResult validate(Bill bill) {<br>        boolean passed = bill.getTotalMinutes() &lt;= bill.getPlanLimit();<br>        return new RuleResult(getRuleId(), passed,<br>            passed ? null : &quot;Total minutes exceeded plan limit&quot;);<br>    }<br>}</pre><p>Engine returning structured results:</p><pre>public List&lt;RuleResult&gt; applyAllRulesDetailed(Bill bill) {<br>    return ruleMap.values().stream()<br>        .map(rule -&gt; rule.validate(bill))<br>        .toList();<br>}</pre><h3>🔗 3. Rule Chaining (Conditional Execution)</h3><p>Sometimes a rule should <strong>only execute if another passes</strong>.<br> For example:</p><ul><li>Run INTL_CALL_CHARGE <strong>only if</strong> OVER_LIMIT_CALL passed</li></ul><p>We’ll extend our rules with <strong>dependency metadata</strong>:</p><pre>public interface DependentBillingRule extends BillingRule {<br>    default List&lt;String&gt; dependsOn() {<br>        return List.of(); // default: no dependencies<br>    }<br>}</pre><p>Engine with dependency resolution:</p><pre>public List&lt;RuleResult&gt; applyRulesWithDependencies(Bill bill) {<br>    Map&lt;String, RuleResult&gt; results = new LinkedHashMap&lt;&gt;();<br><br>    for (BillingRule rule : rules) {<br>        if (rule instanceof DependentBillingRule dependentRule) {<br>            boolean depsPassed = dependentRule.dependsOn().stream()<br>                .allMatch(dep -&gt; results.get(dep) != null &amp;&amp; results.get(dep).isPassed());<br><br>            if (!depsPassed) {<br>                results.put(rule.getRuleId(),<br>                    new RuleResult(rule.getRuleId(), false, &quot;Skipped due to dependency failure&quot;));<br>                continue;<br>            }<br>        }<br>        results.put(rule.getRuleId(), rule.validate(bill));<br>    }<br><br>    return new ArrayList&lt;&gt;(results.values());<br>}</pre><p>Example dependent rule:</p><pre>@Component<br>public class InternationalCallChargeRule implements DependentBillingRule {<br>    @Override<br>    public String getRuleId() {<br>        return &quot;INTL_CALL_CHARGE&quot;;<br>    }<br><br>    @Override<br>    public List&lt;String&gt; dependsOn() {<br>        return List.of(&quot;OVER_LIMIT_CALL&quot;);<br>    }<br><br>    @Override<br>    public RuleResult validate(Bill bill) {<br>        boolean passed = bill.getInternationalCharges() &lt; 50;<br>        return new RuleResult(getRuleId(), passed,<br>            passed ? null : &quot;International charges exceeded limit&quot;);<br>    }<br>}</pre><p>Now INTL_CALL_CHARGE won’t even run if OVER_LIMIT_CALL fails.</p><h3>🧠 Lessons &amp; Best Practices</h3><ul><li>✅ Use <strong>parallel execution</strong> for performance but <strong>tune thread pool size</strong> carefully</li><li>✅ Use <strong>structured results</strong> for debugging and audit compliance</li><li>✅ Keep <strong>dependencies declarative</strong> (metadata, not hardcoded logic)</li><li>✅ For very complex chaining/priority → consider <strong>Drools or BPMN engines</strong></li></ul><h3>⚖️ When Your Custom Engine Works Best</h3><p>Your Strategy + Registry approach is perfect when:</p><ul><li>✅ <strong>Rules are developer-owned</strong>: engineers write and maintain them in Java</li><li>✅ <strong>Rules are deterministic &amp; stable</strong>: they don’t change every day</li><li>✅ <strong>Rules are independent or loosely dependent</strong>: simple chaining is enough</li><li>✅ <strong>Code-driven approach is acceptable</strong>: no need for business users to modify logic</li><li>✅ <strong>You want simplicity</strong>: no external engines, no DSLs, just Spring Boot + interfaces</li></ul><p>This is why your solution worked well for telecom billing audits — the rules were technical, numerous, but not highly dynamic.</p><h3>📌 Conclusion</h3><p>We started with a simple Strategy + Registry engine.<br> Now we’ve made it:</p><ul><li><strong>Faster</strong> (parallel execution)</li><li><strong>Clearer</strong> (structured failure reporting)</li><li><strong>Smarter</strong> (rule chaining)</li></ul><p>This keeps the system lightweight and developer-friendly while scaling to <strong>hundreds of rules</strong>.</p><h3>📚 Further Reading</h3><ul><li>Java CompletableFuture for async execution</li><li>Spring Dependency Injection</li><li>Strategy &amp; Registry Patterns</li></ul><h3>🤝 Let’s Connect</h3><p>If you found this useful, leave a comment or share how you manage rule-heavy systems in your own projects.</p><p>Follow me on <a href="https://medium.com/@venkatsai0398">Medium</a>, <a href="https://github.com/SaiNarsimhaGupta">GitHub</a>, or <a href="https://www.linkedin.com/in/sai-narsimha-gupta">LinkedIn</a> for more real-world engineering writeups!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80f3b144bee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Dynamic Rules Engine in Spring Boot with the Strategy + Registry Pattern]]></title>
            <link>https://medium.com/@venkatsai0398/building-a-dynamic-rules-engine-in-spring-boot-with-the-strategy-registry-pattern-c8bafacc1031?source=rss-74b29762383a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8bafacc1031</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rules]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Sai Narsimha Gupta Thammana]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 03:35:02 GMT</pubDate>
            <atom:updated>2025-07-06T03:35:02.311Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A scalable way to manage 150+ business rules without drowning in if-else statements</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*185sM_eZxlGCGd34nUlXmA.png" /></figure><h4>🔍 <strong>Introduction</strong></h4><p>As a backend developer, one of the most frustrating architectural challenges I faced was managing <strong>a massive set of business rules</strong> — over <strong>150</strong> of them — to audit customer telephone bills. Each rule needed to perform validations like checking payments, mismatched charges, duplicate entries, and so on.</p><p>Now imagine trying to handle that many rules using if-else, switch-case, or even @autowiring 150 beans — I knew that path would quickly turn into a maintainability nightmare.</p><p>So, I took a different approach.</p><p>This blog shares how I built a <strong>clean, scalable, and extensible rules engine</strong> using <strong>Spring Boot</strong>, relying on component scanning, a common interface, and dynamic registration. The pattern can be applied to <strong>any rules-heavy system</strong> — not just telecom auditing.</p><h4>🎯 Problem Statement</h4><p>I was tasked with auditing customer telephone bills. Each bill needed to be validated against over <strong>150 different business rules</strong>.</p><p><strong>Each rule had to:</strong></p><ul><li>Perform a unique check (e.g., overcharges, plan violations, adjustments, duplicate payments, etc.)</li><li>Be easy to extend, modify, and debug</li><li><strong>Not result in a 2,000-line </strong><strong>if-else jungle</strong>, <strong>bloated </strong><strong>switch-case block</strong>, or <strong>reflection-based registry</strong></li></ul><p><strong>❌ Approaches I Avoided:</strong></p><ul><li><strong>if-else chains</strong> → Too many conditions, unreadable after scale</li><li><strong>switch-case</strong> → Violates SRP/OCP, centralizes logic unnecessarily</li><li><strong>Reflection (</strong><strong>Class.forName)</strong> → Fragile, error-prone, hard to trace or refactor</li><li><strong>Manually autowiring 150 rules</strong> → Tedious and not scalable</li></ul><p>I needed a better way — one that could be cleaner, scalable and modular…..</p><h4>🧩The Solution: Strategy + Registry Pattern in Spring Boot</h4><p>Here’s what I ended up implementing:</p><ul><li>A BillingRule interface to define a standard contract for all rules</li><li>Each rule implemented as a <strong>Spring </strong><strong>@Component</strong>, autoloaded into the context</li><li>A <strong>central RuleEngine</strong> that registers each rule by ID and executes dynamically</li></ul><p>This design follows a mix of:</p><ul><li><strong>Strategy Pattern</strong> → for dynamic rule selection</li><li><strong>Registry Pattern</strong> → for storing and invoking rules by ID</li><li><strong>Plugin Pattern</strong> → for modular and extensible structure</li></ul><h3>📐 Step 1: Define a Common Rule Interface</h3><pre>public interface BillingRule {<br>    String getRuleId();<br>    boolean validate(Bill bill);<br>}</pre><p>Each rule will implement this interface and provide:</p><ul><li>A unique ruleId</li><li>The logic to validate() a Bill object</li></ul><h3>🧩 Step 2: Implement Rules as Spring Components</h3><pre><br>@Component<br>public class OverLimitCallRule implements BillingRule {<br>    <br>    @Override<br>    public String getRuleId() {<br>        return &quot;OVER_LIMIT_CALL&quot;;<br>    }<br><br>    @Override<br>    public boolean validate(Bill bill) {<br>        return bill.getTotalMinutes() &lt;= bill.getPlanLimit();<br>    }<br>}</pre><p>You can define as many rules as needed like this. Spring auto-discovers and registers them.</p><h3>🧠 Step 3: Load Rules into a Central Rule Engine</h3><pre>@Component<br>public class RuleEngine {<br>private final Map&lt;String, BillingRule&gt; ruleMap = new HashMap&lt;&gt;();<br>    @Autowired<br>    private List&lt;BillingRule&gt; rules;<br>    @PostConstruct<br>    public void init() {<br>        for (BillingRule rule : rules) {<br>            ruleMap.put(rule.getRuleId(), rule);<br>        }<br>    }<br>    public boolean applyRule(String ruleId, Bill bill) {<br>        BillingRule rule = ruleMap.get(ruleId);<br>        if (rule == null) throw new IllegalArgumentException(&quot;Unknown rule: &quot; + ruleId);<br>        return rule.validate(bill);<br>    }<br>    public Map&lt;String, Boolean&gt; applyAllRules(Bill bill) {<br>        return ruleMap.entrySet().stream()<br>                .collect(Collectors.toMap(<br>                    Map.Entry::getKey,<br>                    entry -&gt; entry.getValue().validate(bill)<br>                ));<br>    }<br>}</pre><h3>🚀 Key Benefits of This Architecture</h3><ul><li><strong>🧩 Fully Decoupled</strong><br> Each rule is self-contained in its own class and implements a common interface. Easy to test, debug, and reason about.</li><li><strong>🔌 Easily Extensible</strong><br> Add or remove rules like plugins — no need to touch the engine or modify existing logic.</li><li><strong>🌱 Spring-Managed Lifecycle</strong><br> Rules are picked up automatically via Spring’s component scanning. No manual wiring or factory classes needed.</li><li><strong>🛡️ Follows Open/Closed Principle (OCP)</strong><br> The engine remains closed for modification but open for extension. New behaviors come from new classes — not new if-else blocks.</li></ul><h3>⚠️ Limitations &amp; Considerations</h3><p>While this Strategy + Registry pattern worked well for my use case, it’s important to be aware of its limitations — especially if you’re planning to scale the rule set or handle more complex scenarios.</p><h4>❗ Sequential Execution</h4><p>Currently, all rules are executed sequentially. This is fine for a moderate number of lightweight rules, but as complexity grows, it can become a performance bottleneck. In future iterations, I plan to explore parallel execution of independent rules using Java’s concurrency features (e.g., CompletableFuture, ExecutorService) to improve performance.</p><h4>🔗 No Rule Chaining</h4><p>This implementation doesn’t support chaining or dependent rule flows (e.g., Rule B should only execute if Rule A passes). If your rules have dependencies or branching logic, a more advanced orchestration approach would be required — possibly using a state machine or rule flow engine.</p><h4>🧯 Error &amp; Failure Handling</h4><p>As of now, failed validations are returned as simple true/false flags. In real-world systems, you&#39;d likely want richer error reporting, such as:</p><ul><li>Why a rule failed (error message or code)</li><li>Whether the rule should block the process or be skipped</li></ul><p>I’ll be covering these failure-handling strategies in my next article.</p><h4>🧠 Why Not Drools or a Rule Engine?</h4><p>This is a question I often get — and it’s a fair one.</p><p>For more complex, dynamic, or domain-expert-driven rule systems, you <strong>should absolutely consider a rules engine like </strong><a href="https://www.drools.org/"><strong>Drools</strong></a>. It offers:</p><ul><li>Declarative rule definitions (using DRL)</li><li>Rule chaining and salience (priority)</li><li>Forward/backward chaining</li><li>Built-in support for complex domain models</li><li>More efficient execution with rule indexing</li></ul><p>However, for my use case — 150+ well-defined rules written by developers — introducing Drools would’ve added unnecessary complexity and a steeper learning curve. I chose a code-driven approach to keep things lightweight, maintainable, and aligned with our current tech stack.</p><p>That said, <strong>this architecture is not meant to replace Drools</strong> — it’s just one way to organize and manage a large number of rules <em>in a Spring Boot codebase</em> without getting buried in if-else logic.</p><h3>🔜 What’s Next?</h3><p>In follow-up articles, I plan to cover:</p><ul><li>✅ <strong>Parallelizing rule execution</strong> for performance</li><li>🧯 <strong>Structured failure reporting</strong> and error propagation</li><li>🔗 <strong>Rule chaining and conditional execution</strong></li></ul><p>If you’re building something rules-heavy and wondering when to go “code vs engine,” stay tuned!</p><h3>📌 Conclusion</h3><p>Managing 150+ business rules doesn’t need to be ugly.</p><p>With the <strong>interface + Spring @Component + dynamic registry</strong> pattern, I was able to:</p><ul><li>Build a clean rules engine</li><li>Make it scalable for new rules</li><li>Keep each rule testable and modular</li></ul><p>This architecture has saved me hours of code review time, made onboarding new developers easier, and has proven robust in production.</p><p>If you’re building something rules-heavy — from fraud detection to eligibility validation — consider using this pattern.</p><h3>📚 Further Reading</h3><ul><li><a href="https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html">Spring Dependency Injection</a></li><li><a href="https://refactoring.guru/design-patterns/strategy">Strategy Design Pattern in Java</a></li></ul><h3>🤝 Let’s Connect</h3><p>If you found this useful, leave a comment or share how you manage rule-heavy systems in your own projects.</p><p>Follow me on <a href="https://medium.com/@venkatsai0398">Medium</a>, <a href="https://github.com/SaiNarsimhaGupta">GitHub</a>, or <a href="https://www.linkedin.com/in/sai-narsimha-gupta">LinkedIn</a> for more real-world engineering writeups!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8bafacc1031" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>