<?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 Rahul Kalasuva on Medium]]></title>
        <description><![CDATA[Stories by Rahul Kalasuva on Medium]]></description>
        <link>https://medium.com/@kalasuvar67?source=rss-29fc34e625a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3MjQ2zw-WQZ_RzpI.</url>
            <title>Stories by Rahul Kalasuva on Medium</title>
            <link>https://medium.com/@kalasuvar67?source=rss-29fc34e625a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:10:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalasuvar67/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[Optimistic Concurrency Control]]></title>
            <link>https://medium.com/@kalasuvar67/optimistic-concurrency-control-525b6b31a1c6?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/525b6b31a1c6</guid>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 07:18:01 GMT</pubDate>
            <atom:updated>2026-02-10T07:22:32.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimistic Locking — A Simple Yet Powerful Way to Prevent Data Conflicts</h3><p>In modern applications, multiple users and services often interact with the same data at the same time. This raises a critical question:</p><blockquote><em>How do we prevent one user from accidentally overwriting another user’s changes?</em></blockquote><p>One elegant answer is <strong>Optimistic Locking.</strong></p><p>In this article, we will break down:</p><ul><li>What optimistic locking is</li><li>Why it is needed</li><li>How it works</li><li>How it looks in MongoDB</li><li>How it looks in Redis</li><li>A real HRMS example</li><li>When to use it</li></ul><p>Let’s dive in.</p><h3>The Problem: Lost Updates</h3><p>Imagine this scenario:</p><p>You and your colleague open the same document at the same time.</p><h3>Initial document in database:</h3><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;Nidhi&quot;,<br>  &quot;__v&quot;: 0<br>}</pre><p>Both of you see:</p><ul><li>Name = Nidhi</li><li>Version = 0</li></ul><h3>You change name to “Nidhi Shah”</h3><p>Database becomes:</p><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;Nidhi Shah&quot;,<br>  &quot;__v&quot;: 1<br>}</pre><h3>Your colleague changes name to “Nidhi Patel”</h3><p>If no protection exists, the final database becomes:</p><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;Nidhi Patel&quot;,<br>  &quot;__v&quot;: 2<br>}</pre><p>Your change is <strong>lost forever.</strong></p><p>This is called a <strong>write-write conflict</strong> or <strong>lost update problem.</strong></p><p>This is exactly what optimistic locking is designed to prevent.</p><h3>What is Optimistic Locking?</h3><p>Optimistic locking is a strategy where:</p><blockquote><em>You allow multiple users to read data simultaneously,<br>but before saving changes, you check whether the data has changed since they last read it.</em></blockquote><p>If the data has changed, you reject the update.</p><p>You are “optimistic” because you assume conflicts are rare.</p><h3>How Optimistic Locking Works (Conceptually)</h3><p>There are three steps:</p><ol><li><strong>Read the record + version</strong></li><li><strong>User edits data</strong></li><li><strong>Update only if version is unchanged</strong></li></ol><p>If version changed → reject update.</p><h3>Optimistic Locking in MongoDB (Mongoose)</h3><p>Mongoose automatically adds a field called __v (version key).</p><h3>Step 1 — User reads data</h3><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;Nidhi&quot;,<br>  &quot;__v&quot;: 0<br>}</pre><h3>Step 2 — User tries to update</h3><p>Backend query:</p><pre>await User.findOneAndUpdate(<br>  { _id: &quot;user123&quot;, __v: 0 },<br>  { name: &quot;Nidhi Shah&quot; }<br>);</pre><h3>Two outcomes:</h3><h4>Case 1 — No one else updated</h4><p>Update succeeds, and document becomes:</p><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;Nidhi Shah&quot;,<br>  &quot;__v&quot;: 1<br>}</pre><h4>Case 2 — Someone updated first</h4><p>Suppose another user already changed it:</p><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;Nidhi Patel&quot;,<br>  &quot;__v&quot;: 1<br>}</pre><p>Then this query:</p><pre>{ _id: &quot;user123&quot;, __v: 0 }</pre><p>matches <strong>zero documents</strong>, and Mongoose returns null.</p><p>Your API returns:</p><pre>409 Conflict — Please refresh and try again.</pre><p>No data is overwritten.</p><p>That is optimistic locking in action.</p><h3>Optimistic Locking in Redis (WATCH / MULTI / EXEC)</h3><p>Redis has a different but conceptually similar mechanism using WATCH.</p><p>Imagine a leave balance stored in Redis:</p><pre>SET leaveBalance:emp123 10</pre><p>Two services read it at the same time.</p><h3>Step 1 — Watch the key</h3><pre>WATCH leaveBalance:emp123</pre><h3>Step 2 — Read current value</h3><pre>GET leaveBalance:emp123  # returns 10</pre><h3>Step 3 — Start transaction</h3><pre>MULTI<br>SET leaveBalance:emp123 8</pre><h3>Step 4 — Commit</h3><pre>EXEC</pre><p>If another service changed the key meanwhile, EXEC returns nil — meaning conflict.</p><p>You retry the operation.</p><p>Redis does not use a version field like __v, but the idea is the same:</p><blockquote><em>“Only commit if nothing changed since I last read.”</em></blockquote><h3>Real HRMS Example — Leave Approval</h3><p>Consider a leave request with status workflow:</p><pre>PENDING → UNDER_REVIEW → APPROVED → PAID</pre><h3>Initial document:</h3><pre>{<br>  &quot;_id&quot;: &quot;leave123&quot;,<br>  &quot;status&quot;: &quot;PENDING&quot;,<br>  &quot;__v&quot;: 0<br>}</pre><p>Two managers open the same request.</p><h3>Manager A approves:</h3><pre>findOneAndUpdate(<br>  { _id: &quot;leave123&quot;, __v: 0 },<br>  { $set: { status: &quot;APPROVED&quot; } }<br>);</pre><p>DB becomes:</p><pre>{<br>  &quot;_id&quot;: &quot;leave123&quot;,<br>  &quot;status&quot;: &quot;APPROVED&quot;,<br>  &quot;__v&quot;: 1<br>}</pre><h3>Manager B tries to reject with old version:</h3><pre>findOneAndUpdate(<br>  { _id: &quot;leave123&quot;, __v: 0 },<br>  { $set: { status: &quot;REJECTED&quot; } }<br>);</pre><p>This fails → conflict detected → no overwrite.</p><h3>Optimistic Locking vs Atomic Operations</h3><p>People often confuse these two.</p><p>ConceptWhat it protectsAtomic operationDatabase consistencyOptimistic lockingUser edits &amp; concurrency</p><p>Example of atomic:</p><pre>db.accounts.updateOne(<br>  { _id },<br>  { $inc: { balance: -500 } }<br>);</pre><p>This is atomic — but it does NOT prevent two users from overwriting each other.</p><p>Optimistic locking is needed for that.</p><h3>When Should You Use Optimistic Locking?</h3><p>Use it when:</p><ul><li>Multiple users edit the same data</li><li>You care about preserving user changes</li><li>You are building enterprise systems like:</li><li>HRMS</li><li>CRM</li><li>ERP</li><li>CMS</li><li>Banking apps</li></ul><p>Do NOT use it when:</p><ul><li>You are just updating counters or logs</li><li>No one reads-modifies-writes the same record</li></ul><h3>Final Takeaway</h3><p>Optimistic locking is a simple but powerful pattern:</p><blockquote><em>It assumes conflicts are rare but protects you when they happen.</em></blockquote><p>In MongoDB → use __v<br>In Redis → use WATCH + MULTI/EXEC</p><p>And in real systems, combine it with business rules like status checks.</p><h3>Closing Line</h3><p>Optimistic locking is not about locking the database — it’s about respecting human decisions in a concurrent world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=525b6b31a1c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Phantom Token Pattern]]></title>
            <link>https://medium.com/@kalasuvar67/jwt-phantom-token-pattern-f0439179a398?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0439179a398</guid>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 15:19:50 GMT</pubDate>
            <atom:updated>2026-01-17T15:19:50.816Z</atom:updated>
            <content:encoded><![CDATA[<p>┌─────────────────────────────────────────────────────────────────────────────┐<br>│ PHANTOM TOKEN LIFECYCLE │<br>├─────────────────────────────────────────────────────────────────────────────┤<br>│ │<br>│ LOGIN │<br>│ ├── Auth Server creates JWT │<br>│ ├── Auth Server creates opaque token (random string) │<br>│ ├── Auth Server stores: Redis[opaque] = JWT │<br>│ └── Client receives: opaque token only │<br>│ │<br>│ API REQUEST │<br>│ ├── Client sends: Authorization: Bearer &lt;opaque&gt; │<br>│ ├── API Gateway calls: /introspect { token: opaque } │<br>│ ├── Auth Server returns: { jwt: &lt;real_jwt&gt; } │<br>│ ├── API Gateway forwards: Authorization: Bearer &lt;real_jwt&gt; │<br>│ └── Backend verifies: JWT locally (standard verification) │<br>│ │<br>│ LOGOUT │<br>│ ├── Client sends: POST /logout │<br>│ ├── Auth Server: DEL Redis[opaque] │<br>│ └── Next request: introspect returns { active: false } → 401 │<br>│ │<br>└─────────────────────────────────────────────────────────────────────────────┘</p><p>Never Forget to have iss (issuer ) and aud (audience) of the token</p><h3>Phase 1: Token Store (Redis)</h3><pre>// config/redis.js<br>const Redis = require(&#39;ioredis&#39;);<br>const redis = new Redis(process.env.REDIS_URL);<br>module.exports = redis;</pre><h4>Create Token Service</h4><pre>// services/tokenService.js<br>const crypto = require(&#39;crypto&#39;);<br>const redis = require(&#39;../config/redis&#39;);<br>const TOKEN_PREFIX = &#39;phantom:&#39;;<br>const TOKEN_TTL = 3600; // 1 hour<br>const tokenService = {<br>  // Generate opaque token, store JWT mapping<br>  async createPhantomToken(jwt, userId) {<br>    const opaqueToken = crypto.randomBytes(32).toString(&#39;hex&#39;);<br>    await redis.set(<br>      `${TOKEN_PREFIX}${opaqueToken}`, <br>      JSON.stringify({ jwt, userId }),<br>      &#39;EX&#39;, TOKEN_TTL<br>    );<br>    return opaqueToken;<br>  },<br>  // Introspect: Convert opaque → JWT<br>  async introspect(opaqueToken) {<br>    const data = await redis.get(`${TOKEN_PREFIX}${opaqueToken}`);<br>    if (!data) return null;<br>    return JSON.parse(data);<br>  },<br>  // Revoke token<br>  async revoke(opaqueToken) {<br>    await redis.del(`${TOKEN_PREFIX}${opaqueToken}`);<br>  }<br>};</pre><h3>Phase 2: Modify Login Flow</h3><pre>// Before: Return JWT directly<br>existedUser.accessToken = token;<br>// After: Return opaque token<br>const opaqueToken = await tokenService.createPhantomToken(token, existedUser._id);<br>existedUser.accessToken = opaqueToken;</pre><h3>Add Introspection Endpoint</h3><pre>// POST /auth/introspect<br>const introspect = async (req, res) =&gt; {<br>  const { token } = req.body;<br>  <br>  const data = await tokenService.introspect(token);<br>  if (!data) {<br>    return res.status(401).json({ active: false });<br>  }<br>  <br>  return res.json({ <br>    active: true, <br>    jwt: data.jwt  // Only for internal use<br>  });<br>};</pre><h3>API Gateway Setup (NGINX)</h3><pre># nginx.conf<br>location /api/ {<br>    # Call introspection endpoint<br>    auth_request /auth/introspect;<br>    auth_request_set $jwt $upstream_http_x_jwt;<br>    <br>    # Pass JWT to backend<br>    proxy_set_header Authorization &quot;Bearer $jwt&quot;;<br>    proxy_pass http://backend;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0439179a398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Losing Data: The Transactional Outbox Pattern in Node.js]]></title>
            <link>https://medium.com/@kalasuvar67/stop-losing-data-the-transactional-outbox-pattern-in-node-js-82044a935dbd?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/82044a935dbd</guid>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 10:02:55 GMT</pubDate>
            <atom:updated>2025-11-26T10:02:55.006Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve built a microservice. It works perfectly on your machine. You save a user to MongoDB, and then you send a “Welcome Email” event to RabbitMQ.</p><p>But one day, production logs show something terrifying: <strong>The user exists in the database, but the email was never sent.</strong></p><p>The RabbitMQ connection flickered for just 100ms. Or maybe the server restarted exactly after the database save but before the queue publish. The result? <strong>Data Inconsistency.</strong> You have “Ghost Data” — records that exist but failed to trigger the necessary downstream effects.</p><p>This is the <strong>“Dual Write Problem,”</strong> and today we are going to fix it using the industry-standard <strong>Transactional Outbox Pattern</strong>.</p><h3>The Problem: The “Naked” Publish</h3><p>Here is the code most of us write when we start:</p><pre>// ❌ The Naive Approach<br>async function createUser(req, res) {<br>  // Step 1: Save to DB (Success)<br>  const user = await UserModel.create(req.body); <br><br>  // --- THE DANGER ZONE ---<br>  // If the server crashes here, or RabbitMQ is down...<br>  // The user is saved, but the message is LOST FOREVER.<br>  <br>  // Step 2: Publish Event<br>  await rabbitMQ.publish(&#39;user_created&#39;, user); <br><br>  return res.json(user);<br>}</pre><p>If <strong>Step 1</strong> succeeds but <strong>Step 2</strong> fails, your system is broken. You cannot wrap this in a try/catch to fix a server crash—if the memory is gone, the retry logic is gone too.</p><h3>The Solution: The Transactional Outbox</h3><p>We need <strong>Atomicity</strong>. We need to guarantee that <strong>either BOTH happen, or NEITHER happens.</strong></p><p>We save the message to a local “Outbox” collection in the <strong>same transaction</strong> as the business data.<br>The Architecture</p><p><strong>The API:</strong> Saves the User and the Outbox message in one ACID transaction.<br><strong>The Database:</strong> Holds the data safely.<br><strong>The Relay (Worker):</strong> Asynchronously picks up messages from the Outbox table and pushes them to RabbitMQ.</p><h3>Step 1: The Outbox Model</h3><pre>// models/Outbox.js<br>const mongoose = require(&#39;mongoose&#39;);<br><br>const outboxSchema = new mongoose.Schema({<br>    topic: { type: String, required: true },<br>    payload: { type: Object, required: true },<br>    status: { <br>        type: String, <br>        enum: [&#39;PENDING&#39;, &#39;SENT&#39;, &#39;FAILED&#39;], <br>        default: &#39;PENDING&#39; <br>    },<br>    retries: { type: Number, default: 0 },<br>    lastError: { type: String }<br>}, { timestamps: true });<br><br>module.exports = mongoose.model(&#39;Outbox&#39;, outboxSchema);</pre><h3>Step 2: The Atomic Transaction</h3><pre>// controllers/UserController.js<br>const mongoose = require(&#39;mongoose&#39;);<br>const UserModel = require(&#39;../models/User&#39;);<br>const OutboxModel = require(&#39;../models/Outbox&#39;);<br><br>const registerUser = async (req, res) =&gt; {<br>    const session = await mongoose.startSession();<br>    session.startTransaction();<br><br>    try {<br>        // 1. Create the User (Pass the session!)<br>        const [user] = await UserModel.create([req.body], { session });<br><br>        // 2. Create the Intent to Send Message (Pass the session!)<br>        await OutboxModel.create([{<br>            topic: &#39;user_created&#39;,<br>            payload: { <br>                userId: user._id, <br>                email: user.email <br>            }<br>        }], { session });<br><br>        // 3. Commit - Both become visible instantly<br>        await session.commitTransaction();<br>        <br>        // Respond to user immediately (Don&#39;t wait for RabbitMQ)<br>        res.status(201).json(user);<br><br>    } catch (error) {<br>        // If anything fails, neither is saved. No ghost data.<br>        await session.abortTransaction();<br>        res.status(500).json({ error: error.message });<br>    } finally {<br>        session.endSession();<br>    }<br>};</pre><h3>Step 3: The “Hybrid” Relay Worker</h3><p>Now that the message is safely in the DB, we need to send it.</p><p>Should we use a <strong>Cron Job</strong>? (Reliable, but slow latency). Should we use <strong>Change Streams</strong>? (Fast, but fragile if connection drops).</p><p><strong>Pro Tip:</strong> Use <strong>Both</strong>. We call this the <strong>“Sprinter &amp; Sweeper”</strong> approach</p><pre>// workers/OutboxRelay.js<br>const OutboxModel = require(&#39;../models/Outbox&#39;);<br>const rabbitMQ = require(&#39;../utils/rabbitmq&#39;); <br>const cron = require(&#39;node-cron&#39;);<br><br>// 1. THE SPRINTER (Change Streams) - For Instant Speed<br>// Fires immediately when a document is inserted.<br>const listenForRealTimeChanges = () =&gt; {<br>    const stream = OutboxModel.watch([{ $match: { operationType: &#39;insert&#39; } }]);<br><br>    stream.on(&#39;change&#39;, async (change) =&gt; {<br>        const msg = change.fullDocument;<br>        try {<br>            await rabbitMQ.publish(msg.topic, msg.payload);<br>            await OutboxModel.updateOne({ _id: msg._id }, { status: &#39;SENT&#39; });<br>            console.log(`[Fast-Track] Sent: ${msg._id}`);<br>        } catch (err) {<br>            // If RabbitMQ is down, ignore it. The Cron will catch it.<br>            console.warn(`[Fast-Track] Failed: ${err.message}`);<br>        }<br>    });<br>};<br><br>// 2. THE SWEEPER (Cron Job) - For 100% Reliability<br>// Runs every 1 minute to catch anything the Sprinter missed.<br>cron.schedule(&#39;* * * * *&#39;, async () =&gt; {<br>    const pending = await OutboxModel.find({ status: &#39;PENDING&#39; }).limit(50);<br>    <br>    for (const msg of pending) {<br>        try {<br>            await rabbitMQ.publish(msg.topic, msg.payload);<br>            msg.status = &#39;SENT&#39;;<br>            await msg.save();<br>            console.log(`[Sweeper] Recovered &amp; Sent: ${msg._id}`);<br>        } catch (err) {<br>            msg.retries += 1;<br>            if (msg.retries &gt; 5) msg.status = &#39;FAILED&#39;;<br>            await msg.save();<br>        }<br>    }<br>});<br><br>// Start both<br>listenForRealTimeChanges();</pre><h3>Why This Is “Industry Standard”</h3><p>By implementing this pattern, you solve three massive problems:</p><p><strong>Guaranteed Delivery:</strong> Even if RabbitMQ is down for 5 hours, your API keeps accepting users. The Outbox fills up, and the worker drains it when the queue comes back online.<br><strong>Latency:</strong> Your user doesn’t wait for RabbitMQ connection handshakes. The API response is simply a database write (fast).<br><strong>Data Integrity:</strong> You eliminate the “Ghost Data” problem entirely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82044a935dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Pull Images from ECR without Login]]></title>
            <link>https://medium.com/@kalasuvar67/how-to-pull-images-from-ecr-without-login-f216b79d82f7?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f216b79d82f7</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 06:27:29 GMT</pubDate>
            <atom:updated>2025-11-05T06:27:29.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step 1: Attach an IAM Role to EC2 Instance</h3><p>EC2 → Select instance → <strong>Actions → Security → Modify IAM Role</strong></p><p>Attach a role with this policy:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ecr:GetAuthorizationToken&quot;,<br>        &quot;ecr:BatchCheckLayerAvailability&quot;,<br>        &quot;ecr:GetDownloadUrlForLayer&quot;,<br>        &quot;ecr:BatchGetImage&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    }<br>  ]<br>}</pre><p>✅ No access keys required<br> ✅ Permissions are short-lived and secure</p><h3>✅ Step 2: Install the Credential Helper</h3><pre>sudo apt-get update<br>sudo apt-get install -y amazon-ecr-credential-helper</pre><p>Verify:</p><pre>which docker-credential-ecr-login</pre><p>uld return a valid path, e.g.:</p><pre>/usr/bin/docker-credential-ecr-login</pre><h3>✅ Step 3: Configure Docker to Use It</h3><p>Create/edit:</p><pre>nano ~/.docker/config.json</pre><p>Add:</p><pre>{<br>  &quot;credHelpers&quot;: {<br>    &quot;123456789012.dkr.ecr.ap-south-1.amazonaws.com&quot;: &quot;ecr-login&quot;<br>  }<br>}</pre><p>Or wildcard for all ECR registries:</p><pre>{<br>  &quot;credHelpers&quot;: {<br>    &quot;ecr-login&quot;: &quot;ecr-login&quot;<br>  }<br>}</pre><p>Save &amp; exit (Ctrl+O, Enter, Ctrl+X)</p><h3>✅ Step 4: Pull Image — No Login Needed</h3><pre>docker pull 123456789012.dkr.ecr.ap-south-1.amazonaws.com/app:lates</pre><p>If IAM role + config is correct, it <strong>just works</strong>.</p><p>✅ No auth error<br> ✅ No need to run docker login<br> ✅ No credentials stored on disk</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f216b79d82f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOPS in JavaScript]]></title>
            <link>https://medium.com/@kalasuvar67/oops-in-javascript-06d542a8d161?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/06d542a8d161</guid>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 12:44:05 GMT</pubDate>
            <atom:updated>2024-07-01T12:44:05.640Z</atom:updated>
            <content:encoded><![CDATA[<p>I will delve deeper into how Object-Oriented Programming (OOP) works in JavaScript, exploring key concepts such as:</p><ul><li>Classes and Objects</li><li>Encapsulation</li><li>Inheritance</li><li>Polymorphism</li><li>Abstraction</li></ul><p>These fundamental principles are crucial for understanding JavaScript’s approach to OOP and how they facilitate building modular and reusable code structures</p><h3><strong>1. Class and Objects</strong></h3><blockquote>Class Defines Blueprint , Properties and Methods. It is used to Create instances or objects. Each instance has its own set of properties and can invoke its own methods. Classes typically have a constructor method that is called when an instance of the class is created (new Person(...)). It initializes the object&#39;s state.</blockquote><pre>class Person {<br>  constructor(name, age) {<br>    this.name = name;<br>    this.age = age;<br>  }<br><br>  introduce() {<br>    console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);<br>  }<br><br>}<br><br>const Person1 = new Person(&quot;Alice&quot;, 30);  // As a new is added to class a Seperat instance is created <br>const Person2 = new Person(&quot;Alice&quot;, 30);<br><br>console.log(Person1 === Person2); // false Because both Person1 and Person2 will create separate instances of Person<br><br>Person1.introduce();</pre><h3>2. Encapsulation</h3><blockquote><strong>Encapsulation</strong> refers to the practice of hiding the internal details of an object and exposing only the necessary information to the outside world.</blockquote><pre>class BankAccount {<br>  #balance; // Private Field<br><br>  constructor(initialBalance) {<br>    this.#balance = initialBalance;<br>  }<br><br>  deposit(amount) {<br>    this.#balance += amount;<br>    console.log(`Deposited: $${amount}. New balance: $${this.#balance}`);<br>  }<br><br>  withdraw(amount) {<br>    if (amount &gt; this.#balance) {<br>      console.log(&#39;Insufficient funds.&#39;);<br>    } else {<br>      this.#balance -= amount;<br>      console.log(`Withdrew: $${amount}. New balance: $${this.#balance}`);<br>    }<br>  }<br><br>  getBalance() {<br>    return this.#balance;<br>  }<br><br>}<br><br>const account = new BankAccount(1000);<br>account.deposit(500);<br>account.withdraw(200);<br><br>console.log(account.getBalance()); // Cannot access #balance directly</pre><h3>3. Inheritance</h3><blockquote>Here Create a base class Animal with properties name and age, and a method speak. Then create a subclass Dog that extends Animal and overrides the speak method.</blockquote><pre>class Animal {<br>  constructor(name, age) {<br>    this.name = name;<br>    this.age = age;<br>  }<br><br>  speak() {<br>    console.log(`${this.name} makes a sound.`);<br>  }<br>}<br><br>class Dog extends Animal {<br>  constructor(name, age, breed) {<br>    super(name, age); // This Means that call the Parent class Constructor<br>    this.breed = breed;<br>  }<br><br>  speak() {<br>    console.log(`${this.name} barks.`);<br>  }<br>}<br><br>const dog = new Dog(&quot;Buddy&quot;, 3, &quot;Golden Retriever&quot;);<br>dog.speak(); // Buddy barks.</pre><h3>4. Polymorphism</h3><blockquote>It allows methods to be overridden in subclasses to provide different implementations while still adhering to a common interface defined by the superclass. while both inheritance and polymorphism allow methods to be overridden, inheritance establishes a hierarchical relationship between classes for code reuse, while polymorphism enables flexibility in method implementation across related classes.</blockquote><pre>// Superclass<br>class Employee {<br>    constructor(name, salary) {<br>        console.log(name + &quot;: &quot; + salary)<br>        this.salary = salary;<br>    }<br><br>    // Method to calculate bonus (to be overridden)<br>    calculateBonus() {<br>        throw new Error(&#39;This method should be overridden by subclasses&#39;);<br>    }<br>}<br><br>// Subclasses<br>class Manager extends Employee {<br>    constructor(name, salary, bonusPercentage) {<br>        super(name, salary);   // Calls the superclass constructor of Employee<br>        this.bonusPercentage = bonusPercentage;<br>    }<br><br>    calculateBonus() {<br>        return this.salary * (this.bonusPercentage / 100);<br>    }<br>}<br><br>// Usage<br>const manager = new Manager(&#39;Alice&#39;, 80000, 15);<br>console.log(`${manager.name}&#39;s bonus: $${manager.calculateBonus()}`); // Output: Alice&#39;s bonus: $12000</pre><h3>4. Abstraction</h3><blockquote>Abstract Class: Vehicle is designed as an abstract class. Abstract classes cannot be instantiated directly (new Vehicle() throws an error), but they serve as templates or blueprints for other classes (Car and Motorcycle in this case).</blockquote><pre>class Vehicle {<br>  constructor(make, model) {<br>    if (this.constructor === Vehicle) {<br>      throw new Error(&quot;Cannot instantiate abstract class&quot;);<br>    }<br>    this.make = make;<br>    this.model = model;<br>  }<br><br>  startEngine() {<br>    throw new Error(&quot;This method should be overridden by subclasses&quot;);<br>  }<br>}<br><br>class Car extends Vehicle {<br>  startEngine() {<br>    console.log(`${this.make} ${this.model}&#39;s engine is starting...`);<br>  }<br>}<br><br>class Motorcycle extends Vehicle {<br>  startEngine() {<br>    console.log(`${this.make} ${this.model}&#39;s engine is starting...`);<br>  }<br>}<br><br>console.log(new Vehicle())<br><br>const car = new Car(&quot;Toyota&quot;, &quot;Corolla&quot;);<br>const motorcycle = new Motorcycle(&quot;Yamaha&quot;, &quot;MT-07&quot;);<br><br>car.startEngine(); // Toyota Corolla&#39;s engine is starting...<br>motorcycle.startEngine(); // Yamaha MT-07&#39;s engine is starting...</pre><p>This ends we have just scratched the surface it is still far in implementation in real world scenario Follow for upcoming Class based real world implementation.</p><p>Thanks for reading Please have a look to more such interesting posts</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06d542a8d161" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MultiThreading in Nodejs]]></title>
            <link>https://medium.com/@kalasuvar67/multithreading-in-nodejs-194d6f8daf29?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/194d6f8daf29</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Wed, 29 May 2024 06:45:15 GMT</pubDate>
            <atom:updated>2024-05-29T06:45:15.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Node.js introduced worker threads, which allow for multi-threading and enable the offloading of CPU-intensive tasks to separate threads.</p><h3>Worker Threads and Event Loops</h3><p>When you create a worker thread, Node.js spawns a new thread with its own V8 instance and event loop. This means each worker thread can independently handle asynchronous operations and I/O tasks, without blocking the main thread or other worker threads.</p><ul><li>Each worker thread has its own separate memory heap and execution context. This isolation ensures that variables and data in one thread do not interfere with those in another.</li><li>Communication between the main thread and worker threads is done through message passing using the postMessage and on(&#39;message&#39;) APIs. This avoids the complexities of shared memory and synchronization.</li></ul><p>Server.js</p><pre>const express = require(&quot;express&quot;);<br><br>const app = express();<br>const port = process.env.PORT || 5000;<br><br>// import worker<br>const { Worker } = require(&quot;worker_threads&quot;);<br><br>// Making 2 routes: normal and blocking<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  console.log(&quot;Hello&quot;);<br>  res.status(200).send(&quot;normal non-blocking page&quot;);<br>});<br><br>app.get(&quot;/blocking&quot;, async (req, res) =&gt; {<br>  console.log(&quot;Hello hi&quot;);<br><br>  // constructor a worker, where you pass the path of your worker file<br>  const worker = new Worker(&quot;./worker.js&quot;);<br><br>  // handle when worker thread sends a message to parent<br>  worker.on(&quot;message&quot;, (data) =&gt; {<br>    res.status(200).send(`fibonacci(45) is : ${data}`);<br>  });<br><br>  // handle when worker thread sends an error to parent<br>  worker.on(&quot;error&quot;, (error) =&gt; {<br>    res.status(404).send(`failed to perform: ${error}`);<br>  });<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(&quot;Learning multithreading on port &quot;, port);<br>});</pre><p>Worker.js</p><pre>const { parentPort } = require(&quot;worker_threads&quot;);<br><br>//move the function here<br>function fibonacci(n) {<br>  if (n &lt;= 1) return n;<br>  return fibonacci(n - 1) + fibonacci(n - 2);<br>}<br>const result = fibonacci(45);<br><br>// pass the result to parent thread<br>parentPort.postMessage(result)</pre><p>This server would be Non-Blocking as the CPU Intensive Task is Offloaded to Worker Thread</p><p>Worker Thread will be CPU but it will be ready to run other CPU intensive concurrently</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=194d6f8daf29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling in Nodejs]]></title>
            <link>https://medium.com/@kalasuvar67/error-handling-in-nodejs-be5157ad8f27?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5157ad8f27</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Wed, 01 May 2024 09:08:45 GMT</pubDate>
            <atom:updated>2024-05-01T09:08:45.949Z</atom:updated>
            <content:encoded><![CDATA[<p>In Node.js, middleware is commonly used for handling errors in web applications. Middleware functions in Node.js are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Here&#39;s how you can handle errors using middleware in a Node.js application:</p><p>Create an Error Handling Middleware</p><pre>import { Request, Response, NextFunction } from &quot;express&quot;;<br>import { HttpError } from &quot;http-errors&quot;;<br>import { config } from &quot;../config/config&quot;;<br><br>const globalErrorHandler = (<br>  err: HttpError,<br>  req: Request,<br>  res: Response,<br>  next: NextFunction<br>) =&gt; {<br>  const statusCode = err.statusCode || 500;<br><br>  return res.status(statusCode).json({<br>    message: err.message,<br>    errorStack: config.env === &quot;development&quot; ? err.stack : &quot;&quot;,<br>  });<br>};<br><br>export default globalErrorHandler;</pre><p>Use the Error Handling Middleware:</p><p>First we will initialise it in app.ts file or main file</p><pre>// Global error handler<br>app.use(globalErrorHandler);</pre><p>Then we can use in any Controller or config files following is the example usage of middleware in controller</p><pre>const CreateMyRestaurent = async (req: Request, res: Response , next : NextFunction) =&gt; {<br>    try {<br>        const existingRestaurant = await Restaurant.findOne({ user: req.userId });<br><br>        if (existingRestaurant) {<br>            return res<br>                .status(409)  // conficlit <br>                .json({ message: &quot;User restaurant already exists&quot; });<br>        }<br><br>        const image = req.file as Express.Multer.File;<br><br>    } catch (error) {<br>        console.log(error);<br>        res.status(500).json({ message: &quot;Something went wrong&quot; })<br>        return next(createHttpError(500, &quot;Something went wrong&quot;));    <br><br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5157ad8f27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Keep-Alive” header]]></title>
            <link>https://medium.com/@kalasuvar67/keep-alive-header-2df66b9ad1cf?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df66b9ad1cf</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 11:08:06 GMT</pubDate>
            <atom:updated>2024-04-16T11:08:06.044Z</atom:updated>
            <content:encoded><![CDATA[<pre>// Middleware to set Keep-Alive headers for all responses<br>app.use((req, res, next) =&gt; {<br>  res.setHeader(&#39;Connection&#39;, &#39;keep-alive&#39;);<br>  res.setHeader(&#39;Keep-Alive&#39;, &#39;timeout=5, max=1000&#39;);<br>  next();<br>});</pre><p>HTTP Keep-Alive: If HTTP Keep-Alive is enabled on the server, the TCP connection established for the first request (/app/users) may be kept alive and reused for subsequent requests (/app/projects/getprojects). This reuse of the existing TCP connection can help reduce latency and overhead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df66b9ad1cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Stepper Machine Coding Round]]></title>
            <link>https://medium.com/@kalasuvar67/react-custom-stepper-machine-coding-round-aa834b98b7aa?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa834b98b7aa</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 11:36:54 GMT</pubDate>
            <atom:updated>2024-02-13T11:36:54.103Z</atom:updated>
            <content:encoded><![CDATA[<p>We will try to build a Custom Stepper from start to end with custom logic .<br>please find the below link for reference <a href="https://77nczz.csb.app/">https://77nczz.csb.app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIp8WfFMZV47hKsTSRHrKg.png" /></figure><p>We will start with a stepper configuration which includes the name and the full Component for which ever step is active</p><pre>  const CheckoutSteps = [<br>    {<br>      name: &quot;Customer Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Info&lt;/div&gt;,<br>    },<br>    {<br>      name: &quot;Shipping Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Shipping&lt;/div&gt;,<br>    },<br>    {<br>      name: &quot;Payment Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Complete Payment&lt;/div&gt;,<br>    },<br>    {<br>      name: &quot;Delivery Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Delivery&lt;/div&gt;,<br>    },<br>  ];</pre><p>App.js</p><pre>import CheckoutStepper from &quot;../CheckoutStepper&quot;;<br>import &quot;./styles.css&quot;;<br><br>export default function App() {<br>  const CheckoutSteps = [<br>    {<br>      name: &quot;Customer Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Info&lt;/div&gt;,<br>    },<br>    {<br>      name: &quot;Shipping Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Shipping&lt;/div&gt;,<br>    },<br>    {<br>      name: &quot;Payment Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Complete Payment&lt;/div&gt;,<br>    },<br>    {<br>      name: &quot;Delivery Info&quot;,<br>      Component: () =&gt; &lt;div&gt;Delivery&lt;/div&gt;,<br>    },<br>  ];<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      Checkout<br>      &lt;CheckoutStepper config={CheckoutSteps} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>checkoutStepper.js</p><pre>import { useRef, useState, useEffect } from &quot;react&quot;;<br><br>const CheckoutStepper = ({ config }) =&gt; {<br>  let i = useRef(0);<br>  const [currentstep, setCurrentStep] = useState(1);<br>  const [isCompleted, setIsCompleted] = useState(false);<br>  const [margin, setMargin] = useState({<br>    marginLeft: 0,<br>    marginRight: 0,<br>  });<br>  const stepRef = useRef([]);<br>  if (!config.length) {<br>    return &lt;&gt;&lt;/&gt;;<br>  }<br><br>  useEffect(() =&gt; {<br>    setMargin({<br>      marginLeft: stepRef.current[0].offsetWidth / 2,<br>      marginRight: stepRef.current[config.length - 1].offsetWidth / 2,<br>    });<br>    console.log(margin);<br>  }, [stepRef]);<br><br>  const ActiveComponent = () =&gt; {<br>    return config[currentstep - 1]?.Component();<br>  };<br><br>  const handleNext = () =&gt; {<br>    setCurrentStep((prevStep) =&gt; {<br>      if (prevStep === config.length) {<br>        setIsCompleted(true);<br>        return prevStep;<br>      } else {<br>        return prevStep + 1;<br>      }<br>    });<br>  };<br><br>  const calculateProgress = () =&gt; {<br>    return ((currentstep - 1) / (config.length - 1)) * 100;<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;stepper&quot;&gt;<br>        {config.map((step, index) =&gt; {<br>          return (<br>            &lt;div<br>              key={step.name}<br>              ref={(el) =&gt; (stepRef.current[index] = el)}<br>              className={`step ${<br>                currentstep &gt; index + 1 || isCompleted ? &quot;complete&quot; : &quot;&quot;<br>              } ${currentstep === index + 1 ? &quot;active&quot; : &quot;&quot;}`}<br>            &gt;<br>              &lt;div className=&quot;step-number&quot;&gt;<br>                {currentstep &gt; index + 1 || isCompleted ? (<br>                  &lt;span&gt;&amp;#10003;&lt;/span&gt;<br>                ) : (<br>                  index + 1<br>                )}<br>              &lt;/div&gt;<br>              &lt;div className=&quot;step-name&quot;&gt;{step.name}&lt;/div&gt;<br>            &lt;/div&gt;<br>          );<br>        })}<br>        &lt;div<br>          className=&quot;progress-bar&quot;<br>          style={{<br>            width: `calc(100% - ${margin.marginLeft + margin.marginRight}px)`,<br>            marginLeft: `${margin.marginLeft}px`,<br>            marginRight: `${margin.marginRight}px`,<br>          }}<br>        &gt;<br>          &lt;div<br>            className=&quot;progress&quot;<br>            style={{ width: `${calculateProgress()}%` }}<br>          &gt;<br>            {&quot; &quot;}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;ActiveComponent /&gt;<br>      &lt;/div&gt;<br>      {!isCompleted &amp;&amp; (<br>        &lt;button onClick={handleNext}&gt;<br>          {currentstep === config.length ? &quot;Finish&quot; : &quot;Next&quot;}<br>        &lt;/button&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>};<br><br>export default CheckoutStepper;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa834b98b7aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MakeMyTrip Frontend Machine Coding Interview]]></title>
            <link>https://medium.com/@kalasuvar67/makemytrip-frontend-machine-coding-interview-0134f0261d6c?source=rss-29fc34e625a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0134f0261d6c</guid>
            <dc:creator><![CDATA[Rahul Kalasuva]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 11:27:59 GMT</pubDate>
            <atom:updated>2024-02-13T11:27:59.038Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Problem Statement</li></ol><p>Create a UI and functionality that looks exactly like shown in this <a href="https://7m951t.csb.app/">Link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*Qyx_i4uRU8sla3uUtPJp4g.png" /></figure><pre>import { useEffect, useRef, useState } from &quot;react&quot;;<br>import &quot;./styles.css&quot;;<br><br>export default function App() {<br>  const box_view = [true, true, true, true, false, false, true, true, true];<br>  const boxRef = useRef([]);<br>  let indexrunning = 0;<br>  const [sequence, setSequence] = useState([]);<br><br>  const handleChange = (index) =&gt; {<br>    boxRef.current[index].style.backgroundColor = &quot;green&quot;;<br>    setSequence((prevSequence) =&gt; [...prevSequence, boxRef.current[index]]);<br>  };<br><br>  useEffect(() =&gt; {<br>    if (sequence.length === box_view.filter((ele) =&gt; ele === true).length) {<br>      const reverse = setInterval(() =&gt; {<br>        if (sequence.length - 1 === indexrunning) {<br>          clearInterval(reverse);<br>        }<br>        sequence[indexrunning].style.backgroundColor = &quot;white&quot;;<br>        indexrunning++;<br>      }, 1000);<br><br>      return () =&gt; {<br>        setSequence([]);<br>        boxRef.current = [];<br>        indexrunning = 0;<br>      };<br>    }<br>  }, [sequence]);<br><br>  return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      {box_view.map((ele, index) =&gt; {<br>        return (<br>          &lt;&gt;<br>            &lt;div<br>              key={index}<br>              className=&quot;box&quot;<br>              ref={(el) =&gt; (boxRef.current[index] = el)}<br>              style={{<br>                border: ele ? &quot;1px solid black&quot; : &quot;1px solid transparent&quot;,<br>                pointerEvents: ele ? &quot;auto&quot; : &quot;none&quot;,<br>              }}<br>              onClick={() =&gt; handleChange(index)}<br>            &gt;&lt;/div&gt;<br>          &lt;/&gt;<br>        );<br>      })}<br>    &lt;/div&gt;<br>  );<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0134f0261d6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>