<?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 Jatin Goyal on Medium]]></title>
        <description><![CDATA[Stories by Jatin Goyal on Medium]]></description>
        <link>https://medium.com/@jating4you?source=rss-1e02056ea35d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*a5lcbvvaxlsY5PwD.</url>
            <title>Stories by Jatin Goyal on Medium</title>
            <link>https://medium.com/@jating4you?source=rss-1e02056ea35d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 09:17:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jating4you/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[Euclid’s Algorithm and GCD: Why It Was Invented, Why Fibonacci Is the Worst Case, and Where the…]]></title>
            <link>https://medium.com/@jating4you/euclids-algorithm-and-gcd-why-it-was-invented-why-fibonacci-is-the-worst-case-and-where-the-e425408008b0?source=rss-1e02056ea35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e425408008b0</guid>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Jatin Goyal]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 10:20:55 GMT</pubDate>
            <atom:updated>2025-12-24T10:20:55.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>Euclid’s Algorithm and GCD: Why It Was Invented, Why Fibonacci Is the Worst Case, and Where the Golden Ratio (and Fibonacci Heaps) Show Up</h3><p>The <strong>Greatest Common Divisor (GCD)</strong> is one of those ideas that looks simple on the surface — “the biggest number that divides both” — but keeps reappearing across mathematics, engineering, and computer science.</p><p>What makes GCD especially interesting is that the best-known way to compute it, <strong>Euclid’s Algorithm</strong>, is ancient <em>and</em> still competitive today. It also has a famous “adversarial input”: <strong>consecutive Fibonacci numbers</strong>, which trigger the maximum number of steps. And if you follow that thread far enough, you run into the <strong>golden ratio</strong> and even a data structure called the <strong>Fibonacci heap</strong>.</p><p>This blog ties those together in one coherent story.</p><h3>Why was the GCD algorithm invented?</h3><p>In modern terms we say “GCD,” but Euclid framed the problem as finding a <strong>greatest common measure</strong>: a largest unit length (or number) that “measures” both quantities exactly.</p><p>There were two big historical motivations:</p><ol><li><strong>Arithmetic: working with ratios and fractions</strong></li></ol><ul><li>If you want to simplify a fraction (a/b), you divide numerator and denominator by (\gcd(a,b)).</li><li>Euclid’s <em>Elements</em> Book VII is explicitly about integer arithmetic, ratios, and “greatest common divisor/common measure.” (<a href="https://mathcs.clarku.edu/~djoyce/java/elements/bookVII/bookVII.html?utm_source=chatgpt.com">Clark University</a>)</li></ul><p><strong>2. Geometry: testing commensurability of lengths</strong></p><p>In Book X, Euclid discusses line segments (magnitudes). Repeated subtraction (the geometric form of Euclid’s method) can be used to find a greatest common measure <strong>if it exists</strong>, and it also provides a way to detect <strong>incommensurable</strong> magnitudes (a bridge toward irrationality concepts). (<a href="https://aleph0.clarku.edu/~djoyce/elements/bookX/bookX.html?utm_source=chatgpt.com">Aleph Zero</a>)</p><p>So Euclid’s algorithm wasn’t invented as a “coding interview trick.” It was invented because <strong>measurement, ratios, and exact simplification</strong> were foundational problems in Greek mathematics. (<a href="https://www.britannica.com/science/Euclidean-algorithm?utm_source=chatgpt.com">Encyclopedia Britannica</a>)</p><h3>GCD, precisely</h3><p>For integers (a) and (b) (not both zero), the <strong>GCD</strong> is the largest positive integer that divides both.</p><ul><li>(\gcd(48,18)=6)</li><li>(\gcd(34,21)=1) → <strong>coprime</strong> / relatively prime</li></ul><h3>Euclid’s Algorithm in one identity</h3><p>Euclid’s Algorithm is built on the invariant:</p><p>[</p><p>\gcd(a,b)=\gcd(b,;a\bmod b)<br>]</p><p>Why is this true? If (a = qb + r), then (r = a — qb). Any divisor of both (a) and (b) must also divide (r), and any divisor of (b) and (r) must also divide (a). The set of common divisors doesn’t change — only the numbers shrink. (<a href="https://www.britannica.com/science/Euclidean-algorithm?utm_source=chatgpt.com">Encyclopedia Britannica</a>)</p><h3>Two equivalent “Euclid” views</h3><ul><li><strong>Subtraction form (older geometric flavor):</strong> repeatedly subtract the smaller from the larger until what remains is smaller; repeat. Book VII discussions often present this reciprocal subtraction idea. (<a href="https://mathcs.clarku.edu/~djoyce/java/elements/bookVII/bookVII.html?utm_source=chatgpt.com">Clark University</a>)</li><li><strong>Division/modulo form (what we implement):</strong> use (a \bmod b) to jump multiple subtractions at once. Britannica describes the remainder-based procedure as the standard efficient method. (<a href="https://www.britannica.com/science/Euclidean-algorithm?utm_source=chatgpt.com">Encyclopedia Britannica</a>)</li></ul><h3>A quick example</h3><p>Compute (\gcd(48,18)):</p><ul><li>(48 \bmod 18 = 12)</li><li>(18 \bmod 12 = 6)</li><li>(12 \bmod 6 = 0)</li></ul><p>✅ GCD = 6</p><p>Each remainder step is one “iteration.”</p><h3>How fast is it?</h3><p>A classic result (1844) called <strong>Lamé’s Theorem</strong> shows that the Euclidean algorithm’s step count is tightly controlled by the <em>number of digits</em> of the smaller input. In one common formulation:</p><blockquote><em>The number of division steps is at most about </em><strong><em>5 × (decimal digits of the smaller number)</em></strong><em>.</em></blockquote><p>Lamé’s analysis is also historically famous because it’s one of the earliest widely-cited runtime analyses of an algorithm — and Fibonacci numbers are central to the proof. (<a href="https://mathworld.wolfram.com/LamesTheorem.html?utm_source=chatgpt.com">MathWorld</a>)</p><h3>Why Fibonacci numbers cause the maximum number of steps</h3><h3>The key idea: quotients of 1 are “slow”</h3><p>In Euclid’s algorithm, each step looks like:</p><p>[<br>r_{i-1} = q_i r_i + r_{i+1}, \quad 0 \le r_{i+1} &lt; r_i<br>]</p><p>The algorithm shrinks fastest when the quotient (q_i) is large.<br>It shrinks <em>slowest</em> when (q_i = 1) repeatedly, because then:</p><p>[<br>r_{i-1} = r_i + r_{i+1}<br>]</p><p>That recurrence is exactly Fibonacci-style (read backwards). So the “longest chain” happens when the remainders decrease like Fibonacci numbers. This is why consecutive Fibonacci numbers are the canonical worst case. (<a href="https://people.engr.tamu.edu/andreas-klappenecker/alg/euclid.pdf?utm_source=chatgpt.com">Engineering People</a>)</p><h3>Concrete demo: (\gcd(89,55))</h3><p>(89 and 55 are consecutive Fibonacci numbers)</p><ul><li>(89 \bmod 55 = 34)</li><li>(55 \bmod 34 = 21)</li><li>(34 \bmod 21 = 13)</li><li>(21 \bmod 13 = 8)</li><li>(13 \bmod 8 = 5)</li><li>(8 \bmod 5 = 3)</li><li>(5 \bmod 3 = 2)</li><li>(3 \bmod 2 = 1)</li><li>(2 \bmod 1 = 0)</li></ul><p>The remainders are: <strong>34, 21, 13, 8, 5, 3, 2, 1</strong> — Fibonacci numbers all the way down. (<a href="https://people.engr.tamu.edu/andreas-klappenecker/alg/euclid.pdf?utm_source=chatgpt.com">Engineering People</a>)</p><h3>Why consecutive Fibonacci numbers are always coprime</h3><p>A neat supporting fact:<br>[<br>\gcd(F_{n+1}, F_n)=1<br>]</p><p>Sketch: Euclid’s identity gives<br>[<br>\gcd(F_{n+1},F_n)=\gcd(F_n,F_{n+1}-F_n)=\gcd(F_n,F_{n-1})<br>]<br>Repeat until you reach (\gcd(1,1)=1). So no “early exit” via a large divisor happens. (<a href="https://en.wikipedia.org/wiki/Euclidean_algorithm?utm_source=chatgpt.com">Wikipedia</a>)</p><h3>Where the golden ratio fits</h3><p>The <strong>golden ratio</strong> is:</p><p>[<br>\varphi = \frac{1+\sqrt{5}}{2} \approx 1.6180339887\ldots<br>]</p><p>Britannica gives this standard definition and value. (<a href="https://www.britannica.com/science/golden-ratio?utm_source=chatgpt.com">Encyclopedia Britannica</a>)</p><h3>Why does (\varphi) show up in Euclid’s runtime?</h3><p>Two connected reasons:</p><ol><li><strong>Fibonacci growth is governed by (\varphi)</strong><br>Fibonacci numbers grow roughly like powers of (\varphi), which is exactly what Lamé’s analysis leverages to turn “number of steps” into “number of digits.” (<a href="https://en.wikipedia.org/wiki/Lam%C3%A9%27s_theorem?utm_source=chatgpt.com">Wikipedia</a>)</li><li><strong>Continued fractions + Euclid are essentially the same process</strong><br>For rationals, computing the continued fraction expansion is essentially identical to running Euclid’s algorithm on numerator/denominator. (<a href="https://www.math.u-bordeaux.fr/~pjaming/M1/exposes/MA2.pdf?utm_source=chatgpt.com">Math Bordeaux</a>)</li><li>The golden ratio has the continued fraction:<br>[<br>\varphi = [1;1,1,1,\dots]<br>]<br>i.e., all 1s. (<a href="https://en.wikipedia.org/wiki/Golden_ratio?utm_source=chatgpt.com">Wikipedia</a>)</li></ol><p>“All 1s” means the Euclid quotients are as small as possible for as long as possible → the remainder chain shrinks as slowly as possible. That’s the same “worst-case shape” we saw with consecutive Fibonacci numbers (which are the convergents of this continued fraction). (<a href="https://en.wikipedia.org/wiki/Golden_ratio?utm_source=chatgpt.com">Wikipedia</a>)</p><p>So the practical intuition is:</p><blockquote><em>Ratios close to </em><strong><em>1.618…</em></strong><em> tend to be “more stubborn” for Euclid’s algorithm because they encourage long runs of quotient (=1). (</em><a href="https://mathworld.wolfram.com/LamesTheorem.html?utm_source=chatgpt.com"><em>MathWorld</em></a><em>)</em></blockquote><h3>Small code sample: Euclid GCD + step counter (Java)</h3><p>This snippet computes the number of Euclid iterations. It also compares a Fibonacci worst-case pair to a near neighbor.</p><pre>import java.math.BigInteger;</pre><pre>public final class EuclidGcdSteps {</pre><pre>  static int gcdSteps(BigInteger a, BigInteger b) {<br>    a = a.abs();<br>    b = b.abs();<br>    int steps = 0;</pre><pre>    while (!b.equals(BigInteger.ZERO)) {<br>      BigInteger r = a.mod(b);<br>      a = b;<br>      b = r;<br>      steps++;<br>    }<br>    return steps;<br>  }</pre><pre>  // F1 = 1, F2 = 1 ...<br>  static BigInteger fib(int n) {<br>    if (n &lt;= 0) throw new IllegalArgumentException(&quot;n must be &gt;= 1&quot;);<br>    if (n &lt;= 2) return BigInteger.ONE;</pre><pre>    BigInteger prev = BigInteger.ONE;<br>    BigInteger cur  = BigInteger.ONE;<br>    for (int i = 3; i &lt;= n; i++) {<br>      BigInteger next = prev.add(cur);<br>      prev = cur;<br>      cur = next;<br>    }<br>    return cur;<br>  }</pre><pre>  public static void main(String[] args) {<br>    BigInteger f10 = fib(10); // 55<br>    BigInteger f11 = fib(11); // 89</pre><pre>    System.out.println(&quot;Steps for (89,55): &quot; + gcdSteps(f11, f10)); // Fibonacci worst-case style<br>    System.out.println(&quot;Steps for (89,56): &quot; + gcdSteps(BigInteger.valueOf(89), BigInteger.valueOf(56)));<br>  }<br>}</pre><h3>Bonus: What is a Fibonacci heap?</h3><p>A <strong>Fibonacci heap</strong> is a <strong>priority queue</strong> data structure (a “heap”) designed to make one operation extremely fast:</p><blockquote><strong><em>decrease-key</em></strong><em> in </em><strong><em>amortized (O(1))</em></strong><em> time.</em></blockquote><p>It was developed by <strong>Michael L. Fredman</strong> and <strong>Robert E. Tarjan</strong> (1984; published 1987). (<a href="https://www.cl.cam.ac.uk/teaching//1213/AlgorithII/1987-FredmanTar-fibonacci.pdf?utm_source=chatgpt.com">Computer Laboratory</a>)</p><h3>What it looks like (conceptually)</h3><p>A Fibonacci heap is a <strong>collection of heap-ordered trees</strong>, not a single rigid tree like a binary heap. Its key strategy is <strong>laziness</strong>:</p><ul><li>Inserts and merges mostly just splice lists of roots.</li><li>Structure is “cleaned up” primarily during <strong>extract-min</strong> (delete-min), when trees are consolidated. (<a href="https://www.cl.cam.ac.uk/teaching//1213/AlgorithII/1987-FredmanTar-fibonacci.pdf?utm_source=chatgpt.com">Computer Laboratory</a>)</li></ul><h3>Key amortized runtimes (why people cared)</h3><p>From standard lecture notes and the original line of results:</p><ul><li><strong>insert</strong>: (O(1)) amortized</li><li><strong>find-min</strong>: (O(1)) amortized</li><li><strong>meld/merge</strong>: (O(1)) amortized</li><li><strong>decrease-key</strong>: (O(1)) amortized</li><li><strong>extract-min (delete-min)</strong>: (O(\log n)) amortized (<a href="https://www.cl.cam.ac.uk/teaching//1213/AlgorithII/1987-FredmanTar-fibonacci.pdf?utm_source=chatgpt.com">Computer Laboratory</a>)</li></ul><h3>Why is it called “Fibonacci” heap?</h3><p>Not because the structure stores Fibonacci numbers, but because the <strong>analysis</strong> uses Fibonacci-number bounds on the minimum possible size of a tree of a given degree. That Fibonacci bound is what leads to the (O(\log n)) degree limit and therefore (O(\log n)) extract-min amortized time. (<a href="https://en.wikipedia.org/wiki/Fibonacci_heap?utm_source=chatgpt.com">Wikipedia</a>)</p><h3>The classic application: faster Dijkstra / network optimization</h3><p>In shortest-path and network optimization algorithms, you often perform:</p><ul><li>many <strong>decrease-key</strong> operations</li><li>plus (n) <strong>extract-min</strong> operations</li></ul><p>Using Fibonacci heaps, a standard bound for Dijkstra’s algorithm becomes:<br>[<br>O(m + n\log n)<br>]<br>instead of the more typical (O((m+n)\log n)) with a binary heap. Princeton notes explicitly call out this motivation and improvement. (<a href="https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/FibonacciHeaps.pdf?utm_source=chatgpt.com">Princeton CS Department</a>)</p><h3>Why don’t we see Fibonacci heaps everywhere in production?</h3><p>Even the original “pairing heap” paper (a simpler alternative) states the practical reality plainly: Fibonacci heaps are theoretically efficient but <strong>complicated to implement</strong> and <strong>not as fast in practice</strong> as other heap types. (<a href="https://sedgewick.io/wp-content/themes/sedgewick/papers/1986Pairing.pdf?utm_source=chatgpt.com">Robert Sedgewick</a>)</p><p>In many real systems, you’ll see:</p><ul><li>binary / d-ary heaps (simple, cache-friendly)</li><li>pairing heaps or specialized priority queues depending on workload</li></ul><h3>Closing thought</h3><p>Euclid’s Algorithm is a rare gem: ancient, minimal, and still central in modern computation. Its worst-case story is equally elegant:</p><ul><li><strong>Worst case</strong> comes from <strong>consecutive Fibonacci numbers</strong>. (<a href="https://people.engr.tamu.edu/andreas-klappenecker/alg/euclid.pdf?utm_source=chatgpt.com">Engineering People</a>)</li><li>That worst case is connected to the <strong>golden ratio</strong> via growth rates and continued fractions. (<a href="https://mathworld.wolfram.com/LamesTheorem.html?utm_source=chatgpt.com">MathWorld</a>)</li><li>Fibonacci numbers show up again in algorithm design through <strong>Fibonacci heaps</strong>, where they help prove tight structural bounds. (<a href="https://www.cl.cam.ac.uk/teaching//1213/AlgorithII/1987-FredmanTar-fibonacci.pdf?utm_source=chatgpt.com">Computer Laboratory</a>)</li></ul><p>If you want, I can also add a short section on the <strong>Extended Euclidean Algorithm</strong> (how to compute Bézout coefficients and modular inverses), which is the next “real-world crypto” step after GCD.</p><p>Author is Coder’s High team</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e425408008b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Guide to HTTP Versions: From 0.9 to HTTP/3]]></title>
            <link>https://medium.com/@jating4you/a-quick-guide-to-http-versions-from-0-9-to-http-3-58c6e242de21?source=rss-1e02056ea35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/58c6e242de21</guid>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Jatin Goyal]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 12:05:33 GMT</pubDate>
            <atom:updated>2025-09-22T12:05:33.991Z</atom:updated>
            <content:encoded><![CDATA[<p>The web as we know it runs on <strong>HTTP (HyperText Transfer Protocol)</strong> — the foundation of data communication between browsers and servers. But like all good technologies, HTTP has evolved significantly over the years. Each version introduced new features, better performance, and improved user experience.</p><p>Let’s take a quick journey through the major versions of HTTP.</p><h3>HTTP/0.9 — The Beginning (1991)</h3><p>The very first version of HTTP was extremely simple. It only supported the <strong>GET</strong> method, and servers would just return raw HTML content.</p><ul><li>No headers.</li><li>No metadata.</li><li>Only plain HTML.</li></ul><p>This simplicity worked for the early web, but it couldn’t support images, stylesheets, or scripts that modern pages rely on.</p><h3>HTTP/1.0 — The Expansion (1996)</h3><p>With HTTP/1.0, things started to get interesting. It introduced:</p><ul><li><strong>Headers</strong> (so servers and clients could exchange metadata).</li><li><strong>Status codes</strong> (e.g., 200 OK, 404 Not Found)</li><li><strong>Content negotiation</strong> (browsers could request images, JSON, etc., not just HTML).</li></ul><p>But it still opened a <strong>new TCP connection for each request</strong>, which wasn’t very efficient.</p><h3>HTTP/1.1 — The Workhorse (1997)</h3><p>Even today, many websites still rely on HTTP/1.1. This version brought:</p><ul><li><strong>Persistent connections</strong> (multiple requests over the same TCP connection).</li><li><strong>Host headers</strong> (allowing multiple websites on one server).</li><li><strong>Chunked transfer encoding</strong> (sending dynamic data in pieces).</li></ul><p>It solved many inefficiencies, but it still had one big issue: <strong>head-of-line blocking</strong>, where one slow request could delay others.</p><h3>HTTP/2 — Speeding Things Up (2015)</h3><p>HTTP/2 was a major leap forward:</p><ul><li><strong>Binary framing</strong> instead of plain text.</li><li><strong>Multiplexing</strong> (multiple requests in parallel on a single connection).</li><li><strong>Header compression</strong> to reduce overhead.</li><li><strong>Server push</strong> (servers could send resources before the browser asked).</li></ul><p>This made web browsing noticeably faster and reduced page load times.</p><h3>HTTP/3 — The Future is Here (2022)</h3><p>The latest version, <strong>HTTP/3</strong>, takes things even further. It runs on <strong>QUIC</strong>, a protocol built on top of <strong>UDP</strong> instead of TCP.</p><p>Why does this matter?</p><ul><li><strong>Faster connection setup</strong> (great for mobile).</li><li><strong>Better performance on unreliable networks</strong>.</li><li><strong>Improved security</strong> (TLS 1.3 built in).</li></ul><p>As of today, major browsers (Chrome, Firefox, Edge, Safari) and platforms (Google, Cloudflare, Facebook) already support HTTP/3.</p><h3>Wrapping Up</h3><p>HTTP’s journey from <strong>0.9 to 3</strong> reflects the web’s growth — from serving simple HTML pages to powering rich, dynamic applications across the globe.</p><ul><li><strong>HTTP/1.1</strong> is still widely used.</li><li><strong>HTTP/2</strong> is the current workhorse for most high-traffic sites.</li><li><strong>HTTP/3</strong> is the future, designed for speed and reliability in a mobile-first world.</li></ul><p>The next time you open a website, remember: behind that instant page load is decades of evolution in how computers talk to each other. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58c6e242de21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Internal Working of Database Transactions]]></title>
            <link>https://medium.com/@jating4you/understanding-the-internal-working-of-database-transactions-15dd95231dd3?source=rss-1e02056ea35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/15dd95231dd3</guid>
            <category><![CDATA[database-internals]]></category>
            <dc:creator><![CDATA[Jatin Goyal]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 10:11:34 GMT</pubDate>
            <atom:updated>2025-08-09T10:22:48.801Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>database transaction</strong> is a series of operations that are treated as a single logical unit of work. The key point: either all the operations happen, or none of them do.</p><p>Suppose we have a Transaction like below.</p><p>BEGIN;<br>UPDATE accounts SET balance = balance — 100 WHERE id = 1;<br>UPDATE accounts SET balance = balance + 100 WHERE id = 2;<br>COMMIT;</p><p>What happens Internally ?</p><p><strong>Internal Working of DB</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyYUkHErH_TM9cnfd44d_g.png" /></figure><h3>1. Step-by-Step Internal Flow</h3><ol><li><strong>BEGIN</strong> → The database assigns a transaction ID (TID) and starts tracking all operations.</li><li><strong>Read/Write Operations</strong> → Data pages are fetched from disk into the <strong>Buffer Pool</strong>.</li><li><strong>Locking / MVCC</strong> →</li></ol><ul><li>Lock-based systems: lock rows/tables to ensure isolation.</li><li>MVCC systems: keep multiple versions of data so reads don’t block writes.</li></ul><p>4. <strong>Undo Logging</strong> → Before any change, the old value is written to an <strong>Undo Log</strong>.</p><p><strong>5. Change in Memory</strong> → Updates are made to in-memory pages in the buffer pool.</p><p><strong>6. Redo Logging (WAL)</strong> → The intended changes are written to a <strong>Write-Ahead Log</strong> on disk.</p><p><strong>7. Commit</strong> → The WAL is flushed to disk, guaranteeing durability.</p><p><strong>8. Post-Commit</strong> → Locks are released, and dirty pages are eventually written to disk.</p><p><strong>9. Rollback (if needed)</strong> → Use the Undo Log to restore old values.</p><h3>2. Key Internal Components</h3><ul><li><strong>Buffer Pool</strong> → Memory space to hold frequently used data.</li><li><strong>Undo Log</strong> → Stores old versions for rollback.</li><li><strong>Redo Log / WAL</strong> → Ensures committed changes survive crashes.</li><li><strong>Transaction Table</strong> → Tracks active transactions.</li><li><strong>Lock Table</strong> → Keeps record of who holds which lock.</li><li><strong>Version Store (in MVCC)</strong> → Keeps older row versions for consistent reads.</li></ul><h3>3. Isolation Levels (How Concurrency Is Controlled)</h3><ul><li><strong>Read Uncommitted</strong> → Reads can see uncommitted changes (dirty reads possible).</li><li><strong>Read Committed</strong> → Reads only see committed data.</li><li><strong>Repeatable Read</strong> → Guarantees same row returns same data in one transaction.</li><li><strong>Serializable</strong> → Full isolation as if transactions run one after another.</li></ul><h3>4. Propagation Levels (For Nested Transactions)</h3><ul><li><strong>REQUIRED</strong> → Use current transaction or start one if none exists.</li><li><strong>REQUIRES_NEW</strong> → Always start a new transaction.</li><li><strong>MANDATORY</strong> → Must join existing transaction.</li><li><strong>NESTED</strong> → Sub-transaction inside a main one.</li><li><strong>SUPPORTS</strong> → Join if exists, else run without.</li><li><strong>NOT_SUPPORTED</strong> → Run without transaction.</li><li><strong>NEVER</strong> → Fail if there’s an active transaction.</li></ul><h3>5. Real-World Analogy</h3><p>Imagine editing a Word document:</p><ul><li><strong>Begin</strong> → Open file.</li><li><strong>Undo Log</strong> → Ctrl+Z stores old text.</li><li><strong>Redo Log / WAL</strong> → Auto-save captures changes.</li><li><strong>Commit</strong> → Click Save.</li><li><strong>Rollback</strong> → Close without saving.</li></ul><p><strong>In short:</strong> Internally, a database transaction relies on logging, memory buffers, and concurrency control to ensure that your operations are safe, consistent, and recoverable — even in the event of crashes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15dd95231dd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding Keycloak SPIs: Unlocking Customization with Service Provider Interfaces]]></title>
            <link>https://medium.com/@jating4you/understanding-keycloak-spis-unlocking-customization-with-service-provider-interfaces-0df7313b3381?source=rss-1e02056ea35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0df7313b3381</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[spi]]></category>
            <dc:creator><![CDATA[Jatin Goyal]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 09:38:45 GMT</pubDate>
            <atom:updated>2025-06-12T09:38:45.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>� What is a Keycloak SPI?</h3><p>Keycloak is a powerful open-source identity and access management solution. While it comes with robust features out of the box, many organizations require custom behavior — like plugging in a new login step, modifying token claims, or integrating with external systems.</p><p>That’s where <strong>SPIs (Service Provider Interfaces)</strong> come into play.</p><p><strong>SPIs in Keycloak</strong> allow developers to extend or override core Keycloak functionality by implementing Java interfaces.</p><h3>⚙️ Why Use SPIs?</h3><p>Keycloak SPIs give you <strong>plugin-level control</strong> over:</p><ul><li>Custom authentication flows</li><li>User data handling</li><li>Token generation</li><li>Event auditing</li><li>UI theming and localization</li><li>Protocol extensions (OIDC, SAML)</li><li>External identity federation</li></ul><h3>📦 Common SPIs in Keycloak (with Interfaces &amp; Use Cases)</h3><p>SPI Interfaces to Implement Key Methods Use Case</p><p><strong>Authenticator SPI</strong> Authenticator, AuthenticatorFactory authenticate(), action() Custom login steps (e.g., OTP, CAPTCHA)</p><p><strong>FormAction SPI</strong> FormAction, FormActionFactory validate(), buildPage(), success() Extend registration/profile forms</p><p><strong>UserStorage SPI</strong> UserStorageProvider, UserLookupProvider getUserById(), getUserByUsername() Connect to external user DB/LDAP</p><p><strong>IdentityProvider SPI</strong> IdentityProvider, IdentityProviderFactory performLogin() Create custom social or enterprise IdPs <strong>IdentityProviderMapper SPI</strong> IdentityProviderMapper, IdentityProviderMapperFactory importNewUser(), updateBrokeredUser() Map IdP claims to user attributes</p><p><strong>ProtocolMapper SPI</strong> ProtocolMapper, ProtocolMapperModel transformAccessToken() Add custom claims to tokens <strong>EventListener SPI</strong> EventListenerProvider, EventListenerProviderFactory onEvent(), onAdminEvent() Listen to login/admin events</p><p><strong>EventStore SPI</strong> EventStoreProvider onEvent(), clear() Persist events to DB/log system</p><p><strong>EmailSender SPI</strong> EmailSenderProvider send() Integrate external email providers</p><p><strong>ThemeSelector SPI</strong> ThemeSelectorProvider, ThemeSelectorProviderFactory getThemeName() Dynamically pick UI theme per realm/client</p><p><strong>LoginProtocol SPI</strong> LoginProtocol, LoginProtocolFactory authenticate() Customize auth protocols (OIDC, SAML)</p><p><strong>ScheduledTask SPI</strong> ScheduledTaskProvider, ScheduledTaskProviderFactory runTask() Run background jobs (e.g., cleanup)</p><p><strong>TokenIntrospector SPI</strong> TokenIntrospector introspect() Custom resource server validation</p><p><strong>UserProfile SPI</strong> UserProfileProviderFactory, UserProfileProvider validate(), create() Declarative user attribute validation</p><p><strong>HostnameProvider SPI</strong> HostnameProvider, HostnameProviderFactory getHostname() Control request hostname resolution</p><p><strong>MapStorage SPI</strong> MapStorageProvider CRUD-style Advanced: override internal storage layer</p><h3>🚀 How to Use an SPI (Step-by-Step)</h3><ol><li><strong>Find the Interface</strong><br> Located in the org.keycloak.* package.</li><li><strong>Implement the Interface</strong><br> Create your own class and override the required methods.</li><li><strong>Create and Register a Factory</strong><br> Implement ProviderFactory and register via META-INF/services/&lt;FullyQualifiedFactoryInterface&gt;.</li><li><strong>Package Your Code</strong><br> Build a JAR and drop it into Keycloak’s /providers directory.</li><li><strong>Enable in Admin Console</strong> (if needed)<br> Many SPIs require admin configuration (e.g., Authenticator flows, Protocol Mappers).</li></ol><h3>⚠️ Common Pitfalls</h3><ul><li><strong>Missing Factory Registration</strong>: No META-INF/services = SPI won’t load.</li><li><strong>SPI Version Drift</strong>: SPIs evolve — ensure you match Keycloak version.</li><li><strong>Hard-to-Debug Errors</strong>: Use Keycloak in DEBUG mode during development.</li><li><strong>Security Bugs</strong>: Custom login/token code may weaken security.</li><li><strong>Performance Bottlenecks</strong>: Avoid long-running logic in event listeners.</li></ul><h3>✅ When to Use Which SPI?</h3><p>Scenario Recommended SPI Add extra login step Authenticator SPI Extend user registration form FormAction SPI Sync users from external DB UserStorage SPI Add custom claims to token ProtocolMapper SPI Log all login events EventListener SPI Customize realm’s login page Theme SPI or ThemeSelector SPI Use a 3rd-party email service EmailSender SPI Use custom logic for token introspection TokenIntrospector SPI</p><h3>✍️ Example Snippet: Authenticator SPI</h3><pre>public class MyCaptchaAuthenticator implements Authenticator {<br>    @Override<br>    public void authenticate(AuthenticationFlowContext context) {<br>        // Your CAPTCHA logic here<br>        context.success();<br>    }<br><br>    @Override<br>    public void action(AuthenticationFlowContext context) {}<br><br>    @Override<br>    public boolean requiresUser() { return false; }<br><br>    @Override<br>    public void close() {}<br>}</pre><h3>🎯 Conclusion</h3><p>Keycloak SPIs unlock powerful extensibility. Whether you’re building a custom login, integrating an external identity provider, or modifying token claims — there’s an SPI for it.</p><p>📘 Tip: Always test SPIs in a staging environment before production.</p><p>🛠 Need help with implementation or debugging? Drop a comment or message!</p><p>Happy extending Keycloak! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0df7313b3381" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Microservices with gRPC & Kubernetes ]]></title>
            <link>https://medium.com/@jating4you/scalable-microservices-with-grpc-kubernetes-e319aeac3ae2?source=rss-1e02056ea35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e319aeac3ae2</guid>
            <dc:creator><![CDATA[Jatin Goyal]]></dc:creator>
            <pubDate>Thu, 15 May 2025 09:55:11 GMT</pubDate>
            <atom:updated>2025-05-15T09:55:11.662Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Welcome to gRPC — a powerful, high-performance, open-source universal RPC framework.</em></strong></blockquote><p>In a world increasingly dominated by microservices and cloud-native architectures, <strong>scalability</strong> and <strong>communication efficiency</strong> are paramount. RESTful APIs, while popular, often struggle with performance bottlenecks in highly distributed systems.</p><p>This is where <strong>gRPC</strong> shines.</p><h3>🌐 Why gRPC?</h3><p>gRPC (Google Remote Procedure Call) is a modern, lightweight communication protocol that uses HTTP/2 and Protocol Buffers (protobuf) to deliver efficient, low-latency, and highly scalable services.</p><h3>🔑 Key Features of gRPC:</h3><ul><li>HTTP/2 based: Multiplexed streams, server push, and better performance.</li><li>Contract-first API development using .proto files.</li><li>Supports <strong>multiple communication types</strong>: Unary, Server streaming, Client streaming, Bidirectional streaming.</li><li>Language agnostic: Works with Java, Go, Python, C#, Node.js, and more.</li><li>Great for internal microservices communication and mobile backends.</li></ul><h3>⚠️ The Problem with gRPC</h3><p>While gRPC offers several benefits, it comes with challenges, especially for developers transitioning from REST:</p><h3>🧱 Learning Curve</h3><ul><li>Understanding .proto files and how to compile them per language can be daunting initially.</li><li>Integration with existing HTTP-based tools (e.g., Postman) isn’t straightforward.</li></ul><h3>🔧 Debugging and Monitoring</h3><ul><li>Since gRPC isn’t text-based like REST (it uses binary), inspecting payloads in tools like curl or browser dev tools becomes harder.</li><li>Observability tools may require additional setup (e.g., OpenTelemetry, grpcurl, etc.)</li></ul><h3>🌍 Browser Support</h3><ul><li>gRPC isn’t natively supported in browsers due to its HTTP/2 + binary payload setup. Developers need to use <strong>gRPC-Web</strong> as a workaround</li></ul><h3>✅ Service Call Example: Unary in gRPC</h3><p>Unary is the simplest gRPC call type — one client request and one server response.</p><p>Here’s a basic flow:</p><p><strong>Define Proto</strong></p><pre>syntax = &quot;proto3&quot;;</pre><pre>service Greeter {<br>  rpc SayHello (HelloRequest) returns (HelloReply);<br>}</pre><pre>message HelloRequest {<br>  string name = 1;<br>}</pre><pre>message HelloReply {<br>  string message = 1;<br>}</pre><p><strong>Client Request</strong></p><pre>grpcurl -plaintext -d &#39;{&quot;name&quot;: &quot;Jatin&quot;}&#39; localhost:50051 greeter.Greeter/SayHello</pre><p><strong>Server Response</strong></p><pre>{<br>  &quot;message&quot;: &quot;Hello Jatin&quot;<br>}</pre><p>Simple, clean, and fast. 🔥</p><h3>🚢 Deploying with Kubernetes</h3><p>Combining gRPC with <strong>Kubernetes</strong> adds automatic scaling, load balancing, and service discovery.</p><p>Use <strong>gRPC health checks</strong> for better orchestration.</p><p>Employ <strong>Envoy</strong> or <strong>gRPC Load Balancer</strong> for traffic management.]</p><p>Use <strong>Istio</strong> for advanced service mesh scenarios (optional but powerful).</p><h3>💡 Final Thoughts</h3><p>gRPC isn’t just a buzzword — it’s a <strong>pragmatic solution</strong> for building scalable, efficient microservices. While it has a few hurdles (especially for newcomers), the benefits outweigh the learning curve.</p><p>If you’re building <strong>internal services</strong> or need <strong>high throughput communication</strong>, <strong>gRPC + Kubernetes</strong> is a match made in cloud-native heaven. ☁️⚡</p><p>🔗 <strong>Stay tuned</strong> for upcoming blogs on:</p><ul><li>Streaming gRPC in action</li><li>Securing gRPC services with mTLS</li><li>Observability and monitoring for gRPC with Prometheus &amp; Grafana</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e319aeac3ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍ Why Apple SSO Doesn’t Return First and Last Name After First Login (and How to Handle It)]]></title>
            <link>https://medium.com/@jating4you/why-apple-sso-doesnt-return-first-and-last-name-after-first-login-and-how-to-handle-it-f157e35d7a4d?source=rss-1e02056ea35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f157e35d7a4d</guid>
            <category><![CDATA[apple-login]]></category>
            <dc:creator><![CDATA[Jatin Goyal]]></dc:creator>
            <pubDate>Wed, 14 May 2025 14:47:29 GMT</pubDate>
            <atom:updated>2025-05-14T14:47:29.201Z</atom:updated>
            <content:encoded><![CDATA[<p>🧑‍💻 Why Apple SSO Doesn’t Return First and Last Name After First Login (and How to Handle It)</p><p>Single Sign-On (SSO) has become the gold standard for seamless user authentication. With providers like <strong>Google</strong>, <strong>Facebook</strong>, and <strong>Apple</strong>, integrating social login has never been easier. But when using <strong>Apple SSO</strong>, many developers face a confusing issue:</p><blockquote><em>❗ </em><strong><em>After the first login, Apple no longer returns the user’s first and last name.</em></strong></blockquote><p>This behavior isn’t a bug — it’s by <strong>design</strong>. In this blog, we’ll dive into:</p><ul><li>Why Apple behaves this way</li><li>How it’s different from Google and Facebook</li><li>How to fix it in your app</li><li>Whether you can use Apple’s private relay email for OTP/communication</li></ul><h3>🍏 Why Apple Doesn’t Return Name After First Login — By Design</h3><p>Apple is known for putting <strong>user privacy first</strong>, and its SSO implementation reflects that.</p><p>When a user signs in using Apple for the <strong>first time</strong>, Apple returns the given_name, family_name, and optionally the email. However, <strong>subsequent logins will not return the name again</strong>, regardless of scopes.</p><blockquote><em>📜 </em><strong><em>Apple Developer Docs</em></strong><em>:<br></em>“Apple only shares user information such as name and email once, during the initial authorization.”</blockquote><p>This is intentional to:</p><ul><li>Minimize personal data shared with third-party apps</li><li>Give users complete control over their identity</li><li>Ensure developers store data responsibly</li></ul><h3>🔍 Why This Is Not an Issue with Google or Facebook</h3><p>Both <strong>Google</strong> and <strong>Facebook</strong> take a more traditional OAuth 2.0 approach. When requested via appropriate scopes (profile, email), they <strong>consistently return</strong>:</p><ul><li>First name</li><li>Last name</li><li>Profile picture</li><li>Email</li></ul><p>FeatureAppleGoogle / FacebookName returned always❌ Only on first login✅ On every loginEmail always returned✅ Yes (if allowed)✅ YesCan hide real email✅ Yes (private relay option)❌ NoPrivacy-first approach✅ Very strict❌ Less strict</p><h3>🛠️ How to Fix the Missing Name Issue</h3><p>To build a robust Apple SSO integration, here’s what you should do:</p><h3>✅ 1. Store the Name at First Login</h3><p>After the first login, extract and persist the name in your backend.</p><pre>Map&lt;String, Object&gt; claims = decodeJwt(appleIdToken);<br>String firstName = (String) claims.get(&quot;given_name&quot;);<br>String lastName = (String) claims.get(&quot;family_name&quot;);</pre><pre>if (firstName != null &amp;&amp; lastName != null) {<br>    userService.saveUserName(userId, firstName, lastName);<br>}</pre><h3>🔁 2. Fetch Name From Your DB for Later Logins</h3><p>Since Apple won’t send it again, use the stored name for future user sessions:</p><pre>User user = userRepository.findByAppleSub(appleSub);<br>String name = user.getFirstName() + &quot; &quot; + user.getLastName();</pre><h3>✏️ 3. Prompt User If Name Was Never Captured</h3><p>If the name wasn’t captured during the first login (e.g., due to a bug or user canceling), prompt the user to enter it manually.</p><h3>📧 Can You Use Apple’s Private Relay Email for OTP and Communication?</h3><p>Yes! If a user chooses <strong>“Hide My Email”</strong> during Apple SSO, Apple generates a relay address like:</p><pre>randomstring@privaterelay.appleid.com</pre><h3>✅ You Can Send OTPs and Emails to It</h3><p>Apple forwards emails sent to this relay address to the user’s actual Apple ID inbox. You can use it for:</p><ul><li>OTPs</li><li>Welcome emails</li><li>Password reset links</li><li>Transactional notifications</li></ul><blockquote><em>✅ </em><strong><em>Apple guarantees delivery</em></strong><em> as long as your domain is registered and emails are compliant.</em></blockquote><h3>🔒 Key Considerations</h3><p>AspectDetailsRelay ValidityRelay remains active while the user uses your appSPF/DKIM RequiredSet up email authentication to avoid spam filteringNo Marketing EmailsStick to transactional emails; avoid promotional contentReply-to AddressSet it up if you expect users to reply</p><h3>📥 Can Users Access It?</h3><p>Absolutely. Users receive emails sent to @privaterelay.appleid.com in their <strong>actual inbox</strong>, just like any other email. They typically don’t see or interact with the relay address directly.</p><h3>🧩 Bonus: How to Detect First-Time Apple Login</h3><p>You can determine if it’s a <strong>first-time login</strong> based on whether given_name and family_name are present in the ID token or the user JSON payload. If they&#39;re missing, it&#39;s a returning login.</p><h3>🧭 Final Thoughts</h3><p>Apple’s approach to SSO is driven by a strong privacy philosophy. While it may introduce some extra work for developers, it’s a positive step for user data protection.</p><p>To ensure a smooth experience:</p><ul><li>Store user name on first login</li><li>Use Apple’s private relay email confidently for OTPs and communication</li><li>Respect user privacy — and be ready to ask for missing info if needed</li></ul><p><strong>Need Help With Apple, Google, or Facebook SSO in Spring Boot or WebFlux?</strong><br>I help teams build secure and privacy-conscious SSO integrations. Reach out if you’d like a tailored solution!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f157e35d7a4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>