<?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 Vatsal Gupta on Medium]]></title>
        <description><![CDATA[Stories by Vatsal Gupta on Medium]]></description>
        <link>https://medium.com/@vatsuvaksi?source=rss-43c8f4f75f0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*64aGG5K0R3LmzrHo3KV1Lw.jpeg</url>
            <title>Stories by Vatsal Gupta on Medium</title>
            <link>https://medium.com/@vatsuvaksi?source=rss-43c8f4f75f0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:14:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vatsuvaksi/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[The Postgres Evolution: From SQL to Vectors to Graphs]]></title>
            <link>https://medium.com/@vatsuvaksi/the-postgres-evolution-from-sql-to-vectors-to-graphs-3cbdf3d6af14?source=rss-43c8f4f75f0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cbdf3d6af14</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Vatsal Gupta]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 10:01:26 GMT</pubDate>
            <atom:updated>2026-09-14T10:01:26.783Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Introduction</blockquote><p>PostgreSQL’s pace of innovation has exploded in recent releases. Although when it comes to <strong>ISO/IEC 9075–16:2023 [Property Graph Queries (SQL/PGQ)]</strong> particularly, it is still behind Google Spanner and Oracle AI DB, as they have mature implementations that are production-ready but I am still happy, as I was waiting for psql to release this, as most of the ecosystems I have been working with are written on Postgres only. As AI-driven features surged, PostgreSQL quickly embraced vector search (via extensions like <strong>pgvector</strong> and related tooling), letting teams use <strong>one database</strong> for both relational data and high-dimensional embeddings. Now, PostgreSQL 19 takes the next step: it adds <strong>SQL/PGQ</strong> (the SQL Property Graph Query standard) natively. This means you can define a graph layer on top of your tables and run graph-pattern queries <strong>without</strong> moving data to a separate graph DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9r8_ewyxlvwoF_w-PsvmQ.png" /></figure><p>For those who don’t know me, I’m an engineer obsessed with <strong>high-throughput systems, event-driven architectures, and low-latency distributed systems</strong>. Naturally, over the last couple of years, that curiosity has pulled me toward AI-powered applications.</p><p>I’ve spent quite a bit of time playing with <strong>LLMs, RAG pipelines, embeddings, vector search, and AI-native applications</strong>. And somewhere along the way, I noticed something interesting.</p><p>The AI revolution didn’t just change how we build applications.</p><blockquote><strong>It changed what we expect our databases to understand.</strong></blockquote><p>First came vectors. Suddenly, our databases needed to understand <em>similarity,</em> not just whether two rows matched. And now, there’s another shift happening. Modern applications are becoming increasingly <strong>connected</strong>.</p><p>Users follow users.<br>Users interact with products.<br>Products belong to categories.<br>Documents reference entities.<br>AI agents use tools.<br>Tools have permissions.<br>Everything is connected to something else.</p><p>At some point, the question stops being: <strong><em>“What data do I have?” </em></strong>and becomes: <strong><em>“What is connected to what?” </em></strong>And that’s where things get interesting. Because we’ve actually been storing graphs for years. We just called them <strong>tables, foreign keys, junction tables, and JOINs</strong>. And it works beautifully… until the questions start becoming about <strong>paths, connections, and multiple hops</strong>. A seemingly innocent question like: <strong>“Which products should I recommend to this user based on what similar users interacted with?” </strong>can quickly turn into a maze of JOINs, subqueries, and recursive CTEs.</p><p><strong>What if we stopped treating those relationships as JOINs and started treating them as a graph?</strong></p><p>That’s what caught my attention about <strong>ISO/IEC 9075–16:2023 and SQL/PGQ</strong>. Not because PostgreSQL or Spanner or Oracle AI is suddenly trying to replace every graph database out there, but because something much more interesting is happening:</p><p><strong>The same relational data we already have can now be viewed through a graph lens.</strong></p><p>Same database.<br>Same tables.<br>Same relationships.</p><p>Just a different way of asking questions. And in this article, I want to take one real-world problem, build it the old-fashioned way, watch the SQL get progressively uglier, and then solve the same problem using PostgreSQL’s graph capabilities.</p><p>Because sometimes the biggest improvement in a system isn’t making the database faster.</p><p><strong>It’s making the question easier to ask.</strong></p><blockquote>What’s New in PostgreSQL 19: Native Graph Support</blockquote><p>PostgreSQL 19 (beta) introduces <strong>SQL/PGQ</strong>, the ISO/IEC 9075‑16:2023 syntax for property-graph queries. In practice, you use CREATE PROPERTY GRAPH to declare one or more <strong>vertex tables</strong> and <strong>edge tables</strong> (based on your existing tables) that form the graph. For example, foreign-key relationships in your tables become the <strong>edges</strong> of the graph, and rows become <strong>vertices</strong>. Once the graph is defined, you query it with GRAPH_TABLE (...) MATCH ... COLUMNS ... patterns in effect, a graph match instead of hand-rolled JOINs.</p><p><strong>Importantly</strong>, PostgreSQL 19 <strong>does not copy or duplicate data</strong>: the graph is a semantic <em>layer</em> over the relational tables. No special graph engine is spun up, behind the scenes, the planner still uses joins on your tables. In fact, a recent analysis showed that a simple SQL/PGQ query resulted in essentially the same execution plan (a hash join) as the equivalent SQL JOIN query. The big win is convenience and clarity. Complex traversal queries become easy to express in one place, and you <strong>don’t need a separate graph database</strong> for things like recommendations, fraud-detection patterns, or network analysis.</p><p><strong>Why Graph Queries? A Modern Use Case</strong></p><p>Let’s forget social networks for a moment. There’s a graph hiding inside almost every <strong>distributed system</strong> we build today. Think about a typical production environment:</p><ol><li>A payment service depends on a database.</li><li>The payment service is called by an order service.</li><li>The order service depends on inventory.</li><li>Inventory depends on another internal API.</li><li>That API depends on Redis and Kafka.</li></ol><p>Now a simple production question suddenly becomes very interesting:</p><blockquote><strong><em>“If this database goes down, which services are actually affected?”</em></strong></blockquote><p>Or:</p><blockquote><strong><em>“What is the blast radius of this failure three or four dependencies deep?”</em></strong></blockquote><p>Let’s take an example, build this like a service registry, and solve it.</p><p>A basic schema for the same example:</p><pre>CREATE TABLE services (<br>    id BIGSERIAL PRIMARY KEY,<br>    name TEXT NOT NULL UNIQUE,<br>    service_type TEXT NOT NULL<br>);<br><br>CREATE TABLE service_dependencies (<br>    service_id BIGINT NOT NULL REFERENCES services(id),<br>    depends_on_id BIGINT NOT NULL REFERENCES services(id),<br>    dependency_type TEXT NOT NULL,<br>    PRIMARY KEY (service_id, depends_on_id)<br>);<br><br>CREATE INDEX idx_service_dependencies_service<br>    ON service_dependencies(service_id);<br><br>CREATE INDEX idx_service_dependencies_dependency<br>    ON service_dependencies(depends_on_id);</pre><p>The meaning is simple:</p><pre>orders-api<br>    ↓<br>payments-api<br>    ↓<br>payments-db</pre><p>service_id → depends_on_id</p><p>So if payments-db fails, we want to discover everything that depends on it.</p><p>For a known depth, we can keep adding joins or use a recursive CTE to find the answers. And there is nothing inherently wrong with it. The problem appears when the question stops being: <strong>“Give me exactly three levels” </strong>and becomes: <strong>“Give me everything upstream until the dependency chain ends,”</strong> or something that wants you to analyze the relationship rather than straight connectivity<strong>.</strong></p><p>Let’s suppose we use recursive CTE solutions for these questions. The database is perfectly capable of answering the question, but <strong>the query is describing the mechanics of traversal rather than the relationship we actually care about</strong>.</p><p>And this is exactly where graph querying starts to feel natural.</p><blockquote>Same data. Different way of thinking.</blockquote><p>We can expose our two tables as a graph:</p><pre>CREATE PROPERTY GRAPH service_graph<br>    VERTEX TABLES (<br>        services<br>            KEY (id)<br>            LABEL service<br>            PROPERTIES (id, name, service_type)<br>    )<br>    EDGE TABLES (<br>        service_dependencies<br>            SOURCE KEY (service_id)<br>                REFERENCES services (id)<br>            DESTINATION KEY (depends_on_id)<br>                REFERENCES services (id)<br>            LABEL depends_on<br>            PROPERTIES (dependency_type)<br>    );</pre><p>Conceptually, our relational model:</p><pre>services<br>    +<br>service_dependencies</pre><p>now becomes:</p><pre>(service)<br>    |<br>depends_on<br>    |<br>(service)</pre><p>The data hasn’t been copied into another graph database. PostgreSQL’s documentation explicitly describes property graphs as a graph layer over relational tables, with graph and relational queries using the same planning and execution infrastructure.</p><p>With relational SQL, we describe <strong>how to connect the tables</strong>. With a graph pattern, we describe <strong>the relationship pattern we’re looking for, </strong>and this becomes even more interesting when the graph represents something more complicated than a simple dependency chain.</p><p>Imagine adding:</p><pre>API<br> ↓<br>Service<br> ↓<br>Kafka Topic<br> ↓<br>Consumer<br> ↓<br>Database</pre><p>or:</p><pre>Service<br> ↓<br>Service<br> ↓<br>Queue<br> ↓<br>Consumer<br> ↓<br>Service</pre><p>Suddenly you’re no longer asking:</p><p><strong><em>“Which table do I JOIN next?”</em></strong></p><p>You’re asking:</p><p><strong><em>“What path through my system am I interested in?”</em></strong></p><p>That is a much more natural abstraction for dependency analysis, architecture discovery, impact analysis, security relationships, lineage, and increasingly, AI systems.</p><p>And there is an important point here that is easy to miss.</p><p><strong>Graph syntax does not magically make PostgreSQL faster.</strong></p><p>PostgreSQL’s own documentation explains that graph and relational queries share the same planning and execution infrastructure. In other words, a SQL/PGQ query over these tables can ultimately involve the same underlying joins and indexes as the traditional relational query.</p><p>Simply put → the same data, the same database, the same underlying execution engine, but a much more natural language for relationship-heavy questions.</p><h4><strong><em>Codebase with steps to run :</em></strong></h4><p><a href="https://github.com/vatsuvaksi/Postgres-Evolution/blob/main/README.md">https://github.com/vatsuvaksi/Postgres-Evolution/blob/main/README.md</a></p><h3>Impact and Outlook</h3><p>PostgreSQL 19’s graph features mean you no longer need a separate graph engine (or complex application logic) for many use cases. You can blend graph queries with SQL, Joins, and even vector similarity search in the same database. In other words, Postgres is evolving into a <strong>unified data platform</strong>. Users have observed a “strategic shift toward <em>AI-native</em> PostgreSQL” as the vector ecosystem matures, and now graph queries add to that momentum.</p><p>While SQL/PGQ in PostgreSQL 19 is brand-new (as of beta), the development is driven by real market demand. Feature tables highlight that Postgres 19 adds “SQL/PGQ Graph Queries: analysis of relationships, paths, and hierarchies… without a separate graph database. Early community tests show the graph-query syntax works as expected (returning the same data as old JOIN queries) and can simplify development. Performance-wise, because PG19 implements graph queries on top of regular tables, you’ll rely on the same indexes and tuning you’d use for joins. Benchmarks haven’t been widely published yet, but one can expect similar scaling to careful relational queries, with the extra benefit of cleaner, declarative code.</p><p>In summary, PostgreSQL 19 is another step in Postgres’s “everything-in-one” approach. First it embraced vectors for AI, now it speaks graph. Applications that need to <strong>store and query rich relationships</strong> from social graphs and knowledge graphs to recommendation networks can do so natively in Postgres. <strong>No big surprises: graph queries compile to joins</strong>, but the simplicity is remarkable. As one notes, this isn’t a magic speed hack, but “a queryable layer that maps the relational model to a graph model”. In practice, it means developers and analysts can write complex network queries quickly, focusing on <em>what</em> they want, not <em>how</em> to join it. And all of this with Postgres doing “the heavy lifting as usual” behind the scenes.</p><p>Read about the benchmarks on my machine here (Apple M4):</p><p><a href="https://github.com/vatsuvaksi/Postgres-Evolution/blob/main/RESULTS.md">https://github.com/vatsuvaksi/Postgres-Evolution/blob/main/RESULTS.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cbdf3d6af14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Krishi Sarthi: Event-Driven AI Platform for Indian Agriculture (Kafka, A2A, MCP, Sarvam Voice AI)]]></title>
            <link>https://medium.com/@vatsuvaksi/krishi-sarthi-event-driven-ai-platform-for-indian-agriculture-kafka-a2a-mcp-sarvam-voice-ai-bbce5637db9b?source=rss-43c8f4f75f0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbce5637db9b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[a2a-protocol]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vatsal Gupta]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 21:01:40 GMT</pubDate>
            <atom:updated>2026-04-29T21:03:02.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Krishi Sarthi: Event-Driven AI Platform for Agriculture (Kafka, A2A, MCP, Sarvam Voice AI)</h3><blockquote><strong>Introduction</strong></blockquote><p>Hey everyone, I’m an engineer obsessed with building <strong>high-throughput, event-driven platforms and low-latency distributed architectures</strong>. Lately, I’ve been deep-diving into <strong>LLM integrations, RAG pipelines, and real-time AI systems,</strong> trying to understand how these things actually behave in production, not just in polished demos.</p><p>I’m big on pushing systems to their limits, thinking in terms of <strong>scale, fault tolerance, and clean architecture</strong> rather than quick hacks.</p><p>The AI space is moving insanely fast. Lately, I’ve been working with <strong>RAG pipelines, </strong>the usual flow of fetching relevant data from sources and grounding LLM responses. It’s powerful, no doubt. But also… it starts to feel repetitive pretty quickly.</p><p>Now, with agents evolving fast, huge context windows becoming the norm, and people literally dumping PDFs to get answers, things are shifting. The problem space is moving from <em>“how do I retrieve data?”</em> to <em>“how do I architect intelligence?”</em></p><p>Boring or not, I’ve been leaning into it, getting comfortable with the AI ecosystem, understanding where it actually works and where it breaks.</p><p>At some point, I thought, rather than just consuming patterns, why not <strong>build something from scratch</strong> and really understand the trade-offs? The architectural decisions, the bottlenecks, the “this won’t scale” moments. Basically, approach AI systems the same way we approach <strong>low-latency, high-throughput distributed systems</strong>.</p><p>That’s how <strong>Krishi Sarthi</strong> came into the picture. It’s my attempt to explore AI from a backend engineer’s lens, thinking in terms of <strong>event-driven flows, system design, and real-world constraints</strong>, not just prompts and wrappers.</p><p>I’ll be open-sourcing the code soon, but for now, I wanted to put the idea out there, especially for folks like me who come from the world of <strong>distributed systems, Kafka, and scale</strong>, and want a clear, no-BS, bird’s-eye view of what’s actually happening in AI.</p><p>If you’re in the same boat, I would love to hear how you’re approaching this space.</p><p>Connect with me on <a href="https://www.linkedin.com/in/vatsuvaksi/"><strong><em>Linkedin</em></strong></a></p><blockquote><strong><em>Krishi Sarthi: Intent → Architecture → Making It Real (Because Theory Is Boring)</em></strong></blockquote><p>The idea is simple at heart: help farmers in India make better decisions. Not after the loss has already happened, not when the season is already over, but before. Help them plan, estimate, and understand what they’re walking into before they plant a single seed.</p><p>It’s still early. A lot of iterations away from being public. But the architecture is already teaching me things, and one of the biggest lessons came from a single, deceptively simple question.</p><blockquote><strong>A farmer asks</strong>: “What should I grow this season, and how much profit can I expect?”</blockquote><p>Six words. One question. And underneath it, an enormous web of variables that most people never think about, such as soil composition, rainfall patterns, crop compatibility, market prices, yield estimations, and regional demand. A seemingly simple question is actually five different problems wearing a single coat.</p><p>So what happens when you throw that at one big LLM and ask it to figure everything out?</p><p>For a while, it works. It sounds confident. It answers. And that’s exactly the problem, it sounds confident even when it shouldn’t be. It mixes soil logic, financial logic, and weather logic, all tangled together in one model with no clean separation of concerns. When something goes wrong, you have no idea which part failed. Was it the yield estimate? The crop suggestion? The profit calculation? You can’t debug it cleanly. You can’t improve one part without pulling at everything else. It’s that overworked engineer again, handling too many domains at once, holding the whole thing together with sheer effort until the day it can’t anymore.</p><p>This is exactly where the A2A protocol changes everything. Let me give an example.</p><p>There’s always that one engineer on every team.</p><p>The one who somehow ends up doing everything. They write backend code, fix frontend bugs, debug production issues, talk to product managers, update documentation, and occasionally explain to everyone else why “<em>it works on my machine</em>” is not a valid deployment strategy.</p><p>For a while, this person looks like a superhero. The whole team leans on them. Tickets get closed. Fires get put out. Everyone sleeps a little more easily knowing that the person is around.</p><p>Then one day, everything breaks. Not because they stopped caring. Not because they got lazy, but because no matter how talented someone is, one person cannot do everything well at scale. The cracks were always there. Nobody noticed because they were too busy handing things to the same person.</p><p>Here’s the funny part, though.</p><p>For years, we’ve been doing the exact same thing with software systems. We build one big thing. We expect it to do everything. We push it harder. It struggles. Then we break it apart and pretend we saw it coming.</p><p>We did it with monoliths. One giant codebase, one deployment, one catastrophic point of failure. Sound familiar? So we broke it apart into microservices. Every service did one thing, and did it well. It felt like progress, because it was.</p><p>Then came LLMs. And quietly, almost without noticing, we started doing it all over again. One giant model. Every task. Every domain. Every problem. Push it harder. Watch the cracks form.</p><p>History has a way of rhyming.</p><p>And now, we’re learning the lesson one more time. Only this time, we have a name for the solution.</p><p>[A2A] Agent-to-Agent communication. Instead of one AI trying to do everything, specialized agents talk to each other. Each one does a single job brilliantly. Together, they do what no single model or engineer was ever meant to do alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeNGF5YA-jk6qilfmgiygg.png" /></figure><p>Instead of one agent trying to be an agronomist, a meteorologist, a financial analyst, and a planner all at once, you break the problem apart the same way nature breaks work apart through specialisation. In Krishi Saarthi, I’m architecting it as a system of focused agents, each with a single, clear responsibility. Let me walk you through each one.</p><p><strong>The Soil Agent</strong> knows soil, and only soil. Feed it inputs like texture, water retention capacity, pH levels, nutrient composition, and location-specific properties and it builds a precise understanding of what that land is capable of. A farmer in Punjab working with sandy loam soil that has low nitrogen and moderate water retention gets a very different soil profile than a farmer in Andhra Pradesh sitting on black cotton soil with high moisture holding capacity. The Soil Agent doesn’t care about market prices. It doesn’t think about rainfall forecasts. Its entire world is the ground beneath the farmer’s feet, and it maps that world with focus. That focus is what makes it trustworthy.</p><p><strong>The Weather Agent</strong> lives in climate data. It looks at seasonal trends, historical rainfall patterns, expected temperature ranges, and whether the environment in that particular region, at that particular time of year, can actually support a given crop. It knows, for instance, that a farmer in Vidarbha asking about cotton in the late Kharif season is walking into a different risk profile than one asking the same question at the start of the monsoon. The Weather Agent doesn’t touch crop prices or soil chemistry. It answers one question cleanly: Does this environment support what the farmer wants to grow?</p><p><strong>The Crop Agent</strong> is where soil knowledge and weather knowledge meet. It takes the outputs from the two agents above and uses them to say: given this soil, given this climate, these crops make sense. Not as a guess, but as a reasoned recommendation grounded in real inputs. If the soil is slightly acidic and the rainfall forecast is moderate, it might recommend finger millet over rice. If the soil is rich in potassium and the season is warm and dry, it might lean toward groundnut. It doesn’t estimate profit. It doesn’t calculate yield. It answers exactly one question: what should grow here?</p><p><strong>The Yield Agent</strong> takes it from there. Once you know what to grow, the natural next question is how much of it you can realistically expect to produce. This agent works with simulation logic, historical yield data, and domain-specific rules to give the farmer a grounded estimate. It knows that the same crop in two different districts can yield vastly different amounts depending on irrigation access, farming practices, and soil health. A wheat farmer in Haryana with canal irrigation might expect 5 tonnes per hectare. The same crop in a rain-fed district of Madhya Pradesh might yield 2.5. The Yield Agent holds that nuance and returns an honest number.</p><p><strong>The Profit Agent</strong> is the financial brain of the system. It takes the crop recommendation and the yield estimate and runs the numbers for the cost of seeds, cost of fertilisers, labour, irrigation, transportation, expected market price at harvest time, and a risk margin to account for price volatility. It tells the farmer not just what they might earn, but what they might net after everything is spent. This is the agent that can say: yes, this crop makes agronomic sense, but given current mandi prices and input costs in your district, your expected margin is thin here’s what that means for your planning.</p><p><strong>The Planner Agent</strong> sits above all of them. It doesn’t know soil or weather, or market prices directly. Its job is to coordinate collecting the outputs from every other agent, understanding how they relate to each other, resolving any contradictions, and then forming a single, coherent response that a farmer can actually understand and act on. It’s the one that speaks in plain language, or in Hindi, or in Telugu, depending on who’s asking. It’s the translator between a complex multi-agent conversation and a human being standing in a field trying to make a decision before the season closes.</p><p>Now step back and look at the whole system.</p><p>No single agent is overwhelmed. No single agent is pretending to know something outside its domain. When the yield estimate needs improvement, I’ll go to the Yield Agent and refine it, and the rest of the system continues running exactly as it was. When market prices shift, and the Profit Agent needs updated assumptions, I’ll update that one agent without touching soil logic or weather logic. Each part of the system is independently improvable, independently debuggable, and independently trustworthy.</p><p>This is the beauty of A2A. Not one intelligence doing everything, but many intelligences each doing their one thing and talking to each other to arrive at something none of them could have built alone.</p><p>That farmer’s question, asked in Hindi or Punjabi or Telugu, deserves a real answer. And a real answer requires a real system.</p><blockquote><strong>Async, Resilient, and Ready to Replay How Kafka Holds It All Together</strong></blockquote><p>Here’s where it gets interesting and where most people building multi-agent systems run into a wall they didn’t see coming.</p><p>Not all agents are created equal. The Soil Agent responds in milliseconds. It’s working with structured inputs, a narrow domain, and a well-defined lookup pattern, fast, predictable, and almost mechanical in its speed. The Weather Agent is slightly slower, because it’s pulling from external climate data feeds and doing a bit more reasoning. The Yield Agent is slower still, because it’s running simulation logic against historical data. And the Profit Agent? It might be waiting on live mandi price feeds that have their own latency, their own unreliability, their own bad days. If you build this system synchronously, each agent waits for the previous one to finish before the next one begins. You’ve essentially created a queue of bottlenecks. The slowest agent sets the pace for everything. The farmer waits. The system feels broken even when it isn’t.</p><p>So the question becomes: what do you do when agents run at different speeds? And more importantly, what do you do when one of them fails?</p><p>Because they will fail. A weather API goes down. A price feed returns stale data. An agent times out mid-reasoning. In a tightly coupled synchronous system, one failure cascades into a total failure. The farmer gets nothing. And me, the engineer, get a 2 am alert with no clean way to debug which part of the chain broke and why.</p><p>This is where I introduced Kafka into Krishi Saarthi.</p><p>Every time an agent does something, receives an input, produces an output, or makes a decision, that event is written into Kafka’s log. The agents don’t call each other directly anymore. They publish events, and they consume events. The Soil Agent finishes its analysis and publishes the result to a topic. The Crop Agent, which was already listening to that topic, picks it up and begins its own reasoning without anyone having to tell it to. Everything runs asynchronously, in parallel, at its own pace, without waiting for anyone else.</p><p>And here’s the part that makes this genuinely powerful for a system like this Kafka can replay events. If the Profit Agent fails halfway through because the mandi price feed was down, the event isn’t lost. It’s sitting in the log, waiting. The moment the feed comes back up and the agent recovers, it replays that event and picks up exactly where it left off. No data is lost. No farmer’s query disappears into a void. The system heals itself without anyone needing to manually intervene.</p><p>This also solves the memory problem. In a stateless multi-agent world, each agent processes its input and forgets. There’s no continuity, no sense of what came before. But with Kafka holding the full event log, you have a durable, replayable history of everything that happened, which agent said what, in what order, at what time. That’s not just fault tolerance. That’s auditability. That’s the ability to go back and ask: where exactly did this recommendation go wrong, and why?</p><p>Kafka essentially becomes the nervous system of the entire agent network and not the brain, not the muscle, but the connective tissue that lets every part communicate reliably, recover gracefully, and scale independently without bringing the whole body down with it.</p><blockquote><strong>How MCP Ties Every Agent to the Real World</strong></blockquote><p>Now I have A2A giving me a clean multi-agent architecture where every agent knows its job and stays in its lane. We have Kafka holding the whole thing together as a nervous system, durable, asynchronous, fault-tolerant, replayable. The system is beginning to look like something real.</p><p>But there’s a problem nobody talks about enough.</p><p>These agents, as smart as they are, are essentially blind. They can reason beautifully inside their own domain, but they can’t reach out and touch the world. The Weather Agent can’t actually check today’s rainfall forecast unless someone hands them that data. The Profit Agent can’t look up live mandi prices on its own. The Soil Agent can’t query a government soil health database without being explicitly connected to one. Every agent, in isolation, is a brilliant thinker sitting in a room with no windows and no internet connection.</p><p>This is exactly the problem that the Model Context Protocol (MCP) was designed to solve.</p><p>Think of MCP as a universal adapter. The way a power adapter lets you plug any device into any socket regardless of the country you’re in, MCP lets any agent connect to any external tool, database, or API through a single standardised interface. Instead of each agent being individually hardwired to its own set of data sources, which is brittle, messy, and nearly impossible to maintain at scale, MCP gives every agent in the system a common language for saying: I need something from the outside world, go get it.</p><p>In Krishi Saarthi, this is where the architecture starts to feel genuinely alive.</p><p>The Weather Agent, through MCP, can call a tool that fetches live IMD India Meteorological Department data for a specific district and season. It doesn’t need to know how that API works, what authentication it requires, or how to parse its response format. MCP abstracts all of that away. The agent simply says: give me the weather context for Nashik in October, and the MCP server handles the rest, returning structured, usable context back into the agent’s reasoning window.</p><p>The Profit Agent connects through MCP to a market price tool that pulls live or near-live mandi prices from Agmarknet, the government’s agricultural marketing network. Again, the agent doesn’t manage that connection directly. It makes a context request, MCP fulfils it, and the agent reasons on top of real numbers rather than hallucinated ones.</p><p>The Soil Agent can query a soil health card database through MCP, pulling district-level soil reports that the Indian government has been collecting for years. That’s real, grounded, location-specific data flowing directly into an agent’s reasoning, not approximations baked into training data that may be years out of date.</p><p>Now here’s where the Planner Agent becomes especially interesting in this picture.</p><p>The Planner Agent is the coordinator of the entire system, the one that talks to the farmer, collects outputs from every other agent, and assembles a final coherent response. But the Planner Agent also has its own MCP connections. It can call a translation tool that converts the final response into the farmer’s preferred language. It can call a memory tool that retrieves what this particular farmer asked last season, what crops they grew, what their soil profile looked like, so the response this time isn’t generic but personalised. It can even call a notification tool that, once the recommendation is ready, sends it to the farmer’s basic mobile phone as an SMS because not every farmer in rural India is sitting with a smartphone and a stable internet connection.</p><p>What MCP does, in the deepest sense, is collapse the distance between the agent’s intelligence and the world’s data. Without it, you have a system that reasons well but knows little. With it, you have a system that reasons well and is continuously informed by reality, live, current, location-specific reality.</p><p>And when you put all three layers together, A2A giving each agent a focused identity, Kafka giving the whole network memory and resilience, and MCP giving every agent a window into the real world, you stop building a chatbot and start building something that genuinely thinks, collaborates, recovers, and acts.</p><p>That’s the architecture underneath Krishi Saarthi. And the farmer standing in a field in Maharashtra, asking a simple question about what to grow this season, has no idea any of this is happening. They just get an answer. A real one. In their language. On their phone.</p><p>That’s the whole point.</p><blockquote><strong>Adding the magic : Sarvam AI for voice</strong></blockquote><p>Here’s how it plays out. The farmer calls the system, and the Sarvam-powered assistant answers in her language. For example, on a test call, the assistant might say in Hindi: <em>“नमस्ते! अगले सप्ताह अच्छी बारिश की संभावना है, बाजरा बोना ठीक रहेगा. क्या आप सहमत हैं?”</em> (Hello! Good rains are forecast next week, so planting millet would be fine. Do you agree?). The farmer replies, <em>“हाँ, बाजरा ठीक रहेगा।”</em> (Yes, millet is fine). Sarvam’s speech-to-text (ASR) catches her words. It supports 22 Indian languages with auto-detection and handles code-mixed speech gracefully. (Farmers often mix English terms like “status” or “balance” mid-sentence, and Sarvam handles that seamlessly.)</p><blockquote><strong>Tech Stack</strong></blockquote><p>Laying out the tech stack I’d be working with currently to get the system up and running. [Might change according to a few needs and features, but overall this should be it]</p><p><strong>Backend, Agent Framework, and Orchestration</strong></p><ul><li>LangChain4j (supporting Java equivalent of LangChain, RAG pipelines, memory, and tool use)</li><li>Spring WebFlux</li><li>Python + Java</li><li>Spring Boot (core service framework for every agent)</li><li>Spring AI</li><li>Spring Kafka</li><li>Spring Data JPA (PostgreSQL ORM)</li><li>Spring Data Redis (Redis integration)</li></ul><p><strong>LLMs Per Agent</strong></p><ul><li>Planner Agent → GPT-4o or Claude 3.5 Sonnet (strong reasoning, tool use, multilingual)</li><li>Soil Agent → GPT-4o Mini or Gemini 1.5 Flash (structured input, fast, cost-efficient)</li><li>Weather Agent → GPT-4o Mini or Gemini 1.5 Flash (pattern recognition, low latency)</li><li>Crop Agent → Claude 3.5 Sonnet (nuanced domain reasoning, knowledge retrieval)</li><li>Yield Agent → GPT-4o or Mistral Large (simulation logic, numerical reasoning)</li><li>Profit Agent → GPT-4o or Claude 3.5 Sonnet (financial reasoning, risk analysis)</li><li>Translation Layer → IndicTrans2 or AWS Translate (Indian language support)</li><li>Embedding Model → text-embedding-3-small by OpenAI</li></ul><p><strong>MCP — Model Context Protocol</strong></p><ul><li>Anthropic MCP Specification (open protocol standard)</li></ul><p><strong>Event Streaming and Message Queue</strong></p><ul><li>Apache Kafka</li></ul><p><strong>Vector Storage</strong></p><ul><li>Milvus</li></ul><p><strong>External Data APIs</strong></p><ul><li>IMD API India Meteorological Department (weather and rainfall data)</li><li>Agmarknet API Ministry of Agriculture (live mandi prices)</li><li>Soil Health Card API Department of Agriculture (district-level soil data)</li><li>ICAR crop database, Indian Council of Agricultural Research (agronomic knowledge)</li><li>SoilGrid</li><li>Open-Meteo (free open source weather API, fallback for IMD)</li><li>Data.gov.in (Indian government open data portal, multiple agricultural datasets)</li></ul><p><strong>Multilingual and Voice Interface</strong></p><ul><li>Sarvam AI (Indian language speech to text and text to speech, REST API)</li></ul><p><strong>Farmer Interface and Notifications</strong></p><ul><li>Twilio Java SDK (SMS delivery, WhatsApp API, voice calls)</li><li>Next.js (web frontend)</li><li>React Native (mobile app)</li></ul><p><strong>Infrastructure and DevOps</strong></p><ul><li>Docker</li><li>GitHub Actions (CI/CD pipeline build, test)</li></ul><p><strong>Development and Testing</strong></p><ul><li>JUnit 5</li><li>Mockito</li><li>WireMock (mock external APIs like IMD, Agmarknet, during local development)</li><li>Postman</li><li>LangSmith Evaluation (automated LLM output quality testing and regression)</li></ul><blockquote><strong>Conclusion</strong></blockquote><p>At this point, I don’t really know how soon I’ll be able to live fully or partially.</p><p>There are still a lot of moving pieces, better models, cleaner integrations, cheaper price, more reliable data, and, honestly, just time to build things properly instead of stitching them together over weekends.</p><p>But what I do know is this:</p><p>It starts to feel less like a demo and more like something that could actually exist in the real world, and that’s what excites me.</p><p>Not just building “AI features”, but building systems that people can actually interact with in their own language, in their own way, without needing to understand what’s happening behind the scenes.</p><p>Maybe this takes time. Maybe it evolves differently. Maybe it looks completely different a year from now. But I’d genuinely love to see more people explore this space.</p><p>Because if there’s one thing software engineering has taught me again and again, it’s this:</p><h4>Big problems don’t get solved by making one thing smarter. They get solved by making many things work well together, and it feels like I’ve started to do exactly that with AI.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbce5637db9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Batch on Steroids: Faster, Smarter, Scalable]]></title>
            <link>https://medium.com/@vatsuvaksi/spring-batch-on-steroids-faster-smarter-scalable-d157bec3eaf5?source=rss-43c8f4f75f0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d157bec3eaf5</guid>
            <category><![CDATA[java-concurrency]]></category>
            <category><![CDATA[java-spring-batch]]></category>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vatsal Gupta]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 19:53:19 GMT</pubDate>
            <atom:updated>2024-12-17T19:53:19.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hey everyone! I’m a software engineer with a background in the healthcare-IT domain, where I’ve had the privilege of working on mission-critical systems that make a real impact. As someone passionate about continuously learning and staying on top of emerging technologies, I’m always looking for ways to push the boundaries of what’s possible in backend engineering.</p><p>If you’re into tech, feel free to connect with me on <a href="https://www.linkedin.com/in/vatsuvaksi"><strong>LinkedIn</strong></a> or follow my work on <a href="https://github.com/vatsuvaksi">Github</a> — I love exchanging ideas and insights with like-minded folks.</p><p><strong><em>Let’s get started!</em></strong></p><p>This quarter, I had the chance to tackle a pretty exciting challenge: building a short-lived microservice designed to process anywhere from 5,000 to over 200,000 records. This project pushed me to dive deep into the Spring Batch framework, fine-tune its capabilities, and really put it to the test.</p><p>What made this project even more intriguing was the nightly schedule — this batch job kicked off at midnight via <a href="https://spring.io/projects/spring-cloud-dataflow"><strong>SCDF</strong></a> servers, triggering a chain of dependent microservices. The mission? Wrap up the entire workflow as quickly and efficiently as possible every single day. Since my service was responsible for the heavy lifting and intense computations, I had to make smart, performance-focused decisions to keep processing times razor-sharp. The earlier iterations of this workflow, built in a less optimized and largely synchronous manner, took hours to complete — a challenge I was determined to overcome.</p><p>In this article, I’ve put together a small prototype project. Hopefully, it’ll be helpful for folks who are just starting out with optimizing their batch services!</p><p>I also wanted to share my experience and the reasoning behind my decisions because, while I found plenty of blogs and videos to get the project off the ground (alongside the official docs), very few delved into the finer details of optimizing the application. Things like fine-tuning performance and leveraging multi-threading to handle large-scale processing often go underexplored, and I wanted to bridge that gap.</p><p><strong>Prerequisites :</strong></p><ol><li>Basics of Java Concurrency</li><li>Basics of Spring Batch Framework</li><li>Basics of Reactive Programming</li><li>Basics of Docker and docker-compose</li></ol><p>Also, these videos and blogs did help me when I was figuring out a few things so I wanted to give a shoutout to them here :</p><ol><li><a href="https://www.youtube.com/watch?v=X48mMxEMYps">Bouali Ali</a></li><li><a href="https://medium.com/dreamifly/spring-batch-tutorial-batch-processing-made-easy-with-spring-3219b4de052">Jalal Nasser</a></li><li><a href="https://medium.com/@elouadinouhaila566?source=post_page---byline--393904ac401c--------------------------------">Nouhaila El Ouadi</a></li><li><a href="https://medium.com/@YounessBout/increase-spring-batch-performance-through-multithreading-b513ca90aeb5">Youness boutkhourst</a></li><li><a href="https://www.toptal.com/spring/spring-batch-tutorial">Toptal</a></li></ol><h4>What is Spring Batch?</h4><p>According to the official <a href="https://spring.io/projects/spring-batch">documentation</a>:<br><em>“A lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.”</em></p><p>I couldn’t agree more. Getting started was seamless — setting up the basic batch and running it locally was a breeze. The predefined classes and interfaces provided by the framework make it incredibly easy to bootstrap and get your project up and running in no time.</p><p>Before we dive into what we are trying to build and set up an initial project, let’s take a moment to familiarize ourselves with some key terms that we’ll be using frequently throughout this article.</p><h4>Keywords</h4><ol><li><strong>Job</strong>: Represents the entire batch process and contains a sequence of steps to be executed.</li><li><strong>Step</strong>: A single unit of work within a Job, configured for chunk-oriented processing.</li><li><strong>JobInstance</strong>: Represents a single logical execution of a Job, identified by unique parameters.</li><li><strong>JobExecution</strong>: Tracks the runtime details of a JobInstance, including its status, start time, and end time.</li><li><strong>StepExecution</strong>: Tracks execution details of a Step, including status, input/output counts, and errors.</li><li><strong>JobRepository</strong>: Stores metadata for Job and Step executions, ensuring fault tolerance and recoverability.</li><li><strong>JobLauncher</strong>: Triggers Job execution, programmatically or via scheduling.</li><li><strong>JobParameters</strong>: A set of runtime parameters passed to a Job for configuration or dynamic behavior.</li><li><strong>ExecutionContext</strong>: Provides state persistence across chunk executions or retries, ensuring data integrity.</li><li><strong>ItemReader</strong>: Reads data in chunks from a source (e.g., file, database, or API) for processing. Example — FlatFileItemReader, JdbcCursorItemReader.</li><li><strong>ItemProcessor</strong>: Applies business logic to transform or filter data between reading and writing phases.</li><li><strong>ItemWriter</strong>: Writes processed data in chunks to a destination (e.g., database, file, or API). Examples — FlatFileItemWriter, JdbcBatchItemWriter.</li><li><strong>Partitioner</strong>: Splits a Step into multiple partitions for parallel execution across threads or nodes.</li><li><strong>StepScope</strong>: Scopes beans to the lifecycle of a Step, ensuring data isolation and reusability.</li><li><strong>SkipPolicy</strong>: Customizes rules for skipping records based on specific error conditions.</li><li><strong>Chunk-based processing</strong>: Chunk-based processing in Spring Batch involves reading, processing, and writing data in predefined “<strong><em>chunks</em></strong>” (groups of items), improving performance and memory efficiency by handling large datasets in bulk rather than one item at a time.</li></ol><h4>Problem Statement</h4><p>Unfortunately, I can’t share my exact problem statement due to NDAs (gotta keep it secret, right? 😅), but I’ve crafted a problem statement that I think will definitely get you hooked:</p><h3>Real-Time Analysis of E-commerce Product Reviews</h3><p>Imagine this: you’re tasked with building a <strong>Spring Batch application</strong> capable of processing over <strong>1,000,000 e-commerce product reviews</strong> stored in an SQL database. The goal? To extract valuable insights, compute aggregated statistics, and uncover trends that will empower business decision-making at scale.</p><p>From a technical perspective, our task involves processing over <strong>100,000 records</strong> fetched from a <strong>PostgreSQL database</strong>. For each record, we’ll perform some computations by integrating with an <strong>external API</strong>. Once the required transformations are complete, the enriched data will be persisted into a <strong>distributed cache</strong>, enabling seamless access for other microservices to perform further analysis.</p><h3><strong><em>Without further ado, let’s dive into the diagrams, setup, and code!</em></strong></h3><ol><li><strong>High-Level diagram of the flow:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTFK-huOovM3ExX_7Rb-Qg.png" /></figure><blockquote>Before diving into the flow of this architecture, let me address something that might be on your mind qfter looking at the above diagram: <em>Is all this really necessary just to maximize CPU utilization?</em> Didn’t the creators of the Spring Batch framework already account for such scenarios? The answer is, <em>Yes, absolutely!</em> The brilliant folks at Spring did think about this, and they’ve provided built-in classes like AsyncItemProcessor and AsyncItemWriter to enable asynchronous processing right out of the box.</blockquote><blockquote>If you’re curious about those, I highly recommend checking out an excellent article by <a href="https://medium.com/@YounessBout/increase-spring-batch-performance-through-async-processing-e96fa5d90bbd"><strong>Youness Boutkhours</strong></a><strong>t</strong>, where he breaks down these approaches with examples.</blockquote><p>So why did we go down the custom route instead of leveraging these classes? It boils down to <em>freedom</em>. While these classes are powerful, we wanted more granular control over how computations were handled. For example, with subchunk processing, we can make dynamic decisions:</p><ul><li>Do we need more subchunks for a specific dataset?</li><li>Should we scale down parallel execution in favor of synchronous processing when running on limited resources?</li><li>Should the data processing logic vary depending on specific scenarios?</li></ul><p>Subchunk processing versus asynchronous processing with AsyncItemProcessor in Spring Batch offers different trade-offs. Subchunk processing allows precise control over grouping and processing logic. For instance, we can group records based on business rules—say, processing all records belonging to a single customer in one batch. On the other hand, AsyncItemProcessor delegates processing to asynchronous threads, which can add complexity to error handling, ordering, and rollback mechanisms.</p><p>By opting for subchunk processing in the writer, we gained flexibility that was critical for our use case.</p><h3><strong>Now, let me walk you through how the flow works and why it’s designed the way it is.</strong></h3><p>In a typical <strong>Spring Batch application</strong> (unoptimized), the flow is straightforward: the <strong>Reader</strong> pulls in all the data, the <strong>Processor</strong> applies the necessary transformations, and the <strong>Writer</strong> sends the processed data to its destination. This flow can be represented as <strong>Reader → Processor → Writer</strong>. For smaller datasets, this works just fine and gets the job done. However, when dealing with <strong>large datasets</strong>, this approach can become a bottleneck, making the batch process time-consuming and the concept of a <strong>“short-lived microservice”</strong> practically laughable 😅.</p><p>Thankfully, Spring Batch provides mechanisms to handle this efficiently by enabling <strong>parallel processing</strong> using interfaces like the <strong>Partitioner</strong>, which we’ll be leveraging here.</p><p>If you’ve glanced at the diagram (you’ll want to), you might notice something unconventional: typically, the <strong>Processor</strong> handles all the business logic for each record. However, in our approach, we’re offloading much of this heavy lifting to the <strong>Writer</strong> instead.</p><p>Now, the big question: <strong>Why this decision?</strong></p><p>Here’s how a Spring Batch flow typically works:</p><ul><li>The <strong>Reader</strong> reads a chunk of data and sends it to the <strong>Processor</strong>, which processes each record synchronously in its ongoing thread.</li><li>Once the processing is complete, the chunk is handed off to the <strong>Writer</strong>.</li></ul><p>The limitation? Processing one record at a time in the <strong>Processor</strong> can’t fully utilize system resources when working with large chunks of data. By shifting the computational work to the <strong>Writer</strong>, we can process entire chunks asynchronously, taking better advantage of available resources for computation and reducing overall processing time.</p><p>The core concept here is <strong>Chunk-Oriented Processing</strong>, which forms the backbone of what we’re doing. Instead of processing records synchronously within the <strong>Processor</strong>, we’re using chunk-based asynchronous processing to maximize resource utilization and achieve the speed and scalability needed for large-scale datasets.</p><p>There’s one more important detail I’d like to cover about how we’ll be splitting the dataset. There are two ways to approach this:</p><p><strong>Partitioning with a Direct List from the Database</strong>: In this approach, the <strong>Partitioner</strong> pulls a list of records (possibly in batches) directly from the database and partitions the list into smaller chunks. Each chunk is then passed to a reader thread for processing.</p><p><strong>Downside?</strong> Storing a large list in memory can lead to <strong>JVM memory issues</strong>, especially when handling massive datasets. The partitioning itself can also become a bottleneck if the system struggles to manage this data efficiently.</p><p><strong>Pagination-Based Partitioning</strong>: Instead of fetching a large list, we can get the <strong>count of records</strong> in the partition and create <strong>page number metadata</strong>, which is then passed through the <strong>execution context</strong>. This way, each reader thread is responsible for reading a chunk of data by making an SQL call using <strong>pagination</strong>.</p><p><strong>Downside?</strong> While this method avoids memory bloat, it could <strong>overload the database</strong> with multiple calls, especially if the chunk size is too small and the dataset is huge. So, choosing the right chunk size is key — too small, and you make more DB calls; too large, and you might face memory issues again.</p><p>It’s important to <strong>smartly select the chunk size</strong> based on the volume of records you expect. As the volume grows, you might need to <strong>adjust the chunk size</strong> and <strong>scale your infrastructure</strong>, like adding more <strong>CPU cores</strong> or <strong>RAM</strong>, to support this increased load. It’s all about finding the right balance!</p><p>As you can probably tell from my previous explanation, we opted for the second approach: <strong>Pagination-Based Partitioning</strong>. 😄</p><p>P.S. If you want to read about the LLD architecture of Spring Batch architecture and components you can read this <a href="https://www.toptal.com/spring/spring-batch-tutorial">article by totpal</a></p><blockquote><strong><em>OKAY ! Let us get our hands dirty with code.</em></strong></blockquote><p>First things first I want to set up an infrastructure and a maven project to run this app.</p><p>a. DockerFile to Build the app image</p><pre># Use an official OpenJDK 17 base image<br>FROM eclipse-temurin:17-jdk-alpine<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the Spring Batch application JAR file into the container<br>COPY target/springbatchdemo-0.0.1-SNAPSHOT.jar app.jar<br><br># Expose any required ports (if needed, for monitoring or metrics)<br># EXPOSE 8080<br><br># Command to delay for 5 minutes and then run the batch job<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;sleep 300 &amp;&amp; java -jar app.jar&quot;]</pre><p>b. docker-compose file to build infra to support our application</p><pre>version: &#39;3.9&#39;<br><br>services:<br>  app:<br>    image: springbatchdemo:latest<br>    container_name: batch_app<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    networks:<br>      - app-network<br>    depends_on:<br>      - psql<br>      - redis<br>    environment:<br>      SPRING_DATASOURCE_URL: jdbc:postgresql://psql:5432/batchdb<br>      SPRING_DATASOURCE_USERNAME: batchuser<br>      SPRING_DATASOURCE_PASSWORD: batchpassword<br>      SPRING_REDIS_HOST: redis<br>      SPRING_REDIS_PORT: 6379<br><br>  psql:<br>    image: postgres:15<br>    container_name: psql<br>    networks:<br>      - app-network<br>    environment:<br>      POSTGRES_DB: batchdb<br>      POSTGRES_USER: batchuser<br>      POSTGRES_PASSWORD: batchpassword<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - ./init.sql:/docker-entrypoint-initdb.d/init.sql<br><br>  redis:<br>    image: redis:7<br>    container_name: redis<br>    networks:<br>      - app-network<br>    ports:<br>      - &quot;6379:6379&quot;<br>    command: [&quot;redis-server&quot;]<br><br>networks:<br>  app-network:<br>    driver: bridge</pre><p>c. init.sql file with 1,00,000 records</p><ul><li>Let me show you how my table looks and sample values can be downloaded from below link</li></ul><pre>CREATE TABLE product_review (<br>    review_id SERIAL PRIMARY KEY,                 -- Unique identifier for each review<br>    product_id INT NOT NULL,                     -- Reference to the product (foreign key to product table)<br>    user_id INT NOT NULL,                        -- Identifier for the user who made the review<br>    rating SMALLINT CHECK (rating BETWEEN 1 AND 5), -- Rating between 1 and 5<br>    review_text TEXT,                            -- Text of the review<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp for when the review was created<br>    is_processed BOOLEAN DEFAULT FALSE           -- Flag to indicate if the review has been processed<br>);<br><br>CREATE INDEX idx_created_at ON product_review (created_at); -- indexing created at as the query fill use this as a filter</pre><blockquote><a href="https://github.com/vatsuvaksi/RealTime-Product-Review-Processing/blob/master/init.sql">https://github.com/vatsuvaksi/RealTime-Product-Review-Processing/blob/master/init.sql</a></blockquote><p>d. pom dependencies</p><pre>  &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-batch&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-data-jpa&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-devtools&lt;/artifactId&gt;<br>         &lt;scope&gt;runtime&lt;/scope&gt;<br>         &lt;optional&gt;true&lt;/optional&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>         &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>         &lt;scope&gt;runtime&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>         &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>         &lt;optional&gt;true&lt;/optional&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>         &lt;scope&gt;test&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>      &lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-webflux --&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-webflux&lt;/artifactId&gt;<br>         &lt;version&gt;6.2.0&lt;/version&gt;<br>      &lt;/dependency&gt;<br>      &lt;!-- https://mvnrepository.com/artifact/redis.clients/jedis --&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;redis.clients&lt;/groupId&gt;<br>         &lt;artifactId&gt;jedis&lt;/artifactId&gt;<br>         &lt;version&gt;5.2.0&lt;/version&gt;<br>      &lt;/dependency&gt;<br>      &lt;!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>         &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;<br>         &lt;version&gt;2.18.2&lt;/version&gt;<br>      &lt;/dependency&gt;<br>      &lt;!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>         &lt;artifactId&gt;jackson-core&lt;/artifactId&gt;<br>         &lt;version&gt;2.18.1&lt;/version&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;<br>         &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;<br>         &lt;version&gt;2.15.2&lt;/version&gt; &lt;!-- Adjust the version as needed --&gt;<br>      &lt;/dependency&gt;<br> &lt;/dependencies&gt;</pre><p>e. application.properties file</p><pre># Application name<br>spring.application.name=springbatchdemo<br><br># PostgreSQL database configuration<br>spring.datasource.url=jdbc:postgresql://psql:5432/batchdb<br>spring.datasource.driverClassName=org.postgresql.Driver<br>spring.datasource.username=batchuser<br>spring.datasource.password=batchpassword<br>spring.datasource.platform=postgres<br><br># JPA settings (if using Hibernate/JPA)<br>spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect<br>spring.jpa.hibernate.ddl-auto=update<br><br># Additional settings (optional, for better performance and debugging)<br>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.format_sql=true<br>spring.datasource.initialization-mode=always<br><br>logging.level.org.springframework.batch=DEBUG<br>logging.level.org.springframework=DEBUG</pre><p>and viola your basic setup is done.</p><p>Now all you have to do to test this setup is run the following scripts :</p><ol><li>Windows: <a href="https://github.com/vatsuvaksi/RealTime-Product-Review-Processing/blob/master/run.bat">https://github.com/vatsuvaksi/RealTime-Product-Review-Processing/blob/master/run.bat</a></li><li>Linux/mac: <a href="https://github.com/vatsuvaksi/RealTime-Product-Review-Processing/blob/master/run.sh">https://github.com/vatsuvaksi/RealTime-Product-Review-Processing/blob/master/run.sh</a></li></ol><p><em>Note: The above script would take 5 min to complete as it inserts a lot of records and then starts the application. I have intentionally put a timer on the dockerfile to wait for 300 seconds before booting up the application.</em></p><p>Now, we have a basic spring batch app running.</p><p>Let’s build the SQL queries and keep them handy.</p><ol><li>Entity class</li></ol><pre>@Entity<br>@Table(name = &quot;product_review&quot;)<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Builder<br>public class ProductReview {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    @Column(name = &quot;review_id&quot;)<br>    private Long reviewId;<br><br>    @Column(name = &quot;product_id&quot;, nullable = false)<br>    private Integer productId;<br><br>    @Column(name = &quot;user_id&quot;, nullable = false)<br>    private Integer userId;<br><br>    @Column(name = &quot;rating&quot;, nullable = false)<br>    private Short rating;<br><br>    @Column(name = &quot;review_text&quot;)<br>    private String reviewText;<br><br>    @Column(name = &quot;created_at&quot;, updatable = false, nullable = false)<br>    private LocalDateTime createdAt;<br><br>    @Column(name = &quot;is_processed&quot;, nullable = false)<br>    private Boolean isProcessed = false;<br>}</pre><p>2. Repository interface</p><pre>public interface ProductReviewRepository extends JpaRepository&lt;ProductReview, Long&gt; {<br><br>    @Query(&quot;SELECT pr FROM ProductReview pr &quot;)<br>    Page&lt;ProductReview&gt; findAllWithPagination(LocalDateTime yesterdayStart, LocalDateTime yesterdayEnd, Pageable pageable);<br><br>    @Query(&quot;SELECT COUNT(pr) FROM ProductReview pr &quot;)<br>    long countAllRecords(LocalDateTime yesterdayStart, LocalDateTime yesterdayEnd);<br>}</pre><p>Now, we’ll dive into the actual logic in a bit but let’s create the skeleton of all important classes so that we can build a configuration class for our batch application.</p><p><strong>Partioner :</strong></p><pre>@Component(&quot;partitioner&quot;)<br>public class ChunkPartitioner implements Partitioner {<br><br>    private final ProductReviewRepository repository;<br>    private final LocalDateTime yesterdayStart;<br>    private final LocalDateTime yesterdayEnd;<br>    private final int chunkSize = 5000;<br><br>    @Autowired<br>    public ChunkPartitioner(ProductReviewRepository repository) {<br>        this.repository = repository;<br>        LocalDate yesterday = LocalDate.now().minusDays(1);<br>        this.yesterdayStart = yesterday.atStartOfDay();<br>        this.yesterdayEnd = yesterday.atTime(LocalTime.MAX);<br>    }<br><br>    @Override<br>    public Map&lt;String, ExecutionContext&gt; partition(int gridSize) {<br>        long totalRecords = repository.countAllRecords(yesterdayStart,yesterdayEnd);<br>        System.out.println(&quot;Total Records Satisfying the condition &quot; + totalRecords);<br>        int numberOfPartitions = (int) Math.ceil((double) totalRecords / chunkSize);<br>        Map&lt;String, ExecutionContext&gt; partitions = new HashMap&lt;&gt;();<br><br>        for (int i = 0; i &lt; numberOfPartitions; i++) {<br>            ExecutionContext context = new ExecutionContext();<br>            context.putInt(&quot;pageNumber&quot;, i);<br>            context.putInt(&quot;pageSize&quot;, chunkSize);<br>            partitions.put(&quot;partition&quot; + i, context);<br>            System.out.println(&quot;Creating partition -&quot; + i + &quot; with pageNumber + &quot; + i + &quot; chunkSize &quot; + chunkSize);<br>        }<br><br>        return partitions;<br>    }<br>}</pre><p>Let me walk you through what’s happening here and how <strong>Spring Batch</strong> handles it. This class implements the <strong>Partitioner</strong> interface, which is provided by Spring Batch to create partitions. The core method responsible for this is <strong>public Map&lt;String, ExecutionContext&gt; partition(int gridSize)</strong>.</p><p>Here’s how it works: the size of the map returned by this method determines how many parallel threads will be created for the worker step. In other words, the <strong>Leader step</strong> uses this class to decide how many <strong>worker steps</strong> will run in parallel. For context, a <strong>worker step</strong> consists of the <strong>Reader → Processor → Writer</strong> sequence.</p><p>Now, don’t imagine that just because, say, 100 partitions are created, 100 parallel threads will automatically spin up. That’s not the case. In the <strong>configuration class</strong> (which we’ll define later), we’ll specify a <strong>thread pool</strong>, and only the threads using the core pool will be executed according to the number of available cores. The rest will sit in a queue, waiting their turn.</p><p><strong>ItemReader :</strong></p><pre>@Component(&quot;reader&quot;)<br>@StepScope<br>public class Reader implements ItemReader&lt;ProductReview&gt; {<br><br>    @Autowired<br>    private ProductReviewRepository repository;<br>    private Iterator&lt;ProductReview&gt; currentBatch;<br>    private int pageNumber;<br>    private int pageSize;<br>    private final LocalDateTime yesterdayStart;<br>    private final LocalDateTime yesterdayEnd;<br><br><br>    public Reader() {<br>        LocalDate yesterday = LocalDate.now().minusDays(1);<br>        this.yesterdayStart = yesterday.atStartOfDay();<br>        this.yesterdayEnd = yesterday.atTime(LocalTime.MAX);<br><br>    }<br><br>    @BeforeStep<br>    public void beforeStep(StepExecution stepExecution){<br>        ExecutionContext executionContext = stepExecution.getExecutionContext();<br>        this.pageNumber = executionContext.getInt(&quot;pageNumber&quot;);<br>        this.pageSize = executionContext.getInt(&quot;pageSize&quot;);<br>        PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);<br>        Page&lt;ProductReview&gt; page = repository.findAllWithPagination(yesterdayStart, yesterdayEnd, pageRequest);<br>        currentBatch = page.hasContent() ? page.getContent().iterator() : null;<br>    }<br><br>    @Override<br>    public ProductReview read() throws Exception {<br>        // Return the next item from the batch, or null if no more data<br>        if (currentBatch != null &amp;&amp; currentBatch.hasNext()) {<br>            return currentBatch.next();<br>        }<br><br>        return null;<br>    }<br>}</pre><p>Let me break down what this <strong>Reader class</strong> does. It’s fairly straightforward and forms the foundation of our batch job.</p><p>The <strong>beforeStep</strong> method is a key part of this class, and it takes a <strong>StepExecution</strong> object as a parameter. Wondering what that is? Let me explain:</p><ul><li>A <strong>Step</strong> is the logical unit of work in a batch job. It can either be <strong>tasklet-based</strong> or <strong>chunk-oriented</strong> (like in our case).</li><li><strong>StepExecution</strong> is a runtime object that tracks the execution of a step. It provides crucial metadata about the step, including details passed from the <strong>Partitioner</strong> for this specific thread, such as the <strong>page number</strong> and <strong>page size</strong> — essentially, the chunk of data this thread needs to read from the database.</li></ul><p>Once we have the required details, we use them to prepare an <strong>Iterator</strong> object that holds the data to be processed. The <strong>read()</strong> method, part of the Spring Batch framework, then takes over. It works by iterating over this iterator, fetching one item at a time. If an item exists, it passes it to the <strong>Processor</strong> for further transformation.</p><p>This setup ensures efficient chunk-based processing while keeping things modular and easy to debug.</p><p><strong>ItemProcessor :</strong></p><pre>@Component(&quot;processor&quot;)<br>public class NoOpItemProcessor implements ItemProcessor&lt;ProductReview, ProductReview&gt; {<br>    @Override<br>    public ProductReview process(ProductReview item) throws Exception {<br>        return item;<br>    }<br>}</pre><p>Well, as the name of the class suggests, we won’t be doing much here. 😄 However, if there’s any computation — like validation or business logic — that needs to be applied to each record, this is where it would typically go. We’ve decided not to utilize this for now, since we wanted to focus on processing <strong>subchunks in the writer</strong> rather than handling logic for each individual record in the processor.</p><p><strong>ItemWriter :</strong></p><pre>@Component(&quot;writer&quot;)<br>@StepScope<br>public class Writer implements ItemWriter&lt;ProductReview&gt; {<br><br>    private ThreadPoolExecutor executor;<br>    private final int parallelChunkSizeWriter = 2500;<br>    private final WebClient webClient;<br>    private final RedisService redisServer;<br><br><br>    @Autowired<br>    public Writer(WebClient.Builder webClientBuilder, RedisService redisServer) {<br>        this.webClient = webClientBuilder.baseUrl(&quot;http://localhost:3031&quot;).build();<br>        this.redisServer = redisServer;<br>    }<br><br>    @PostConstruct<br>    public void postConstruct() {<br>        int parallelExecutionInWriter = 2;<br>        executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(parallelExecutionInWriter);<br>    }<br><br>    @Override<br>    public void write(Chunk&lt;? extends ProductReview&gt; chunk) throws Exception {<br>        List&lt;? extends ProductReview&gt; reviews = chunk.getItems();<br><br>        // Step 1: Create subchunks of size parallelChunkSizeWriter<br>        List&lt;List&lt;ProductReview&gt;&gt; subChunks = createSubChunks(reviews, parallelChunkSizeWriter);<br><br>        // Step 2: Process subchunks in parallel using executor<br>        List&lt;CompletableFuture&lt;Void&gt;&gt; futures = new ArrayList&lt;&gt;();<br><br>        for (List&lt;ProductReview&gt; subChunk : subChunks) {<br>            futures.add(CompletableFuture.runAsync(() -&gt; processSubChunk(subChunk), executor));<br>        }<br><br>        // Wait for all parallel tasks to complete<br>        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();<br>    }<br><br>    private List&lt;List&lt;ProductReview&gt;&gt; createSubChunks(List&lt;? extends ProductReview&gt; reviews, int chunkSize) {<br>        List&lt;List&lt;ProductReview&gt;&gt; subChunks = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; reviews.size(); i += chunkSize) {<br>            subChunks.add(new ArrayList&lt;&gt;(reviews.subList(i, Math.min(i + chunkSize, reviews.size()))));<br>        }<br>        return subChunks;<br>    }<br><br>    private void processSubChunk(List&lt;ProductReview&gt; subChunk) {<br>        // Collect all API calls into a list of Monos<br>        List&lt;Mono&lt;Void&gt;&gt; tasks = new ArrayList&lt;&gt;();<br><br>        for (ProductReview review : subChunk) {<br>            Mono&lt;Void&gt; task = callGetApi(review)<br>                    .flatMap(response -&gt; {<br>                        storeInRedis(review, response);<br>                        return Mono.empty(); // Return a Mono&lt;Void&gt; to chain further processing if needed<br>                    });<br>            tasks.add(task);<br>        }<br><br>        // Combine all Monos and wait for completion<br>        Mono.when(tasks).block(); // This will wait for all tasks in this subchunk to complete<br>    }<br><br><br>    private Mono&lt;String&gt; callGetApi(ProductReview review) {<br>        return webClient.get()<br>                .uri(uriBuilder -&gt; uriBuilder.path(&quot;/endpoint&quot;)<br>                        .queryParam(&quot;id&quot;, review.getProductId())<br>                        .build())<br>                .retrieve()<br>                .bodyToMono(String.class)<br>                .doOnCancel(() -&gt; System.out.println(&quot;Request was canceled&quot;));<br>    }<br><br>    private void storeInRedis(ProductReview review, String apiResponse)  {<br>        try {<br>            redisServer.saveToRedis(String.valueOf(review.getReviewId()), apiResponse, review);<br>        } catch (JsonProcessingException e) {<br>            System.out.println(&quot;Redis push failed&quot; + e.getMessage());<br>        }<br>        System.out.println(&quot;Storing in Redis: &quot; + review + &quot; with response: &quot; + apiResponse);<br>    }<br>}</pre><p>Alright, folks, let’s dive into the final and arguably the most exciting part of our application: the <strong>Writer</strong> class. :) Remember when I mentioned earlier that the <strong>chunk</strong> of data we process is passed here? The chunk size is something we define in the <strong>configuration class</strong> (which we’ll build right after this).</p><p>Now, here’s where we make a few key decisions. After receiving the chunk, I break it down further into <strong>subchunks</strong>. Why? To keep processing efficient and resource-friendly. For simplicity and to avoid overwhelming my machine, I’ve set the subchunk size to <strong>500</strong> and created a thread pool with just <strong>two threads</strong>.</p><p>Given that I’ve specified a chunk size of <strong>5000</strong>, the chunk gets divided into <strong>10 subchunks</strong>, with only <strong>two</strong> being processed in parallel at any given time (thanks to the fixed thread pool). To manage these subchunks, I’ve leveraged <strong>CompletableFutures</strong> for asynchronous processing, ensuring we maximize performance without overloading resources.</p><p>Now, these numbers — like the chunk size and thread pool size — largely depend on the <strong>volume of data</strong> and your system’s <strong>JVM specs</strong>. For simplicity, I’ve chosen <strong>500</strong> as the subchunk size and a <strong>two-thread</strong> pool, but in a real-world scenario, you can derive optimal values based on factors such as <strong>available memory</strong>, <strong>number of CPU cores</strong>, and <strong>heap size</strong>. Remember, you don’t want to pick a chunk size that’s so large it overwhelms the JVM or causes memory issues. Similarly, your <strong>executor pool</strong> should be properly configured with the right number of threads, queue sizes, and policies to ensure smooth processing without bottlenecks.</p><p>Now, take a closer look at the <strong>GetAPI</strong> call. To make things even more efficient, I’ve incorporated <strong>Reactive WebFlux</strong> here. What does that mean? Instead of blocking calls, I generate a list of <strong>Mono</strong> objects and process the entire subchunk asynchronously. Once processed, the results are seamlessly pushed into <strong>Redis</strong>, ready for downstream systems to pick up.</p><p><strong>P.S.</strong> → If you’ve been following along and implementing this setup exactly as described, here’s a heads-up: the downstream services need to scale too! 😄 For instance, if you’re making API calls from multiple threads, the API server better be robust enough to handle the peak load. The same goes for Redis — handling so many concurrent inserts isn’t something your local machine will breeze through without breaking a sweat.</p><p>To truly make the magic happen in a production environment, proper configurations and scaling efforts are non-negotiable. For learning purposes, though, you can replace those API calls with simple log statements instead of actually invoking them. Save the heavy lifting for when your amazing <strong>DevOps team</strong> has worked their magic to scale this for a real-world production app! 😉</p><h3>What Happens in the Writer? Scenarios to Understand</h3><p>To clarify how this all plays out, let’s look at three common scenarios:</p><h4>Scenario 1: Records per Partition Matches Chunk Size</h4><p>If the number of records in a partition equals the chunk size (e.g. both are 5000):</p><ul><li>The writer processes one chunk of 5000 records.</li><li>This is the most efficient scenario since the records align perfectly with the chunk size.</li></ul><h4>Scenario 2: Records per Partition Are Less Than Chunk Size</h4><p>For example, suppose Partition 1 has 5000 records and Partition 2 has 200 records:</p><ul><li>Partition 1 processes a single chunk of 5000 records.</li><li>Partition 2 processes a smaller chunk of 200 records (whatever is available). There’s no “padding” or filler to reach the defined chunk size.</li></ul><h3>Should Partition Size Match Worker Chunk Size?</h3><p>It’s not mandatory for these sizes to match. Here’s why:</p><h4>Partition Size (Defined in Partitioner):</h4><ul><li>Represents the total workload assigned to a worker thread.</li><li>Typically larger and defines the maximum records a worker will handle.</li></ul><h4>Worker Chunk Size (Defined in Worker Step):</h4><ul><li>Represents the number of records processed in a single transaction within a worker.</li><li>Often smaller or equal to the partition size for better fault tolerance and resource management.</li></ul><p>Ultimately, the exact values depend on your <strong>data volume</strong>, <strong>available JVM memory</strong>, and <strong>core/thread pool configuration</strong>. A key takeaway is to find a sweet spot where:</p><ul><li><strong>Chunk sizes</strong> aren’t too large to exhaust memory or too small to cause excessive I/O overhead.</li><li><strong>Thread pool</strong> is configured thoughtfully, balancing throughput and available resources (like cores and memory).</li></ul><p><strong>BatchConfiguration</strong> :</p><pre>@Configuration<br>@EnableBatchProcessing<br>public class BatchConfig {<br><br>    @Autowired<br>    private JobRepository jobRepository;<br><br>    @Autowired<br>    @Qualifier(&quot;transactionManager&quot;)<br>    private PlatformTransactionManager transactionManager;<br><br>    @Autowired<br>    @StepScope<br>    private Reader reader;<br><br>    @Autowired<br>    @StepScope<br>    private NoOpItemProcessor processor;<br><br>    @Autowired<br>    @StepScope<br>    private Writer writer;<br><br>    @Autowired<br>    private Partitioner partitioner;<br><br>    @Autowired<br>    private JobCompletionNotificationListener listener;<br><br>    private final int chunkSize = 5000;<br><br>    @Bean<br>    public Job job(){<br>        return new JobBuilder(&quot;batchJobdemo&quot; , jobRepository)<br>                .incrementer(new RunIdIncrementer())<br>                .start(leaderStep())<br>                .listener(listener)<br>                .build();<br>    }<br><br>    @Bean<br>    public Step leaderStep() {<br>        return new StepBuilder(&quot;leaderStep&quot; , jobRepository)<br>                .partitioner(&quot;workerStep&quot; , partitioner)<br>                .step(workerStep())<br>                .taskExecutor(taskExecutor())<br>                .allowStartIfComplete(true)<br>                .build();<br>    }<br><br>    @Bean<br>    public Step workerStep() {<br>        return new StepBuilder(&quot;workerStep&quot;, jobRepository)<br>                .&lt;ProductReview, ProductReview&gt;chunk(chunkSize, transactionManager)<br>                .reader(reader)<br>                .processor(processor)<br>                .writer(writer)<br>                .allowStartIfComplete(true)<br>                .build();<br>    }<br><br>    @Bean<br>    public TaskExecutor taskExecutor() {<br>        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();<br>        int cores = Runtime.getRuntime().availableProcessors();<br>        taskExecutor.setCorePoolSize(Math.max(cores - 1, 1));<br>        taskExecutor.setMaxPoolSize(Math.max(cores - 1, 1));<br>        taskExecutor.setQueueCapacity(64);<br>        taskExecutor.setThreadNamePrefix(&quot;BatchTask-&quot;);<br>        taskExecutor.initialize();<br>        return taskExecutor;<br>    }<br>}</pre><p>Let’s dive into the <strong>batch configuration</strong> — the core of the application. While this setup isn’t production-grade, it’s sufficient for now. However, when building a large-scale application, there are plenty of additional options to consider, such as <strong>better error handling</strong>, <strong>skipping specific exceptions</strong>, and <strong>implementing retries</strong> to handle transient failures gracefully. Think of this configuration as the <strong>brain of the application</strong>: it orchestrates the flow of the batch job, ensuring everything runs as expected.</p><p>Here’s how it works: when a <strong>job</strong> is launched, the <strong>JobLauncher</strong> initializes the <strong>JobRepository</strong>, which holds all the metadata and runtime information about the job (such as its status, execution history, etc.). The <strong>job</strong>, in turn, defines the overall flow of the application, including all the steps involved. Each job is registered within the <strong>JobRepository</strong>.</p><p>In the first function, job(), we initialize the job with a <strong>leader step</strong>. Now, what does a leader step do? It’s essentially the <strong>master step</strong> that coordinates the execution of partitions. Using a <strong>StepBuilder</strong>, we configure the leader step with a <strong>partitioner</strong>, a <strong>task executor</strong>, and <strong>worker (slave) steps</strong>. The leader step is responsible for running the partitioner, which divides the data into partitions. Each partition is then assigned to a <strong>worker step</strong>, and all the worker steps execute in parallel within the thread pool we’ve configured. Cool, right?</p><p>Now let’s discuss the <strong>worker step</strong>. As you can see in the configuration, the worker step ties together the <strong>reader</strong>, <strong>processor</strong>, and <strong>writer</strong>, executing them sequentially (Reader → Processor → Writer).</p><p>Finally, you might have noticed we’ve added a <strong>listener</strong>. This is a handy addition for logging events like when the batch starts, when it ends, or any other custom logs you’d like to add for better traceability and monitoring.</p><p><strong>DbConfig:</strong></p><pre>@Configuration<br>@EnableTransactionManagement<br>@EnableJpaRepositories(entityManagerFactoryRef = &quot;entityManagerFactoryBatchReadWrite&quot;,<br>        transactionManagerRef = &quot;transactionManager&quot;, basePackages = {<br>        &quot;com.vatsuvaksi.springbatchdemo.repository&quot;})<br>public class BatchDbConfig {<br><br>    private final String connectionTestQuery = &quot;SELECT 1&quot;;<br><br>    @Bean(&quot;dataSource&quot;)<br>    @BatchDataSource<br>    @Primary<br>    public HikariDataSource dataSourceBatchReadWrite() {<br><br>        HikariConfig config = new HikariConfig();<br><br>        config.setJdbcUrl(&quot;jdbc:postgresql://localhost:5432/batchdb&quot;);<br>        config.setUsername(&quot;batchuser&quot;);<br>        config.setPassword(&quot;batchpassword&quot;);<br>        config.setDriverClassName(&quot;org.postgresql.Driver&quot;);<br>        config.setMaximumPoolSize(10);<br>        config.setConnectionTimeout(30000);<br>        config.setIdleTimeout(600000);<br><br>        return new HikariDataSource(config);<br>    }<br><br>    @Bean(&quot;entityManagerFactoryBatchReadWrite&quot;)<br>    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBatchReadWrite(<br>            @Qualifier(&quot;dataSource&quot;) HikariDataSource dataSourceReadWrite, EntityManagerFactoryBuilder builder) {<br>        return builder.dataSource(dataSourceReadWrite).packages(&quot;com.vatsuvaksi.springbatchdemo.entities&quot;).persistenceUnit(&quot;batchPersistenceUnit&quot;).build();<br>    }<br><br>    @Bean(&quot;transactionManager&quot;)<br>    public PlatformTransactionManager transactionManagerBatchReadWrite(<br>            @Qualifier(&quot;entityManagerFactoryBatchReadWrite&quot;) EntityManagerFactory entityManagerFactoryReadWrite) {<br>        return new JpaTransactionManager(entityManagerFactoryReadWrite);<br>    }<br>}</pre><p>I added this database connectivity configuration because, apart from your business database, Spring Batch needs its own set of metadata tables to track and manage job executions. Ideally, you’d separate these into two schemas — one for your business data and another dedicated to batch metadata. But for simplicity (and to keep things less chaotic for now), I’ve configured everything within a single database instance.</p><p>You can find all the code and helper code like job runner, main class etc to run the app here :</p><p><a href="https://github.com/vatsuvaksi/RealTime-Product-Review-Processing">https://github.com/vatsuvaksi/RealTime-Product-Review-Processing</a></p><p>That’s it now everything is set and we are ready to test :)</p><p>===========================================================</p><h3>Conclusion:</h3><p>The batch architecture we discussed here embraces scalability, efficiency, and adaptability. By leveraging partitioning, parallel processing, subchunking, and custom configurations, we ensured that even the most computationally demanding workloads were processed in record time without overloading resources. This approach doesn’t just get the job done; it transforms the job into a streamlined, high-performance workflow that’s ready for real-world challenges. Sure, it might take a bit more effort to set up, but when you see the results, you’ll know it’s worth every line of code! 💪</p><blockquote>Screenshots of my local machine :</blockquote><p><strong>Before the execution of docker compose:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*hhjKGeKWilXTjpAdRIQLZQ.png" /></figure><p><strong>During the execution :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*5OMiouQPoVpEpuZze8_ZNw.png" /></figure><p><strong>Final Status Logs</strong> [All helper Services running within the same docker network]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoR1TqGRM_9wwsAX5485gw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d157bec3eaf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>