<?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 Rajneesh Shukla on Medium]]></title>
        <description><![CDATA[Stories by Rajneesh Shukla on Medium]]></description>
        <link>https://medium.com/@rajpg16?source=rss-5fa0993abbfb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kJnjJHMUsCQOWKdRzCjKTw.jpeg</url>
            <title>Stories by Rajneesh Shukla on Medium</title>
            <link>https://medium.com/@rajpg16?source=rss-5fa0993abbfb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:38:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajpg16/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[How Amazon.com, Amazon.in, JWTs, SSO, OAuth, SAML, and OpenID actually work together]]></title>
            <link>https://medium.com/@rajpg16/how-amazon-com-amazon-in-jwts-sso-oauth-saml-and-openid-actually-work-together-12110cdbbcb2?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/12110cdbbcb2</guid>
            <category><![CDATA[saml2]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[oidc]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 10:00:47 GMT</pubDate>
            <atom:updated>2026-01-22T10:07:53.787Z</atom:updated>
            <content:encoded><![CDATA[<p>You open <strong>amazon.com</strong>. You’re not logged in.</p><p>You then open <strong>amazon.in</strong>. Boom. You <em>are</em> logged in.</p><p>No password typed. No popup. No drama.</p><p>This feels like magic, but it’s actually a well-organized kingdom running on seals, messengers, and trusted gates.</p><p>Let’s enter the kingdom.</p><h3>The Kingdom Analogy</h3><p>Imagine <strong>Amazon</strong> as a massive kingdom.</p><ul><li><strong>amazon.com</strong> and <strong>amazon.in</strong> are different cities.</li><li>Each city has its own gates.</li><li>The <strong>King’s Identity Office</strong> sits at the center. This is the <em>Identity Provider</em>.</li><li>Every citizen carries a <strong>sealed scroll</strong>. That scroll is your <strong>JWT token</strong>.</li></ul><p>The seal matters more than the scroll.</p><h3>Step 1: Login Happens Once</h3><p>You visit <strong>amazon.com</strong> and log in.</p><p>Behind the scenes:</p><ol><li>You enter username + password.</li><li>Amazon’s <strong>Identity Server</strong> verifies you.</li><li>It creates a <strong>JWT token</strong>.</li><li>That token is:</li></ol><ul><li>Digitally signed</li><li>Contains your user ID</li><li>Contains the <em>issuer</em> (who issued this token)</li><li>Has an expiry time</li></ul><p>This token is sent back to your browser and stored as a <strong>cookie</strong>.</p><p>Important detail 👇<br>The cookie is scoped to a <strong>parent domain</strong>, like:</p><pre>.amazon.com</pre><p>or sometimes via a shared identity domain like:</p><pre>.amazon-auth.com</pre><h3>Step 2: What’s Inside a JWT (The Scroll)</h3><p>A JWT has <strong>three parts</strong>:</p><pre>HEADER.PAYLOAD.SIGNATURE</pre><h3>Payload (What it says)</h3><ul><li>User ID</li><li>Email</li><li>Issuer (iss)</li><li>Expiry (exp)</li></ul><h3>Signature (The royal seal)</h3><ul><li>Created using a <strong>private key</strong></li><li>Proves the token was issued by the King’s Office</li><li>Cannot be forged</li></ul><p>Yes, <strong>the signature is stored inside the token</strong>.</p><h3>Step 3: Same Token, Different City</h3><p>Now you open <strong>amazon.in</strong>. Your browser automatically sends the cookie along, amazon.in says:</p><blockquote><em>“You’re claiming to be Raj. Prove it.”</em></blockquote><p>It does <strong>not</strong> ask the Identity Server again.</p><p>Instead, it does this</p><h3>Step 4: How the Server Verifies You (The Seal Check)</h3><p>This is the most important step.</p><h3>What amazon.in does</h3><ol><li>Extracts the JWT from the cookie</li><li>Reads the <strong>issuer (iss)</strong><br>“Who issued this token?”</li><li>Fetches the <strong>public key</strong> of that issuer</li><li>Uses the public key to <strong>verify the signature</strong></li><li>Checks:</li></ol><ul><li>Signature is valid</li><li>Token is not expired</li><li>Issuer is trusted</li></ul><p>If all checks pass:</p><blockquote><em>“This seal is real. Let him in.”</em></blockquote><p>No database lookup.<br>No session storage.<br>Just math.</p><h3>Public and Private Keys (Real-World Meaning)</h3><p>Think of it like this:</p><ul><li><strong>Private key</strong> -&gt;King’s unique stamp</li><li><strong>Public key</strong> -&gt; Anyone can see and verify the stamp</li></ul><p>The King:</p><ul><li>Signs documents using the <strong>private key</strong></li><li>Never shares it</li></ul><p>Cities:</p><ul><li>Use the <strong>public key</strong></li><li>Can verify authenticity</li><li>Cannot forge documents</li></ul><p>That’s asymmetric cryptography.</p><h3>Do All Amazon Users Share the Same Key?</h3><p>Yes.</p><ul><li>All user tokens are signed using <strong>one key pair</strong></li><li>Or a small rotating set of keys</li><li>Keys are stored securely, not plain env vars</li><li>Public keys are exposed via a <strong>JWKS endpoint</strong></li></ul><p>This allows:</p><ul><li>Millions of users</li><li>Stateless verification</li><li>Global scale</li></ul><p>Netflix, Google, Amazon all do this.</p><h3>Why You Were Logged Into amazon.in</h3><p>Because:</p><ol><li>You already had a valid JWT</li><li>Token issuer was Amazon’s Identity Service</li><li>amazon.in trusts that issuer</li><li>Signature verification passed</li><li>Issuer + keys proved authenticity</li></ol><p>No new login needed.</p><h3>Now Enter SSO (Single Sign-On)</h3><p>SSO is just this idea, formalized.</p><h3>SSO means:</h3><blockquote><em>“Authenticate once, access many services.”</em></blockquote><p>Amazon, Google Workspace, Microsoft Azure all use SSO internally.</p><h3>Flow:</h3><ol><li>User logs in once</li><li>Identity Provider issues token</li><li>All services trust that provider</li><li>Tokens act as universal passes</li></ol><h3>Where OAuth, SAML, and OpenID Fit In</h3><p>They are <strong>messenger protocols</strong>, not rivals.</p><h3>OAuth</h3><p>Used when:</p><ul><li>An app wants <strong>permission</strong></li><li>Example: “Let Spotify read my Google profile”</li></ul><p>OAuth answers:</p><blockquote><em>“What can this app access?”</em></blockquote><h3>OpenID Connect (OIDC)</h3><p>Built on OAuth.</p><p>Used when:</p><ul><li>You want <strong>login + identity</strong></li><li>Example: “Login with Google”</li></ul><p>OIDC answers:</p><blockquote><em>“Who is this user?”</em></blockquote><p>JWT is the hero here.</p><h3>SAML</h3><p>Older, XML-based, enterprise-heavy.</p><p>Used when:</p><ul><li>Large companies</li><li>Legacy systems</li><li>Bank, HR, payroll tools</li></ul><p>SAML answers:</p><blockquote><em>“This employee is authenticated by our company.”</em></blockquote><p>Still widely used in enterprises.</p><h3>Why Big Tech Loves This Model</h3><ul><li>No server-side sessions</li><li>Stateless and scalable</li><li>Works across regions</li><li>Secure by design</li><li>One login, many services</li></ul><p>This is how:</p><ul><li>Amazon scales</li><li>Google signs you into 20 app</li><li>Enterprise SSO works globally</li></ul><p>A workflow diagram to demonstrate the flow together.</p><h3>1️. Login + Token Issuance Flow (Once)</h3><pre>┌─────────┐      username/password      ┌────────────────────┐<br>│ Browser │ ──────────────────────────▶ │ Amazon Identity   │<br>│         │                              │ Server (IdP)      │<br>│         │ ◀────── JWT (signed) ───────│ - verifies user    │<br>│         │                              │ - signs token      │<br>└─────────┘                              │ - private key      │<br>     │                                   └────────────────────┘<br>     │<br>     │  Cookie stored in browser<br>     │  (scoped to .amazon.* or auth domain)<br>     ▼</pre><h3>2️. Accessing amazon.com (First City)</h3><pre>Browser<br>   │<br>   │  Request + JWT Cookie<br>   ▼<br>┌────────────────┐<br>│ amazon.com     │<br>│ (Service)      │<br>│                │<br>│ 1. Extract JWT │<br>│ 2. Verify sig  │◀── Public Key<br>│ 3. Check exp   │<br>│ 4. Check iss   │<br>└────────────────┘<br>   │<br>   ▼<br>User is logged in</pre><h3>3️. Opening amazon.in (Second City, Same Kingdom)</h3><pre>Browser<br>   │<br>   │  Same JWT Cookie automatically sent<br>   ▼<br>┌────────────────┐<br>│ amazon.in      │<br>│ (Service)      │<br>│                │<br>│ 1. Extract JWT │<br>│ 2. Read issuer │───────┐<br>│ 3. Fetch key   │       │<br>│ 4. Verify sig  │◀──────┘ Public Key<br>│ 5. Check exp   │<br>└────────────────┘<br>   │<br>   ▼<br>User is logged in instantly</pre><h3>4️. Signature Verification (The Seal Check)</h3><pre>JWT = HEADER + PAYLOAD + SIGNATURE</pre><pre>PAYLOAD:<br>{<br>  userId: &quot;raj123&quot;,<br>  iss: &quot;amazon-identity&quot;,<br>  exp: 1700000000<br>}</pre><pre>SIGNATURE = sign(HEADER + PAYLOAD, PRIVATE_KEY)</pre><p>Verification step:</p><pre>verify(<br>  HEADER + PAYLOAD,<br>  SIGNATURE,<br>  PUBLIC_KEY<br>) == true ? TRUST : REJECT</pre><p>No DB call.<br> No session lookup.<br> Pure cryptography</p><h3>5️. SSO Big Picture (Zoomed Out)</h3><pre>                ┌---─────────────────┐<br>                │ Identity Provider  │<br>                │ (Amazon IdP)       │<br>                │ - Private Key      │<br>                └─────────┬──────────┘<br>                          │ JWT<br>        ┌─────────────────┼─────────────────┐<br>        ▼                 ▼                 ▼<br> ┌────────────┐     ┌────────────┐     ┌────────────┐<br> │ amazon.com │     │ amazon.in  │     │ primevideo │<br> │ verifies   │     │ verifies   │     │ verifies   │<br> │ via pub    │     │ via pub    │     │ via pub    │<br> └────────────┘     └────────────┘     └────────────┘</pre><p>Authenticate once. Access everywhere.</p><h3>Final Thought</h3><p>That moment when <strong>amazon.in</strong> recognized you?</p><p>That wasn’t coincidence.</p><p>All powered by a tiny sealed scroll traveling silently with your browser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12110cdbbcb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 SQL Query Optimizations Every Developer Should Know]]></title>
            <link>https://medium.com/@rajpg16/12-sql-query-optimizations-every-developer-should-know-e8f325ccbb2f?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f325ccbb2f</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 09:19:35 GMT</pubDate>
            <atom:updated>2026-01-22T09:19:35.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Use Indexes (Your Database’s Shortcut)</h3><p><strong>Production case:</strong> Login by email</p><p><strong>Before:</strong> Full table scan<br><strong>After:</strong> Indexed lookup</p><pre>CREATE INDEX idx_users_email ON users(email);</pre><p>2.3s -&gt; <strong>30ms</strong></p><h3>2. Stop Using SELECT *</h3><p>Fetch only what you need.</p><p><strong>Before</strong></p><pre>SELECT * FROM orders;</pre><p><strong>After</strong></p><pre>SELECT order_id, status FROM orders;</pre><p>Less data = faster response<br>Network + memory saved</p><h3>3. Avoid % at the Start of LIKE</h3><p>Indexes don’t work backwards.</p><p><strong>Bad</strong></p><pre>LIKE &#39;%john&#39;</pre><p><strong>Good</strong></p><pre>LIKE &#39;john%&#39;</pre><p>Table scan → Index scan</p><h3>4. Use Correct Data Types</h3><p>Dates as DATE, not VARCHAR.</p><p><strong>Why?</strong><br>Smaller storage, faster comparison.</p><p>Filtering improved by <strong>30–40%</strong></p><h3>5. Limit Rows Early</h3><p>Databases are not dump trucks.</p><pre>LIMIT 50</pre><p><strong>Production case:</strong> Dashboards, admin panels<br>Seconds → milliseconds</p><h3>6. EXISTS &gt; COUNT</h3><p>Don’t count if you only want to know <em>if</em>.</p><p><strong>Before</strong></p><pre>COUNT(*)</pre><p><strong>After</strong></p><pre>EXISTS(...)</pre><p>Stops at first match</p><h3>7. Replace Subqueries with JOINs</h3><p>JOINs think flatter. Subqueries think deeper.</p><p><strong>Before:</strong> Nested loops<br><strong>After:</strong> Optimized joins</p><p>1.8s → <strong>120ms</strong></p><h3>8. Use Database Features</h3><p>Your DB is smarter than you think.</p><p>Examples:</p><ul><li>PostgreSQL → EXPLAIN ANALYZE</li><li>MySQL -&gt; Index hints</li><li>Cloud DBs → Auto scaling</li></ul><p>Free performance wins</p><h3>9. Monitor Slow Queries</h3><p>Every production system has slow queries.</p><pre>EXPLAIN</pre><p>Find them. Fix them. Repeat.</p><h3>10. Let AI Help</h3><p>Modern databases auto-suggest:</p><ul><li>Indexes</li><li>Query rewrites</li><li>Execution plans</li></ul><p><strong>Result:</strong> Less manual tuning, more speed</p><h3>11. Split Databases by Purpose</h3><p>One DB for everything = slow everything.</p><p><strong>Microservices</strong></p><ul><li>Users DB</li><li>Orders DB</li><li>Payments DB</li></ul><p>Smaller tables -&gt;faster queries</p><h3>12. Use the Right Tool for Big Data</h3><p>SQL is great.<br>Big SQL needs big engines.</p><p>Use:</p><ul><li>Spark</li><li>BigQuery</li><li>Snowflake</li></ul><p>Parallel thinking = parallel speed</p><h3>Final Lesson (Remember This)</h3><blockquote><strong><em>Fast queries come from fewer rows, fewer columns, and fewer thoughts.</em></strong></blockquote><p>Optimize where it matters:</p><ul><li>Index smartly</li><li>Fetch less</li><li>Measure always</li></ul><p>Your database is fast. Your query decides how fast.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f325ccbb2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Database Indexing Works (From Scratch, With a B-Tree Example)]]></title>
            <link>https://medium.com/@rajpg16/how-database-indexing-works-from-scratch-with-a-b-tree-example-0966c053a7b1?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0966c053a7b1</guid>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-indexing]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 08:14:37 GMT</pubDate>
            <atom:updated>2026-01-16T08:14:37.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Database Indexing Works (From Scratch, With a B-Tree)</h3><p>If you’ve used databases, you’ve probably heard this advice:</p><blockquote><em>“Add an index to make queries faster.”</em></blockquote><p>But <strong>how does an index actually work internally?</strong><br>How does the database <em>avoid scanning the entire table</em> and <em>jump directly</em> to the right row?</p><p>In this article, we’ll break indexing down <strong>from first principles</strong>, using a <strong>concrete example</strong> and <strong>ASCII diagrams</strong> to show what’s really happening under the hood.</p><h3>The Problem: Searching Without an Index</h3><p>Consider a simple table:</p><pre>Employees<br>-------------------------<br>RowID | Name<br>-------------------------<br>1     | Zoe<br>2     | Alice<br>3     | John<br>4     | Mike<br>5     | Carol<br>6     | Bob<br>7     | Eve<br>8     | David<br>9     | Frank<br>10    | Grace<br>11    | Henry<br>12    | Irene</pre><p>Now run this query:</p><pre>SELECT * FROM Employees WHERE Name = &#39;Henry&#39;;</pre><h3>What happens without an index?</h3><p>The database:</p><ol><li>Reads row 1 -&gt;Zoe ❌</li><li>Reads row 2 -&gt;Alice ❌</li><li>Reads row 3 -&gt;John ❌</li><li>Continues until row 11 -&gt;Henry ✅</li></ol><p>This is a <strong>full table scan</strong>.</p><ul><li>Time complexity: <strong>O(n)</strong></li><li>For millions of rows → very slow</li></ul><h3>What Is an Index, Really?</h3><p>An <strong>index</strong> is a <strong>separate data structure</strong>, stored apart from the table, that contains:</p><ul><li>The indexed column values</li><li>Pointers to the exact rows in the table</li><li>Data organized in a way that is fast to search</li></ul><p>Think of it like a <strong>book index</strong>:</p><ul><li>You don’t read every page</li><li>You jump directly to the page number</li></ul><h3>Step 1: Building the Index</h3><p>Suppose we create an index on Name:</p><pre>CREATE INDEX idx_name ON Employees(Name);</pre><p>Internally, the database extracts the Name column, sorts it, and stores it with row pointers:</p><pre>Alice  → Row 2<br>Bob    → Row 6<br>Carol  → Row 5<br>David  → Row 8<br>Eve    → Row 7<br>Frank  → Row 9<br>Grace  → Row 10<br>Henry  → Row 11<br>Irene  → Row 12<br>John   → Row 3<br>Mike   → Row 4<br>Zoe    → Row 1</pre><p>⚠ Important:<br>The index <strong>does not store full rows</strong>, only keys and pointers.</p><h3>Step 2: Why B-Trees Are Used</h3><p>Most relational databases store indexes as <strong>B-Trees (or B+Trees)</strong> because:</p><ul><li>They stay balanced</li><li>They work efficiently on disk</li><li>Search time is <strong>O(log n)</strong></li></ul><p>Instead of one value per node (like a binary tree), <strong>each node holds multiple keys</strong>, minimizing disk reads.</p><h3>Step 3: A B-Tree Example (ASCII Diagram)</h3><p>Assume:</p><ul><li>Max <strong>3 keys per node</strong></li><li>Data stored in <strong>leaf nodes</strong></li></ul><h3>Leaf nodes</h3><pre>[ Alice | Bob | Carol ]<br>[ David | Eve | Frank ]<br>[ Grace | Henry | Irene ]<br>[ John | Mike | Zoe ]</pre><h3>Root (internal) node</h3><p>The root stores separator keys:</p><pre>[ David | Grace | John ]</pre><h3>Final B-Tree structure</h3><pre>[ David | Grace | John ]<br>                   /         |         |         \<br>[ Alice Bob Carol ] [ David Eve Frank ] [ Grace Henry Irene ] [ John Mike Zoe ]</pre><p>Each value in the leaf points to the <strong>exact disk location</strong> of its row.</p><h3>Step 4: How a Search Works (Finding “Henry”)</h3><p>Query:</p><pre>SELECT * FROM Employees WHERE Name = &#39;Henry&#39;;</pre><h3>Step 1: Start at the root</h3><pre>[ David | Grace | John ]</pre><p>Compare strings lexicographically:</p><ul><li>Henry &gt; David</li><li>Henry &gt; Grace</li><li>Henry &lt; John</li></ul><p>➡️ Follow the <strong>third child</strong></p><h3>Step 2: Reach the leaf</h3><pre>[ Grace | Henry | Irene ]</pre><p>Found:</p><pre>Henry → Row 11</pre><h3>Step 3: Fetch the table row</h3><p>The index gives the database the <strong>exact row address</strong>, so it reads only:</p><pre>Row 11 → [11, Henry]</pre><p>No table scan. Just <strong>2–3 node reads</strong>.</p><h3>How String Comparison Works</h3><p>When the tree compares:</p><pre>Bob &lt; David</pre><p>It compares characters <strong>one by one</strong> using collation rules:</p><pre>&#39;B&#39; (66) &lt; &#39;D&#39; (68) → true</pre><p>Decision is made immediately.<br>This consistent ordering is what makes tree navigation possible.</p><h3>Why Indexing Is So Fast</h3><p>Rows Table ScanB-Tree Index1212 checks~21,000,0001,000,000~3–4</p><p>Indexes drastically reduce <strong>disk I/O</strong>, which is the real performance bottleneck.</p><h3>Trade-Offs of Indexing</h3><p>Indexes are powerful, but not free:</p><h3>Pros</h3><ul><li>Faster SELECT queries</li><li>Efficient filtering and sorting</li></ul><h3>Cons</h3><ul><li>Extra storage</li><li>Slower INSERT / UPDATE / DELETE</li><li>Poorly chosen indexes can hurt performance</li></ul><h3>The Key Insight</h3><blockquote><strong><em>The database searches the index, not the table.<br>The table is accessed only after the exact row location is known.</em></strong></blockquote><p>That’s the core idea behind indexing.</p><h3>Final Mental Model</h3><p>Think of a database index as:</p><blockquote><strong><em>A balanced, sorted map that converts a value (like “Henry”) into a precise disk address in just a few steps.</em></strong></blockquote><p>Once you understand this, query optimization starts to make a lot more sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0966c053a7b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Critical Role of Comprehensive Logging in E-Commerce Platforms]]></title>
            <link>https://medium.com/@rajpg16/the-critical-role-of-comprehensive-logging-in-e-commerce-platforms-086e256f0f42?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/086e256f0f42</guid>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 07:21:50 GMT</pubDate>
            <atom:updated>2026-01-15T07:21:50.343Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the fast-paced world of e-commerce, where transactions happen in milliseconds and customer expectations are sky-high, logging isn’t just a nice-to-have feature — it’s the backbone of operational excellence, security, and business intelligence. A robust logging system can mean the difference between a seamless shopping experience and a catastrophic data breach or system outage.</p><p>In this article, we’ll explore how implementing comprehensive logging across API endpoints, database operations, and user interactions creates a resilient e-commerce platform. Using a real-world example of an online marketplace, we’ll see how logs serve as both a safety net and a strategic asset.</p><h3>The Logging Architecture</h3><p>Our e-commerce platform uses Winston, a powerful Node.js logging library, configured with multiple transports for different log levels and purposes:</p><pre>const createCustomLogger = (logName) =&gt; {<br>  return createLogger({<br>    transports: [<br>      new transports.File({<br>        filename: path.join(logDirectory, `${logName}-info.log`),<br>        level: &quot;info&quot;,<br>        format: format.combine(customTimestamp(), format.json()),<br>      }),<br>      new transports.File({<br>        filename: path.join(logDirectory, `${logName}-error.log`),<br>        level: &quot;error&quot;,<br>        format: format.combine(customTimestamp(), format.json()),<br>      }),<br>    ],<br>  });<br>};</pre><p>This creates separate log files for different modules (UserManagement, ProductCatalog, OrderProcessing, etc.), each with structured JSON entries including timestamps, log levels, and contextual data.</p><h3>API-Level Logging: Every Request Matters</h3><h3>User Authentication Flow</h3><p>Consider a customer attempting to log in to their account:</p><pre>async loginUser(req, res) {<br>  const { email, password } = req.body;<br>  const clientIP = req.ip;<br>  <br>  try {<br>    // Log authentication attempt<br>    UserLogger.info(`Login attempt - Email: ${email} from IP: ${clientIP}`);<br>    <br>    const user = await UserModel.findByEmail(email);<br>    if (!user) {<br>      UserLogger.warn(`Login failed - User not found: ${email} from IP: ${clientIP}`);<br>      return res.status(401).json({ message: &#39;Invalid credentials&#39; });<br>    }<br>    <br>    const isValidPassword = await bcrypt.compare(password, user.password_hash);<br>    if (!isValidPassword) {<br>      UserLogger.warn(`Login failed - Invalid password for: ${email} from IP: ${clientIP}`);<br>      return res.status(401).json({ message: &#39;Invalid credentials&#39; });<br>    }<br>    <br>    // Log successful authentication<br>    UserLogger.info(`Login success - User ID: ${user.id}, Email: ${email} from IP: ${clientIP}`);<br>    <br>    const token = generateJWT(user);<br>    return res.json({ token, user: sanitizeUser(user) });<br>    <br>  } catch (error) {<br>    UserLogger.error(`Login error - ${error.message} for email: ${email} from IP: ${clientIP}`);<br>    return res.status(500).json({ message: &#39;Internal server error&#39; });<br>  }<br>}</pre><p><strong>Why this logging matters:</strong></p><ul><li><strong>Security Monitoring</strong>: Failed login attempts help detect brute force attacks</li><li><strong>User Experience</strong>: Track authentication success rates</li><li><strong>Fraud Detection</strong>: Unusual login patterns from different IPs</li><li><strong>Compliance</strong>: Audit trail for regulatory requirements</li></ul><h4>Product Search and Filtering</h4><pre>async searchProducts(req, res) {<br>  const { query, category, priceRange, page = 1 } = req.query;<br>  const startTime = Date.now();<br>  <br>  try {<br>    ProductLogger.info(`Product search - Query: &quot;${query}&quot;, Category: ${category}, Page: ${page}`);<br>    <br>    const results = await ProductModel.search({<br>      query,<br>      category,<br>      priceRange,<br>      limit: 20,<br>      offset: (page - 1) * 20<br>    });<br>    <br>    const searchTime = Date.now() - startTime;<br>    ProductLogger.info(`Product search completed - ${results.length} results in ${searchTime}ms`);<br>    <br>    return res.json({<br>      products: results,<br>      pagination: { page, total: results.totalCount }<br>    });<br>    <br>  } catch (error) {<br>    ProductLogger.error(`Product search failed - ${error.message} for query: &quot;${query}&quot;`);<br>    return res.status(500).json({ message: &#39;Search temporarily unavailable&#39; });<br>  }<br>}</pre><p><strong>Performance Insights:</strong></p><ul><li>Query execution times help optimize database indexes</li><li>Popular search terms inform product recommendations</li><li>Failed searches indicate potential system issues</li></ul><h3>Database Operation Logging</h3><h4>Order Processing Transactions</h4><pre>async createOrder(req, res) {<br>  const { items, shippingAddress, paymentMethod } = req.body;<br>  const userId = req.user.id;<br>  const orderId = generateOrderId();<br>  <br>  const transaction = await db.beginTransaction();<br>  <br>  try {<br>    OrderLogger.info(`Order creation started - Order ID: ${orderId}, User: ${userId}`);<br>    <br>    // Validate inventory<br>    for (const item of items) {<br>      const product = await ProductModel.findById(item.productId, { transaction });<br>      if (product.stock &lt; item.quantity) {<br>        OrderLogger.warn(`Insufficient stock - Product: ${item.productId}, Requested: ${item.quantity}, Available: ${product.stock}`);<br>        await transaction.rollback();<br>        return res.status(400).json({ message: &#39;Insufficient stock&#39; });<br>      }<br>    }<br>    <br>    // Create order<br>    const order = await OrderModel.create({<br>      id: orderId,<br>      userId,<br>      items,<br>      shippingAddress,<br>      paymentMethod,<br>      status: &#39;pending&#39;<br>    }, { transaction });<br>    <br>    // Update inventory<br>    for (const item of items) {<br>      await ProductModel.updateStock(item.productId, -item.quantity, { transaction });<br>      InventoryLogger.info(`Stock updated - Product: ${item.productId}, Quantity: -${item.quantity}`);<br>    }<br>    <br>    // Process payment<br>    const paymentResult = await PaymentService.process({<br>      orderId,<br>      amount: order.total,<br>      paymentMethod<br>    });<br>    <br>    if (!paymentResult.success) {<br>      OrderLogger.error(`Payment failed - Order: ${orderId}, Reason: ${paymentResult.error}`);<br>      await transaction.rollback();<br>      return res.status(400).json({ message: &#39;Payment failed&#39; });<br>    }<br>    <br>    await transaction.commit();<br>    OrderLogger.info(`Order completed successfully - Order ID: ${orderId}, Amount: $${order.total}`);<br>    <br>    return res.json({ orderId, status: &#39;confirmed&#39; });<br>    <br>  } catch (error) {<br>    await transaction.rollback();<br>    OrderLogger.error(`Order creation failed - Order ID: ${orderId}, Error: ${error.message}`);<br>    return res.status(500).json({ message: &#39;Order processing failed&#39; });<br>  }<br>}</pre><p><strong>Database Logging Benefits:</strong></p><ul><li><strong>Transaction Integrity</strong>: Track rollbacks and failed operations</li><li><strong>Inventory Management</strong>: Monitor stock level changes</li><li><strong>Payment Processing</strong>: Audit financial transactions</li><li><strong>Performance Monitoring</strong>: Identify slow queries</li></ul><h3>Security Event Logging</h3><h4>Suspicious Activity Detection</h4><pre>async monitorSecurityEvents(req, res, next) {<br>  const clientIP = req.ip;<br>  const userAgent = req.get(&#39;User-Agent&#39;);<br>  const endpoint = req.path;<br>  <br>  // Log all API access<br>  SecurityLogger.info(`API Access - IP: ${clientIP}, Endpoint: ${endpoint}, User-Agent: ${userAgent}`);<br>  <br>  // Check for suspicious patterns<br>  const recentRequests = await SecurityModel.getRecentRequests(clientIP, 60); // Last minute<br>  <br>  if (recentRequests.length &gt; 100) {<br>    SecurityLogger.warn(`Rate limit exceeded - IP: ${clientIP}, Requests: ${recentRequests.length}`);<br>    return res.status(429).json({ message: &#39;Too many requests&#39; });<br>  }<br>  <br>  // Detect potential attacks<br>  if (req.body.password &amp;&amp; req.body.password.length &gt; 100) {<br>    SecurityLogger.error(`Potential attack - Long password attempt from IP: ${clientIP}`);<br>  }<br>  <br>  next();<br>}</pre><p><strong>Security Logging Value:</strong></p><ul><li><strong>Intrusion Detection</strong>: Identify attack patterns</li><li><strong>Compliance</strong>: Maintain security audit trails</li><li><strong>Forensic Analysis</strong>: Investigate security incidents</li><li><strong>Threat Intelligence</strong>: Build patterns for prevention</li></ul><h3>Business Intelligence Through Logs</h3><h4>User Behavior Analytics</h4><pre>async trackUserBehavior(req, res, next) {<br>  const userId = req.user?.id;<br>  const sessionId = req.session?.id;<br>  const page = req.path;<br>  const timestamp = new Date();<br>  <br>  if (userId) {<br>    AnalyticsLogger.info(`User activity - User: ${userId}, Page: ${page}, Session: ${sessionId}, Timestamp: ${timestamp}`);<br>    <br>    // Track user journey<br>    await AnalyticsModel.updateUserJourney(userId, {<br>      page,<br>      timestamp,<br>      referrer: req.get(&#39;Referer&#39;),<br>      device: req.get(&#39;User-Agent&#39;)<br>    });<br>  }<br>  <br>  next();<br>}</pre><p><strong>Business Insights:</strong></p><ul><li><strong>Conversion Funnels</strong>: Track drop-off points in purchase process</li><li><strong>Product Performance</strong>: Identify popular vs. unpopular items</li><li><strong>User Segmentation</strong>: Understand customer behavior patterns</li><li><strong>A/B Testing</strong>: Measure effectiveness of UI changes</li></ul><h3>Error Handling and Alerting</h3><h4>Structured Error Logging</h4><pre>async handleError(error, req, res, next) {<br>  const errorId = generateErrorId();<br>  const context = {<br>    errorId,<br>    url: req.url,<br>    method: req.method,<br>    ip: req.ip,<br>    userId: req.user?.id,<br>    userAgent: req.get(&#39;User-Agent&#39;),<br>    timestamp: new Date(),<br>    stack: error.stack<br>  };<br>  <br>  ErrorLogger.error(`Application error - ${error.message}`, context);<br>  <br>  // Send alert for critical errors<br>  if (error.status &gt;= 500) {<br>    await AlertService.sendAlert({<br>      level: &#39;critical&#39;,<br>      message: `Server Error: ${error.message}`,<br>      context<br>    });<br>  }<br>  <br>  res.status(error.status || 500).json({<br>    message: &#39;An error occurred&#39;,<br>    errorId<br>  });<br>}</pre><p><strong>Error Management:</strong></p><ul><li><strong>Root Cause Analysis</strong>: Stack traces help debug issues</li><li><strong>Alerting</strong>: Critical errors trigger notifications</li><li><strong>Trend Analysis</strong>: Identify recurring problems</li><li><strong>SLA Monitoring</strong>: Track system uptime and reliability</li></ul><h3>Real-World Scenarios Where Logs Saved the Day</h3><h3>Scenario 1: Payment System Outage</h3><p><strong>Impact:</strong> Logs enabled quick identification of the payment gateway issue, preventing inventory inconsistencies and customer dissatisfaction.</p><h3>Scenario 2: Security Breach Detection</h3><p><strong>Impact:</strong> Automated security monitoring prevented account takeover.</p><h3>Scenario 3: Performance Degradation</h3><p><strong>Impact:</strong> Performance logs identified database indexing issues before they severely impacted user experience.</p><h3>Best Practices for E-Commerce Logging</h3><h3>1. Structured Logging</h3><pre>// Good: Structured data<br>logger.info(&#39;Order processed&#39;, {<br>  orderId: &#39;ORD-12345&#39;,<br>  userId: &#39;USER-678&#39;,<br>  amount: 299.99,<br>  items: 3,<br>  paymentMethod: &#39;credit_card&#39;<br>});<br><br>// Bad: String concatenation<br>logger.info(`Order ORD-12345 processed for user USER-678`);</pre><h3>2. Log Levels Appropriately</h3><ul><li><strong>ERROR</strong>: System failures, exceptions</li><li><strong>WARN</strong>: Suspicious activities, potential issues</li><li><strong>INFO</strong>: Normal operations, business events</li><li><strong>DEBUG</strong>: Detailed troubleshooting information</li></ul><h3>3. Include Contextual Information</h3><p>Always include:</p><ul><li>User ID (when available)</li><li>Session ID</li><li>IP address</li><li>Timestamp</li><li>Request ID for correlation</li></ul><h3>4. Performance Considerations</h3><ul><li>Use asynchronous logging to avoid blocking operations</li><li>Implement log rotation to manage disk space</li><li>Consider log aggregation services (ELK stack, Splunk)</li><li>Archive old logs for compliance</li></ul><h3>5. Security and Privacy</h3><ul><li>Never log sensitive data (passwords, credit card numbers)</li><li>Implement log encryption for sensitive environments</li><li>Regular log review and anomaly detection</li><li>Compliance with data retention policies</li></ul><h3>Monitoring and Alerting Integration</h3><h4>Real-Time Dashboards</h4><pre>// Example alerting rules<br>const alertRules = {<br>  &#39;high-error-rate&#39;: {<br>    condition: (logs) =&gt; logs.filter(log =&gt; log.level === &#39;error&#39;).length &gt; 10,<br>    action: () =&gt; AlertService.sendAlert(&#39;High error rate detected&#39;)<br>  },<br>  <br>  &#39;payment-failures&#39;: {<br>    condition: (logs) =&gt; logs.filter(log =&gt; log.message.includes(&#39;Payment failed&#39;)).length &gt; 5,<br>    action: () =&gt; AlertService.pageOnCall(&#39;Payment system issues&#39;)<br>  }<br>};</pre><h3>Automated Responses</h3><ul><li>Auto-scale resources during high traffic</li><li>Temporarily disable features with high error rates</li><li>Send notifications to relevant teams</li><li>Trigger incident response workflows</li></ul><h3>Conclusion</h3><p>In an e-commerce platform where every millisecond counts and customer trust is paramount, comprehensive logging is not just a technical requirement — it’s a business imperative. The logging system we’ve implemented provides:</p><ul><li><strong>Operational Visibility</strong>: Real-time insights into system health</li><li><strong>Security Posture</strong>: Early detection of threats and anomalies</li><li><strong>Business Intelligence</strong>: Data-driven decisions for product and UX improvements</li><li><strong>Compliance Readiness</strong>: Audit trails for regulatory requirements</li><li><strong>Incident Response</strong>: Rapid diagnosis and resolution of issues</li></ul><p>By logging every API call, database operation, and user interaction, we create a comprehensive digital trail that transforms potential problems into opportunities for improvement. In the competitive world of e-commerce, this logging infrastructure isn’t just monitoring the system — it’s actively contributing to its success.</p><p>Remember: In e-commerce, logs aren’t just records of what happened; they’re the foundation of what will happen next. Every logged event is a data point that can prevent disasters, optimize performance, and drive business growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=086e256f0f42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade OTP-Based Password Reset System]]></title>
            <link>https://medium.com/@rajpg16/building-a-production-grade-otp-based-password-reset-system-4e45e2d3dca8?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e45e2d3dca8</guid>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[password-security]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[forgot-password]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 07:14:55 GMT</pubDate>
            <atom:updated>2026-01-15T07:14:55.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s digital landscape, implementing secure and user-friendly authentication systems is crucial for any web application. One of the most critical components is the password reset functionality, which must balance security with usability. In this article, I’ll walk you through implementing a comprehensive OTP-based password reset system for a pipeline management portal, covering everything from backend APIs to frontend components, security considerations, and enterprise-scale improvements.</p><h3>System Architecture Overview</h3><p>Our password reset system follows a three-step process:</p><ol><li><strong>Initiation</strong>: User requests password reset with email verification</li><li><strong>Verification</strong>: OTP validation via multiple channels</li><li><strong>Completion</strong>: Secure password update with JWT authorization</li></ol><p>The system is built with Node.js/Express backend, React frontend, and MSSQL database, featuring comprehensive logging and rate limiting.</p><h3>Backend Implementation</h3><h3>API Endpoints</h3><h4>1. Forgot Password Endpoint</h4><pre>POST /users/forgot-password<br>{<br>  &quot;email&quot;: &quot;user@company.com&quot;<br>}</pre><pre>// POST /users/forgot-password<br>async forgotPassword(req, res) {<br>  try {<br>    const { email } = req.body;<br>    const clientIP = req.ip || req.connection.remoteAddress;<br><br>    if (!email) {<br>      Logger.error(`Forgot Password - Missing email from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Email is required&quot;,<br>      });<br>    }<br><br>    const user = await UserModel.getUserByEmail(email);<br>    if (!user) {<br>      Logger.warn(`Forgot Password - User not found: ${email} from IP: ${clientIP}`);<br>      return res.status(404).json({<br>        success: false,<br>        message: &quot;User not found&quot;,<br>      });<br>    }<br><br>    const otp = Math.floor(100000 + Math.random() * 900000).toString();<br>    const expiresAt = Date.now() + 5 * 60 * 1000; // 5 minutes<br><br>    otpStore.set(email, { otp, expiresAt });<br><br>    const cookieOptions = {<br>      httpOnly: true,<br>      secure: false, // Set to true in production with HTTPS<br>      sameSite: &quot;Lax&quot;,<br>      path: &quot;/&quot;,<br>      maxAge: 5 * 60 * 1000,<br>    };<br><br>    res.cookie(`${OTP_COOKIE_NAME}_reset`, email, cookieOptions);<br>    res.cookie(<br>      `${OTP_COOKIE_NAME}_reset_data`,<br>      JSON.stringify({ otp, timestamp: Date.now() }),<br>      cookieOptions<br>    );<br><br>    // Send OTP via email and SMS asynchronously<br>    try {<br>      await sendEmailService(<br>        email,<br>        &quot;Password Reset OTP&quot;,<br>        `Your OTP for password reset is ${otp}. It is valid for 5 minutes.`<br>      );<br>    } catch (emailError) {<br>      console.error(&quot;Email Error:&quot;, emailError);<br>    }<br><br>    if (user.mobile_number) {<br>      try {<br>        await sendSMS(<br>          user.mobile_number,<br>          `One-time password (OTP) is ${otp} for password reset in GAIL UPIMS. Do not share OTP for security reasons.`<br>        );<br>      } catch (smsError) {<br>        console.error(&quot;SMS Error:&quot;, smsError);<br>      }<br>    }<br><br>    Logger.info(`Forgot Password - OTP sent successfully to: ${email} from IP: ${clientIP}`);<br><br>    return res.status(200).json({<br>      success: true,<br>      message: &quot;OTP sent successfully for password reset&quot;,<br>      email,<br>    });<br><br>  } catch (err) {<br>    Logger.error(`Forgot Password - Internal error: ${err.message} from IP: ${req.ip || req.connection.remoteAddress}`);<br>    console.error(&quot;Forgot Password Error:&quot;, err);<br>    return res.status(500).json({<br>      success: false,<br>      message: &quot;Internal server error during OTP generation&quot;,<br>    });<br>  }<br>}</pre><p><strong>Implementation Details:</strong></p><ul><li>Validates user existence in database</li><li>Generates 6-digit OTP with 5-minute expiry</li><li>Stores OTP in memory cache with timestamp</li><li>Sets HTTP-only cookies for session management</li><li>Sends OTP via email and SMS asynchronously</li><li>Returns immediate response (non-blocking)</li></ul><h4>2. OTP Verification Endpoint</h4><pre>POST /users/verify-reset-otp<br>{<br>  &quot;email&quot;: &quot;user@company.com&quot;,<br>  &quot;otp&quot;: &quot;123456&quot;<br>}</pre><pre>// POST /users/verify-reset-otp<br>async verifyResetOTP(req, res) {<br>  try {<br>    const { email, otp } = req.body;<br>    const clientIP = req.ip || req.connection.remoteAddress;<br><br>    if (!email || !otp) {<br>      Logger.warn(`Verify Reset OTP - Missing email or OTP from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Email and OTP are required&quot;,<br>        otp_verified: false,<br>      });<br>    }<br><br>    const cookies = req.cookies || {};<br>    const resetEmail = cookies[`${OTP_COOKIE_NAME}_reset`];<br>    const otpDataCookie = cookies[`${OTP_COOKIE_NAME}_reset_data`];<br><br>    if (!resetEmail || !otpDataCookie) {<br>      Logger.warn(`Verify Reset OTP - Session not found for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Reset OTP session not found&quot;,<br>        otp_verified: false,<br>      });<br>    }<br><br>    let storedOtp, timestamp;<br>    try {<br>      const parsed = JSON.parse(otpDataCookie);<br>      storedOtp = parsed.otp;<br>      timestamp = parsed.timestamp;<br>    } catch (e) {<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Invalid OTP data&quot;,<br>        otp_verified: false,<br>      });<br>    }<br><br>    if (Date.now() - timestamp &gt; 5 * 60 * 1000) {<br>      Logger.warn(`Verify Reset OTP - OTP expired for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;OTP expired&quot;,<br>        otp_verified: false,<br>      });<br>    }<br><br>    if (otp !== storedOtp) {<br>      Logger.warn(`Verify Reset OTP - Invalid OTP for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Invalid OTP&quot;,<br>        otp_verified: false,<br>      });<br>    }<br><br>    if (email.toLowerCase() !== resetEmail.toLowerCase()) {<br>      Logger.warn(`Verify Reset OTP - Email mismatch for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Email does not match reset session&quot;,<br>        otp_verified: false,<br>      });<br>    }<br><br>    // Issue JWT reset token<br>    const resetToken = jwt.sign(<br>      { email, purpose: &#39;reset_password&#39; },<br>      process.env.JWT_SECRET || &#39;default_secret&#39;,<br>      { expiresIn: &#39;10m&#39; }<br>    );<br><br>    res.cookie(&#39;reset_token&#39;, resetToken, {<br>      httpOnly: true,<br>      secure: false,<br>      sameSite: &quot;Lax&quot;,<br>      path: &quot;/&quot;,<br>      maxAge: 10 * 60 * 1000,<br>    });<br><br>    res.clearCookie(`${OTP_COOKIE_NAME}_reset`);<br>    res.clearCookie(`${OTP_COOKIE_NAME}_reset_data`);<br><br>    Logger.info(`Verify Reset OTP - Success for email: ${email} from IP: ${clientIP}`);<br><br>    return res.status(200).json({<br>      success: true,<br>      otp_verified: true,<br>      message: &quot;OTP verified successfully for password reset&quot;,<br>      email,<br>    });<br><br>  } catch (err) {<br>    Logger.error(`Verify Reset OTP - Internal error: ${err.message} for email: ${req.body.email || &#39;unknown&#39;} from IP: ${req.ip || req.connection.remoteAddress}`);<br>    console.error(&quot;Error in verifyResetOTP:&quot;, err);<br>    return res.status(500).json({<br>      success: false,<br>      message: &quot;Internal server error&quot;,<br>      otp_verified: false,<br>    });<br>  }<br>}</pre><p><strong>Security Features:</strong></p><ul><li>Validates OTP against stored value and expiry</li><li>Issues short-lived JWT token (10 minutes) for reset authorization</li><li>Clears OTP cookies after successful verification</li><li>Comprehensive input validation and error handling</li></ul><h4>3. Password Reset Endpoint</h4><pre>POST /users/reset-password<br>{<br>  &quot;email&quot;: &quot;user@company.com&quot;,<br>  &quot;newPassword&quot;: &quot;SecurePass123!&quot;<br>}</pre><pre>// POST /users/reset-password<br>async resetPassword(req, res) {<br>  try {<br>    const { email, newPassword } = req.body;<br>    const clientIP = req.ip || req.connection.remoteAddress;<br><br>    if (!email || !newPassword) {<br>      Logger.warn(`Reset Password - Missing email or password from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Email and new password are required&quot;,<br>      });<br>    }<br><br>    const resetToken = req.cookies.reset_token;<br>    if (!resetToken) {<br>      Logger.warn(`Reset Password - No reset token for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Reset session expired or invalid&quot;,<br>      });<br>    }<br><br>    let decoded;<br>    try {<br>      decoded = jwt.verify(resetToken, process.env.JWT_SECRET || &#39;default_secret&#39;);<br>    } catch (err) {<br>      Logger.warn(`Reset Password - Invalid JWT token for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Invalid reset token&quot;,<br>      });<br>    }<br><br>    if (decoded.email !== email || decoded.purpose !== &#39;reset_password&#39;) {<br>      Logger.warn(`Reset Password - Token mismatch for email: ${email} from IP: ${clientIP}`);<br>      return res.status(400).json({<br>        success: false,<br>        message: &quot;Invalid reset token&quot;,<br>      });<br>    }<br><br>    const user = await UserModel.getUserByEmail(email);<br>    if (!user) {<br>      Logger.error(`Reset Password - User not found during reset: ${email} from IP: ${clientIP}`);<br>      return res.status(404).json({<br>        success: false,<br>        message: &quot;User not found&quot;,<br>      });<br>    }<br><br>    await UserModel.updatePassword(user.user_id, newPassword);<br><br>    res.clearCookie(&#39;reset_token&#39;);<br><br>    Logger.info(`Reset Password - Success for user ID: ${user.user_id}, email: ${email} from IP: ${clientIP}`);<br><br>    return res.status(200).json({<br>      success: true,<br>      message: &quot;Password reset successfully&quot;,<br>    });<br><br>  } catch (err) {<br>    Logger.error(`Reset Password - Internal error: ${err.message} for email: ${req.body.email || &#39;unknown&#39;} from IP: ${req.ip || req.connection.remoteAddress}`);<br>    console.error(&quot;Reset Password Error:&quot;, err);<br>    return res.status(500).json({<br>      success: false,<br>      message: &quot;Internal server error&quot;,<br>    });<br>  }<br>}</pre><p><strong>Implementation:</strong></p><ul><li>Verifies JWT reset token</li><li>Updates password with bcrypt hashing (salt rounds: 10)</li><li>Clears reset token cookie</li><li>Updates password timestamp in database</li></ul><h4>Rate Limiting Middleware</h4><pre>// middleware/rateLimiter.js<br>const rateLimitStore = new Map();<br><br>const rateLimit = (keyPrefix, windowMs, maxAttempts) =&gt; {<br>  return (req, res, next) =&gt; {<br>    const key = `${keyPrefix}:${req.ip}`;<br>    const now = Date.now();<br>    const windowStart = now - windowMs;<br><br>    if (!rateLimitStore.has(key)) {<br>      rateLimitStore.set(key, []);<br>    }<br><br>    const attempts = rateLimitStore.get(key).filter(timestamp =&gt; timestamp &gt; windowStart);<br><br>    if (attempts.length &gt;= maxAttempts) {<br>      return res.status(429).json({<br>        success: false,<br>        message: &#39;Too many attempts, please try again later.&#39;<br>      });<br>    }<br><br>    attempts.push(now);<br>    rateLimitStore.set(key, attempts);<br><br>    next();<br>  };<br>};<br><br>module.exports = { rateLimit };</pre><h4>Route Configuration</h4><pre>// routes/usersRoute.js<br>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const userController = require(&quot;../controller/usersController&quot;);<br>const { rateLimit } = require(&quot;../middleware/rateLimiter&quot;);<br><br>router.post(&quot;/signup&quot;, userController.signup);<br>router.post(&quot;/login&quot;, userController.login);<br>router.post(&quot;/forgot-password&quot;, rateLimit(&#39;forgot-password&#39;, 15 * 60 * 1000, 5), userController.forgotPassword);<br>router.post(&quot;/verify-reset-otp&quot;, rateLimit(&#39;verify-reset-otp&#39;, 15 * 60 * 1000, 5), userController.verifyResetOTP);<br>router.post(&quot;/reset-password&quot;, userController.resetPassword);<br><br>module.exports = router;  </pre><h3>Security Architecture</h3><h4>Rate Limiting</h4><ul><li>In-memory rate limiter (5 attempts per 15 minutes per IP)</li><li>Prevents brute force attacks on OTP endpoints</li><li>Configurable window and attempt limits</li></ul><h4>Session Management</h4><ul><li>HTTP-only cookies prevent XSS access</li><li>Secure cookie flags in production</li><li>Automatic cleanup of expired sessions</li></ul><h4>Data Protection</h4><ul><li>Passwords hashed with bcrypt</li><li>OTP stored temporarily in memory (not persisted)</li><li>JWT tokens signed with server secret</li><li>Input sanitization and SQL injection prevention</li></ul><h3>Frontend Implementation</h3><h4>Multi-Step Component Design</h4><p>The React component implements a three-step wizard:</p><pre>// Step 1: Email + Captcha<br>const [step, setStep] = useState(&#39;email&#39;);<br><br>// Step 2: OTP Input (6 fields with auto-focus)<br>const [otp, setOtp] = useState([&#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;, &#39;&#39;]);<br><br>// Step 3: New Password<br>const [newPassword, setNewPassword] = useState(&#39;&#39;);</pre><h4>Auto-Submit OTP Feature</h4><pre>const handleOtpChange = (index, value) =&gt; {<br>  const newOtp = [...otp];<br>  newOtp[index] = value;<br>  <br>  // Auto-submit when all digits entered<br>  if (newOtp.every(digit =&gt; digit !== &#39;&#39;)) {<br>    handleVerifyOTP(newOtp.join(&#39;&#39;));<br>  }<br>};</pre><h4>API Integration</h4><pre>const authService = {<br>  forgotPassword: async (email) =&gt; {<br>    const response = await apiClient.post(&quot;/users/forgot-password&quot;, { email });<br>    return response.data;<br>  },<br>  <br>  verifyResetOTP: async (email, otp) =&gt; {<br>    const response = await apiClient.post(&quot;/users/verify-reset-otp&quot;, { email, otp });<br>    return response.data;<br>  },<br>  <br>  resetPassword: async (email, newPassword) =&gt; {<br>    const response = await apiClient.post(&quot;/users/reset-password&quot;, { email, newPassword });<br>    return response.data;<br>  }<br>};</pre><h3>Production-Grade Features</h3><h3>1. Comprehensive Logging</h3><ul><li>Winston-based logging with separate info/error files</li><li>IP address tracking for security monitoring</li><li>User activity audit trail</li><li>Timestamped entries with structured JSON format</li></ul><h3>2. Error Handling &amp; Validation</h3><ul><li>Input validation at all layers</li><li>Graceful error responses with appropriate HTTP codes</li><li>Database transaction safety</li><li>Fallback mechanisms for service failures</li></ul><h3>3. Security Headers &amp; CORS</h3><ul><li>Security headers (CSP, XSS protection, etc.)</li><li>Configured CORS with credentials support</li><li>Environment-based configuration</li></ul><h3>4. Performance Optimizations</h3><ul><li>Non-blocking email/SMS operations</li><li>In-memory OTP storage for fast lookups</li><li>Connection pooling for database operations</li><li>Efficient bcrypt hashing</li></ul><h3>5. Monitoring &amp; Observability</h3><ul><li>Structured logging for metrics collection</li><li>Error tracking with stack traces</li><li>Performance monitoring capabilities</li></ul><h3>Tradeoffs and Considerations</h3><h3>Security vs. Usability Balance</h3><p><strong>Security Benefits:</strong></p><ul><li>Multi-channel OTP verification (email + SMS)</li><li>Short-lived tokens prevent replay attacks</li><li>Rate limiting prevents brute force</li><li>Secure cookie-based sessions</li></ul><p><strong>Usability Tradeoffs:</strong></p><ul><li>Requires multiple steps (email → OTP → password)</li><li>Depends on email/SMS delivery reliability</li><li>CAPTCHA adds friction but prevents automation</li></ul><h3>Scalability Considerations</h3><p><strong>Current Implementation:</strong></p><ul><li>In-memory rate limiting (single server only)</li><li>Memory-based OTP storage (lost on restart)</li><li>Synchronous database operations</li></ul><p><strong>Scalability Tradeoffs:</strong></p><ul><li>Memory storage limits horizontal scaling</li><li>No distributed caching layer</li><li>Database connection pooling helps but has limits</li></ul><h3>Performance Optimizations</h3><p><strong>Implemented:</strong></p><ul><li>Async email/SMS to avoid blocking responses</li><li>Efficient in-memory lookups</li><li>Minimal database queries per request</li></ul><p><strong>Performance Tradeoffs:</strong></p><ul><li>Memory usage for OTP storage</li><li>Email/SMS delivery time affects user experience</li><li>Rate limiting may cause legitimate user frustration</li></ul><h3>Potential Improvements for Enterprise Scale</h3><h3>1. Distributed Architecture</h3><ul><li><strong>Redis Integration</strong>: Replace in-memory storage with Redis for OTP and rate limiting</li><li><strong>Load Balancing</strong>: Session affinity or distributed sessions</li><li><strong>Microservices</strong>: Separate authentication service with API gateway</li></ul><h3>2. Enhanced Security</h3><ul><li><strong>Hardware Security Keys</strong>: FIDO2/WebAuthn support</li><li><strong>Biometric Authentication</strong>: Integration with device biometrics</li><li><strong>Risk-Based Authentication</strong>: Analyze login patterns and device fingerprints</li><li><strong>Account Lockout</strong>: Progressive delays and temporary account suspension</li></ul><h3>3. Advanced Monitoring</h3><ul><li><strong>SIEM Integration</strong>: Send logs to Security Information and Event Management systems</li><li><strong>Real-time Alerts</strong>: Automated alerts for suspicious activities</li><li><strong>Compliance Reporting</strong>: GDPR/CCPA audit trails and reporting</li></ul><h3>4. User Experience Enhancements</h3><ul><li><strong>Progressive Web App</strong>: Offline OTP generation capabilities</li><li><strong>Push Notifications</strong>: Alternative to SMS for OTP delivery</li><li><strong>Magic Links</strong>: Email-based passwordless authentication</li><li><strong>Social Login Integration</strong>: OAuth providers for enterprise SSO</li></ul><h3>5. Compliance &amp; Governance</h3><ul><li><strong>Audit Logging</strong>: Immutable audit trails with blockchain verification</li><li><strong>Data Residency</strong>: Geographic data storage compliance</li><li><strong>Privacy Controls</strong>: Granular consent management and data portability</li><li><strong>Incident Response</strong>: Automated breach detection and response workflows</li></ul><h3>6. Performance &amp; Reliability</h3><ul><li><strong>CDN Integration</strong>: Global distribution of static assets</li><li><strong>Database Sharding</strong>: Horizontal scaling for user data</li><li><strong>Caching Layers</strong>: Multi-level caching (Redis, CDN, browser)</li><li><strong>Circuit Breakers</strong>: Fault tolerance for external service dependencies</li></ul><h3>7. Advanced Analytics</h3><ul><li><strong>User Behavior Analytics</strong>: Machine learning for anomaly detection</li><li><strong>Conversion Funnel Analysis</strong>: Optimize registration and reset flows</li><li><strong>A/B Testing Framework</strong>: Continuous improvement of security measures</li><li><strong>Predictive Security</strong>: Anticipate and prevent security threats</li></ul><h3>Conclusion</h3><p>Building a production-grade password reset system requires careful consideration of security, usability, and scalability. The implementation we’ve explored provides a solid foundation with OTP-based verification, comprehensive logging, and rate limiting, while maintaining good user experience.</p><p>The tradeoffs between security and usability are inevitable, but can be optimized through iterative improvements and user feedback. For enterprise deployments, the potential improvements outlined above provide a roadmap for scaling the system to handle millions of users while maintaining the highest security standards.</p><p>Remember, security is not a one-time implementation but an ongoing process of monitoring, updating, and adapting to new threats. Regular security audits, penetration testing, and staying current with industry best practices are essential for maintaining a robust authentication system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e45e2d3dca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Git Push to Production: A Simple Node.js CI/CD Pipeline with GitHub Actions and AWS]]></title>
            <link>https://medium.com/@rajpg16/from-git-push-to-production-a-simple-node-js-ci-cd-pipeline-with-github-actions-and-aws-1e7050fef3a0?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e7050fef3a0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 14:59:22 GMT</pubDate>
            <atom:updated>2025-12-26T14:59:22.426Z</atom:updated>
            <content:encoded><![CDATA[<p>I Push Code. My Server Updates Itself. Here’s How.</p><p>A few years ago, deploying meant SSH, pulling code, installing dependencies, restarting services, and praying nothing broke.</p><p>Now my deployment ritual is just this:</p><pre>git push origin &lt;branch_name&gt;</pre><p>That’s it.</p><p>Somewhere in the cloud, gears start turning. Containers get built. Images get shipped. Servers update themselves quietly.</p><p>This article walks you through <strong>exactly how to build that pipeline for a Node.js app</strong>, step by step, with no Kubernetes and no buzzword fog.</p><h3>The Deployment Story (High Level)</h3><pre>Git Push<br>↓<br>GitHub Actions wakes up<br>↓<br>Docker image is built<br>↓<br>Image pushed to AWS ECR<br>↓<br>EC2 pulls latest image<br>↓<br>Container restarts</pre><p>Each arrow is intentional. Each step solves a real problem.</p><p>Let’s build it.</p><h3>Step 0: What You Need Before Starting</h3><p>Assumptions:</p><ul><li>Node.js app (Express, Fastify, NestJS, anything)</li><li>One EC2 instance (Amazon Linux / Ubuntu)</li><li>Docker is installed on EC2</li><li>AWS ECR repository created</li><li>GitHub repo connected</li></ul><p>On EC2, Docker should already be running:</p><pre>docker --version</pre><p>If this fails, fix that first. Containers are the backbone here.</p><h3>Step 1: Dockerize the Node.js App</h3><p>This is where predictability begins.</p><h3>Dockerfile</h3><pre>FROM node:18-alpine</pre><pre>WORKDIR /app</pre><pre>COPY package*.json ./<br>RUN npm install --production</pre><pre>COPY . .</pre><pre>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p>Why this matters:</p><ul><li>Same Node version everywhere</li><li>Same dependencies everywhere</li><li>No “works on my machine” excuses</li></ul><p>Build once. Run anywhere.</p><h3>Step 2: Create the GitHub Actions Workflow</h3><p>This is the heart of automation.</p><p>Create this file:</p><pre>.github/workflows/deploy.yml</pre><h3>GitHub Actions YAML (Node.js + ECR + EC2)</h3><pre>name: Deploy Node App to EC2<br>on:<br>  push:<br>    branches:<br>      - main<br>env:<br>  AWS_REGION: ap-south-1<br>  ECR_REPOSITORY: my-node-app<br>  IMAGE_TAG: latest<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br>      - name: Login to Amazon ECR<br>        uses: aws-actions/amazon-ecr-login@v2<br>      - name: Build Docker image<br>        run: |<br>          docker build -t $ECR_REPOSITORY:$IMAGE_TAG .<br>      - name: Tag Docker image<br>        run: |<br>          docker tag $ECR_REPOSITORY:$IMAGE_TAG \<br>          ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${AWS_REGION}.amazonaws.com/$ECR_REPOSITORY:$IMAGE_TAG<br>      - name: Push Docker image to ECR<br>        run: |<br>          docker push \<br>          ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${AWS_REGION}.amazonaws.com/$ECR_REPOSITORY:$IMAGE_TAG<br>      - name: Deploy on EC2 via SSH<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ secrets.EC2_HOST }}<br>          username: ec2-user<br>          key: ${{ secrets.EC2_SSH_KEY }}<br>          script: |<br>            docker pull ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${AWS_REGION}.amazonaws.com/$ECR_REPOSITORY:$IMAGE_TAG<br>            docker stop node-app || true<br>            docker rm node-app || true<br>            docker run -d \<br>              --name node-app \<br>              -p 3000:3000 \<br>              ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${AWS_REGION}.amazonaws.com/$ECR_REPOSITORY:$IMAGE_TAG</pre><h3>Step 3: Secrets That Make This Secure 🔐</h3><p>In GitHub → <strong>Settings → Secrets → Actions</strong>, add:</p><ul><li>AWS_ACCESS_KEY_ID</li><li>AWS_SECRET_ACCESS_KEY</li><li>AWS_ACCOUNT_ID</li><li>EC2_HOST</li><li>EC2_SSH_KEY (private key)</li></ul><p>No secrets in code. Ever.</p><p>Your repo stays clean. Your pipeline stays safe.</p><h3>Step 4: What Actually Happens After git push</h3><p>Let’s narrate it like a story:</p><ol><li>You push Node.js code</li><li>GitHub Actions spins up a clean Linux runner</li><li>Docker image is built from scratch</li><li>Image is pushed to ECR</li><li>EC2 pulls the latest image</li><li>Old container dies quietly</li><li>New container takes over</li></ol><p>No SSH sessions. No manual restarts. No stress.</p><p>Production just updates itself.</p><h3>Why This Works So Well for Node.js</h3><p>Node apps love this model because:</p><ul><li>Startup is fast</li><li>Containers are lightweight</li><li>Horizontal scaling is easy later</li><li>Rollback is trivial</li></ul><p>To rollback:</p><pre>docker run my-node-app:previous-tag</pre><p>That’s it. No redeploy ceremony.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e7050fef3a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LinkedIn stores connections as a distributed social graph and computes mutuals, and Databases…]]></title>
            <link>https://medium.com/@rajpg16/how-linkedin-linkedin-stores-connections-as-a-distributed-social-graph-and-computes-mutuals-and-b0656ddb52df?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0656ddb52df</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[linkedin]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 18:26:52 GMT</pubDate>
            <atom:updated>2025-12-26T14:59:55.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>How <strong>LinkedIn stores connections as a distributed social graph and computes mutuals, and Databases used.</strong></h3><p>LinkedIn models its network as a <strong>graph</strong>:</p><ul><li><strong>Nodes (vertices)</strong> -&gt;Members</li><li><strong>Edges (relationships)</strong> -&gt;Connections (1st-degree connections)</li></ul><p>If you have <strong>60,000 connections</strong>, that means:</p><ul><li>One node (example your profile)</li><li>~60,000 edges linking your node to other member nodes</li></ul><p>This is a <strong>many-to-many</strong> relationship, since each connection belongs to two people.</p><h3>2. Data storage approach (high level)</h3><h3>a. Graph-like data on distributed systems</h3><p>LinkedIn historically built its own infrastructure rather than relying on off-the-shelf graph databases at massive scale.</p><p>They typically use:</p><ul><li><strong>Distributed key-value stores</strong> (e.g., LinkedIn’s own systems like <em>Voldemort</em> in the past)</li><li><strong>Graph abstractions on top of these stores</strong></li></ul><p>Each user ID is a key, and the value contains:</p><ul><li>List of connection IDs</li><li>Metadata (connection date, status, privacy flags, etc.)</li></ul><p>Example (simplified):</p><pre>UserID: 12345<br>Connections: [67890, 54321, 98765, ...]</pre><h3>3. How rough number around 60K connections are handled efficiently</h3><h3>a. Sharding (splitting data)</h3><p>Your 60K connections are <strong>not stored in one giant row</strong>.</p><p>Instead:</p><ul><li>The connection list is <strong>split (sharded)</strong> across multiple machines</li><li>Each shard might store a few thousand connection IDs</li></ul><p>This avoids performance bottlenecks and size limits.</p><h3>b. Bidirectional storage</h3><p>Connections are <strong>mutual</strong>, so LinkedIn stores them for both users:</p><ul><li>Your user record → contains their IDs</li><li>Their user record → contains your ID</li></ul><p>This allows fast lookup like:</p><ul><li>“Who are Manish’s connections?”</li><li>“Is Manish connected to Yash?”</li></ul><h3>c. Caching for fast access</h3><p>For frequently accessed profiles (like users with many connections):</p><ul><li>Parts of the connection graph are stored in <strong>in-memory caches</strong></li><li>This makes loading “1st-degree connections” very fast, even at 60K+</li></ul><h3>How does it stores in the DB , which DB is used and why ?</h3><h3>1. Primary database for connections: Espresso (LinkedIn’s NoSQL DB)</h3><h3>What is Espresso?</h3><ul><li><strong>Espresso</strong> is LinkedIn’s <strong>in-house distributed NoSQL database</strong></li><li>Similar in spirit to Google Bigtable or Amazon DynamoDB</li><li>Designed specifically for <strong>social graph data</strong></li></ul><h3>Why Espresso is used</h3><p>Connections need:</p><ul><li>Extremely <strong>fast reads</strong> (view profile, mutual connections)</li><li><strong>Horizontal scaling</strong> (millions of users × thousands of connections)</li><li><strong>High availability</strong> (LinkedIn cannot go down)</li></ul><p>Relational DBs (like MySQL) <strong>cannot scale this well</strong> for graph-style access.</p><h3>How connections look in Espresso (simplified)</h3><p>Each user is a key:</p><pre>Key: user_id<br>Value: {<br>  connections: [<br>    { target_user_id: 456, since: 2019, visibility: public },<br>    { target_user_id: 789, since: 2021, visibility: private }<br>  ]<br>}</pre><p>If you have <strong>60K connections</strong>:</p><ul><li>Your connections are <strong>split across multiple partitions</strong></li><li>Each partition lives on a different server</li><li>Reads happen in parallel</li></ul><h3>2. Why NOT a relational DB (MySQL / PostgreSQL)?</h3><h3>Relational model example (bad at scale)</h3><pre>connections(user_id, connected_user_id, created_at)</pre><p>Problems:</p><ul><li>Table would have <strong>hundreds of billions of rows</strong></li><li>JOINs for mutual connections become very slow</li><li>Vertical scaling hits limits quickly</li></ul><p>Relational DBs are great for:</p><ul><li>Transactions</li><li>Strong consistency</li></ul><p>But <strong>terrible for large-scale graph traversal</strong>.</p><h3>3. Secondary system: Venice (Derived Data Store)</h3><h3>What Venice does</h3><p>Venice stores <strong>precomputed views</strong> of data, such as</p><ul><li>Mutual connections</li><li>“People You May Know”</li><li>Connection counts</li></ul><h3>Why it’s needed</h3><p>Instead of computing:</p><blockquote><em>“Which of Manish’s 60K connections overlap with Yash’s 40K connections?”</em></blockquote><p>…in real time (very expensive), LinkedIn:</p><ul><li>Precomputes results</li><li>Stores them in Venice</li><li>Serves them in <strong>milliseconds</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0656ddb52df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Day I Learned Why Transactions and Connection Pools Are Not Optional]]></title>
            <link>https://medium.com/@rajpg16/the-day-i-learned-why-transactions-and-connection-pools-are-not-optional-1fdab039b836?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fdab039b836</guid>
            <category><![CDATA[connection-pooling]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 08:17:40 GMT</pubDate>
            <atom:updated>2025-12-19T08:17:40.333Z</atom:updated>
            <content:encoded><![CDATA[<p>It started with a bug that “wasn’t reproducible”.</p><p>An approval went through. The UI showed success. But the application never moved to the next stage.</p><p>No crash. No error. Just… broken data.</p><h3>The Invisible Bug</h3><p>We had a simple workflow system:</p><ol><li>A user approves a request</li><li>We log the action</li><li>We move the request to the next stage</li><li>We notify the next team</li></ol><p>Four steps.</p><p>One API call.</p><p>On paper, everything looked fine.</p><p>In reality, production logs told a different story:</p><ul><li>The approval action existed</li><li>The request stage didn’t change</li></ul><p>The system believed two contradictory things at the same time.</p><p>That’s when I learned a painful truth:<strong><em>Databases don’t protect you from partial success.<br> You have to ask for it.</em></strong></p><blockquote><strong><em>Databases don’t protect you from partial success.<br> You have to ask for it.</em></strong></blockquote><h3>Real-World Analogy: A Bank Transfer</h3><p>Imagine transferring money from your account to a friend.</p><p>What if the system:</p><ul><li>Deducts money from your account</li><li>Crashes before crediting your friend</li></ul><p>You wouldn’t accept:</p><blockquote><em>“Sorry, step one worked.”</em></blockquote><p>That’s exactly how workflows break without transactions.</p><h3>What a Transaction Really Is</h3><p>A <strong>transaction</strong> is a promise to the database:</p><blockquote><em>“Treat these operations as one single action.”</em></blockquote><p>Either:</p><ul><li><strong>Everything succeeds → COMMIT</strong></li><li><strong>Anything fails → ROLLBACK</strong></li></ul><p>No in-between states.<br>No half-truths.</p><h3>But First… What Is a Connection Pool?</h3><p>Before we even talk about transactions, let’s talk about <strong>connections</strong>.</p><p>Opening a database connection is <strong>expensive</strong>:</p><ul><li>Handshake</li><li>Authentication</li><li>Memory allocation</li></ul><p>Doing that for every API request is like:</p><blockquote><em>Calling the bank, opening a new account, transferring money, and closing it — every time.</em></blockquote><p>That’s why we use <strong>connection pooling</strong>.</p><h3>Connection Pooling (Real-World Example)</h3><p>Think of a <strong>restaurant</strong>:</p><ul><li>The <strong>kitchen</strong> = Database</li><li><strong>Waiters</strong> = Connections</li><li><strong>Customers</strong> = API requests</li></ul><p>You don’t hire a new waiter for every customer.</p><p>You maintain:</p><ul><li>A fixed number of waiters</li><li>Customers borrow a waiter, place orders, and release them</li></ul><p>That’s exactly what a <strong>connection pool</strong> does.</p><h3>Pool vs Connection vs Request (Mental Model)</h3><p>ConceptReal-World MeaningPoolRestaurant staff managerConnectionA waiterRequestA single orderTransactionOne combined bill</p><p>You:</p><ul><li>Create <strong>one pool</strong> for the app</li><li>Borrow connections automatically</li><li>Execute queries using requests</li></ul><h3>Where Transactions Fit In</h3><p>Back to our workflow bug.</p><p>Approving a request required:</p><ol><li>Insert action log</li><li>Update request stage</li><li>Insert notification</li></ol><p>Without a transaction, each step was:</p><blockquote><em>“Best effort”</em></blockquote><p>With a transaction:</p><blockquote><em>“All or nothing”</em></blockquote><h3>What Went Wrong (Code Smell)</h3><pre>await pool.request().query(&quot;INSERT action_log&quot;);<br>await pool.request().query(&quot;UPDATE request_stage&quot;);</pre><p>Looks fine.<br> — Works most of the time.<br> — Fails silently at scale.</p><h3>The Correct Way</h3><pre>const transaction = new sql.Transaction(pool);<br>try {<br>    await transaction.begin();<br>    const request = new sql.Request(transaction);<br>    await request.query(&quot;INSERT action_log&quot;);<br>    await request.query(&quot;UPDATE request_stage&quot;);<br>    await request.query(&quot;INSERT notification&quot;);<br>    await transaction.commit();<br>} catch (err) {<br>    await transaction.rollback();<br>}</pre><p>Now the database guarantees consistency.</p><h3>Important Rule Most Developers Miss</h3><p>When using a transaction:</p><ul><li><strong>Do not create multiple requests</strong></li><li><strong>Do not use </strong><strong>pool.request()</strong></li></ul><p>A transaction binds to <strong>one connection</strong>.<br> Multiple requests may use multiple connections — and break atomicity.</p><h3>When NOT to Use Transactions</h3><p>Not everything needs protection.</p><h3>Don’t use transactions for:</h3><ul><li>GET APIs</li><li>Dashboards</li><li>Reports</li><li>Independent updates</li></ul><p>Transactions hold locks.<br> Locks reduce throughput.</p><p>Use them only where correctness matters.</p><h3>Another Real-World Example: Airport Security</h3><ul><li><strong>Pool</strong> = Security lanes</li><li><strong>Connection</strong> = One lane</li><li><strong>Request</strong> = One passenger</li><li><strong>Transaction</strong> = Passenger + luggage + boarding pass check</li></ul><p>You don’t want:</p><ul><li>Passenger cleared</li><li>Luggage unchecked</li></ul><p>All checks pass → board<br> Any check fails → stop</p><p>That’s a transaction.</p><h3>The Final Lesson</h3><p>Databases are fast.<br> They are powerful.<br> But they are not mind readers.</p><p>If your system:</p><ul><li>Has approvals</li><li>Has stages</li><li>Has rollbacks</li><li>Has money or compliance</li></ul><p>Then <strong>transactions are not optional</strong>.</p><p>And connection pooling is not an optimization — <br> it’s how production systems survive load.</p><h3>🧠 One Sentence to Remember</h3><blockquote><strong><em>If partial success is dangerous, use a transaction.<br>If opening a connection per request sounds insane — use pooling.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fdab039b836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles Explained for Humans (Not Just Developers) Typescript]]></title>
            <link>https://medium.com/@rajpg16/solid-principles-explained-for-humans-not-just-developers-typescript-5712474ddfb7?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5712474ddfb7</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 18:47:35 GMT</pubDate>
            <atom:updated>2025-12-16T18:47:35.547Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you own a small food delivery app. At first, life is simple. One restaurant, one payment method, one delivery guy. Then success arrives. New features show up with luggage.</p><p>SOLID principles exist to make sure your code doesn’t start tripping over its own shoelaces.</p><h3>S — Single Responsibility Principle</h3><p><strong>One job, done well</strong></p><p><strong>Meaning in plain words</strong><br>Every class should have <strong>only one reason to change</strong>.</p><p>Think of a chef. If the chef cooks, cleans, takes orders, and manages accounts, something will break. Not because the chef is bad, but because the job description is chaotic.</p><h3>Bad Design</h3><pre>class OrderService {<br>  createOrder() {}<br>  chargePayment() {}<br>  sendEmail() {}<br>}</pre><p>Now, if email logic changes, order logic gets touched. Unrelated chaos.</p><h3>Better Design</h3><pre>class OrderService {<br>  createOrder() {}<br>}<br><br>class PaymentService {<br>  charge() {}<br>}<br>class NotificationService {<br>  sendEmail() {}<br>}</pre><h3>Takeaway</h3><p>One person, one responsibility. Less confusion. Fewer mistakes.</p><h3>O — Open/Closed Principle</h3><p><strong>Open for extension, closed for modification</strong></p><p><strong>Meaning in plain words</strong><br>You should be able to <strong>add new behavior without rewriting old code</strong>.</p><p>You don’t tear down a house to add a balcony.</p><h3>Bad Design</h3><pre>if (paymentType === &#39;CARD&#39;) payByCard();<br>else if (paymentType === &#39;UPI&#39;) payByUPI();</pre><p>Every new payment means editing this block.</p><h3>Better Design</h3><pre>interface Payment {<br>  pay(): void;<br>}<br><br>class CardPayment implements Payment {<br>  pay() {}<br>}<br>class UPIPayment implements Payment {<br>  pay() {}<br>}</pre><p>Now adding WalletPayment doesn’t disturb the existing code.</p><h3>Layman’s takeaway</h3><p>Good systems grow by <strong>adding</strong>, not by <strong>rewriting</strong>.</p><h3>L — Liskov Substitution Principle</h3><p><strong>Subtypes should behave like their parents</strong></p><p><strong>Meaning in plain words</strong><br>If something claims to be a type, it must <strong>behave like that type without surprises</strong>.</p><p>If you rent a car and the steering wheel falls off, it doesn’t matter that it’s technically “a car”.</p><h3>Bad Design</h3><pre>class Payment {<br>  pay() {}<br>}<br><br>class CashOnDelivery extends Payment {<br>  pay() {<br>    throw new Error(&quot;Can&#39;t prepay&quot;);<br>  }<br>}</pre><p>The app expects all payments to work the same way.</p><h3>Better Design</h3><pre>interface OnlinePayment {<br>  pay(): void;<br>}<br><br>class CardPayment implements OnlinePayment {}<br>class UPIPayment implements OnlinePayment {}</pre><p>COD simply doesn’t pretend to be an online payment.</p><h3>Takeaway</h3><p>Don’t promise what you can’t deliver.</p><h3>I — Interface Segregation Principle</h3><p><strong>Don’t force people to do what they don’t need</strong></p><p><strong>Meaning in plain words</strong><br>Big, fat interfaces make everyone unhappy.</p><p>Imagine forcing a delivery partner to cook food because “everyone in the app must cook.</p><h3>Bad Design</h3><pre>interface UserActions {<br>  placeOrder(): void;<br>  cookFood(): void;<br>  deliverOrder(): void;<br>}</pre><h3>Better Design</h3><pre>interface Customer {<br>  placeOrder(): void;<br>}<br><br>interface Chef {<br>  cookFood(): void;<br>}<br>interface DeliveryPartner {<br>  deliverOrder(): void;<br>}</pre><h3>Takeaway</h3><p>Give people <strong>only the tools they actually use</strong>.</p><h3>D — Dependency Inversion Principle</h3><p><strong>Depend on ideas, not concrete things</strong></p><p><strong>Meaning in plain words</strong><br>High-level logic shouldn’t care about <strong>how</strong> things are done, only <strong>what</strong> is done.</p><p>You don’t care which brand of electricity powers your house. You care that the lights turn on.</p><h3>Bad Design</h3><pre>class OrderService {<br>  payment = new CardPayment();<br>}</pre><p>You are now married to card payments.</p><h3>Better Design</h3><pre>class OrderService {<br>  constructor(private payment: Payment) {}<br>}</pre><p>Now the payment type is injected.</p><h3>Takeaway</h3><p>Flexibility comes from not hard-coding choices.</p><h3>All SOLID Together (The Big Picture)</h3><p>Principle Real-life meaning. One job per person. Add features without breaking old ones. Don’t fake capabilities. No unnecessary responsibilities. Plug-and-play dependencies</p><h3>Why SOLID Matters in System Design</h3><p>Without SOLID:</p><ul><li>Features slow down</li><li>Bugs multiply</li><li>Developers fear touching code</li></ul><p>With SOLID:</p><ul><li>Code evolves calmly</li><li>Teams scale smoothly</li><li>Systems age gracefully</li></ul><p>SOLID isn’t about perfection. It’s about <strong>damage control at scale</strong>.</p><h3>Interview Gold Tip ✨</h3><p>When asked about SOLID, don’t recite definitions.</p><p>Say:</p><blockquote><em>“SOLID helps us design systems that grow without rewriting everything.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5712474ddfb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharding, Partitioning, Replication, Bucketing: Database Scaling Without the Headache]]></title>
            <link>https://medium.com/@rajpg16/sharding-partitioning-replication-bucketing-database-scaling-without-the-headache-17661171fab6?source=rss-5fa0993abbfb------2</link>
            <guid isPermaLink="false">https://medium.com/p/17661171fab6</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Rajneesh Shukla]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 18:38:21 GMT</pubDate>
            <atom:updated>2025-12-16T18:38:21.705Z</atom:updated>
            <content:encoded><![CDATA[<p>When an application is young, its database feels like a quiet café. A few customers, manageable orders, and everything works smoothly. Then growth hits. Suddenly, the café turns into a busy airport terminal and the single counter collapses under pressure.</p><p>This is where database scaling concepts enter the story. Words like <em>sharding</em>, <em>partitioning</em>, <em>replication</em>, and <em>bucketing</em> sound intimidating at first, but they are simply different ways of organizing data so systems don’t panic under success.</p><h3>Partitioning: Organizing a Giant Table into Smaller Pieces</h3><p>Partitioning is the art of <strong>splitting one large table into smaller, manageable parts</strong>, while keeping everything inside the same database.</p><p>Imagine a library where all books are piled in one room. Finding a book becomes slow. Partitioning is like adding rooms based on category or year. The books are still in the same building, just neatly separated.</p><h3>Example</h3><p>A users table with 100 million rows can be partitioned by year:</p><ul><li>users_2023</li><li>users_2024</li><li>users_2025</li></ul><p>When you query recent users, the database quietly ignores older partitions. Less scanning, faster results.</p><h3>Common Partitioning Strategies</h3><ul><li><strong>Range</strong>: dates, price ranges, age groups</li><li><strong>List</strong>: country, status values</li><li><strong>Hash</strong>: evenly distribute rows using a hash function</li></ul><h3>Key takeaway</h3><p>Partitioning improves performance <strong>without adding new machines</strong>. It’s a structural discipline, not distribution.</p><h3>Sharding: Distributing Data Across Multiple Databases</h3><p>Sharding goes a step further. Instead of splitting data inside one database, it <strong>distributes data across multiple databases or servers</strong>.</p><p>Think of it as opening multiple library branches across a city. Each branch holds only part of the collection.</p><h3>Example</h3><p>Users split by ID range:</p><ul><li>Shard 1: userId 1–1M</li><li>Shard 2: userId 1M–2M</li><li>Shard 3: userId 2M–3M</li></ul><p>Each shard lives on a separate machine with its own database.</p><h3>Why Sharding Matters</h3><ul><li>One machine has limits</li><li>Traffic grows faster than vertical scaling</li><li>Enables horizontal scaling</li></ul><h3>The tradeoff</h3><p>Sharding increases complexity. Routing logic, cross-shard queries, and rebalancing data need careful design.</p><h3>Key takeaway</h3><p>Sharding is about <strong>scaling out</strong>, not just optimizing.</p><h3>Partitioning vs Sharding (The Classic Confusion)</h3><p>This confusion appears in almost every interview.</p><ul><li>Partitioning splits data <strong>inside one database</strong></li><li>Sharding splits data <strong>across multiple databases</strong></li></ul><p>Partitioning organizes.<br>Sharding distributes.</p><h3>Replication: Copying Data for Safety and Speed</h3><p>Replication means <strong>keeping multiple copies of the same data</strong> in different places.</p><p>If sharding is about dividing work, replication is about <strong>backup and availability</strong>.</p><p>Imagine a popular book with multiple copies across shelves. Readers don’t queue behind one copy.</p><h3>Common Setup</h3><ul><li>One <strong>primary</strong> database for writes</li><li>Multiple <strong>replicas</strong> for reads</li></ul><p>Reads go to replicas. Writes go to the primary. Changes flow downstream.</p><h3>Why Replication is Critical</h3><ul><li>High availability</li><li>Faster reads</li><li>Disaster recovery</li></ul><p>If one database crashes, another steps in without drama.</p><h3>Key takeaway</h3><p>Replication increases reliability, not capacity.</p><h3>Bucketing: Hash-Based Grouping for Performance</h3><p>Bucketing groups rows into <strong>fixed buckets using a hash function</strong>.</p><p>It’s most common in analytics systems and data warehouses.</p><h3>Example</h3><p>Orders bucketed by userId:</p><ul><li>bucket_0 → userId % 4 = 0</li><li>bucket_1 → userId % 4 = 1</li><li>bucket_2 → userId % 4 = 2</li><li>bucket_3 → userId % 4 = 3</li></ul><p>Rows with the same key tend to land in the same bucket, which speeds up joins and aggregations.</p><h3>Partitioning vs Bucketing</h3><ul><li>Partitioning is logical and flexible</li><li>Bucketing is fixed and hash-driven</li></ul><p>They are often used together, not in competition.</p><h3>Key takeaway</h3><p>Bucketing optimizes <strong>query execution</strong>, especially at scale.</p><h3>How Real Systems Combine Everything</h3><p>Large-scale systems rarely rely on a single technique. They stack them.</p><p>A Netflix-scale system might look like this:</p><ul><li><strong>Sharding</strong> users by region</li><li><strong>Replication</strong> for each shard</li><li><strong>Partitioning</strong> events by date</li><li><strong>Bucketing</strong> logs by userId</li></ul><p>Each technique solves a different problem. Together, they keep systems calm under chaos.</p><h3>Final Mental Model</h3><p>If you remember nothing else, remember this:</p><ul><li>Partitioning: split tables</li><li>Sharding: split databases</li><li>Replication: copy data</li><li>Bucketing: hash-based grouping</li></ul><p>Scaling databases is not about one silver bullet. It’s about choosing the right combination as your system grows from a quiet café into a global airport.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17661171fab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>