<?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 Rishindu yohan on Medium]]></title>
        <description><![CDATA[Stories by Rishindu yohan on Medium]]></description>
        <link>https://medium.com/@rishinduyohan?source=rss-c6aab50a37fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9z2kVnaCT5wHpz1y</url>
            <title>Stories by Rishindu yohan on Medium</title>
            <link>https://medium.com/@rishinduyohan?source=rss-c6aab50a37fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 14:48:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishinduyohan/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[Apache Kafka: Why You Need It, How to Install It, and How to Use It?]]></title>
            <link>https://medium.com/@rishinduyohan/apache-kafka-why-you-need-it-how-to-install-it-and-how-to-use-it-e362a8b093b5?source=rss-c6aab50a37fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e362a8b093b5</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Rishindu yohan]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 07:05:48 GMT</pubDate>
            <atom:updated>2026-07-06T07:05:48.016Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever built a system where <strong>one service needs to tell many other services that something happened</strong> — a new order, a signup, a payment, a location update — you’ve run into the exact problem Apache Kafka was built to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Rcug3TJ4Eyx5sxhh6UpwA.jpeg" /></figure><p>This article walks through:</p><ol><li>What Kafka actually is (in plain English)</li><li>Why you need it — with a real before/after example</li><li>How to install it (Docker, and a manual setup)</li><li>How to create topics, produce, and consume messages</li><li>A working Node.js/TypeScript example</li><li>Common mistakes to avoid</li></ol><h3>1. What Is Kafka, Really?</h3><p>Apache Kafka is a <strong>distributed event streaming platform</strong>. Strip away the buzzwords, and it’s really just a very fast, very durable, highly scalable <strong>log</strong>.</p><p>Services write events (“messages”) into Kafka. Other services read those events, independently and at their own pace. Kafka doesn’t care who’s listening — it just keeps the log.</p><pre>┌─────────────┐<br>   Producer  ──▶ │             │ ──▶  Consumer A (Email service)<br>   (Order API)   │   KAFKA     │ ──▶  Consumer B (Analytics)<br>   Producer  ──▶ │   TOPIC     │ ──▶  Consumer C (Inventory)<br>   (Payments)    │             │<br>                 └─────────────┘</pre><h3>The core building blocks</h3><p>Concept What it means <strong>Broker</strong> A single Kafka server. A cluster is made up of multiple brokers. <strong>Topic</strong> A named stream of events, e.g. orders.created. <strong>Partition</strong> A topic is split into partitions for parallelism and ordering guarantees. <strong>Producer</strong> An app that writes/publishes messages to a topic. <strong>Consumer</strong> An app that reads/subscribes to messages from a topic. <strong>Consumer Group</strong> A set of consumers sharing the work of reading a topic. <strong>Offset</strong> A pointer marking how far a consumer has read in a partition.</p><p><em>(Suggested image: a diagram of a topic split into 3 partitions, each holding an ordered log of messages with offsets.)</em></p><h3>2. Why Do You Actually Need Kafka?</h3><p>Here’s the problem Kafka solves, illustrated with a common scenario.</p><h3>The “Before” — tightly coupled services</h3><p>Imagine an e-commerce Order Service. When an order is placed, it needs to:</p><ul><li>Send a confirmation email</li><li>Update inventory</li><li>Notify the shipping service</li><li>Log the event for analytics</li></ul><p>A naive approach calls each service directly:</p><pre>Order Service → calls Email Service (HTTP)<br>             → calls Inventory Service (HTTP)<br>             → calls Shipping Service (HTTP)<br>             → calls Analytics Service (HTTP)</pre><p><strong>Problems with this:</strong></p><ul><li>If Email Service is down, does the whole order fail?</li><li>Adding a new consumer (say, a fraud-detection service) means modifying Order Service’s code.</li><li>If Inventory Service is slow, the customer’s checkout request hangs.</li><li>No replay: if Analytics Service was down for an hour, that data is gone.</li></ul><h3>The “After” — Kafka as the buffer</h3><pre>Order Service → publishes &quot;order.created&quot; event → Kafka</pre><pre>Kafka topic: order.created<br>   ├── Email Service        (consumes independently)<br>   ├── Inventory Service    (consumes independently)<br>   ├── Shipping Service     (consumes independently)<br>   └── Analytics Service    (consumes independently, even if it&#39;s down for a while)</pre><p>Order Service now does <strong>one thing</strong>: publish an event. It doesn’t know or care who’s listening. New consumers can be added later with zero changes to Order Service. If a consumer goes down, it just resumes from its last offset when it comes back — no data lost.</p><h3>When you actually need it</h3><p>Kafka earns its complexity when you have:</p><ul><li>Multiple services that need the same event (fan-out)</li><li>High-throughput data (clickstreams, IoT sensors, logs, metrics)</li><li>A need to replay historical events (rebuild a cache, backfill a new service)</li><li>Strict ordering requirements per key (e.g., all events for user_id=123 processed in order)</li></ul><p>If you just need one service to call another and get an immediate response, Kafka is overkill — a simple REST call or a lightweight queue (like SQS or RabbitMQ) is usually the better fit.</p><h3>3. Installing Kafka</h3><p>There are two common paths. Docker is the fastest way to get a working setup for local development.</p><h3>Option A: Docker Compose (recommended for local dev)</h3><p>Create a file named docker-compose.yml:</p><pre>version: &quot;3.8&quot;<br>services:<br>  kafka:<br>    image: apache/kafka:latest<br>    container_name: kafka<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      KAFKA_NODE_ID: 1<br>      KAFKA_PROCESS_ROLES: broker,controller<br>      KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1</pre><p>Then start it:</p><pre>docker compose up -d</pre><p>That’s it — no separate ZooKeeper needed. Modern Kafka (KRaft mode) runs without ZooKeeper entirely.</p><h3>Option B: Manual installation (Linux/macOS)</h3><pre># 1. Make sure Java 17+ is installed<br>java -version<br><br># 2. Download the latest Kafka binary<br>curl -O https://downloads.apache.org/kafka/3.8.0/kafka_2.13-3.8.0.tgz<br>tar -xzf kafka_2.13-3.8.0.tgz<br>cd kafka_2.13-3.8.0<br><br># 3. Generate a cluster ID and format storage (KRaft mode, no ZooKeeper)<br>KAFKA_CLUSTER_ID=&quot;$(bin/kafka-storage.sh random-uuid)&quot;<br>bin/kafka-storage.sh format -t $KAFKA_CLUSTER_ID -c config/kraft/server.properties<br><br># 4. Start the broker<br>bin/kafka-server-start.sh config/kraft/server.properties</pre><blockquote><em>Check the official Kafka downloads page for the current stable version number before running these commands, since version numbers change over time.</em></blockquote><p><em>(Suggested image: a screenshot of your terminal after step 4, showing the broker successfully started.)</em></p><h3>Verifying it works</h3><pre># Create a topic<br>bin/kafka-topics.sh --create --topic test-topic \<br>  --bootstrap-server localhost:9092 \<br>  --partitions 3 --replication-factor 1</pre><pre># List topics to confirm<br>bin/kafka-topics.sh --list --bootstrap-server localhost:9092</pre><p>If test-topic shows up, Kafka is running correctly.</p><h3>4. Producing and Consuming from the Command Line</h3><p>Open two terminal windows.</p><p><strong>Terminal 1 — start a consumer (it will wait for messages):</strong></p><pre>bin/kafka-console-consumer.sh --topic test-topic \<br>  --bootstrap-server localhost:9092</pre><p><strong>Terminal 2 — start a producer and type messages:</strong></p><pre>bin/kafka-console-producer.sh --topic test-topic \<br>  --bootstrap-server localhost:9092</pre><p>Type a message and hit enter. It will instantly appear in Terminal 1. This is Kafka in its simplest form — a durable pipe between a writer and a reader.</p><h3>5. A Real Example: Node.js/TypeScript Producer and Consumer</h3><p>Most developers building on Next.js or Node.js backends will use <a href="https://kafka.js.org/">KafkaJS</a>.</p><pre>npm install kafkajs</pre><h3>Producer — publishing an “order created” event</h3><pre>// producer.ts<br>import { Kafka } from &quot;kafkajs&quot;;<br><br>const kafka = new Kafka({<br>  clientId: &quot;order-service&quot;,<br>  brokers: [&quot;localhost:9092&quot;],<br>});<br><br>const producer = kafka.producer();<br><br>async function publishOrderCreated(orderId: string, userId: string) {<br>  await producer.connect();<br><br>  await producer.send({<br>    topic: &quot;order.created&quot;,<br>    messages: [<br>      {<br>        key: userId, // ensures all events for this user go to the same partition<br>        value: JSON.stringify({<br>          orderId,<br>          userId,<br>          createdAt: new Date().toISOString(),<br>        }),<br>      },<br>    ],<br>  });<br><br>  await producer.disconnect();<br>}<br><br>publishOrderCreated(&quot;order_123&quot;, &quot;user_456&quot;);</pre><h3>Consumer — an email service reacting to the event</h3><pre>// consumer.ts<br>import { Kafka } from &quot;kafkajs&quot;;<br><br>const kafka = new Kafka({<br>  clientId: &quot;email-service&quot;,<br>  brokers: [&quot;localhost:9092&quot;],<br>});<br><br>const consumer = kafka.consumer({ groupId: &quot;email-service-group&quot; });<br><br>async function run() {<br>  await consumer.connect();<br>  await consumer.subscribe({ topic: &quot;order.created&quot;, fromBeginning: true });<br><br>  await consumer.run({<br>    eachMessage: async ({ message }) =&gt; {<br>      const event = JSON.parse(message.value?.toString() ?? &quot;{}&quot;);<br>      console.log(`Sending confirmation email for order ${event.orderId}`);<br>      // sendEmail(event.userId, event.orderId) ...<br>    },<br>  });<br>}</pre><pre>run().catch(console.error);</pre><p>Run the consumer first, then the producer. You’ll see the consumer react to the event the moment it’s published — and if you add a second consumer group (say, inventory-service-group), it will get the <em>same</em> event independently, without touching the producer&#39;s code at all.</p><p><em>(Suggested image: two boxes — “email-service-group” and “inventory-service-group” — both reading from the same “order.created” topic, each with their own offset.)</em></p><h3>6. Common Mistakes to Avoid</h3><ul><li><strong>Using one giant topic for everything.</strong> Design topics around business events (order.created, payment.failed), not around technical convenience.</li><li><strong>Not setting a message key.</strong> Without a key, Kafka spreads related messages across partitions randomly, which breaks per-entity ordering (e.g., events for the same user arriving out of order).</li><li><strong>Treating Kafka like a database.</strong> Kafka retains data for a configured period (or size) — it’s a durable log with retention, not permanent storage. Use retention policies deliberately.</li><li><strong>Ignoring consumer group IDs.</strong> Two consumers with the same groupId split the work between them (each message goes to only one). Two consumers with <em>different</em> group IDs each get their own full copy of the stream. Mixing this up is one of the most common production bugs.</li><li><strong>Skipping partition planning.</strong> The number of partitions limits how many consumers in a group can process a topic in parallel. Too few partitions and you can’t scale consumers; too many creates overhead you may not need.</li><li><strong>Not monitoring consumer lag.</strong> If consumers fall behind the rate of production, lag builds up silently until something breaks downstream. Track it from day one.</li></ul><h3>Wrapping Up</h3><p>Kafka isn’t just “a message queue” — it’s a shift in how services communicate: from direct, tightly-coupled calls to independent, replayable event streams. Once one team adopts it for a single use case, it tends to become the backbone other teams build on too.</p><p>If you’re building anything with multiple services that need to react to the same events — orders, signups, payments, sensor data — it’s worth the setup cost.</p><p><strong>Have you used Kafka in production? What tripped you up the first time?</strong> Drop a comment below — I’d love to compare notes.</p><p><em>If this was useful, follow for more deep dives into backend architecture, Next.js, and system design.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e362a8b093b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-powered
