<?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 Samitha_ Senevirathne on Medium]]></title>
        <description><![CDATA[Stories by Samitha_ Senevirathne on Medium]]></description>
        <link>https://medium.com/@samithadilshan59?source=rss-44ff7c80d445------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yWV2T62vZz7YCOhcg8CY5Q.jpeg</url>
            <title>Stories by Samitha_ Senevirathne on Medium</title>
            <link>https://medium.com/@samithadilshan59?source=rss-44ff7c80d445------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 02:48:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samithadilshan59/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[Understanding Linux Process Status: Running, Interruptible Sleep, Stopped, Zombie, Orphan, and…]]></title>
            <link>https://medium.com/@samithadilshan59/understanding-linux-process-status-running-interruptible-sleep-stopped-zombie-orphan-and-ee1a0cfb06b2?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1a0cfb06b2</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 03:14:09 GMT</pubDate>
            <atom:updated>2025-12-22T03:14:09.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Linux Process Status: Running, Interruptible Sleep, Stopped, Zombie, Orphan, and Reaping Explained with Examples</h3><p>Linux is a multitasking operating system that manages various processes simultaneously. Each process has a status describing what it is currently doing. Understanding these statuses helps us monitor and debug processes effectively. This article covers common Linux process states such as Running, Interruptible Sleep, Stopped, Zombie, and Orphan, and explains how the system “reaps” terminated processes. You’ll also see simple command snippets and code examples to observe these states practically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOatfEgjQ8VmGeag-NiV9g.png" /></figure><h4>What Is a Linux Process Status?</h4><p>When you look at processes on Linux using commands like ‘ps’ or ‘top’ , each process has a state usually shown as a single character:</p><ul><li>Running (R)</li><li>Interruptible Sleep (S)</li><li>Stopped (T)</li><li>Zombie (Z)</li><li>Orphan</li></ul><p>These statuses tell you if a process is executing, waiting, stopped, or has finished but not cleaned up yet.</p><h4>Running (R)</h4><p>A Running process means it is currently executing on the CPU or is ready to run.</p><h4>Interruptible Sleep (S)</h4><p>Processes in Interruptible Sleep are waiting for input or some resource, but can be woken by signals.</p><p>For instance, the ‘sleep’ command goes into this state because it waits for a timer, and meanwhile, it’s sleeping &quot;interruptibly.&quot;</p><h4>Stopped (T)</h4><p>A process is stopped when it has been paused, often by a user signal (<strong><em>SIGSTOP</em></strong>) or debugger. This pauses the execution entirely until it receives a signal to continue (<strong><em>SIGCONT</em></strong>).</p><p><strong>How to see it:</strong> Run any command (like top ), then press Ctrl + Z.</p><h4>Zombie (Z)</h4><p>A zombie process happens when the child process in Linux finishes its work and exits, but its parent process does not properly acknowledge this termination.</p><p>When the child completes, it sends (SIGCHLD) signal to its parent and waits for the parent to call a function Wait() to collect the child’s exit status.</p><p>If the parent doesn’t call ‘wait()’, the dead child process remains in the process table as a ‘Zombie’. Which means the system occupies a small amount of memory.</p><p>If the parent calls the wait(), the zombie is cleaned and removed from the entire process list.</p><p>Let&#39;s see some practical examples:</p><pre>#include &lt;unistd.h&gt;<br>#include &lt;stdlib.h&gt;<br>int main() {<br>    if (fork() == 0) {<br>        exit(0);   // child exits immediately → zombie<br>    }<br>    sleep(100);   // parent never reaps<br>}</pre><p>Compile and run :</p><pre>gcc zombie.c -o zombie<br>./zombie &amp;<br>ps -ef | grep defunct</pre><p>Outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*c4D-OSmlvmP6AamosV5dVw.png" /></figure><ul><li>ps -ef | grep defunct and saw a process listed as [zombie] &lt;defunct&gt; with <strong>PID 1374</strong>.</li><li>Its <strong>PPID is 1373</strong>, which means it still has a parent process alive.</li><li>The process is in a <strong>defunct state</strong> because it has exited, but the parent has <strong>not collected its exit status</strong> yet.</li></ul><p>This shows that the child process remains in the <strong>process table</strong> until the parent reaps it, which is why it appears as a zombie.</p><h4>Orphan Process</h4><p>An orphan process in Linux happens when a child process is still running, but its parent process has finished or terminated unexpectedly. Since every process normally has a parent that exits first, the child process becomes an ‘Orphan’.</p><p>The Linux kernel automatically detects orphan processes and immediately reassigns them to a special process called ‘Init’(Process ID 1)</p><p>The init process acts like a guardian parent that takes care of these orphaned processes by waiting for them to finish and cleaning up their resources properly.</p><pre>#include &lt;unistd.h&gt;<br>#include &lt;stdlib.h&gt;<br>int main() {<br>    if (fork() == 0) {<br>        sleep(5);   // child lives longer<br>        exit(0);<br>    }<br>    exit(0);         // parent exits immediately<br>}</pre><p>compile and run :</p><pre>gcc orphan.c -o orphan<br>./orphan<br>ps -ef | grep orphan</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*NW_R-dMGDwujcyedwoE0fQ.png" /></figure><ul><li>ran ps -ef | grep orphan and that the child process <strong>PID 1641</strong> was still running even after its parent exited.</li><li>The <strong>PPID of the child changed to 1</strong>, which means <strong>systemd (PID 1) adopted the child</strong>.</li><li>This shows that when a parent process exits before its child, the kernel automatically <strong>re-parents the orphan to PID 1</strong>.</li></ul><p>The adoption ensures that the child process will eventually be cleaned up properly when it finishes execution.</p><h4>Reaping Processes</h4><p>In Linux, reaping refers to a process where the operating system cleans up and removes child processes that have finished executing (terminated) but still have an entry in the process table as ‘zombies’ when a process ends. Its end is its existence status to its parent.</p><p>The parent then calls a system function (usually wait() ) to “reap” the child. Meaning it reads this exit status and removes the child’s record from the process table to free up system resources.</p><p>Without reaping, these finished child processes remain as ‘Zombies’.</p><pre>#include &lt;signal.h&gt;<br>#include &lt;sys/wait.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;stdio.h&gt;<br><br>void handler(int sig) {<br>    while (waitpid(-1, NULL, WNOHANG) &gt; 0) {<br>        printf(&quot;Reaped a child\n&quot;);<br>    }<br>}<br><br>int main() {<br>    signal(SIGCHLD, handler);<br><br>    for (int i = 0; i &lt; 5; i++) {<br>        if (fork() == 0) {<br>            sleep(1);<br>            return 0;<br>        }<br>    }<br><br>    sleep(10);<br>}</pre><p>command and run ;</p><pre>gcc reaper.c -o reaper<br>./reaper</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*OQjnpYBYpXjpM074Iz47MQ.png" /></figure><p>multiple lines “Reaped a child”, each corresponding to a child process exiting.</p><h4><strong>Summary:</strong></h4><p>Linux process statuses tell you what a process is doing at any moment:</p><ul><li>Running (R): The process is working or ready to work.</li><li>Interruptible Sleep (S): The process is waiting but can wake up if needed.</li><li>Stopped (T): The process is paused, usually by a signal or user action.</li><li>Zombie (Z): The process has finished but is still listed because its parent hasn’t checked its exit status yet.</li><li>Orphan: The process lost its parent, so it gets taken care of by the special ‘Init’ process.</li></ul><p>Learning to check these statuses with simple commands and examples helps you understand and fix issues with Linux processes better.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1a0cfb06b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Type docker run? A Deep Dive into the Linux Kernel]]></title>
            <link>https://medium.com/@samithadilshan59/what-really-happens-when-you-type-docker-run-a-deep-dive-into-the-linux-kernel-a310b93512ec?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/a310b93512ec</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 02:48:22 GMT</pubDate>
            <atom:updated>2025-11-10T02:48:22.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding containers, namespaces, and the mysteries of data persistence</p><h3>Introduction: The container vs VM confusion</h3><p>Many people believe that Docker containers are just “lightweight virtual machines”.But this little misconception leads to confusion about how containers actually work at the kernel level.</p><p>Let&#39;s dive deep into these fundamental concepts through this article</p><p>Actual Architecture of the VM and Docker container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*Xhuc5J-3PtOqOwrF8Nb0Hw.png" /><figcaption>Vm(Virtual Machine Architecture)</figcaption></figure><p><strong>Virtual Machines:</strong></p><ul><li>Each VM has its own complete kernel</li><li>Full OS installation required for each VM</li><li>Heavy resource use(RAM, CPU,storage)</li></ul><p>Slower boot times (minutes)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*IU3bWTGnLNkhlvEM5xUKpg.png" /><figcaption>Docker Container</figcaption></figure><p><strong>Docker Container:</strong></p><ul><li>Share the host’s kernel</li><li>Lightweight &amp; efficient</li><li>Instant startup (milliseconds)</li><li>Process-level isolation only</li></ul><h4>Proving Containers Share the Kernel</h4><p>Before diving into how containers work, it&#39;s essential to verify that containers actually share the host kernel.</p><p>Let&#39;s see a simple test to demonstrate this:</p><pre># Check kernel version on host<br> $ uname -r<br> 6.14.0-1015-aws<br><br> # Check kernel version in Ubuntu container<br> $ docker run ubuntu uname -r<br> 6.14.0-1015-aws<br><br> # Check kernel version in Alpine container<br> $ docker run alpine uname -r<br> 6.14.0-1015-aws</pre><p>All three show identical kernel versions. Same kernel version, down to the exact patch number.</p><p>So this is the crucial proof point. Ubuntu and Alpine are completely different Linux distributions with different package managers, different default shells, and different system utilities. Yet they’re running on the same kernel.</p><p>A virtual machine would show different kernel versions because each VM boots its own kernel. But containers all use the host’s kernel.</p><h3>The Journey of “docker run” from command to running container</h3><p>So let&#39;s see what happened inside the kernel after giving the Docker run command</p><pre> docker run -it --name my-app ubuntu </pre><p>So after this command, it&#39;s not all about starting the container; the reality involves a complex chain of events within the kernel.</p><p>Let&#39;s break down each of these steps.</p><p><strong>Step 1: Docker CLI Sends an API Request</strong></p><p>When the command executes, the Docker CLI doesn’t actually start anything. It sends an HTTP request to the Docker daemon (dockerd) running in the background</p><p><strong>Step 2: Dockerd delegates to containerd</strong></p><p>Dockerd doesn’t actually create containers itself. It’s just the API server. Upon receiving the request, it immediately delegates to another process called containerd.</p><p>process tree shows:</p><pre> $ pstree -p | grep docker<br> dockerd(450)───containerd(890)</pre><p>containerd is the actual container lifecycle manager, handling starting, stopping, and managing containers.</p><p>Then containerd invokes another component: runc.</p><p><strong>Step 3: runc Makes the Magic System Call</strong></p><p>This is where the process becomes very important. Runc is a specialized program with one primary job communicate with the Linux kernel to create containers.</p><p>Using strace to observe:</p><pre> $ strace -e clone docker run ubuntu echo &quot;test&quot;</pre><pre> clone(child_stack=NULL, <br>      flags=CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWNET|<br>            CLONE_NEWIPC|CLONE_NEWUTS|CLONE_NEWCGROUP,<br> ...)<br></pre><p>Those CLONE_NEW* flags instruct the kernel:</p><p>“Create a new process, but also provide it with brand new namespaces for PID, networking, filesystem mounts, IPC, hostname, and cgroups.”</p><p>The clone() system call is a more advanced version of fork(). It gives developers <strong>more control</strong> over what the new process shares or separates from the parent.</p><p>For example, while fork() always creates a completely separate process, clone() can choose to share memory, file descriptors, or other resources depending on the flags provided.</p><p><strong>Step 4: Kernel Creates 7 Namespaces</strong></p><p>The kernel creates isolated universes:</p><ol><li><strong>PID-Process ID Namespace (CLONE_NEWPID)</strong></li></ol><ul><li>The process perceives itself as PID 1</li><li>Cannot see any other processes on the system</li></ul><p><strong>2. NET -Network Namespace (CLONE_NEWNET)</strong></p><ul><li>Receives its own network stack, routing tables, and firewall rules</li><li>Gets its own IP address</li></ul><p><strong>3. MNT -Mount Namespace (CLONE_NEWNS)</strong></p><ul><li>Own filesystem view and mount points</li></ul><p>4. UTS Namespace (CLONE_NEWUTS)</p><ul><li>Own hostname</li></ul><p><strong>5. IPC Namespace (CLONE_NEWIPC)</strong></p><ul><li>Isolated inter-process communication</li></ul><p><strong>6. User Namespace (CLONE_NEWUSER)</strong></p><ul><li>UID/GID mapping</li></ul><p><strong>7. Cgroup Namespace (CLONE_NEWCGROUP)</strong></p><ul><li>Isolated view of the cgroup tree</li><li>Process perceives itself at the root of the cgroup hierarchy</li></ul><pre>$ docker inspect --format &#39;{{.State.Pid}}&#39; mycontainer<br> 15234<br> $ ls -l /proc/15234/ns/<br> pid -&gt; pid:[4026532359]    # Unique namespace inode<br> net -&gt; net:[4026532361]    # Different from host<br> mnt -&gt; mnt:[4026532356]</pre><p>Different inode numbers = isolated namespaces.</p><p><strong>Step 6: Kernel Configures Cgroups</strong></p><p>Cgroups (short for Control Groups) are a Linux feature used to limit, monitor, and control how much CPU, memory, disk I/O, and other resources a group of processes can use.</p><p><strong>Step 7: Kernel Mounts OverlayFS</strong></p><p><strong>What is OverlayFS ?</strong></p><p>The kernel must provide the container with a filesystem. Docker uses OverlayFS, a “union” filesystem combining layers:</p><p><strong>LowerDir</strong>: Image layers (shared by all containers)</p><p><strong>UpperDir</strong>: Container changes (unique per container)</p><p><strong>MergedDir</strong>: What the container sees (union of both)</p><p>When the container reads a file, it comes from lowerdir. When it writes a file, it goes to upperdir. This enables 100 containers to share the same image while maintaining separate data.</p><p><strong>Step 8: The Container Process</strong></p><p>starts inside the isolated environment. Total time gets like Milliseconds.</p><p>No OS boot. No hardware initialization. Just namespace setup, cgroup config, filesystem mount, and process start.</p><h3>The Container Illusion -How Namespaces and Cgroups Work Together</h3><p>After understanding the boot process, containers reveal themselves as an illusion. The kernel makes a process believe it’s running in isolation, while actually sharing everything with the host.</p><p>The Namespace:” what you can see”</p><pre> $ docker run -dit --name demo ubuntu bash<br> $ docker exec -it demo bash<br> root@demo:/# echo $<br> 1    # Process appears as PID 1<br></pre><p>Inside the container, bash believes it’s PID 1.</p><p>But in the host:</p><pre>$ docker inspect - format &#39;{{.State.Pid}}&#39; demo <br>15234 <br>$ ps -ef | grep 15234<br> root 15234 15200 bash</pre><p>It’s actually PID 15234!</p><p>The same process has two PIDs:</p><ul><li>Inside the PID namespace: PID 1</li><li>Outside the namespace: PID 15234</li></ul><p>This is the namespace illusion. The kernel maintains the real PID (15234), but when the process queries “What’s the PID?”, the kernel responds with the namespace-specific answer: “PID 1.”</p><pre> # Inside container<br> root@demo:/# ps aux<br> USER  PID  CMD<br> root  1    bash<br> root  45   ps aux<br><br> # On host<br> $ ps aux <br> 347  </pre><p>The container sees only 2 processes. The host sees 347. Same kernel, different views. That’s namespace isolation.</p><p><strong>Testing Network Isolation</strong></p><pre># Inside container<br> root@demo:/# ip addr show eth0<br> inet 172.17.0.2/16<br><br> # On host<br> $ ip addr show eth0<br> inet 192.168.1.100/24<br></pre><p>Different IP addresses</p><p>The container has its own network stack, routing tables, and interfaces, completely isolated from the host’s network.</p><p>Both network stacks are managed by the same kernel. The kernel simply filters which network devices each process can access based on its network namespace.</p><p><strong>The Cgroup Enforcement: “What You Can Use”</strong></p><p>Namespaces answer “what can be seen,” but cgroups answer “what can be used.”</p><p>Testing with a CPU-limited container:</p><pre>$Docker run -dit --name limited-container --cpus=”0.5&quot; --memory=”256m” ubuntu</pre><p>Running a CPU-intensive process inside:</p><pre> // cpu_hog.js<br> while(true) { }  // Infinite loop attempting 100% CPU<br><br> $ docker exec limited node cpu_hog.js</pre><p>Monitoring on the host:</p><pre> $ docker stats limited<br> CONTAINER  CPU %    MEM USAGE<br> limited    <br>50.12%   10 MB</pre><p>Despite the process attempting to use 100% CPU, it remains capped at 50%!</p><pre> $ cat /sys/fs/cgroup/system.slice/docker-&lt;id&gt;.scope/cpu.stat<br> nr_periods 5420<br> nr_throttled 5280<br> throttled_usec 264000000</pre><p>Out of 5,420 CPU scheduling periods, the process was throttled 5,280 times. The kernel actively prevents exceeding the 50% CPU limit.</p><p>This demonstrates cgroup enforcement in action. The process can request 100% CPU, but the kernel scheduler enforces: “The limit is 50%.”</p><p>Now, let&#39;s see how these two pillars are working together to make the container illusion</p><p>Namespaces make the process believe it’s alone.</p><p>Cgroups ensure it doesn’t consume excessive resources.</p><p>Together, they create the illusion of a separate machine, while everything runs on the same kernel, sharing CPU, RAM, and hardware.</p><p><strong>The Kernel As Orchestrator</strong></p><p>The kernel’s remarkable capability, managing all of this for hundreds of containers. It maintains:</p><ul><li>Separate namespace mappings for each container</li><li>Separate cgroup hierarchies for each container</li><li>A single process table with real PIDs</li><li>A single CPU scheduler enforcing all cgroup limits</li></ul><h3><strong>Why Stop Preserves, Delete Destroys</strong></h3><p>Why does Docker stop preserving data, but docker rm deletes it?</p><p>Direct observation provides the answer:</p><p>Create a file :</p><pre>docker exec overlay-test bash -c “echo ‘this is writable data’&gt; /test.txt”</pre><p>Where does this file exist on the host? Container inspection reveals:</p><pre>$ docker inspect myapp | grep -A 10 GraphDriver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJyO1K7xh4MgTaK4xN_ZNQ.png" /></figure><p>This shows that the file exists on the host filesystem, in the container’s UpperDir.</p><pre>Container&#39;s View: /<br> │<br> ├─ /bin    (from LowerDir - Ubuntu image layer 1)<br> ├─ /usr    (from LowerDir - Ubuntu image layer 2)<br> ├─ /lib    (from LowerDir - Ubuntu image layer 3)<br> └─ /test.txt  (from UpperDir - container&#39;s writable layer)</pre><p><strong>The OverlayFS Structure</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*uQugiKXN7Dk4S-cnaWhr2Q.png" /></figure><p>The filesystem consists of three parts:</p><p><strong>LowerDir:</strong></p><ul><li>Contains base image files (e.g., /bin, /usr, /lib from Ubuntu).</li><li>Shared by many containers.</li><li>Read-only — cannot be modified.</li></ul><p><strong>UpperDir:</strong></p><ul><li>Container’s personal workspace</li><li>New or modified files are stored here.</li><li>Uses Copy-on-Write — only changed files are copied.</li><li>Deleted files are hidden (not removed from lower layer).</li></ul><p><strong>MergedDir:</strong></p><ul><li>What the container actually sees when you ls /.</li><li>Merged view of UpperDir + LowerDir.</li></ul><p>When a container reads an unmodified file, it comes from LowerDir. When it writes a file, it goes to UpperDir. This is called <strong>Copy-on-Write.</strong></p><p>Now let&#39;s see how the stopping and destroying comparison.</p><p><strong>Stopping the Container</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GjNqmsZGa75My4VqvWeDsg.png" /></figure><p>Results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3Pk1izIcqq9ABjOAYvBoQ.png" /></figure><p>This shows that the file remains!</p><p>When stopping a container, the kernel performs these operations:</p><ol><li>Sends SIGTERM to the container’s process (PID 15234)</li><li>Process exits gracefully</li><li>Namespaces are released (no longer in use)</li><li>Cgroups are cleaned up (process no longer consuming resources)</li><li>UpperDir remains on disk untouched</li></ol><p>The container is stopped, but all data in UpperDir is preserved. This enables restarting the container later to continue from the same state.</p><p><strong>Removing the container</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*cDkRAII267AWZ4-SfVn9Mg.png" /><figcaption>Remove docker container</figcaption></figure><p>Results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFS_ryzAsB8vyjY4gW1f5Q.png" /><figcaption>Removed from the file directory</figcaption></figure><p>The entire directory is gone!</p><p>When deleting a container, Docker removes:</p><ol><li>Container metadata (name, configuration, etc.)</li><li>Network resources (IP address released)</li><li>The entire UpperDir directory</li></ol><p>The test.txt file has been permanently deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmM9XJt7C65X710eQZUGBw.png" /></figure><p>Each container has its own UpperDir with its own changes. They all share the same LowerDir (image layers).</p><p>When Docker stops, processes are killed, namespaces released, cgroups cleaned</p><p>when Docker is removed, everything from stop, plus UpperDir is deleted.</p><p>The LowerDir (image layers) remains untouched. This explains why deleting all containers still allows immediate creation of new ones from the same image.</p><h4>Conclusion:</h4><p>After exploring how containers actually work, it’s clear they’re not some kind of magic or separate virtual machines; they’re just regular Linux processes running with extra kernel features.</p><p>When we use `docker run`, the Docker daemon hands things over to `containerd`, which uses `runc` to talk to the kernel. The kernel then creates isolated namespaces, sets up resource limits using cgroups, and mounts an OverlayFS combining image layers with a writable layer for changes. This setup makes containers lightweight yet powerful. Namespaces handle what a process can see, cgroups control how much it can use, and OverlayFS manages storage efficiently. That’s also why stopping a container only ends the process but keeps the writable layer, while removing it deletes everything above the base image.</p><p>In the end, containers are just smartly managed processes that give us isolation, control, and speed all built right on top of the Linux kernel.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a310b93512ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Network Drivers Explained in Simple Terms]]></title>
            <link>https://medium.com/@samithadilshan59/docker-network-drivers-explained-in-simple-terms-61812adecbd4?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/61812adecbd4</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 15:57:40 GMT</pubDate>
            <atom:updated>2025-11-09T15:57:40.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCOBbooRFLiZT0gpnN02qA.png" /></figure><h4>What is a Docker network?</h4><p>A Docker network driver is like a set of rules and tools telling Docker how to connect container networks together. It creates bridges or direct links between containers, the host, and external networks.</p><p>Docker has many network drivers, but the most common ones are:</p><ol><li>Default Bridge</li></ol><p>2. User-Defined Bridge</p><p>3. Host</p><p>4. MACVLAN</p><p>5. IPVLAN</p><p>Let’s understand each driver with simple explanations and sample commands.</p><p>to see the docker network list:</p><pre>docker network ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*7KmFsP8kSm4BySuqGftqbw.png" /></figure><h4>Default-bridge Network</h4><p>When you install Docker, it creates a pre-made network called ‘bridge’.If you run a container but don’t say anything about the network, Docker connects it to this bridge.This bridge is like a private switch on your computer. Containers connected here get their own IP addresses but cannot talk to your main network directly. To let outside world reach containers, you need to map ports manually.</p><p>It keeps containers isolated for security but lets them communicate by IP address inside the host machine. And also containers cannot use container names easily to find each other in this network you have to use IP addresses</p><p><strong>communication possibilities:</strong></p><p>Containers can communicate with each other using IP addresses.</p><p>Containers cannot directly reach the external network without ports mapping.</p><h4>User-Defined Bridge Network</h4><p>In this we create a our own bridge network by ourselves</p><p>you can create a user defined bridge using below command</p><pre>docker network create -d bridge mynew</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*x2EBxS0kGfKbvW6-aSWCYg.png" /></figure><p>When containers connect to this network, Docker creates DNS service discovery, meaning containers can find each other by their names, not just IP addresses. So this is isolated from other networks only can communicate containers in the same network.</p><p>Because of this in microservices ,its easy to build differant containers to talk each other using the names instead of the IP addresses.</p><p>Let’s see simple example command to run a container in user defined bridge</p><pre>docker network create -d bridge mynew<br><br>docker run -d -p 81:80 --network mynew --name my-service nginx<br>docker run -d -p 82:80 --network mynew --name my-service2 httpd<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*jep_9Y6ORSrsbwz9k3DusA.png" /></figure><pre>docker exec -it my-service <br>apt-get update <br>apt install iputils-ping<br>ping my-service2</pre><p>after above ping command you should see the ping work by container names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*iM6lHoAqKxd_WofHYa3ZdQ.png" /></figure><p><strong>Communication Possibilities:</strong></p><p>Full communication between containers in the same network using names or IPs.</p><h4>Host Network Driver</h4><p>Here, Containers do not get their own network namespace or IP. Instead, they use the host machine’s network directly. In here the Ports on the container are the same ports on the host, no port mapping needed.</p><p>This gives the container the best network performance because nothing is translated or routed through Docker.</p><p><strong>Communication possibilities:</strong></p><p>Containers can reach all devices on the host network.</p><h4>MACVLAN Network Driver</h4><p>MACVLAN is like giving each container its own network identity. Normally, containers share the host’s network using a bridge, but with MACVLAN, every container gets its own MAC address just like your phone or laptop has one.</p><p>This makes each container appear as a separate device on your local network. Docker connects the container’s network directly to your computer’s network interface (like eth0), so the container gets its own IP and MAC address. Because of this, other devices on the same network can see and communicate with the container as if it’s another real machine.</p><p>to create a MACVLAN network:</p><pre>docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 -o parent=eth0 my-macvlan                      </pre><p>in above command we do a subnet configuration which is define the range<strong> </strong>of IP addresses the macvlan network will use./24 means the subnet mask is 255.255.255.0, so the IP range is:</p><pre>192.168.1.1 ---&gt; 192.168.1.254</pre><p>Containers connected to this network will get IPs from that range.</p><p>and default gateway for the containers in this network is specifies by the gateway. It’s normally your router’s<strong> </strong>IP<strong> </strong>address (the device that connects your LAN to the internet).</p><p>So this is helpful if your application or your network environment requires unique MAC addresses for each container.</p><p>MACVLAN usually doesn’t work on Docker<strong> </strong>Desktop (Windows or macOS).<br> That’s because Docker Desktop actually runs inside a small virtual<strong> </strong>machine, not directly on your real computer.</p><p>So, it doesn’t have full access to your real network card (eth0).<br> Because of that, MACVLAN can’t connect properly to your local network, and you’ll often get errors or no internet connection inside the container.</p><h4>IPVLAN Network Driver</h4><p>IPVLAN is somewhat similar to MACVLAN. Containers share a MAC address with the host in certain modes but have unique IP addresses.</p><p>There are two modes of IPVLAN:</p><ol><li>Layer2 (L2) — In L2 mode, each container gets its own IP address and appears like a separate device on the same physical network as the host.</li><li>Layer3(L3) — In L3 mode, each container also gets its own unique IP address, but unlike L2, the containers don’t appear as separate devices on the physical network. Instead, they communicate through the host’s network stack using routing.</li></ol><p>The host acts like a gateway, and all container traffic goes through it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cr44v3d948RKjb6zCjscg.png" /></figure><p>Let’s see the comparison between default bridge network and user defined bridge network.</p><p><strong>Default bridge</strong></p><p>Automatically created by the docker.</p><p>Requires port mapping for external access.</p><p>Containers communication via ip addresses.</p><p><strong>User-Bridge Network</strong></p><p>Custom bridge network with DNS-based name — containers can communicate using names instead of IPs, making it perfect for microservices.</p><p>Let’s see the comparison between MACVLAN network and IPVLAN network.</p><p><strong>MACVLAN Network</strong></p><p>Gives each container a unique MAC and IP.</p><p><strong>IPVLAN Network</strong></p><p>IPVLAN gives each container its<strong> </strong>own<strong> </strong>IP<strong> </strong>only and shares host MAC.</p><p><strong>Conclusion</strong></p><p>Docker networking might look a bit confusing at first, but once you get the idea of what each driver does, it’s actually not that hard. The default<strong> </strong>bridge is perfect for small tests or simple setups. The user<strong>-</strong>defined<strong> </strong>bridge is really useful for microservices because containers can talk to each other easily using their names. The host<strong> </strong>network gives better performance, but it removes the isolation between the container and the host. The MACVLAN driver lets containers act like real devices on your network, but it usually doesn’t work on Docker Desktop. The IPVLAN driver is more advanced and works well for big or enterprise-level systems. So basically, each network type has its own job you just have to pick the one that fits your project best.</p><p>I hope this article helped you get a clear idea about how Docker network drivers work and when to use each one. Thank you !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61812adecbd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices: Key Deployment Patterns]]></title>
            <link>https://medium.com/@samithadilshan59/microservices-key-deployment-patterns-7ab1f399de4d?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab1f399de4d</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 07:18:23 GMT</pubDate>
            <atom:updated>2025-09-28T07:18:23.265Z</atom:updated>
            <content:encoded><![CDATA[<p>Microservices are a popular way to build modern applications. Instead of creating one big system, the application is divided into smaller, independent services. Each service can be built, deployed, and scaled on its own. This makes the system more flexible and reliable. However, the main challenge is finding the best way to deploy these services so they work smoothly together.</p><p>This is where deployment<strong> </strong>patterns come into play. In this article, we will explore some of the most widely used deployment patterns in microservices.</p><h4>Side-Car Pattern</h4><p>This is a way to deploy a helper alongside the microservice container, where the term &quot;sidecar&quot; originates from the real-world vehicle.</p><p>In this pattern, it supports the main microservice to run the core business logic while the sidecar takes care of support functions. handle secondary tasks such as logging, monitoring, security, etc.</p><p>Let&#39;s see a real-world scenario:</p><p>Imagine a shopping microservice that processes the orders, instead of adding logging and monitoring code inside the order service. A Sidecar container is added next to it just to handle logging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*i_6zHut3oXyV2tO3x2Xdeg.png" /><figcaption>SideCar Pattern</figcaption></figure><h4>Ambassador</h4><p>An ambassador is a separate intermediary communication between the main application (microservice) and external services.</p><p>There are two types of the ambassador pattern</p><ol><li>Inside Ambassador</li></ol><p>This is run inside the same pod (same environment), and helps to communicate with the external services or APIs. It manages outbound communication from the microservice to external services.</p><p>Let&#39;s see a real-world scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxRqTWjILQYZAZ4hGB2lJQ.png" /><figcaption>Inside Ambassador</figcaption></figure><p>In here, the Payment Service pod contains two containers:</p><p>Payment Service — responsible only for the business logic of processing payments. It doesn&#39;t worry about how to securely</p><p>Ambassador Container — acts as an outbound proxy that manages all communication between the Payment Service and third-party banking APIs.</p><p>When a client request comes in, it first reaches the Payment Service. Any time the Payment Service needs to connect to an external banking API, it simply passes the request to the Ambassador Container.</p><p>2. Outside Ambassador</p><p>This runs outside in a separate pod acting as a proxy/API Gateway that external clients or other services use to reach the micro services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wO56cpDWktys8N6UbqRn0A.png" /><figcaption>Outside Ambassador</figcaption></figure><p>In the above outside Ambassador diagram, an API gateway acts as an outside ambassador by receiving requests from users of an e-commerce platform and routing them to relevant backend microservices like catalog, order, or payment services. It manages authentication, routing, caching, and throttling before the requests reach the microservices.</p><h4>Adapter</h4><p>The adapter pattern acts as a helper container that transforms requests and responses between the microservice and an incompatible external system. It converts protocols or data formats to ensure smooth communication.</p><p>In microservices, they mostly have to communicate with the different services and some legacy systems or APIs that use different protocols or data formats. Instead of changing the microservice code, we use an adapter to translate for better integration and translation.</p><p>Just imagine a modern microservice using a REST API for communication, but needs to interface with some old legacy system that only understands the SOAP requests. Without an adapter, the microservice cannot directly talk to the legacy system because of the different protocols.</p><p>By deploying an adapter container alongside or as a separate service, the REST requests from the microservice are converted into SOAP format and sent to the CRM. The adapter also converts SOAP responses back into REST responses that the microservice can understand.</p><h4>BlueGreen Pattern</h4><p>Blue-green pattern is a strategy that we use to minimize downtime and the latency by creating two identical production environments called blue and green. At any time, only the blue one serves all the live production traffic, while the other green one is identical to the blue one and is being updated with a new version(v2).</p><p>Then switch traffic from the blue to green using a load balancer or service discovery routing. If issues arise , Blue environment stands by as a backup, ready for immediate rollback if any problem occurs in Green.</p><p>Over time, in the next release cycle, the green one becomes blue.</p><p>Let’s see a simple example;</p><p>Handling user authentication in the Blue environment where version 1.0 runs. Now deploy a new version 2.0 with improved login speed and a new security feature to the green environment. Route all to the green. If version 2.0 works fine, blue is retired, or if the green one has issues, immediately route back traffic to the blue using version 1.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNpHur7Dfyff72axcFfiSg.png" /><figcaption>Bluegreen Pattern</figcaption></figure><h4>Canary</h4><p>This is a deployment strategy where a new version of a service is gradually rolled out to a small subset of users or servers before full production release. This allows teams to test and monitor the new version for issues before releasing it to the entire user base.</p><p>Let&#39;s see how it works.</p><p>Initially, 100% of the traffic of users goes to the current stable version,</p><p>then we deploy a new version, and a small percentage of live user traffic is routed to the canary version(5%,10%). This can be a random subset or a targeted user group, such as internal testers or users in a certain region.</p><p>Then carefully monitor any issues that occur any latency, and user feedback.</p><p>If metrics are good, traffic to the canary is gradually increased ( 25%, 50%, then 100%). If issues arise, traffic is rolled back to the stable version immediately, isolating the problem.</p><h4>Dark Launch</h4><p>Dark Launch is a deployment pattern which a new feature or service is deployed directly to production and receives the real production traffic, but responses are hidden from the user. This means the new code runs in the background, processing live traffic, but without impacting the user experience.</p><p>When a new version of a service is created, it is deployed alongside the existing one in the production environment without replacing it immediately. The real user traffic is duplicated, with one copy going to the live service and the other going to the new service.</p><p>The new service processes the requests, but its results are not shown to users; instead, they are logged or stored for analysis. This allows developers to study the new version’s performance and correctness compared to the current service. Once the new version is tested and verified to be reliable, it can then be gradually released to real users.</p><p>Understanding microservices deployment patterns is key to building reliable and scalable systems. Each pattern, Sidecar, Ambassador, Adapter, Blue-Green, Canary, and Dark Launch, solves specific challenges in deploying and managing microservices.</p><p>I hope this article has given you a clearer understanding of the deployment patterns used in microservices. Apply them wisely to build reliable and efficient systems. Wishing you all the best on your microservices journey!</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab1f399de4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Transactions in Microservices: Patterns and Techniques]]></title>
            <link>https://medium.com/@samithadilshan59/managing-transactions-in-microservices-patterns-and-techniques-2e7e5ced55bd?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e7e5ced55bd</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 06:17:17 GMT</pubDate>
            <atom:updated>2025-09-28T06:18:43.711Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing transactions across multiple microservices is one of the trickiest parts of designing distributed systems. Unlike traditional monolithic applications, where everything shares a single database, each microservice usually has its own database. This makes classic ACID transactions hard or even impossible to implement across services.</p><p>As a result, developers have come up with several patterns and techniques to keep data consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdxj577cbgtMXE-VbN-JCQ.png" /></figure><p>In this article, I’ll go over some of the most important distributed transaction methods I’ve learned. I’ll also include simple examples and practical use cases to make them easier to understand.</p><h4>Saga Pattern</h4><p>The SAGA pattern splits a big distributed transaction into a series of smaller local transactions. Each microservice does its part, then passes the result along to the next service using an event or a message. If something goes wrong at any step, the system rolls back by running compensating actions to undo the changes that have already happened</p><p>There are two types of implementation approaches for the Saga pattern</p><ol><li>Orchestration — where this acts as a middle controller called the orchestrator, overall transactions. In here, the orchestrator calls each service in order and handles rollbacks if something fails.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*5W3n08xzuFhB_3VZBJ8w1w.png" /><figcaption>Orchestration</figcaption></figure><p>2. Choreography — There is no central controller; instead, services are communicated by emitting and listening to events. And this is to avoid the single point of failure.</p><p>Let&#39;s see an example scenario</p><p>Let’s say we’re building an e-commerce system with three services: Order Service, Payment Service, and Inventory Service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*HSJBZYheNmfrRfr1P3IWrA.png" /></figure><p>The Order Service creates a new order. It sends an event to the Payment Service to charge the customer. If the payment goes through, the Payment Service triggers the Inventory Service to reserve stock. But if the Inventory Service can’t reserve stock (for example, items are out of stock), the Payment Service refunds the money, and the Order Service cancels the order.</p><h4>TCC Pattern</h4><p>TCC stands for Try-Confirm-Cancel. It’s like a three-step process for transactions. First, each service tries to reserve resources. Then, once everything is good, they confirm the reservation. If something fails in between, they cancel and release resources.</p><p>Try — this is the phase where the necessary resources are made available.</p><p>Confirm — if all try operations succeed, then confirm.</p><p>Cancel — if any needs fail to abort and roll back.</p><p>Example scenario:</p><p>Imagine booking a flight</p><p>The flight service tries to reserve a seat. The Payment Service tries to reserve funds on the customer’s card. If both succeed, the services move to confirm the seat is booked and the money is charged. If the seat reservation fails at step 1, the Payment Service will cancel and release the held funds.</p><h4>Event Sourcing</h4><p>Instead of storing just the final state in the database, Event Sourcing saves every event that changed the state.</p><p>Let&#39;s think about a bank account. Instead of storing ‘balance =$1000&#39;, store the event history of ‘deposit = $2000’ and ‘withdraw = $1000’.To get the current balance, it&#39;s replay all events.</p><p>This is very useful for auditing, a full history of what happened, dates, wise, we can have a clear idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pskbN7pVUz2hIW5gn-xG5w.png" /></figure><h4>CQRS(Command Query Responsibility Segregation)</h4><p>When building microservices, one challenge we often face is that reads and writes behave very differently. In most systems, reads are far more common than writes. For example, thousands of users may browse and search for products on an e-commerce site, but only a fraction of them actually place an order. Using the same model and database for both reads and writes can become inefficient as the system grows</p><p>This is where CQRS<strong> </strong>comes in. The idea is simple: separate the write side (commands) from the read side (queries).</p><p>Commands<strong> —</strong> handle operations that change data, like Place<em> </em>Order or Update<em> </em>Profile. These usually require strict validation and consistency.</p><p>Queries — handle operations that just fetch data, like Get<em> </em>Order<em> </em>History or List<em> </em>Available<em> </em>Products. These don’t change anything.</p><p>The reason we separate commands and queries is that reading and writing data usually work very differently. In most systems, reading happens a lot more than writing. For example, on an online shop, thousands of people may browse products, but only a few actually buy something. Because of this, the read side can be made faster with things like caching, search engines, or a database that is built just for quick lookups. On the other hand, commands often need more careful checks and rules, like making sure you don’t sell items that are already out of stock. By splitting the two, we can also scale them separately, so if the system needs to handle millions of reads, we can make the read side bigger without changing how the write side works.</p><h4>Outer box Pattern</h4><p>Sometimes when a service updates its database, it also needs to publish an event so other services know about the change. The problem is, if the database update works but the event fails to send, the system can become inconsistent. The Outbox Pattern solves this by storing the event in a special outbox<strong> </strong>table inside the same database transaction as the main update. Later, a background process or message relay picks up the event from the outbox and publishes it to the message broker (like Kafka ).</p><p>Let’s see an example for better understanding.</p><p>Imagine an Order Service, a new order is created and saved in the database. In the same transaction, an event “orderCreated” is also written into the outbox table. A background worker later reads the outbox and publishes “orderCreated” to the message broker. Other services (like Payment or Inventory) receive the event and act on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTqrErh6G81rAX2w_5DvVg.png" /></figure><h4>CDC (Change Data Capture)</h4><p>Change Data Capture, or CDC, is a way to turn database changes directly into events without the application having to do it manually. Instead of writing an event in the code, CDC tools watch the database and capture any inserts, updates, or deletes. These changes are then published as events to a message broker so other services can react to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*cuTK8YiTsMi23QBtN4T4ng.png" /><figcaption>CDC</figcaption></figure><p>When we use Change Data Capture (CDC) with tools like Debezium, the flow usually looks like this:</p><ol><li>A service updates its main database (for example, the Inventory Service adds new stock).</li><li>Debezium is connected to this database through a source connector. The source connector watches the database log and captures any changes — like inserts, updates, or deletes.</li><li>Debezium then publishes these changes as CDC events into Kafka. Each event describes exactly what changed in the main DB.</li><li>Other services that need this data use a sink connector to read the CDC events from Kafka and store them in their own database or system.</li><li>Now all services stay up to date because whenever the main DB changes, the events flow through Debezium → Kafka → sink connectors → target systems.</li></ol><h4>Schema Evaluation</h4><p>Schema evolution is how to safely change and update data schemas(Database tables, Event formats, APIs) without breaking existing services or causing disruption in distributed systems.</p><p>There are two types of contracts;</p><ol><li>Producer Contract — The producer defines the schema of the data or event it sends.In other words, what the producer promises to deliver. Changes on the producer side must maintain backward compatibility so old consumers don’t break.</li></ol><p>Example: The Inventory Service sends ‘StockUpdate’ events with fields productId and quantity. If a new field location is added, old consumers should still be able to process the event without errors.</p><p>2. Consumer Contract — The consumer defines what it expects from the producer. This allows consumers to safely ignore new fields they don’t care about.</p><p>Example: The Order Service only cares about productId and quantity in the StockUpdate event. Even if the producer adds a location, the Order Service still works fine.</p><h4>Conclusion</h4><p>Managing transactions and data consistency in microservices is challenging because each service has its own database. Traditional ACID transactions don’t work well in distributed systems, so patterns like SAGA<strong>, </strong>TCC, CQRS, Outbox, CDC, and Schema Evolution help keep data consistent.</p><p>I hope this article helped you understand how these patterns work in microservices. Thank you for reading, and all the best with your microservices journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e7e5ced55bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro Service Design Patterns & Resilience Strategies]]></title>
            <link>https://medium.com/@samithadilshan59/micro-service-design-patterns-resilience-strategies-a77abf98d202?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/a77abf98d202</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:27:41 GMT</pubDate>
            <atom:updated>2025-09-15T16:28:56.044Z</atom:updated>
            <content:encoded><![CDATA[<p>In today&#39;s world, we have complex software applications, and micro services offer scalability, flexibility, and fast independent deployments. But these benefits come with new challenges, because distributed services can crash or be overwhelmed.</p><p>To build an efficient microservice, we used different design patterns and resilience strategies that help to make it resilient, face failures, and handle unpredictable loads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oK5FWhjPK2EVabvh1rYADA.png" /></figure><p>This article explores key microservice design patterns and resilience mechanisms you need to know, with simple explanations and practical examples that can help you build the best systems.</p><h4>What is a Design Pattern?</h4><p>A design pattern is a reusable solution to a commonly occurring problem in software design. It is a general concept or blueprint that can be adapted to different situations to solve design challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNPFtXnkmfBvzfcGMfjbhQ.png" /><figcaption>Micro-Service Design Patterns</figcaption></figure><h4>Micro Service Routing Patterns</h4><p>Routing patterns send client requests to the appropriate microservice instances in a distributed system.</p><ol><li>API Gateway Pattern — This acts as a single entry point for the client requests. Mainly routing requests to the relevant micro services, and other than that, API management also happened inside the API gateway.</li></ol><p>Some API management tasks ;</p><p>Authentication and Authorization — by verifying API keys, JWT tokens, or other credentials to access.</p><p>Transformation of Request and response — do modifications to payloads as expected from the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*2EZf-zcCouYIZtDCwYxUWw.png" /><figcaption>API Gateway</figcaption></figure><p>2. Proxy Pattern — Proxy acts as an intermediary that forwards client requests to backend servers. mainly focus on routing the requests.</p><p>There are two types of proxy;</p><ol><li>Forward Proxy — Sit in front of the client and send a request to the server. In here, the server doesn&#39;t know anything about the client. Basically, hide the client identity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*E6hOA68e7xgZYDnpBqqY2w.png" /><figcaption>Forward proxy</figcaption></figure><p>2. Reverse Proxy — sits in front of one or more web servers and acts as an intermediary between the web servers and the Internet. The client sends the request, it goes to the reverse proxy first, then the reverse proxy passes it to the relevant web server. The web server prepares and sends the response back to the reverse proxy. Reverse proxy pass that response to the relevant client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*cmRgFC3DKZhh1TgkjgQHmQ.png" /><figcaption>Reverse Proxy</figcaption></figure><p>Let’s see an example:</p><p>In an online shopping system, many services use a payment service. When a new version of the payment service is deployed, old consumers may fail since they aren’t updated. To handle this we put Payment service proxy infront. Payment service proxy we sit infront of the payment service.</p><p>If a request is compatible with the old version, it forwards it to the old payment service.If a request is compatible with the new version,it forwards it to the new payment service. After time since no one using the old version, we can remove the old version smoothly.</p><p>3. Service Discovery — This is a centralized service registry of all available services with the network locations(IP/Ports). It acts as a service locator, allowing microservices to find the network</p><p>It has 2 types of discovery;</p><ol><li>Client-side Discovery — client service queries the registry and directly calls the target service instance. (Eureka, Consul)</li><li>Server-side Discovery — Client sends a request to load balance or router,which queries the register and forwards the request to target service instance. (ALB, Istio)</li></ol><h4>Micro Service Integration Patterns:</h4><ol><li><strong>Aggregator Pattern — </strong>This pattern acts as a gathering of responses and combines them into a single result.</li></ol><p>There are 3 types of Aggregator patterns</p><ol><li>Scatter &amp; Gather Pattern — Send requests to multiple services at the same time and then collect and combine into a single result.</li></ol><p>Example: Just imagine the Travel package. When a customer requests a travel package, simultaneously ask the Airline Service for flights, then the Taxi service for transport, then the Hotel service for accommodation. Once all responses arrive, the travel package service combines them into one complete package for the customer.</p><p>2. Chained Pattern — requests are passed through a chain of service in sequence, one after another.</p><p>Let&#39;s try to understand that using a simple, real-world online order management process.</p><p>order service → payment service →Inventory service →shipping service</p><p>Here, first validate the order, then process the payment, reserve the items, and finally schedule the delivery. Each service in the chain does its role, and the final result is returned after all the services have completed. Each service depends on the previous service.</p><p>3. Branch — This pattern is a mix of the aggregator pattern and the chained pattern. This is used when the request has to go through different flows depending on conditions.</p><p>3.1 Decision Branch — choose a branch or path based on a condition in business logic.</p><p>3.2 Selective Branch —Multiple paths can be triggered, and select a specific branch to execute.</p><h4>Resilience Patterns and Strategies</h4><ol><li><strong>Strangler-Fig — </strong>This is a strategy to gradually replace a legacy system with new components around it, and slowly shift functionality from the old system to the new.</li></ol><p>Expand-contract is the tactic used for scaling, where, according to the demand, resources are temporarily increased and reduced when they are not needed.</p><p>2. <strong>Circuit Breaker Pattern — </strong>This is a microservice pattern used to handle failures and improve system resilience.</p><p>Before we dive into this pattern, we should learn something called “Cascading failure,” which is a common failure in micro services.</p><p>When a failure in one service causes failure in other connected or dependent services, it is called a <strong>Cascading failure</strong>.</p><p>In the circuit breaker pattern, it prevents an application from repeatedly trying to perform an operation that is likely to fail. which means avoiding cascading failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*lOsytzcRFh6bdBwRtk1LHA.png" /><figcaption>Circuit Breaker Pattern</figcaption></figure><p>Let’s see how it works.</p><p>When the circuit breaker closes, everything works fine, and all requests flow as usual.</p><p>If the service fails repeatedly, a certain failure threshold, the circuit breaker opens. This immediately stops calls to the service and instead returns an error or a fallback response.</p><p>After a set cooldown time, the breaker moves to a half-open state (20%), and a few test requests are made to check if the service has recovered. If the test pass request succeeds. Then the circuit breaker closes and resumes. If it fails again, then again open the circuit breaker and wait for the next cooldown period.</p><p>Three states of the circuit breaker pattern,</p><p>Closed state →Open state →Half open state.</p><p><strong>3. Time-out — </strong>This is a strategy to handle delays and failures in communication between services by setting a maximum wait time before considering the request failed.</p><p>Basically, it defines a specific duration a service waits for a response</p><p>Example: Service A sets a timeout to 2 seconds for the call. If service B does not respond within 2 seconds, then service A aborts the call and handles the timeout by returning an error or a fallback message.</p><p><strong>4. Exponential-backoff — </strong>This strategy is used to stop overloading a service by repeated rapid retries. Instead of retrying immediately or after a fixed delay, the wait time between retries increases exponentially.</p><p>Let&#39;s see how it works using a simple example;</p><p>mainly, we use 3 variables to calculate the time in exponential-backoff</p><p>Interval:<em> </em>the initial wait time before the first retry</p><p>Factor: how much the wait time grows after each retry</p><p>retry count: maximum number of retry attempts</p><pre>retry Count-3<br>Interval-2/3600<br>Factor-1.5<br><br>inital wait time-2s<br>first retry time - 2s * 1.5(initial time * factor) = 3s if this fail <br>second retry time -3s * 1.5 =4.5s </pre><p>However, this can cause another problem: many clients may retry at the same time, potentially overloading the service.</p><p><strong>5. Jitter —</strong> to prevent the problem of retries simultaneously that occurs during the exponential-backoff strategy, in jitter, add a random number to the final time, which solves the problem, smoothing out traffic and reducing the load on the service by reducing the chance of retries from many clients.</p><pre>retry Count-3<br>Interval-2/3600<br>Factor-1.5<br><br>inital wait time-2s<br>first retry time - 2s * 1.5(initial time * factor) = 3s + Random number </pre><p><strong>6. Hedging — </strong>This strategy is used to reduce the latency and failures in micro services by sending multiple requests for the same task to the parallel service instances and taking the first successful response while others are cancelled.</p><p>The first request is sent to one service instance. If the first request does not respond within a predefined hedge delay (threshold time), then a second (or more) request is sent to other instances.</p><p>The system then takes the first successful response and cancels the rest.</p><p><strong>7. Bulkhead Pattern — </strong>The Bulkhead Pattern is used in microservices to isolate failures so that one failing service doesn’t bring down the entire system(not affect to other services). The idea comes from ships a bulkhead separates compartments so if one floods, the whole ship doesn’t sink.</p><p>So let’s see a simple example;</p><p>Imagine in our system has 200 threads in total. Without bulkheads, all services share these threads. If one service (say Service A) suddenly gets overloaded and uses up all 200 threads, other services won’t get any threads and will also fail.</p><p>With the bulk pattern, we allocated threads into pools.</p><p>service A → 100 threads</p><p>service B →50 threads</p><p>service C →50 threads</p><p>Now, if Service A gets overloaded, it can only use its 100 threads. Services B and C still have their own threads available, so they continue working fine.</p><p><strong>8. Rate-Limit — </strong>Control the number of requests a client can send to a microservice or API within a specified time frame. It prevents system overload. Ensure the fair use of resources.</p><p>Example: an e-commerce API allows customers to make a maximum of 10 requests per minute per user.</p><pre>User A -------10 requests----------&gt;get response<br>User A -------11 requests----------&gt;before miniute pass API response with an error <br>429-too many request</pre><p><strong>9. Load shading —</strong> Here, this is a server-side pattern; the service defines a maximum(fixed value) threshold of requests it can handle safely. Anything beyond that limit is dropped immediately.</p><p>Example: A service can handle 100 requests per second (threshold = 100).If it receives 120 requests, it processes the first 100 and drops the other 20.</p><p><strong>10. BackPressure — </strong>In this,<strong> </strong>instead of dropping requests, the service signals the client to slow down when the load is coming in big, and the service sets a warning threshold (say 75% of capacity).</p><p>Once requests exceed 75, the service tells clients, <em>“Slow down.” </em>Clients then reduce the rate (retry later). This way, the service never reaches the point of being overloaded.</p><p><strong>11. BFF (Back End for Frontend) —</strong> The BFF pattern creates a separate backend layer specifically for different frontend clients. It handles client-specific logic, aggregation, and adapts backend microservices data for the client’s needs. its helps to keep frontend code simple because backend code does the heavy work.</p><p>For example, think differently about the display for a web app and a mobile app. The mobile app shows lightweight very simple responses, while the web app shows more details since it can handle large responses. Both BFFs get data from the same backend services, but each BFF reshapes it for its own client.</p><h4>Conclusion</h4><p>Microservice patterns and strategies are crucial because, while microservices give us flexibility and scalability, they also add complexity. That’s why it’s important to clearly understand each pattern when to use it, how to apply it, and the problems it solves.</p><p>I hope my previous articles helped you gain a clear picture of how microservices evolved from monolithic systems and the full revolution of the microservice architecture.</p><p>The real challenge is choosing the right pattern at the right time. Do that wisely. Thank you so much for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a77abf98d202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOA, EBS, and the Path to Microservices]]></title>
            <link>https://medium.com/@samithadilshan59/soa-ebs-and-the-path-to-microservices-d79dc8c14d66?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79dc8c14d66</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:27:03 GMT</pubDate>
            <atom:updated>2025-09-14T17:27:03.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, it’s important for software systems to work well together. Before microservices became popular, companies mainly used SOA(Software Oriented Architecture) and ESB(Enterprise Service Bus) to help different applications communicate and integrate smoothly.</p><p>This article explores these foundational concepts, explains how ESB’s key services work, and explains the difference between ESB and microservices</p><h4>What is Service-Oriented Architecture (SOA)?</h4><p>SOA is a software design style where you divide things into small, reusable services, and each one has a specific job. The main point is that different apps can still work together, even if they’re built on different platforms or technologies.</p><h4>Enterprise Service Bus (ESB)</h4><p>Enterprise Service Bus is a middleware that acts as a central hub for SOA implementations. It handles communication, transformation, and routing of messages between services or applications, allowing them to interact without directly depending on each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*YVrivQs8BtpqEBtn9icpYw.png" /></figure><p>Let’s see how ESB works:</p><p>There are three key services in ESB</p><ol><li>Translate — translate a message from one communication format (like XML) to another (like JSON). An ESB’s adapters work like translators, helping different systems that use different “languages” share and understand data.</li></ol><p><strong>Example: </strong>An application sends data as an XML file, but the recipient. The system requires the data in a JSON format via HTTP, and the ESB translates. The XML is converted into JSON and uses the HTTP protocol for delivery.</p><p>2. Transform — Changing the data format or structure of a message to match what the receiving application expects. This can involve mapping fields, converting data types, or restructuring the message.</p><p><strong>Example: </strong>let&#39;s think service A sends a JSON message as below</p><pre>{<br>  &quot;firstName&quot;: &quot;Samitha&quot;,<br>  &quot;lastName&quot;: &quot;Senevirathne&quot;<br>}</pre><p>The ESB transformation can combine these and send them to service B as:</p><pre>{&quot;fullName&quot;:&quot;Samitha Senevirathne&quot;}</pre><p>3. Protocol Negotiate — Handling communication protocol between different systems.ESB manages converting and adapting messages from one protocol to another</p><p><strong>Example: </strong>System A receives a message via HTTP and forwards it over JMS to another system.</p><h4>Why move from ESB to microservices:</h4><p>Like we said before, the ESB acts as a central hub where all the systems connect. It handles the integration by taking care of translation, transformation, and communication. But since everything has to pass through the ESB, if it gets slow or crashes, the entire system feels the impact.</p><p>Later on, microservices came in to fix some of the problems with ESB by spread out the control instead of keeping it in one place. This made systems more flexible and easier to scale.</p><h4>Conclusion</h4><p>Now we know Learning about SOA and ESB really helped us see how big companies used to handle complex system integration before microservices became popular. The ESB made it easier for different systems to talk to each other by handling things like transformation, translation, and protocol negotiation, so they could work together without clashing.</p><p>Thanks for reading! In the next article, we’ll explore microservice design patterns and how they help build flexible, scalable systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79dc8c14d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monoliths vs Microservices: Why We Moved On]]></title>
            <link>https://medium.com/@samithadilshan59/monoliths-vs-microservices-why-we-moved-on-60cad1b57962?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/60cad1b57962</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:26:09 GMT</pubDate>
            <atom:updated>2025-09-14T17:26:09.714Z</atom:updated>
            <content:encoded><![CDATA[<p>Before 2011, most of the software applications were built as a single code base, which was known as “Monolithic architecture”.But in early 2011, when Martin Flower and James Lewis introduced the new architecture called “Micro Service” as a solution for some monolithic architecture’s problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKN19e7m2Ac18bnJvL1pIA.png" /></figure><p>In this article, we’ll explore the journey from monolithic to microservices architecture, understand the pros and cons of each, and discover why microservices have become the backbone of modern software development.</p><h4>Monolithic Architecture</h4><p>This is a software development approach where an entire application is built as a single unit, indivisible, with all components, user interfaces, business logics, and everything into a single large code base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*W3tKPRRcYtgnEIGrzxQAsQ.png" /><figcaption>Monolithic Architecture</figcaption></figure><p>Let&#39;s see what the pros and cons of Monolithic architecture are.</p><p><strong><em>Pros of Monolithic Architecture</em></strong></p><p><strong>Easy to test</strong> — Since everything is in one codebase, end-to-end testing is easier.</p><p><strong>Easy to monitor</strong> — The system runs as a single process, making it easy to monitor.</p><p><strong><em>Cons of Monolithic Architecture</em></strong></p><p><strong>Tightly coupled —</strong> Your entire application is packed into one single file, making it hard to isolate or modify without affecting others.</p><p>When versioning happened, the whole other set of services was affected</p><p><strong>Complex debugging — </strong>Since everything is packed into one large codebase, tracking down the exact source of an error can be time consuming.</p><p><strong>Difficult deployments — </strong>A single change means redeploying the entire application</p><p><strong>Scaling Issues — </strong>Scaling the application usually means scaling the whole system rather than just the parts under heavy load.</p><h4>Micro Service Architecture</h4><p>Unlike monoliths, microservices architecture breaks an application into multiple small, independent services. Each service focuses on a well-defined, scoped business functionality and can be deployed and scaled independently.</p><p><strong>Key Characteristics</strong></p><p><strong>Domain Driven Design (DDD)</strong> — Exactly defined business scope. A specific single service handles each business scope really well.</p><p><strong>Example:</strong> Imagine an e-commerce system,</p><p>order service — to handle orders</p><p>payment service — to handle payments</p><p><strong>Independent scalable —</strong>each small, self-contained service can be scaled up or down independently of others in the application.</p><p><strong>Independent deployable — </strong>where each of the services can be deployed separately</p><p><strong><em>Pros of Microservices :</em></strong></p><p><strong>Independent deployment — </strong>Each service can be updated or redeployed without affecting the rest of the system.</p><p><strong>Scalability —</strong> Only the components under heavy load need to be scaled, making resource usage more efficient.</p><p><strong>Flexibility in technology –</strong>Different services can use different programming languages, frameworks, or databases.</p><p><strong>Decentralized Data Management — </strong>Each service manages its own database or data source.</p><p><strong>Better maintainability</strong> — Smaller, focused codebases are easier to understand and manage over time.</p><p><strong><em>Cos of Microservices :</em></strong></p><p><strong>Hard to monitor — </strong>Monitoring many small services across a distributed infrastructure can be challenging.</p><p><strong>Testing challenges </strong>— End-to-end testing across multiple services can be more complicated</p><h4>Monolithic Vs Micro Service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*5hqr1cgil5DE9__xfOPVOg.png" /></figure><p>How do we manage the code?</p><p>Since microservices use separate, independent services, it has two options to manage the code</p><ol><li>Mono Repository — All microservices live inside one central repository.</li><li>Poly Repository — Each microservice has its own repository, managed independently.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*rPMyL5_ei9z_r6Qyr2s0rA.png" /></figure><p>In a monorepo setup, all the microservices sit inside one big repository. It makes the code management and development easier. Since it has one repository, it is easy to clone and start the development. Changes can be tested easily together. But there are some challenges in a mono repo.</p><p>If you need to make a change that affects multiple services, it’s easier since the whole codebase is together. But the worst case is that as the repo grows, it can get complex and hard to handle. If teams don’t use best practices to write code, the services can start feeling like one big “monolithic Architecture” again.</p><p>But in a polyrepo, each microservice lives in its own separate repository. This is nice because every service can grow, get new versions, and be deployed without messing up the other services.</p><p>Each team fully owns its service they handle the code, which makes things more organized and gives a clean separation between services.</p><p>When companies started moving to microservices for things like flexibility, scalability, and giving teams more independence, they also looked back at older methods, such as Service-Oriented Architecture (SOA), to see how people handled distributed systems before. Microservices basically push SOA ideas further, but back then, big enterprise systems mostly depended on something called an Enterprise Service Bus (ESB) to handle communication and integration between services.</p><p>Moving from monoliths to microservices is like going from having one giant block of code that does everything to having many smaller, focused services that work together. Monoliths are easy to start with, but they get harder to manage as your app grows. Microservices give you more freedom, scalability, and flexibility, but they also add some new challenges to deal with. In the end, it’s all about what your project really needs.</p><p>Thank you for taking the time to read this article. I hope it helped you understand the journey from monolithic to microservices architecture. In the upcoming article, we’ll continue by exploring SOA and ESB, and how they shaped today’s microservices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60cad1b57962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Java’s Class Loader Hierarchy in Minutes.]]></title>
            <link>https://medium.com/@samithadilshan59/understanding-javas-class-loader-hierarchy-in-minutes-cbec5a61c28b?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbec5a61c28b</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 12:22:23 GMT</pubDate>
            <atom:updated>2025-09-10T14:00:21.153Z</atom:updated>
            <content:encoded><![CDATA[<p>A class loader is a special object in Java that handles loading class files into the Java Virtual Machine’s(JVM) method area while a program is running.</p><p>Instead of loading all classes at once, the JVM uses class loaders to load each class only when the program actually needs it, helping manage memory and improve efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GyUqiJEJShH0S4wiA2y1g.png" /></figure><h4>Types of Class Loaders</h4><p>Java has three built-in class loaders :</p><ol><li>Bootstrap — This is the core class loader in the JVM. Loads core Java libraries such as those in<em>&lt;JAVA_HOME&gt;/jre/lib.</em></li><li>Extensions — Loads classes from the extensions directory <em>&lt;JAVA_HOME&gt;/jre/lib/ext</em>. Its parent is the Bootstrap class loader.</li><li>Application/System — Loads classes from the application’s classpath. Extension is the parent class loader for the application. And this is the default class loader that loads the user classes.</li><li>Custom — A custom class loader in Java is a user-defined class loader created by extending the <em>java.lang.ClassLoader</em>.</li></ol><p>It allows developers to customize the process of loading classes. example, loading classes from unusual sources like a network location or database.</p><h4>Delegation Model</h4><p>Class loaders used the delegation principle, where a request to load a class is first passed to the parent class loader before the current loader attempts to load itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*eUisqsnwwR3RA7AwGvauEQ.png" /><figcaption>Class Loader Hierarchy</figcaption></figure><p>Let’s see the above diagram steps of how delegation happens in Java.</p><p>In here, the first class loader received the Class load request from the default Application class loader. Then, without checking itself, it passes the request to its parent class, which is the Extension loader, to load the class first.</p><p>The extension class loader also passes the request to its parent class, which is the top in the hierarchy, the Bootstrap class loader.<br>In the top, the bootstrap class loader attempts to load the class from the core Java runtime libraries.</p><p>Since the bootstrap class loader only loads core Java runtime classes found in the JVM system libraries (e.g, <em>rt.jar </em>or equivalent). It won’t find third-party classes that reside outside these core library paths.</p><p>Then it passes to the Extension Class loader, then it checks for the class inside the ext folder, not found, then it passes to the default class loader, Application class loader.</p><p>Now let’s dive into a practical scenario of how it&#39;s happened, actually, and see the different outputs.</p><pre>public class Application {<br><br><br>public static void main(String[] args){<br><br>Employee employee = new Employee();<br>employee.sleep();<br>}<br><br>}</pre><pre>public class Employee {<br><br>public void sleep(){<br><br>System.out.println(&quot;Employee is sleeping&quot; + Employee.class.getClassLoader());<br>}<br>}</pre><p>First, we try it with the default way,</p><p>Go to your project directory first and in the terminal,</p><ol><li>To compile the Java files</li></ol><pre>Javac *.java</pre><p>2. To run the Java main file</p><pre>Java Application</pre><p>Since <em>Employee.class</em> is in the application classpath, it’s loaded by the <strong>Application ClassLoader (AppClassLoader)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*hKogJOpkryN8ZpWqzziGiQ.png" /><figcaption>AppClassLoader output</figcaption></figure><p>To see how the delegation happened ,we have to downgrade the JDK version to 8,</p><p>Let’s create a jar file from Employee class</p><pre>jar -cvf employee.jar Employee.class</pre><p>Created employee.jar file , we should copy it into the /jre/lib/ext folder. Then try to run the main program again. Then you’ll figure out the output given as the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*RiLFSe9EWSuB0Vqo2LYpAg.png" /><figcaption>ExtClassLoader Output</figcaption></figure><p>Now the class is picked up from the <strong>extension directory</strong>, so it is loaded by the <strong>Extension ClassLoader</strong> instead of the AppClassLoader. When you placed employee.jar inside jre/lib/ext, it was no longer loaded by the Application ClassLoader.</p><p>But when we consider the Bootstrap, it only knows about the core Java runtime classes. So when we create our own classes (like Employee), Bootstrap will never find them, so delegation passes the request down the chain.</p><h4>What Happens When No Loader Can Find the Class? (ClassNotFoundException)</h4><p>First, the<strong> </strong>Application ClassLoader is asked by its parent.</p><p>It delegates to the Extension ClassLoader.</p><p>Then, Extension delegates to Bootstrap ClassLoader.</p><p>If Bootstrap doesn’t find the class, control goes back to Extension.</p><p>If Extension doesn’t find it, control goes back to Application.</p><p>If the Application also can’t find it the JVM throws: ClassNotFoundException</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ZVpDgjD1yCj7WUxriwdHyA.png" /><figcaption>ClassNotFoundException</figcaption></figure><p>By simply moving the Employee class around, we now have an idea about how the Java Delegation works in practice. By shifting the class between the application classpath and the extension directory, we saw how responsibility moves between the Application ClassLoader, the Extension ClassLoader, and finally, the Bootstrap ClassLoader.</p><p>Now, I hope you have a good idea about this and its importance in the Java ecosystem. Understanding class loader delegation not only helps you debug common issues like <em>ClassNotFoundException</em> but also gives you deeper insight into how the JVM maintains security, like preventing overriding Java core classes.</p><p>Happy exploring, Thank You! .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbec5a61c28b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Exception Handling Basics]]></title>
            <link>https://medium.com/@samithadilshan59/java-exception-handling-basics-7a9b8ff319a9?source=rss-44ff7c80d445------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9b8ff319a9</guid>
            <dc:creator><![CDATA[Samitha_ Senevirathne]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 15:33:56 GMT</pubDate>
            <atom:updated>2025-08-31T17:32:43.740Z</atom:updated>
            <content:encoded><![CDATA[<p>In the real world, mistakes happen all the time: a file might be missing, the internet might go down, or a user might type something unexpected. The same is true in programming. Whether you are an experienced software engineer or not, we have to handle some operations in programming. If we don’t prepare for these surprises, our applications can crash.</p><p>This is where <strong>Exception Handling</strong> in Java comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbDMbTjdqdZgkxh2OEuZNA.png" /></figure><p>In general Exception means something like an event that interrupts the normal flow of a program.</p><p><strong>Exception Handling</strong> is a technique that helps programs manage runtime issues, allowing them to continue running normally or exit safely when necessary.</p><p>At the core of Java’s error-handling system is the Throwable class. It’s like the parent of two big groups: <strong>Errors</strong> and <strong>Exceptions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*45PF0rB1jHXoWMhLAbTsTw.png" /><figcaption><a href="https://rollbar.com/blog/java-exceptions-hierarchy-explained/?utm_source=chatgpt.com">Java Exceptions Hierarchy</a></figcaption></figure><p><strong>Errors </strong>are serious problems that can&#39;t be handled, such as running out of memory, which programs usually can’t recover from.</p><pre>// Example of a compile-time error<br>class ExampleError {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello World&quot;  // Missing closing parenthesis and semicolon<br>    }<br>}</pre><p><strong>Exceptions</strong>, on the other hand, are issues your code can catch and deal with, like missing files or invalid input, so your program can keep running smoothly.</p><pre>        // Example of an exception (ArithmeticException)<br>class ExampleException {<br>    public static void main(String[] args) {<br>        int a = 10;<br>        int b = 0;<br>        int c = a / b; --------&gt;// Causes ArithmeticException division by zero<br>    }<br>}</pre><p>In Java, exceptions can also be split into two separate categories as Unchecked, which is also called “RuntimeExceptions,” and checked Exceptions.</p><pre>java.lang.Object<br>   └── java.lang.Throwable<br>         ├── java.lang.Error<br>         └── java.lang.Exception<br>              └──java.lang.RuntimeException<br>              └──chceked Exception</pre><h4>Checked vs Unchecked Exceptions</h4><ol><li>Checked — These are exceptions that the compiler forces you to handle. If a method can throw a checked exception, you must either wrap it in a try/catch block or declare it with throws in your method signature.</li></ol><p>Examples:</p><p>IOException (input/output errors)</p><p>SQLException (database access errors)</p><p>ClassNotFoundException (when the class is not found)</p><pre>public void readFile(String path) throws IOException {<br>    FileReader fr = new FileReader(path);-----&gt; // must handle IOException<br>}</pre><p>2. Unchecked — These are exceptions that the compiler does not force you to handle. They are subclasses of RuntimeException . You can catch them if you want, but it’s optional.</p><p>Examples:</p><p>ArithmeticException (e.g., divide by zero)</p><p>NullPointerException (accessing null object)</p><pre>public int divide(int x, int y) {<br>    return x/ y; ----------------&gt;// may throw ArithmeticException if y== 0<br>}</pre><h4>Java Exception Handling Basics</h4><ol><li>Try — a block of code where something risky might happen.</li><li>Catch — The part of the program that catches and manages the exception.</li><li>Finally — An optional block that always runs after try (whether an exception occurs or not). It’s often used for clean-up tasks like closing files or releasing resources.</li></ol><p>Let&#39;s look at a simple Java exception handling example</p><pre>public class ExampleDemo {<br><br>public static void main(String []args){<br><br><br>try{<br><br>int result = 10/0 ;          -----------------&gt;//where will throw an exception<br><br>}catch(ArithmaticException e){  ----------&gt;//where handle the exception, no crash<br><br><br>System.out.println(&quot;Cant devide by Zero!&quot;);<br><br>}<br>System.out.println(&quot;rest of the code running fine&quot;); ------&gt;//print this<br><br>}<br><br>}</pre><h4>Exception Propagation in Java</h4><p>Exception propagation happens when an exception is not handled in the method where it occurs. Java then passes the exception up the call stack to the method that called it. This continues until the exception is caught or the program terminates.</p><p>In simple terms, if a method doesn&#39;t handle an exception, it throws it to its caller method, which may handle it, or pass it further up.</p><p>Let&#39;s see how it happened</p><pre>Public class ExampleTwo{<br><br>public static void main(String [] args){<br><br>System.out.println(&quot;This is the start of the program&quot;);<br>methodA();                   -----------------&gt; //call method A<br><br>System.out.println(&quot;This is the end of the program&quot;);<br><br>}<br><br>Static void methodA(){<br><br>methodB();                    -----------------&gt; //call method B<br><br><br>}<br>static void methodB(){<br><br>methodC();                   -----------------&gt; //call method C<br><br>}<br><br>static void methodC()<br>{ <br><br>int result = 10/0 ;---------------&gt;// This will throw ArithmeticException<br>System.out.println(result);<br><br>}<br><br>}<br>}</pre><p>In here, during runtime first main()starts execution. Then print “This is the start of the program”.And calls methodA().</p><p>Then invoke methodA() and call methodB()</p><p>Then invoke methodB() and call methodC()</p><p>Finally, the methodC () is invoked.</p><p>Tries to execute int result = 10/0;</p><p>Division by zero occurs, ArithmeticException is thrown immediately. The line System.out.println(result) is never executed.</p><p>Then exception propagation starts, since there’s no try-catch block inside methodC(), the exception is not handled there. Then Java passes the exception up the call stack to the method that called it, methodB(). MethodB() also has no try-catch, so the exception goes up to its caller methodA().</p><p>methodA() also doesn’t handle it, so it goes back up to main().</p><p>main() doesn’t handle it either, it reaches main() and JVM handles it (program crashes).</p><pre>public class ExampleTwo {<br><br>    public static void main(String[] args) {<br>        System.out.println(&quot;This is the start of the program&quot;);<br>        methodA();<br>        System.out.println(&quot;This is the end of the program&quot;);<br>    }<br><br>    static void methodA() {<br>        methodB();<br>    }<br><br>    static void methodB() {<br>        try {<br>            methodC();   // risky call<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Exception caught in methodB: &quot; + e);<br>        }<br>    }<br><br>    static void methodC() {<br>        int result = 10 / 0;   // throws ArithmeticException<br>        System.out.println(result);<br>    }<br>}</pre><ul><li>In the above program, let&#39;s see what happens now;</li></ul><p>methodC() throws exception and goes back to methodB().methodB() has<strong> </strong>try-catch it catches the ArithmeticException.So after that exception is handled, there for does not propagate further. The program continues normally after methodB() finishes.</p><h4>Exception Rethrowing in Java</h4><p>When a method catches an exception using a try-catch block but decides that it cannot fully handle it, it can rethrow the exception to its caller.</p><p>Catch the checked exception thrown as an unchecked exception, then no need to force handling the exception.</p><pre>public class ExampleforThrowing{<br>public static void main(String []args){<br><br>System.out.println(&quot;Start of program&quot;);<br><br>        // No try catch here (not forced by compiler)<br>        readFile();  <br><br>        System.out.println(&quot;End of program (if no exception occurs)&quot;);<br>    }<br><br><br>static void readFile(){<br><br><br>try{<br>                             //Checked exception (FileNotFoundException)<br> FileReader fr = new FileReader(&quot;Samitha.txt&quot;);<br><br>}catch(FileNotFoundException e){<br><br>  System.out.println(&quot;Checked exception caught&quot;);<br>  throw new RuntimeException(&quot;File not found, wrapped as unchecked&quot;, e);<br>}<br><br>}<br><br>}<br><br></pre><p>When main() calls the readFile() method, it attempts to open a file named samitha.txt. Since the file does not exist, a FileNotFoundException (which is a checked exception) occurs.</p><p>This exception is caught inside the readFile() method, but instead of being handled directly, it is rethrown as an unchecked RuntimeException. Because the exception has been converted to an unchecked type, the Main() method is not forced by the compiler to use a try-catch block or declare it with “throws”. As a result, the program compiles without error, and at runtime, the JVM prints the exception details and terminates the program.</p><h4>Custom Exception Handling in Java</h4><p>Now, let’s get into seeing how we can create our own custom exception. Sometimes the built-in exceptions in Java are not enough for specific problems in your application. In such cases, you can create your own custom exception by extending the Exception class.</p><pre>public AgeSmallException extends Exception{   -----&gt; //create a custom exception<br>   <br>public AgeSmallException(String message) {<br>        super(message);<br>    }<br>}<br><br>public class CustomExceptionExample {<br>static void checkAge(int age)throws AgeSmallException {<br><br>if (age &lt; 18) {<br><br>throw new AgeSmallException(&quot;Age is too small&quot;);<br><br>}else{<br>System.out.println(&quot;Age accepted: &quot; + age);<br>}<br><br>} <br> public static void main(String[] args) {<br>        try {<br>            checkAge(15); --------&gt; //here its happens a exception<br>        } catch (AgeTooSmallException e) {<br>            System.out.println(&quot;Caught Exception: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><h4>Best practices in exception handling</h4><ol><li>Do not catch if you cannot handle — If your method doesn’t know how to deal with an exception, don’t catch it unnecessarily. Instead, let it propagate to a higher level where it can be handled properly.</li><li>Catch the most specific exception — Always catch the most precise exception type rather than using Exception or Throwable.</li></ol><pre>catch (Exception e) { ... }  // too broad and bad<br>catch (ArithmeticException e) { ... }  // very specific ans]d easy</pre><p>3. Do not swallow exceptions —it means that when an exception is caught, it should not be ignored or suppressed silently without proper handling, logging, or rethrowing. Swallowing exceptions makes debugging and error tracing difficult.</p><pre>catch (ArithmeticException e){ ----&gt;// Exception swallowed nothing is done here<br>    <br>}</pre><p>4. Throw early, catch later — Throw exceptions as soon as the problem arises (throw early).Catch exceptions where you can handle them properly (catch later). Avoid catching exceptions just to rethrow them or do nothing useful</p><p>5. Do not throw from a finally block —As we mentioned above, the finally block is meant for cleanup (like closing files or database connections).</p><p>If the finally block throws an exception (commented out line), it suppresses the original ArithmeticException.Suppressing the original exception hides the root cause, making debugging difficult.</p><pre>public class SimpleFinally {<br>    public static void main(String[] args) {<br>        try {<br>            System.out.println(&quot;In try block&quot;);<br>            int x = 5 / 0; -------------------&gt; // Causes ArithmeticException<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Catch: &quot; + e.getMessage());<br>        } finally {<br>            System.out.println(&quot;In finally block&quot;);<br>            // Throwing exception here is bad really and hides the original one<br>            // throw new RuntimeException(&quot;Exception from finally&quot;);<br>        }<br>    }<br>}</pre><p>6. Do not log and throw — Avoid both logging an exception and rethrowing it, because it may lead to duplicate log entries.</p><p>Exception handling is not just about avoiding crashes; it’s about making your code resilient, clear, and user friendly. Beyond preventing failures, it helps maintain code readability, ensures better debugging, and improves system reliability.With the right practices, your applications can handle unexpected issues gracefully and deliver a smoother user experience.</p><p>Thank you for reading!Good luck with your Java programming journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9b8ff319a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>