<?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 Bala s on Medium]]></title>
        <description><![CDATA[Stories by Bala s on Medium]]></description>
        <link>https://medium.com/@balagurumoorthya?source=rss-6d5a085fce48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TvXTmBgHXGsI-8h7</url>
            <title>Stories by Bala s on Medium</title>
            <link>https://medium.com/@balagurumoorthya?source=rss-6d5a085fce48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:33:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balagurumoorthya/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[From boilerplate to high-throughput: Mastering Streams, Virtual Threads, and Custom Collectors in…]]></title>
            <link>https://medium.com/@balagurumoorthya/from-boilerplate-to-high-throughput-mastering-streams-virtual-threads-and-custom-collectors-in-236af6fc208c?source=rss-6d5a085fce48------2</link>
            <guid isPermaLink="false">https://medium.com/p/236af6fc208c</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Bala s]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 00:16:02 GMT</pubDate>
            <atom:updated>2026-10-21T00:16:02.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>From boilerplate to high-throughput: Mastering Streams, Virtual Threads, and Custom Collectors in modern Java.</h3><p>Java has evolved significantly since the introduction of lambdas in Java 8. With the release of Java 25, functional paradigms are more seamlessly integrated into the language than ever, with enhanced pattern matching, record types, and streamlined collections.</p><p>In this article, we’ll explore how to leverage Java’s functional interfaces to build a clean, readable, and highly concurrent server-side Trading API. We will specifically dive into <strong>Predicates</strong>, <strong>Consumers (Acceptors)</strong>, <strong>Binary Functions</strong>, <strong>Stream Limiters</strong>, and <strong>Collectors</strong>.</p><h3>The Domain Model</h3><p>First, let’s define our core data structure using Java records, which provide immutable data carriers perfect for functional transformations.</p><pre>public record Trade(String tradeId, String symbol, double price, int quantity, Status status) {<br>    public enum Status { PENDING, PARTIAL, FILLED, REJECTED }<br>    <br>    public double getTotalValue() {<br>        return price * quantity;<br>    }<br>}</pre><h3>1. Filtering with Predicate</h3><p>In a trading system, you constantly need to filter streams of data — whether it’s finding rejected trades, filtering by specific tickers, or flagging unusually large orders. The Predicate&lt;T&gt; interface handles this elegantly.</p><pre>import java.util.function.Predicate;<br><br>Predicate&lt;Trade&gt; isHighVolume = trade -&gt; trade.quantity() &gt;= 10_000;<br>Predicate&lt;Trade&gt; isFilled = trade -&gt; trade.status() == Trade.Status.FILLED;<br>Predicate&lt;Trade&gt; isTechStock = trade -&gt; trade.symbol().matches(&quot;AAPL|MSFT|GOOGL&quot;);<br><br>// Combining predicates<br>Predicate&lt;Trade&gt; highVolumeTech = isFilled.and(isHighVolume).and(isTechStock);</pre><h3>2. Processing with Consumer (Acceptor)</h3><p>When you need to execute side effects — such as logging a trade to an audit trail or publishing a message to a Kafka topic — you use a Consumer&lt;T&gt; (often referred to conceptually as an acceptor).</p><pre>import java.util.function.Consumer;<br><br>Consumer&lt;Trade&gt; auditLogger = trade -&gt; <br>    System.out.printf(&quot;[AUDIT] Trade %s executed for %s%n&quot;, trade.tradeId(), trade.symbol());<br><br>Consumer&lt;Trade&gt; riskEnginePublisher = trade -&gt; <br>    RiskService.publish(trade);<br><br>// Chain consumers together<br>Consumer&lt;Trade&gt; processTrade = auditLogger.andThen(riskEnginePublisher);</pre><h3>3. Merging and Aggregating with BinaryOperator / BiFunction</h3><p>When dealing with partial fills, you often need to merge two trades into a single consolidated record. A BinaryOperator&lt;T&gt; (a specialized BiFunction&lt;T, T T,&gt;) is perfect for this.</p><pre>import java.util.function.BinaryOperator;<br><br>BinaryOperator&lt;Trade&gt; mergePartialFills = (t1, t2) -&gt; {<br>    if (!t1.symbol().equals(t2.symbol())) {<br>        throw new IllegalArgumentException(&quot;Cannot merge different symbols&quot;);<br>    }<br>    double vwap = ((t1.price() * t1.quantity()) + (t2.price() * t2.quantity())) <br>                  / (t1.quantity() + t2.quantity());<br>                  <br>    return new Trade(<br>        t1.tradeId() + &quot;-&quot; + t2.tradeId(),<br>        t1.symbol(),<br>        vwap,<br>        t1.quantity() + t2.quantity(),<br>        Trade.Status.FILLED<br>    );<br>};</pre><h3>4. Bringing it Together: Streams, Limiters, and Collectors</h3><p>Now let’s simulate a server-side endpoint that receives a massive stream of trades. We want to find the top 50 largest completed tech trades, log them, and then group them by symbol while calculating the total monetary volume for each.</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>public class TradeProcessor {<br><br>    public Map&lt;String, Double&gt; processMarketData(List&lt;Trade&gt; rawTrades) {<br>        return rawTrades.stream()<br>            // 1. Predicate: Filter the data<br>            .filter(isFilled.and(isTechStock))<br>            <br>            // Sort to get the largest trades first<br>            .sorted((t1, t2) -&gt; Double.compare(t2.getTotalValue(), t1.getTotalValue()))<br>            <br>            // 2. Limiter: Protect the server by only taking the top 50<br>            .limit(50)<br>            <br>            // 3. Consumer/Acceptor: Log the filtered, limited stream<br>            .peek(auditLogger)<br>            <br>            // 4. Collectors: Group by symbol and sum the total value<br>            .collect(Collectors.groupingBy(<br>                Trade::symbol,<br>                Collectors.reducing(<br>                    0.0, <br>                    Trade::getTotalValue, <br>                    Double::sum // BinaryFunction for aggregation<br>                )<br>            ));<br>    }<br>}</pre><h3>5. Scaling with Java 21+ Virtual Threads</h3><p>Functional pipelines are excellent for readability, but in a high-throughput Trading API, you often need to perform I/O-bound operations — like enriching a trade with real-time market data or validating against a remote risk engine — before applying your stream operations.</p><p>Prior to Java 21, doing this concurrently meant tying up expensive OS threads. With the introduction of <strong>Virtual Threads</strong> (Project Loom), we can now spin up millions of lightweight threads, combining the declarative power of functional streams with massive concurrency.</p><p>By pairing our functional predicates and consumers with a VirtualThreadPerTaskExecutor, we can process trades concurrently without blocking the main server threads:</p><pre>import java.util.List;<br>import java.util.Map;<br>import java.util.concurrent.CompletableFuture;<br>import java.util.concurrent.Executors;<br>import java.util.stream.Collectors;<br><br>public class ConcurrentTradeProcessor {<br><br>    public Map&lt;String, Double&gt; processConcurrently(List&lt;Trade&gt; rawTrades) {<br>        // Create an executor that spins up a new Virtual Thread for every task<br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            <br>            // 1. Fan-out: Enrich or validate each trade in its own virtual thread<br>            List&lt;CompletableFuture&lt;Trade&gt;&gt; enrichedFutures = rawTrades.stream()<br>                .map(trade -&gt; CompletableFuture.supplyAsync(() -&gt; {<br>                    // Simulate an I/O bound network call (e.g., Risk Engine validation)<br>                    return riskEngineValidator.apply(trade);<br>                }, executor))<br>                .toList();<br>                <br>            // 2. Fan-in: Join the virtual threads and apply our functional pipeline<br>            return enrichedFutures.stream()<br>                .map(CompletableFuture::join) // Non-blocking at the OS level!<br>                <br>                // Reuse our functional Predicates from earlier<br>                .filter(isFilled.and(isTechStock))<br>                <br>                .sorted((t1, t2) -&gt; Double.compare(t2.getTotalValue(), t1.getTotalValue()))<br>                .limit(50)<br>                <br>                // Reuse our Consumer<br>                .peek(auditLogger)<br>                <br>                // Reuse our Collector and BinaryOperator<br>                .collect(Collectors.groupingBy(<br>                    Trade::symbol,<br>                    Collectors.reducing(0.0, Trade::getTotalValue, Double::sum)<br>                ));<br>        }<br>    }<br>}</pre><h3>The Synergy of Functions and Virtual Threads</h3><p>Notice how seamlessly the virtual thread executor integrates with our existing Predicate and Consumer logic. The CompletableFuture.supplyAsync takes a functional Supplier, executes it on a highly efficient virtual thread, and then hands the result back to our declarative stream. This gives you the best of both worlds: synchronous, easy-to-read code that performs like a highly tuned asynchronous system.</p><h3>6. Testing the Pipeline with JUnit 5</h3><p>One of the greatest benefits of functional programming is testability. Because our business logic is built from pure functions, predicates, and immutable records, writing unit tests becomes incredibly straightforward.</p><p>Even though our ConcurrentTradeProcessor uses Virtual Threads under the hood, the method signature remains perfectly synchronous. We don&#39;t need complex CountDownLatch or Thread.sleep() hacks to test it.</p><p>Here is how you can test this pipeline using JUnit 5 and some mock trade data:</p><pre>import org.junit.jupiter.api.Test;<br>import java.util.List;<br>import java.util.Map;<br>import static org.junit.jupiter.api.Assertions.*;<br><br>class ConcurrentTradeProcessorTest {<br><br>    @Test<br>    void shouldFilterAndAggregateTechTradesConcurrently() {<br>        // Arrange: Create an immutable list of mock trades<br>        List&lt;Trade&gt; mockTrades = List.of(<br>            new Trade(&quot;T1&quot;, &quot;AAPL&quot;, 150.0, 100, Trade.Status.FILLED),   // 15,000 - Tech, Filled (Keep)<br>            new Trade(&quot;T2&quot;, &quot;MSFT&quot;, 300.0, 200, Trade.Status.FILLED),   // 60,000 - Tech, Filled (Keep)<br>            new Trade(&quot;T3&quot;, &quot;AAPL&quot;, 150.0, 50, Trade.Status.PENDING),   // 7,500 - Tech, Pending (Drop)<br>            new Trade(&quot;T4&quot;, &quot;TSLA&quot;, 200.0, 10, Trade.Status.FILLED),    // 2,000 - Non-Tech, Filled (Drop)<br>            new Trade(&quot;T5&quot;, &quot;GOOGL&quot;, 2800.0, 100, Trade.Status.FILLED), // 280,000 - Tech, Filled (Keep)<br>            new Trade(&quot;T6&quot;, &quot;AAPL&quot;, 155.0, 100, Trade.Status.FILLED)    // 15,500 - Tech, Filled (Keep)<br>        );<br><br>        // Assuming our processor is instantiated (and mock risk validator injected if needed)<br>        ConcurrentTradeProcessor processor = new ConcurrentTradeProcessor();<br><br>        // Act: Run the concurrent pipeline<br>        Map&lt;String, Double&gt; result = processor.processConcurrently(mockTrades);<br><br>        // Assert: Verify the aggregations and filtering<br>        assertAll(<br>            &quot;Verify Trade Aggregation&quot;,<br>            () -&gt; assertEquals(3, result.size(), &quot;Should only contain AAPL, MSFT, and GOOGL&quot;),<br>            <br>            // AAPL should be the sum of T1 (15,000) and T6 (15,500)<br>            () -&gt; assertEquals(30500.0, result.get(&quot;AAPL&quot;), 0.001, &quot;AAPL total is incorrect&quot;),<br>            <br>            // MSFT should be exactly T2 (60,000)<br>            () -&gt; assertEquals(60000.0, result.get(&quot;MSFT&quot;), 0.001, &quot;MSFT total is incorrect&quot;),<br>            <br>            // GOOGL should be exactly T5 (280,000)<br>            () -&gt; assertEquals(280000.0, result.get(&quot;GOOGL&quot;), 0.001, &quot;GOOGL total is incorrect&quot;),<br>            <br>            // TSLA should have been filtered out by the Predicate<br>            () -&gt; assertFalse(result.containsKey(&quot;TSLA&quot;), &quot;TSLA should be filtered out&quot;)<br>        );<br>    }<br>}</pre><h3>Why this test is effective</h3><p>By utilizing JUnit 5’s assertAll, we ensure that all assertions are evaluated even if the first one fails, giving us a complete picture of our pipeline&#39;s behavior. We can confidently verify that our Predicate successfully stripped out the PENDING AAPL trade and the non-tech TSLA trade, while our Collector flawlessly merged the two completed AAPL trades into a single summed value—all while Virtual Threads handled the heavy lifting concurrently.</p><h3>7. Exhaustive Routing with Switch Expressions and Pattern Matching</h3><p>In a functional pipeline, mapping data from one state to another is a daily task. When dealing with enums like Trade.Status, older Java switch statements were notoriously verbose and error-prone.</p><p>With Java 21+ switch expressions and pattern matching, we can transform enum states cleanly within our functional flows. Switch expressions are expressions (they return a value) and use the concise arrow (-&gt;) syntax, eliminating the need for break statements. More importantly, the compiler enforces <strong>exhaustiveness</strong>—meaning if a new status is added to Trade.Status in the future, the code will fail to compile until the switch is updated.</p><p>Here is how we can implement a functional Function&lt;Trade, String&gt; to map trades to status messages:</p><pre>import java.util.function.Function;<br><br>Function&lt;Trade, String&gt; statusMapper = trade -&gt; switch (trade.status()) {<br>    case PENDING  -&gt; &quot;Trade &quot; + trade.tradeId() + &quot; is awaiting execution.&quot;;<br>    case PARTIAL  -&gt; &quot;Trade &quot; + trade.tradeId() + &quot; is partially filled.&quot;;<br>    case FILLED   -&gt; &quot;Trade &quot; + trade.tradeId() + &quot; is fully executed.&quot;;<br>    case REJECTED -&gt; {<br>        // We can use blocks and the &#39;yield&#39; keyword for more complex logic<br>        System.err.println(&quot;[ALERT] Rejected trade detected: &quot; + trade.tradeId());<br>        yield &quot;Trade &quot; + trade.tradeId() + &quot; was rejected.&quot;;<br>    }<br>};<br><br>// Using it in a stream:<br>List&lt;String&gt; statusReports = rawTrades.stream()<br>    .map(statusMapper)<br>    .toList();</pre><h3>Why this is a game-changer</h3><p>By embedding switch expressions directly inside our Function mappers, we keep our stream pipelines incredibly clean. There is no need to drop out of the functional paradigm to handle complex branching logic. Plus, the compiler acts as an automatic safety net, ensuring every possible trade status is explicitly handled in our business logic.</p><h3>8. Beyond the Basics: Building Custom Collectors</h3><p>While built-in collectors like Collectors.groupingBy and Collectors.reducing are incredibly powerful, they can become unwieldy when you need to calculate multiple metrics simultaneously. For example, what if we want to calculate the total trade count, total volume, and the Volume Weighted Average Price (VWAP) in a single pass?</p><p>Creating intermediate objects for every step in reducing can create unnecessary garbage collection overhead. Instead, we can build a custom Collector that accumulates multiple statistics efficiently into a single mutable container.</p><p>First, let’s define an accumulator class to hold our running totals:</p><pre>public class TradeStats {<br>    private int tradeCount = 0;<br>    private int totalQuantity = 0;<br>    private double totalValue = 0.0;<br><br>    // Accumulator method: Adds a single trade&#39;s data<br>    public void add(Trade trade) {<br>        this.tradeCount++;<br>        this.totalQuantity += trade.quantity();<br>        this.totalValue += trade.getTotalValue();<br>    }<br><br>    // Combiner method: Merges two TradeStats (crucial for parallel streams)<br>    public TradeStats merge(TradeStats other) {<br>        this.tradeCount += other.tradeCount;<br>        this.totalQuantity += other.totalQuantity;<br>        this.totalValue += other.totalValue;<br>        return this;<br>    }<br><br>    public double getVwap() {<br>        return totalQuantity == 0 ? 0.0 : totalValue / totalQuantity;<br>    }<br>    <br>    @Override<br>    public String toString() {<br>        return String.format(&quot;Trades: %d | Vol: %d | VWAP: $%.2f&quot;, <br>                             tradeCount, totalQuantity, getVwap());<br>    }<br>}</pre><p>Now, we use Collector.of() to wire our functional components together: a <strong>Supplier</strong> (creates the container), an <strong>Accumulator</strong> (adds elements), and a <strong>Combiner</strong> (merges containers for parallel streams).</p><pre>import java.util.stream.Collector;<br>import java.util.Map;<br>import java.util.List;<br>import java.util.stream.Collectors;<br><br>public class AdvancedTradeAggregator {<br><br>    public static void main(String[] args) {<br>        List&lt;Trade&gt; trades = getMarketData(); // Assume this returns our trades<br>        <br>        // Define the custom collector<br>        Collector&lt;Trade, TradeStats, TradeStats&gt; statsCollector = Collector.of(<br>            TradeStats::new,   // Supplier<br>            TradeStats::add,   // BiConsumer (Accumulator)<br>            TradeStats::merge  // BinaryOperator (Combiner)<br>        );<br><br>        // Group by symbol, but use our custom collector for the downstream aggregation!<br>        Map&lt;String, TradeStats&gt; marketStats = trades.stream()<br>            .filter(trade -&gt; trade.status() == Trade.Status.FILLED)<br>            .collect(Collectors.groupingBy(<br>                Trade::symbol,<br>                statsCollector<br>            ));<br><br>        marketStats.forEach((symbol, stats) -&gt; <br>            System.out.println(symbol + &quot; -&gt; &quot; + stats)<br>        );<br>    }<br>}</pre><h3>Why custom Collectors excel</h3><p>By defining a custom Collector, we loop through the stream exactly once, performing three different mathematical aggregations without allocating any throwaway wrapper objects for intermediate reductions. It integrates seamlessly as a downstream collector inside groupingBy, keeping the top-level stream pipeline beautifully declarative while hiding the complex math inside the TradeStats object.</p><h3>Conclusion</h3><p>By separating the <em>what</em> (Predicates, Consumers) from the <em>how</em> (Stream evaluation and Virtual Threads), a modern Java trading server remains robust, easy to test, and highly readable.</p><p>Functional programming in Java has matured from a bolt-on feature to a foundational way of structuring high-performance applications. Whether you are building low-latency trading engines, orchestrating complex microservices, or simply trying to make your enterprise codebase more maintainable, Java 25 provides the tools to write code that is as elegant as it is powerful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236af6fc208c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Monolith to Microservices: Architecting the Future of Digital Banking]]></title>
            <link>https://medium.com/@balagurumoorthya/from-monolith-to-microservices-architecting-the-future-of-digital-banking-273e0259c0e6?source=rss-6d5a085fce48------2</link>
            <guid isPermaLink="false">https://medium.com/p/273e0259c0e6</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Bala s]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 00:11:01 GMT</pubDate>
            <atom:updated>2026-10-08T00:11:01.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUl1Z5AE26firDNGwsFuxQ.jpeg" /></figure><p>Transforming a monolithic online banking application into a microservices architecture becomes significantly more resilient and performant when you incorporate modern API offloading, stateless authentication, and robust observability.</p><p>Here is the expanded blueprint incorporating GraphQL, JWTs, caching, and specialized monitoring teams.</p><h3>1. Microservices Decomposition &amp; Data Offloading</h3><ul><li><strong>CQRS (Command Query Responsibility Segregation):</strong> Banking applications are heavily read-skewed. To prevent user login spikes from bogging down the core banking transaction engines, we implement CQRS to separate commands (writes, like initiating a transfer) from queries (reads). By utilizing this pattern, the system fetches the user’s last known balance and account details from a highly optimized Read-Only store, completely bypassing the primary, high-latency transactional databases.</li><li><strong>API-Backed Cache (Read Offloading):</strong> Complementing CQRS, a distributed caching layer (like Redis) sits in front of the microservices. It serves frequently accessed or slowly changing read requests (such as routing numbers, reward tiers, or temporary session states) almost instantly, further offloading traffic from the backend.</li><li><strong>Database per Service:</strong> The monolithic relational database is split so each microservice (Accounts, Loans, Payments) owns its respective data store. This prevents tightly coupled schema changes and allows the Read-Only stores (utilized by CQRS) to be scaled independently of the write databases.</li><li><strong>Saga Pattern (Distributed Transactions):</strong> Because banking requires strict data integrity, transactions spanning multiple services (e.g., transferring funds across bounded contexts) use Sagas. If a step fails, compensating transactions are triggered to roll back the previous steps, maintaining eventual consistency across the decentralized databases.</li></ul><h3>2. Stateless Authentication (12-Factor App Rules)</h3><ul><li><strong>JWT-Based Auth (Replacing Sessions):</strong> Traditional monoliths rely on stateful server-side sessions, which hinder auto-scaling because the server must remember the user. By switching to JSON Web Tokens (JWT), authentication becomes entirely stateless (adhering to 12-Factor Rule VI). The Identity Provider issues a cryptographically signed JWT containing user claims. Microservices can independently verify this token without querying a central session database for every single request.</li><li><strong>Config &amp; Disposability:</strong> Configuration is stored in the environment (Rule III), and services are designed to start instantly and shut down gracefully (Rule IX) to support Kubernetes auto-scaling.</li></ul><h3>3. Advanced Edge Systems: GraphQL BFF</h3><ul><li><strong>GraphQL as the Backend for Frontend (BFF):</strong> Instead of a single REST API or multiple bloated endpoints, deploy GraphQL as the BFF layer. GraphQL allows the mobile or web client to specify exactly what data it needs in a single query. The GraphQL orchestrator fetches user details from the Auth service, balances from Accounts, and recent transactions from Payments in parallel, stitching them into one optimized response payload. This minimizes network latency and prevents over-fetching data to mobile devices.</li><li><strong>Open Banking API Gateway:</strong> A dedicated gateway exposing normalized financial data to third-party providers using OAuth2/OIDC for secure user consent management.</li></ul><h3>4. Kubernetes Hosting &amp; Observability Infrastructure</h3><ul><li><strong>Container Orchestration:</strong> Each microservice runs as a Docker container managed by Kubernetes, which handles load balancing and self-healing.</li><li><strong>Service Mesh (e.g., Istio):</strong> Handles internal service-to-service communication, enforcing mutual TLS (mTLS) for zero-trust security.</li><li><strong>Centralized Logging &amp; Monitoring Services:</strong> In a distributed architecture, tracking a single failed payment requires specialized tools:</li><li><strong>Logging:</strong> An ELK Stack (Elasticsearch, Logstash, Kibana) or Splunk aggregates logs from every container into a single searchable dashboard.</li><li><strong>Metrics:</strong> Prometheus scrapes resource metrics (CPU/Memory) and business metrics (transaction rates), visualized in Grafana.</li><li><strong>Distributed Tracing:</strong> Tools like Jaeger or OpenTelemetry inject a correlation ID at the edge gateway. This ID is passed in the headers to every downstream microservice, allowing you to visualize the exact execution path and latency bottlenecks of a single request.</li></ul><h3>5. Reorganizing Teams: Squads &amp; SREs</h3><ul><li><strong>Cross-Functional Squads:</strong> Transition from horizontal silos (Frontend, Backend, DBA) to vertical “Squads” (e.g., “Payments Squad”). They own a specific business domain, building and deploying their own microservices (“You build it, you run it”).</li><li><strong>Site Reliability Engineering (SRE) &amp; Observability Team:</strong> You must introduce a dedicated SRE team. They do not build banking features. Instead, they build the monitoring infrastructure, define Service Level Objectives (SLOs), manage alerting thresholds, and provide the internal platform tooling that allows the product Squads to understand their services’ health in production.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273e0259c0e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structuring Scalable Frontends: Building an N-Layered Architecture with Lit, GraphQL, and Context]]></title>
            <link>https://medium.com/@balagurumoorthya/structuring-scalable-frontends-building-an-n-layered-architecture-with-lit-graphql-and-context-f02f80e2a83d?source=rss-6d5a085fce48------2</link>
            <guid isPermaLink="false">https://medium.com/p/f02f80e2a83d</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Bala s]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 09:03:46 GMT</pubDate>
            <atom:updated>2026-10-07T09:03:46.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMHk6hy2zjH1GKoPnq2yEw.jpeg" /></figure><p>If you have ever opened a frontend web component and found a terrifying spaghetti bowl of UI markup, API fetching logic, and global state mutations all crammed into one file, you are not alone. As frontend applications grow, coupling your data layer directly to your presentation layer creates fragile, unmaintainable code.</p><p>The solution is an <strong>N-Layered Architecture</strong>. By strictly separating where data is fetched, where it is stored, and how it is displayed, you create a system that is predictable and easy to debug.</p><p>Let’s break down this architecture using <strong>Lit</strong>, <strong>GraphQL</strong>, and <strong>Lit Context</strong>.</p><h3>The Architecture of Data Flow</h3><p>In a well-structured N-Layered frontend, data flows in a single, predictable direction from the server to the screen. Here is how our tech stack maps to distinct architectural layers:</p><ul><li><strong>The Backend Layer (Microservices):</strong> This is the ultimate source of truth. Your user databases, core business logic, and authentications live securely on downstream servers.</li><li><strong>The API Layer (GraphQL):</strong> GraphQL acts as the network gateway. Instead of making multiple REST calls to various microservices, you write GraphQL queries to fetch exactly the shape of the data the frontend requires.</li><li><strong>The Orchestration Layer (Root Component):</strong> The top-level Lit component in your application acts as the manager. It executes the GraphQL network requests and stores the result in its local component state.</li><li><strong>The State Layer (Lit Context):</strong> Lit Context acts as an invisible broadcast system. Once the Root Component has cached the data, Context publishes it downward through the DOM tree.</li><li><strong>The Presentation Layer (Leaf Components):</strong> These are your pure UI components. They do not know how to fetch data. They simply subscribe to the Lit Context and render the provided data to the screen.</li></ul><h3>Parallel Data Fetching: Static vs. Functional Data</h3><p>When initializing an application, we typically deal with two distinct types of data:</p><ol><li><strong>Static Data:</strong> Application configurations, theme settings, and feature flags. This data rarely changes during a session.</li><li><strong>Functional (Dynamic) Data:</strong> User profiles, real-time dashboard feeds, or shopping cart contents. This data drives the actual business value of the view.</li></ol><p>If we fetch these sequentially (waiting for static config to load <em>before</em> asking for the user profile), we artificially slow down the application. Instead, our Root Component should fetch them in parallel using JavaScript’s Promise.all(). This ensures both GraphQL queries race across the network simultaneously.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCFWVNtzfCG0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCFWVNtzfCG0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCFWVNtzfCG0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/da2e734c1c4eb40a0ecfe29c62f2d5eb/href">https://medium.com/media/da2e734c1c4eb40a0ecfe29c62f2d5eb/href</a></iframe><h3>Layer 1 &amp; 2: Fetching and Caching at the Root</h3><p>Here is our Orchestration Layer (Root Component) executing the parallel network requests and establishing the local cache for both our static and functional data.</p><pre>import { LitElement, html } from &#39;lit&#39;;<br>import { customElement, state } from &#39;lit/decorators.js&#39;;<br>import { provide, createContext } from &#39;@lit/context&#39;;<br><br>// 1. Define the Data Contracts<br>export interface AppConfig { theme: string; features: string[]; }<br>export interface UserProfile { name: string; role: string; }<br><br>export const configContext = createContext&lt;AppConfig&gt;(&#39;app-config&#39;);<br>export const userContext = createContext&lt;UserProfile&gt;(&#39;user-profile&#39;);<br><br>@customElement(&#39;app-root&#39;)<br>export class AppRoot extends LitElement {<br>  <br>  // 2. The Context Providers: Broadcasting our cached state<br>  @provide({ context: configContext })<br>  @state()<br>  private cachedConfig?: AppConfig;<br><br>  @provide({ context: userContext })<br>  @state()<br>  private activeUser?: UserProfile;<br><br>  connectedCallback() {<br>    super.connectedCallback();<br>    this.initializeData();<br>  }<br><br>  // 3. Fetching Static and Functional Data in Parallel<br>  private async initializeData() {<br>    try {<br>      // Promise.all fires both network requests simultaneously<br>      const [configResponse, userResponse] = await Promise.all([<br>        this.fetchStaticConfig(),<br>        this.fetchFunctionalData()<br>      ]);<br><br>      // Cache the responses at the root. <br>      // This automatically pushes updates to all Context subscribers!<br>      this.cachedConfig = configResponse.data.appConfig;<br>      this.activeUser = userResponse.data.userProfile;<br>      <br>    } catch (error) {<br>      console.error(&quot;Failed to initialize application data&quot;, error);<br>    }<br>  }<br><br>  private async fetchStaticConfig() {<br>    const query = `query { appConfig { theme features } }`;<br>    return fetch(&#39;/graphql&#39;, { method: &#39;POST&#39;, body: JSON.stringify({ query }) }).then(r =&gt; r.json());<br>  }<br><br>  private async fetchFunctionalData() {<br>    const query = `query { userProfile { name role } }`;<br>    return fetch(&#39;/graphql&#39;, { method: &#39;POST&#39;, body: JSON.stringify({ query }) }).then(r =&gt; r.json());<br>  }<br><br>  render() {<br>    // Render UI only when BOTH static and functional data have resolved<br>    const isReady = this.cachedConfig &amp;&amp; this.activeUser;<br>    <br>    return html`<br>      ${isReady <br>        ? html`&lt;dashboard-ui&gt;&lt;/dashboard-ui&gt;` <br>        : html`&lt;div class=&quot;loader&quot;&gt;Loading workspace...&lt;/div&gt;`}<br>    `;<br>  }<br>}</pre><p>By storing the data at the root and decorating it with @provide, we establish an efficient, centralized cache. The application now has stable local states for both configurations and user data to distribute to the interface.</p><h3>Layer 3 &amp; 4: Subscribing to Data in the UI</h3><p>Now we move down to the <strong>Presentation Layer</strong>. These “Leaf” components are completely oblivious to Promise.all(), HTTP headers, or backend microservices. Their only job is to consume data and render HTML.</p><p>Using Lit Context’s @consume decorator, these components simply tap into the exact slice of state they need.</p><pre>import { LitElement, html, css } from &#39;lit&#39;;<br>import { customElement, property } from &#39;lit/decorators.js&#39;;<br>import { consume } from &#39;@lit/context&#39;;<br>import { configContext, userContext, AppConfig, UserProfile } from &#39;./app-root.js&#39;;<br><br>@customElement(&#39;dashboard-ui&#39;)<br>export class DashboardUI extends LitElement {<br>  <br>  // 1. The Subscriptions: Pulling the cached data straight from Context<br>  // Bypassing all intermediate DOM elements completely.<br>  @consume({ context: configContext, subscribe: true })<br>  @property({ attribute: false })<br>  public config?: AppConfig;<br><br>  @consume({ context: userContext, subscribe: true })<br>  @property({ attribute: false })<br>  public user?: UserProfile;<br><br>  static styles = css`<br>    .theme-dark { background: #1a1a1a; color: white; }<br>    .theme-light { background: #ffffff; color: black; }<br>  `;<br><br>  render() {<br>    return html`<br>      &lt;div class=&quot;theme-${this.config?.theme || &#39;light&#39;}&quot;&gt;<br>        &lt;h1&gt;Welcome, ${this.user?.name}!&lt;/h1&gt;<br>        &lt;p&gt;Role: ${this.user?.role}&lt;/p&gt;<br>        <br>        &lt;h2&gt;Active Features:&lt;/h2&gt;<br>        &lt;ul&gt;<br>          ${this.config?.features.map(<br>            feature =&gt; html`&lt;li&gt;${feature}&lt;/li&gt;`<br>          )}<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    `;<br>  }<br>}</pre><p>Because we set subscribe: true on the @consume decorator, if the Root Component ever fetches new data (e.g., the user changes their theme), this UI component will automatically re-render. There is no need to manually pass properties down through dozens of parent-child relationships, eliminating the dreaded &quot;prop-drilling&quot; problem.</p><h3>The Network Layer Impact: How HTTP/1, 2, and 3 Affect This Stack</h3><p>While the component architecture organizes your code, the underlying HTTP protocol dictates how efficiently this Promise.all() fetching and code actually travel over the network.</p><ul><li><strong>HTTP/1.1 (The Gateway Optimizer):</strong> Older browsers using HTTP/1.1 suffer from TCP head-of-line blocking and strictly limit concurrent connections. In this environment, our architecture shines. Instead of a dozen scattered REST calls fighting for connection slots, our Promise.all executes exactly two clean GraphQL queries (one for static, one for functional). GraphQL masks the limitations of HTTP/1.1 by bundling complex requirements into minimal payloads.</li><li><strong>HTTP/2 (Multiplexing the Component Tree):</strong> HTTP/2 introduced multiplexing, allowing multiple streams of data over a single TCP connection. Modern Lit applications are often bundled as many small ECMAScript (ES) modules. With HTTP/2, the browser can aggressively download dozens of lightweight Lit UI component files simultaneously while the Root Component’s parallel GraphQL fetches are in flight, drastically reducing the time to interactive (TTI).</li><li><strong>HTTP/3 (Resiliency on the Edge):</strong> Built on the UDP-based QUIC protocol, HTTP/3 eliminates TCP head-of-line blocking entirely. If a user is viewing your dashboard on a spotty mobile connection and a packet is lost, it only delays that specific stream. For our architecture, this means if a chunk of a Lit component gets delayed, the Root Component’s critical Promise.all data fetch continues unhindered. HTTP/3 ensures the underlying data orchestration layer remains highly resilient.</li></ul><p>When you adopt an N-Layered architecture, you transform a chaotic codebase into a predictable machine. By treating your UI components purely as presentation receivers, your root app as the orchestration cache, and GraphQL as your parallel network gateway, you naturally enforce a separation of concerns that scales beautifully from a weekend project to an enterprise application.</p><h3>Structuring Your Repository: A Folder Strategy for N-Layered Architectures</h3><p>A great architecture is useless if your codebase is a disorganized mess. The physical folder structure of your project should directly reflect the logical boundaries of your architecture. When a junior developer opens the repository for the first time, the directory tree itself should tell them exactly where data is fetched, where it is stored, and where it is rendered.</p><p>To enforce the N-Layered approach we established (Lit, GraphQL, and Context), your content organization strategy should strictly separate the Orchestration, API, Context, and UI layers.</p><p>Here is a highly scalable directory structure that enforces these boundaries:</p><pre>  <br>src/<br>├── api/                  # The Network Layer<br>│   ├── client.ts         # Base fetch configuration &amp; error handling<br>│   ├── queries/          # GraphQL query strings<br>│   │   ├── static.ts     # e.g., getConfig, getTheme<br>│   │   └── user.ts       # e.g., getUserProfile, getPermissions<br>│   └── mutations/        # GraphQL mutation strings<br>│<br>├── context/              # The State Layer (Contracts &amp; Publishers)<br>│   ├── config.context.ts # AppConfig interface and createContext()<br>│   └── user.context.ts   # UserProfile interface and createContext()<br>│<br>├── components/           # The Presentation Layer (Leaf Components)<br>│   ├── shared/           # Dumb, highly reusable UI (buttons, cards, inputs)<br>│   ├── dashboard/        # Feature-specific UI components<br>│   │   ├── dashboard-ui.ts<br>│   │   └── user-widget.ts<br>│   └── navigation/<br>│       └── side-menu.ts<br>│<br>├── orchestrators/        # The Orchestration Layer (Root Components)<br>│   ├── app-root.ts       # The main entry point (Promise.all fetches live here)<br>│   └── workspace-root.ts # Sub-orchestrators for complex nested routes<br>│<br>└── index.html            # Application entry</pre><h3>The Rules of the Repository</h3><p>To keep this architecture intact as your team grows, you can enforce three simple rules during code reviews based on this folder structure:</p><p><strong>1. The Presentation Rule (</strong><strong>/components):</strong> Files inside the /components folder are strictly prohibited from importing anything from the /api folder. A Leaf Component must never trigger a network request. If a component needs data, it must import a context token from /context and use the @consume decorator.</p><p><strong>2. The Network Rule (</strong><strong>/api):</strong> The /api folder only exports pure functions, query strings, and standard JavaScript/TypeScript types. It should contain zero Lit code, zero HTML templates, and zero CSS. This makes your network layer completely UI-agnostic and incredibly easy to unit test.</p><p><strong>3. The Orchestration Rule (</strong><strong>/orchestrators):</strong> Files in /orchestrators are the only components allowed to import from <em>both</em> /api and /context. Their sole responsibility is bridging the gap: they call the API, await the data, and assign it to the Context providers. Because their job is orchestration, they should contain minimal HTML—usually just a wrapper &lt;div&gt; and the tags for the Leaf Components they are rendering.</p><h3>Why This Strategy Works for Growing Teams</h3><p>By physically separating your layers into distinct folders, you eliminate the cognitive load of navigating the codebase.</p><ul><li><strong>When an API contract changes:</strong> You only update the GraphQL strings in /api and the TypeScript interfaces in /context.</li><li><strong>When a designer requests a UI overhaul:</strong> You only touch the CSS and HTML inside /components. You don&#39;t have to worry about accidentally breaking a critical network fetch.</li><li><strong>When you need to debug a slow initial load:</strong> You go straight to /orchestrators/app-root.ts to inspect the Promise.all logic.</li></ul><p>This organization strategy turns your file system into a physical map of your architecture, making it virtually impossible to accidentally couple your <strong>GraphQL network requests</strong> to your UI buttons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f02f80e2a83d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Java 8 to Java 25: A Code-First Guide to the Modern Java Evolution]]></title>
            <link>https://medium.com/@balagurumoorthya/from-java-8-to-java-25-a-code-first-guide-to-the-modern-java-evolution-28033d99c565?source=rss-6d5a085fce48------2</link>
            <guid isPermaLink="false">https://medium.com/p/28033d99c565</guid>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[java25]]></category>
            <dc:creator><![CDATA[Bala s]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 07:42:21 GMT</pubDate>
            <atom:updated>2026-10-07T07:42:21.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxUph8vAZmfgD7xJS_Zy-Q.jpeg" /></figure><p>Java 8 fundamentally changed how we wrote code in 2014 by introducing Streams and Lambdas. Since then, the platform has accelerated its release cadence, delivering hundreds of JDK Enhancement Proposals (JEPs). While many of these were under-the-hood JVM optimizations (like ZGC and G1 enhancements), the <em>language itself</em> has undergone a massive transformation.</p><p>If you are migrating a legacy Java 8 codebase to Java 21, or preparing for the Java 25 Long-Term Support (LTS) release, your daily coding habits are about to change.</p><p>Here is a side-by-side comparison of how you wrote code in Java 8, and how you will write it in Java 25, utilizing the most impactful developer-facing JEPs.</p><h3>1. Data Carriers (JEP 395: Records)</h3><p>For decades, Java developers relied on IDE generation or libraries like Lombok to avoid writing boilerplate getters, setters, equals(), and hashCode() methods. Records introduce native, immutable data carriers to the language.</p><p><strong>The Java 8 Way:</strong></p><pre>public class User {<br>    private final String name;<br>    private final String email;<br><br>    public User(String name, String email) {<br>        this.name = name;<br>        this.email = email;<br>    }<br><br>    public String getName() { return name; }<br>    public String getEmail() { return email; }<br><br>    @Override<br>    public boolean equals(Object o) { /* 10 lines of boilerplate */ }<br>    <br>    @Override<br>    public int hashCode() { /* 3 lines of boilerplate */ }<br>}</pre><p>The Java 25 Way:</p><pre>public record User(String name, String email) {}</pre><h3>2. Multi-line Strings (JEP 378: Text Blocks)</h3><p>Writing JSON, SQL, or HTML inside Java used to mean an unreadable mess of escaped quotes and manual newline concatenations. Text blocks eliminate this friction.</p><p><strong>The Java 8 Way:</strong></p><pre>String json = &quot;{\n&quot; +<br>              &quot;  \&quot;name\&quot;: \&quot;Java\&quot;,\n&quot; +<br>              &quot;  \&quot;version\&quot;: 8\n&quot; +<br>              &quot;}&quot;;</pre><p>The Java 25 Way:</p><pre>String json = &quot;&quot;&quot;<br>              {<br>                &quot;name&quot;: &quot;Java&quot;,<br>                &quot;version&quot;: 25<br>              }<br>              &quot;&quot;&quot;;</pre><h3>3. Type Checking and Casting (JEP 394: Pattern Matching for instanceof)</h3><p>Checking an object’s type and immediately casting it to use its methods is one of the most common patterns in Java. Pattern matching removes the redundant cast.</p><p><strong>The Java 8 Way:</strong></p><pre>if (obj instanceof String) {<br>    String s = (String) obj; // Redundant cast<br>    System.out.println(s.toLowerCase());<br>}</pre><p>The Java 25 Way:</p><pre>if (obj instanceof String s) {<br>    System.out.println(s.toLowerCase()); // &#39;s&#39; is already cast and in scope<br>}</pre><h3>4. Branching Logic (JEP 361 &amp; 441: Switch Expressions &amp; Pattern Matching)</h3><p>The traditional switch statement was statement-based (requiring break to avoid fall-through) and only accepted a few basic types. Modern Java turns switch into an expression that can return a value, exhaustively check types, and instantly destructure Records.</p><p><strong>The Java 8 Way:</strong></p><pre>String formatted;<br>if (obj instanceof Integer) {<br>    formatted = String.format(&quot;int %d&quot;, (Integer) obj);<br>} else if (obj instanceof Long) {<br>    formatted = String.format(&quot;long %d&quot;, (Long) obj);<br>} else {<br>    formatted = obj.toString();<br>}</pre><p>The Java 25 Way:</p><pre>String formatted = switch (obj) {<br>    case Integer i -&gt; String.format(&quot;int %d&quot;, i);<br>    case Long l    -&gt; String.format(&quot;long %d&quot;, l);<br>    case null      -&gt; &quot;Null value provided&quot;;<br>    default        -&gt; obj.toString();<br>};</pre><h3>5. Advanced Stream Operations (JEP 485: Stream Gatherers)</h3><p>Java 8 gave us the Stream API, but complex intermediate operations (like windowing, folding, or custom grouping) were difficult to implement without writing custom Spliterators or pulling in third-party libraries. Java 24/25 introduces Stream Gatherers to make Streams infinitely extensible.</p><p><strong>The Java 8 Way (Simulating batches of 3):</strong></p><pre>// Requires complex external libraries (like Guava Iterables) <br>// or verbose custom collectors that break the fluent Stream chain.<br>List&lt;List&lt;Integer&gt;&gt; batches = new ArrayList&lt;&gt;();<br>List&lt;Integer&gt; current = new ArrayList&lt;&gt;();<br>for (Integer i : List.of(1, 2, 3, 4, 5)) {<br>    current.add(i);<br>    if (current.size() == 3) {<br>        batches.add(current);<br>        current = new ArrayList&lt;&gt;();<br>    }<br>}</pre><p>The Java 25 Way:</p><pre>List&lt;List&lt;Integer&gt;&gt; batches = Stream.of(1, 2, 3, 4, 5)<br>    .gather(Gatherers.windowFixed(3))<br>    .toList(); <br>// Result: [[1, 2, 3], [4, 5]]</pre><h3>6. Ignored Variables (JEP 456: Unnamed Variables)</h3><p>How often have you caught an exception just to ignore it, or iterated through a map where you only needed the keys? The unnamed variable (_) signals intent clearly and suppresses compiler warnings.</p><p><strong>The Java 8 Way:</strong></p><pre>try {<br>    int id = Integer.parseInt(input);<br>} catch (NumberFormatException e) { <br>    // &#39;e&#39; is never used, IDE flags a warning<br>    System.out.println(&quot;Invalid input&quot;);<br>}</pre><p>The Java 25 Way:</p><pre>try {<br>    int id = Integer.parseInt(input);<br>} catch (NumberFormatException _) { <br>    // &#39;_&#39; explicitly tells the compiler and other devs this is ignored<br>    System.out.println(&quot;Invalid input&quot;);<br>}</pre><h3>7. High-Throughput Concurrency (JEP 444: Virtual Threads)</h3><p>Before Virtual Threads, Java threads were mapped 1:1 to OS threads. OS threads are heavy and expensive, meaning thread pools maxed out at a few thousand threads. Virtual Threads are lightweight, allowing you to run <em>millions</em> of concurrent tasks without memory exhaustion, revolutionizing non-blocking I/O.</p><p><strong>The Java 8 Way:</strong></p><pre>// Heavy, limited by OS capabilities<br>ExecutorService executor = Executors.newFixedThreadPool(100);<br>for (int i = 0; i &lt; 100_000; i++) {<br>    executor.submit(() -&gt; performDatabaseCall());<br>}</pre><p>The Java 25 Way:</p><pre>// Lightweight, handles millions of tasks effortlessly<br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    for (int i = 0; i &lt; 100_000; i++) {<br>        executor.submit(() -&gt; performDatabaseCall());<br>    }<br>}</pre><h3>The Bottom Line</h3><p>Java 25 isn’t just faster under the hood; it is a more expressive, concise, and safe language. If your team is still writing Java 8 style code, migrating to the modern features highlighted above will drastically reduce boilerplate, eliminate entire categories of bugs (like fall-through switch statements and Null Pointer Exceptions), and make your codebase infinitely more readable</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28033d99c565" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>