applications with Kotlin and Spring AI]]></title>
            <link>https://medium.com/@rishinduyohan/ai-powered-applications-with-kotlin-and-spring-ai-284243f2cf79?source=rss-c6aab50a37fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/284243f2cf79</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[jetbrains]]></category>
            <dc:creator><![CDATA[Rishindu yohan]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 05:01:01 GMT</pubDate>
            <atom:updated>2026-03-07T05:01:01.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xM-l8trdbOc7MPaMqjOICA.png" /></figure><blockquote>A friendly, step-by-step guide to connecting your Kotlin backend to an LLM, storing docs in a vector database, and answering questions with real context</blockquote><p>Imagine building a chatbot that doesn’t just hallucinate answers — but actually <em>reads your documentation</em> and responds based on what’s in it. That’s exactly what we’re building today.</p><p>In this tutorial, we’ll create a Kotlin + Spring Boot application that:</p><ul><li>Loads real Kotlin documentation into a <strong>vector database</strong> (Qdrant)</li><li>Lets you search those docs using <strong>semantic similarity</strong></li><li>Powers a /chat endpoint that answers questions using <strong>Retrieval-Augmented Generation (RAG)</strong> via OpenAI</li></ul><p>No fluff. No hand-waving. Just clean Kotlin code and real results. Let’s go.</p><h3>What We’ll Use</h3><p>Before we start, here’s a quick overview of the tech stack:</p><p>Tool Role <strong>Kotlin</strong> Our language of choice — concise, expressive, JVM-powered <strong>Spring Boot</strong> Application framework and HTTP server <strong>Spring AI</strong> Abstracts LLM interactions and vector store integrations <strong>OpenAI</strong> Powers the language model (GPT-4o Mini) <strong>Qdrant</strong> Vector database for storing and searching document embeddings <strong>Docker</strong> Runs Qdrant locally with one command <strong>IntelliJ IDEA</strong> IDE with first-class Kotlin + Spring support</p><h3>A Quick Concept Check: What Is RAG?</h3><p><strong>Retrieval-Augmented Generation (RAG)</strong> sounds fancy, but the idea is simple:</p><ol><li>You have documents (e.g., Kotlin docs)</li><li>You convert them into <strong>embeddings</strong> (numerical representations of meaning)</li><li>When a user asks a question, you find the most <em>semantically similar</em> documents</li><li>You send those documents along with the question to the LLM</li><li>The LLM answers using that context — not just its training data</li></ol><p>Think of it like giving your AI open-book access to your own documentation.</p><h3>Prerequisites</h3><p>Before writing a single line of code, make sure you have:</p><ol><li><strong>IntelliJ IDEA Ultimate</strong> — <a href="https://www.jetbrains.com/idea/download/">Download here</a>. (Community Edition also works if you use <a href="https://start.spring.io/">start.spring.io</a> to generate the project.)</li><li><strong>An OpenAI API Key</strong> — Create one at <a href="https://platform.openai.com/api-keys">platform.openai.com/api-keys</a></li><li><strong>Docker Desktop</strong> — <a href="https://www.docker.com/">Download here</a></li><li><strong>Java 17+</strong> (the project uses Java 17)</li></ol><p>Once Docker is running, start Qdrant with this single command:</p><pre>docker run -p 6333:6333 -p 6334:6334 qdrant/qdrant</pre><p>That’s it — Qdrant is now running locally. You can verify it’s alive by visiting: <a href="http://localhost:6333/dashboard">http://localhost:6333/dashboard</a></p><h3>Step 1: Create the Spring Boot Project</h3><p>Open IntelliJ IDEA and go to <strong>File → New → Project → Spring Boot</strong>.</p><p>Fill in the fields:</p><ul><li><strong>Name:</strong> springAIDemo</li><li><strong>Language:</strong> Kotlin</li><li><strong>Type:</strong> Gradle — Kotlin</li><li><strong>Package name:</strong> com.example.springaidemo</li><li><strong>JDK:</strong> Oracle OpenJDK 21 (or your installed version)</li><li><strong>Java:</strong> 17</li></ul><p>Click <strong>Next</strong>, then select these dependencies:</p><ul><li>✅ Spring Web (under Web)</li><li>✅ OpenAI (under AI)</li><li>✅ Qdrant Vector Database (under SQL)</li></ul><p>Click <strong>Create</strong>. IntelliJ will download everything and set up your project structure like this:</p><pre>springAIDemo/<br>├── src/<br>│   └── main/<br>│       ├── kotlin/<br>│       │   └── com/example/springaidemo/<br>│       │       └── SpringAiDemoApplication.kt<br>│       └── resources/<br>│           └── application.properties<br>├── build.gradle.kts<br>└── settings.gradle.kts</pre><blockquote><em>💡 </em><strong><em>Tip:</em></strong><em> If you’re using Community Edition, go to </em><a href="https://start.spring.io/#!language=kotlin&amp;type=gradle-project-kotlin"><em>start.spring.io</em></a><em>, configure the same settings, and download the ZIP.</em></blockquote><h3>⚙️ Step 2: Configure the Project</h3><h3>2a. Update build.gradle.kts</h3><p>Make sure your Kotlin version and Spring AI version are up to date:</p><pre>plugins {<br>    kotlin(&quot;jvm&quot;) version &quot;2.3.10&quot;<br>    kotlin(&quot;plugin.spring&quot;) version &quot;2.3.10&quot;<br>    // ... other plugins<br>}</pre><pre>// Inside the extra block:<br>extra[&quot;springAiVersion&quot;] = &quot;1.0.0&quot;</pre><p>Click the <strong>Sync Gradle Changes</strong> button (the elephant icon with a refresh symbol) in the top-right of the editor. Gradle will download all required dependencies.</p><h3>2b. Configure application.properties</h3><p>Open src/main/resources/application.properties and add:</p><pre># OpenAI Configuration<br>spring.ai.openai.api-key=YOUR_OPENAI_API_KEY<br>spring.ai.openai.chat.options.model=gpt-4o-mini<br>spring.ai.openai.embedding.options.model=text-embedding-ada-002</pre><pre># Qdrant Configuration<br>spring.ai.vectorstore.qdrant.host=localhost<br>spring.ai.vectorstore.qdrant.port=6334<br>spring.ai.vectorstore.qdrant.collection-name=kotlinDocs<br>spring.ai.vectorstore.qdrant.initialize-schema=true</pre><blockquote><em>⚠️ </em><strong><em>Important:</em></strong><em> Replace </em><em>YOUR_OPENAI_API_KEY with your actual key. Never commit this to version control — use environment variables or a secrets manager in production.</em></blockquote><p><strong>What’s happening here?</strong></p><ul><li>We’re telling Spring AI to use gpt-4o-mini for chat (fast and cost-effective)</li><li>text-embedding-ada-002 converts text into vector embeddings</li><li>Qdrant will create a collection called kotlinDocs to store those embeddings</li><li>initialize-schema=true tells Qdrant to auto-create the collection on first run</li></ul><h3>Step 3: Run the App (First Time)</h3><p>Run the SpringAiDemoApplication.kt file. The Spring Boot app will start and automatically create the kotlinDocs collection in Qdrant.</p><p>Open your browser and visit:</p><pre>http://localhost:6333/dashboard#/collections</pre><p>You should see kotlinDocs listed — empty for now, but ready to be filled.</p><h3>Step 4: Add a RestTemplate Bean</h3><p>Before we create our controller, we need to configure a RestTemplate bean so our app can make HTTP calls to fetch Kotlin documentation from GitHub.</p><p>Update SpringAiDemoApplication.kt:</p><pre>package com.example.springaidemo</pre><pre>import org.springframework.boot.autoconfigure.SpringBootApplication<br>import org.springframework.boot.runApplication<br>import org.springframework.context.annotation.Bean<br>import org.springframework.web.client.RestTemplate</pre><pre>@SpringBootApplication<br>class SpringAiDemoApplication {</pre><pre>    @Bean<br>    fun restTemplate(): RestTemplate = RestTemplate()<br>}</pre><pre>fun main(args: Array&lt;String&gt;) {<br>    runApplication&lt;SpringAiDemoApplication&gt;(*args)<br>}</pre><p>RestTemplate is Spring&#39;s HTTP client — here we&#39;re registering it as a Spring bean so it can be injected anywhere in our app.</p><h3>Step 5: Create the Document Controller</h3><p>Now for the fun part. Create a new file KotlinSTDController.kt in your main package:</p><pre>package com.example.springaidemo</pre><pre>import org.slf4j.LoggerFactory<br>import org.springframework.ai.document.Document<br>import org.springframework.ai.vectorstore.SearchRequest<br>import org.springframework.ai.vectorstore.VectorStore<br>import org.springframework.web.bind.annotation.*<br>import org.springframework.web.client.RestTemplate<br>import kotlin.uuid.ExperimentalUuidApi<br>import kotlin.uuid.Uuid</pre><pre>@RestController<br>@RequestMapping(&quot;/kotlin&quot;)<br>class KotlinSTDController(<br>    private val restTemplate: RestTemplate,<br>    private val vectorStore: VectorStore,<br>) {<br>    private val logger = LoggerFactory.getLogger(this::class.java)</pre><pre>    @OptIn(ExperimentalUuidApi::class)<br>    @PostMapping(&quot;/load-docs&quot;)<br>    fun load() {<br>        val kotlinStdTopics = listOf(<br>            &quot;collections-overview&quot;, &quot;constructing-collections&quot;, &quot;iterators&quot;,<br>            &quot;ranges&quot;, &quot;sequences&quot;, &quot;collection-operations&quot;,<br>            &quot;collection-transformations&quot;, &quot;collection-filtering&quot;,<br>            &quot;collection-plus-minus&quot;, &quot;collection-grouping&quot;, &quot;collection-parts&quot;,<br>            &quot;collection-elements&quot;, &quot;collection-ordering&quot;, &quot;collection-aggregate&quot;,<br>            &quot;collection-write&quot;, &quot;list-operations&quot;, &quot;set-operations&quot;,<br>            &quot;map-operations&quot;, &quot;read-standard-input&quot;, &quot;opt-in-requirements&quot;,<br>            &quot;scope-functions&quot;, &quot;time-measurement&quot;,<br>        )</pre><pre>        val url = &quot;https://raw.githubusercontent.com/JetBrains/kotlin-web-site/refs/heads/master/docs/topics/&quot;</pre><pre>        kotlinStdTopics.forEach { topic -&gt;<br>            val data = restTemplate.getForObject(&quot;$url$topic.md&quot;, String::class.java)<br>            data?.let {<br>                val doc = Document.builder()<br>                    .id(Uuid.random().toString())<br>                    .text(it)<br>                    .metadata(&quot;topic&quot;, topic)<br>                    .build()<br>                vectorStore.add(listOf(doc))<br>                logger.info(&quot;Document $topic loaded.&quot;)<br>            } ?: logger.warn(&quot;Failed to load document for topic: $topic&quot;)<br>        }<br>    }</pre><pre>    @GetMapping(&quot;/docs&quot;)<br>    fun query(<br>        @RequestParam query: String = &quot;operations, filtering, and transformations&quot;,<br>        @RequestParam topK: Int = 2<br>    ): List&lt;Document&gt;? {<br>        val searchRequest = SearchRequest.builder()<br>            .query(query)<br>            .topK(topK)<br>            .build()</pre><pre>        val results = vectorStore.similaritySearch(searchRequest)<br>        logger.info(&quot;Found ${results?.size ?: 0} documents for query: &#39;$query&#39;&quot;)<br>        return results<br>    }<br>}</pre><h3>Breaking It Down</h3><p><strong>/kotlin/load-docs (POST)</strong></p><p>This endpoint:</p><ol><li>Defines a list of Kotlin standard library topic names</li><li>Fetches the raw Markdown content of each from GitHub</li><li>Wraps each in a Document object with a random UUID</li><li>Stores it in Qdrant via vectorStore.add()</li></ol><p>Spring AI automatically converts the text to embeddings using text-embedding-ada-002 before storing it. No extra code needed!</p><p><strong>/kotlin/docs (GET)</strong></p><p>This endpoint:</p><ol><li>Accepts a query string (default: &quot;operations, filtering, and transformations&quot;)</li><li>Accepts topK — how many similar documents to return</li><li>Calls vectorStore.similaritySearch() to find the most relevant documents</li></ol><p>The magic of vector search: it doesn’t match on keywords — it matches on <em>meaning</em>. Searching “how to iterate a list” will return documents about iterators, even if they don’t contain that exact phrase.</p><h3>Step 6: Load Documents and Search</h3><p>Run the app, then in your terminal:</p><p><strong>Load all documentation into Qdrant:</strong></p><pre>curl -X POST http://localhost:8080/kotlin/load-docs</pre><p>You’ll see log output as each document is fetched and stored. This takes a minute or two since we’re fetching ~22 documents and generating embeddings for each.</p><p><strong>Search the documentation:</strong></p><pre>curl -X GET &quot;http://localhost:8080/kotlin/docs?query=how+do+sequences+work&amp;topK=2&quot;</pre><p>You’ll get back a JSON array of the top 2 most relevant documents. Head back to the Qdrant dashboard to see your vectors stored and queryable!</p><h3>Step 7: Add the AI Chat Endpoint</h3><p>Now we add the real intelligence — a chat endpoint that combines search <em>and</em> generation.</p><p>Update KotlinSTDController.kt with the new imports:</p><pre>import org.springframework.ai.chat.client.ChatClient<br>import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor<br>import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor<br>import org.springframework.ai.chat.prompt.Prompt<br>import org.springframework.ai.chat.prompt.PromptTemplate<br>import org.springframework.web.bind.annotation.RequestBody</pre><p>Add a data class for the request:</p><pre>data class ChatRequest(val query: String, val topK: Int = 3)</pre><p>Update the controller constructor to include ChatClient.Builder:</p><pre>class KotlinSTDController(<br>    private val chatClientBuilder: ChatClient.Builder,<br>    private val restTemplate: RestTemplate,<br>    private val vectorStore: VectorStore,<br>)</pre><p>Build the ChatClient inside the class body:</p><pre>private val chatClient = chatClientBuilder<br>    .defaultAdvisors(SimpleLoggerAdvisor())<br>    .build()</pre><p>Finally, add the /chat/ask endpoint:</p><pre>@PostMapping(&quot;/chat/ask&quot;)<br>fun chatAsk(@RequestBody request: ChatRequest): String? {<br>    val promptTemplate = PromptTemplate(<br>        &quot;&quot;&quot;<br>        {query}.<br>        Please provide a concise answer based on the &quot;Kotlin standard library&quot; documentation.<br>        &quot;&quot;&quot;.trimIndent()<br>    )</pre><pre>    val prompt: Prompt = promptTemplate.create(mapOf(&quot;query&quot; to request.query))</pre><pre>    val retrievalAdvisor = QuestionAnswerAdvisor.builder(vectorStore)<br>        .searchRequest(<br>            SearchRequest.builder()<br>                .similarityThreshold(0.7)<br>                .topK(request.topK)<br>                .build()<br>        )<br>        .promptTemplate(promptTemplate)<br>        .build()</pre><pre>    val response = chatClient.prompt(prompt)<br>        .advisors(retrievalAdvisor)<br>        .call()<br>        .content()</pre><pre>    logger.info(&quot;Chat response generated for query: &#39;${request.query}&#39;&quot;)<br>    return response<br>}</pre><h3>What’s Happening Here?</h3><ol><li><strong>PromptTemplate</strong> — A reusable template with {query} as a placeholder. We substitute the real question at runtime.</li><li><strong>QuestionAnswerAdvisor</strong> — This is the RAG magic. It:</li></ol><ul><li>Takes the user’s question</li><li>Searches Qdrant for relevant documents (with similarityThreshold: 0.7 filtering out weak matches)</li><li>Injects those documents into the prompt as context <em>before</em> sending to OpenAI</li></ul><ol><li><strong>chatClient.prompt().advisors().call().content()</strong> — Chains the prompt with the RAG advisor, calls OpenAI, and returns the plain text response.</li></ol><p>The similarityThreshold(0.7) means only documents with ≥70% semantic similarity to the query are included. This prevents irrelevant context from polluting the answer.</p><h3>Step 8: Ask Your First Question!</h3><p>Run the app and test the chat endpoint:</p><pre>curl -X POST &quot;http://localhost:8080/kotlin/chat/ask&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;: &quot;What are the performance implications of using lazy sequences in Kotlin for large datasets?&quot;, &quot;topK&quot;: 3}&#39;</pre><p>You should get a response like:</p><pre>&quot;Lazy sequences in Kotlin process elements on-demand rather than eagerly,<br>which means they don&#39;t allocate intermediate collections. This makes them <br>significantly more memory-efficient for large datasets. When chaining <br>multiple operations (e.g., filter + map + take), sequences only process <br>each element through the full chain once, versus lists which create <br>a new collection at each step...&quot;</pre><p>That answer came from <em>your</em> Qdrant database, not just from OpenAI’s training data. That’s the power of RAG. 🎉</p><h3>Full Flow Recap</h3><p>Here’s the complete flow of what we built:</p><pre>User Question<br>     │<br>     ▼<br>PromptTemplate (formats the question)<br>     │<br>     ▼<br>QuestionAnswerAdvisor<br>     ├── Searches Qdrant for top-K similar docs<br>     └── Injects docs as context into the prompt<br>           │<br>           ▼<br>      OpenAI GPT-4o Mini<br>           │<br>           ▼<br>      Grounded Answer ✅</pre><h3>Production Tips</h3><p>Before you ship this to production, here are a few things to keep in mind:</p><p><strong>1. Secure your API key</strong></p><pre># Use environment variables instead of hardcoding<br>export SPRING_AI_OPENAI_API_KEY=sk-...</pre><p><strong>2. Don’t re-load documents every time</strong></p><p>The /load-docs endpoint should only be called once (or when docs change). Add an idempotency check or use a startup flag.</p><p><strong>3. Scale Qdrant</strong></p><p>For production, use <a href="https://cloud.qdrant.io/">Qdrant Cloud</a> instead of a local Docker container.</p><p><strong>4. Tune </strong><strong>similarityThreshold</strong></p><p>0.7 is a good starting point, but experiment based on your use case. Lower values return more results (but noisier); higher values are more selective.</p><p><strong>5. Monitor token usage</strong></p><p>gpt-4o-mini is cost-efficient, but with RAG you&#39;re sending documents + the query every time. Keep an eye on your OpenAI usage dashboard.</p><h3>What’s Next?</h3><p>You’ve built a fully functional RAG-powered app! Here’s what you could explore next:</p><ul><li><strong>Load your own docs</strong> — Replace Kotlin docs with your company wiki, product manuals, or any Markdown content</li><li><strong>Add streaming responses</strong> — Use .stream() instead of .call() for real-time token streaming</li><li><strong>Try other LLMs</strong> — Spring AI supports Anthropic Claude, Google Gemini, Azure OpenAI, and more with minimal config changes</li><li><strong>Explore Koog</strong> — JetBrains’ new Kotlin-native agent framework for building more complex multi-step AI workflows</li><li><strong>Add conversation history</strong> — Store previous messages and pass them to maintain context across turns</li></ul><h3>📦 Resources</h3><ul><li><a href="https://github.com/Kotlin/Kotlin-AI-Examples/tree/master/projects/spring-ai/springAI-demo">Complete project on GitHub</a></li><li><a href="https://github.com/Kotlin/Kotlin-AI-Examples">Kotlin AI Examples Repository</a></li><li><a href="https://spring.io/projects/spring-ai">Official Spring AI Docs</a></li><li><a href="https://qdrant.tech/documentation/">Qdrant Docs</a></li><li><a href="https://github.com/JetBrains/koog">Koog -Kotlin AI Agent Framework</a></li></ul><p>If you found this helpful, give it a clap 👏 and share it with a fellow Kotlin dev! Have questions or improvements? Drop them in the comments.I’d love to hear what you’re building.</p><p>Happy coding! 🦋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=284243f2cf79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Spaghetti to Structure: Migrating to a Modular Monolith with Spring Modulith and IntelliJ IDEA]]></title>
            <link>https://medium.com/@rishinduyohan/from-spaghetti-to-structure-migrating-to-a-modular-monolith-with-spring-modulith-and-intellij-idea-bc7d6b1c91f5?source=rss-c6aab50a37fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc7d6b1c91f5</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rishindu yohan]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 12:58:45 GMT</pubDate>
            <atom:updated>2026-02-26T12:58:45.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRQrs0UMpfBEWqPaKEmeOA.png" /></figure><p><em>Stop choosing between messy monolith and complex microservices — there’s a better way.</em></p><h3>The Problem with the Way We’ve Been Building Monoliths</h3><p>If you’ve worked on a Spring Boot application for more than a year, you’ve probably stared at a project structure that looks something like this:</p><pre>bookstore<br>├── config<br>├── controllers<br>├── entities<br>├── exceptions<br>├── models<br>├── repositories<br>└── services</pre><p>This <strong>package-by-layer</strong> approach feels natural at first. But as the codebase grows, it becomes a nightmare. Everything is tangled together. A BookRepository lives next to an OrderRepository, even though books and orders are completely different concerns. You end up with services that reach into each other&#39;s guts, and before long, you have the classic big ball of mud.</p><p>The knee-jerk reaction is to go full microservices. But microservices bring their own complexity: distributed transactions, network latency, service discovery, deployment overhead, and debugging nightmares. For most teams, that’s trading one problem for three.</p><p>Enter the <strong>modular monolith</strong> — and Spring Modulith is here to make it a first-class citizen in the Spring ecosystem.</p><h3>What Is a Modular Monolith?</h3><p>A modular monolith is still a single deployable unit (no distributed systems complexity), but it’s organized around <strong>domain modules</strong> with enforced boundaries. Think of it as microservices living inside one process — with clear APIs between them, but none of the networking overhead.</p><p>Spring Modulith is the Spring project that brings this architecture to life. It:</p><ul><li>Detects your application modules automatically based on package structure</li><li>Enforces module boundaries at test time (and optionally at runtime)</li><li>Supports event-driven communication between modules</li><li>Integrates deeply with IntelliJ IDEA Ultimate for real-time feedback</li></ul><p>Let’s walk through migrating a bookstore application from a package-by-layer monolith to a modular monolith, step by step.</p><h3>Step 1: Restructure from Package-by-Layer to Package-by-Module</h3><p>The first step is to reorganize your packages around <strong>business capabilities</strong>, not technical roles.</p><p><strong>Before (package-by-layer):</strong></p><pre>com.example.bookstore<br>├── config/<br>├── controllers/<br>│   ├── BookController.java<br>│   ├── OrderController.java<br>│   └── InventoryController.java<br>├── entities/<br>│   ├── Book.java<br>│   ├── Order.java<br>│   └── InventoryItem.java<br>├── repositories/<br>│   ├── BookRepository.java<br>│   ├── OrderRepository.java<br>│   └── InventoryRepository.java<br>└── services/<br>    ├── BookService.java<br>    ├── OrderService.java<br>    └── InventoryService.java</pre><p><strong>After (package-by-module):</strong></p><pre>com.example.bookstore<br>├── catalog/<br>│   ├── BookController.java<br>│   ├── BookService.java<br>│   ├── Book.java<br>│   └── internal/<br>│       └── BookRepository.java<br>├── orders/<br>│   ├── OrderController.java<br>│   ├── OrderService.java<br>│   ├── Order.java<br>│   └── internal/<br>│       └── OrderRepository.java<br>└── inventory/<br>    ├── InventoryService.java<br>    └── internal/<br>        ├── InventoryItem.java<br>        └── InventoryRepository.java</pre><p>Each module owns everything related to its domain. The internal sub-package signals that the contents should not be accessed by other modules.</p><h3>Step 2: Add Spring Modulith Dependencies</h3><p>Add the Spring Modulith BOM and starter to your pom.xml:</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.modulith&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-modulith-bom&lt;/artifactId&gt;<br>            &lt;version&gt;1.3.0&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><pre>&lt;dependencies&gt;<br>    &lt;!-- Core Spring Modulith support --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.modulith&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-modulith-starter-core&lt;/artifactId&gt;<br>    &lt;/dependency&gt;</pre><pre>    &lt;!-- Test support --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.modulith&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-modulith-starter-test&lt;/artifactId&gt;<br>        &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;</pre><pre>    &lt;!-- Optional: for generating documentation --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.modulith&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-modulith-docs&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>Step 3: Annotate the Main Application Class</h3><p>Spring Modulith detects modules from the root package of the class annotated with @SpringBootApplication. You can optionally add @Modulithic to make modular intent explicit:</p><pre>package com.example.bookstore;</pre><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.modulith.Modulithic;</pre><pre>@SpringBootApplication<br>@Modulithic<br>public class BookstoreApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(BookstoreApplication.class, args);<br>    }<br>}</pre><p>Spring Modulith will now treat every direct sub-package of com.example.bookstore as an application module: catalog, orders, and inventory.</p><h3>Step 4: Write Your First Modularity Test</h3><p>This is where the magic happens. Add a single test to verify your module structure:</p><pre>package com.example.bookstore;</pre><pre>import org.junit.jupiter.api.Test;<br>import org.springframework.modulith.core.ApplicationModules;<br>import org.springframework.modulith.docs.Documenter;</pre><pre>class ModularityTest {</pre><pre>    ApplicationModules modules = ApplicationModules.of(BookstoreApplication.class);</pre><pre>    @Test<br>    void verifiesModularStructure() {<br>        modules.verify();<br>    }</pre><pre>    @Test<br>    void createModuleDocumentation() {<br>        new Documenter(modules)<br>            .writeDocumentation()<br>            .writeIndividualModulesAsPlantUml();<br>    }<br>}</pre><p>Run this test. If you have any boundary violations — say, OrderService directly calls BookRepository from the catalog.internal package — the test will fail with a clear explanation of what&#39;s wrong.</p><h3>Step 5: Define Module Public APIs</h3><p>Not everything in a module should be public. Spring Modulith treats <strong>top-level classes in the module root</strong> as the public API, while anything in sub-packages (especially internal/) is considered private.</p><p>Here’s how to define a clean public API for the catalog module:</p><pre>package com.example.bookstore.catalog;</pre><pre>// This class IS the public API of the catalog module<br>public class CatalogService {</pre><pre>    private final BookRepository bookRepository; // internal, only injected here</pre><pre>    public CatalogService(BookRepository bookRepository) {<br>        this.bookRepository = bookRepository;<br>    }</pre><pre>    public Book findBookById(Long id) {<br>        return bookRepository.findById(id)<br>            .orElseThrow(() -&gt; new BookNotFoundException(id));<br>    }</pre><pre>    public List&lt;Book&gt; findAllBooks() {<br>        return bookRepository.findAll();<br>    }<br>}</pre><pre>package com.example.bookstore.catalog.internal;</pre><pre>import org.springframework.data.jpa.repository.JpaRepository;</pre><pre>// This repository is INTERNAL — other modules cannot use it directly<br>interface BookRepository extends JpaRepository&lt;Book, Long&gt; {<br>}</pre><p>Now orders module code can use CatalogService, but it cannot reach into catalog.internal.BookRepository. Spring Modulith will catch this at test time.</p><h3>Step 6: Declare Explicit Module Dependencies</h3><p>You can make dependencies between modules explicit using @ApplicationModule:</p><pre>package com.example.bookstore.orders;</pre><pre>import org.springframework.modulith.ApplicationModule;</pre><pre>@ApplicationModule(allowedDependencies = &quot;catalog&quot;)<br>public class OrdersModule {<br>    // Signals that the orders module may only depend on catalog<br>    // Any accidental dependency on inventory will be caught<br>}</pre><p>This is powerful for enforcing architectural decisions as code. When a new developer accidentally adds a dependency on inventory from orders, the modularity test fails immediately — no architecture review meeting required.</p><h3>Step 7: Use Application Events for Loose Coupling</h3><p>Instead of having orders call inventory directly (tight coupling), use <strong>Spring Application Events</strong>:</p><h3>Define the event in the orders module:</h3><pre>package com.example.bookstore.orders;</pre><pre>// Event published when an order is placed<br>public record OrderPlaced(Long orderId, Long bookId, int quantity) {<br>}</pre><h3>Publish the event from OrderService:</h3><pre>package com.example.bookstore.orders;</pre><pre>import org.springframework.context.ApplicationEventPublisher;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;</pre><pre>@Service<br>public class OrderService {</pre><pre>    private final OrderRepository orderRepository;<br>    private final ApplicationEventPublisher eventPublisher;</pre><pre>    public OrderService(OrderRepository orderRepository,<br>                        ApplicationEventPublisher eventPublisher) {<br>        this.orderRepository = orderRepository;<br>        this.eventPublisher = eventPublisher;<br>    }</pre><pre>    @Transactional<br>    public Order placeOrder(Long bookId, int quantity) {<br>        Order order = new Order(bookId, quantity);<br>        orderRepository.save(order);</pre><pre>        // Publish event — inventory will react without orders knowing about it<br>        eventPublisher.publishEvent(new OrderPlaced(order.getId(), bookId, quantity));</pre><pre>        return order;<br>    }<br>}</pre><h3>Listen for the event in the inventory module:</h3><pre>package com.example.bookstore.inventory;</pre><pre>import com.example.bookstore.orders.OrderPlaced;<br>import org.springframework.modulith.events.ApplicationModuleListener;<br>import org.springframework.stereotype.Component;</pre><pre>@Component<br>public class InventoryManagement {</pre><pre>    private final InventoryRepository inventoryRepository;</pre><pre>    public InventoryManagement(InventoryRepository inventoryRepository) {<br>        this.inventoryRepository = inventoryRepository;<br>    }</pre><pre>    @ApplicationModuleListener<br>    void onOrderPlaced(OrderPlaced event) {<br>        inventoryRepository.decrementStock(event.bookId(), event.quantity());<br>    }<br>}</pre><p>The @ApplicationModuleListener annotation is Spring Modulith&#39;s way of saying &quot;this is a cross-module event listener.&quot; It handles transactionality and observability automatically.</p><p>Now orders doesn&#39;t know about inventory at all. The dependency graph is acyclic and clean.</p><h3>Step 8: Testing Modules in Isolation</h3><p>Spring Modulith lets you bootstrap and test a single module without loading the entire application context:</p><pre>package com.example.bookstore.orders;</pre><pre>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.modulith.test.ApplicationModuleTest;<br>import org.springframework.modulith.test.Scenario;</pre><pre>@ApplicationModuleTest<br>class OrderModuleTest {</pre><pre>    @Autowired<br>    OrderService orderService;</pre><pre>    @Test<br>    void placeOrderPublishesOrderPlacedEvent(Scenario scenario) {<br>        scenario.stimulate(() -&gt; orderService.placeOrder(42L, 2))<br>                .andWaitForEventOfType(OrderPlaced.class)<br>                .toArrive()<br>                .andVerify(event -&gt; {<br>                    assertThat(event.bookId()).isEqualTo(42L);<br>                    assertThat(event.quantity()).isEqualTo(2);<br>                });<br>    }<br>}</pre><p>@ApplicationModuleTest bootstraps only the orders module context — making tests significantly faster and more focused.</p><h3>How IntelliJ IDEA Makes This Effortless</h3><p>If you’re using <strong>IntelliJ IDEA Ultimate</strong>, the built-in Spring Modulith plugin gives you real-time feedback without running tests:</p><p><strong>Module Indicators</strong> — In the Project view, top-level modules are marked with a 🔒 green lock (public) and internal components with a 🔒 red lock (private), making the structure immediately visible.</p><p><strong>Boundary Violation Warnings</strong> — If you try to inject BookRepository (internal) into OrderService, IntelliJ will highlight it as a violation right in the editor, before you even run the tests.</p><p><strong>Dependency Autocompletion</strong> — When you type allowedDependencies = &quot;&quot;, IntelliJ autocompletes with the names of available modules in your project.</p><p><strong>Quick-fixes</strong> — If a violation is detected, IntelliJ suggests a quick-fix: either create an event, extract a public API method, or create a @NamedInterface.</p><p><strong>Module Structure View</strong> — Select your @SpringBootApplication class and press Alt+7 to see a dedicated Modules tree showing every module, its allowed dependencies, and named interfaces.</p><h3>Named Interfaces: Sharing Specific Types Across Modules</h3><p>Sometimes you need to share a specific type — like a DTO or an event — between modules without exposing everything. Use @NamedInterface to carve out specific packages as part of the public API:</p><pre>// File: src/main/java/com/example/bookstore/catalog/events/package-info.java</pre><pre>@org.springframework.modulith.NamedInterface(&quot;events&quot;)<br>package com.example.bookstore.catalog.events;</pre><p>Now only the catalog.events sub-package is reachable by other modules. Everything else in catalog.internal remains locked.</p><p>Other modules can then declare a dependency on this named interface:</p><pre>@ApplicationModule(allowedDependencies = &quot;catalog::events&quot;)<br>package com.example.bookstore.orders;</pre><h3>Generating Architecture Documentation</h3><p>Spring Modulith can automatically generate PlantUML diagrams and Asciidoc documentation of your module structure:</p><pre>@Test<br>void writeDocumentation() {<br>    var modules = ApplicationModules.of(BookstoreApplication.class);<br>    new Documenter(modules)<br>        .writeModulesAsPlantUml()<br>        .writeIndividualModulesAsPlantUml()<br>        .writeDocumentation();<br>}</pre><p>This generates living documentation that always reflects the actual code structure — no more outdated architecture diagrams.</p><h3>Migration Strategy: Don’t Rewrite, Refactor Incrementally</h3><p>You don’t need to do this all at once. Here’s a pragmatic approach:</p><ol><li><strong>Start with one module</strong> — Pick the most isolated domain (e.g., catalog) and refactor it to package-by-module first.</li><li><strong>Add Spring Modulith and the modularity test</strong> — Let the test tell you what’s broken.</li><li><strong>Fix violations one by one</strong> — Use IntelliJ IDEA’s inspections to guide you. Replace direct inter-module service calls with events where coupling is the problem, or expose a proper public API where direct calls make sense.</li><li><strong>Repeat module by module</strong> — Once catalog is clean, move to orders, then inventory.</li><li><strong>Add </strong><strong>allowedDependencies</strong> — Once the structure stabilizes, lock it down explicitly.</li></ol><h3>Summary</h3><p>Spring Modulith gives you the structure of microservices with the simplicity of a monolith. The key takeaways are:</p><ul><li><strong>Organize by feature, not by layer</strong> — package-by-module makes domain boundaries visible.</li><li><strong>Let the tools enforce the rules</strong> — ModularityTest catches violations before they reach production.</li><li><strong>Use events for cross-module side effects</strong> — keep modules loosely coupled and independently testable.</li><li><strong>IntelliJ IDEA Ultimate is your best friend here</strong> — real-time inspections, module indicators, and quick-fixes make modular thinking part of your daily workflow.</li><li><strong>Migrate incrementally</strong> — you don’t need a big bang rewrite. Start with one module and build from there.</li></ul><p>The modular monolith isn’t a compromise. For most teams building domain-rich applications, it’s the right architecture and Spring Modulith makes it the easy choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc7d6b1c91f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Transaction API (JTA) ගැන සරලව: A Complete Guide]]></title>
            <link>https://medium.com/@rishinduyohan/java-transaction-api-jta-%E0%B6%9C%E0%B7%90%E0%B6%B1-%E0%B7%83%E0%B6%BB%E0%B6%BD%E0%B7%80-a-complete-guide-fbc92a210622?source=rss-c6aab50a37fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbc92a210622</guid>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rishindu yohan]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 11:18:42 GMT</pubDate>
            <atom:updated>2025-11-22T11:20:29.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn1h7esDfdwktVAJ51uqfA.jpeg" /><figcaption>cover page</figcaption></figure><p>Software development වලදී, විශේෂයෙන්ම Enterprise applications හදනකොට Data Consistency කියන එක &quot;Top Priority&quot; දෙයක්. Database එකකට data save කරනකොට errors ආවොත් මොකද වෙන්නේ? system එක crash වුනොත් data වලට මොකද වෙන්නේ? අන්න එතනදී තමයි Transactions සහ JTA (Java Transaction API) අපිට උදව් වෙන්නේ.<br>අපි බලමු ඇත්තටම මොකක්ද මේ JTA කියන්නේ සහ ඇයි software engineers ලට මේක වැදගත් වෙන්නේ කියලා.</p><h3>මුලින්ම, මොකක්ද මේ &quot;Transaction&quot; එකක් කියන්නේ?</h3><p>සරලවම කිව්වොත්, Transaction එකක් කියන්නේ &quot;Logical Unit of Work&quot; එකක්. ඒ කියන්නේ වැඩ ගොඩක් එකතුවෙලා හැදෙන තනි process එකක්.<br>හොඳම උදාහරණය තමයි Bank Money Transfer එකක්.<br>ඔයා යාලුවෙක්ට රුපියල් 5000ක් යවනවා කියල හිතන්න. එතන පියවර (steps) දෙකක් තියෙනවා:</p><ol><li>ඔයාගේ ගිණුමෙන් 5000ක් අඩු වෙන්න ඕන (Debit).</li><li>යාලුවාගේ ගිණුමට 5000ක් එකතු වෙන්න ඕන (Credit).</li></ol><p>මේ steps දෙකම සාර්ථක වෙන්න ඕන. යම් හෙයකින් පලවෙනි step එක වෙලා (සල්ලි කැපිලා), දෙවෙනි step එකේදී error එකක් ආවොත් (සල්ලි වැටුනේ නැත්නම්), සම්පුර්ණ process එකම cancel වෙන්න ඕන. කලින් තිබ්බ විදියටම සල්ලි ආපහු ගිණුමට එන්න ඕන. මේකට තමයි &quot;All or Nothing&quot; කියන්නේ.</p><p>Technology පැත්තෙන් ගත්තම Transaction එකක ප්‍රධාන ලක්ෂණ 4ක් තියෙනවා (ACID Properties):</p><ol><li>Atomicity: වැඩේ සම්පුර්ණ වෙන්න ඕන, නැත්තම් මුකුත් නොවී තියෙන්න ඕන.</li><li>Consistency: Transaction එකට කලින් සහ පස්සේ data valid වෙන්න ඕන.</li><li>Isolation: එක වෙලාවේ transactions ගොඩක් run වුනත්, එකකින් අනිකට බාධාවක් නොවී run වෙන්න ඕන.</li><li>Durability: වැඩේ ඉවර වුනාම data ස්ථිරවම save වෙන්න ඕන (Power fail වුනත් data නැති වෙන්න බෑ).</li></ol><h3>මොකක්ද JTA (Java Transaction API)?</h3><p>Java වල transactions handle කරන්න ප්‍රධාන ක්‍රම දෙකක් තියෙනවා:</p><ol><li>JDBC Transactions: මේක පාවිච්චි කරන්නේ තනි database එකක් එක්ක වැඩ කරනකොට. (Connection object එක හරහා commit සහ rollback කරන්නේ මේකෙන්).</li><li>JTA (Java Transaction API): මේක තමයි standard specification එක Distributed Transactions handle කරන්න.</li></ol><h4>JTA විශේෂ වෙන්නේ ඇයි?</h4><p>අපි හිතමු ඔයාගේ system එකේ Database දෙකක් තියෙනවා (e.g., MySQL සහ PostgreSQL) නැත්නම් Database එකයි Message Queue (e.g., RabbitMQ/Kafka) එකකුයි තියෙනවා කියලා.</p><p>Transaction එකක් ඇතුලේ මේ resources දෙකේම data update වෙන්න ඕන නම්, සාමාන්‍ය JDBC transaction එකකින් ඒක කරන්න බෑ. මොකද JDBC දන්නේ එක database connection එකක් ගැන විතරයි.</p><p>අන්න එතනදී තමයි JTA කරළියට එන්නේ. JTA වලට පුළුවන් resources කිහිපයක් (Databases, Message Queues) හරහා දුවන &quot;Global Transaction&quot; එකක් manage කරන්න.</p><h3>JTA වැඩ කරන්නේ කොහොමද? (The Mechanism)</h3><p>JTA වැඩ කරන්න ප්‍රධාන වශයෙන් Transaction Manager කෙනෙක් ඉන්න ඕන. මේක ගොඩක් වෙලාවට Application Server එකෙන් (like WildFly, WebLogic) හෝ Spring Boot වගේ frameworks වලින් provide කරනවා.</p><p>මේකේදී පාවිච්චි වෙන main protocol එක තමයි Two-Phase Commit (2PC) protocol එක.</p><ul><li>Phase 1 (Prepare Phase): Transaction Manager ඔක්කොම databases (resources) වලින් අහනවා &quot;ඔයාලට මේ data save කරන්න පුලුවන්ද?&quot; කියලා.</li><li>Phase 2 (Commit Phase): ඔක්කොම resources &quot;Yes&quot; කිව්වොත් විතරක්, Manager කියනවා &quot;Okay, දැන් ඔක්කොම commit කරන්න&quot; කියලා. එක resource එකක් හරි &quot;බෑ&quot; කිව්වොත් (error එකක් ආවොත්), Manager කියනවා &quot;එහෙනම් ඔක්කොම rollback කරන්න&quot; කියලා.</li></ul><p>JTA කියන්නේ ගොඩක් powerful ඒ වගේම පොඩ්ඩක් complex mechanism එකක්. හැබැයි distributed systems හදනකොට data integrity තියාගන්න මේක නැතුවම බෑ.</p><h3>Spring Boot සහ JTA</h3><p>අපි අද කාලේ raw JTA code (UserTransaction interface එක) ලියන්නේ නෑ. Spring Boot පාවිච්චි කරනවා නම් වැඩේ හරිම ලේසියි.<br>Spring වල @Transactional annotation එක පාවිච්චි කරාම, Spring විසින් background එකේ transaction management එක බලාගන්නවා.</p><p>Example :</p><pre> @Service<br>public class BankService {<br><br>    @Autowired<br>    private AccountRepository accountRepository;<br><br>    @Autowired<br>    private AuditLogRepository auditLogRepository;<br><br>    // @Transactional දැම්මම මේ method එකේ වෙන හැම database operation එකක්ම<br>    // තනි unit එකක් විදියට වැඩ කරනවා.<br>    @Transactional<br>    public void transferMoney(Long fromId, Long toId, Double amount) {<br>        <br>        // 1. සල්ලි අඩු කරනවා<br>        Account fromAcc = accountRepository.findById(fromId).get();<br>        fromAcc.setBalance(fromAcc.getBalance() - amount);<br>        accountRepository.save(fromAcc);<br><br>        // 2. අපි හිතමු මෙතනදී මොකක් හරි Error එකක් ආවා කියලා (e.g., Exception)<br>        if (amount &gt; 100000) {<br>            throw new RuntimeException(&quot;Limit Exceeded!&quot;);<br>        }<br><br>        // 3. සල්ලි එකතු කරනවා<br>        Account toAcc = accountRepository.findById(toId).get();<br>        toAcc.setBalance(toAcc.getBalance() + amount);<br>        accountRepository.save(toAcc);<br>        <br>        // Transaction එක ඇතුලේ Exception එකක් ආපු ගමන්, <br>        // Spring විසින් කලින් කරපු &quot;save&quot; එක (step 1) Rollback කරනවා.<br>        // ඒ කියන්නේ සල්ලි කැපෙන්නේ නෑ.<br>    }<br>}<br><br></pre><p>Spring Boot වලදී normal JPA/Hibernate පාවිච්චි කරනකොට default තියෙන්නේ Local Transaction Manager එකක්. හැබැයි ඔයාට Database දෙකක් එක්ක වැඩ කරන්න (Distributed Transaction) ඕන නම්, Atomikos හෝ Bitronix වගේ JTA implementation එකක් dependency එකක් විදියට add කරගන්න වෙනවා.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbc92a210622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics vs. Polymorphism in Java. What is the best ? ]]></title>
            <link>https://medium.com/@rishinduyohan/generics-vs-polymorphism-in-java-what-is-the-best-342da202c0c7?source=rss-c6aab50a37fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/342da202c0c7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rishindu yohan]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 18:43:03 GMT</pubDate>
            <atom:updated>2025-08-06T18:43:03.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1QHsokTU9ZOXd0B0k6G3Q.jpeg" /><figcaption>Generics vs. Polymorphism</figcaption></figure><h3>Generics vs. Polymorphism in Java. What is the best ?</h3><p>Java is a versatile programming language that supports both generics and polymorphism, two key concepts in object-oriented programming. While both serve to enhance code flexibility and reusability, they do so in different ways. This comparison aims to shed light on the distinctions and use cases for each.</p><h3>🧩 Generics 🧩</h3><p>Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. This provides a way to implement algorithms and data structures in a type-safe manner.</p><p>Here are some key features and benefits of generics:</p><p>1. <strong><em>Type Safety:</em></strong> By using generics, you can catch type-related errors at compile time rather than runtime. This means fewer bugs and exceptions when the code is executed.</p><p>2. <strong><em>Code Reusability</em>:</strong> Generics allow you to create a single method or class that operates on different data types without duplicating code. For example, a generic `List&lt;T&gt;` class can store any type of object.</p><p>3. <strong><em>Improved Readability</em></strong><em>:</em> Code using generics can be easier to read, as it clearly indicates what type of data structures are being used, reducing the need for casting.</p><pre><br>import java.util.ArrayList;<br>import java.util.List; public class GenericExample {<br>    public static &lt;T&gt; void printList(List&lt;T&gt; list) {<br>        for (T item : list) {<br>            System.out.println(item);<br>        }<br>    }<br>}</pre><h3>🎭 Polymorphism 🎭</h3><p>Polymorphism, on the other hand, is a fundamental concept in object-oriented programming that allows methods to do different things based on the object it is acting upon. It can be achieved through method overriding and method overloading.</p><p>1. <strong><em>Method Overriding</em>:</strong> Subclasses can provide a specific implementation of a method that is already defined in their superclass, allowing for dynamic method dispatch.</p><p>2. <strong><em>Method Overloading</em></strong>: You can create multiple methods with the same name but different parameters, which allows for methods to be called based on the arguments passed.</p><p>3. <strong><em>Flexibility</em></strong>: Polymorphism allows for design patterns that can simplify code and make it easier to extend and maintain.</p><pre><br>class Animal {<br>    void sound() {<br>        System.out.println(&quot;Animal makes a sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {<br>    void sound() {<br>        System.out.println(&quot;Bark&quot;);<br>    }<br>}</pre><pre>class Cat extends Animal {<br>    void sound() {<br>        System.out.println(&quot;Meow&quot;);<br>    }<br>}</pre><h3><strong>Key Differences</strong></h3><ul><li><strong><em>Purpose</em></strong>: Generics focus on type safety and code reusability, while polymorphism emphasizes flexibility and dynamic method resolution.</li><li><strong><em>Implementation</em></strong>: Generics are implemented at the class or method level, whereas polymorphism is achieved through class inheritance and method definitions.</li><li><strong><em>Use Cases</em></strong><em>:</em> Use generics when you need to work with various types without sacrificing type safety; use polymorphism when you want to define methods in a way that they can be overridden and utilize the appropriate class implementation at runtime.</li></ul><h3>My Conclusion</h3><blockquote>“Both generics and polymorphism are essential tools in a Java developer’s toolkit. Choosing between them largely depends on the specific needs of your program.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342da202c0c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference Between Stack and Queue Data Structures]]></title>
            <link>https://medium.com/@rishinduyohan/difference-between-stack-and-queue-data-structures-08e139493489?source=rss-c6aab50a37fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/08e139493489</guid>
            <dc:creator><![CDATA[Rishindu yohan]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 06:05:50 GMT</pubDate>
            <atom:updated>2025-07-10T06:05:50.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*yAyoFW0E-saBfk4nBoKbzA.png" /></figure><p>July 10, 2025</p><p>අද අපි කතා කරන්න යන්නෙ Stack Data Structure එකෙයි Queue Data Structure එකෙයි තියන main differences මොනවද? මේවා Real — world එකේදි use වෙන්නෙ කොහොමද කියන එක ගැන.</p><h3>Stack</h3><p>Stack Data Structure එක කියන්නෙ හරියට නිකන් data එකතු උන අට්ටියක් (🥞) වගේ Structure එකක්. ඒ කියන්නෙ අපි මුලින්ම දාන data එක තමා stack එකේ අන්තිමටම එකතු වෙන්නෙ.ඒ වගේම තමයි අපි අන්තිමටම දාන data එක තමයි stack එකේ මුලින්ම add වෙන්නෙ. මෙය <strong><em>Last In First Out (LIFO) or First In Last Out (FILO) system</em></strong> එකක් විදියට හදුන්වනවා. ඒ කියන්නේ, stack එකට අන්තිමට දාන data එක තමයි මුලින්ම ඉවත් කරන data (Top data) එක වෙන්නේ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uWhEURFMIDkxfIUY" /><figcaption>Stack Data Structure</figcaption></figure><h3>Stack එකේ Basic Operation 4ක් තියෙනවා.</h3><ol><li>push(item) — අලුත් data එකක් Stack එකට add කරනවා.</li><li>pop() — Stack එකේ ඉහලම තියෙන data එක remove කරනවා.</li><li>peek() හෝ top() — ඉහලම තියෙන data එක බලනවා, ඒත් remove කරන්නෙ නැහැ.</li><li>isEmpty() — Stack එක හිස්ද කියලා පරීක්ෂා කරනවා.</li></ol><h3>Queue</h3><p>Queue Data Structure කියන්නෙ Line (🧍🧍🧍) එකක් වගේ structure එකක්. මේක <em>First In First Out (FIFO) </em>system එකකට අයත්. ඒ කියන්නෙ queue එකට අපි data දානකොට මුලින්ම දාපු data එකම මුලින්ම remove වෙනවා.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*LPRJuMsYF9157fRj" /><figcaption>Queue Data Structure</figcaption></figure><h3>Queue එකෙත් Basic Operation 4ක් තියෙනවා.</h3><ol><li>enqueue() — Queue එකට data එකක් එකතු කරනවා</li><li>dequeue() — Queue එකේ මුල් data එක ඉවත් කරනවා</li><li>peek() -මුලින්ම තියෙන data එක බලනවා, ඒත් remove කරන්නෙ නැහැ.</li><li>isEmpty() — Queue එක හිස්ද කියලා පරීක්ෂා කරනවා</li></ol><p>අනික් operations ගොඩක් ඒවා Stack එකෙයි Queue එකෙයි සමානයි. දෙකේම array එකේ pointer එක විදිහට තියාගන්නෙ nextIndex එක. array එකට data දාන්න, data remove කරන්න මේ සේරටම use කරන්නෙ nextIndex එක.</p><h3>Difference Between Stack and Queue.</h3><p>Queue එකෙයි Stack ඒකෙයි තියන ප්රධානම වෙනස්කමක් වෙන්නෙ data print කරන method එක.</p><p>Stack එකේ data print කරනකොට array එකේ අන්තිමටම තියන data එක තමයි මුලින්ම print වෙන්නෙ. ඒ කියන්නෙ Stack එකට අපි අන්තිමටම දාන data එක තමයි මුලින්ම print වෙන්නෙ. array එකේ nextIndex-1 වලින් අපිට Stack එකේ අන්තිමට තියන data එක print කරගන්න පුලුවන්.</p><pre>public void printStack(){<br>	System.out.print(&quot;[&quot;);<br>	for (int i = nextIndex-1; i&gt;=0; i--){<br>		System.out.print(dataArray[i]+&quot;, &quot;);<br>	}<br>	System.out.println(nextIndex==0 ? &quot;empty]&quot;:&quot;\b\b]&quot;);<br>}</pre><p>Queue එකේ data print කරනකොට සාමාන්ය array එකක් print කරනව වගේම print කරගන්න පුලුවන්. හැබැයි Queue එකට අපි මුලින්ම දාන data එක මුලින්ම print කරගන්න පුලුවන් වෙන්න ඕනි. ඒ කියන්නෙ array එකේ array[0] එක තමයි මුලින්ම print වෙන්න ඕනි.</p><pre>public void printQueue(){<br>	System.out.print(&quot;[&quot;);<br>	for (int i = 0; i&lt;nextIndex; i++){<br>		System.out.print(dataArray[i]+&quot;, &quot;);<br>	}<br>	System.out.println(nextIndex==0 ? &quot;empty]&quot;:&quot;\b\b]&quot;);<br>}</pre><p>Satck එකෙයි Queue එකෙයි තියන අනික් main differences ලෙස,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*cFGF2kAQ0UFEz6tD" /><figcaption>difference between stack and queue</figcaption></figure><p>Stack සහ Queue කියන්නේ ද්විතීයක data structures දෙකක් වන අතර, දත්ත හැසිරවීමේ ක්රමවේදය අනුව එකිනෙකෙන් වෙනස් වෙනවා. Stack එකක් තුළ දත්ත හැසිරවෙන්නේ Last In First Out (LIFO) ක්රමයටය. මෙහිදී අන්තිමට දමන දත්තය මුලින්ම ඉවත් වේ. Queue එකක් තුළ දත්ත හැසිරවෙන්නේ First In First Out (FIFO) ක්රමයටය. මෙහිදී මුලින්ම දමන දත්තය මුලින්ම ඉවත් වේ. මෙම දෙකම programming, algorithm වලදි ඉතා වැදගත් වේ.</p><p>Stack Data Structure එක real-world system වලදි use කරන ආකාර ලෙස, <strong>Programming languages වල Function Calls track කරන්න, Undo/Redo functionalities </strong>(word, photoshop වගේ software වල), <strong>Web browser වල Back/Forward history, Expression evaluation</strong> (උදා: postfix, infix), <strong>Syntax parsing</strong> (Compiler වලදි) වගේ දේවල් වලට use කරනවා.</p><p>Queue Data Structure එක real-world system වලදි use කරන ආකාර ලෙස, Print <strong>Queue Management, Customer Service Ticket Systems, CPU Task Scheduling, Messaging Services </strong>(e.g., WhatsApp message queue) වගේ <strong>systematic data flow</strong> එකක් maintain කරන්න හොඳම data structure එකක් විදිහට හදුන්වන්න පුලුවන්.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08e139493489" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>