<?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 Ayush Gupta on Medium]]></title>
        <description><![CDATA[Stories by Ayush Gupta on Medium]]></description>
        <link>https://medium.com/@ayushgupta228?source=rss-d90a0284330------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UNC9mct7x-R84-O6L3yDqg.jpeg</url>
            <title>Stories by Ayush Gupta on Medium</title>
            <link>https://medium.com/@ayushgupta228?source=rss-d90a0284330------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:20:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayushgupta228/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[100% Safe, 100% Working Fix for “fatal: Failed to resolve HEAD as a valid ref”]]></title>
            <link>https://medium.com/@ayushgupta228/100-safe-fix-100-working-for-fatal-failed-to-resolve-head-as-a-valid-ref-no-data-loss-no-2db93c6a6290?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db93c6a6290</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 15:00:03 GMT</pubDate>
            <atom:updated>2026-08-21T16:43:14.149Z</atom:updated>
            <content:encoded><![CDATA[<p>A Proven, Read-Only-First, Remote-Safe Methodology for Resurrecting Broken Local Repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*NTY_BM_JkjrmHaNI1S691Q.png" /><figcaption><strong>Problem we are talking about</strong></figcaption></figure><h3>Foreword: The “Probe First, Patch Later” Philosophy</h3><p>When Git shows an error like fatal: Failed to resolve HEAD as a valid ref, the first reaction is often to start running recovery commands immediately. That can make the situation worse.</p><p>This guide explains a careful, step-by-step recovery process that was tested on a real repository. In that case, several important Git reference files — refs/heads/prod3, ORIG_HEAD, and refs/remotes/origin/prod3 — had been overwritten with null bytes (00 00 00...).</p><p>The goal of this approach is to first understand exactly what is broken, identify the correct commit, and only then make the necessary local repairs.</p><h3>The Ironclad Safety Guarantees</h3><ul><li><strong>No Changes to the Remote Repository</strong><br>We will not run any git push commands. The only network command used is git fetch origin, which simply downloads the latest information from the remote repository. It does not make any changes to the remote.</li><li><strong>Diagnose First, Make Changes Later</strong><br>Steps 1 through 6 are only for checking and diagnosing the problem. We first confirm exactly what went wrong and identify the correct commit hash. No changes are made until the issue is clearly understood.</li><li><strong>Create a Full Backup First</strong><br>Before changing anything locally, we make a complete copy of the .git directory. This gives us a backup of the repository&#39;s Git data, so we can quickly restore it if anything goes wrong.</li><li><strong>Only Modify Local Git References</strong><br>All repairs are limited to the plain-text reference files inside the local .git directory. We will not modify Git hooks, Git configuration files, or any files in the working directory.</li></ul><h3>The Syndrome (What You Will See)</h3><pre>git branch<br>&gt; fatal: Failed to resolve HEAD as a valid ref<br><br>git status<br>&gt; fatal: ambiguous argument &#39;HEAD&#39;<br><br>git pull<br>&gt; fatal: update_ref failed for ref &#39;ORIG_HEAD&#39;</pre><h3>Terminology Decoder (Read Once, Refer Always)</h3><h4>Glossary: To avoid repeating the same explanations throughout the guide, here are the main terms used in the recovery process.</h4><p><strong>.git directory</strong><br>The hidden directory that contains Git’s internal data, including objects, references, logs, and configuration.</p><p><strong>HEAD</strong><br>A special reference that tells Git which branch is currently checked out. For example:<br>ref: refs/heads/prod3</p><p><strong>Refs</strong><br>Short for “references.” These are files inside .git/refs/heads/ and .git/refs/remotes/ that contain 40-character SHA-1 commit hashes.</p><p><strong>Format-Hex</strong><br>A PowerShell command that displays the raw hexadecimal contents of a file. It is useful for finding invisible characters, such as null bytes (00).</p><p><strong>Null Bytes (00)</strong><br>Binary zero bytes. If a Git reference file contains null bytes instead of a valid commit hash, Git cannot read the reference and reports it as an invalid SHA-1 pointer. This can happen if a write operation is interrupted.</p><p><strong>Reflog</strong><br>Git’s record of previous reference changes. It is stored under .git/logs/refs/heads/ and can often help recover an earlier commit hash.</p><p><strong>git cat-file -t</strong><br>A Git plumbing command that checks what type of object a given hash points to. It can return commit, tree, blob, or tag. If the object cannot be found, the hash may no longer exist in the Git object database.</p><p><strong>Backup</strong><br>A complete copy of the .git directory created before making any changes. It allows the repository to be restored if something goes wrong.</p><p><strong>Set-Content</strong><br>A PowerShell command used in this recovery process to replace a corrupted reference file with the correct 40-character commit hash.</p><p><strong>Remote-Tracking Branch</strong><br>A local reference, such as .git/refs/remotes/origin/prod3, that records the state of the remote branch from the last git fetch.</p><p><strong>ORIG_HEAD</strong><br>A temporary reference that Git creates before operations such as merge, rebase, or reset. It can help recover a previous state and can be removed if it becomes corrupted.</p><p><strong>git fsck</strong><br>Short for “File System Check.” It checks the integrity of Git’s object database and reports missing, corrupted, or unreachable objects.</p><p><strong>Dangling Objects</strong><br>Commits, trees, or blobs that still exist in Git’s object database but are no longer connected to any branch or other reference. They are usually harmless and do not necessarily mean the repository is corrupted.</p><h3>Step-by-Step Restoration Protocol</h3><p><strong><em>Note</em></strong><em>: All commands are written for PowerShell (Windows). Adjust </em>Get-Content<em> and </em>Set-Content<em> syntax accordingly for Bash (</em>cat<em> and </em>echo<em>).</em></p><h3>Phase 1: Read-Only Diagnosis (No Writes Yet)</h3><h4>Step 1: Establish Your Bearings</h4><pre>dir .git</pre><p>What it does: Lists the .git directory. Confirms you are standing inside the root of the actual repository.</p><p><strong>Expected Result:</strong></p><pre>Mode                 LastWriteTime         Length Name<br>d-----         8/19/2026   9:10 PM                hooks<br>d-----         8/19/2026   9:12 PM                logs<br>d-----         8/19/2026   9:12 PM                objects<br>d-----         8/19/2026   9:10 PM                refs<br>-a----         8/19/2026   9:12 PM             41 HEAD</pre><p><strong>Non-Expected Result:</strong></p><pre>dir : Cannot find path &#39;F:\...\.git&#39; because it does not exist.</pre><p>Action: Navigate up one folder via cd .. and repeat until .git appears.</p><h4>Step 2: Read the HEAD Pointer</h4><pre>type .git\HEAD</pre><p>What it does: Displays the content of the HEAD file. This tells us which branch name Git is currently assigned to.</p><p><strong>Expected Result:</strong></p><pre>ref: refs/heads/prod3</pre><p><em>(Note the branch name, e.g., </em>prod3<em>. This is your target.)</em></p><p><strong>Non-Expected Result:</strong></p><pre>fatal: Not a git repository</pre><p>Action: Re-evaluate Step 1.</p><h4>Step 3: Verify the Branch Reference Exists</h4><pre>dir .git\refs\heads</pre><p>What it does: Lists all local branch reference files.</p><p><strong>Expected Result:</strong></p><pre>Mode                 LastWriteTime         Length Name<br>-a----         8/19/2026   9:12 PM             41 prod3<br>-a----         8/19/2026   9:10 PM             41 main</pre><p><strong>Non-Expected Result:</strong> The specific branch is missing from the list.<br>Action: Proceed to Step 5 anyway; the reflog may still hold the data.</p><h4>Step 4: The Definitive Corruption Check</h4><pre>Get-Content .git\refs\heads\prod3 | Format-Hex</pre><p><em>(Replace </em>prod3<em> with the branch name found in Step 2.)</em></p><p>What it does: Reads the raw binary bytes of the branch reference file. We are looking for the cause of the fatal errors.</p><p><strong>Expected Result (Corruption Confirmed):</strong></p><pre>00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F<br>00000000   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................<br>00000010   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................<br>00000020   00 00 00 00 00 00 00 00 00 00                    ..........</pre><p><em>Interpretation:</em> The file is filled entirely with null bytes. This is the root cause.</p><p><strong>Non-Expected Result (File is already healthy):</strong></p><pre>00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F<br>00000000   1D 79 82 EA 7D D8 25 E8 1B F4 C7 A5 97 B6 57 4F  .y..}.%.......WO<br>00000010   D9 4E A5 30                                      .N.0</pre><p><em>Interpretation:</em> If the file contains a valid ASCII hex hash, your problem is different. Stop this protocol and investigate other causes.</p><h4>Step 5: Extract the Last Valid Commit Hash (The “Forensic Gold”)</h4><pre>Get-Content .git\logs\refs\heads\prod3</pre><p><em>(Replace </em>prod3<em> with your branch.)</em></p><p>What it does: Reads the reflog (diary) for this specific branch.</p><p><strong>Expected Result:</strong> A list of lines, each ending with a 40-character hash. Look at the last line. The final hash on that line is the commit we need.</p><p><strong><em>Example last line:</em></strong></p><pre>1d7982ea7dd825e81bf4c7a597b6574fd94ea530</pre><p>Critical: Copy this 40-character string and save it. This is your proof of life.</p><p><strong>Non-Expected Result:</strong> The file is empty or throws an error.<br>Action: If the local reflog is destroyed, try git reflog (global command). If that is empty, you must find the hash from your IDE history or remote server (git ls-remote origin prod3).</p><h4>Step 6: Verify the Commit Object Exists</h4><pre>git cat-file -t 1d7982ea7dd825e81bf4c7a597b6574fd94ea530</pre><p><em>(Replace with the hash found in Step 5.)</em></p><p>What it does: Asks the object database, “Is this hash valid and what type is it?”</p><p><strong>Expected Result:</strong></p><pre>commit</pre><p><em>Interpretation:</em> Your code is 100% intact. The corruption is purely a pointer issue.</p><p><strong>Non-Expected Result:</strong></p><pre>fatal: Not a valid object name 1d7982ea...</pre><p><em>Interpretation:</em> The commit itself is garbage-collected or missing. This would require advanced git reflog expire or recovery from a remote. (This did not happen in our validated scenario).</p><h3>Phase 2: Safety &amp; Write Operations (Based upon the success of Steps 1–6)</h3><h4>Step 7: Create the Safety Backup</h4><pre>Copy-Item .git .git_backup -Recurse</pre><p>What it does: Duplicates the entire .git folder before any mutations.</p><p><strong>Expected Result:</strong> A new folder named .git_backup appears next to your .git with identical timestamps.</p><p><strong>Non-Expected Result:</strong> Permission denied.<br>Action: Close Visual Studio Code, terminals, and file explorer windows that might have locks on .git. Retry as Administrator.</p><h4>Step 8: Suture the Broken Branch Reference</h4><pre>Set-Content .git\refs\heads\prod3 &quot;1d7982ea7dd825e81bf4c7a597b6574fd94ea530&quot;</pre><p><em>(Replace branch and hash accordingly.)</em></p><p>What it does: Overwrites the null bytes in the branch reference file with the valid commit hash we verified in Step 6.</p><p><strong>Expected Result:</strong> No output. The file is repaired.</p><p><strong>Verification:</strong></p><pre>Get-Content .git\refs\heads\prod3</pre><p>Should now output the 40-character hash.</p><h4>Step 9: Verify Local Recovery</h4><pre>git branch<br>git status</pre><p>What it does: Tests if the core Git functions are operational again.</p><p><strong>Expected Result:</strong></p><pre>* prod3</pre><p>and</p><pre>On branch prod3<br>nothing to commit, working tree clean</pre><p><strong>Non-Expected Result:</strong> If git branch still fails, double-check that HEAD points to the exact name you repaired. Use type .git\HEAD to confirm.</p><h4>Step 10: Rescue the Remote-Tracking Reference</h4><pre>Get-Content .git\refs\remotes\origin\prod3 | Format-Hex</pre><p><em>(Replace with branch name.)</em></p><p>What it does: Inspects the file that tracks the remote origin/prod3.</p><p><strong>Expected Result (Corrupted):</strong> Null bytes 00 00....<br>Action: Delete the broken file:</p><pre>Remove-Item .git\refs\remotes\origin\prod3</pre><p>Now, recreate it safely via a read-only network call:</p><pre>git fetch origin</pre><p>What git fetch does: Contacts the remote server, reads the current prod3 hash, and writes a fresh, valid reference file to .git/refs/remotes/origin/prod3.</p><p><strong>Expected Result:</strong></p><pre>* [new branch]      prod3 -&gt; origin/prod3</pre><h4>Step 11: Eradicate the Corrupted ORIG_HEAD</h4><pre>Get-Content .git\ORIG_HEAD | Format-Hex</pre><p>What it does: Checks the temporary safety file.</p><p><strong>Expected Result (Corrupted):</strong> Null bytes.<br>Action: Delete it. ORIG_HEAD is a transient marker. Git creates it on-demand.</p><pre>Remove-Item .git\ORIG_HEAD</pre><h3>Phase 3: System-Wide Integrity Scan</h3><h4>Step 12: Run the Full File System Check</h4><pre>git fsck --full</pre><p>What it does: Thoroughly verifies the SHA-1 checksums and connectivity of every object in your database.</p><p><strong>Expected Result:</strong> You may see lines like:</p><pre>dangling blob 4a2b3c...<br>dangling commit 5b6c7d...</pre><p><em>Interpretation:</em> These are dangling objects — historical debris left behind by resets or amendments. They are not corruption and can be safely ignored or cleaned later with git gc.</p><p><strong>Non-Expected Result (Serious Danger):</strong></p><pre>missing blob 123abc...<br>corrupt loose object ...<br>fatal: error in object</pre><p><em>Interpretation:</em> If you see these, your object database is physically damaged. This protocol does not cover that scenario, and you would need to restore from a remote.</p><p><strong>Final Verification Filter:</strong></p><pre>git fsck --full | findstr /i &quot;error missing corrupt fatal&quot;</pre><p>This filters out “dangling” noise. A healthy output returns nothing.</p><h4>Step 13: The Ultimate Functional Test</h4><pre>git status<br>git fetch origin<br>git pull<br>git log --oneline -5</pre><p>What it does: Simulates a normal developer workflow to confirm all systems are green.</p><p><strong>Expected Results:</strong></p><ul><li>git status → On branch prod3 Your branch is up to date with &#39;origin/prod3&#39;.</li><li>git pull → Already up to date.</li><li>git log → Shows the 5 most recent commits, including the one we recovered.</li></ul><h3>The “Zero-Prompt” Automation Master Prompt</h3><p>This guide is designed to be executable by an AI agent without requiring constant user intervention. Below is the exact prompt you can paste into any LLM along with attaching this file or pasting its contents. The agent will run the entire workflow from start to finish, deriving branch names and hashes on the fly, and will not stop to ask you clarifying questions.</p><p><strong>Save it into a file and attached it to the chat and type “see this”</strong></p><pre>Agent Instructions: Git Ref Corruption Recovery (Autonomous Mode)<br><br>Trigger: When the user types &quot;see this&quot; and attaches this file, execute the full procedure below immediately, in order, without pausing to ask clarifying questions. Only stop and report to the user if a critical, unrecoverable error is encountered (defined below).<br><br>---<br><br>GROUND RULES (Do Not Violate)<br><br>- Do NOT ask the user which branch, which repo, or for confirmation before each step. Detect everything dynamically from the repository itself (HEAD file, reflog, etc.).<br>- ALWAYS create a safety backup before any destructive or write action.<br>- If a value like a commit hash or branch name is needed, extract it from the repo output in the prior command. Never prompt the user for it.<br>- If a command&#39;s actual output diverges from what is expected, treat that as a signal to inspect further using the built-in fallback logic defined in this doc. Do NOT halt and ask the user what to do.<br>- Only escalate (stop and report to the user) if:<br>  1. The `.git` repository cannot be located at all.<br>  2. `git fsck --full` reveals corruption beyond simple null-byte ref files, such as missing blobs, commits, or trees that cannot be recovered from reflog or remote.<br>  3. A destructive step (like removing a ref) would delete the only known copy of a commit that is not recoverable from the reflog or remote.<br><br>---<br><br>EXECUTION PIPELINE (Run This Entire Sequence Autonomously)<br><br>1.  **Locate the Repository**<br>    Run `dir .git`. If the folder is missing, run `cd ..` and repeat `dir .git` until found. If you reach the root of the drive and still cannot find `.git`, stop and tell the user: &quot;FATAL: No .git directory could be located in this or any parent directory.&quot;<br><br>2.  **Verify the Symptoms**<br>    Run `git branch`, `git status`, and `git pull`. Note any occurrence of the following fatal errors: `Failed to resolve HEAD as a valid ref`, `ambiguous argument &#39;HEAD&#39;`, `update_ref failed for ref &#39;ORIG_HEAD&#39;`, `reference broken`, or `invalid sha1 pointer 0000...0000`. If none of these appear, the repo may not need repair—skip to the final verification (Section 9) to confirm.<br><br>3.  **Read HEAD and Derive the Target Branch**<br>    Run `type .git\HEAD`. Parse the output to extract the branch name. For example, if the output is `ref: refs/heads/prod3`, set your target branch to `prod3`. If HEAD is detached (shows a commit hash directly), stop and tell the user: &quot;FATAL: HEAD is detached. This recovery method assumes a branch reference is corrupt. Please attach to a branch manually.&quot;<br><br>4.  **Check if the Branch Reference File Exists**<br>    Run `dir .git\refs\heads` and look for a file matching your derived branch name. If the file is missing, do not panic—the reflog may still have the commit. Proceed directly to inspecting the reflog in the next step.<br><br>5.  **Inspect the Branch Reference File for Null-Byte Corruption**<br>    Run `Get-Content .git\refs\heads\&lt;branch&gt;` (replace `&lt;branch&gt;` with the name derived in Step 3). If the output is blank or suspicious, run `Get-Content .git\refs\heads\&lt;branch&gt; | Format-Hex`.<br>    - A **healthy** file shows a 40-character SHA-1 hash (e.g., `1d7982ea...`). If healthy, skip the repair and jump to Section 6 (Remote Check).<br>    - A **corrupted** file shows all null bytes (`00 00 00...`). This confirms the issue. You are now authorized to perform the repair.<br><br>6.  **Recover the Last Valid Commit from the Reflog**<br>    Run `Get-Content .git\logs\refs\heads\&lt;branch&gt;`. Look at the **last line** of this output. The final 40-character string on that line is your lost commit hash. Save this hash immediately. If the reflog is empty or missing, check the remote: run `git ls-remote --heads origin &lt;branch&gt;` and grab the hash from there. If neither the reflog nor the remote provide a hash, stop and report: &quot;FATAL: No commit hash found in reflog or remote. Recovery impossible via this method.&quot;<br><br>7.  **Verify the Recovered Commit Object Exists**<br>    Run `git cat-file -t &lt;hash&gt;` (replace `&lt;hash&gt;` with the one found in Step 6). <br>    - If the output is `commit`, your data is completely intact. Proceed immediately.<br>    - If the output is anything else (error, `missing`, `fatal`), the commit is unrecoverable locally. Check the remote: if `git ls-remote --heads origin &lt;branch&gt;` returns a valid hash, use that hash instead. If the remote also fails, stop and tell the user: &quot;FATAL: The commit object is missing and cannot be recovered from remote.&quot;<br><br>8.  **Create the Safety Backup (Before Any Writes)**<br>    Run `Copy-Item .git .git_backup -Recurse`. This is your absolute parachute. Do not proceed without confirming this completes successfully.<br><br>9.  **Repair the Broken Branch Reference**<br>    Run `Set-Content .git\refs\heads\&lt;branch&gt; &quot;&lt;hash&gt;&quot;` using the valid hash confirmed in Step 7. This overwrites the null bytes with the correct pointer. <br><br>10. **Verify Local Recovery**<br>    Run `git branch`, `git status`, and `git log --oneline -5`. <br>    - You should see your branch listed, `HEAD -&gt; &lt;branch&gt;` in the log, and a clean status.<br>    - If `git branch` still fails, double-check that `.git\HEAD` contains exactly `ref: refs/heads/&lt;branch&gt;` and correct it with `Set-Content .git\HEAD &quot;ref: refs/heads/&lt;branch&gt;&quot;` if necessary.<br><br>11. **Handle Remote Tracking References**<br>    Check the remote tracking file: run `Get-Content .git\refs\remotes\origin\&lt;branch&gt; | Format-Hex`.<br>    - If it contains null bytes (`00 00...`), delete it immediately: `Remove-Item .git\refs\remotes\origin\&lt;branch&gt;`.<br>    - After deleting, run `git fetch origin`. This contacts the remote server (read-only) and recreates a fresh, valid remote-tracking reference. Confirm the output shows `[new branch] &lt;branch&gt; -&gt; origin/&lt;branch&gt;`.<br><br>12. **Repair ORIG_HEAD (If It Was Throwing Errors)**<br>    Check the file: `Get-Content .git\ORIG_HEAD | Format-Hex`.<br>    - If it is corrupted (null bytes), delete it with `Remove-Item .git\ORIG_HEAD`. ORIG_HEAD is a temporary safety marker—deleting it is safe, and Git will recreate it when needed. <br>    - Verify the fix by running `git pull`. It should output `Already up to date.`<br><br>13. **Find and Repair Any Remaining Corrupted Refs**<br>    Run `git fsck --full`. Scan the output for lines containing `invalid sha1 pointer 0000000000000000000000000000000000000000`.<br>    - For each such line, it will mention a specific file path (e.g., `refs/heads/feature-x`). <br>    - For that branch, run `git ls-remote --heads origin feature-x` to get the correct commit hash from the remote.<br>    - Repair it by running `Set-Content .git\refs\heads\feature-x &quot;&lt;hash-from-remote&gt;&quot;`. <br>    - If the remote does not have that branch, check that branch&#39;s reflog (`Get-Content .git\logs\refs\heads\feature-x`) to find the hash. If neither works, skip that branch and note it in the final report.<br><br>14. **Run the Final Integrity Scan**<br>    Run `git fsck --full | findstr /i &quot;error missing corrupt fatal&quot;`. <br>    - This filter removes harmless &quot;dangling&quot; messages. If this command produces **no output**, your object database is structurally sound.<br>    - If it produces any output (e.g., `missing blob`, `corrupt loose object`), stop immediately and report: &quot;FATAL: Severe object corruption detected (missing blobs/commits). Manual intervention required.&quot; Do not proceed to cleanup.<br><br>15. **Perform Final Functional Tests**<br>    Run `git status`, `git fetch origin`, `git pull`, and `git log --oneline -5`. All commands must complete without fatal errors. `git pull` should return `Already up to date.`.<br><br>16. **Classify Remaining Dangling Objects (Ignore Them)**<br>    If you re-run `git fsck --full` and see `dangling blob` or `dangling tree`, ignore them completely. These are harmless remnants of previous operations and do not indicate active corruption. Only `missing`, `corrupt`, or `fatal` lines are serious.<br><br>17. **Cleanup (Optional Automation)**<br>    Once all success criteria (listed below) are met, run `Remove-Item .git_backup -Recurse -Force` to delete the backup. <br>    - If Windows blocks deletion, automatically attempt to close any open terminals/IDEs in the background. If that fails, report to the user: &quot;Backup folder `.git_backup` could not be deleted. Please close all applications and run the command as Administrator.&quot;<br><br>---<br><br>SUCCESS CRITERIA (Report This Checklist to the User)<br><br>After completing the pipeline, print the status of each of these items clearly:<br><br>- [x] `git status` works<br>- [x] `git branch` works<br>- [x] `git fetch origin` works<br>- [x] `git pull` works<br>- [x] `git log` works<br>- [x] `git fsck --full | findstr /i &quot;error missing corrupt fatal&quot;` returns no errors<br>- [x] Local branch matches remote branch<br>- [x] HEAD resolves correctly<br><br>Final Verdict: If all items are checked, output &quot;SUCCESS: Repository fully recovered.&quot; If any item fails, output &quot;PARTIAL RECOVERY: [List the failed item]&quot; or &quot;FAILURE: [Exact reason]&quot; and do not run the cleanup.<br><br>---<br><br>END OF INSTRUCTIONS</pre><h3>Success Criteria Checklist</h3><p>Before you walk away, ensure all of the following are true:</p><ul><li>git status does not throw fatal errors.</li><li>git branch shows your branch with an asterisk (*).</li><li>git fetch origin completes successfully.</li><li>git pull returns &quot;Already up to date&quot;.</li><li>git log --oneline -5 displays recent commits.</li><li>git fsck --full | findstr /i &quot;error missing corrupt fatal&quot; returns no lines.</li><li>Your local branch matches the remote branch hash (verify via git ls-remote origin prod3).</li></ul><h3>Remember this</h3><p>Git branches are just text files. Your code is stored safely in the object database, and your reflog is the forensic key to unlocking it. Corruption isn’t the end , it’s just a broken pointer.</p><p>This exact workflow was tested and proven on a real, production repository with zero data loss and zero remote impact. Bookmark this guide, share it with your team, and the next time you see ‘fatal: Failed to resolve HEAD’, you’ll just open this page and fix it in 5 minutes.</p><p>Trust the reflog, and always backup before you patch. Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db93c6a6290" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Byzantine Generals Problem and What Happened at Github]]></title>
            <link>https://medium.com/@ayushgupta228/the-byzantine-generals-problem-and-what-happened-at-github-788e9852ce15?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/788e9852ce15</guid>
            <category><![CDATA[byzantine-fault-tolerance]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:28:57 GMT</pubDate>
            <atom:updated>2026-06-12T03:36:05.544Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>You just fixed a bug where two honest users conflicted(my last article named <em>Escaping the Loop - A Systematic Approach to Debugging State and Dependency Cycles</em><strong>)</strong>. Do check it out if not have already. Now let me show you what happens when the system itself stops being honest - when a node doesn’t crash, but lies. The math changes. The fixes get uglier. And sometimes, you can’t fix it at all. You can only contain the damage.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4hl6I-wfhjtthZRmNxj7A.png" /><figcaption>It’s AI Generated</figcaption></figure><h3>The Example: A Flight Booking System Where Customers Get Double-Charged</h3><p>A travel booking site.</p><p><strong>The bug</strong>: Sometimes, customers get charged twice for the same flight. Not often. Maybe 1 in 10,000 bookings. But when it happens, it’s a massive charge. Customers notice. They call support. Support refunds. Company eats the loss.</p><p><strong>The setup</strong>: You have 3 microservices:</p><ul><li><strong><em>Booking </em></strong><em>Service</em>: Creates the reservation</li><li><strong><em>Payment</em></strong><em> Service</em>: Charges the card</li><li><strong><em>Notification </em></strong><em>Service</em>: Sends confirmation email</li></ul><p>Each service has its own database. They communicate via Kafka (event queue).</p><p>The bug appears after 6 months of perfect operation. Your team has tried everything: added retries, idempotency keys, distributed transactions. Nothing fixes it completely. It just happens less often.</p><h3>What Your Code Might Looks Like</h3><pre>// BookingService.java<br>public class BookingService {<br>    @EventListener<br>    public void handleBookingRequest(BookingRequest request) {<br>        // Create booking record<br>        Booking booking = new Booking(request);<br>        booking.save();  // status = PENDING<br>        <br>        // Publish event for payment<br>        kafka.send(&quot;payment-requests&quot;, new PaymentRequestEvent(booking.getId(), request.getAmount()));<br>        <br>        // Wait for payment confirmation<br>        waitForPaymentConfirmation(booking.getId(), 30000);<br>    }<br>    <br>    @KafkaListener(topics = &quot;payment-confirmations&quot;)<br>    public void onPaymentConfirmed(PaymentConfirmationEvent event) {<br>        Booking booking = Booking.findById(event.getBookingId());<br>        booking.setStatus(&quot;CONFIRMED&quot;);<br>        booking.save();<br>        <br>        // Publish event for notification<br>        kafka.send(&quot;notification-requests&quot;, new NotificationRequestEvent(booking.getId()));<br>    }<br>}<br><br>// PaymentService.java<br>public class PaymentService {<br>    @KafkaListener(topics = &quot;payment-requests&quot;)<br>    public void handlePaymentRequest(PaymentRequestEvent event) {<br>        // Check if already processed (idempotency)<br>        if (processedIds.contains(event.getId())) {<br>            return;<br>        }<br>        <br>        // Charge the card<br>        boolean success = paymentGateway.charge(event.getAmount());<br>        <br>        if (success) {<br>            processedIds.add(event.getId());<br>            kafka.send(&quot;payment-confirmations&quot;, new PaymentConfirmationEvent(event.getBookingId()));<br>        } else {<br>            kafka.send(&quot;payment-failures&quot;, new PaymentFailureEvent(event.getBookingId()));<br>        }<br>    }<br>}</pre><p>What’s wrong? On paper, nothing. Idempotency keys prevent double charges. Kafka guarantees at-least-once delivery. But double charges still happen.</p><h3>What “Byzantine Failure” Actually Means (No Jargon)</h3><p>In 1982, Leslie Lamport published a paper called “The Byzantine Generals Problem.” The title came from a thought experiment:</p><p><em>Imagine several generals surround a city. They must all attack at the same time or all retreat. They can only communicate by messenger. Some generals might be traitors - they’ll send false messages to break coordination. How do the loyal generals still agree?</em></p><p><strong>The kicker</strong>: Lamport later admitted he chose “Byzantine” because it sounded exotic. He wanted to avoid offending anyone by naming it after a real country. The problem he described wasn’t new - it’s the same problem that breaks voting systems, blockchain, and your microservices.</p><p><em>The mathematical result (important): To tolerate </em><em>f traitors (or faulty nodes), you need at least </em><em>3f + 1 total nodes.</em></p><ul><li>To survive 1 traitor -&gt; 4 nodes minimum</li><li>To survive 2 traitors -&gt; 7 nodes minimum</li><li>To survive 3 traitors -&gt; 10 nodes minimum</li></ul><p>Why <strong>3f+1</strong>? Here’s the actual proof in simple terms:</p><p>With 3 nodes and 1 traitor:</p><ul><li>Node A (loyal) hears “attack” from commander</li><li>Node B (loyal) hears “retreat” from commander</li><li>A tells B: “commander said attack”</li><li>B tells A: “commander said retreat”</li><li>A thinks: “Commander told me attack, but B says commander said retreat. Is B lying or is commander lying?”</li><li>A cannot know. Agreement impossible.</li></ul><p>With 4 nodes and 1 traitor:</p><ul><li>Nodes A, B, C (loyal) hear various things</li><li>After two rounds of messaging, each loyal node has 3 reports</li><li>The traitor’s lies are outvoted 2-to-1 (or 3-to-0)</li><li>Loyal nodes can agree on the majority</li></ul><h3>How This Applies To Your Double-Charge Bug</h3><p>Your system has 3 services (Booking, Payment, Notification). That’s exactly the 3-generals case. If one service has a bug (acts like a traitor), Byzantine agreement is mathematically impossible.</p><p>The actual bug in your system (discovered after 3 weeks of debugging):</p><p>The Payment Service has a bug: sometimes it processes the same <strong>payment-requests</strong> event twice. The idempotency check-<strong>processedIds.contains(event.getId()</strong>) should prevent this, but <strong>processedIds </strong>is an in-memory HashSet. When the service restarts (which happens during deployments), the set is empty.</p><p>The sequence that causes double charge:</p><ol><li>Payment Service receives event evt_123.</li><li>Processes it, charges card, adds evt_123 to processedIds.</li><li>Before sending payment-confirmations, the service crashes (out of memory, network blip, whatever).</li><li>Kafka hasn’t received acknowledgment yet, so it redelivers evt_123.</li><li>Service restarts, processedIds is empty.</li><li>Service processes evt_123 again, charges card again.</li><li>Booking Service receives TWO payment-confirmations for the same booking.</li><li>Booking Service updates status to CONFIRMED twice (harmless).</li><li>Customer is charged twice. Refund process starts. Support gets angry call.</li></ol><p>From the perspective of Booking Service: The Payment Service looks Byzantine. It sent two confirmations for the same request. Is it lying? Is it buggy? Is the network duplicating messages? Booking Service cannot know.</p><h3>The Real Solution: Practical Byzantine Fault Tolerance (PBFT)</h3><p>In 1999, <strong>Miguel Castro</strong> and <strong>Barbara Liskov</strong> (MIT) published PBFT - the first practical algorithm for Byzantine agreement. It works for your microservices too.</p><p><strong>The key insight</strong>: Don’t trust a single service. Ask multiple services and compare answers.</p><p>For our booking system:</p><pre>// Instead of 1 payment service, run 4 replicas (3f+1 where f=1)<br>// When Booking Service needs to charge a card, it asks all 4 replicas<br><br>public class ByzantineResilientBookingService {<br>    private static final int TOTAL_REPLICAS = 4;<br>    private static final int REQUIRED_AGREEMENT = 3;  // 2f+1<br>    <br>    public void chargeCustomer(String bookingId, BigDecimal amount) {<br>        // Phase 1: Request (send to all replicas)<br>        ChargeRequest request = new ChargeRequest(bookingId, amount, generateNonce());<br>        List&lt;Future&lt;ChargeResponse&gt;&gt; futures = new ArrayList&lt;&gt;();<br>        <br>        for (int i = 0; i &lt; TOTAL_REPLICAS; i++) {<br>            futures.add(sendToReplica(i, request));<br>        }<br>        <br>        // Phase 2: Collect responses<br>        Map&lt;String, List&lt;ChargeResponse&gt;&gt; responsesByResult = new HashMap&lt;&gt;();<br>        for (Future&lt;ChargeResponse&gt; future : futures) {<br>            ChargeResponse resp = future.get(5, TimeUnit.SECONDS);<br>            String key = resp.isSuccess() + &quot;:&quot; + resp.getTransactionId();<br>            responsesByResult.computeIfAbsent(key, k -&gt; new ArrayList&lt;&gt;()).add(resp);<br>        }<br>        <br>        // Phase 3: Find majority<br>        for (Map.Entry&lt;String, List&lt;ChargeResponse&gt;&gt; entry : responsesByResult.entrySet()) {<br>            if (entry.getValue().size() &gt;= REQUIRED_AGREEMENT) {<br>                // We have consensus<br>                ChargeResponse consensus = entry.getValue().get(0);<br>                if (consensus.isSuccess()) {<br>                    booking.setStatus(&quot;CONFIRMED&quot;);<br>                    booking.setTransactionId(consensus.getTransactionId());<br>                } else {<br>                    booking.setStatus(&quot;FAILED&quot;);<br>                }<br>                booking.save();<br>                return;<br>            }<br>        }<br>        <br>        // No consensus - possible Byzantine failure<br>        throw new ByzantineFailureException(&quot;Payment replicas cannot agree: &quot; + responsesByResult);<br>    }<br>}</pre><p><strong>How this prevents double charge</strong>: Even if one replica is buggy (or malicious) and sends two confirmations, the other three loyal replicas will send only one. The majority vote (3 out of 4) will be correct.</p><p><strong>The cost</strong>: 4x the infrastructure. 4x the network messages. <strong>O(n²)</strong> message complexity. For each charge, you send 4 requests and receive 4 responses = 16 messages total. With 1 replica, you send 1 request and get 1 response = 2 messages. PBFT is 8x more chatty.</p><p><strong>This is why most companies don’t run PBFT</strong>. They accept the occasional double charge and refund it. <em>The math says you can’t have both low cost and Byzantine fault tolerance</em>. <em>You have to choose</em>.</p><h3>The GitHub Outage (June 10, 2026) - A Real-World Byzantine-Like Failure</h3><p><strong>What GitHub reported</strong>: “Erroneous 401 responses causing app integrations to trigger authentication flows.”</p><p><strong>What actually happened </strong>(reconstructed from public post-mortems):</p><p>GitHub’s authentication system has a cache. The cache has multiple replicas for performance. On June 10, one replica started returning stale data. Specifically:</p><ul><li>Replica A: returns correct token status</li><li>Replica B: returns stale “token invalid” for tokens that are actually valid</li><li>Replica C: returns correct token status</li><li>Replica D: returns correct token status</li></ul><p><strong>To a client that happens to talk to Replica B</strong>: The auth system is broken. It says my token is invalid but it’s not.<br><strong>To a client that talks to Replica A</strong>: The auth system is fine.</p><p><strong>This is not Byzantine</strong>. No one is malicious. But the effect is identical to Byzantine failure: different clients receive conflicting information from the same system.</p><p><strong>The cascading failure</strong>:</p><ol><li>Clients that hit Replica B get 401</li><li>They correctly re-authenticate (OAuth spec says: on 401, refresh token)</li><li>Thousands of clients simultaneously hit the auth endpoint</li><li>The auth endpoint, already under stress, gets overloaded</li><li>More timeouts, more retries, more 401s</li><li>The good replicas start timing out too</li><li>Eventually, all clients see failures</li></ol><p><strong>The fix GitHub applied</strong> (<em>from their status page</em>):</p><ul><li>Added circuit breakers to their client SDKs</li><li>Implemented exponential backoff with jitter</li><li>Added client-side caching of auth failures</li></ul><p><strong>The fix that would have prevented it</strong> (Byzantine-style):</p><ul><li>Run 4 auth replicas (instead of 2)</li><li>Make clients query at least 3 replicas and take majority</li><li>If 2 say “valid” and 1 says “invalid”, trust the majority</li></ul><p><em>But GitHub didn’t do this.</em> <strong>Why</strong>? Cost. 4 replicas vs 2 means double the infrastructure. Quorum reads mean 3x the network traffic. For a company GitHub’s size, that’s millions of dollars per year. They accepted the risk of a 80-minute outage every few years instead.</p><p>Now, I<strong><em>f this resonated with you, share it with someone who might enjoy it too.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788e9852ce15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Escaping the Loop - A Systematic Approach to Debugging State and Dependency Cycles]]></title>
            <link>https://medium.com/@ayushgupta228/escaping-the-loop-a-systematic-approach-to-debugging-state-and-dependency-cycles-32454feef945?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/32454feef945</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 08:20:48 GMT</pubDate>
            <atom:updated>2026-06-11T08:20:48.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Example: A Document Editor That Corrupts Files When Two People Edit Together</h3><p>A legal tech startup. Lawyers edit contracts together in real-time. Like Google Docs but for legal clauses.</p><p><strong>The bug</strong>: When two lawyers edit the same contract section within 2 seconds of each other, the document saves but half the clauses disappear. No error message. No crash. Just… gone. Lawyers notice 20 minutes later. Panic ensues.</p><p><strong>The setup</strong>: You’re a backend dev. You didn’t build the collaboration feature. The senior who did quit 3 months ago. You have no documentation. Your manager says “just fix it”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*labtjAoFnWs0lU9HPRwBVg.png" /><figcaption>Of Course it’s AI generated, but it’s cool right??</figcaption></figure><h3>The Actual Code (What You Inherited)</h3><pre>// DocumentCollaboration.java<br>public class DocumentCollaboration {<br>    private Map&lt;String, Document&gt; docs = new ConcurrentHashMap&lt;&gt;();<br>    private Map&lt;String, Set&lt;String&gt;&gt; activeEditors = new HashMap&lt;&gt;();<br>    private Map&lt;String, Queue&lt;Edit&gt;&gt; pendingEdits = new HashMap&lt;&gt;();<br>    <br>    public void applyEdit(String docId, String userId, Edit edit) {<br>        // Get or create edit queue<br>        Queue&lt;Edit&gt; queue = pendingEdits.computeIfAbsent(docId, k -&gt; new LinkedList&lt;&gt;());<br>        <br>        // Add edit to queue<br>        queue.add(edit);<br>        <br>        // If this user is the only editor, apply immediately<br>        Set&lt;String&gt; editors = activeEditors.get(docId);<br>        if (editors != null &amp;&amp; editors.size() == 1 &amp;&amp; editors.contains(userId)) {<br>            processQueue(docId);<br>        }<br>    }<br>    <br>    private void processQueue(String docId) {<br>        Document doc = docs.get(docId);<br>        Queue&lt;Edit&gt; queue = pendingEdits.get(docId);<br>        <br>        while (!queue.isEmpty()) {<br>            Edit edit = queue.poll();<br>            // Apply edit to document<br>            doc.apply(edit);<br>        }<br>        <br>        saveToDatabase(doc);<br>    }<br>    <br>    public void joinDocument(String docId, String userId) {<br>        activeEditors.computeIfAbsent(docId, k -&gt; new HashSet&lt;&gt;()).add(userId);<br>    }<br>    <br>    public void leaveDocument(String docId, String userId) {<br>        Set&lt;String&gt; editors = activeEditors.get(docId);<br>        if (editors != null) {<br>            editors.remove(userId);<br>            if (editors.isEmpty()) {<br>                // Last editor left, flush any pending edits<br>                processQueue(docId);<br>            }<br>        }<br>    }<br>}</pre><p>Looks <strong>reasonable</strong>? That’s what you thought too.</p><h3>What You Try First (The 16-Hour Guess Loop)</h3><p>Monday 9 AM: Bug report comes in. You add logs:</p><pre>System.out.println(&quot;Editors in &quot; + docId + &quot;: &quot; + activeEditors.get(docId));<br>System.out.println(&quot;Queue size: &quot; + pendingEdits.get(docId).size());</pre><p>Test it manually. Can’t reproduce. Works fine.</p><p>Monday 2 PM: You write a stress test. 10 users, 100 edits each. Still works.</p><p>Monday 6 PM: You realize the bug only happens when edits happen within 2 seconds of each other. You add Thread.sleep() to your test. Still can’t reproduce.</p><p>Tuesday 10 AM: You give up on reproducing. You stare at the code for 3 hours. Nothing.</p><p>Tuesday 2 PM: You rewrite the entire collaboration logic. Tests pass. You deploy to staging. Bug still happens.</p><p>Tuesday 6 PM: Your manager asks for an update. You say “still investigating.”</p><p>Wednesday 10 AM: You finally dump the actual production state during a corruption event. You see the bug.</p><h3>Phase 1: Deterministic Isolation (What Actually Worked)</h3><p>You wrote a script to capture the state of one document right after a corruption:</p><pre>// CaptureState.java - Run on production when bug happens<br>public class CaptureState {<br>    public static void main(String[] args) {<br>        String docId = args[0];<br>        DocumentCollaboration collab = getCollaborationFromProduction();<br>        <br>        Map&lt;String, Object&gt; state = new HashMap&lt;&gt;();<br>        state.put(&quot;activeEditors&quot;, collab.activeEditors.get(docId));<br>        state.put(&quot;pendingEdits&quot;, collab.pendingEdits.get(docId));<br>        state.put(&quot;documentContent&quot;, collab.docs.get(docId).getContent());<br>        state.put(&quot;documentVersion&quot;, collab.docs.get(docId).getVersion());<br>        <br>        System.out.println(JsonUtils.prettyPrint(state));<br>    }<br>}</pre><p>The output when bug happened:</p><pre>{<br>  &quot;activeEditors&quot;: [&quot;user_42&quot;, &quot;user_99&quot;],<br>  &quot;pendingEdits&quot;: [<br>    {&quot;type&quot;: &quot;insert&quot;, &quot;position&quot;: 100, &quot;text&quot;: &quot;indemnification clause&quot;, &quot;userId&quot;: &quot;user_42&quot;},<br>    {&quot;type&quot;: &quot;insert&quot;, &quot;position&quot;: 100, &quot;text&quot;: &quot;liability waiver&quot;, &quot;userId&quot;: &quot;user_99&quot;}<br>  ],<br>  &quot;documentContent&quot;: &quot;...partial text...&quot;,<br>  &quot;documentVersion&quot;: 14<br>}</pre><p>The clue: Two pending edits at the SAME position. But the code should apply them one after another. Why are they both pending?</p><p>You wrote a unit test that hardcodes this exact state:</p><pre>@Test<br>public void testConcurrentEditsAtSamePosition() {<br>    DocumentCollaboration collab = new DocumentCollaboration();<br>    String docId = &quot;test_doc&quot;;<br>    Document doc = new Document(&quot;original text here...&quot;);<br>    collab.docs.put(docId, doc);<br>    <br>    // Simulate two users already in the doc<br>    collab.joinDocument(docId, &quot;user_42&quot;);<br>    collab.joinDocument(docId, &quot;user_99&quot;);<br>    <br>    // Both edit at the same position within milliseconds<br>    Edit edit1 = new Edit(&quot;insert&quot;, 100, &quot;indemnification clause&quot;, &quot;user_42&quot;);<br>    Edit edit2 = new Edit(&quot;insert&quot;, 100, &quot;liability waiver&quot;, &quot;user_99&quot;);<br>    <br>    // Apply edits in separate threads to simulate real timing<br>    Thread t1 = new Thread(() -&gt; collab.applyEdit(docId, &quot;user_42&quot;, edit1));<br>    Thread t2 = new Thread(() -&gt; collab.applyEdit(docId, &quot;user_99&quot;, edit2));<br>    <br>    t1.start();<br>    t2.start();<br>    t1.join();<br>    t2.join();<br>    <br>    // Both edits should be applied<br>    assertTrue(doc.getContent().contains(&quot;indemnification clause&quot;));<br>    assertTrue(doc.getContent().contains(&quot;liability waiver&quot;));<br>}</pre><p>Run this test. It fails 50% of the time. You have a reproduction that runs in 0.1 seconds. Finally.</p><h3>Phase 2: The Invariants (Written as Assertions)</h3><p>You write down what must NEVER be true:</p><pre>public class DocumentInvariants {<br>    // Invariant 1: No two pending edits should have the same position AND same type<br>    public static void noDuplicatePositionEdits(Queue&lt;Edit&gt; queue) {<br>        Map&lt;String, Set&lt;Integer&gt;&gt; seen = new HashMap&lt;&gt;();<br>        for (Edit e : queue) {<br>            String key = e.getType() + &quot;:&quot; + e.getPosition();<br>            if (seen.containsKey(key)) {<br>                throw new IllegalStateException(<br>                    &quot;Two &quot; + e.getType() + &quot; edits at position &quot; + e.getPosition() + <br>                    &quot; from users &quot; + seen.get(key) + &quot; and &quot; + e.getUserId()<br>                );<br>            }<br>            seen.put(key, e.getUserId());<br>        }<br>    }<br>    <br>    // Invariant 2: Active editors set must match the users who have pending edits in queue<br>    public static void editorsMatchPendingEdits(Set&lt;String&gt; activeEditors, Queue&lt;Edit&gt; pendingEdits) {<br>        Set&lt;String&gt; editorsWithPending = pendingEdits.stream()<br>            .map(Edit::getUserId)<br>            .collect(Collectors.toSet());<br>        <br>        // Every user with a pending edit should be an active editor<br>        for (String userId : editorsWithPending) {<br>            if (!activeEditors.contains(userId)) {<br>                throw new IllegalStateException(<br>                    &quot;User &quot; + userId + &quot; has pending edit but is not active&quot;<br>                );<br>            }<br>        }<br>    }<br>    <br>    // Invariant 3: Document version should increase with each successful edit<br>    public static void versionMonotonic(Document doc, int previousVersion) {<br>        if (doc.getVersion() &lt;= previousVersion) {<br>            throw new IllegalStateException(<br>                &quot;Version didn&#39;t increase: was &quot; + previousVersion + <br>                &quot;, now &quot; + doc.getVersion()<br>            );<br>        }<br>    }<br>}</pre><p>Add them to your code:</p><pre>public void applyEdit(String docId, String userId, Edit edit) {<br>    Queue&lt;Edit&gt; queue = pendingEdits.computeIfAbsent(docId, k -&gt; new LinkedList&lt;&gt;());<br>    <br>    // Invariant check before mutation<br>    Set&lt;String&gt; editors = activeEditors.get(docId);<br>    DocumentInvariants.editorsMatchPendingEdits(editors, queue);<br>    <br>    queue.add(edit);<br>    <br>    // Check again after add<br>    DocumentInvariants.noDuplicatePositionEdits(queue);<br>    <br>    // ... rest of logic<br>}</pre><p>Now when the bug happens, you get an exception immediately instead of corrupted document.</p><h3>Phase 3: The Golden Rule (Where The Bug Actually Lives)</h3><p>You run your test with invariants enabled. The exception hits: “Two insert edits at position 100 from user_42 and user_99”.</p><p>Why does this happen? Look at <strong>applyEdit </strong>again:</p><pre>public void applyEdit(String docId, String userId, Edit edit) {<br>    Queue&lt;Edit&gt; queue = pendingEdits.computeIfAbsent(docId, k -&gt; new LinkedList&lt;&gt;());<br>    queue.add(edit);  // ← OBSERVATION: queue now has two edits<br>    <br>    // DECISION based on activeEditors (which is SEPARATE state)<br>    Set&lt;String&gt; editors = activeEditors.get(docId);<br>    if (editors != null &amp;&amp; editors.size() == 1 &amp;&amp; editors.contains(userId)) {<br>        processQueue(docId);  // ← MUTATION: applies edits<br>    }<br>}</pre><p>The problem: The decision to process the queue depends on <strong>activeEditors</strong>, but the queue itself is mutated separately. Here&#39;s the race:</p><ol><li>User A adds edit -&gt; queue size = 1, editors = {A, B} -&gt; condition false (size=2)</li><li>User B adds edit -&gt; queue size = 2, editors = {A, B} -&gt; condition false (still size=2)</li><li>User A leaves -&gt; editors = {B} but NO ONE processes the queue</li><li>User B leaves -&gt; editors = {} -&gt; processQueue runs</li><li><strong>processQueue </strong>applies both edits at position 100 -&gt; the second edit overwrites the first</li></ol><p>The fix with baseline capture:</p><pre>public void applyEdit(String docId, String userId, Edit edit) {<br>    // STEP 1: CAPTURE BASELINE (copy current state)<br>    Set&lt;String&gt; baselineEditors = new HashSet&lt;&gt;(activeEditors.getOrDefault(docId, Collections.emptySet()));<br>    Queue&lt;Edit&gt; baselineQueue = new LinkedList&lt;&gt;(pendingEdits.getOrDefault(docId, Collections.emptyQueue()));<br>    int baselineQueueSize = baselineQueue.size();<br>    <br>    // STEP 2: DECIDE based on baseline, not live state<br>    boolean shouldProcessNow = (baselineEditors.size() == 1 &amp;&amp; baselineEditors.contains(userId));<br>    <br>    // STEP 3: MUTATE (only after decision)<br>    Queue&lt;Edit&gt; queue = pendingEdits.computeIfAbsent(docId, k -&gt; new LinkedList&lt;&gt;());<br>    queue.add(edit);<br>    <br>    // Check invariants on the new state<br>    DocumentInvariants.noDuplicatePositionEdits(queue);<br>    <br>    if (shouldProcessNow) {<br>        // But wait — the editor set might have changed since baseline<br>        Set&lt;String&gt; currentEditors = activeEditors.get(docId);<br>        if (currentEditors != null &amp;&amp; currentEditors.size() == 1 &amp;&amp; currentEditors.contains(userId)) {<br>            processQueue(docId);<br>        } else {<br>            // Schedule a delayed process instead of losing edits<br>            scheduleDelayedProcess(docId, 100);<br>        }<br>    }<br>}</pre><p>But the real fix is bigger: The design is wrong. You can’t base processing decisions on <strong>activeEditors </strong>because that set changes independently. The proper fix:</p><pre>public void applyEdit(String docId, String userId, Edit edit) {<br>    // Instead of conditionally processing, ALWAYS queue and have a separate flusher<br>    Queue&lt;Edit&gt; queue = pendingEdits.computeIfAbsent(docId, k -&gt; new ConcurrentLinkedQueue&lt;&gt;());<br>    queue.add(edit);<br>    <br>    // Signal that there&#39;s work to do (non-blocking)<br>    processingSignal.signal(docId);<br>}<br>// Background thread that processes queues safely<br>private void backgroundProcessor() {<br>    while (true) {<br>        String docId = processingSignal.waitForWork(1000);  // 1 second timeout<br>        if (docId != null) {<br>            processQueueSafely(docId);<br>        }<br>    }<br>}<br>private void processQueueSafely(String docId) {<br>    synchronized (docLock(docId)) {<br>        Document doc = docs.get(docId);<br>        Queue&lt;Edit&gt; queue = pendingEdits.get(docId);<br>        <br>        if (queue == null || queue.isEmpty()) {<br>            return;<br>        }<br>        <br>        // Capture baseline version before applying<br>        int versionBefore = doc.getVersion();<br>        <br>        // Apply edits in order, handling conflicts<br>        List&lt;Edit&gt; appliedEdits = new ArrayList&lt;&gt;();<br>        while (!queue.isEmpty()) {<br>            Edit edit = queue.poll();<br>            <br>            // Check if position is still valid (document might have changed)<br>            int adjustedPosition = resolveConflict(edit, doc);<br>            edit.setPosition(adjustedPosition);<br>            <br>            doc.apply(edit);<br>            appliedEdits.add(edit);<br>        }<br>        <br>        // Invariant: version increased<br>        DocumentInvariants.versionMonotonic(doc, versionBefore);<br>        <br>        saveToDatabase(doc);<br>        broadcastEdits(docId, appliedEdits);<br>    }<br>}</pre><h3>Phase 4: Circuit Breaker (Stop Making It Worse)</h3><p>When conflicts happen repeatedly for the same document, you need to slow down:</p><pre>public class DocumentCollaboration {<br>    private final Map&lt;String, CircuitBreaker&gt; docCircuitBreakers = new ConcurrentHashMap&lt;&gt;();<br>    private static final int CONFLICT_THRESHOLD = 5;<br>    private static final long CIRCUIT_OPEN_MS = 60000;<br>    <br>    private void resolveConflictAndApply(String docId, Edit edit, Document doc) {<br>        CircuitBreaker cb = docCircuitBreakers.computeIfAbsent(docId, <br>            k -&gt; new CircuitBreaker(CONFLICT_THRESHOLD, CIRCUIT_OPEN_MS));<br>        <br>        if (cb.isOpen()) {<br>            // Too many conflicts — stop trying to auto-resolve<br>            logger.warn(&quot;Document {} circuit open, queuing edit for manual review&quot;, docId);<br>            manualReviewQueue.add(new PendingEdit(docId, edit));<br>            return;<br>        }<br>        <br>        try {<br>            int adjustedPosition = resolveConflict(edit, doc);<br>            edit.setPosition(adjustedPosition);<br>            doc.apply(edit);<br>            cb.recordSuccess();<br>        } catch (ConflictException e) {<br>            cb.recordFailure();<br>            if (cb.getFailureCount() &gt;= CONFLICT_THRESHOLD) {<br>                logger.error(&quot;Document {} has {} conflicts, opening circuit&quot;, docId, CONFLICT_THRESHOLD);<br>                notifyOnCall(&quot;Document &quot; + docId + &quot; needs manual merge&quot;);<br>            }<br>            throw e;<br>        }<br>    }<br>}</pre><h3>The Fix That Finally Worked</h3><p>You deployed the background processor + circuit breaker. The corruption stopped. Lawyers stopped panicking. Your manager stopped asking for updates.</p><p>But you learned something: The bug wasn’t in the edit logic. It was in the assumption that “activeEditors” could be used to decide when to process edits. That assumption was wrong. And you only found it by isolating the state, defining invariants, and separating observation from mutation.</p><h3>Now…</h3><p>Before you deploy the fix, you run the test one more time. It passes. You merge. The document corruption stops. Lawyers stop yelling.</p><p>But something bothers you.</p><p>Your fix assumes the system is basically honest - that the two editors made their edits in good faith, that the queue processes them correctly, that the background thread doesn’t crash. You assumed that when <strong>processQueueSafely </strong>runs, the edits it applies are the same edits the users intended.</p><p>That assumption held. This time.</p><p>But what happens when a user’s client has a bug? What happens when a network proxy silently reorders your messages? What happens when one of your own services starts lying - not crashing, not slowing down, but sending different data to different replicas because someone deployed a bad configuration?</p><p>Your circuit breaker won’t catch that. Your invariants won’t catch that. Your background processor will happily apply the lies because they look like edits.</p><p><strong><em>Curious about the solution?? I’ll walk through it in my next post.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32454feef945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 21 Virtual Threads vs Platform Threads in a Real-Time Fraud Detection System]]></title>
            <link>https://medium.com/@ayushgupta228/java-21-virtual-threads-vs-platform-threads-in-a-real-time-fraud-detection-system-8629cd485e31?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/8629cd485e31</guid>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Fri, 22 May 2026 20:43:24 GMT</pubDate>
            <atom:updated>2026-05-22T20:47:38.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaG0T1J-OYQN3YG8r2QcEA.png" /></figure><p>So I was running a fraud detection microservice and it started throwing RejectedExecutionException and HTTP 503 errors at peak times. The CPU was barely warm, memory was fine, but the thread pool was full. The code was plain Spring MVC with blocking I/O, the same pattern we’d relied on for years. We were starved for threads.</p><p>Java 21’s virtual threads promised to fix this by making blocking cheap. I rewrote the service, and the biggest change wasn’t a magic performance number, it was that we stopped thinking about thread pools entirely.</p><p>Here I’ll show you real production code from that service, first the traditional way and then the virtual‑thread version, so you can see exactly what changes and what stays the same.</p><h3>The Problem: One Platform Thread Per Request</h3><p>A typical fraud evaluation for a single payment needs four separate checks:</p><ol><li>Query the database for how many transactions the user made in the last hour (velocity).</li><li>Call a device‑fingerprinting HTTP service.</li><li>Call a sanctions‑list AML HTTP service.</li><li>Call a third‑party scoring API.</li></ol><p>Also let me clarify these terms if you are not familiar. In a fraud detection system, <br>(i) a <strong>velocity check</strong> verifies how many transactions a user made recently to detect suspicious rapid activity.</p><p>(ii) A <strong>device-fingerprinting service</strong> identifies the user’s device using browser and system details to spot unusual behavior.</p><p>(iii) A <strong>sanctions-list AML service</strong> checks whether the user or recipient appears on government or anti-money-laundering watchlists.</p><p>(iv) A <strong>third-party scoring API</strong> analyzes the transaction using external fraud intelligence and returns a risk score to help decide whether the payment should be approved or blocked.</p><p>All four are I/O‑bound and independent. Running them one after another would be slow, so we run them in parallel.</p><p>The traditional approach uses a thread pool. Spring MVC dispatches each HTTP request to a Tomcat platform thread from a pool we’ve configured to, say, 200 threads. To run the four subtasks in parallel, you typically submit them to a separate ExecutorService with its own fixed thread pool.</p><p>When all 200 Tomcat threads are waiting for slow fraud APIs, the server can’t accept new connections‑even though the CPU is mostly idle. That’s thread starvation.</p><h3>1. Traditional Code (Platform Threads + Thread Pool)</h3><p>The controller is plain Spring MVC - nothing special:</p><pre>@RestController<br>public class FraudController {<br>   private final FraudEvaluationService service;<br>    public FraudController(FraudEvaluationService service) {<br>        this.service = service;<br>    }<br>    @PostMapping(&quot;/evaluate&quot;)<br>    public EvaluationResponse evaluate(@RequestBody PaymentRequest request)<br>            throws Exception {<br>        return service.evaluate(request);<br>    }<br>}</pre><p>Now the service, using a dedicated executor for parallel tasks.</p><p>This code was in my codebase.</p><pre>@Service<br>public class FraudEvaluationService {<br>    private final VelocityRepository velocityRepo;<br>    private final ExternalFraudClient fraudClient;<br>    // Tuned by trial and error. Too small -&gt; tasks queue.<br>    // Too large -&gt; memory and context-switching overhead.<br>    private final ExecutorService executor = Executors.newFixedThreadPool(8);<br>    public FraudEvaluationService(VelocityRepository velocityRepo,<br>                                  ExternalFraudClient fraudClient) {<br>        this.velocityRepo = velocityRepo;<br>        this.fraudClient = fraudClient;<br>    }<br>    public EvaluationResponse evaluate(PaymentRequest request) throws Exception {<br>        Future&lt;Integer&gt; velocityFuture = executor.submit(() -&gt;<br>            velocityRepo.recentCount(request.userId()));<br>        Future&lt;DeviceResult&gt; deviceFuture = executor.submit(() -&gt;<br>            fraudClient.checkDevice(request.deviceFingerprint()));<br>        Future&lt;AmlResult&gt; amlFuture = executor.submit(() -&gt;<br>            fraudClient.checkAml(request.senderIban(), request.receiverIban()));<br>        Future&lt;ThirdPartyResult&gt; scoreFuture = executor.submit(() -&gt;<br>            fraudClient.thirdPartyScore(request));<br>        // Block the main thread until every future completes<br>        int velocityCount = velocityFuture.get();<br>        DeviceResult device = deviceFuture.get();<br>        AmlResult aml = amlFuture.get();<br>        ThirdPartyResult score = scoreFuture.get();<br>        return buildResponse(velocityCount, device, aml, score, request.amount());<br>    }<br>}</pre><p>The HTTP client uses a blocking RestClient:</p><pre>@Component<br>public class ExternalFraudClient {<br>    private final RestClient restClient;<br>    public ExternalFraudClient(RestClient.Builder builder) {<br>        this.restClient = builder<br>                .connectTimeout(Duration.ofSeconds(5))<br>                .readTimeout(Duration.ofSeconds(5))<br>                .build();<br>    }<br>    public DeviceResult checkDevice(String fingerprint) {<br>        return restClient.post()<br>                .uri(&quot;http://device-service/check&quot;)<br>                .body(new DeviceRequest(fingerprint))<br>                .retrieve()<br>                .body(DeviceResult.class);<br>    }<br>    // similar methods we could write for AML and third‑party<br>}</pre><p>This works until it doesn’t. When concurrent requests exceed the Tomcat pool size, you get errors even though the database and downstream services are still responding. We had two thread pools to tune, and the interplay between them was fragile.</p><h3>2. The Virtual Threads Version-Same Logic, No Thread Pools</h3><p>Virtual threads are cheap and blocking is free. The controller stays identical. The only configuration change is in application.yml:</p><p>yaml below :-</p><pre>spring:<br>  threads:<br>    virtual:<br>      enabled: true</pre><p>Now every request handler runs on a virtual thread. When that thread blocks (e.g., waiting for an HTTP response), the JVM unmounts it from its carrier OS thread. The carrier is immediately free to work on another virtual thread.</p><p>We delete the ExecutorService entirely and use StructuredTaskScope to run subtasks in parallel - still synchronous code, but on lightweight virtual threads.</p><pre>@Service<br>public class FraudEvaluationService {<br>    private final VelocityRepository velocityRepo;<br>    private final ExternalFraudClient fraudClient;<br>    // No more thread pool. Each fork creates a virtual thread<br>    // that the JVM handles automatically.<br>    public EvaluationResponse evaluate(PaymentRequest request)<br>            throws InterruptedException, ExecutionException {<br>        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>            var velocityTask = scope.fork(() -&gt;<br>                velocityRepo.recentCount(request.userId()));<br>            var deviceTask = scope.fork(() -&gt;<br>                fraudClient.checkDevice(request.deviceFingerprint()));<br>            var amlTask = scope.fork(() -&gt;<br>                fraudClient.checkAml(request.senderIban(), request.receiverIban()));<br>            var scoreTask = scope.fork(() -&gt;<br>                fraudClient.thirdPartyScore(request));<br>            scope.join();          // blocks current virtual thread (but unmounts)<br>            scope.throwIfFailed(); // propagate if any subtask failed<br>            int velocityCount = velocityTask.get();<br>            DeviceResult device = deviceTask.get();<br>            AmlResult aml = amlTask.get();<br>            ThirdPartyResult score = scoreTask.get();<br>            return buildResponse(velocityCount, device, aml, score, request.amount());<br>        }<br>    }<br>}</pre><p>Notice:</p><ul><li>No Future management. StructuredTaskScope.fork() returns a Subtask tied to the scope. If any task fails, the scope cancels the others.</li><li>scope.join() blocks the virtual thread, not the OS carrier. The carrier thread picks up another virtual thread while this one waits.</li><li>Zero thread‑pool tuning. Concurrency scales with incoming requests, bounded only by a semaphore we place on outbound calls.</li></ul><p>The external client code is identical; we only add a Semaphore to avoid overwhelming downstream services.</p><pre>@Component<br>public class ExternalFraudClient {<br>    private final RestClient restClient;<br>    private final Semaphore semaphore = new Semaphore(50); // throttle external calls<br>    public DeviceResult checkDevice(String fingerprint) {<br>        semaphore.acquireUninterruptibly();<br>        try {<br>            return restClient.post()<br>                    .uri(&quot;http://device-service/check&quot;)<br>                    .body(new DeviceRequest(fingerprint))<br>                    .retrieve()<br>                    .body(DeviceResult.class);<br>        } finally {<br>            semaphore.release();<br>        }<br>    }<br>}</pre><p>The Semaphore is crucial - without it, a surge of virtual threads could fire thousands of concurrent HTTP calls, crushing the downstream service.</p><h3>3. What Actually Changed in Production</h3><p>After deploying, we observed:</p><ul><li>No more RejectedExecutionException or 503 errors during traffic spikes. The service handled far more concurrent requests without any queuing or rejected connections, limited only by our downstream partners.</li><li>We deleted all thread‑pool configuration. No server.tomcat.threads.max=200, no executor.fixed.pool=8. The JVM managed concurrency dynamically.</li><li>Heap usage increased slightly because virtual thread stacks live on the Java heap instead of native memory. We adjusted -Xmx by a modest amount and kept an eye on GC logs.</li><li>Code became simpler. Compared to the reactive version we had experimented with earlier, the virtual‑thread service was readable, linear Java. New team members could understand it in hours.</li></ul><p>The real victory wasn’t a “X% improvement” number - it was the removal of an entire category of failure. We stopped worrying about thread starvation and started focusing on fraud rules again.</p><h3>4. Pitfalls We Hit (and Fixed)</h3><h4>Synchronized causes carrier‑thread pinning</h4><p>A virtual thread that blocks inside a synchronized block cannot be unmounted. The carrier thread stays pinned, and you lose concurrency. Our old code had a synchronized cache in the device client:</p><pre>// BAD – virtual thread pinned during I/O<br>public synchronized DeviceProfile getProfile(String fp) {<br>    return cache.computeIfAbsent(fp, this::fetchFromDeviceService);<br>}</pre><p>We replaced it with ConcurrentHashMap:</p><pre>// GOOD – I/O happens outside any lock<br>private final ConcurrentHashMap&lt;String, DeviceProfile&gt; cache = new ConcurrentHashMap&lt;&gt;();<br>public DeviceProfile getProfile(String fp) {<br>    return cache.computeIfAbsent(fp, this::fetchFromDeviceService);<br>}</pre><p>To catch pinning during development, run with:</p><pre>-Djdk.tracePinnedThreads=full</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*fw28FLwtxPJ1V7_2XXp4-A.png" /></figure><h4>Don’t pool virtual threads</h4><p>Submitting virtual threads to a FixedThreadPool defeats their purpose. The JVM already schedules them efficiently. Use Executors.newVirtualThreadPerTaskExecutor() only if you need an ExecutorService interface - never a bounded pool.</p><h4>Throttle outbound calls (always)</h4><p>Virtual threads can unleash massive concurrency. Keep semaphores or similar rate limiters to protect downstream systems.</p><h3>5. When Not to Use Virtual Threads</h3><p>This fraud service is almost pure I/O. If your fraud engine runs CPU‑heavy ML inference locally, keep that on a fixed pool of platform threads. Virtual threads are for I/O orchestration - if your code spends more time waiting than computing, they’re a win.</p><h3>6. Leaving You With This Thought…</h3><p>Virtual threads don’t make your external API calls any faster. They just stop you paying the tax of OS thread exhaustion. For a fraud detection microservice that orchestrates several slow checks, that means you can delete thread‑pool tuning, write plain synchronous Java, and let the JVM handle the rest. In my experience, that’s the real benefit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8629cd485e31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal Consistency vs Eventual Consistency: When Your Data Can’t Decide & Why Your Chai Matters]]></title>
            <link>https://medium.com/@ayushgupta228/the-consistency-chronicles-when-your-data-cant-decide-why-your-chai-order-holds-the-key-8fd7c494d7a0?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd7c494d7a0</guid>
            <category><![CDATA[causal-consistency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[eventual-consistency]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 07:28:56 GMT</pubDate>
            <atom:updated>2025-08-10T15:41:57.881Z</atom:updated>
            <content:encoded><![CDATA[<p>(<em>Because code without chai is just… trauma)<br>Also Java 17 + MongoDB 6.0.8 used</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*VvW2m6sa6pin41TvbnDBIQ.png" /></figure><p><strong>Scene</strong>: A bustling tapri (street-side tea stall). Steel glasses clink, samosas sizzle, and three chaiwalas juggle chaos:</p><ul><li>Chaiwala <strong>A</strong>: Brews masala chai with ginger crushed to the perfect level of spiciness.</li><li>Chaiwala <strong>B</strong>: Scribbles orders on a greased notepad.</li><li>Chaiwala <strong>C</strong>: Washes cups while humming <em>“Chaiyya Chaiyya”</em>.</li></ul><p><strong>You</strong> yell: “Ek cutting chai!”<br>Your <strong>friend</strong>: “Mujhe bhi wahi!” (Same for me!)</p><p>Chaiwala <strong>C</strong>: “Kisne kya maanga?!” (Who ordered what?!)</p><p>Chaos erupts:</p><ul><li>Chaiwala <strong>A</strong> nods.</li><li>Chaiwala <strong>B</strong> writes <em>“adrak chai”</em>.</li><li>Chaiwala <strong>C</strong> shrugs.</li></ul><p>Congratulations! you’ve experienced distributed databases</p><p>Your “orders” = <strong>data</strong>.<br>Your “chaiwalas” = <strong>servers</strong>.</p><p>The rules? Consistency models. Let’s decode this with <em>chai</em> as our guru.</p><p>MongoDB in a replica set has one <strong>primary</strong> (where writes go) and multiple <strong>secondaries</strong> (which replicate data asynchronously).</p><p>If you read from a secondary right after a write, you may see <em>old</em> data because replication lag exists.</p><p>Consistency models define how and when different clients see these changes.</p><h3>🧩 Part 1: Causal Consistency: The Gup-Shup (Gossip) Network</h3><p>In our tea stall, each <strong>chaiwala</strong> represents a MongoDB <strong>node</strong>. If you order from one chaiwala (primary) and your friend asks another chaiwala (secondary) for “the same,” there’s a chance the second chaiwala hasn’t yet heard your order. That’s how <em>replication lag</em> causes inconsistent reads.</p><p><strong>Rule</strong>: If Chaiwala <strong>A</strong> hears your <em>cutting chai</em>, Chaiwala <strong>B</strong> MUST know before processing <em>“mujhe bhi wahi”</em>.<br>Why? Your friend’s order depends on yours. Fail this? They get <em>“same”</em> as… <em>nothing</em> (a tragedy!).</p><p>☕ Java + MongoDB Proof of Chaos<br><em>Default MongoDB isn’t causally consistent. Behold the mess:</em></p><pre>MongoCollection&lt;Document&gt; orders = db.getCollection(&quot;orders&quot;);<br>orders.drop();<br><br>// Act 1: You order cutting chai<br>Document yourOrder = new Document(&quot;item&quot;, &quot;cutting-chai&quot;).append(&quot;by&quot;, &quot;You&quot;);<br>orders.insertOne(yourOrder);<br><br>// Act 2: Friend orders AFTER seeing yours<br>Document friendOrder = new Document(&quot;item&quot;, &quot;same&quot;).append(&quot;by&quot;, &quot;Friend&quot;)<br>  .append(&quot;cause&quot;, yourOrder.getObjectId(&quot;_id&quot;));<br>orders.insertOne(friendOrder);<br><br>// Two observers (chaiwalas) see different realities<br>try (MongoClient observer1 = MongoClients.create();<br>     MongoClient observer2 = MongoClients.create()) {<br><br>  Document result1 = observer1.getDatabase(&quot;chaiChaos&quot;)<br>    .getCollection(&quot;orders&quot;)<br>    .find(eq(&quot;by&quot;, &quot;Friend&quot;)).first();<br><br>  Document result2 = observer2.getDatabase(&quot;chaiChaos&quot;)<br>    .getCollection(&quot;orders&quot;)<br>    .find(eq(&quot;by&quot;, &quot;You&quot;)).first();<br><br>  System.out.println(&quot;Observer 1 sees friend: &quot; + <br>    (result1 != null ? result1.toJson() : &quot;KUCH NAHI!&quot;));<br>  System.out.println(&quot;Observer 2 sees you: &quot; + <br>    (result2 != null ? result2.toJson() : &quot;KUCH NAHI!&quot;));<br>}</pre><p>Here, observer1 and observer2 are connected to <strong>different nodes</strong> in the replica set. Because MongoDB’s default replication is asynchronous, one node may see your friend’s dependent order but not your original order, breaking the cause-effect chain.</p><p><strong>Output</strong>:</p><pre>Observer 1 sees friend: { &quot;by&quot;: &quot;Friend&quot;, &quot;item&quot;: &quot;same&quot;, … }<br>Observer 2 sees you: KUCH NAHI!</pre><p><em>Observer 2 sees the effect (friend’s order) without the cause (your chai). Your friend ordered “same” as thin air!</em></p><p>🦸 The Fix: Force Chaiwalas to Gossip in Order</p><pre>ClientSession session = client.startSession(ClientSessionOptions.builder()<br>  .causalConsistency(true)<br>  .build());<br><br>orders.insertOne(session, yourOrder);<br>orders.insertOne(session, friendOrder); // Preserves cause-effect chain</pre><p><em>Now the system remembers: Friend’s “same” only exists if your cutting chai does too.</em></p><p>If we don’t enforce causal order and just write with WriteConcern.W1 (write acknowledged by only one node), we get <em>eventual consistency</em>.</p><p>The system will “catch up” eventually, but immediate reads from other nodes may show incomplete data.</p><h3>🐢 Part 2: Eventual Consistency: The Aaram Se (Chill) Philosophy</h3><p>Rule: <em>“Shanti se! I’ll figure out your chai… eventually. 5 seconds? or 5 minutes? Baadmein dekhenge.”</em></p><p>☕ Java + MongoDB Proof</p><pre>MongoCollection&lt;Document&gt; orders = db.getCollection(&quot;orders&quot;)<br>  .withWriteConcern(WriteConcern.W1); // Write to only ONE node<br><br>orders.insertOne(new Document(&quot;item&quot;, &quot;masala-chai&quot;).append(&quot;by&quot;, &quot;You&quot;));<br>orders.insertOne(new Document(&quot;item&quot;, &quot;samosa&quot;).append(&quot;by&quot;, &quot;Friend&quot;));<br><br>// Immediate read from a different node<br>try (MongoClient newObserver = MongoClients.create()) {<br>  Document yourOrder = newObserver.getDatabase(&quot;chaiChaos&quot;)<br>    .getCollection(&quot;orders&quot;)<br>    .find(eq(&quot;by&quot;, &quot;You&quot;)).first();<br><br>  Document friendOrder = newObserver.getDatabase(&quot;chaiChaos&quot;)<br>    .getCollection(&quot;orders&quot;)<br>    .find(eq(&quot;by&quot;, &quot;Friend&quot;)).first();<br><br>  System.out.println(&quot;Immediate fetch -&gt; Your chai: &quot; + <br>    (yourOrder != null ? &quot;hai!&quot; : &quot;GHOST!&quot;));<br>  System.out.println(&quot;Immediate fetch -&gt; Friend&#39;s samosa: &quot; + <br>    (friendOrder != null ? &quot;hai!&quot; : &quot;GHOST!&quot;));<br>}<br>Thread.sleep(2000); // Let gossip happen</pre><p>Here, the read is coming from a secondary node that might not have replicated the writes yet.</p><p><strong>Outcome</strong>: First read may show GHOST! orders. Wait 2 seconds? <em>Everything appears A-okay.</em></p><p>In real life, eventual consistency can cause visible glitches, like empty carts, duplicate items, or stale prices, when your actions depend on the latest data but the system serves old data from a lagging node.</p><h3>🧪 Part 3: Real-World Jugaad Stories</h3><h4>💸 The ₹10,000 Flipkart Fiasco</h4><ul><li>You add a ₹10,000 phone (eventual consistency).</li><li>Refresh -&gt; cart empty!</li><li>Re-add -&gt; now <em>two</em> phones.</li><li>Your wallet: <em>“Yaar, ye kyu?!”</em></li></ul><p><strong>Fix</strong>:</p><pre>orders.withWriteConcern(WriteConcern.MAJORITY); // Ensure most nodes agree</pre><h3>🔮 MongoDB’s Secret Sauce</h3><p>For Causal Consistency:</p><pre>ClientSession session = client.startSession(ClientSessionOptions.builder()<br>  .causalConsistency(true)<br>  .build());</pre><p><em>Uses logical timestamps like “pehle aap” queues.</em></p><p>For Eventual Consistency:</p><ul><li>WriteConcern.W1 -&gt; Fast but risky writes (<em>&quot;chalta hai&quot;</em> mode).</li><li>ReadConcern.LOCAL -&gt; Dirty reads (<em>&quot;jugaad&quot;</em> reads).<br>Pro Tip: Monitor replication lag like cricket scores!</li></ul><h3>☕ The Final Ghoont (Sip)</h3><ul><li>Causal consistency: Your friend who says, <em>“Arre, ‘same’ matlab 10 baje wali cutting chai!”</em></li><li>Eventual consistency: Your <em>dadi</em> who says, <em>“Beta, thanda karke pilaoongi… baad mein.”</em></li></ul><p>Rule of thumb:</p><ul><li>Building a <em>chai</em> delivery app? -&gt; Causal consistency.</li><li>Building social media? -&gt; Embrace eventual chaos.</li></ul><p>So go forth, build systems that won’t ruin <em>chai</em> orders.</p><p>Ready to <em>chai-fy</em> your code? 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd7c494d7a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reproducible Java Builds: Why Your JARs Lie And How to Fix It]]></title>
            <link>https://medium.com/@ayushgupta228/reproducible-java-builds-why-your-jars-lie-and-how-to-fix-it-e32e4942acf6?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/e32e4942acf6</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 12:12:22 GMT</pubDate>
            <atom:updated>2025-08-09T12:34:00.782Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Mystery of the Changing JAR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjbhCJXQIKxToBjMh4eIag.png" /></figure><p>Picture this:</p><p>You write a simple Java app. You build it today, save the JAR. Tomorrow, without changing a single line of code, you build it again.</p><p><em>“Surely,”</em> you think, <em>“the JARs should be identical?”</em></p><p>But when you check:</p><pre>$ sha256sum myapp-1.0.jar<br>a1c34d9121e3a4dcdab893f48a...<br><br>$ sha256sum myapp-1.0-2.jar<br>f8239b5412e1ff9a234a0deac...</pre><p>They’re different.</p><p>This isn’t a bug, it’s how Java builds work by<em> default</em>. Tiny, invisible differences sneak into your binaries every time you compile.</p><p>For some, this is just a quirk. For security-conscious teams? It’s a red flag.</p><p>In this article, we’ll:</p><ul><li>🕵️ Discover why Java builds aren’t reproducible out of the box.</li><li>🔧 Fix it step-by-step in Maven <em>and</em> Gradle.</li><li>✅ End with a checklist to ensure your builds are bit-for-bit<em> identical</em>, every time.</li></ul><p>By the end, you’ll go from:</p><pre>Build 1 SHA256: a1c34d91...<br>Build 2 SHA256: f8239b54...</pre><p>To:</p><pre>Build 1 SHA256: 7df3f2c9...<br>Build 2 SHA256: 7df3f2c9... ✅</pre><h3>Why Should You Care?</h3><h3>1. Security &amp; Supply Chain Attacks</h3><p>Your CI/CD server is just another computer and computers get hacked. If someone slips malicious code into your JAR between compile and deploy, you’d want to know.</p><p>Reproducible builds let you:</p><ul><li>Build the same code on a trusted machine.</li><li>Compare it to the CI build’s output.</li><li>Detect tampering instantly if the hashes don’t match.</li></ul><h3>2. Debugging Nightmares</h3><p>Ever had a bug in production that vanished on your local machine? Sometimes, it’s because the builds weren’t truly identical. Subtle differences in timestamps or file ordering can cause different runtime behavior.</p><h3>3. Compliance &amp; Future-Proofing</h3><p>In regulated industries (finance, healthcare), you must prove the binary matches the reviewed source code. Reproducible builds give you that proof forever.</p><h3>4. Peace of Mind</h3><p>Even if you’re not in a high-stakes environment, knowing that your builds are deterministic means:</p><ul><li>No surprises when rebuilding old releases.</li><li>No “works on my machine” excuses.</li><li>Confidence that what you tested is what you shipped.</li></ul><h3>What Exactly Is a Reproducible Build?</h3><p>A reproducible build means:</p><blockquote><em>Same source + same dependencies + same environment = identical binary output, </em>byte-for-byte<em>.</em></blockquote><p>In Java terms:</p><ul><li>Same .java files -&gt; same .class files.</li><li>Packaged into the same .jar or .war.</li><li>Hash matches every single time.</li></ul><h3>A Simple Example</h3><p>Take this HelloWorld.java:</p><pre>public class HelloWorld {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello, reproducible world!&quot;);<br>    }<br>}</pre><p>Compile it twice:</p><pre># First build<br>javac HelloWorld.java<br>jar cf hello.jar HelloWorld.class</pre><pre># Second build<br>javac HelloWorld.java<br>jar cf hello2.jar HelloWorld.class</pre><p>Now compare:</p><pre>$ sha256sum hello.jar<br>6b1a16b7a9450fd31268d9f6317acb1fd6c81a7981adcf0a1468fd3adcf0f83d</pre><pre>$ sha256sum hello2.jar<br>5f8d04b789ae5c06b15c79a84d8f39411b9856e06b0b8d60bcfb31e29c5bde1e</pre><p>Different hashes. Why?</p><p>Peek inside the JAR:</p><pre>unzip -p hello.jar META-INF/MANIFEST.MF</pre><p>You’ll see something like:</p><pre>Manifest-Version: 1.0<br>Created-By: 17.0.7 (Oracle Corporation)<br>Build-Date: Sat Aug  9 18:04:37 IST 2025  # THIS CHANGES EVERY BUILD!</pre><p>That timestamp is just one of many culprits.</p><h3>Why Java Builds Aren’t Reproducible by Default</h3><p>Even if your code doesn’t change, Java injects tiny differences into your builds. Here’s how:</p><h3>1. Timestamps in .class Files</h3><p>javac embeds the compilation time in .class metadata:</p><pre>javap -verbose HelloWorld.class | grep &quot;Last modified&quot;<br># Output: Last modified Aug 9, 2025; size 427 bytes</pre><p>Changes every build.</p><h3>2. Manifest Mayhem</h3><p>The META-INF/MANIFEST.MF often includes:</p><ul><li>Build dates</li><li>Java version</li><li>Random whitespace differences</li></ul><h3>3. ZIP Chaos</h3><p>JARs are ZIP files, and ZIPs can vary by:</p><ul><li>File order (OS-dependent)</li><li>Per-file timestamps</li><li>Compression quirks</li></ul><h3>4. Dependency Drift</h3><p>If you don’t lock versions, your build might silently pull:</p><ul><li>New library updates</li><li>Different transitive dependencies</li></ul><h3>The Enemies of Reproducibility</h3><p>✅ Timestamps (in class files, manifests, ZIP headers)<br>✅ Unstable file ordering<br>✅ Changing dependencies<br>✅ Environment differences (OS, Java vendor, etc.)</p><h3>How to Fix It: Step-by-Step</h3><h3>1. Kill Timestamps in JARs</h3><p>Maven:</p><pre>&lt;plugin&gt;<br>  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>  &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;<br>  &lt;configuration&gt;<br>    &lt;outputTimestamp&gt;1980-01-01T00:00:00Z&lt;/outputTimestamp&gt; &lt;!-- Fixed date! --&gt;<br>  &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>Gradle:</p><pre>tasks.withType(Jar).configureEach {<br>  preserveFileTimestamps = false<br>  reproducibleFileOrder = true<br>}</pre><h3>2. Stabilize File Ordering</h3><p>ZIPs can pack files in random orders. Force consistency:</p><p>Maven:<br>The outputTimestamp trick above <em>also</em> fixes ordering.</p><p>Gradle:<br>reproducibleFileOrder = true does the job.</p><h3>3. Tame the Manifest</h3><p>Remove time-varying fields:</p><p>Maven:</p><pre>&lt;plugin&gt;<br>  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>  &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;<br>  &lt;configuration&gt;<br>    &lt;archive&gt;<br>      &lt;manifestEntries&gt;<br>        &lt;Implementation-Title&gt;${project.name}&lt;/Implementation-Title&gt;<br>        &lt;Implementation-Version&gt;${project.version}&lt;/Implementation-Version&gt;<br>      &lt;/manifestEntries&gt;<br>      &lt;addDefaultImplementationEntries&gt;false&lt;/addDefaultImplementationEntries&gt;<br>    &lt;/archive&gt;<br>  &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>Gradle:</p><pre>jar {<br>  manifest {<br>    attributes(<br>      &quot;Implementation-Title&quot;: project.name,<br>      &quot;Implementation-Version&quot;: project.version<br>    )<br>  }<br>}</pre><h3>4. Lock Dependencies</h3><p>Maven: Use &lt;dependencyManagement&gt; and explicit versions.</p><p>Gradle: Enable locking</p><pre>dependencyLocking {<br>  lockAllConfigurations()<br>}</pre><p>Then run:</p><pre>./gradlew dependencies --write-locks</pre><h3>Before vs. After: Proof It Works</h3><h3>The “Before” Build</h3><pre>mvn clean package<br>sha256sum target/app.jar  # Output: 34b5ac92e9f...<br>mvn clean package<br>sha256sum target/app.jar  # Output: 7fc9be4da1...  # 😱 Different!</pre><h3>The “After” Build (With Fixes Applied)</h3><pre>mvn clean package<br>sha256sum target/app.jar  # Output: a2e548be6c...<br>mvn clean package<br>sha256sum target/app.jar  # Output: a2e548be6c...  # ✅ Identical!</pre><h3>Troubleshooting: When Hashes Still Don’t Match</h3><p>Use diffoscope to compare JARs:</p><pre>diffoscope jar1.jar jar2.jar</pre><p>Common Culprits:</p><ul><li>IDE configs sneaking into builds (.DS_Store, .idea/)</li><li>Line endings (Windows CRLF vs. Unix LF)</li><li>Different Java versions</li></ul><h3>Final Checklist for Reproducible Builds</h3><p>✅ Fix timestamps (use outputTimestamp or preserveFileTimestamps=false)<br>✅ Stabilize file order (reproducibleFileOrder=true)<br>✅ Strip volatile manifest entries<br>✅ Lock dependencies (Maven &lt;dependencyManagement&gt; / Gradle dependencyLocking)<br>✅ Compare builds with diffoscope</p><h3><em>Still getting different hashes? Here’s what to check..</em></h3><p>Even after configuring your build, these sneaky culprits might still sabotage reproducibility. Here’s how to hunt them down:</p><h3>1. Timestamps in JAR Entries</h3><p>The Issue:<br>Every build embeds fresh timestamps in ZIP metadata and class files.</p><p>The Fix:</p><pre>&lt;!-- Maven --&gt;  <br>&lt;outputTimestamp&gt;1980-01-01T00:00:00Z&lt;/outputTimestamp&gt;  </pre><pre>// Gradle  <br>tasks.withType(Jar) {  <br>  preserveFileTimestamps = false  <br>}</pre><h3>2. JAR File Order Roulette</h3><p>The Issue:<br>ZIPs pack files in different orders across OSes.</p><p>The Fix:</p><pre>// Gradle  <br>reproducibleFileOrder = true</pre><p><em>(Maven handles this automatically with </em><em>outputTimestamp)</em></p><h3>3. Randomness at Build Time</h3><p>The Issue:<br>UUIDs, hashes, or new Date() in generated code.</p><p>The Fix:</p><ul><li>Replace with fixed values in builds</li><li>Use the -Ddeterministic flag for code generators</li></ul><h3>4. Debug Info Leaks</h3><p>The Issue:<br>Compiler embeds local paths like /Users/yourname/project/.</p><p>The Fix:</p><pre>javac -g:source,lines  # Only keep source/line info</pre><h3>5. The Line Ending Trap</h3><p>The Issue:<br>Windows (CRLF) vs. Unix (LF) differences in resources.</p><p>The Fix:</p><pre># .gitattributes  <br>* text=auto eol=lf</pre><h3>6. Java Version Jitter</h3><p>The Issue:<br>Different JDKs produce slightly different bytecode.</p><p>The Fix:</p><pre>&lt;!-- Maven Toolchains --&gt;  <br>&lt;toolchain&gt;  <br>  &lt;type&gt;jdk&lt;/type&gt;  <br>  &lt;version&gt;17&lt;/version&gt;  <br>&lt;/toolchain&gt;</pre><h3>Pro Tip: The “Invisible” Differences</h3><p>Sometimes the villain isn’t your code, it’s your environment:</p><ul><li>IDE artifacts: IntelliJ/VS Code configs accidentally packaged</li><li>Build leftovers: Previous compilations polluting new builds</li></ul><pre># .gitignore  <br>.DS_Store  <br>.idea/  <br>*.iml  <br>target/</pre><pre>&lt;!-- Maven failsafe --&gt;  <br>&lt;plugin&gt;  <br>  &lt;artifactId&gt;maven-clean-plugin&lt;/artifactId&gt;  <br>  &lt;version&gt;3.3.2&lt;/version&gt;  <br>&lt;/plugin&gt;</pre><h3>Why This Matters</h3><p>Reproducible builds aren’t just for paranoiacs. They give you:</p><p>🔒 Security: Detect tampering.<br>🐛 Stability: No more “works on my machine.”<br>📜 Compliance: Prove your binaries match your source.<br>☕ Peace of mind: Rebuild any version, anytime, exactly as it was.</p><p>Now go forth and build <em>reproducibly</em>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e32e4942acf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polyglot Microservices System: Java Spring Boot Meets Python]]></title>
            <link>https://medium.com/@ayushgupta228/polyglot-microservices-system-java-spring-boot-meets-python-d49426df0953?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49426df0953</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[polyglot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 18:49:10 GMT</pubDate>
            <atom:updated>2025-07-23T19:47:14.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UrP0N_zlK-HCkeyOBQpmw.png" /></figure><h3>Introduction</h3><p>Okay so while working on a Python project of mine recently, I wondered how I could combine the secure and reliable authentication capabilities of Java Spring Boot (my professional work experience) with Python’s powerful analytics tools.</p><p>After watching a YouTube video that introduced me to this concept and doing extensive reading on the topic, I became interested in integrating the two technologies together.</p><p>So In this article, I’ll guide you through step by step instructions, including real code and Docker Compose, to show how Java and Python microservices can integrate smoothly.</p><p>And I have also implemented advanced connections, such as Kafka for event driven workflows and gRPC for fast, type safe APIs. <br>So let’s get started.</p><h3>Architecture Overview: A Real World Note Taking Application</h3><p>Let’s illustrate these concepts with a practical <strong>Note Taking Application</strong> use case:</p><ul><li><strong>Java/Spring Boot: Authentication Service: </strong>Handles user login, authentication, and JWT issuing, leveraging Java’s strong security features.</li><li><strong>Python (FastAPI) Analytics Service: </strong>Provides notes analytics and smart recommendations, taking advantage of Python’s data processing capabilities.</li></ul><p>These services will communicate primarily over HTTP (REST) and then evolve to more advanced patterns like Kafka and gRPC. <br><strong>Docker Compose</strong> will manage seamless local development and easy deployment.</p><h3>Tech Used and it’s Use Case</h3><p><strong>Auth Service:</strong> Java (Spring Boot)<br><strong>use:</strong> User login/auth, JWT issuing</p><p><strong>Analytics Service:</strong> Python (FastAPI)<br><strong>use:</strong> Notes analytics, smart scoring</p><p><strong>Database(s):</strong> PostgreSQL/Redis <br><strong>use:</strong> Data storage</p><p>Databases <strong>implementation</strong> is <strong>not</strong> explained in this article, just wanted to show how all these things integrate and that could be explained without having a db at back necessarily.</p><p>If wanted(write down in the comments) then I will publish a proper redis or postgreSQL or mongoDB impl. version of this too.</p><h3>Phase 1: RESTful Communication with Docker Compose</h3><p>Let’s begin by setting up the foundational RESTful communication between our services.</p><h3>Step 1: Bootstrapping the Java Spring Boot Auth Service</h3><p>We’ll start with a classic Spring Boot skeleton for our authentication service.</p><h4>Maven Setup (pom.xml)</h4><p>Add the necessary dependencies for web functionality, security, and JWT:</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>        &lt;artifactId&gt;jjwt&lt;/artifactId&gt;<br>        &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><h4>REST Controller (AuthController.java)</h4><p>This controller will handle user login and issue JWT tokens upon successful authentication.</p><pre>package com.example.authservice.controller;<br><br>import com.example.authservice.model.JwtResponse;<br>import com.example.authservice.model.LoginRequest;<br>import com.example.authservice.security.JwtProvider;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.context.SecurityContextHolder;@RestController<br><br>@RequestMapping(&quot;/api/auth&quot;)<br>public class AuthController {<br>    private final AuthenticationManager authenticationManager;<br>    private final JwtProvider jwtProvider;<br>    public AuthController(AuthenticationManager authenticationManager, JwtProvider jwtProvider) {<br>        this.authenticationManager = authenticationManager;<br>        this.jwtProvider = jwtProvider;<br>    }<br><br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;?&gt; login(@RequestBody LoginRequest request) {<br>        // Authenticate user credentials<br>        Authentication authentication = authenticationManager.authenticate(<br>                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())<br>        );<br>        SecurityContextHolder.getContext().setAuthentication(authentication);<br>        // Generate JWT token<br>        String jwt = jwtProvider.generateToken(authentication); // generateToken takes Authentication object<br>        return ResponseEntity.ok(new JwtResponse(jwt));<br>    }<br>    // can Implement register endpoint here, I didn&#39;t do it here  </pre><p><strong>Service Exposes:</strong> POST /api/auth/login (Expects username/password, issues JWT)</p><h3>Step 2: Python FastAPI Analytics Microservice</h3><p>Next, we’ll build our lightweight Python analytics service using FastAPI.</p><h4>Python Environment Setup</h4><p>Install FastAPI and Uvicorn:</p><pre>pip install fastapi uvicorn pydantic</pre><h4>Analytics Endpoint Example (main.py)</h4><p>This service will receive note text and return a simple “score” (e.g., word count) as a dummy analytic.</p><pre>from fastapi import FastAPI, Request<br>from pydantic import BaseModel<br><br>app = FastAPI()<br><br>class NotePayload(BaseModel):<br>    note_text: str<br><br>@app.post(&quot;/api/analytics/summarize&quot;)<br>def summarize(payload: NotePayload):<br>    <br>    # Receives note text and returns a simple word count as an analytic score.<br>    <br>    text = payload.note_text<br>    word_count = len(text.split())<br>    return {&quot;score&quot;: word_count}<br><br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p><strong>Service Exposes:</strong> POST /api/analytics/summarize (Receives note text, returns analysis)</p><h3>Step 3: Letting the Services Talk (Java Calls Python)</h3><p>From our Java Spring Boot service, we can call the Python service using <strong>RestTemplate</strong> or the more modern <strong>WebClient</strong>. Let&#39;s use <strong>RestTemplate </strong>for simplicity in this example.</p><pre>package com.example.authservice.service; <br><br>import org.springframework.http.HttpHeaders;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.client.RestTemplate;<br>import java.util.HashMap;<br>import java.util.Map;<br><br>@Service<br>public class AnalyticsIntegrationService {<br>    private final RestTemplate restTemplate;<br><br>    public AnalyticsIntegrationService(RestTemplate restTemplate) {<br>        this.restTemplate = restTemplate;<br>    }<br><br>    public Integer getAnalyticsScore(String noteText) {<br>        // In Docker Compose, &#39;analytics&#39; is the hostname of the Python service<br>        String pythonServiceUrl = &quot;http://analytics:8000/api/analytics/summarize&quot;;<br>        <br>        HttpHeaders headers = new HttpHeaders();<br>        headers.setContentType(MediaType.APPLICATION_JSON);<br>        Map&lt;String, String&gt; json = new HashMap&lt;&gt;();<br>        json.put(&quot;note_text&quot;, noteText);<br><br>        HttpEntity&lt;Map&lt;String, String&gt;&gt; request = new HttpEntity&lt;&gt;(json, headers);<br>        try {<br>            ResponseEntity&lt;Map&gt; response = restTemplate.postForEntity(pythonServiceUrl, request, Map.class);<br>            if (response.getStatusCode().is2xxSuccessful() &amp;&amp; response.getBody() != null) {<br>                return (Integer) response.getBody().get(&quot;score&quot;);<br>            }<br>        } catch (Exception e) {<br>            System.err.println(&quot;Error calling Python analytics service: &quot; + e.getMessage());<br>        }<br>        return 0; // Default score in case of error<br>    }<br>}</pre><p><strong>Note:</strong> When deploying with Docker Compose, the hostname <strong>analytics</strong> refers directly to the Python service container, thanks to Docker&#39;s internal DNS resolution.</p><h3>Step 4: Dockerizing Everything</h3><p>Docker makes our microservices portable and reproducible.</p><h4>Dockerfile for Java Auth Service (auth-service/Dockerfile)</h4><pre>FROM openjdk:17-jdk-slim<br>VOLUME /tmp<br>COPY target/auth-service.jar app.jar<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]</pre><h4>Dockerfile for Python Analytics Service (analytics-service/Dockerfile)</h4><pre>FROM python:3.11-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY . .<br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p><strong>analytics-service/requirements.txt:</strong></p><pre>fastapi<br>uvicorn<br>pydantic</pre><h4>Sample docker-compose.yml</h4><p>This file orchestrates both services, allowing them to communicate.</p><pre>version: &#39;3.8&#39;<br>services:<br>  auth:<br>    build:<br>      context: ./auth-service # Assuming auth-service is in a sibling directory<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=prod<br>    # Link to a database if needed<br>    # depends_on:<br>    #   - postgres<br>analytics:<br>    build:<br>      context: ./analytics-service # Assuming analytics-service is in a sibling directory<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8000:8000&quot;<br>    # depends_on:<br>    #   - redis # if analytics uses Redis<br># Example Database Service (uncomment and configure if needed)<br>  # postgres:<br>  #   image: postgres:13<br>  #   environment:<br>  #     POSTGRES_DB: auth_db<br>  #     POSTGRES_USER: user<br>  #     POSTGRES_PASSWORD: password<br>  #   volumes:<br>  #     - postgres_data:/var/lib/postgresql/data<br>  #   ports:<br>  #     - &quot;5432:5432&quot;<br>volumes:<br>  postgres_data: # Define named volume for persistence</pre><p>To run, navigate to the <strong>docker-compose.yml</strong> directory and <br>execute: docker-compose up --build.</p><h3>Phase 2: Beyond REST :- Event Driven and High Performance Communication</h3><p>While REST is excellent for simplicity, real world polyglot systems often benefit from more robust and performant communication patterns.</p><h3>Why Go Beyond REST?</h3><p>REST is stateless and simple, but as systems scale, the need for:</p><ul><li><strong>Low latency, bi-directional communication</strong></li><li><strong>Schema typed, high throughput APIs</strong></li><li><strong>Asynchronous, decoupled workflows </strong>drives the adoption of event driven architectures and protocols like gRPC built atop Protocol Buffers.</li></ul><h3>1. Event Driven Microservices (Kafka Example)</h3><p><strong>Event driven architectures</strong> allow services to react asynchronously to events published on platforms like Kafka, instead of direct, synchronous API calls. This pattern provides:</p><ul><li><strong>Loosely coupled microservices:</strong> Services don’t need to know about each other’s existence directly.</li><li><strong>Real time data flows:</strong> Events can be processed almost instantly across services.</li><li><strong>Resilient, scalable integration:</strong> A publishing service isn’t affected if a consuming service is temporarily down.</li></ul><p><strong>Example Overview:</strong> Suppose we have two services:</p><ul><li><strong>Order Service (Java):</strong> Places orders, publishes <strong>OrderCreatedEvent</strong> events.</li><li><strong>Analytics Service (Python):</strong> Listens for order events, processes analytics like total revenue or popular items.</li></ul><h4>Publish-Subscribe Design:</h4><p><strong>Order Service:</strong> In Java<br><strong>Kafka Topic: </strong>orders <br><strong>role: </strong>Publishes events</p><p><strong>Analytics Svc:</strong> In Python<br><strong>Kafka Topic:</strong> orders<br><strong>role: </strong>Consumes events</p><h4>Step 1: Define the Event Schema (Protobuf Example)</h4><p>Protocol Buffers (Protobuf) provide a language-agnostic, efficient way to serialize structured data.</p><p><strong>order_event.proto:</strong></p><pre>syntax = &quot;proto3&quot;;<br>package com.example.protobuf; // the Java package name<br>message OrderCreatedEvent {<br>  string order_id = 1;<br>  string user_id = 2;<br>  float total_amount = 3;<br>  string created_at = 4;<br>}</pre><h4>Step 2: Generate Python/Java Classes from Protobuf</h4><p><strong>In Python:</strong></p><pre>pip install grpcio-tools kafka-python # kafka-python is for Kafka client<br>python -m grpc_tools.protoc -I. --python_out=. --pyi_out=. order_event.proto</pre><p><strong>Java:</strong> Add the Protobuf Maven plugin to your <strong>pom.xml</strong>. This plugin will generate Java classes from <strong>order_event.proto</strong> during the build phase.</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.xolstice.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;protobuf-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;0.6.1&lt;/version&gt; &lt;configuration&gt;<br>                &lt;protocArtifact&gt;com.google.protobuf:protoc:3.25.1:exe:${os.detected.classifier}&lt;/protocArtifact&gt;<br>                &lt;pluginId&gt;grpc-java&lt;/pluginId&gt;<br>                &lt;pluginArtifact&gt;io.grpc:protoc-gen-grpc-java:1.62.2:exe:${os.detected.classifier}&lt;/pluginArtifact&gt;<br>            &lt;/configuration&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;compile&lt;/goal&gt;<br>                        &lt;goal&gt;compile-custom&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;<br>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;<br>        &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;<br>        &lt;version&gt;3.7.0&lt;/version&gt; &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.google.protobuf&lt;/groupId&gt;<br>        &lt;artifactId&gt;protobuf-java&lt;/artifactId&gt;<br>        &lt;version&gt;3.25.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><h4>Step 3: Publish Event in Java (Order Service using Kafka)</h4><pre>package com.example.orderservice.service;<br>import com.example.protobuf.OrderCreatedEvent;<br>import org.apache.kafka.clients.producer.KafkaProducer;<br>import org.apache.kafka.clients.producer.ProducerRecord;<br>import org.springframework.stereotype.Service;<br>import java.time.Instant;<br>import java.util.Properties;<br>import java.util.UUID;<br><br>@Service<br>public class OrderEventProducer {<br>    private final KafkaProducer&lt;String, byte[]&gt; producer;<br>    private final String TOPIC_NAME = &quot;orders&quot;;<br><br>    public OrderEventProducer() {<br>        Properties props = new Properties();<br>        props.put(&quot;bootstrap.servers&quot;, &quot;broker:9092&quot;); // Kafka broker in Docker Compose<br>        props.put(&quot;key.serializer&quot;, &quot;org.apache.kafka.common.serialization.StringSerializer&quot;);<br>        props.put(&quot;value.serializer&quot;, &quot;org.apache.kafka.common.serialization.ByteArraySerializer&quot;);<br>        this.producer = new KafkaProducer&lt;&gt;(props);<br>    }<br>    <br>    public void publishOrderCreatedEvent(String userId, float totalAmount) {<br>        String orderId = UUID.randomUUID().toString();<br>        OrderCreatedEvent orderEvent = OrderCreatedEvent.newBuilder()<br>                .setOrderId(orderId)<br>                .setUserId(userId)<br>                .setTotalAmount(totalAmount)<br>                .setCreatedAt(Instant.now().toString())<br>                .build();<br>        ProducerRecord&lt;String, byte[]&gt; record = new ProducerRecord&lt;&gt;(<br>                TOPIC_NAME,<br>                orderEvent.getOrderId(),<br>                orderEvent.toByteArray());<br>                <br>        producer.send(record, (metadata, exception) -&gt; {<br>        if (exception == null) {<br>                System.out.printf(&quot;Produced record to topic %s partition %d @ offset %d%n&quot;,<br>                        metadata.topic(), metadata.partition(), metadata.offset());<br>            } else {<br>                System.err.println(&quot;Error producing record: &quot; + exception.getMessage());<br>            }<br>        });<br>    }<br><br>    // Don&#39;t forget to close the producer on application shutdown<br>    public void close() {<br>        producer.close();<br>    }<br>}</pre><h4>Step 4: Consume Event in Python (Analytics Service)</h4><pre>from kafka import KafkaConsumer<br>import order_event_pb2 # Generated from protobuf<br>import json<br><br>def consume_order_events():<br>    consumer = KafkaConsumer(<br>        &#39;orders&#39;,<br>        bootstrap_servers=&#39;broker:9092&#39;, # Kafka broker in Docker Compose<br>        auto_offset_reset=&#39;earliest&#39;, # Start from beginning if no offset committed<br>        enable_auto_commit=True,<br>        group_id=&#39;analytics_group&#39;,<br>        value_deserializer=lambda m: m  # get bytes<br>    )<br><br>    print(&quot;Starting Kafka consumer for &#39;orders&#39; topic...&quot;)<br>    for msg in consumer:<br>        try:<br>            event = order_event_pb2.OrderCreatedEvent()<br>            event.ParseFromString(msg.value)<br>            print(f&quot;Consumed Order Event: ID={event.order_id}, User={event.user_id}, Total={event.total_amount}&quot;)<br>            # Here, integrate with our analytics logic, database storage, etc.<br>            # Example: Increment total sales, update user purchase history<br>        except Exception as e:<br>            print(f&quot;Error parsing Protobuf message: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    consume_order_events()</pre><p>This decoupled system allows our Java service to emit events and your Python service to consume and process them asynchronously, with Protobuf ensuring strict schema consistency.</p><h3>2. Protocol Buffers + gRPC: High Performance, Typed APIs</h3><p>gRPC, built atop Protocol Buffers for data serialization, offers:</p><ul><li><strong>Strongly typed contracts:</strong> Eliminates runtime type errors.</li><li><strong>Language-agnostic stubs:</strong> Automatically generated client and server code for multiple languages.</li><li><strong>Streaming and bi-directional communication:</strong> Ideal for real time applications and large data transfers.</li></ul><h4>Example: Analytics Service gRPC API</h4><p>Let’s expose our analytics functionality via gRPC.</p><h4>Step 1: Define the Proto Service (analytics.proto)</h4><pre>syntax = &quot;proto3&quot;;<br><br>package analytics; // Python package name or service name. For Java, it&#39;s typically defined via &#39;option java_package&#39;<br><br>// The analytics service definition.<br>service Analytics {<br>  // Analyzes the provided note text and returns a score and keywords.<br>  rpc AnalyzeNote (NoteRequest) returns (NoteResponse);<br>}<br><br>message NoteRequest {  // Request message for the AnalyzeNote RPC<br>  string note_text = 1;<br>}<br><br>message NoteResponse {<br>  int32 score = 1;<br>  // Potentially more detailed analysis fields<br>  repeated string keywords = 2;<br>}</pre><h4>Step 2: Generate gRPC Stubs</h4><p>To make our Java and Python services understand and communicate using this defined <strong>analytics.proto</strong> contract, we need to generate client and server stub code.</p><p><strong>Python: </strong>Navigate to the directory containing analytics.proto and run the following command. This will generate analytics_pb2.py (for Protobuf messages) and analytics_pb2_grpc.py (for gRPC service stubs), along with type hints (.pyi files).</p><pre>python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. --pyi_out=. analytics.proto</pre><p><strong>Java:</strong> Ensuring the Protobuf Maven plugin to integrate the stub generation into your build process.</p><p><strong>1. Add Dependencies to pom.xml:</strong></p><p>We’ll need the gRPC and Protobuf runtime dependencies.</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-netty-shaded&lt;/artifactId&gt;<br>        &lt;version&gt;1.62.2&lt;/version&gt; &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-protobuf&lt;/artifactId&gt;<br>        &lt;version&gt;1.62.2&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-stub&lt;/artifactId&gt;<br>        &lt;version&gt;1.62.2&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.google.protobuf&lt;/groupId&gt;<br>        &lt;artifactId&gt;protobuf-java&lt;/artifactId&gt;<br>        &lt;version&gt;3.25.1&lt;/version&gt; &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.google.protobuf&lt;/groupId&gt;<br>        &lt;artifactId&gt;protobuf-java-util&lt;/artifactId&gt;<br>        &lt;version&gt;3.25.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><p><strong>2. Configure the Protobuf Maven Plugin in pom.xml (within the </strong><strong>&lt;build&gt;&lt;plugins&gt; section):</strong></p><p>This plugin will automatically download the <strong>protoc</strong> compiler and the <br><strong>grpc-java</strong> plugin, and then run them to generate the Java source files from our <strong>.proto</strong> definition during our Maven build (e.g., mvn clean install).</p><pre>&lt;build&gt;<br>    &lt;extensions&gt;<br>        &lt;extension&gt;<br>            &lt;groupId&gt;kr.motd.maven&lt;/groupId&gt;<br>            &lt;artifactId&gt;os-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;1.7.1&lt;/version&gt; &lt;/extension&gt;<br>    &lt;/extensions&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.xolstice.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;protobuf-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;0.6.1&lt;/version&gt; &lt;configuration&gt;<br>                &lt;protocArtifact&gt;com.google.protobuf:protoc:3.25.1:exe:${os.detected.classifier}&lt;/protocArtifact&gt;<br>                &lt;pluginId&gt;grpc-java&lt;/pluginId&gt;<br>                &lt;pluginArtifact&gt;io.grpc:protoc-gen-grpc-java:1.62.2:exe:${os.detected.classifier}&lt;/pluginArtifact&gt;<br>                &lt;protoSourceRoot&gt;${project.basedir}/src/main/proto&lt;/protoSourceRoot&gt;<br>                &lt;outputDirectory&gt;${project.build.directory}/generated-sources/protobuf/java&lt;/outputDirectory&gt;<br>                &lt;clearOutputDirectory&gt;false&lt;/clearOutputDirectory&gt;<br>            &lt;/configuration&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;compile&lt;/goal&gt;          &lt;goal&gt;compile-custom&lt;/goal&gt;    &lt;/goals&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br>            &lt;artifactId&gt;build-helper-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;3.4.0&lt;/version&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;id&gt;add-source&lt;/id&gt;<br>                    &lt;phase&gt;generate-sources&lt;/phase&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;add-source&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                    &lt;configuration&gt;<br>                        &lt;sources&gt;<br>                            &lt;source&gt;${project.build.directory}/generated-sources/protobuf/java&lt;/source&gt;<br>                        &lt;/sources&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p><strong>3. Place our analytics-proto file:</strong></p><p>Place the <strong>analytics-proto </strong>file in the location specified in the protobuf-maven-plugin configuration. By convention at: <strong>src/main/proto/analytics.proto</strong></p><p>Now, when run mvn clean install (or mvn compile), Maven will automatically generate the Java classes (e.g., AnalyticsProto.java, NoteRequest.java, NoteResponse.java, AnalyticsGrpc.java) in <strong>target/generated-sources/protobuf/java</strong> directory, making them available for our Java code.</p><h4>Step 3: Implement Python gRPC Service (analytics_grpc_server.py)</h4><pre>from concurrent import futures<br>import grpc<br>import analytics_pb2 # Generated from protobuf<br>import analytics_pb2_grpc # Generated from protobuf<br><br>class AnalyticsServicer(analytics_pb2_grpc.AnalyticsServicer):<br>    def AnalyzeNote(self, request, context):<br>        &quot;&quot;&quot;<br>        Implements the gRPC AnalyzeNote method.<br>        Performs a simple word count and returns it as a score.<br>        &quot;&quot;&quot;<br>        text = request.note_text<br>        word_count = len(text.split())<br>        # Example of adding more analysis: simple keyword extraction<br>        keywords = [word for word in text.lower().split() if len(word) &gt; 3 and word.isalpha()]<br>        return analytics_pb2.NoteResponse(score=word_count, keywords=list(set(keywords)))<br><br>def serve_grpc():<br>    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))<br>    analytics_pb2_grpc.add_AnalyticsServicer_to_server(AnalyticsServicer(), server)<br>    server.add_insecure_port(&#39;[::]:50051&#39;) # Listen on all interfaces on port 50051<br>    server.start()<br>    print(&quot;gRPC Analytics Service started on port 50051&quot;)<br>    server.wait_for_termination()<br><br>if __name__ == &quot;__main__&quot;:<br>    serve_grpc()</pre><h4>Step 4: Java gRPC Client Invoking Python Analytics Service</h4><pre>package com.example.authservice.service; <br>import analytics.AnalyticsGrpc; // Generated gRPC client<br>import analytics.NoteRequest;<br>import analytics.NoteResponse;<br>import io.grpc.ManagedChannel;<br>import io.grpc.ManagedChannelBuilder;<br>import org.springframework.stereotype.Service;<br>import javax.annotation.PreDestroy; // For proper shutdown<br><br>@Service<br>public class GrpcAnalyticsClient {<br>    private final ManagedChannel channel;<br>    private final AnalyticsGrpc.AnalyticsBlockingStub blockingStub;<br><br>    public GrpcAnalyticsClient() {<br>        // &#39;analytics&#39; is the service name in Docker Compose<br>        this.channel = ManagedChannelBuilder.forAddress(&quot;analytics&quot;, 50051)<br>                .usePlaintext() // Use plaintext for local development; use SSL in production<br>                .build();<br>        this.blockingStub = AnalyticsGrpc.newBlockingStub(channel);<br>    }<br>    <br>    public NoteResponse getAnalysisFromPython(String noteText) {<br>        NoteRequest request = NoteRequest.newBuilder()<br>                .setNoteText(noteText)<br>                .build();<br>        return blockingStub.analyzeNote(request);<br>    }<br>    <br>    @PreDestroy // Ensure channel shutdown on Spring application context close<br>    public void shutdown() throws InterruptedException {<br>        channel.shutdown().awaitTermination();<br>        System.out.println(&quot;gRPC channel shut down.&quot;);<br>    }<br>}</pre><h3>Phase 3: Deployment and Best Practices</h3><h3>Full Working Local Stack (Docker Compose Example Outline)</h3><p>To bring it all together, here’s an updated <strong>docker-compose.yml</strong> including Kafka and Zookeeper for the event driven architecture, and specifying ports for gRPC.</p><pre>version: &#39;3.8&#39;<br>services:<br>  auth-service:<br>    build:<br>      context: ./auth-service<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      - SPRING_PROFILES_ACTIVE=prod<br>      - KAFKA_BROKER=broker:9092 # For publishing events<br>    depends_on:<br>      - broker<br>    # can Add database if needed<br>analytics-service:<br>    build:<br>      context: ./analytics-service<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8000:8000&quot; # For REST endpoint (if still needed)<br>      - &quot;50051:50051&quot; # For gRPC endpoint<br>    environment:<br>      - KAFKA_BROKER=broker:9092 # For consuming events<br>      - GRPC_PORT=50051 # For gRPC server<br>    depends_on:<br>      - broker<br>broker: # Kafka Broker<br>    image: confluentinc/cp-kafka:7.6.1 # Use a stable Kafka image<br>    hostname: broker<br>    container_name: broker<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: &#39;zookeeper:2181&#39;<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1<br>    depends_on:<br>      - zookeeper<br>zookeeper:<br>    image: confluentinc/cp-zookeeper:7.6.1 # Use a stable Zookeeper image<br>    hostname: zookeeper<br>    container_name: zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>volumes:<br>  postgres_data:</pre><h3>Advanced Integration (GraalVM: Why not for production?)</h3><ul><li><strong>GraalVM:</strong> An evolving polyglot VM that allows Java and Python (among others) to run in the same memory space. While powerful, its setup can be nontrivial, and not all Python libraries or features are fully supported or performant yet. I talked about this in brief in my previous article.</li></ul><p>For production grade polyglot microservices, stick to well defined network protocols like REST, gRPC, or message queues (Kafka, RabbitMQ) for inter-service communication.</p><h3>Testing, Monitoring and Scaling</h3><ul><li><strong>Unit/Integration Tests:</strong> Use native testing frameworks (<strong>JUnit</strong> for Java, <strong>Pytest</strong> for Python).</li><li><strong>API level Contracts:</strong> Define and version OpenAPI/Swagger specs for REST interfaces and Protobuf schemas for gRPC. This ensures compatibility between services.</li><li><strong>Monitor</strong> each container with tools like <strong>Prometheus</strong> for metrics, <strong>Grafana</strong> for visualization, and <strong>Jaeger</strong> or <strong>OpenTelemetry</strong> for distributed tracing across services.</li><li>Implement health checks (/actuator/health for Spring Boot, custom endpoints for FastAPI).</li><li><strong>Scaling:</strong> Each service can scale horizontally in Docker, Kubernetes, or other container orchestration platforms based on its unique usage patterns and resource requirements.</li></ul><h3>Conclusion</h3><p>We’ve seen how:</p><ul><li><strong>Polyglot microservices</strong> enable maximum agility, letting every service use its ideal language and stack.</li><li><strong>Java Spring Boot</strong> powers robust, scalable core functionality, especially for security and enterprise grade needs.</li><li><strong>Python FastAPI</strong> brings data processing, machine learning(can do, I didn’t do in this article), and rapid prototyping capabilities to the same ecosystem.</li><li><strong>APIs (REST)</strong> and advanced communication patterns like <strong>Event Driven Kafka</strong> and <strong>gRPC with Protocol Buffers</strong> are the backbone of safe, reliable, and high performance cross-language communication.</li></ul><p><strong>Keep on coding people, until the next one!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49426df0953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Error Analysis Microservice from Spring Boot to Micronaut]]></title>
            <link>https://medium.com/@ayushgupta228/my-error-analysis-microservice-from-spring-boot-to-micronaut-9fabef0e36c8?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fabef0e36c8</guid>
            <category><![CDATA[micronaut]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 06:01:45 GMT</pubDate>
            <atom:updated>2025-07-13T06:43:43.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULeJC3o-d9s6zI5IdfbNGg.png" /></figure><h3>What Was I Building?</h3><ul><li>REST API: Accepts error logs (stack traces, CORS, SQL, etc.)</li><li>Analyzes/classifies errors &amp; checks for sensitive info (tokens, emails)</li><li>Stores results in MongoDB</li><li>Dashboard endpoint for UI (drag-and-drop file upload)</li><li>JWT-secured endpoints</li><li>CORS support</li><li>Observability endpoints</li><li>Native image ready</li><li>Frontend: Drag-and-drop log upload, live analysis</li></ul><h3>Step 1: Micronaut Maven Project Setup</h3><p>pom.xml essentials:</p><pre>&lt;dependencyManagement&gt;<br>  &lt;dependencies&gt;<br>    &lt;dependency&gt;<br>      &lt;groupId&gt;io.micronaut.platform&lt;/groupId&gt;<br>      &lt;artifactId&gt;micronaut-platform&lt;/artifactId&gt;<br>      &lt;version&gt;4.0.0&lt;/version&gt;<br>      &lt;type&gt;pom&lt;/type&gt;<br>      &lt;scope&gt;import&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>  &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;<br><br>&lt;dependencies&gt;<br>  &lt;!-- Core Micronaut --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-runtime&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- HTTP Server --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-http-server-netty&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- MongoDB Sync --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut.mongodb&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-mongo-sync&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- Security (JWT) --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut.security&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-security-jwt&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- Management endpoints --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-management&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- Annotation processor --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-inject-java&lt;/artifactId&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- JUnit 5 for tests --&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;io.micronaut.test&lt;/groupId&gt;<br>    &lt;artifactId&gt;micronaut-test-junit5&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>    &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>Step 2: MongoDB Configuration</h3><p>application.yml:</p><pre>mongodb:<br>  uri: mongodb://myuser:mypassword@localhost:27017/errorlogsdbdb:<br>  name: errorlogsdb<br>  collection: error_logs<br>micronaut:<br>  server:<br>    cors:<br>      enabled: true<br>      configurations:<br>        ui:<br>          allowed-origins:<br>            - &quot;http://localhost:3000&quot;<br>          allowed-methods:<br>            - GET<br>            - POST<br>          allowed-headers:<br>            - &quot;*&quot;<br>  security:<br>    enabled: true<br>    token:<br>      jwt:<br>        signatures:<br>          secret:<br>            generator:<br>              secret: &quot;supersecretkey&quot;<br>endpoints:<br>  all:<br>    path: /actuator<br>  health:<br>    enabled: true<br>    sensitive: false<br>  beans:<br>    enabled: true<br>    sensitive: false</pre><h3>Step 3: MongoDB Entity, Config, and Repository</h3><p>MongoDbConfiguration.java</p><pre>package com.example;<br>import io.micronaut.context.annotation.ConfigurationProperties;<br>import io.micronaut.core.annotation.NonNull;<br>import io.micronaut.core.naming.Named;<br><br>@ConfigurationProperties(&quot;db&quot;)<br>public interface MongoDbConfiguration extends Named {<br>    @NonNull String getCollection();<br>}</pre><p>ErrorLog.java</p><pre>package com.example;<br>import org.bson.codecs.pojo.annotations.BsonId;<br><br>public class ErrorLog {<br>    @BsonId<br>    private String id;<br>    private String message;<br>    private String type;<br>    private String stackTrace;<br>    // Constructors, getters, setters<br>    public ErrorLog() {}<br>    public ErrorLog(String message, String type, String stackTrace) {<br>        this.message = message;<br>        this.type = type;<br>        this.stackTrace = stackTrace;<br>    }<br>    // getters/setters, can come below this....<br>}</pre><p>ErrorLogRepository.java</p><pre>package com.example;<br>import com.mongodb.client.MongoClient;<br>import com.mongodb.client.MongoCollection;<br>import com.mongodb.client.model.Filters;<br>import jakarta.inject.Singleton;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>@Singleton<br>public class ErrorLogRepository {<br>    private final MongoDbConfiguration mongoConf;<br>    private final MongoClient mongoClient;<br>    public ErrorLogRepository(MongoDbConfiguration mongoConf, MongoClient mongoClient) {<br>        this.mongoConf = mongoConf;<br>        this.mongoClient = mongoClient;<br>    }<br>    private MongoCollection&lt;ErrorLog&gt; getCollection() {<br>        return mongoClient<br>            .getDatabase(mongoConf.getName())<br>            .getCollection(mongoConf.getCollection(), ErrorLog.class);<br>    }<br>    public ErrorLog save(ErrorLog log) {<br>        getCollection().insertOne(log);<br>        return log;<br>    }<br>    public List&lt;ErrorLog&gt; findAll() {<br>        return getCollection().find().into(new ArrayList&lt;&gt;());<br>    }<br>}</pre><h3>Step 4: Error Analysis Service</h3><p>ErrorAnalyzer.java</p><pre>package com.example;<br>import jakarta.inject.Singleton;<br><br>@Singleton<br>public class ErrorAnalyzer {<br>    public String analyze(String message) {<br>        if (message.contains(&quot;NullPointerException&quot;)) return &quot;NullPointer&quot;;<br>        if (message.contains(&quot;CORS&quot;)) return &quot;CORS&quot;;<br>        if (message.contains(&quot;SQL&quot;)) return &quot;Database&quot;;<br>        return &quot;Unknown&quot;;<br>    }<br>    public boolean containsSensitiveInfo(String log) {<br>        return log.matches(&quot;.*(token=\\w+|[\\w.-]+@[\\w.-]+).*&quot;);<br>    }<br>}</pre><h3>Step 5: REST Controller (with File Upload, JWT, Error Handling)</h3><p>ErrorController.java</p><pre>package com.example;<br>import io.micronaut.http.annotation.*;<br>import io.micronaut.http.HttpResponse;<br>import io.micronaut.http.MediaType;<br>import io.micronaut.http.multipart.CompletedFileUpload;<br>import io.micronaut.security.annotation.Secured;<br>import io.micronaut.security.rules.SecurityRule;<br>import jakarta.inject.Inject;<br>import java.io.IOException;<br>import java.nio.charset.StandardCharsets;<br>import java.util.List;<br><br>@Controller(&quot;/api/errors&quot;)<br>public class ErrorController {<br>    private final ErrorLogRepository repo;<br>    private final ErrorAnalyzer analyzer;<br>    @Inject<br>    public ErrorController(ErrorLogRepository repo, ErrorAnalyzer analyzer) {<br>        this.repo = repo; this.analyzer = analyzer;<br>    }<br><br>    @Post(value = &quot;/&quot;, consumes = MediaType.APPLICATION_JSON)<br>    @Secured(SecurityRule.IS_AUTHENTICATED)<br>    public HttpResponse&lt;ErrorLog&gt; analyzeAndSave(@Body ErrorLog log) {<br>        String type = analyzer.analyze(log.getMessage());<br>        log.setType(type);<br>        ErrorLog saved = repo.save(log);<br>        return HttpResponse.created(saved);<br>    }<br><br>    @Get(&quot;/&quot;)<br>    @Secured(SecurityRule.IS_AUTHENTICATED)<br>    public List&lt;ErrorLog&gt; all() { <br>      return repo.findAll(); <br>    }<br><br>    @Post(value = &quot;/upload&quot;, consumes = MediaType.MULTIPART_FORM_DATA)<br>    @Secured(SecurityRule.IS_AUTHENTICATED)<br>    public ErrorAnalysisResult upload(@Part CompletedFileUpload file) throws IOException {<br>        String content = new String(file.getBytes(), StandardCharsets.UTF_8);<br>        String type = analyzer.analyze(content);<br>        boolean hasSensitive = analyzer.containsSensitiveInfo(content);<br>        return new ErrorAnalysisResult(type, hasSensitive);<br>    }<br>}<br><br>class ErrorAnalysisResult {<br>    public String errorType;<br>    public boolean sensitiveInfo;<br>    public ErrorAnalysisResult(String errorType, boolean sensitiveInfo) {<br>        this.errorType = errorType;<br>        this.sensitiveInfo = sensitiveInfo;<br>    }<br>}</pre><p>GlobalExceptionHandler.java</p><pre>package com.example;<br>import io.micronaut.http.*;<br>import io.micronaut.http.server.exceptions.ExceptionHandler;<br>import jakarta.inject.Singleton;<br><br>@Singleton<br>public class GlobalExceptionHandler implements ExceptionHandler&lt;Exception, HttpResponse&lt;?&gt;&gt; {<br>    @Override<br>    public HttpResponse&lt;?&gt; handle(HttpRequest request, Exception exception) {<br>        return HttpResponse.serverError(new ErrorResponse(&quot;Internal Error&quot;, exception.getMessage()));<br>    }<br>}<br><br>class ErrorResponse {<br>    public String error;<br>    public String details;<br>    public ErrorResponse(String error, String details) {<br>        this.error = error;<br>        this.details = details;<br>    }<br>}</pre><h3>Step 6: Observability &amp; Management</h3><ul><li><strong>endpoints</strong> : /actuator/health, /actuator/beans</li><li>To enable observability and management endpoints like /actuator/health and /actuator/beans in a Micronaut (Maven-based) project, you need to:</li></ul><p>1. Add the Management Dependency</p><p>pom.xml:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.micronaut&lt;/groupId&gt;<br>  &lt;artifactId&gt;micronaut-management&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>2. Configure Endpoints in application.yml</p><p>Add this part to your src/main/resources/application.yml:</p><pre>endpoints:<br>  all:<br>    path: /actuator<br>  health:<br>    enabled: true<br>    sensitive: false<br>  beans:<br>    enabled: true<br>    sensitive: false</pre><ul><li>path: /actuator means your management endpoints will be under /actuator/* (e.g., /actuator/health, /actuator/beans).</li><li>enabled: true turns on the endpoints.</li><li>sensitive: false makes them accessible without authentication (set to true for production security).</li></ul><p>3. Start Your Application</p><p>Now, when you run your Micronaut app, you can access:</p><ul><li>Health check: <a href="http://localhost:8080/actuator/health">http://localhost:8080/actuator/health</a></li><li>Beans info: <a href="http://localhost:8080/actuator/beans">http://localhost:8080/actuator/beans</a></li></ul><h3>Step 7: Native Image (GraalVM)</h3><p>pom.xml plugin:</p><pre>&lt;plugin&gt;<br>  &lt;groupId&gt;io.micronaut.maven&lt;/groupId&gt;<br>  &lt;artifactId&gt;micronaut-maven-plugin&lt;/artifactId&gt;<br>  &lt;version&gt;4.0.0&lt;/version&gt;<br>  &lt;executions&gt;<br>    &lt;execution&gt;<br>      &lt;goals&gt;<br>        &lt;goal&gt;native-image&lt;/goal&gt;<br>      &lt;/goals&gt;<br>    &lt;/execution&gt;<br>  &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>Build:</p><pre>./mvnw mn:native-image</pre><p><strong>Note</strong>:- If you hit a reflection error, add a reflect-config.json and stick to Micronaut-supported libs.</p><h3>Step 8: Live Error Analyzer Dashboard (Frontend Example)</h3><p>HTML/JS for drag-and-drop log upload:</p><pre>&lt;div id=&quot;dropzone&quot; style=&quot;padding:2em; border:2px dashed #888; background:#222; color:#fff;&quot;&gt;<br>  &lt;p&gt;Drag &amp; drop your error log here&lt;/p&gt;<br>  &lt;div id=&quot;result&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;script&gt;<br>const dz = document.getElementById(&#39;dropzone&#39;);<br>dz.ondragover = e =&gt; { e.preventDefault(); dz.style.background = &#39;#444&#39;; };<br>dz.ondragleave = e =&gt; { dz.style.background = &#39;#222&#39;; };<br>dz.ondrop = e =&gt; {<br>  e.preventDefault(); dz.style.background = &#39;#222&#39;;<br>  const file = e.dataTransfer.files[0];<br>  const form = new FormData(); form.append(&#39;file&#39;, file);<br>  fetch(&#39;/api/errors/upload&#39;, { method: &#39;POST&#39;, body: form, headers: { &#39;Authorization&#39;: &#39;Bearer &lt;your-jwt-token&gt;&#39; } })<br>    .then(r =&gt; r.json())<br>    .then(res =&gt; {<br>      dz.querySelector(&#39;#result&#39;).innerHTML =<br>        `&lt;b&gt;Error Type:&lt;/b&gt; ${res.errorType}&lt;br&gt;<br>         &lt;b&gt;Sensitive Info:&lt;/b&gt; ${res.sensitiveInfo ? &#39;Yes&#39; : &#39;No&#39;}`;<br>    });<br>};<br>&lt;/script&gt;</pre><h3>Step 9: Testing (JUnit 5 + Micronaut)</h3><p>ErrorAnalyzerTest.java</p><pre>import io.micronaut.test.extensions.junit5.annotation.MicronautTest;<br>import org.junit.jupiter.api.Test;<br>import jakarta.inject.Inject;<br>import static org.junit.jupiter.api.Assertions.*;<br><br>@MicronautTest<br>class ErrorAnalyzerTest {<br>    @Inject ErrorAnalyzer analyzer;<br>    @Test<br>    void testAnalyze() {<br>        assertEquals(&quot;CORS&quot;, analyzer.analyze(&quot;CORS preflight failed&quot;));<br>    }<br>}</pre><h3>Step 10: Performance and Results</h3><p>Let’s talk real numbers, on my own setup:<br>12GB RAM (8GB internal + 4GB external), i5 8th Gen laptop.</p><p><strong>Startup Time</strong></p><p>Honestly, this is where I first noticed the difference:</p><ul><li><strong>Micronaut</strong>: My service (with MongoDB, JWT, file upload, etc.) starts up in about 1.5 seconds. Sometimes even faster if I’m not running a bunch of other stuff.</li><li><strong>Spring</strong> <strong>Boot</strong>: Same project, same features, takes anywhere from 5 to 8 seconds to get going. It’s fine, but it feels slow once you’ve seen Micronaut.</li></ul><p><strong>Memory Usage</strong></p><p>I kept an eye on memory in Task Manager and with JVM flags:</p><ul><li>Micronaut: Sits around 65-70MB used heap after startup, total JVM memory almost 170MB.</li><li>Spring Boot: Used heap is usually 150-180MB, and total JVM memory can hit 300MB+ with the same codebase.</li></ul><p>So, Micronaut is way lighter on RAM, which matters when you’re running multiple services or working in containers.</p><p><strong>Native Image (GraalVM)</strong></p><ul><li>Micronaut native image: Starts in under 100ms. Memory usage drops to 20-25MB.</li><li>Spring Boot native: Still experimental for bigger services; I had more issues getting it to work smoothly.</li></ul><p><strong>My Honest Take</strong></p><p>On my hardware, Micronaut just feels snappier and more efficient.</p><ul><li>If you care about fast restarts, low memory, or running lots of services at once, it’s a no-brainer.</li><li>For big, complex monoliths, Spring Boot is still great, but for microservices, especially with MongoDB and JWT, Micronaut is just faster and lighter.</li></ul><h3>When You May Try This?</h3><ul><li>You want server less Java microservices</li><li>You care about startup time and memory (K8s, Lambda, edge)</li><li>You want compile-time DI safety</li><li>You want to build lightweight APIs with less bloat</li></ul><h3>Final Thoughts</h3><p>I used Micronaut because it is new, fast, cloud-native Java service, it’s the most exciting framework I’ve used in years.</p><p>If you want your microservice to start fast, run in a tiny container, can give Micronaut a try.</p><p>See you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fabef0e36c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Auth to Access: Securing Inter-Service Communication in Microservices]]></title>
            <link>https://medium.com/@ayushgupta228/from-auth-to-access-securing-inter-service-communication-in-microservices-130b5ab5ca68?source=rss-d90a0284330------2</link>
            <guid isPermaLink="false">https://medium.com/p/130b5ab5ca68</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[internal-api]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ayush Gupta]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 06:08:42 GMT</pubDate>
            <atom:updated>2025-06-16T06:22:30.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*WIJR8iDR8kW5K2LO8BNtfA.png" /></figure><p>How do you ensure that your services only talk to each other when they’re supposed to?<br>Let’s break it down, step by step, with code, flowcharts and best practices.</p><h3>Why Secure Communication Matters</h3><p>In a microservice architecture, services are like buildings in a city.<br>They need to share information, but only with trusted neighbors.<br>If you don’t secure these conversations, attackers can eavesdrop, impersonate services, or steal data.</p><p>Authentication (proving who you are) and authorization (proving what you’re allowed to do) are the keys to keeping your digital neighborhood safe.</p><h3>The Big Picture: How Auth Works in Microservices</h3><p>Let’s imagine two services:</p><ul><li><strong>Auth Service:</strong> The security guard and ID card issuer.</li><li><strong>User Service:</strong> The vault where user data is stored.</li></ul><p>When the Auth Service needs user info, it must prove its identity to the User Service.<br>This is where <strong>OAuth2</strong> and <strong>JWT</strong> come in.</p><h3>The Basic Flow</h3><pre>    sequenceDiagram:-<br><br>    participant AuthService as Auth Service (Client)<br>    participant AuthServer as Auth Service (Auth Server)<br>    participant UserService as User Service (Resource Server)<br><br>    AuthService -&gt; AuthServer:  Request Token (Client Credentials)<br>    AuthServer  -&gt; AuthService: Return Access Token (JWT)<br>    AuthService -&gt; UserService: Request with Bearer Token<br>    UserService -&gt; AuthService: Validate Token &amp; Respond</pre><p>This is the OAuth2 Client Credentials Grant, perfect for service-to-service communication.</p><h3>Step-by-Step: Implementing Secure Inter-Service Auth</h3><h3>1. Auth Service: Issue Tokens</h3><p>The Auth Service is both the token issuer and a client.</p><h3>Register Internal Clients</h3><pre>RegisteredClient internalService = RegisteredClient.withId(UUID.randomUUID().toString())<br>    .clientId(&quot;internal-service&quot;)<br>    .clientSecret(&quot;{noop}internal-secret&quot;)<br>    .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)<br>    .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)<br>    .scope(&quot;internal_service_scope&quot;)<br>    .tokenSettings(TokenSettings.builder()<br>        .accessTokenTimeToLive(Duration.ofHours(1))<br>        .build())<br>    .build();</pre><p><strong>Best Practice:</strong></p><ul><li>Use short-lived tokens (e.g., 1 hour).</li><li>Store secrets securely — never in plaintext in production.</li></ul><h3>2. User Service: Validate Tokens</h3><p>The User Service must trust tokens issued by the Auth Service.</p><h3>Spring Security Configuration</h3><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .anyRequest().authenticated()<br>            )<br>            .oauth2ResourceServer(oauth2 -&gt; oauth2.jwt());<br>        return http.build();<br>    }<br>    @Bean<br>    public JwtDecoder jwtDecoder() {<br>        // For local development:<br>        // return NimbusJwtDecoder.withJwkSetUri(&quot;http://localhost:8080/oauth2/jwks&quot;).build();<br>        return NimbusJwtDecoder.withJwkSetUri(&quot;http://auth-service:8080/oauth2/jwks&quot;).build();<br>    }<br>}</pre><p><strong>Best Practice:</strong></p><ul><li>Validate every token — check signature, expiry, and issuer.</li><li>Use HTTPS for all communication.</li></ul><h3>3. Auth Service: Call User Service Securely</h3><p>The Auth Service needs to fetch a token and use it to call the User Service.</p><h3>OAuth2 Client Configuration</h3><pre># For local development:<br>spring.security.oauth2.client.registration.internal-service.client-id=internal-service<br>spring.security.oauth2.client.registration.internal-service.client-secret=internal-secret<br>spring.security.oauth2.client.registration.internal-service.authorization-grant-type=client_credentials<br>spring.security.oauth2.client.registration.internal-service.scope=internal_service_scope<br>spring.security.oauth2.client.provider.self.issuer-uri=http://localhost:8080<br>spring.security.oauth2.client.provider.self.token-uri=http://localhost:8080/oauth2/token<br><br># For prod:<br># spring.security.oauth2.client.provider.self.issuer-uri=http://auth-service:8080<br># spring.security.oauth2.client.provider.self.token-uri=http://auth-service:8080/oauth2/token</pre><p><strong>Best Practice:</strong></p><ul><li>Automatically attach tokens to outgoing requests.</li><li>Rotate secrets regularly.</li></ul><h3>4. Automate Token Handling with WebClient</h3><pre>@Service<br>public class UserServiceClientImpl {<br>    private final WebClient webClient;<br><br>    public UserServiceClientImpl(<br>        WebClient.Builder webClientBuilder,<br>        OAuth2AuthorizedClientManager authorizedClientManager,<br>        ClientRegistrationRepository clientRegistrationRepository<br>    ) {<br>        this.webClient = webClientBuilder<br>            .baseUrl(&quot;http://user-service:8081&quot;) // For prod, or use &quot;http://localhost:8081&quot; for local dev<br>            .filter((request, next) -&gt; {<br>                var clientRegistration = clientRegistrationRepository.findByRegistrationId(&quot;internal-service&quot;);<br>                OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(<br>                    OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistration.getRegistrationId())<br>                        .principal(&quot;internal-auth-service-principal&quot;)<br>                        .build()<br>                );<br>                if (authorizedClient != null &amp;&amp; authorizedClient.getAccessToken() != null) {<br>                    return next.exchange(ClientRequest.from(request)<br>                        .header(HttpHeaders.AUTHORIZATION, &quot;Bearer &quot; + authorizedClient.getAccessToken().getTokenValue())<br>                        .build());<br>                }<br>                // token acquisition failure<br>                return Mono.error(new RuntimeException(&quot;Failed to acquire OAuth2 token&quot;));<br>            })<br>            .build();<br>    }<br>}</pre><p><strong>Best Practice:</strong></p><ul><li>Log failed token acquisitions for monitoring.</li><li>Handle token expiry gracefully.</li></ul><h3>Full Inter-Service Auth Flow</h3><pre>    flowchart TD :-<br><br>    A[Auth Service (needs user info)] -&gt; B[WebClient Intercepts Request]<br>    B -&gt; C[OAuth2AuthorizedClientManager: Get Token]<br>    C - Token Exists -&gt; E[Attach Token to Request]<br>    C - Token Missing/Expired -&gt; D[Request Token from Auth Server]<br>    D -&gt; E<br>    E -&gt; F[Send Request to User Service]<br>    F -&gt; G[User Service Validates Token]<br>    G - Valid -&gt; H[Controller Executes]<br>    G - Invalid -&gt; I[Return 403 Forbidden]<br>    H -&gt; J[Return Data to Auth Service]</pre><h3>Best Practices and Real-World Advice</h3><h3>1. Secrets Management in Production</h3><p>Never store secrets in code or properties files.<br>Use a secrets manager app or environment variables injected at runtime.</p><pre>spring.security.oauth2.client.registration.internal-service.client-id=${INTERNAL_SERVICE_CLIENT_ID}<br>spring.security.oauth2.client.registration.internal-service.client-secret=${INTERNAL_SERVICE_CLIENT_SECRET}</pre><h3>2. Token Rotation and Key Management</h3><ul><li>Rotate secrets and keys regularly.</li><li>Use automated tools to manage key rotation.</li><li>Monitor for leaked secrets and revoke them immediately.</li></ul><h3>3. Fine-Grained Authorization</h3><p>Map JWT claims to Spring Security roles for more control.</p><pre>@Bean<br>public JwtAuthenticationConverter jwtAuthenticationConverter() {<br>    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();<br>    grantedAuthoritiesConverter.setAuthorityPrefix(&quot;ROLE_&quot;);<br>    grantedAuthoritiesConverter.setAuthoritiesClaimName(&quot;scope&quot;);<br>    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();<br>    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);<br>    return jwtAuthenticationConverter;<br>}</pre><h3>4. Testing and CI/CD</h3><ul><li>Integration Tests: Ensure only authorized services can access endpoints.</li></ul><pre>@Test<br>public void testUnauthenticatedAccess() {<br>    webTestClient.get().uri(&quot;/api/users/123&quot;)<br>        .exchange()<br>        .expectStatus().isUnauthorized();<br>}</pre><ul><li>CI/CD Pipeline: Automate secret injection and deployment.</li></ul><h3>5. Monitoring and Logging</h3><ul><li>Log auth failures and monitor for anomalies.</li><li>Set up alerts for unusual access patterns.</li></ul><h3>6. Resilience and Error Handling</h3><ul><li><strong>Retry Logic:</strong> Handle token acquisition failures gracefully.</li><li><strong>Circuit Breakers:</strong> Use resilience patterns for inter-service calls.</li><li><strong>Error Responses:</strong> Return clear error messages for invalid tokens or unauthorized access.</li></ul><h3>7. Architecture Diagram</h3><p>Here’s a high-level view of the architecture:</p><pre>    flowchart LR :-<br><br>    A[Auth Service] - Issues Tokens -&gt; B[Auth Server]<br>    A - Requests User Data -&gt; C[User Service]<br>    C - Validates Tokens -&gt; B</pre><h3>8. Enforce HTTPS</h3><p>To enable HTTPS in Spring Boot, add the following to your application.properties and include your keystore:</p><pre>server.ssl.enabled=true<br>server.ssl.key-store-type=PKCS12<br>server.ssl.key-store=classpath:keystore.p12<br>server.ssl.key-store-password=yourpassword</pre><p>This ensures all communication is encrypted.</p><h3>9. Avoiding Circular Dependencies</h3><p>Circular dependencies happen when two or more services depend on each other, directly or indirectly (e.g., Service A → Service B → Service C → Service A).<br>This tight coupling makes deployment, scaling, and maintenance harder.</p><h3>How to Avoid Circular Dependencies</h3><ul><li><strong>Design Services as a Directed Acyclic Graph (DAG):<br></strong>Ensure dependencies only flow in one direction — never in a loop.</li><li><strong>Use Event-Driven Architecture: </strong>Instead of direct calls, publish events or messages. Other services can subscribe and react asynchronously, breaking the dependency chain.</li><li><strong>Consolidate Related Services: </strong>If two services are tightly coupled, consider merging them.</li><li><strong>Duplicate Data When Needed: </strong>Store relevant data in multiple services to reduce cross-service calls.</li><li><strong>Refactor Regularly: </strong>Review and refactor your architecture to catch and remove circular dependencies early.</li></ul><pre>    flowchart LR :-<br><br>    A[Service A] -- Publishes Event --&gt; Q[Message Queue]<br>    Q -- Consumes Event --&gt; B[Service B]<br>    Q -- Consumes Event --&gt; C[Service C]</pre><h3>10. API Gateway and Rate Limiting</h3><p>For production, consider using an API gateway like <strong>Spring Cloud Gateway</strong> or <strong>Kong</strong> to centralize security, rate limiting, and request routing.</p><h3>11. CORS Configuration</h3><p>If your services are accessed from browsers, configure CORS in your resource server:</p><pre>@Bean<br>public CorsFilter corsFilter() {<br>    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>    CorsConfiguration config = new CorsConfiguration();<br>    config.setAllowCredentials(true);<br>    config.addAllowedOrigin(&quot;https://frontend-url.com&quot;);<br>    config.addAllowedHeader(&quot;*&quot;);<br>    config.addAllowedMethod(&quot;*&quot;);<br>    source.registerCorsConfiguration(&quot;/**&quot;, config);<br>    return new CorsFilter(source);<br>}</pre><h3>12. Troubleshooting Common Issues</h3><ul><li><strong>401 Unauthorized: </strong>Check if the token is expired or invalid and ensure the token is attached to the request.</li><li><strong>403 Forbidden: </strong>Check if the token has the required scopes or roles.</li><li><strong>Service Unavailable: </strong>Check if the service is running and reachable, also verify service discovery and network configuration.</li><li><strong>Token Acquisition Failure: </strong>Check client credentials and token endpoint and monitor logs for errors.</li></ul><h3>13. Common Mistakes and How to Avoid Them</h3><ul><li><strong>Hardcoding secrets</strong>: Always use external secrets management.</li><li><strong>Ignoring token validation</strong>: Always validate tokens on the resource server.</li><li><strong>Broad scopes</strong>: Use fine-grained scopes to limit access.</li><li><strong>Monitoring</strong>: Always log and monitor auth events.</li></ul><h3>Real-World Example: Order Service Calling Inventory</h3><p><strong>Scenario</strong>: Your Order Service needs to check stock in the Inventory Service.</p><p><strong>How it works:</strong></p><ol><li>Order Service requests a token from the Auth Service.</li><li>Order Service calls the Inventory Service with the token.</li><li>Inventory Service validates the token before responding.</li></ol><p><strong>User Benefit: </strong>Customers see accurate stock info and their orders are processed securely.</p><h3>Sample Project Structure</h3><p>Check out a sample project structure:</p><pre>microservices-auth-example/<br>├── auth-service/<br>│   ├── src/main/java/com/example/auth/<br>│   │   ├── config/AuthServerConfig.java<br>│   │   └── ...<br>├── user-service/<br>│   ├── src/main/java/com/example/user/<br>│   │   ├── config/SecurityConfig.java<br>│   │   └── ...<br>└── README.md</pre><h3>Key Takeaways</h3><ul><li>Centralize auth rules before enforcing them everywhere.</li><li>Use short-lived tokens and HTTPS.</li><li>Monitor and test your auth flows.</li><li>Manage secrets securely.</li><li>Mapping JWT to Spring Security roles.</li><li>Avoid circular dependencies, designed for one-way data flow.</li><li>Handle errors.</li><li>Log and monitor all auth events.</li></ul><h3>What’s Next?</h3><p>If you’ve found this guide helpful, you might be wondering: what comes next?<br>Many teams take their microservices security to the next level by introducing an API gateway, a central entry point that handles authentication, routing, and more.</p><p><strong>Would you like to see a deep dive into using an API gateway like Spring Cloud Gateway or Kong in your microservices architecture?<br></strong>Let me know in the comments or on social media!</p><p>Stay tuned, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=130b5ab5ca68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>