<?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 Ekata Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Ekata Agrawal on Medium]]></description>
        <link>https://medium.com/@ekatakumari207?source=rss-264f8034e395------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zPDObMQgy2xmiv5-jLLpJA.jpeg</url>
            <title>Stories by Ekata Agrawal on Medium</title>
            <link>https://medium.com/@ekatakumari207?source=rss-264f8034e395------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:43:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ekatakumari207/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[ Caching Explained: Strategies, Trade-offs, and Real-World Edge Cases]]></title>
            <link>https://medium.com/@ekatakumari207/caching-explained-strategies-trade-offs-and-real-world-edge-cases-ea4f343d95c9?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea4f343d95c9</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 10:51:33 GMT</pubDate>
            <atom:updated>2026-07-25T10:51:33.106Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>🔍 What Is Caching?</strong></p><p><strong>Caching</strong> is storing a copy of data in a faster-access layer so future requests can be served without repeating expensive work.</p><ul><li>🐢 <strong>Without cache:</strong> Request → Database → Compute → Response (slow, every single time)</li><li>⚡ <strong>With cache:</strong> Request → Cache (hit!) → Response (fast) — only fall back to the database on a miss</li></ul><p>🌎 <strong>Where Caching Lives (Layers)</strong></p><p>Caching isn’t one single thing — it exists at almost every layer of a system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ytF--vzUvBQrAdTN2ikUA.png" /></figure><p><strong>🧩 Caching Strategies</strong></p><p>1️⃣ <strong>Cache-Aside (Lazy Loading) </strong>🦥<br>The app check the cache first. On a miss it fetches from the database and then store it in the cache.<br>Request → Check Cache<br> ├── Hit → Return cached data ✅<br> └── Miss → Fetch from DB → Store in cache → Return data</p><p>🌎<strong>Real World Example</strong> :A Product page on a ecommerce site. First visitor trigger a DB fetch; every visitor after that gets the cached version.</p><p>⚠️<strong>Edge case</strong></p><blockquote><em>Cache miss stampede(also called “</em><strong><em>thundering herd</em></strong><em>”) → It happens when a popular cache entry is expires or is missing and huge number of requests arrive for it at almost the same instant -so instead of one request going to the database,<br>thousands do all at once.</em></blockquote><h4><strong>Why it happens:</strong></h4><ol><li>A cached item (say, a trending product page) has a TTL of 5 minutes.</li><li>At the exact moment it expires, 10,000 users are actively requesting that same page.</li><li>Since the cache is now empty for that key, <strong>all 10,000 requests see a cache miss simultaneously.</strong></li><li>Every single one of them turns around and hits the database at the same time, asking for the same data.</li><li>The database — which was only ever supposed to handle occasional cache-refill traffic — suddenly gets slammed with 10,000 identical queries in the same second, and can slow down or crash.</li></ol><p><strong>How it fixed</strong></p><p>🔒 <strong>Locking / request coalescing</strong></p><p>only the First request that misses is allowed to query the databases, every other request for that same key wait for that one result and reuse it.</p><p>⏳ <strong>Jittered TTLs</strong></p><p>instead of every cache entry expiring at exactly 5:00 minutes, add a small random offset (4:45–5:15) so keys don’t all expire in the same instant.</p><p>🔄 <strong>Background/early refresh</strong></p><p>refresh the cache slightly <em>before</em> it actually expires (e.g., at 90% of TTL), so there’s never a moment where the cache is fully empty for that key.</p><p><strong>2️⃣ Read-Through 📖</strong></p><p>similar to cache-aside but , cache itself is responsible for fetching from a DB on a miss — the app never talk the DB directly.</p><p>App → Cache<br> ├── Has data? → Return it ✅<br> └── Missing? → Cache fetches from DB itself → stores it → returns it to App</p><p>So from the app’s point of view, it always just asks the cache, and the cache handles everything behind the scenes.</p><p>🌎<strong>Real World Example</strong></p><p>AWS ElastiCache in read-through mode sitting in front of RDS means:</p><ul><li>Your application only ever queries ElastiCache (Redis/Memcached).</li><li>If ElastiCache has the data cached, it returns it instantly.</li><li>If not, ElastiCache itself goes and pulls the data from RDS (the actual database), caches it, and hands it back — your application code never had to write any “check DB” logic at all.</li></ul><p>This is nice because it centralizes the caching logic in one place instead of scattering “check cache, then check DB” code across every part of your app</p><p><strong>⚠️ Edge case:</strong></p><p>Here’s the catch:<strong> the cache is now a middleman that depends entirely on the database being reachable</strong>.</p><p>If Database goes down or becomes unreachable:</p><ul><li>The cache still works fine for anything it <em>already has</em> cached.</li><li>But for any <strong>cache miss</strong>, the cache tries to “read through” to the database — and there’s nothing there to read from. 💥</li></ul><p>Without a plan for this, your app doesn’t just get a slow response — it can get a hard failure or a cascading crash, because the request that started at your app, went to the cache, tried to reach the DB, and failed, might now bubble an error all the way back up.</p><p><strong>The two safety nets mentioned:</strong></p><ol><li><strong>Serve stale data</strong> — if the cache <em>used to</em> have this data (even if it technically expired), serve the old value anyway rather than nothing. Better to show a slightly outdated product price than a broken page.</li><li><strong>Friendly error / graceful degradation</strong> — if there’s truly nothing cached and the DB is unreachable, return a clean “please try again shortly” instead of an unhandled exception crashing the request.</li></ol><h4><strong>3️⃣ Write-Through ✍️</strong></h4><p>Every write goes to the cache <strong>and</strong> the database at the same time (synchronously).</p><p>App writes new data<br> ├── Write to Cache ⚡<br> └── Write to DB 🗄️<br> (both must happen before the write is considered “complete”)<br>Compare this to the earlier patterns where the cache only gets filled on a <em>read</em>. Here, the cache gets filled the moment data is <em>written</em> — so it’s never out of date</p><h4>🌎Real-world example</h4><p><strong>Banking balance updates</strong> are a perfect example. If you transfer money and your balance updates in the database but the cache still shows the old number — even for a few seconds — that’s a real problem. Someone could see an outdated balance and make a decision based on wrong information (like thinking they have more money than they actually do).</p><p>So for banking, it’s worth the extra effort to keep cache and database perfectly in sync on every single write.</p><p><strong>The pro and con, explained</strong></p><p>✅ <strong>Pro — cache is never stale:</strong> Since every write updates both places immediately, whenever someone <em>reads</em> the data next, the cache is guaranteed to be correct. No waiting, no guessing.</p><p>⚠️ <strong>Con — writes get slower:</strong> Now every write has to succeed in <em>two</em> places instead of one. If the database takes 50ms and the cache takes 5ms, your write now takes at least 50ms (the slower one) — instead of just relying on one system.<br>The edge case, explained simply</p><p>Here’s the scary part: <strong>what if one write succeeds and the other fails?</strong></p><p>Example:</p><ul><li>✅ Cache write succeeds (balance updated to ₹5,000 in cache)</li><li>❌ DB write fails (still shows ₹4,000 in the actual database)</li></ul><p>Now your cache and database <strong>disagree</strong> with each other. Anyone reading from the cache sees ₹5,000, but the “real” source of truth (the DB) still says ₹4,000. That’s a dangerous inconsistency — especially in banking.</p><p>🚀<strong>How it fixed</strong></p><p><strong>Treat the database as the “boss” (source of truth)</strong></p><ul><li>Write to the <strong>database first</strong>.</li><li>If that succeeds, then try to write to the cache.</li><li>If the cache write happens to fail, don’t panic — just <strong>delete (invalidate) that cache key</strong> instead of leaving it wrong.</li><li>Next time someone reads that key, since it’s missing from cache, it’ll simply re-fetch the correct value from the database.</li></ul><p>This way, the cache can only ever be <strong>missing</strong> data (safe) — never <strong>wrong</strong> data (dangerous). A missing cache entry just causes one slightly slower read. A wrong cache entry could cause a real, harmful mistake.</p><h4><strong>5️⃣ Write-Around 🔄</strong></h4><p>This one flips the order from write-through. Instead of writing to the cache <strong>and</strong> the database at the same time, you write to the cache <strong>first</strong>, tell the user “done” immediately, and quietly update the database <strong>later, in the background</strong></p><p>App writes new data<br> └── Write to Cache ⚡ (instant — user gets response now)<br> ↓ (later, in a batch, asynchronously)<br> Write to DB 🗄️ (happens on its own schedule)</p><p>🌎<strong>Real-world example, explained</strong></p><p><strong>Likes and view counts</strong> on a social media post are a great fit. If a post has 45,231 likes and someone likes it, does it <em>really</em> matter if the database says 45,231 for another 2 seconds while the cache already says 45,232? Not really — nobody’s checking that precisely, and it’s not a critical piece of financial or safety data.</p><p>Because of that, you can let thousands of “like” events pile up in the cache, and then flush them to the database in one efficient <strong>batch</strong> (say, every few seconds) instead of hitting the database on every single click.</p><p><strong>The pro and con, explained</strong></p><p>✅ <strong>Pro — writes are extremely fast:</strong> The user never waits on the database. And instead of writing to the database 10,000 times for 10,000 likes, you can combine them into one batched write (“add 10,000 to this counter”), which is far more efficient.</p><p>⚠️ <strong>Con — risk of losing data:</strong> Since the database hasn’t been updated yet, all that “pending” data is sitting <em>only</em> in the cache, waiting to be flushed. If something happens to the cache before that flush happens… it’s just gone. The database never finds out those events occurred.</p><p><strong>⚠️ Edge case:</strong></p><p>Imagine 5,000 “like” events happened in the last few seconds. They’re sitting in Redis’s memory, waiting for the next scheduled batch flush to the database.</p><p>Then: 💥 <strong>the power goes out</strong>, or the Redis process crashes.</p><p>Since Redis normally keeps data in memory (RAM), and RAM is wiped when power is lost, <strong>all 5,000 unflushed likes disappear permanently</strong> — the database never receives them, and there’s no way to recover them.</p><p>🚀<strong>How it fixed</strong></p><p><strong>Option 1 — Persistence:</strong> Configure Redis to regularly save its in-memory data to disk using:</p><ul><li><strong>AOF (Append Only File):</strong> logs every write command as it happens, so it can be replayed after a crash.</li><li><strong>RDB snapshots:</strong> periodic full backups of memory to disk.</li></ul><p>This way, even if power is lost, Redis can reload from disk when it restarts and recover most (or all) of the pending writes.</p><p><strong>Option 2 — Use a durable queue as a buffer (like Kafka):</strong> Instead of the “pending write” living only in Redis’s memory, first write the event into Kafka (which is built to durably store messages on disk across multiple machines). Then a background worker reads from Kafka and updates the database. Even if Redis crashes, Kafka still has the event safely stored, so nothing is lost.</p><h4>5️⃣ Write-Around 🔄</h4><p>Write directly to the DB, skip the cache. Cache only gets populated on a subsequent <em>read.</em></p><p>App writes new data<br> └── Write to DB only 🗄️ (cache is completely skipped)</p><p>Later, when someone reads that data…<br> └── Cache miss (nothing there yet) → Fetch from DB → Store in cache →Return</p><p><strong>Why do this at all?</strong></p><p>Because <strong>caching everything you write is wasteful if most of it never gets read again.</strong> Populating the cache costs memory and a bit of time. If you’re writing a huge amount of data that’s rarely re-accessed right away, why bother caching it immediately? Just write it to the database, and let the cache fill in naturally <em>only</em> for the data that actually turns out to be popular.</p><p>🌎<strong>Real World Example</strong></p><p><strong>Bulk data imports or logs</strong> are the classic case. Imagine you’re importing 2 million rows of historical order data, or writing application logs every second. Nobody is going to immediately turn around and read log entry #1,432,991 right after it’s written. So there’s no point caching it — that would just fill up your limited cache space with data nobody asks for, pushing out things that actually are frequently read (this connects back to “cache pollution” from earlier).</p><p>Write-around avoids that problem: bulk-written data just sits quietly in the database, uncached, until (and unless) someone actually requests it.</p><p><strong>⚠️ Edge case:</strong></p><p>Here’s where it gets tricky: <strong>what if someone writes data and then immediately tries to read that exact same thing?</strong></p><p>This is an extremely common flow in real apps:</p><ol><li>User clicks “Place Order” ✍️</li><li>App writes the new order to the database (write-around — cache is skipped)</li><li>App immediately redirects the user to /orders/12345 — the order&#39;s detail page</li><li>That page tries to <strong>read</strong> order #12345</li></ol><p>Since the write never touched the cache, that read is a <strong>guaranteed cache miss</strong> — even though the data is brand new and was <em>just</em> created a second ago. The system has to go all the way to the database to fetch something it literally just wrote moments earlier.</p><blockquote><strong>Why this feels like a bug:</strong> From the user’s perspective, they just did something (placed an order), and now the very next screen feels slightly slower to load than usual. If you didn’t know about write-around, you might think, “Wait, why is loading a page for data that was <em>just written</em> somehow slow? Shouldn’t this be the freshest, easiest thing to fetch?” It’s counterintuitive — but it’s expected behavior for this caching strategy, not an actual bug.</blockquote><h4>Here’s a practical breakdown of when to use each strategy, with concrete examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dR7jUD5qUooW32nGY2S4-w.png" /></figure><h4>Walking through it by scenario</h4><p><strong>🛒 E-commerce product catalog</strong> → <strong>Cache-Aside</strong><br> Millions of products exist, but only a small % are actively browsed at any moment. You don’t want to pre-cache everything — just cache products as people actually view them.</p><p><strong>🏦 Banking app showing account balance</strong> → <strong>Write-Through</strong><br> The moment money moves, the balance shown to the user must be correct immediately. You can’t risk the cache saying ₹5,000 when the DB says ₹4,500 for even a few seconds.</p><p><strong>❤️ Instagram/YouTube like &amp; view counters</strong> → <strong>Write-Behind</strong><br> Millions of likes per minute. Writing to the DB on every single like would be brutal for performance. Batch 10,000 likes into one DB update every few seconds — nobody notices a 2-second lag on a like counter.</p><p><strong>📊 Managed cache in front of a reporting database</strong> → <strong>Read-Through</strong><br> You want your app code to just say “give me this data” without knowing or caring whether it’s in cache or DB — the caching layer (like ElastiCache) handles that complexity for you.</p><p><strong>📝 Application logs / bulk CSV import of 5 million historical orders</strong> → <strong>Write-Around</strong><br> These records are written once and almost never read again immediately. Caching them at write time would just evict genuinely popular data from your limited cache space.</p><h4>The one-line decision rule</h4><ul><li>Needs to be instantly correct → <strong>Write-Through</strong></li><li>Can tolerate a short delay, high write volume → <strong>Write-Behind</strong></li><li>Read-heavy, unpredictable access → <strong>Cache-Aside</strong> (or <strong>Read-Through</strong> if you want the cache to own the fetch logic)</li><li>Written once, rarely re-read soon → <strong>Write-Around</strong></li></ul><h4>🧹 Eviction Policies — What to Throw Away When Full</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1S1uQsic9INH4TPzSAaZg.png" /></figure><h4><strong>⚠️ Edge case:</strong></h4><p><strong>What “Cache Pollution” means</strong></p><p>Cache pollution happens when data that’s <strong>not actually useful to keep</strong> ends up filling up your cache and pushing out data that <strong>is</strong> genuinely useful — simply because of how the eviction policy interprets “recently used.”</p><p><strong>Walking through the scenario</strong></p><p>Let’s say you’re running <strong>LRU (Least Recently Used)</strong> eviction, which is the most common default. LRU’s rule is simple: <em>“whatever hasn’t been touched in the longest time gets evicted first.”</em> The assumption baked into this rule is: <strong>if something was accessed recently, it’s probably going to be accessed again soon.</strong> That assumption is usually true — but not always.</p><p>Now imagine this happens:<br>Your cache is nicely filled with <strong>hot, frequently-requested data</strong> — popular product pages, trending posts, active user sessions. This is exactly what should be in cache.</p><ul><li>A <strong>one-time batch job</strong> kicks off — maybe a nightly report, a data migration, or an analytics scan — that reads through <strong>millions of records, one after another, sequentially.</strong></li><li>As that job touches each record, LRU sees each one as “just accessed” and marks it as <strong>recently used</strong>.</li><li>Since the cache has limited space, LRU starts evicting the <strong>oldest-touched entries to make room</strong> — and because the batch job just touched millions of <em>new</em> entries, it ends up <strong>kicking out your actually-popular, actually-hot data</strong> to make space for records that will likely never be looked at again.</li><li>Once the batch job finishes, your cache is now full of “cold” data from a one-time scan, and all your real, frequently-requested data has to be re-fetched from the database from scratch.</li><li><strong>This is exactly backwards from what you want.</strong> The data most likely to be reused (product pages, sessions) got thrown out, while the data least likely to ever be reused (a one-time scan) is sitting in the cache.</li></ul><p><strong>Why this is called “pollution”</strong></p><p>Because the cache gets filled — <em>polluted</em> — with data that provides no future value, purely because of a blind spot in how LRU defines “recently used.” LRU tracks <strong>recency</strong>, not <strong>actual usefulness</strong> — and a sequential batch scan looks recent to the algorithm even though it’s a one-off event.</p><h4>🚀<strong>How it fixed</strong></h4><p><strong>Option 1 — LRU-K</strong><br> Regular LRU only remembers <em>the last time</em> something was accessed. <strong>LRU-K</strong> (commonly LRU-2) instead tracks the <strong>last K accesses</strong> of an item, and prioritizes eviction based on that history. A batch job touches each record exactly <strong>once</strong> — so under LRU-2, those single-touch records look far less “important” than something that’s been accessed <em>multiple times</em> by real user traffic. This naturally protects genuinely hot data from being wiped out by a one-time sequential scan.</p><p><strong>Option 2 — Segmented / scan-resistant cache pools</strong><br> Instead of one big shared cache, you split it into separate pools — for example:</p><ul><li>A pool for regular application traffic (your real hot data)</li><li>A separate, smaller pool specifically for bulk/batch scan operations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea4f343d95c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolithic Architecture — The Foundation of Traditional Software Design]]></title>
            <link>https://medium.com/@ekatakumari207/monolithic-architecture-the-foundation-of-traditional-software-design-3d3c9edb75f9?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d3c9edb75f9</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 15:29:58 GMT</pubDate>
            <atom:updated>2025-11-20T15:29:58.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀Monolithic Architecture — The Foundation of Traditional Software Design</h3><p>A <strong>monolithic architecture</strong> is a software design pattern where <strong>the entire application is built as one single, unified unit</strong>.</p><p>This means:</p><ul><li>One codebase</li><li>One build</li><li>One deployment</li><li>One database (usually)</li><li>One runtime environment</li></ul><p>All features — authentication, products, orders, payments, notifications, admin — live inside <strong>one big application</strong>.</p><p>🧧<strong>Full Monolithic Application (Frontend + Backend Together)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hre-czakfhSGVtj38nGJpg.png" /></figure><p>🟩 <strong>How Backend Monolithic Apps Are Structured</strong></p><p>A typical monolith has 3 layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCPECsrNhwPuy3CcAzOW0g.png" /></figure><p>All these are packaged in <strong>one application</strong>.</p><h4>✅ Example of a Monolithic Application (E-Commerce App)</h4><p>Think of a simple online store built as <strong>one single application</strong>.</p><p>Inside the monolith, you have folders like:</p><pre>/src<br> ├── controllers/<br> ├── services/<br> ├── models/<br> ├── views/<br> ├── utils/<br> ├── routes/<br> └── config/</pre><p>All features live inside these folders.</p><p>Let’s map them to the <strong>3 monolithic layers</strong>:</p><p><strong>🟦 1. Presentation Layer (Top Layer)</strong></p><p>This layer handles everything the user sees or interacts with.</p><p><strong>Example features:</strong></p><ul><li>Login page</li><li>Product listing page</li><li>Add to cart button</li><li>HTML templates</li><li>UI components</li><li>API endpoints like:</li><li>GET /products</li><li>POST /add-to-cart</li></ul><p><strong>Example code:</strong></p><pre>// controller<br>function getProducts(req, res) {<br>  const products = productService.getAll();<br>  res.render(&quot;products&quot;, { products });<br>}</pre><p>The presentation layer <strong>displays things</strong> and takes user input.</p><p><strong>🟩 2. Business Logic Layer (Middle Layer)</strong></p><p>This layer contains the <strong>actual rules of the application</strong>.</p><p>This is the “brain” of the monolith.</p><p><strong>Example features:</strong></p><ul><li>Check if user is logged in</li><li>Validate discount rules</li><li>Calculate cart total</li><li>Apply business rules:</li><li>“User cannot order more than 5 items”</li><li>“Premium members get 10% discount”</li></ul><p><strong>Example code:</strong></p><pre>// service<br>function calculateTotal(cartItems) {<br>  let sum = 0;<br>  for (const item of cartItems) {<br>    sum += item.price * item.quantity;<br>  }<br>  return sum;<br>}</pre><p>The business layer <strong>decides what should happen</strong> based on rules.</p><p><strong>🟧 3. Data Access Layer (Bottom Layer)</strong></p><p>This layer interacts with the <strong>database</strong>.</p><p><strong>Example features:</strong></p><ul><li>Fetch products</li><li>Save new orders</li><li>Update user details</li><li>SQL queries or ORM calls</li></ul><p><strong>Example code:</strong></p><pre>// model<br>function findProductById(productId) {<br>  return db.query(&quot;SELECT * FROM products WHERE id = ?&quot;, [productId]);<br>}</pre><p>This layer <strong>talks to the database</strong>.</p><h4><strong>📦 Putting It All Together</strong></h4><p>Here’s a typical request flow in a monolith:</p><pre>User clicks &quot;Buy Now&quot; →<br>Presentation Layer receives request →<br>Business Logic Layer applies rules →<br>Data Access Layer saves order to DB →<br>Response goes back to presentation layer</pre><p>Everything happens <strong>inside one application</strong>, in one process.</p><p>🟪 <strong>Real-World Monolithic Examples(Nodejs)</strong></p><pre>Routes  →  Presentation Layer<br>Controllers  →  Business Logic Layer<br>Models  →  Data Access Layer</pre><h4><strong>🟨 Why Monolithic Architecture Is Simple (Easy to Begin)</strong></h4><ol><li><strong>One codebase → easy to develop</strong></li><li><strong>One deployment → simple CI/CD</strong></li><li><strong>Easy debugging → everything in one place</strong></li><li><strong>Simple tracing → logs come from one app</strong></li><li><strong>No API communication between services</strong><br> (just function calls, faster and easier)</li></ol><p>This is why most startups begin with a monolith.</p><h4>🟥 Problems with Monolithic Architecture (Deep Dive)</h4><p>As your application grows, monolith becomes problematic.</p><p>Let’s explore the issues slowly and clearly:</p><p><strong>❌ 1. Codebase Becomes Very Large</strong></p><p>After months or years, the codebase looks like:</p><ul><li>1 million+ lines of code</li><li>Hundreds of modules</li><li>Hard to understand</li><li>Difficult to maintain</li></ul><p>New developers struggle to learn the entire system.</p><p><strong>❌ 2. Hard to Scale</strong></p><p>If only <strong>product service</strong> needs scaling, you cannot scale it alone.<br>You must scale <strong>the entire monolith</strong>, even if one part is the bottleneck.<br>This wastes CPU/memory and increases cost.<br>Example:<br>If search is heavy, you cannot scale only search — you scale everything.</p><p><strong>❌ 3. Slow Deployment<br></strong>One small change in orders or payments → you must redeploy <strong>the entire app</strong>.</p><p>Why this is bad:</p><ul><li>Deployment becomes risky</li><li>Long downtime window</li><li>Multiple teams block each other</li><li>Harder to release new features fast</li></ul><p><strong>❌ 4. One Bug Can Crash the Entire System</strong></p><p>If a small bug or infinite loop happens in the <strong>payment module</strong>, it can bring down:</p><ul><li>login</li><li>user service</li><li>orders</li><li>inventory</li><li>notifications</li></ul><p>Everything goes down because it’s all one system.</p><p><strong>❌ 5. Technology Lock-In</strong></p><p>If your monolith is built in Java, you <strong>cannot</strong> build a new module in Python or Go.</p><p>Every feature must use the same:</p><ul><li>language</li><li>framework</li><li>ORM</li><li>environment</li></ul><p>Modern apps often need flexibility which monoliths lack.</p><p><strong>❌ 6. Large Team Conflicts</strong></p><p>With 50+ developers working on the same codebase:</p><ul><li>Merge conflicts</li><li>Harder code reviews</li><li>Hard to maintain quality in such a huge app</li><li>One team may break code used by another team</li></ul><p>Microservices solve this by giving each team ownership over one service.</p><p><strong>❌ 7. Slow Build and Test Times</strong></p><p>Large apps take:</p><ul><li>15–40 minutes to build</li><li>30–60 minutes to run full automated tests</li></ul><p>This slows down CI/CD pipelines.</p><h4>🟩 When Monolithic Architecture Is a Good Choice</h4><p>✔ Good for small teams (1–10 developers)</p><p>✔ Good for early-stage startups</p><p>✔ Faster development</p><p>✔ Cheaper to maintain initially</p><p>✔ Simple applications</p><p>✔ Prototype and MVP</p><p>✔ When requirements change often</p><p>If you’re building a <strong>new product</strong> with uncertain requirements, monolith is perfect.</p><h4>🟦 When You Should Avoid Monolithic Architecture</h4><p>Avoid monoliths when:</p><ul><li>You expect the app to grow huge</li><li>You have multiple teams</li><li>You need independent deployments</li><li>You want to use different tech stacks</li><li>You have modules that need different scaling</li><li>You’re building a global, distributed system</li></ul><p>In such cases, <strong>microservices</strong> are better</p><blockquote><strong><em>🔥Monolithic architecture is perfect when you’re small and simple,<br>but becomes painful as your system grows in features, users, and teams.</em></strong></blockquote><p><strong>That’s all for now! I hope you enjoyed reading this article.<br>If you did, please follow, and share — your support really keeps me motivated!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d3c9edb75f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JSON Web Tokens (JWT): A Secure Approach to Web Authentication]]></title>
            <link>https://medium.com/@ekatakumari207/understanding-json-web-tokens-jwt-a-secure-approach-to-web-authentication-68076a2ccac6?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/68076a2ccac6</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 07:14:25 GMT</pubDate>
            <atom:updated>2025-11-19T07:14:25.554Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web applications need a secure, scalable way to know <strong>who the user is</strong> and <strong>what they are allowed to do</strong> — especially when you have SPAs, mobile apps, microservices, and third-party integrations.<br> This is where <strong>JWT (JSON Web Token)</strong> becomes one of the most popular patterns.</p><h4>🎯 What Is a JWT?</h4><p>A <strong>JWT (JSON Web Token)</strong> is a <strong>compact, URL-safe token format</strong> used to represent claims between two parties, typically:</p><ul><li><strong>Client</strong> (browser, mobile app)</li><li><strong>Server</strong> (API / auth server)</li></ul><p>Instead of storing session state on the server (like classic sessionId in a DB), the server <strong>signs</strong> a token containing user information and sends it to the client.</p><p>The client then sends this token with every request, and the server validates it.</p><p>Think of it as a <strong>digitally signed pass</strong> that says:</p><blockquote><em>“This user is userId=123, has role=’admin’, and this pass is valid until 10:30 PM.”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOeKdHhVID3pvBUL0X0EIA.png" /></figure><h4>🚀JWT Structure: Header, Payload, Signature</h4><p>A typical JWT looks like this:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<br>eyJzdWIiOiIxMjM0NTYiLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MzIwMDgwMDB9.<br>h9FZ2C9kq8pQmNQFlx9-3dGZgMZ9T8u7B5CwL4y37m8</pre><p>It is three Base64URL-encoded parts separated by dots:</p><ol><li><strong>Header</strong></li><li><strong>Payload</strong></li><li><strong>Signature</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVMyW1jRNEqqmJOBfpN94A.png" /></figure><p><strong>1️⃣Header</strong></p><p>Example:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ul><li>alg: Signing algorithm (e.g., HS256, RS256)</li><li>typ: Token type (JWT)</li></ul><p>This is encoded as Base64URL and becomes the first part.</p><h4>2️⃣Payload (Claims)</h4><p>Example:</p><pre>{<br>  &quot;sub&quot;: &quot;123456&quot;,<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;iat&quot;: 1732000000,<br>  &quot;exp&quot;: 1732003600<br>}</pre><p>This is where the <strong>claims</strong> live.</p><h4>Registered (standard) claims</h4><p>Common standard fields:</p><ul><li>iss → Issuer (who issued the token)</li><li>sub → Subject (usually user id)</li><li>aud → Audience (who token is intended for)</li><li>exp → Expiration time</li><li>iat → Issued at</li><li>nbf → Not before</li></ul><h4>Custom claims</h4><p>You can add app-specific claims:</p><ul><li>role: &quot;admin&quot;, &quot;user&quot;</li><li>permissions: [&quot;read:orders&quot;, &quot;write:orders&quot;]</li><li>tenantId: &quot;acme-corp&quot;</li></ul><p>⚠️ <strong>Important</strong>: Payload is only <strong>encoded</strong>, not encrypted.<br> Anyone who has the token can decode it and see the data. It is not secret.</p><h4>3️⃣Signature</h4><p>The signature is what makes JWT <strong>trustable</strong>.<br>For HS256 (HMAC with SHA-256):</p><pre>signature = HMAC_SHA256(<br>  base64Url(header) + &quot;.&quot; + base64Url(payload),<br>  secret_key<br>)</pre><p>For RS256 (RSA):</p><ul><li>Private key signs</li><li>Public key verifies</li></ul><p>The final JWT is:</p><pre>&lt;base64Url(header)&gt;.&lt;base64Url(payload)&gt;.&lt;base64Url(signature)&gt;</pre><p>The server verifies this signature to ensure:</p><ul><li>The token was <strong>not modified</strong></li><li>It was issued by someone who owns the <strong>secret / private key</strong></li></ul><h4>🚀Signed vs Encrypted JWT</h4><p>There are two concepts:</p><h4><strong>✅JWS (JSON Web Signature)</strong> → Signed JWT</h4><ul><li>Server takes some JSON data (claims) → {&quot;sub&quot;: &quot;123&quot;, &quot;role&quot;: &quot;admin&quot;, &quot;exp&quot;: ...}</li><li>It <strong>signs</strong> it with a secret key / private key.</li><li>The signature proves: Who created it (<strong>authenticity</strong>),<br>That nobody changed it (<strong>integrity</strong>)</li></ul><p>But the <strong>data is still visible</strong> (only Base64 encoded, not encrypted)</p><blockquote><em>Analogy: A </em><strong><em>transparent plastic envelope</em></strong><em> with a </em><strong><em>tamper-proof seal</em></strong><em>.<br>You can see what’s inside, but if you try to change it, the seal breaks.</em></blockquote><p><strong>Structure of a Signed JWT (JWS)</strong></p><p>Typical 3-part JWT you already know:</p><pre>HEADER.PAYLOAD.SIGNATURE</pre><ul><li><strong>Header</strong> → which algorithm was used for signing (HS256, RS256, etc.)</li><li><strong>Payload</strong> → claims (user id, role, exp…)</li><li><strong>Signature</strong> → cryptographic signature over header.payload</li></ul><p><strong>Everything except the signature is visible if someone has the token.</strong></p><h4>🤔Where is JWS used?</h4><ul><li>Access tokens (API auth)</li><li>ID tokens (OpenID Connect — “Login with Google”, etc.)</li><li>Microservice-to-microservice auth</li><li>Most tutorials, blog posts, and libraries</li></ul><p>💡 <strong>Key point:</strong> If an attacker gets the token, they can <strong>read</strong> the claims, but they <strong>cannot change</strong> them without breaking the signature.</p><h4>✅JWE — Encrypted JWT</h4><p>Here we care about <strong>privacy</strong>:</p><ul><li>We don’t want <em>anyone</em> (even the client) to see the claims.</li><li>Only someone with the <strong>decryption key</strong> can read the content.</li></ul><blockquote><em>Analogy: A </em><strong><em>locked metal safe</em></strong><em>.<br>From outside, you can’t see anything inside. Only whoever has the key can open it.</em></blockquote><p><strong>Structure (conceptual, simplified)</strong></p><p>JWE internally has more parts, but conceptually:</p><pre>ENCRYPTED_HEADER.ENCRYPTED_KEY.IV.CIPHERTEXT.TAG</pre><p>More complex than JWS. But think simply:</p><ul><li><strong>Payload (claims) is encrypted</strong>, not readable.</li><li>You first have to <strong>decrypt</strong> the token, then you can see the claims.</li></ul><p><strong>🤔When is JWE used?</strong></p><ul><li>When the <strong>claims themselves are sensitive</strong>, e.g.Full personal data, Financial info</li><li>Internal data you don’t want the client to read</li><li>When regulations/security policies say:</li><li>“Token content must not be visible to the end user”</li></ul><p>💡 <strong>Key point:</strong> Even if someone steals a JWE token, they <strong>cannot read</strong> the data without the decryption key.</p><h4>🎯Typical Authentication Flow with JWT</h4><p>Let’s walk through a standard “user logs in, gets a token, and calls APIs” flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_CMuZTtD5KNyiSQbR1Ztw.png" /></figure><h4>🔑Login</h4><p>1️⃣Client sends credentials:</p><ul><li>POST /auth/login Content-Type: application/json { &quot;email&quot;: &quot;user@example.com&quot;, &quot;password&quot;: &quot;secret&quot; }</li></ul><p>2️⃣Server verifies credentials:</p><ul><li>Looks up user in DB</li><li>Verifies password hash</li></ul><p>3️⃣On success, server generates a JWT:</p><ul><li>{ &quot;sub&quot;: &quot;user-123&quot;, &quot;name&quot;: &quot;John Doe&quot;, &quot;role&quot;: &quot;user&quot;, &quot;iat&quot;: 1732000000, &quot;exp&quot;: 1732003600 }</li></ul><p>4️⃣Token is signed and sent back:</p><ul><li>{ &quot;access_token&quot;: &quot;&lt;JWT_STRING&gt;&quot;, &quot;token_type&quot;: &quot;Bearer&quot;, &quot;expires_in&quot;: 3600 }</li></ul><h4>🌸Using JWT in Requests</h4><p>The client attaches the token to each API call:</p><pre>GET /api/orders<br>Authorization: Bearer &lt;JWT_STRING&gt;</pre><p>On the server:</p><ol><li>Extract JWT from Authorization header.</li><li>Verify signature using the secret/public key.</li><li>Check claims:</li></ol><ul><li>Is exp in the future?</li><li>Is iss what we expect?</li><li>Is aud our API?</li></ul><ol><li>If valid:</li></ol><ul><li>Attach user info to request context.</li><li>Proceed to business logic.</li></ul><p>This makes the system <strong>stateless</strong> from a session perspective — no session table required.</p><h4>✅ Where to Store JWT on the Client?</h4><p>When the server returns a <strong>JWT</strong> after login, the browser needs to store it somewhere so it can send it with future requests.</p><p>There are <strong>3 main places</strong> to store JWT:</p><ol><li><strong>localStorage</strong></li><li><strong>HttpOnly Cookies</strong></li><li><strong>In-Memory Storage</strong></li></ol><p>Each one has different security impacts, so let’s break it down.</p><p><strong>1️⃣ localStorage</strong></p><p>Example:</p><pre>localStorage.setItem(&quot;access_token&quot;, token)</pre><p><strong>✔ Advantages</strong></p><ul><li>Easy to use in frontend apps (React, Vue, Angular)</li><li>Survives page refresh</li><li>Simple to implement</li></ul><p><strong>❌ Disadvantages</strong></p><ul><li><strong>Biggest issue: XSS vulnerability</strong></li><li>Any malicious JavaScript can read localStorage</li><li>If attacker steals your JWT → full account takeover</li></ul><p><strong>⚠️ Should you use it?</strong></p><p>Only in <strong>very low-risk</strong> apps OR when you have <strong>excellent XSS protection</strong> (rare).</p><p><strong>2️⃣ HttpOnly Cookies (Most Recommended for Real Apps)</strong></p><p>Example (from server):</p><pre>Set-Cookie: access_token=&lt;JWT&gt;; HttpOnly; Secure; SameSite=Strict</pre><p><strong>✔ Advantages</strong></p><ul><li><strong>Not accessible from JavaScript</strong></li><li>Protects against <strong>XSS</strong></li><li>Cookies automatically attach to requests</li><li>Used by almost all secure production systems</li></ul><p><strong>❌ Disadvantages</strong></p><ul><li>Vulnerable to <strong>CSRF attacks</strong></li><li>Use SameSite=Strict or Lax</li><li>OR use CSRF tokens</li></ul><p><strong>⚠️ Should you use it?</strong></p><p><strong>YES.</strong><br>This is the <strong>safest and most common</strong> production setup, especially when using refresh tokens.</p><p><strong>3️⃣ In-Memory Storage (Best for SPA + Refresh Token Flow)</strong></p><p>Store token in a JS variable/state (React state, Redux, etc.)</p><p>Example:</p><pre>let accessToken = null;</pre><p><strong>✔ Advantages</strong></p><ul><li>Token disappears when user closes the tab → reduces risk</li><li>Cannot be stolen via XSS (unless attacker injects JS before token is created)</li><li>Works best with short-lived access tokens</li></ul><p><strong>❌ Disadvantages</strong></p><ul><li><strong>Token lost on page reload</strong></li><li>Requires a refresh-token cookie to get new access tokens</li></ul><p><strong>⚠️ Should you use it?</strong></p><p>Yes, in <strong>modern secure architecture</strong>:</p><p>✔ Store <strong>access token in memory</strong><br>✔ Store <strong>refresh token in HttpOnly cookie</strong></p><p>This is what big apps (Google, GitHub, Facebook) follow.</p><h4>🦋Access Tokens vs Refresh Tokens</h4><p>JWTs are often used in a <strong>two-token model</strong>:</p><ul><li><strong>Access Token</strong></li><li><strong>Refresh Token</strong></li></ul><p>🌸<strong>Access Token</strong></p><ul><li>Short-lived (e.g., 5–15 min)</li><li>Included in Authorization: Bearer &lt;token&gt;</li><li>Used to access APIs</li><li>If stolen, damage is limited by short expiry</li></ul><p>🌸<strong>Refresh Token</strong></p><ul><li>Longer-lived (e.g., 7–30 days)</li><li>Stored more securely (often HttpOnly cookie)</li><li>Used only to obtain new access tokens</li><li>Usually validated against DB/Redis so it can be revoked</li></ul><h4>🔄Refresh Token Flow Explain</h4><p>When a user logs into your app:</p><ul><li>The server gives <strong>two tokens</strong>:</li><li><strong>Access Token</strong> → short-lived (5–15 minutes)</li><li><strong>Refresh Token</strong> → long-lived (7–30 days)</li></ul><p>The <strong>access token</strong> is used to call APIs.</p><p>But because it expires quickly, the user should not be forced to log in again every 15 minutes.</p><p>So we use the <strong>refresh token</strong> to silently get a new access token <strong>without asking the user to log in again</strong>.</p><p>This silent renewal process is called <strong><em>Refresh Token Flow</em></strong></p><h4>🔥 Why Do We Use Refresh Tokens?</h4><p>Reasons:</p><p>✔ To keep users logged in for days/weeks<br> ✔ To prevent token theft harm (access token expires fast)<br> ✔ To avoid storing long-lived tokens in insecure places<br> ✔ To support auto-renew / background login</p><h4>🚶‍♂️ Step-by-Step Explanation</h4><p>Below is the full flow in <strong>simple steps</strong>.</p><p><strong>1️⃣ Access Token Expires</strong></p><p>The user tries to call an API:</p><pre>GET /api/user<br>Authorization: Bearer &lt;expired_access_token&gt;</pre><p>Server responds:</p><pre>401 Unauthorized (Token expired)</pre><p>👉 This means: “Your access token is expired. Please refresh!”</p><h4>2️⃣ Client Sends Refresh Token</h4><p>Client automatically sends a request to the refresh endpoint:</p><pre>POST /auth/refresh<br>Cookie: refresh_token=&lt;refreshToken&gt;</pre><p>Note:<br> Refresh token is stored in <strong>HttpOnly cookie</strong> → cannot be read by JavaScript → safe.</p><p><strong>3️⃣ Server Validates Refresh Token</strong></p><p>Server checks if refresh token:</p><ul><li>is correctly signed</li><li>is not expired</li><li>exists in DB/Redis (if you store it there)</li><li>not revoked</li><li>matches user details</li></ul><p>If everything is correct → continue.</p><p>If not → <strong>401 Unauthorized</strong> and force logout.</p><p><strong>4️⃣ Server Creates a New Access Token</strong></p><p>The server generates a new short-lived access token:</p><pre>{<br>  &quot;userId&quot;: 123,<br>  &quot;role&quot;: &quot;user&quot;,<br>  &quot;exp&quot;: &lt;15 minutes&gt;<br>}</pre><p>Server may also <strong>rotate</strong> the refresh token:</p><ul><li>issue a fresh one</li><li>invalidate the old one</li></ul><p>This improves security.</p><p><strong>5️⃣ Server Sends Back New Access Token</strong></p><p>Server response:</p><pre>{<br>  &quot;access_token&quot;: &quot;&lt;newAccessToken&gt;&quot;<br>}</pre><p>Or sometimes:</p><ul><li>Set-Cookie for rotating refresh token</li></ul><p>Client updates its in-memory access token.</p><p><strong>User Continues Without Re-logging In</strong> →<strong>App now uses the new access token. User does not even notice anything — seamless auto login.</strong></p><h4>🟦 When Refresh Token is Invalid?</h4><p>If refresh token:</p><p>❌ expired<br> ❌ revoked<br> ❌ tampered<br> ❌ does not exist in DB</p><p>Server returns:</p><pre>401 Unauthorized</pre><p>Client logs the user out.</p><h4>🟧 Why Refresh Token is Stored in HttpOnly Cookie?</h4><p>Because:</p><ul><li>It is long lived → MUST be protected</li><li>Should never be exposed to JavaScript</li><li>Should not be stolen by XSS attacks</li><li>HttpOnly cookies block JavaScript access</li></ul><p><strong>So this is the most secure pattern:</strong></p><p><strong>✔ Access Token → in memory<br> ✔ Refresh Token → HttpOnly cookie</strong></p><h4>🟣 Complete Refresh Token Flow Diagram</h4><pre>CLIENT                              SERVER<br>──────────────────────────────────────────────────────────<br>1. API Request with expired token ───────► 401 Unauthorized<br>2. Send refresh token (cookie) ─────────► Validate refresh token<br>3.                                  If valid:<br>                                      - generate new access token<br>                                      - optionally rotate refresh token<br>4. ◄────────────── Send new access token to client<br>5. Client stores new token and continues normally</pre><p>That’s all for now! I hope you enjoyed reading this article.<br>If you did, please follow, and share — your support really keeps me motivated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68076a2ccac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ JavaScript Hoisting]]></title>
            <link>https://medium.com/@ekatakumari207/javascript-hoisting-22ef5dfc2678?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ef5dfc2678</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 04:32:11 GMT</pubDate>
            <atom:updated>2025-11-18T04:32:11.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Hoisting is one of the most important concepts in JavaScript.<br><br><strong><em>Hoisting is JavaScript’s default behavior of allocating memory for variable and function declarations before executing the code</em></strong></p><p>This means <strong>declarations</strong> are processed first, but <strong>assignments</strong> run later.</p><h4>🧠 How JavaScript Executes Code</h4><p>JS engine runs your code in <strong>two phases</strong>:</p><ol><li>Memory Creating :-&gt; Hoisting Happens here</li><li>Code Execution :-&gt;Line by line code Execution</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0NwCOps1Qj__FNDbGaw3A.png" /></figure><h4>🟦 var hoisting</h4><pre>console.log(a);  // undefined<br>var a = 10;<br>console.log(a);  // 10</pre><p><strong>Internal hoisting behavior:</strong></p><p>During compile:</p><pre>var a = undefined</pre><p>Execution phase:</p><pre>console.log(a) → undefined<br>a = 10<br>console.log(a) → 10</pre><p>✔ <strong>No error</strong><br>✔ Because var gets initialized to undefined.</p><h4><strong>🟥 let hoisting + TDZ (Temporal Dead Zone)</strong></h4><pre>console.log(b); // ❌ ReferenceError<br>let b = 20;</pre><p><strong>Why error?</strong></p><ul><li>let is <strong>hoisted</strong></li><li>BUT not initialized</li><li>Before assignment, variable is in the <strong>Temporal Dead Zone (TDZ)</strong></li></ul><h4>🟩 const hoisting + TDZ (Temporal Dead Zone)</h4><pre>console.log(c); // ❌ ReferenceError<br>const c = 30;</pre><p>Same as let, but<br> ❌ const <strong>must</strong> be assigned at declaration.</p><h4>🟪 Function Declaration Hoisting</h4><pre>greet(); // Works<br>function greet() {<br>  console.log(&quot;Hello&quot;);<br>}</pre><p><strong>Why?</strong></p><p>Function declarations are hoisted <strong>with full body</strong>.<br>Memory phase:</p><pre>greet = function() { console.log(&quot;Hello&quot;) }</pre><p>So calling before definition is OK.</p><h4>🟧 Function Expression with var</h4><pre>hello(); // ❌ TypeError: hello is not a function<br>var hello = function() {<br>  console.log(&quot;Hi&quot;);<br>}</pre><h3>Why?</h3><p>Memory:</p><pre>hello = undefined</pre><p>Execution:</p><pre>hello() → undefined() → TypeError</pre><h4>🟨 Function Expression with let/const</h4><pre>hey(); // ❌ ReferenceError<br>let hey = () =&gt; {};</pre><p>Why?</p><ul><li>let is in TDZ → cannot access before assignment</li></ul><h4>🟫 Class Hoisting</h4><pre>new Person(); // ❌ ReferenceError<br>class Person {}</pre><p>Classes are hoisted but:</p><ul><li>not initialized</li><li>fully in TDZ until evaluated</li></ul><h4>⚫ Hoisting inside functions (LOCAL scope)</h4><pre>function test() {<br>  console.log(x); // undefined<br>  var x = 5;<br>}<br>test();</pre><p>var hoisting applies to local scope also.</p><h4>⚪ Hoisting inside blocks (block scope)</h4><pre>{<br>  console.log(y); // ❌ ReferenceError<br>  let y = 10;<br>}</pre><p>Block-level TDZ applies.</p><h4>🔵 Mixed var + let + function</h4><pre>console.log(a);   // undefined<br>console.log(b); // error<br>console.log(foo); // error<br>var a = 1;<br>let b = 2;<br>const foo = 3;</pre><p>Everything is hoisted but behaves differently.</p><h4>🟣 Function Declaration vs Function Expression Priority</h4><p>JavaScript prioritizes <strong>function declarations</strong> over var.</p><pre>console.log(test()); // function declaration wins<br>var test = 10;<br>function test() {<br>  return &quot;function won&quot;;<br></pre><p>Output:</p><pre>&quot;function won&quot;</pre><h4>🟠 Multiple Declarations (var redeclaration allowed)</h4><pre>var x = 1;<br>var x = 2;<br>console.log(x);  // 2</pre><p>var can be redeclared (hoisting allows merging).</p><h4>🟤 let/const redeclaration NOT allowed</h4><pre>let a = 1;<br>let a = 2; // ❌ SyntaxError</pre><h4>🧊 Hoisting with default parameters</h4><pre>function test(x = y, y = 10) {<br>  console.log(x, y);<br>}<br>test(); // ❌ ReferenceError</pre><p>Why?</p><p>Parameter y is not initialized before x tries to access it.</p><h4>🌋 TDZ even inside typeof</h4><p>Normally typeof never errors:</p><pre>typeof undeclaredVariable // &quot;undefined&quot;</pre><p>But with let/const:</p><pre>typeof x; // ❌ ReferenceError<br>let x = 10;</pre><h4>🧠 How to Avoid Hoisting Problems</h4><ul><li>Always use <strong>let/const</strong></li><li>Declare variables at the <strong>top</strong> of the scope</li><li>Use function declarations OR always call functions after definition</li></ul><p><strong>That’s all for now! I hope you enjoyed reading this article.<br>If you did, please follow, and share — your support really keeps me motivated!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ef5dfc2678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Frontend Performance Metrics — Complete Deep Dive]]></title>
            <link>https://medium.com/@ekatakumari207/frontend-performance-metrics-complete-deep-dive-2bd48748d497?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd48748d497</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 07:27:15 GMT</pubDate>
            <atom:updated>2025-11-16T07:27:15.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>📈 <strong>Frontend Performance Metrics — Complete Deep Dive</strong></h3><p>When users visit your website, they judge speed <strong>within milliseconds</strong> — not by what <em>you see</em> as a developer, but by how <em>responsive</em> and <em>stable</em> the page feels to them.</p><p>To measure this objectively, we rely on <strong>performance metrics</strong> — numbers that represent how quickly and smoothly a web page loads and reacts.</p><h4><strong>💡 What Are Frontend Performance Metrics?</strong></h4><p>Frontend performance metrics are <strong>quantitative indicators</strong> that measure <strong>how fast</strong>, <strong>how interactive</strong>, and <strong>how visually stable</strong> your web application is.</p><p>They tell you:</p><ul><li>⚡ How quickly users can <strong>see</strong> your content (loading)</li><li>🎯 How soon they can <strong>interact</strong> (interactivity)</li><li>🧩 How stable the page layout is (visual stability)</li><li>🧠 How efficiently the browser renders and executes JS/CSS (rendering)</li></ul><h4>🧭 <strong>Two Categories of Metrics</strong></h4><p><strong>1. Lab Matrix → </strong>Measured in a Controlled environment(simulated network and device) <em>🔨LighHouse, WebPageTest</em></p><p><strong>2. Field Matrix →</strong>Real-world user data collected via analytics<br> 🔨Chrome UX Report (CrUX), Web Vitals API</p><p>👉 <strong>Lab metrics</strong> help you debug.<br>👉 <strong>Field metrics</strong> help you validate real user experience.</p><h4>⚙️ <strong>Core Frontend Performance Metrics</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2YjLuXKjYyEWG9ZGVizjg.png" /></figure><h4>🕐 FCP — First Contentful Paint</h4><p><strong>What it measures:</strong><br>When the <strong>first piece of content</strong> (text, image, SVG, or canvas) appears on the screen.</p><p><strong>Why it matters:</strong><br>FCP is the moment users first <em>see</em> something appear on the screen. When FCP is delayed, the page looks empty for too long, giving the impression that the website is frozen or not loading.</p><p><strong>Good score:</strong><br> ✅ ≤ 1.8s (fast)<br> ⚠️ 1.8–3s (needs improvement)<br> ❌ &gt; 3s (slow)</p><h4><strong>⚡ How to Improve FCP (First Contentful Paint)</strong></h4><p><strong>1️⃣ Improve Server Response Speed (Reduce TTFB(time To Last Byte</strong>.<strong>))</strong></p><p><strong>TTFB-&gt;</strong>How long it takes for the browser to receive the <strong>first byte</strong> from the server.<br><strong>🎯Good score: </strong>✅ &lt; 200ms<br><strong>Why TTLB matters : </strong>It’s the earliest signal of server performance.<br>FCP cannot start until the browser receives the first byte of HTML.<br>So slow backend → slow FCP.</p><p><strong>How to reduce TTFB</strong>:</p><ul><li>Use highly optimized servers (Node.js, Go, PHP-FPM, NGINX tuned)</li><li>Add server-side caching (Redis, Cloudflare, Varnish)</li><li>Enable <strong>HTTP caching headers</strong></li><li>Reduce database bottlenecks</li><li>Pre-render or Server-Side Render (SSR) pages</li></ul><p>👉 Faster server = faster FCP.</p><p><strong>2️⃣ Use a CDN for Static Assets</strong></p><p>A CDN reduces latency by delivering HTML, CSS, JS, and images from servers close to the user.</p><p>Benefits:</p><ul><li>Fewer network hops</li><li>Faster resource delivery</li><li>Reduced load on origin server</li></ul><p>This directly improves:</p><ul><li>FCP</li><li>LCP</li><li>Overall load time</li></ul><h4>3️⃣ Inline Critical CSS (Critical Rendering Path)</h4><p>The browser must download <strong>CSS</strong> before it can render anything.<br>So if CSS is large or slow to load → FCP becomes slow.</p><p><strong>What to do:</strong></p><ul><li>Inline <strong>critical/above-the-fold CSS</strong> directly in &lt;head&gt;</li><li>Defer or async non-critical CSS</li><li>Use media=&quot;print&quot; or media=&quot;(min-width:…) for conditionally loaded CSS</li><li>Split CSS into critical + non-critical</li></ul><p>This ensures the page can render immediately.</p><p><strong>4️⃣ Minimize Render-Blocking Resources</strong></p><p>Render-blocking resources delay the browser from painting the screen.</p><p>These include:</p><ul><li>CSS files</li><li>JS files loaded without async/defer</li><li>Web fonts that delay text rendering</li></ul><p><strong>Fixes:</strong></p><ul><li>Add defer to JS:</li></ul><pre>&lt;script src=&quot;app.js&quot; defer&gt;&lt;/script&gt;</pre><ul><li>Load CSS asynchronously:</li></ul><pre>&lt;link rel=&quot;preload&quot; as=&quot;style&quot; href=&quot;styles.css&quot; onload=&quot;this.rel=&#39;stylesheet&#39;&quot;/&gt;</pre><ul><li>Reduce CSS size (remove unused CSS)</li><li>Use smaller JS bundles (tree shaking, code splitting)</li></ul><p><strong>5️⃣ Optimize and Preload Web Fonts</strong></p><p>Web fonts can <strong>block text from rendering</strong>, delaying FCP.</p><p><strong>Fixes:</strong></p><ul><li>Use font-display: swap;</li><li>Preload important fonts:</li></ul><pre>&lt;link rel=&quot;preload&quot; href=&quot;font.woff2&quot; as=&quot;font&quot; type=&quot;font/woff2&quot; crossorigin /&gt;</pre><ul><li>Reduce number of font variants (700/500/300 weight)</li><li>Prefer modern fonts (WOFF2)</li></ul><p><strong>6️⃣ Compress and Optimize Images</strong></p><p>Even for FCP, the first visible content may be:</p><ul><li>a logo</li><li>a small SVG</li><li>a background image</li></ul><p><strong>Fixes:</strong></p><ul><li>Use next-gen formats (WebP, AVIF)</li><li>Inline small SVGs</li><li>Preload hero images if they appear early</li><li>Use responsive sizes (srcset)</li></ul><p><strong>7️⃣ Use HTTP/2 or HTTP/3</strong></p><p>Both improve resource loading:</p><ul><li>Parallel downloads</li><li>Reduced latency</li><li>Faster TLS handshake</li></ul><p>This speeds up initial rendering → better FCP.</p><p><strong>8️⃣ Remove Unnecessary JavaScript</strong></p><p>Heavy JS delays DOM parsing and rendering.<br>The browser can’t paint anything while JS blocks the main thread.</p><p><strong>Fix:</strong></p><ul><li>Remove unused JS</li><li>Lazy-load JS for non-critical components</li><li>Split bundles (Webpack / Vite / Next.js)</li><li>Use tree-shaking</li></ul><p><strong>9️⃣ Enable Preloading and Preconnecting</strong></p><p><strong>Preload critical resources:</strong></p><pre>&lt;link rel=&quot;preload&quot; href=&quot;/img/banner.jpg&quot; as=&quot;image&quot;&gt;</pre><p><strong>Preconnect to important domains:</strong></p><pre>&lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;</pre><p>This reduces network round trips → faster content display.</p><p><strong>🔟 Limit Third-Party Scripts (Ads, Analytics, Trackers)</strong></p><p>Third-party scripts slow down FCP by:</p><ul><li>Blocking the main thread</li><li>Loading large JS</li><li>Delaying rendering</li></ul><p><strong>Fix:</strong></p><ul><li>Load them with async</li><li>Use tag manager with firing rules</li><li>Remove unnecessary trackers</li><li>Lazy-load ads</li></ul><p><strong>1️⃣1️⃣ Reduce HTML Document Size</strong></p><p>Large HTML takes longer to parse → slower to paint.<br>Fixes:</p><ul><li>Remove unnecessary HTML comments</li><li>Minimize inline scripts</li><li>Reduce DOM tree size</li></ul><p><strong>1️⃣2️⃣ Use Server-Side Rendering (SSR) or Static Site Generation (SSG)</strong></p><p>Client-side rendering (React/Vue/SPA) must:</p><ul><li>Download JS</li><li>Parse JS</li><li>Execute JS</li><li>Build DOM</li><li>Render content</li></ul><p>This delays FCP significantly.</p><p>SSR/SSG sends ready-to-render HTML → faster FCP.</p><h4>🕑 INP — Interaction to Next Paint (Replaces FID)</h4><p><strong>What it measures:</strong><br>How quickly the page responds to <strong>any interaction</strong> and visually updates afterward.<br><strong>Why it matters:</strong><br>Reflects real-world responsiveness and smoothness.</p><p><strong>🎯Good score:</strong> ≤ 200ms</p><p>⚡<strong> How to Improve INP (Interaction to Next Paint)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiqQ-yqj6DN5WOzxXdSCiA.png" /></figure><p>INP measures <strong>how quickly the page reacts</strong> after a user clicks, taps, or types.<br> If INP is slow, the UI feels laggy, frozen, or delayed.</p><p>Below are <strong>all important points</strong>, explained simply:</p><p><strong>1️⃣ Break Large JavaScript Tasks into Smaller Parts<br>Why?</strong></p><p>When JavaScript runs a long operation (e.g., parsing a huge array, heavy calculations),<br>the browser can’t respond to user actions — the UI becomes stuck.<br><strong>Fix:</strong></p><ul><li>Split big tasks into smaller pieces</li><li>Run them one by one instead of blocking the main thread</li></ul><p><strong>Example:</strong></p><p>❌ Bad (blocks UI for 500ms)</p><pre>function heavyTask() {<br>  // Simulate ~500ms of blocking work<br>  const start = performance.now();<br>  while (performance.now() - start &lt; 500) {<br>    // Doing nothing — but blocking the main thread<br>  }<br>}<br><br>console.log(&quot;Before heavy task&quot;);<br>heavyTask(); // ❌ Blocks UI for 500ms<br>console.log(&quot;After heavy task&quot;);</pre><p>✅ Good (split work)</p><pre>function heavyTaskChunked() {<br>  let remaining = 500; // ms of work to simulate<br><br>  function runChunk() {<br>    const chunkSize = 50; // run 50ms at a time<br><br>    const start = performance.now();<br>    while (performance.now() - start &lt; chunkSize) {<br>      // simulate chunk of work<br>    }<br><br>    remaining -= chunkSize;<br><br>    if (remaining &gt; 0) {<br>      setTimeout(runChunk, 0); // allow browser to breathe<br>    }<br>  }<br><br>  runChunk();<br>}<br><br>console.log(&quot;Before&quot;);<br>heavyTaskChunked(); // ✅ Non-blocking; UI stays responsive<br>console.log(&quot;After&quot;);</pre><p>This gives the browser breathing space to respond to the user.</p><p><strong>2️⃣ Use </strong><strong>requestIdleCallback or Web Workers</strong></p><p><strong>🧵 Web Workers</strong></p><p>Move heavy JavaScript work <strong>off the main thread</strong>, so UI stays smooth.</p><p>Use workers for:</p><ul><li>Image processing</li><li>JSON parsing</li><li>Sorting large lists</li><li>Heavy calculations</li></ul><p><strong>💤 requestIdleCallback()</strong></p><p>Run non-critical tasks <strong>when the browser is free</strong>, not during user interactions.</p><p>Example:</p><pre>requestIdleCallback(() =&gt; {<br>  // run low-priority work<br>});</pre><p><strong>3️⃣ Optimize Event Listeners</strong></p><p>Poorly written event listeners can freeze the interface.</p><p><strong>What slows INP?</strong></p><ul><li>Running too much code inside click/scroll handlers</li><li>Doing heavy calculations on every event</li><li>Multiple listeners for the same element</li></ul><p><strong>Fix:</strong></p><ul><li>Keep event handlers tiny</li><li>Debounce or throttle repeated events (scroll, resize, input)</li><li>Remove unnecessary listeners</li><li>Avoid doing expensive work inside event callbacks</li></ul><p>Example:</p><pre>const handleScroll = throttle(() =&gt; {<br>  // light and simple code<br>}, 100);</pre><p><strong>4️⃣ Avoid Heavy Re-renders (Especially in React/Vue)</strong></p><p>Re-rendering the whole component tree after every user action increases INP.</p><p><strong>Causes of heavy re-renders:</strong></p><ul><li>Unnecessary state updates</li><li>Passing new objects/functions as props</li><li>Large lists without virtualization</li><li>Missing memoization</li></ul><p><strong>Fixes in React:</strong></p><ul><li>Use React.memo()</li><li>Use useCallback, useMemo</li><li>Use <strong>React DevTools Profiler</strong></li><li>Virtualize long lists (react-window, react-virtual)</li><li>Avoid updating global state on small UI interactions</li></ul><p><strong>Fixes in Vue:</strong></p><ul><li>Use computed properties correctly</li><li>Avoid watchers for everything</li><li>Use v-once, keep-alive where possible</li></ul><p><strong>5️⃣ Reduce JavaScript Bundle Size</strong></p><p>More JS = more parsing + more execution = slower interactions.</p><p><strong>Optimize:</strong></p><ul><li>Code splitting</li><li>Tree-shaking unused code</li><li>Only import what you need</li><li>Remove old polyfills</li><li>Defer non-critical scripts</li></ul><p><strong>6️⃣ Prioritize User Actions</strong></p><p>Important interactions (clicks, form submit, input typing)<br>should run immediately — not wait behind animations or heavy JS.</p><p><strong>Fix:</strong></p><ul><li>Cancel or skip low-priority tasks when the user interacts</li><li>Show instant feedback (loading spinner, disabled button)</li></ul><p><strong>7️⃣ Avoid Long Running Layout or Paint Tasks</strong></p><p>UI updates (like resizing, heavy DOM manipulation) can delay paint.</p><p><strong>Improve:</strong></p><ul><li>Use CSS transforms instead of layout-heavy properties</li><li>Batch DOM updates</li><li>Use requestAnimationFrame for animations</li><li>Avoid layout thrashing (multiple style reads during updates)</li></ul><p><strong>8️⃣ Minimize Third-Party Scripts</strong></p><p>Analytics, ads, and tracking scripts often slow down event responses.</p><p><strong>Fix:</strong></p><ul><li>Load them using async</li><li>Remove unused third-party libraries</li><li>Use lighter alternatives (e.g., replace jQuery with native JS</li></ul><h4>🕒 LCP — Largest Contentful Paint</h4><p><strong>What it measures:</strong><br> Time to render the <strong>largest visible element</strong> (hero image, heading, banner).</p><p><strong>Why it matters:</strong><br> It represents when the main content is visible — a key UX milestone.</p><p><strong>🎯Good score:</strong> ≤ 2.5s</p><h4><strong>⚡ How to Improve LCP (Largest Contentful Paint)</strong></h4><p><strong>1️⃣ Compress and Preload Large Images</strong></p><p><strong>📌 Why?</strong></p><p>Most websites have a <strong>hero image</strong> above the fold.<br> If the image is large or loads late → LCP becomes slow.</p><p><strong>✔ Compress Images</strong></p><p>Use modern image formats:</p><ul><li><strong>WebP</strong></li><li><strong>AVIF</strong></li><li><strong>JPEG XL</strong></li></ul><p>They reduce file size by <strong>50–80%</strong> without losing quality.</p><p><strong>✔ Preload Key Images</strong></p><p>Tell the browser to load the hero image <strong>as early as possible</strong>:</p><pre>&lt;link rel=&quot;preload&quot; as=&quot;image&quot; href=&quot;/hero.webp&quot; fetchpriority=&quot;high&quot;&gt;</pre><p>This pushes the image to the <strong>front of the loading queue</strong>, improving LCP dramatically.</p><p><strong>✔ Resize or optimize your hero image</strong></p><p>Avoid loading a 3000px image on mobile screens.<br>Smaller images = faster download = faster LCP.</p><p><strong>2️⃣ Use Responsive Image Sizes</strong></p><p><strong>📌 Why?</strong></p><p>Mobile devices should not download desktop-sized images.</p><p><strong>✔ Use </strong><strong>srcset + </strong><strong>sizes</strong></p><p>This allows browsers to choose the <strong>best</strong> image size based on device width:</p><pre>&lt;img <br>  src=&quot;hero-1600.webp&quot;<br>  srcset=&quot;hero-600.webp 600w, hero-1200.webp 1200w, hero-1600.webp 1600w&quot;<br>  sizes=&quot;(max-width: 768px) 600px, 1200px&quot;<br>  alt=&quot;Hero&quot;<br>/&gt;</pre><p><strong>Benefits:</strong></p><ul><li>Mobile users get smaller images</li><li>Desktop gets higher quality</li><li>Browser chooses the most optimal size</li></ul><p>This significantly improves LCP on all devices.</p><p><strong>3️⃣ Optimize Critical Path Rendering</strong></p><p><strong>📌 What is the critical path?</strong></p><p>Before the browser can paint anything (including LCP), it must:</p><ol><li>Download HTML</li><li>Parse HTML</li><li>Download CSS</li><li>Parse CSS</li><li>Build Render Tree</li><li>Paint content (LCP happens here)</li></ol><p>If anything delays these steps → <strong>LCP slows down</strong>.</p><p><strong>✔ Inline critical CSS</strong></p><p>Only for above-the-fold content:</p><pre>&lt;style&gt;<br>  /* Critical CSS here */<br>&lt;/style&gt;</pre><p>This avoids waiting for external CSS files.</p><p><strong>✔ Load non-critical CSS asynchronously</strong></p><pre>&lt;link rel=&quot;preload&quot; href=&quot;style.css&quot; as=&quot;style&quot; onload=&quot;this.rel=&#39;stylesheet&#39;&quot;&gt;</pre><p><strong>✔ Minimize layout complexity</strong></p><p>A deep or complicated layout takes longer to process → delays LCP.</p><p><strong>✔ Remove unused CSS</strong></p><p>Large CSS files take longer to download and parse.</p><p><strong>4️⃣ Reduce Render-Blocking CSS/JS</strong></p><p><strong>📌 Why?</strong></p><p>By default:</p><ul><li><strong>CSS blocks rendering</strong></li><li><strong>JavaScript blocks parsing</strong></li></ul><p>If CSS/JS arrives late → LCP element arrives late too.</p><p><strong>✔ Fix render-blocking CSS</strong></p><p><strong>✔ Minify CSS →</strong>Reduce unnecessary rules, whitespace, comments.</p><p><strong>✔ Split CSS</strong></p><ul><li><strong>Critical CSS</strong> = inline</li><li><strong>Non-critical CSS</strong> = load async</li></ul><p><strong>✔ Avoid large CSS frameworks</strong></p><p>Example: importing entire Bootstrap or Tailwind when you use 10% of it.</p><p><strong>✔ Fix render-blocking JavaScript</strong></p><p><strong>✔ Use </strong><strong>defer attribute</strong></p><p>Loads JS <strong>without blocking HTML parsing</strong>:</p><pre>&lt;script src=&quot;app.js&quot; defer&gt;&lt;/script&gt;</pre><p><strong>✔ Use </strong><strong>async for scripts that do not depend on others</strong></p><pre>&lt;script src=&quot;analytics.js&quot; async&gt;&lt;/script&gt;</pre><p><strong>✔ Reduce JS bundle size</strong></p><p>Large JavaScript delays everything, including LCP.</p><p>Ways to reduce:</p><ul><li>Tree-shaking</li><li>Code-splitting</li><li>Lazy loading</li><li>Removing unused libraries</li></ul><p><strong>✔ Avoid expensive JS before LCP</strong></p><p>Example: Avoid running analytics, heavy computations, or DOM modifications too early.</p><h4>🕓 CLS — Cumulative Layout Shift</h4><p><strong>What it measures:</strong><br>How much the page layout <strong>shifts unexpectedly</strong> during loading.</p><p><strong>Why it matters:</strong><br> Avoids “rage clicks” or mis-clicks when content moves.</p><p><strong>🎯Good score:</strong> ≤ 0.1</p><p><strong>⚙️ How to Improve CLS (Cumulative Layout Shift)</strong></p><p>Let’s break down every point in a simple and detailed way 👇</p><p><strong>1️⃣ Set width and height for images and ads</strong></p><p><strong>Why?</strong></p><p>If the browser doesn’t know an image’s size in advance,<br> it can’t reserve space — so when the image loads later, the layout <strong>shifts</strong>.</p><p><strong>Fix:</strong></p><p>Always specify image dimensions:</p><pre>&lt;img src=&quot;banner.jpg&quot; width=&quot;800&quot; height=&quot;400&quot; /&gt;</pre><p>Or use CSS:</p><pre>img {<br>  aspect-ratio: 16/9;<br>}</pre><p>Ads also need fixed-size containers:</p><pre>&lt;div style=&quot;width: 300px; height: 250px;&quot;&gt;<br>  &lt;!-- Ad loads here --&gt;<br>&lt;/div&gt;</pre><p>⭐ This prevents sudden jumps when assets load.</p><p><strong>2️⃣ Reserve space for dynamic content</strong></p><p><strong>Why?</strong></p><p>Elements like:</p><ul><li>Ads</li><li>Pop-ups</li><li>Lazy-loaded images</li><li>Chat widgets</li></ul><p>often load later and push content down.</p><p><strong>Fix:</strong></p><p>Give them a placeholder or container with fixed height/width before they load.</p><p>Example:</p><pre>&lt;div class=&quot;skeleton&quot; style=&quot;height: 200px;&quot;&gt;&lt;/div&gt;</pre><p>This ensures <strong>no layout jump</strong> when the actual content appears.</p><p><strong>3️⃣ Use CSS transforms for animations</strong></p><p><strong>Why?</strong></p><p>Animations that change layout (top, left, width, height) cause shifts.</p><p>Example:</p><pre>.move {<br>  top: 20px;   /* BAD - layout shift */<br>}</pre><p><strong>Fix:</strong></p><p>Use transform instead — it does NOT affect layout:</p><pre>.move {<br>  transform: translateY(20px); /* GOOD - no layout shift */<br>}</pre><p>✔ GPU-friendly<br> ✔ Smooth animations<br> ✔ No CLS impact</p><p><strong>4️⃣ Load fonts with </strong><strong>font-display: swap</strong></p><p><strong>Why?</strong></p><p>When custom fonts load slowly:</p><ul><li>The browser shows invisible text (FOIT)</li><li>Then suddenly replaces it with real font → <strong>layout shift</strong></li></ul><p>The text may jump due to different font spacing.</p><p><strong>Fix:</strong></p><p>Use font-display: swap:</p><pre>@font-face {<br>  font-family: &#39;CustomFont&#39;;<br>  src: url(https://medium.com/&#39;custom.woff2&#39;) format(&#39;woff2&#39;);<br>  font-display: swap;<br>}</pre><p>This makes the browser:</p><ul><li>Show fallback font instantly</li><li>Replace it later <strong>without shifting layout</strong></li></ul><p>⭐ Great for avoiding text jumps.</p><p><strong>That’s all for now! I hope you enjoyed reading this article.<br>If you did, please follow, and share — your support really keeps me motivated!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd48748d497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Build a Traffic Light System Using React(Machine Coding Round)]]></title>
            <link>https://medium.com/@ekatakumari207/build-a-traffic-light-system-using-react-machine-coding-round-5d50e75e5892?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d50e75e5892</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 13:18:20 GMT</pubDate>
            <atom:updated>2025-11-13T13:18:20.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*XBH5X_doOlSsJaI1oiBRJQ.png" /></figure><p>Frontend machine-coding rounds are becoming more common in companies like <strong>Razorpay, Swiggy, CoinDCX, Paytm, Walmart, Meesho</strong>, and fast-growing SaaS startups.</p><p>One practical UI challenge that frequently appears in interviews:</p><p><strong>🚦 Build a Traffic Light System using React — -&gt; Machine Coding</strong></p><h4>🧩 Problem Statement</h4><p>We need to build a <strong>Traffic Light</strong> system where lights switch from <strong>Green → Yellow → Red</strong> at fixed time intervals and repeat indefinitely.</p><p>Each light should stay ON for the following durations:</p><p>Light Color<br>🟥 Red — →4000 ms (4 seconds)<br>🟨 Yellow — →500 ms (0.5 second)<br>🟩 Green — →3000 ms (3 seconds)</p><h4>🚀Full Component code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*pLQ2DqrbFu4W80yuxkX0MQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBsrjGyZa8uwiNNCJqQiZA.png" /></figure><p><strong>🧱 Create the Configuration</strong></p><p>We define a configuration array for the traffic lights.<br> Each object includes:</p><ul><li>background → the light color</li><li>duration → how long the light stays on</li><li>next → the color to switch to after the duration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*CzhEj_h_QLCSsp8JEW45OA.png" /></figure><p><strong>🔁 Use useEffect for Timed Switching</strong></p><ul><li>Find the current light configuration.</li><li>Wait for its duration using setTimeout.</li><li>Then switch to the next light.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbmbviPIB5mWx4BBUB_bGg.png" /></figure><p><strong>✅ Explanation:</strong></p><ul><li>When lightStatus changes, useEffect runs again.</li><li>It sets a new timeout based on the current light’s duration.</li><li>After that time, the next light is activated using setLightStatus.</li><li>This creates a continuous cycle — Green → Yellow → Red → Green</li></ul><p><strong>🎨 Step 4: Display the Traffic Light UI</strong></p><p>We render 3 circular lights.<br> The <strong>active</strong> one will have its color filled, while others remain white.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teYIiRJnVEN4WKt_sZIWJg.png" /></figure><p>✅ <strong>How It Works:</strong></p><ul><li>We iterate through all lights in the config.</li><li>For each light, we compare its color with lightStatus.</li><li>If it matches, that light turns ON (shows its color).</li><li>Otherwise, it stays OFF (white).</li></ul><p><strong>Github Link<br> </strong><a href="https://github.com/ekata789123/Frontend-Practice/blob/main/MachineCoding/src/TrafficLight/TrafficLight.jsx">https://github.com/ekata789123/Frontend-Practice/blob/main/MachineCoding/src/TrafficLight/TrafficLight.jsx</a></p><p><strong>That’s all for now! I hope you enjoyed reading this article.<br>If you did, please follow, and share — your support really keeps me motivated!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d50e75e5892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Clean Coding: The Foundation of Low Level Design and Readable Code]]></title>
            <link>https://medium.com/@ekatakumari207/clean-coding-the-foundation-of-low-level-design-and-readable-code-96295680b318?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/96295680b318</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 13:11:43 GMT</pubDate>
            <atom:updated>2025-11-12T13:15:07.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>💭 What is Clean Coding?</h3><p><strong>Clean Coding</strong> means writing code that is <strong>easy to read, easy to understand, and easy to modify</strong>.<br>It’s not just about making the program run — it’s about writing it so that <strong>any human</strong> (including your future self) can understand what’s happening without much effort.</p><h4>💭 Why Learn Clean Coding?</h4><ol><li>The most important reason to learn <strong>Low Level Design (LLD)</strong> is to learn how to <strong>write clean, modular, and reusable code</strong></li><li>We don’t write code for machines — we write it for <strong>humans</strong></li></ol><ul><li>Machines don’t care about how clean or dirty your code is.</li><li>But <strong>humans care about clarity</strong>, structure, and readability.</li></ul><p>3. As teams grow larger, multiple developers work on the same project, Clean code ensures that everyone can easily <strong>understand, debug, and extend</strong> the logic.<br><strong>4. Dirty code</strong> leads to <strong>confusion, frustration, bugs, and wasted time<br>5. </strong>Even <strong>wrong but clean code</strong> is better than correct code that’s messy — because it’s easier to fix something understandable.<br>6.If there’s a bug, clean code makes debugging <strong>faster and simpler</strong>.</p><h4>🧱 Code Modularity — Building in Small, Clean Blocks</h4><p>Modular code means breaking large problems into <strong>small, independent, and reusable parts</strong>.<br><strong>🔑 Principles of Modularity</strong></p><ol><li><strong>Avoid repeating the same code</strong> multiple times.<br> → If you see a repeated pattern, create a <strong>separate function</strong>.</li><li><strong>Don’t pass too many variables</strong> to a single function.<br> → Too many parameters make code confusing and harder to test.</li><li><strong>Follow the Single Responsibility Principle (SRP)</strong>.<br> → A function or class should do <strong>only one job</strong>.</li><li><strong>Prefer many small functions</strong> instead of one big function.</li><li><strong>Avoid too many indentation levels.</strong><br> → Deeply nested if or for statements make code hard to follow.</li></ol><p><strong>💡 Example: Dirty Code vs Clean Code</strong></p><p><strong>❌ Dirty Code</strong></p><pre>function main() {<br>    const nums = [5, 3, 7, 9, 12, 4, 7];<br>    let c1 = 0, c2 = 0;<br>    for (let i = 0; i &lt; nums.length - 1; i++) {<br>        if ((nums[i] + nums[i + 1]) % 3 === 0) {<br>          c1++;<br>        }<br>        if ((nums[i] + nums[i + 1]) % 5 === 0) {<br>          c2++;<br>        }<br>      }<br>  console.log(c1 + &quot; &quot; + c2);<br>}<br>main();</pre><h3>🧠 What’s Wrong Here?</h3><p>❌ Repeated code logic for checking divisibility<br>❌Poor variable names (c1, c2)<br>❌Hardcoded divisors (3 and 5)<br>❌No modularity or reusability</p><p><strong>✅ Clean Code</strong></p><pre>// Helper function to check divisibility<br>function isSumDivisibleBy(sum, divisor) {<br>  return sum % divisor === 0;<br>}<br>function main() {<br>  const numbers = [5, 3, 7, 9, 12, 4, 7];<br>  const divisors = [3, 5];<br>  const countOfDivisiblePairs = [0, 0];<br>  for (let i = 0; i &lt; numbers.length - 1; i++) {<br>    const adjacentSum = numbers[i] + numbers[i + 1];<br>    divisors.forEach((divisor, index) =&gt; {<br>      if (isSumDivisibleBy(adjacentSum, divisor)) {<br>        countOfDivisiblePairs[index]++;<br>      }<br>    });<br>  }<br>  console.log(<br>    `Pairs divisible by ${divisors[0]}: ${countOfDivisiblePairs[0]}\n` +<br>    `Pairs divisible by ${divisors[1]}: ${countOfDivisiblePairs[1]}`<br>  );<br>}<br>main();</pre><p><strong>🌻What’s Better Here:</strong></p><p>🌸<strong>Modularity</strong>:isSumDivisibleBy() separates logic into a reusable function<br>🌸<strong>Meaningful Name</strong>: numbers, divisors, adjacentSum clearly describe purpose<br>🌸<strong>DRY Principle</strong>: No repeated modulo checks,<br>🌸<strong>Scalability</strong>: You can easily add more divisors,<br>🌸<strong>Readability</strong>: Code reads like natural language</p><h3>✍️ Importance of Naming</h3><p>Good naming is the <strong>heart of clean code</strong>.<br> Names should clearly tell <em>what the variable, function, or class does.</em></p><p><strong>💬 Why It Matters</strong></p><ol><li><strong>Hardcoded numbers</strong> or <strong>random names</strong> (like x, y, z, a1, b2) make code frustrating to read.</li></ol><p>For example:</p><ul><li>❌ d = b - a;</li><li>✅ displacement = finalPosition - initialPosition;</li></ul><ol><li>Only the original writer may understand random names — others will struggle later.</li><li>Good names <strong>reveal the intent</strong> of the code.</li><li>Avoid <strong>magic numbers</strong> — use <strong>named constants</strong> instead.</li><li>Readability improves <strong>many times</strong> with proper names.</li></ol><h4>🏷️ Best Practices for Naming</h4><ol><li>Use <strong>descriptive names</strong><br> → countOfStudents is better than count.</li><li>Avoid <strong>numbered variables</strong> like i1, i2, i3, c1, c2.</li><li>Don’t include <strong>data structure names</strong> in variable names<br> → ❌ priceArray, ✅ prices.</li><li>Use <strong>pronounceable</strong> names → countLeaves not cntLvs.</li><li>Use <strong>searchable</strong> names → numberOfPoints not NOP or n.</li><li><strong>Longer scope = more descriptive name</strong>.<br> Global or class-level variables should have clear, full names.</li><li>Avoid <strong>hardcoded numbers</strong> → use constants like MAX_SIZE = 100.</li><li>Use <strong>explanatory variables</strong> for clarity:</li></ol><ul><li>bool isPrime = p.second.first; if (isPrime) { ... }</li></ul><p>9.Prefer clear naming in functions too:</p><ul><li>bool isChildValueGreater(Node *parent, Node *child) { return parent-&gt;value &lt; child-&gt;value; }</li></ul><h4>🧩 Clean Functions</h4><p>Functions are the <strong>building blocks</strong> of clean code.<br> A clean function should be <strong>short, focused, and do one thing well</strong>.</p><p><strong>✅ Key Principles</strong></p><ol><li>Keep functions <strong>small and concise</strong>.</li><li><strong>Single responsibility</strong> — one function = one job.</li><li>Don’t modify the <strong>original input data</strong> unless necessary.</li><li><strong>Many small functions</strong> are better than one big one.</li><li>If you can’t break it down further, it’s probably at the right size.</li><li>High-level code (business logic) should be readable by humans; low-level code (like bit operations) should stay hidden in helper methods.</li><li>Avoid mixing low-level operations inside high-level APIs.</li></ol><p><strong>⚙️ Best Practices for Functions</strong></p><p>✅Write <strong>small, single-responsibility</strong> functions.</p><p>✅Organize code:</p><ul><li>Functions → Classes</li><li>Classes → Packages</li><li>Packages → Modules</li></ul><p>✅Use <strong>descriptive verb-based names</strong>:</p><ul><li>int findMax(Node *parent, Node *child);</li></ul><p>✅<strong>Long descriptive names</strong> are better than short unclear ones.</p><p>✅Stick to <strong>one naming pattern</strong> → use consistent prefixes like get, update, delete.<br>✅Use <strong>void</strong> for write functions and <strong>non-void</strong> for read functions:</p><ul><li>Read: getUser(), getData()</li><li>Write: updateUser(), deleteUser()</li></ul><p>✅<strong>Avoid too many </strong><strong>if-else or </strong><strong>switch statements</strong> — they’re harder to maintain. Instead, create <strong>separate functions or classes</strong> for each case.<br>✅If you must use conditions, keep <strong>maximum two levels of indentation</strong>.<br>✅Limit the <strong>number of function arguments</strong> — fewer is better.<br>✅Separate <strong>I/O operations</strong> (like file reading) from logic.</p><p><strong>📄 Example: Side-Effect Function</strong></p><pre>Marks getMarks() {<br>    String dataFromFile = readFromFile(fileName);<br>    ...<br>}<br>String readFromFile(String fileName) {<br>    openFile(fileName);<br>    readData();<br>    closeFile();<br>    return data;<br>}</pre><p>💡 These are <strong>side-effect functions</strong>, meaning they affect the system (e.g., open/close files).<br> Always <strong>undo the change</strong> (close file, free memory, etc.) after such operations.</p><h4>🔁 The DRY Principle</h4><p><strong>DRY = Don’t Repeat Yourself</strong></p><p><em>If you’re repeating code, extract it into a function or helper class.<br> Reusing code improves readability and reduces bugs.</em></p><p><strong>That’s all for now! I hope you enjoyed reading this article.<br> If you did, please follow, and share — your support really keeps me motivated!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96295680b318" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Closure Concept]]></title>
            <link>https://medium.com/@ekatakumari207/javascript-closure-concept-cbc5f9e876ac?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbc5f9e876ac</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 12:29:42 GMT</pubDate>
            <atom:updated>2025-11-12T05:45:27.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NGYiBdo4QtGIITxI9fePA.png" /></figure><h3>🔐 What is a Closure?</h3><p>A <strong>closure</strong> is created when a function retains access to variables from its <strong>lexical environment</strong> (where it was defined), even after that outer function has returned.</p><p>In simple terms:</p><p><em>A closure lets a function </em><strong><em>remember and access</em></strong><em> variables outside its own scope </em><strong><em>even after the parent function has finished executing</em></strong><em>.</em></p><h4>🔥 Closure = Function + Remembered Lexical Scope</h4><p><strong>✅Closure Example</strong></p><pre>function outer() {<br>  let count = 0;<br><br>  function inner() {<br>    count++;<br>    console.log(count);<br>  }<br><br>  return inner;<br>}<br><br>const fn = outer();<br>fn(); // 1<br>fn(); // 2 — count is preserved</pre><h4>🧠 What&#39;s happening?</h4><ol><li>You call outer()</li><li>Inside outer, a variable count is created (count = 0)</li><li>outer() returns the inner function inner</li><li>Now fn <strong>becomes the inner function</strong></li><li>When you call fn():</li></ol><ul><li>It increases count</li><li>It prints the updated value</li></ul><p><strong>Even though </strong><strong>outer() has finished, </strong><strong>count does not disappear</strong> 👈<br>Because inner() keeps a <strong>memory of </strong><strong>count</strong> — this is called a <strong>closure</strong></p><h3>🧠 Why Closures Work</h3><p>JavaScript uses <strong>lexical scoping</strong>, meaning the scope of variables is determined by <strong>where functions are written</strong>, not where they are called.</p><p>When JavaScript creates a function, it stores:</p><ul><li>Function code</li><li><strong>Reference to the environment where it was created</strong></li></ul><p>This environment is stored in a hidden internal slot called [[Environment]].</p><p>So when the function runs later, it accesses variables via its <strong>saved scope chain</strong>, not the global scope.</p><p><strong>Closures are powered by JavaScript Execution Context + Scope Chain</strong></p><h4>📦 Where Closures Live in Memory?</h4><p>To understand closures deeply, we must understand <strong>how JavaScript stores variables in memory</strong>.</p><p><strong>✅ Normal variables (no closure involved)<br></strong>When a function runs:<br> 📍Local variables are stored in the <strong>stack<br></strong>📍When the function finishes, that stack frame is removed<br>📍All its local variables <strong>disappear</strong></p><p>Example:</p><pre>function test() {<br>  let x = 10; // stored in stack<br>}<br>test(); // stack frame removed -&gt; x is gone</pre><p>This is the normal case.</p><p><strong>✅ But closure variables behave differently</strong></p><p>When a function creates a closure, any variable used by the inner function <strong>cannot be thrown away</strong>.</p><p>So JavaScript <strong>moves those variables to heap memory</strong> (or keeps them there) instead of destroying them.</p><p>Why? <br><em>Because the inner function still needs access to those variables even after the outer function has returned. So Closure extend lifetime of variable.</em></p><h4>🎯 When Are Closures Used in Real Projects?</h4><p>Closures are not just a theory topic — they are used everywhere in modern JavaScript development.</p><p><strong>✅ 1. Data Privacy (Encapsulation / Private Variables)</strong></p><p>Closures allow you to keep data private and only expose what is needed.</p><p><strong>Use case:</strong> Security-sensitive values, API keys, private counters, internal state.</p><pre>function createUser() {<br>  let balance = 0; // private<br>  return {<br>  deposit(amount) { balance += amount; },<br>  getBalance() { return balance; }<br>  };<br>  }</pre><p><strong>✅ 2. Stateful Functions</strong></p><p>Closures let functions <strong>remember values</strong> across calls.<br><strong>Examples:</strong> Counters, caching data, saving user session state</p><pre>function counter() {<br>  let c = 0;<br>  return () =&gt; ++c;<br>}</pre><p><strong>✅ 3. Functions Returning Functions (Currying)</strong></p><p>Closures help break multi-argument functions into reusable smaller ones.</p><p><strong>Used in:</strong> Functional programming, libraries like Redux, Lodash</p><pre>const add = a =&gt; b =&gt; c =&gt; a + b + c;</pre><p><strong>✅ 4. Callbacks (Async &amp; Event-Driven Programming)</strong></p><p>Closures preserve values inside callbacks — important for timing/event logic.</p><p><strong>Examples:</strong></p><ul><li>setTimeout</li><li>DOM click handlers</li><li>API callbacks</li></ul><pre>function delayedLogger(msg) {<br>  setTimeout(() =&gt; console.log(msg), 1000);<br>}</pre><p><strong>✅ 5. Functional Programming (Higher-order functions)</strong></p><p>Closures power functions like .map(), .filter(), .reduce()</p><pre>const multiplier = x =&gt; n =&gt; x * n;<br>const double = multiplier(2);<br>console.log([1,2,3].map(double)); // [2,4,6]</pre><p><strong>✅ 6. Module Pattern / JS Module Scope</strong></p><p>Closures emulate <strong>private scope</strong> and expose only necessary parts.</p><p>Used heavily before ES Modules — still relevant in Node.js &amp; IIFEs.</p><pre>const App = (() =&gt; {<br>  let secret = &quot;hidden&quot;;<br>  return {<br>    reveal() { console.log(secret); }<br>  };<br>})();</pre><h4>🧨 Common Closure Pitfalls</h4><p><strong>❌ Memory Leaks</strong></p><p>Closures <strong>can accidentally keep large data alive</strong></p><pre>function keepLargeData() {<br>  const big = new Array(1e6).fill(&quot;data&quot;);<br>  return () =&gt; console.log(big.length);<br>}</pre><p>✅ solution: explicitly null references if no longer needed</p><p><strong>❌ Overuse in Loops</strong></p><p>Wrapping every iteration in closures = performance overhead if not needed</p><p><strong>❌ Debugging Scope Chain</strong></p><p>Closures make debugging harder → VSCode devtools show “closure” in scope panel</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbc5f9e876ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Build a Pagignation Component in React (Machine Coding Round )]]></title>
            <link>https://medium.com/@ekatakumari207/build-a-pagignation-component-in-react-machine-coding-round-b3b3c6da80f3?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3b3c6da80f3</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 16:14:43 GMT</pubDate>
            <atom:updated>2025-11-10T16:15:51.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*ZdcqQka3F1gWK5KjYTwR6Q.png" /></figure><p>Frontend machine-coding rounds are becoming more common in companies like <strong>Razorpay, Swiggy, CoinDCX, Paytm, Walmart, Meesho</strong>, and fast-growing SaaS startups.</p><p>One practical UI challenge that frequently appears in interviews:</p><blockquote><strong><em>Build a Pagination UI Component to fetch data page-by-page from an API</em></strong></blockquote><p>In this article, we’ll build a <strong>Pagination Component in React</strong>, using public API data.</p><p>✅ Fetch paginated data<br> ✅ Track current page<br> ✅ Show page numbers dynamically<br> ✅ Handle Prev / Next controls<br> ✅ Disable buttons when needed<br> ✅ Manage state cleanly using hooks</p><h4>🎯 Final Result</h4><ul><li>Each page fetches <strong>15 products</strong></li><li>You can navigate using <strong>page buttons + Prev/Next</strong></li><li>The current page gets active highlight</li><li>No page reload — everything React-state driven</li></ul><h4>🧠 Code — Pagination Component</h4><pre>import &quot;./PagignationComponent.css&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>export const Pagignation = () =&gt; {<br>  const LIMIT = 15;<br>  const [result, setResult] = useState([]);<br>  const [total, setTotal] = useState(0);<br>  const [page, setPage] = useState(1); <br>  const totalPages = Math.max(1, Math.ceil(total / LIMIT));<br>  const pageList = Array.from({ length: totalPages }, (_, i) =&gt; i + 1);<br>  useEffect(() =&gt; {<br>    fetchData(page);<br>  }, [page]);<br>  async function fetchData(currentPage) {<br>    const skip = (currentPage - 1) * LIMIT;<br>    const res = await fetch(<br>      `https://dummyjson.com/products?limit=${LIMIT}&amp;skip=${skip}&amp;select=title,price`<br>    );<br>    const json = await res.json();<br>    setResult(json.products || []);<br>    setTotal(json.total || 0);<br>  }<br>  return (<br>    &lt;div className=&quot;pagignation-component&quot;&gt;<br>        &lt;div className=&quot;heading&quot;&gt;<br>       &lt;h2&gt;Frontend Machine Coding&lt;/h2&gt;<br>        &lt;h3&gt;Pagignation Component&lt;/h3&gt;<br>       &lt;/div&gt;<br>      &lt;div className=&quot;pagignation-data&quot;&gt;<br>        {result.map((item) =&gt; (<br>          &lt;div key={item.id} className=&quot;pagignation-row&quot;&gt;<br>            &lt;span&gt;{item.title}&lt;/span&gt;<br>            &lt;span&gt;₹{item.price}&lt;/span&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>      &lt;div className=&quot;pagination-buttons&quot;&gt;<br>        &lt;button<br>          className=&quot;page-btn&quot;<br>          disabled={page === 1}<br>          onClick={() =&gt; setPage((p) =&gt; Math.max(1, p - 1))}<br>        &gt;<br>          Prev<br>        &lt;/button&gt;<br>        {pageList.map((p) =&gt; (<br>          &lt;button<br>            key={p}<br>            className={`page-btn ${page === p ? &quot;active&quot; : &quot;&quot;}`}<br>            onClick={() =&gt; setPage(p)} <br>          &gt;<br>            {p}<br>          &lt;/button&gt;<br>        ))}<br>        &lt;button<br>          className=&quot;page-btn&quot;<br>          disabled={page === totalPages}<br>          onClick={() =&gt; setPage((p) =&gt; Math.min(totalPages, p + 1))}<br>        &gt;<br>          Next<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>🔍 Code Breakdown</h4><h4>✅ 1. State &amp; Constants</h4><pre>const LIMIT = 15;<br>const [result, setResult] = useState([]);<br>const [total, setTotal] = useState(0);<br>const [page, setPage] = useState(1);</pre><ul><li>LIMIT: number of items per page</li><li>result: stores products for current page</li><li>total: total number of items in API</li><li>page: current active page</li></ul><h4>✅ 2. Calculate Total Pages</h4><pre>const totalPages = Math.max(1, Math.ceil(total / LIMIT));<br>const pageList = Array.from({ length: totalPages }, (_, i) =&gt; i + 1);</pre><ul><li>Math.ceil ensures last page is included</li><li>pageList generates [1,2,3,...] dynamically</li></ul><h4>✅ 3. Fetch Data When Page Changes</h4><pre>useEffect(() =&gt; {<br>  fetchData(page);<br>}, [page]);<br><br>async function fetchData(currentPage) {<br>    const skip = (currentPage - 1) * LIMIT;<br>    const res = await fetch(<br>      `https://dummyjson.com/products?limit=${LIMIT}&amp;skip=${skip}&amp;select=title,price`<br>    );<br>    const json = await res.json();<br>    setResult(json.products || []);<br>    setTotal(json.total || 0);<br>  }</pre><p>This automatically fetches new results whenever page changes.</p><h4>✅ 4. API Call With Skip Logic</h4><pre>const skip = (currentPage - 1) * LIMIT;</pre><h4>✅ 5. Render Products</h4><pre>{result.map(item =&gt; (<br>  &lt;div key={item.id} className=&quot;pagignation-row&quot;&gt;<br>    &lt;span&gt;{item.title}&lt;/span&gt;<br>    &lt;span&gt;₹{item.price}&lt;/span&gt;<br>  &lt;/div&gt;<br>))}</pre><p>Pure UI mapping — optimized &amp; clean.</p><h4>✅ 6. Pagination Controls</h4><h4>Prev Button</h4><pre>        &lt;button<br>          className=&quot;page-btn&quot;<br>          disabled={page === 1}<br>          onClick={() =&gt; setPage((p) =&gt; Math.max(1, p - 1))}<br>        &gt;<br>         Prev<br>        &lt;/button&gt;</pre><p>Prevents going below page 1.</p><h4>Page Buttons</h4><pre>{pageList.map(p =&gt; (<br>  &lt;button<br>    key={p}<br>    className={`page-btn ${page === p ? &quot;active&quot; : &quot;&quot;}`}<br>    onClick={() =&gt; setPage(p)}<br>  &gt;<br>    {p}<br>  &lt;/button&gt;<br>))}</pre><p>Highlights current page ✅</p><h4>Next Button</h4><pre>       &lt;button<br>          className=&quot;page-btn&quot;<br>          disabled={page === totalPages}<br>          onClick={() =&gt; setPage((p) =&gt; Math.min(totalPages, p + 1))}<br>        &gt;<br>          Next<br>        &lt;/button&gt;</pre><p>Stops at last page ✅</p><p><strong>Github Link<br></strong><a href="https://github.com/ekata789123/Frontend-Practice/blob/main/MachineCoding/src/component/PagignationComponent/PagignationComponent.jsx">https://github.com/ekata789123/Frontend-Practice/blob/main/MachineCoding/src/component/PagignationComponent/PagignationComponent.jsx</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3b3c6da80f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Memory Management and Garbage Collection]]></title>
            <link>https://medium.com/@ekatakumari207/javascript-memory-management-and-garbage-collection-96671ab7e25c?source=rss-264f8034e395------2</link>
            <guid isPermaLink="false">https://medium.com/p/96671ab7e25c</guid>
            <dc:creator><![CDATA[Ekata Agrawal]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 13:40:47 GMT</pubDate>
            <atom:updated>2025-11-09T13:40:47.648Z</atom:updated>
            <content:encoded><![CDATA[<p>When we write JavaScript code, we mostly think about variables, functions, and objects — but behind the scenes, the JavaScript engine is working continuously to <strong>allocate memory</strong>, <strong>use it efficiently</strong>, and <strong>free it when no longer needed</strong>.</p><p>This automatic process is called <strong>memory management</strong>, and JavaScript does it using <strong>garbage collection</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leO9YR25oinjiqNIyV6T8Q.png" /></figure><h4>✅ What is Memory Management?</h4><p>Memory management means:</p><p><strong><em>Allocating memory when data is created and cleaning (freeing) memory when that data is no longer needed.</em></strong></p><p>JavaScript does this automatically — you don’t manually free memory.</p><h4>🧱 Memory Areas in JavaScript</h4><p>JavaScript manages memory in two main areas:</p><p>✅<strong> Stack</strong></p><p>Used to store:</p><ul><li>Primitive values (Numbers, Strings, Booleans, null, undefined, Symbol, BigInt)</li><li>Function call information (Execution context frames)</li><li>References (pointers) to objects in the heap</li></ul><p><strong>Characteristics:</strong></p><ul><li>Small</li><li>Fast access</li><li>Automatically managed with function execution order (LIFO)</li></ul><p><strong>Example</strong></p><pre>let a = 10; // primitive stored in the stack</pre><p><strong>✅ Heap</strong></p><p>Used to store dynamic &amp; complex data like:</p><ul><li>Objects</li><li>Arrays</li><li>Functions</li><li>Closures (inner function + referenced variables)</li></ul><p><strong>Characteristics:</strong></p><ul><li>Large, flexible memory space</li><li>Slower access compared to stack</li><li>Stores values that do not have fixed size</li></ul><p><strong>Example</strong></p><pre>let obj = { x: 20 }; // object stored in the heap, reference stored in stack</pre><h4>🚀 Example — Stack vs Heap in Action</h4><pre>function foo() {<br>  let x = 10;         // primitive -&gt; stack<br>  let obj = {y: 20};  // object -&gt; heap<br>  return obj;<br>}<br>let result = foo();<br>result = null; // object becomes unreachable -&gt; removed by garbage collector</pre><h4>🧹 Garbage Collection (GC)</h4><p>JavaScript uses <strong>automatic garbage collection</strong>.</p><p><strong>The key idea:</strong></p><p><em>If no variable points to an object, it becomes unreachable and is removed from memory. </em>This is called <strong>reachability</strong>.</p><h4>⚙️ How Garbage Collection Works — Mark &amp; Sweep Algorithm</h4><p>JS uses a common algorithm called <strong>Mark-and-Sweep</strong>:</p><ol><li><strong>Mark</strong> all values that can still be reached (in use)</li><li><strong>Sweep</strong> and remove everything else (unused / unreachable)</li></ol><h4>⚠️ Common Causes of Memory Leaks in JavaScript</h4><p>Memory leaks occur when memory that is no longer needed is not released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzMDVGODPACw8QGPLdA7Yg.png" /></figure><p><strong>✅ 1. Accidental Global Variables</strong></p><p>Happens when you assign a variable without let, const, or var.</p><pre>x = 10; // ❌ Creates global leak<br>let x = 10; // ✅ Correct</pre><p><strong>✅ 2. Uncleared Timers (</strong><strong>setInterval, </strong><strong>setTimeout)</strong></p><p>Timers continue running and holding memory if not cleared.</p><pre>const timer = setInterval(() =&gt; console.log(&quot;running&quot;), 1000);<br>// ❌ If never cleared → memory leak<br>clearInterval(timer); // ✅ Clear when no longer needed</pre><p><strong>✅ 3. Unremoved Event Listeners</strong></p><p>Event listeners hold references to DOM elements and callbacks.</p><pre>button.addEventListener(&quot;click&quot;, handler);<br>// ❌ If element removed without removing listener → leak<br>button.removeEventListener(&quot;click&quot;, handler); // ✅</pre><p><strong>✅ 4. Closures Holding Unused References</strong></p><p>Functions can unintentionally keep large data in memory.</p><pre>function createBigClosure() {<br>  const bigData = new Array(1000000).fill(&quot;data&quot;); // huge memory<br>  return function () {<br>    console.log(bigData); // ❌ Still referenced → not garbage collected<br>  };<br>}</pre><h4><strong>✅ Best Practices to Avoid Memory Leaks</strong></h4><ul><li>Always use let / const, not implicit globals</li><li>Clear intervals &amp; timeouts</li><li>Remove event listeners when done</li><li>Set unused references to null</li><li>Avoid holding large data in closures unnecessarily</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96671ab7e25c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>