<?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 Farhan Asghar on Medium]]></title>
        <description><![CDATA[Stories by Farhan Asghar on Medium]]></description>
        <link>https://medium.com/@farhanbajwa46?source=rss-c5f5764daa0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lI7GM9U4xMbh-lLKz7lcSg.jpeg</url>
            <title>Stories by Farhan Asghar on Medium</title>
            <link>https://medium.com/@farhanbajwa46?source=rss-c5f5764daa0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:50:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farhanbajwa46/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Think About Caching in Next.js Apps]]></title>
            <link>https://medium.com/@farhanbajwa46/how-to-think-about-caching-in-next-js-apps-8f680d9b72e5?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f680d9b72e5</guid>
            <category><![CDATA[rtk-query]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 08:39:53 GMT</pubDate>
            <atom:updated>2026-06-19T10:12:36.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwnBlPYJJDt4YlWUhtm54A.png" /></figure><p>A few years ago, “caching” in a web app meant one or two things: maybe a Cache-Control header, maybe Redis in front of your database. You could hold the whole picture in your head.</p><p>That world is gone. A modern Next.js app has caching happening in at least <em>eight</em> different places at once and most of them are turned on by default, invisible, and don’t know the others exist. The browser is caching. The CDN is caching. The Next.js Router is caching on the client. The server is memoizing requests, caching data, and caching whole routes. Your data-fetching library is caching. And underneath all of it, your database and Redis are caching too.</p><p>Here’s the thing nobody tells you when you start: <strong>caching is not a performance optimization you bolt on at the end. It’s an architectural decision you make at the beginning.</strong> If you treat it as an afterthought, you don’t get a slow app — you get a <em>correct-looking</em> app that occasionally serves a user someone else’s data, shows a price that changed an hour ago, or renders a “logged out” navbar to a logged-in user. And those bugs are the worst kind: intermittent, environment-dependent, and nearly impossible to reproduce locally.</p><p>This article is the mental map I wish I’d had before my first serious project. The goal isn’t to memorize every API. It’s to build a model of <em>where</em> data can get stuck so that when something goes stale, you know which drawer to open.</p><h3>The one idea that makes all of this tractable</h3><blockquote><em>Caching is state management across time, distributed across layers you don’t fully control.</em></blockquote><p>Read that again, because it reframes the whole problem. Every cache is just a copy of some data, frozen at a moment, living somewhere along the path between your database and the user’s eyeballs. A “caching bug” is almost never a bug in a cache. It’s a mismatch between <strong>how fresh you assumed the data was</strong> and <strong>how fresh it actually is</strong> at some layer.</p><p>So the real skill isn’t knowing the APIs. It’s being able to answer, for any piece of data on your screen: <em>which layers is this sitting in right now, and what would it take to refresh each one?</em></p><p>To answer that, you need the map.</p><h3>The map: a request’s journey</h3><p>Think of data flowing through five zones. Each zone can hold a copy.</p><pre>        ┌──────────────────────────────────────────────┐<br>        │                 THE BROWSER                    │<br>        │   bfcache · HTTP cache · Service Worker        │<br>        └──────────────────────────────────────────────┘<br>                            ↓  ↑<br>        ┌──────────────────────────────────────────────┐<br>        │             THE CLIENT APP (JS)                │<br>        │   Next.js Router Cache · RTK Query / SWR        │<br>        └──────────────────────────────────────────────┘<br>                            ↓  ↑<br>        ┌──────────────────────────────────────────────┐<br>        │                 EDGE / CDN                     │<br>        │   Static assets · Full HTTP responses          │<br>        └──────────────────────────────────────────────┘<br>                            ↓  ↑<br>        ┌──────────────────────────────────────────────┐<br>        │              THE NEXT.JS SERVER                │<br>        │   Request Memoization · Data Cache              │<br>        │   Full Route Cache · &#39;use cache&#39; (PPR)          │<br>        └──────────────────────────────────────────────┘<br>                            ↓  ↑<br>        ┌──────────────────────────────────────────────┐<br>        │             THE BACKEND / ORIGIN               │<br>        │   Redis / app cache · DB query cache            │<br>        └──────────────────────────────────────────────┘</pre><p>When you debug a stale-data issue, you walk this stack top to bottom (or bottom to top) and ask “is the old value living <em>here</em>?” until you find it. Let’s go through each zone the way I think about it in practice.</p><h3>Zone 1 The browser</h3><p>This is the layer engineers forget exists, because it’s not in your codebase.</p><p><strong>The HTTP cache.</strong> The classic one. Driven by response headers — Cache-Control, ETag, Expires. If you set Cache-Control: max-age=3600 on an API response, the browser will happily serve a one-hour-old copy without ever asking your server. Powerful, and a great way to ship a bug that only some users see (the ones whose cache hasn&#39;t expired).</p><p><strong>The back/forward cache (bfcache).</strong> When a user hits “back,” modern browsers often restore the <em>entire page from memory</em> — DOM, JavaScript heap, scroll position — without re-running anything. This is fantastic for UX and occasionally infuriating: a user logs out, hits back, and sees the logged-in page because nothing re-executed. If you have state that <em>must</em> re-validate on navigation, you handle it with a pageshow listener checking event.persisted.</p><p><strong>Service Workers</strong> (if you have a PWA) add yet another programmable cache. Most apps don’t, so I’ll leave it there.</p><p>The mental note for Zone 1: <em>you don’t control when this clears.</em> You can only influence it with headers and event hooks. So be conservative with Cache-Control on anything personalized or fast-moving.</p><h3>Zone 2 The client app</h3><p>Now we’re in JavaScript you wrote (or imported).</p><p><strong>The Next.js Router Cache.</strong> This is a client-side, in-memory store of the React Server Component payloads for routes the user has visited or prefetched. Its entire job is to make navigation feel instant — click a link, and if the segment is in the Router Cache, no server round-trip happens.</p><p>This is also where a <em>lot</em> of “I mutated the data but the page didn’t update” confusion comes from. You ran a Server Action, the database changed, but the user navigates back to a page whose RSC payload is still sitting in the client Router Cache. The fix is to invalidate it explicitly — revalidatePath / revalidateTag from a Server Action, or router.refresh() on the client.</p><p>One honest caveat: the <em>lifetime</em> of this cache (the staleTimes config) has changed meaningfully across Next.js versions — the defaults in v13/14 were more aggressive than what you get today, where dynamically-rendered routes are barely cached client-side by default. Don&#39;t memorize a number; know that it&#39;s short, configurable in next.config, and version-dependent. Verify against the version you&#39;re actually running.</p><p><strong>Your data library — RTK Query, TanStack Query, SWR.</strong> If you’re fetching in Client Components, you almost certainly have one of these, and each maintains its <em>own</em> cache with its <em>own</em> invalidation model. RTK Query’s is tag-based and genuinely excellent once you commit to it:</p><pre>// Define what each endpoint provides and invalidates<br>const api = createApi({<br>  endpoints: (build) =&gt; ({<br>    getPosts: build.query({<br>      query: () =&gt; &quot;posts&quot;,<br>      providesTags: [&quot;Posts&quot;],<br>    }),<br>    addPost: build.mutation({<br>      query: (body) =&gt; ({ url: &quot;posts&quot;, method: &quot;POST&quot;, body }),<br>      // This single line keeps the cache honest:<br>      invalidatesTags: [&quot;Posts&quot;],<br>    }),<br>  }),<br>});</pre><p>The lesson that took me too long to internalize: <strong>pick one source of truth per piece of data.</strong> If the same list of posts is fetched once by the server (and cached there) <em>and</em> again by RTK Query on the client (and cached there), you now have two caches with two clocks and no coordination. That’s a stale-data factory. Decide whether a given dataset is “server-owned” or “client-owned” and don’t let it live in both.</p><h3>Zone 3 The edge / CDN</h3><p>For static assets — JS bundles, images, fonts — this is a solved problem and you mostly don’t think about it. Next.js fingerprints filenames, so a new build produces new URLs and the CDN cache invalidates itself naturally.</p><p>The interesting case is when the CDN caches <strong>full HTML/RSC responses</strong> for your statically-rendered routes. This is where Next.js’s edge story shines — a fully static page can be served from a CDN edge node geographically close to the user, never touching your origin. The trap: a CDN cache and your server’s Data Cache are <em>different layers</em>. Purging one does not purge the other. I’ve watched a team purge the Data Cache, confirm the origin was serving fresh data, and still field “it’s stale!” reports for an hour — because the CDN edge was happily serving its own copy. When something is wrong at the edge, you need an edge-level purge, full stop.</p><h3>Zone 4 The Next.js server (where the real complexity lives)</h3><p>This is the zone that has changed the most, so let me first clear up the single biggest source of outdated advice on the internet.</p><p><strong>fetch is no longer cached by default.</strong> In the early App Router days (v13/14), every fetch you wrote was silently cached forever unless you opted out. This caused enormous confusion. Since v15, the default flipped: fetch requests are <strong>not</strong> cached unless you explicitly ask. If you read a tutorial that says &quot;Next.js caches all your fetches automatically,&quot; it&#39;s describing a world that no longer exists.</p><p>With that out of the way, here are the server-side layers, from shortest-lived to longest:</p><ol><li><strong>Request Memoization.</strong> Within a <em>single render pass</em>, if you call the same fetch (same URL + options) in five different components, it executes once. This is React&#39;s deduplication — it exists so you can fetch the same data wherever you need it without prop-drilling, and not pay for it five times. It&#39;s ephemeral: gone the moment the render finishes. For non-fetch data sources (a database client, a CMS SDK), you opt in with React&#39;s cache():</li></ol><pre>import { cache } from &quot;react&quot;;<br><br>// Now calling getUser(42) twice in one render hits the DB once.<br>export const getUser = cache(async (id: number) =&gt; {<br>  return db.user.findUnique({ where: { id } });<br>});</pre><p>The classic mistake here: thinking cache() is <em>persistent</em>. It is not. It&#39;s per-request memoization. Using it to &quot;cache&quot; a DB result across requests does nothing — the result is thrown away after each render.</p><p><strong>2. The Data Cache.</strong> This is the persistent one. It stores fetch/computation results across requests, across users, and even across deployments, until you revalidate. This is your workhorse for “data that’s the same for everyone and changes infrequently” — a marketing page’s content, a product catalog, a blog.</p><p><strong>3. The Full Route Cache.</strong> At build time, statically-renderable routes get their HTML + RSC payload baked and stored. Subsequent requests serve the baked version with zero rendering. This is what makes a static Next.js page absurdly fast. It clears on redeploy.</p><h3>The modern model: Cache Components and use cache</h3><p>Here’s where it’s worth knowing what’s current, because Next.js 16 introduced a genuinely different philosophy. Instead of caching being an implicit default you fight against, the new <strong>Cache Components</strong> model (enabled with cacheComponents: true) makes caching <em>explicit and opt-in</em> via the use cache directive.</p><pre>// next.config.ts<br>const nextConfig = { cacheComponents: true };<br>export default nextConfig;</pre><pre>import { cacheLife, cacheTag } from &quot;next/cache&quot;;<br><br>// Cache an entire component&#39;s output<br>async function BlogPosts() {<br>  &quot;use cache&quot;;<br>  cacheLife(&quot;hours&quot;);   // revalidate roughly hourly<br>  cacheTag(&quot;posts&quot;);    // tag it for targeted invalidation<br><br>  const res = await fetch(&quot;https://api.example.com/blog&quot;);<br>  const posts = await res.json();<br>  return &lt;PostList posts={posts} /&gt;;<br>}</pre><p>The mental model is clean and, in my opinion, the right one: <strong>anything not explicitly marked </strong><strong>use cache is assumed dynamic.</strong> If a component reads request-time data (cookies, headers, search params) or does something non-deterministic, you wrap it in &lt;Suspense&gt; and it <em>streams</em> at request time instead of caching:</p><pre>import { Suspense } from &quot;react&quot;;<br><br>export default function Page() {<br>  return (<br>    &lt;&gt;<br>      &lt;BlogPosts /&gt;                          {/* cached, in the static shell */}<br>      &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>        &lt;UserGreeting /&gt;                      {/* per-user, streams in live */}<br>      &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>This is <strong>Partial Prerendering (PPR)</strong>: one page, with a cached static shell sent instantly and dynamic “holes” streamed in per request. It’s the default behavior once Cache Components is on, and it dissolves the old “is this page static or dynamic?” binary — a single page can be both.</p><p>Invalidation in this model is tag-driven and immediate. A Server Action mutates data and calls updateTag(&quot;posts&quot;), and the next visitor sees fresh content:</p><pre>async function createPost(formData: FormData) {<br>  &quot;use server&quot;;<br>  await db.post.create({ data: { title: formData.get(&quot;title&quot;) } });<br>  updateTag(&quot;posts&quot;); // expires the &#39;posts&#39; cache everywhere it lives on the server<br>}</pre><p>A practical note for serverless deployments: use cache stores entries in-memory by default, and in serverless that memory doesn&#39;t survive between requests so a cache can quietly re-evaluate every time. For durable, shared caching across instances, there&#39;s a remote variant (&#39;use cache: remote&#39;). Worth knowing before you assume your cache is working in production when it&#39;s really cold every request.</p><h3>Zone 5 The backend / origin</h3><p>Finally, behind Next.js, your own infrastructure: a Redis or in-process application cache for expensive computations, and the database’s own query cache. As a backend engineer this is probably your home turf, so I won’t belabor it. The one cross-cutting point: <strong>this layer’s invalidation has to be coordinated with the layers above it.</strong> If you bust your Redis cache but the Next.js Data Cache still holds the old value, the user sees old data. Caches don’t cascade their invalidations for free — you wire that up.</p><h3>The framework: how to decide, up front</h3><p>Now the payoff. Before you write a single fetch, run each meaningful piece of data through five questions. This is the &quot;mind map&quot; — do it on paper, in a design doc, whatever <em>at the start</em>.</p><p><strong>1. Who owns this data, and who can see it?</strong> Is it global (same for every user) or personalized (per-user, per-session)? This is the single most important question, because <strong>personalized data cached at a shared layer is a security incident</strong>, not a perf bug. Global data can be cached aggressively and far from the user. Personalized data must either skip shared caches entirely or be keyed by user.</p><p><strong>2. How fresh does it actually need to be?</strong> Be honest, and push back on “real-time.” A stock ticker needs seconds. A product price needs minutes. A blog post or marketing copy can be hours or days stale and nobody notices. The acceptable staleness <em>is</em> your cache lifetime. Most data tolerates far more staleness than stakeholders claim.</p><p><strong>3. How does it get invalidated?</strong> Time-based (it just expires) or event-based (a mutation must purge it)? Event-based is where tags earn their keep. Decide your tagging scheme early and make it *specific* — `post:id‘,‘user:{id}`, `user: id‘,‘user:{id}`, not one giant `”all”` tag you nuke on every write, which throws away every benefit of caching in the first place.</p><p><strong>4. What’s the blast radius if it’s stale?</strong> A stale “related articles” sidebar is fine. A stale account balance or inventory count is a real problem. The cost of being wrong tells you how conservative to be. High blast radius → cache less, invalidate harder.</p><p><strong>5. Which layer is the <em>right</em> layer?</strong> Cache global, slow-changing data as close to the user as you can (CDN / Full Route Cache). Cache per-user data on the server keyed by user, or stream it. Cache nothing for genuinely real-time data — use Suspense and accept the request-time cost.</p><p>From those five answers, a default posture falls out almost mechanically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*LWPEPtDWNgTZQQV7xJP9_w.png" /></figure><h3>Debugging stale data, the disciplined way</h3><p>When (not if) something serves stale data, resist the urge to disable caching everywhere. That’s how you turn a fast app into a slow one and learn nothing. Instead, walk the map:</p><ol><li><strong>Reproduce in production conditions.</strong> next dev renders dynamically and hides most caching. Use next build &amp;&amp; next start. Half of all &quot;caching bugs&quot; are really &quot;I only tested in dev.&quot;</li><li><strong>Walk the stack and locate the stale copy.</strong> Is it the browser (try incognito / hard refresh)? The CDN (check response headers for cache-hit markers)? The Router Cache (does a hard nav fix it but a soft nav doesn’t)? The server Data Cache? The origin? Find <em>which drawer</em> holds the old value.</li><li><strong>Fix the invalidation, not the caching.</strong> The bug is almost never “this layer caches.” It’s “this layer caches and nothing told it to refresh.” Add the missing tag, the missing revalidate, the missing router.refresh().</li></ol><p>Identify the layer holding the stale data rather than carpet-bombing every cache. That single habit will save you more time than any API knowledge.</p><h3>The takeaway</h3><p>The proliferation of caching layers in modern Next.js isn’t accidental complexity each layer solves a real problem at a real point in the request’s journey. But because they’re independent, default-on, and uncoordinated, the only way to stay sane is to <strong>decide your strategy before you build, not after it breaks.</strong></p><p>You don’t need to memorize every directive. You need the map five zones, data can get stuck in any of them and the five questions you run every piece of data through. Do that at the start, write it down, and the difference is night and day: caching stops being the spooky layer that randomly serves wrong data, and becomes what it should be a deliberate, debuggable performance asset.</p><p>Cache on purpose. Invalidate on purpose. The rest is just APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f680d9b72e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[After 1 Year Running MongoDB Atlas in Production (10K Users), Here Are 7 Mistakes That Cost Me…]]></title>
            <link>https://medium.com/@farhanbajwa46/after-1years-running-mongodb-atlas-in-production-10k-users-here-are-7-mistakes-that-cost-me-42791a2551ae?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/42791a2551ae</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 13:02:45 GMT</pubDate>
            <atom:updated>2026-03-18T13:03:19.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>After 1 Year Running MongoDB Atlas in Production (10K Users), Here Are 7 Mistakes That Cost Me Money and Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2r6KxWerP4NQpms-Mea6RA.png" /></figure><p>I’ve been running a Node.js platform on MongoDB Atlas for over two years now.</p><p>No team.<br>No DBA.<br>Just me, figuring things out as I go.</p><p>Things worked… until they didn’t.</p><p>Over time, small decisions turned into performance bottlenecks, higher costs, and a lot of late-night debugging sessions. Looking back, most of these mistakes were avoidable.</p><p>Here are the 7 biggest ones — and what I’d do differently today.</p><h3>1. Not Using Compound Indexes from Day One</h3><p>In the beginning, I created indexes the way most beginners do — one field at a time.</p><p>It <em>felt</em> right.</p><p>But my queries didn’t agree.</p><p>I was frequently querying on multiple fields together, yet MongoDB had to scan far more data than necessary. Queries that should’ve taken under 10ms were taking 150–200ms.</p><p>The fix was embarrassingly simple:</p><pre>{ userId: 1, createdAt: -1 }</pre><p>One compound index dropped my most frequent query from <strong>~180ms to 3ms</strong>.</p><p>Lesson: Index for how you <em>query</em>, not how your data looks.</p><h3>2. Treating MongoDB Like SQL (Overusing $lookup)</h3><p>Coming from a SQL background, I normalized everything.</p><p>I had 4–5 collections where 2 would’ve been enough. Every API request triggered multiple $lookup operations.</p><p>It worked — but it was slow.</p><p>Once I embraced MongoDB’s strength (embedding data for hot paths), things changed dramatically.</p><ul><li>Fewer joins</li><li>Simpler queries</li><li>Faster responses</li></ul><p>After denormalizing key parts of my data, response times dropped by <strong>~70%</strong>.</p><p>👉 Lesson: MongoDB rewards <strong>read-optimized data models</strong>, not relational purity.</p><h3>3. Ignoring Connection Pool Tuning</h3><p>For a long time, I just used the default connection settings.</p><p>Everything seemed fine… until traffic grew.</p><p>Then came:</p><ul><li>Random timeouts</li><li>Hanging requests</li><li>Unpredictable latency</li></ul><p>The issue? My connection pool was too small.</p><p>After tuning:</p><pre>maxPoolSize: 50<br>minPoolSize: 10</pre><p>…and adding retry logic, stability improved immediately.</p><p>👉 Lesson: Defaults are not designed for your workload.</p><h3>4. Doing Analytics in Node.js Instead of Aggregation Pipelines</h3><p>This one hurt.</p><p>I was pulling large datasets (hundreds of thousands of documents) into Node.js and processing them in memory.</p><p>It worked… until it didn’t.</p><ul><li>High memory usage</li><li>Slow responses</li><li>Occasional crashes</li></ul><p>Moving the same logic into MongoDB aggregation pipelines changed everything:</p><ul><li>~90% less memory usage</li><li>~5x faster queries</li></ul><p>👉 Lesson: Let the database do the heavy lifting.</p><h3>5. Using $regex for Search Instead of Atlas Search</h3><p>I initially implemented search using $regex.</p><p>It was simple — but dangerously inefficient.</p><p>Every search triggered a <strong>full collection scan</strong>.</p><p>As data grew, search became painfully slow.</p><p>Switching to <strong>Atlas Search</strong> with a proper text index made results almost instant.</p><p>The UX improvement alone was worth it.</p><p>👉 Lesson: $regex is not search—it&#39;s a fallback.</p><h3>6. Manually Cleaning Temporary Data (Instead of TTL Indexes)</h3><p>For things like:</p><ul><li>OTPs</li><li>Sessions</li><li>Temporary tokens</li></ul><p>…I wrote cron jobs to clean up expired data.</p><p>It worked, but it added unnecessary complexity and occasional bugs.</p><p>Then I discovered TTL indexes.</p><pre>{ expiresAt: 1 }</pre><p>That’s it.</p><p>MongoDB handled cleanup automatically.</p><p>No cron jobs. No extra services.</p><p>👉 Lesson: If data expires, let the database handle it.</p><h3>7. Ignoring Atlas Performance Advisor</h3><p>MongoDB Atlas literally tells you:</p><blockquote><em>“Hey, create this index.”</em></blockquote><p>And I ignored it for months.</p><p>I was debugging slow queries manually, guessing at optimizations, and wasting time — while Atlas already had the answers.</p><p>Once I started paying attention, performance improvements became much more straightforward.</p><p>👉 Lesson: Don’t fly blind — use the tools available.</p><h3>The Biggest Mindset Shift</h3><p>The real turning point wasn’t a specific optimization.</p><p>It was this realization:</p><blockquote><strong><em>MongoDB is not a SQL database with JSON syntax.</em></strong></blockquote><p>The moment I stopped thinking in joins and started thinking in <strong>documents and access patterns</strong>, everything clicked.</p><h3>Final Thoughts</h3><p>If you’re running MongoDB in production — especially as a solo developer — you’re going to make mistakes.</p><p>That’s part of the process.</p><p>But if I could go back, I’d focus on just three things early:</p><ul><li>Model data around <strong>read patterns</strong></li><li>Invest in <strong>indexes early</strong></li><li>Let MongoDB handle what it’s good at (aggregation, TTL, search)</li></ul><p>If you’ve worked with MongoDB in production, I’d love to hear:</p><p><strong>What’s one mistake that cost you the most?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42791a2551ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Modeling Design Patterns in MongoDB]]></title>
            <link>https://medium.com/@farhanbajwa46/data-modeling-design-patterns-in-mongodb-cc9e183c6636?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9e183c6636</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[data-modeling]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 06:50:32 GMT</pubDate>
            <atom:updated>2026-01-24T06:50:32.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTcS6R1R3KgoqgGbqrLJXw.png" /></figure><p>A Practical Guide to Schema Design for Performance and Scale</p><p>When working with MongoDB, <strong>schema design is not an afterthought</strong> — it <em>is</em> the architecture. Unlike relational databases where schemas are rigid and normalized, MongoDB gives you flexibility. That flexibility is powerful, but dangerous if misused.</p><p>Great MongoDB applications don’t just “store JSON.” They use <strong>intentional data modeling patterns</strong> that align with:</p><ul><li>access patterns</li><li>read vs write frequency</li><li>data growth</li><li>indexing behavior</li><li>scalability requirements</li></ul><p>In this article, we’ll walk through <strong>core MongoDB data modeling design patterns</strong>, explain <em>why</em> they exist, <em>when</em> to use them, and <em>what trade-offs</em> come with each.</p><h3>Why MongoDB Schema Design Is Different</h3><p>In MongoDB:</p><ul><li><strong>Documents are read as a whole</strong></li><li><strong>Joins are expensive</strong> compared to relational DBs</li><li><strong>Indexes work best on predictable structures</strong></li><li><strong>Document growth matters</strong> (16MB limit, padding, fragmentation)</li></ul><p>So instead of asking <em>“How do I normalize this?”</em>, you should ask:</p><blockquote><em>“How will my application read and write this data most often?”</em></blockquote><p>Design patterns exist to answer exactly that question.</p><h3>1. Bucket Pattern</h3><p><strong>Best for:</strong> Time-series, IoT, logs, streaming data</p><h4>Problem</h4><p>High-frequency data creates <strong>millions of tiny documents</strong>, killing performance and indexes.</p><h4>Solution</h4><p>Group related records into <strong>time-based buckets</strong>.</p><h4>Example: IoT Temperature Sensor</h4><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;50bf1fbbbcf86cd799439051&quot;),<br>  &quot;sensor_id&quot;: &quot;S123&quot;,<br>  &quot;start_date&quot;: ISODate(&quot;2023-10-03T08:00:00Z&quot;),<br>  &quot;end_date&quot;: ISODate(&quot;2023-10-03T08:59:59Z&quot;),<br>  &quot;readings&quot;: [<br>    { &quot;value&quot;: 22, &quot;timestamp&quot;: ISODate(&quot;2023-10-03T08:00:01Z&quot;) },<br>    { &quot;value&quot;: 23, &quot;timestamp&quot;: ISODate(&quot;2023-10-03T08:01:10Z&quot;) }<br>  ]<br>}</pre><h3>Why It Works</h3><ul><li>Fewer documents → better index efficiency</li><li>Faster range queries</li><li>Reduced storage overhead</li></ul><h3>Trade-offs</h3><ul><li>Document size can grow quickly</li><li>Updates may cause document relocation</li></ul><p><strong>Rule of thumb:</strong> Bucket by time <em>or</em> count, never both uncontrolled.</p><h3>2. Attribute Pattern</h3><p><strong>Best for:</strong> Products, catalogs, sparse or variable fields</p><h4>Problem</h4><p>Large documents with hundreds of optional fields cause:</p><ul><li>sparse indexes</li><li>inefficient queries</li><li>rigid schemas</li></ul><h4>Solution</h4><p>Convert variable fields into a <strong>name-value array</strong>.</p><p>Example: E-commerce Product</p><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;50cf1fcbcf86cd799439061&quot;),<br>  &quot;product_name&quot;: &quot;Smartphone XYZ&quot;,<br>  &quot;category&quot;: &quot;Electronics&quot;,<br>  &quot;attributes&quot;: [<br>    { &quot;name&quot;: &quot;color&quot;, &quot;value&quot;: &quot;black&quot; },<br>    { &quot;name&quot;: &quot;storage&quot;, &quot;value&quot;: &quot;128GB&quot; },<br>    { &quot;name&quot;: &quot;camera&quot;, &quot;value&quot;: &quot;12MP&quot; }<br>  ]<br>}</pre><h3>Why It Works</h3><ul><li>Easier indexing on attributes.name</li><li>Cleaner schema evolution</li><li>Better support for filtering and faceting</li></ul><h3>Trade-offs</h3><ul><li>Queries are slightly more complex</li><li>Validation logic moves to application level</li></ul><h3>3. Polymorphic Pattern</h3><p><strong>Best for:</strong> Multiple document types with shared identity</p><h4>Problem</h4><p>Different entities share most fields but have small differences.</p><h4>Solution</h4><p>Store them in <strong>one collection</strong>, differentiate by type.</p><h4>Example: Medical Records</h4><pre>{<br>  &quot;patient_id&quot;: &quot;P45678&quot;,<br>  &quot;type&quot;: &quot;surgical&quot;,<br>  &quot;surgery_name&quot;: &quot;Appendectomy&quot;,<br>  &quot;surgeon&quot;: &quot;Dr. Smith&quot;<br>}</pre><pre>{<br>  &quot;patient_id&quot;: &quot;P45678&quot;,<br>  &quot;type&quot;: &quot;dental&quot;,<br>  &quot;procedure&quot;: &quot;Tooth extraction&quot;,<br>  &quot;dentist&quot;: &quot;Dr. White&quot;<br>}</pre><h3>Why It Works</h3><ul><li>Fewer collections</li><li>Unified indexing</li><li>Easier analytics across types</li></ul><h3>Trade-offs</h3><ul><li>Validation complexity</li><li>Requires discipline with indexes</li></ul><h3>4. Schema Versioning Pattern</h3><p><strong>Best for:</strong> Long-lived applications</p><h4>Problem</h4><p>Schemas change, but old documents don’t magically update.</p><h4>Solution</h4><p>Add an explicit schema_version.</p><h4>Example</h4><pre>{<br>  &quot;username&quot;: &quot;alice123&quot;,<br>  &quot;email&quot;: &quot;alice@email.com&quot;,<br>  &quot;schema_version&quot;: 1<br>}</pre><pre>{<br>  &quot;username&quot;: &quot;bob456&quot;,<br>  &quot;email&quot;: &quot;bob@email.com&quot;,<br>  &quot;contact&quot;: {<br>    &quot;phone&quot;: &quot;+1234567890&quot;<br>  },<br>  &quot;schema_version&quot;: 2<br>}</pre><h3>Why It Works</h3><ul><li>Backward compatibility</li><li>Safe gradual migrations</li><li>Easier debugging</li></ul><p><strong>Pro tip:</strong> Migrate on read, not all at once.</p><h3>5. Extended Reference Pattern</h3><p><strong>Best for:</strong> Read-heavy systems with frequent lookups</p><h4>Problem</h4><p>Repeated $lookup operations slow down reads.</p><h4>Solution</h4><p><strong>Duplicate frequently used fields</strong> from referenced documents.</p><h4>Example: Orders with Product Snapshot</h4><pre>{<br>  &quot;products&quot;: [<br>    {<br>      &quot;product_id&quot;: ObjectId(&quot;50if1ghbbcf86cd799439111&quot;),<br>      &quot;product_name&quot;: &quot;Laptop ABC&quot;,<br>      &quot;price&quot;: 1200<br>    }<br>  ]<br>}</pre><h4>Why It Works</h4><ul><li>Faster reads</li><li>Fewer joins</li><li>Better cache locality</li></ul><h4>Trade-offs</h4><ul><li>Data duplication</li><li>Requires sync strategy</li></ul><h3>6. Approximation Pattern</h3><p><strong>Best for:</strong> Counters, analytics, real-time dashboards</p><h4>Problem</h4><p>Exact calculations are expensive at scale.</p><h4>Solution</h4><p>Store <strong>approximate or cached values</strong>.</p><h4>Example</h4><pre>{<br>  &quot;title&quot;: &quot;Understanding MongoDB Patterns&quot;,<br>  &quot;approximate_views&quot;: 5000,<br>  &quot;exact_views&quot;: 5123<br>}</pre><h3>Why It Works</h3><ul><li>Massive performance boost</li><li>Acceptable error margin</li></ul><p><strong>Perfect is the enemy of fast.</strong></p><h3>7. Computed Pattern</h3><p><strong>Best for:</strong> Aggregation-heavy reads</p><h4>Problem</h4><p>Repeated aggregations slow down hot paths.</p><h4>Solution</h4><p>Precompute results.</p><h4>Example</h4><pre>{<br>  &quot;product_name&quot;: &quot;Laptop XYZ&quot;,<br>  &quot;computed_avg_rating&quot;: 4.5,<br>  &quot;total_reviews&quot;: 200<br>}</pre><h4>Why It Works</h4><ul><li>O(1) reads</li><li>Predictable performance</li></ul><h4>Trade-offs</h4><ul><li>More complex writes</li><li>Requires consistency logic</li></ul><h3>8. Outlier Pattern</h3><p><strong>Best for:</strong> Mostly uniform data with rare exceptions</p><h4>Problem</h4><p>Designing schema for edge cases bloats every document.</p><h4>Solution</h4><p>Separate <strong>common case</strong> from <strong>exceptions</strong>.</p><pre>{<br>  &quot;student_name&quot;: &quot;John&quot;,<br>  &quot;standard_courses&quot;: [&quot;Math&quot;, &quot;Science&quot;],<br>  &quot;new_courses&quot;: [&quot;Advanced Astrophysics&quot;]<br>}</pre><h3>Why It Works</h3><ul><li>Cleaner documents</li><li>Better cache efficiency</li></ul><h3>9. Pre-allocation Pattern</h3><p><strong>Best for:</strong> Known, fixed-structure data</p><h4>Problem</h4><p>Frequent inserts cause fragmentation and overhead.</p><h4>Solution</h4><p>Pre-create document structure.</p><h4>Example</h4><pre>{<br>  &quot;city&quot;: &quot;New York&quot;,<br>  &quot;month&quot;: &quot;October&quot;,<br>  &quot;daily_data&quot;: [<br>    { &quot;day&quot;: 1, &quot;temperature&quot;: null },<br>    { &quot;day&quot;: 2, &quot;temperature&quot;: null }<br>  ]<br>}</pre><h4>Why It Works</h4><ul><li>Faster writes</li><li>Predictable growth</li></ul><h3>10. Subset Pattern</h3><p><strong>Best for:</strong> Large arrays with partial access</p><h4>Problem</h4><p>Large embedded arrays are expensive to read.</p><h4>Solution</h4><p>Store <strong>only frequently accessed subset</strong>.</p><h4>Example</h4><pre>{<br>  &quot;title&quot;: &quot;Moby Dick&quot;,<br>  &quot;subset_reviews&quot;: [<br>    { &quot;user&quot;: &quot;Alice&quot;, &quot;rating&quot;: 5 },<br>    { &quot;user&quot;: &quot;Bob&quot;, &quot;rating&quot;: 4 }<br>  ]<br>}</pre><h3>11. Tree Pattern</h3><p><strong>Best for:</strong> Hierarchical data</p><h4>Example: Comment Thread</h4><pre>{<br>  &quot;text&quot;: &quot;Original comment&quot;,<br>  &quot;replies&quot;: [<br>    {<br>      &quot;text&quot;: &quot;Reply&quot;,<br>      &quot;replies&quot;: [<br>        { &quot;text&quot;: &quot;Nested reply&quot; }<br>      ]<br>    }<br>  ]<br>}</pre><h3>Alternatives</h3><ul><li>Parent references</li><li>Materialized paths</li><li>Array of ancestors</li></ul><p>Choose based on read depth vs write frequency.</p><h3>Final Thoughts</h3><p>MongoDB doesn’t punish bad schemas immediately — but <strong>it will punish them at scale</strong>.</p><p>The best MongoDB schema:</p><ul><li>matches your query patterns</li><li>minimizes joins</li><li>respects document growth</li><li>embraces controlled duplication</li></ul><p>Use these patterns as <strong>building blocks</strong>, not rules. Real systems often combine multiple patterns in a single model.</p><p>If you design for how your app <em>actually works</em>, MongoDB will fly 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc9e183c6636" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minium Height Trees — Leetcode 310]]></title>
            <link>https://medium.com/@farhanbajwa46/minium-height-trees-leetcode-310-ce09870a81eb?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce09870a81eb</guid>
            <category><![CDATA[minimum-height-tree]]></category>
            <category><![CDATA[leetcode-310]]></category>
            <category><![CDATA[neetcode-150]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[graph-data-structure]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 15:43:50 GMT</pubDate>
            <atom:updated>2026-01-18T17:05:52.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Minium Height Trees — Leetcode 310</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6aGVGkflS_yGm4aaOQMYQ.jpeg" /></figure><p>When I first encountered the <strong>Minimum Height Trees (MHT)</strong> problem on LeetCode, my instinct was simple and honest:</p><blockquote><em>“For each node, consider it as a root, compute the height using DFS/BFS, and return the node(s) with minimum height.”</em></blockquote><p>This approach felt <em>natural</em>.<br> It matched the problem statement directly.</p><p>But it was also <strong>O(n²)</strong> — and deep down, I knew this wouldn’t scale.</p><p>Still, I implemented it mentally first, because brute force is often the best way to <em>understand</em> a problem before optimizing it.</p><pre>class Solution:<br>    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -&gt; List[int]:<br>        if n == 1:<br>            return [0]<br><br>        # Build adjacency list<br>        adj = defaultdict(list)<br>        for u, v in edges:<br>            adj[u].append(v)<br>            adj[v].append(u)<br><br>        def bfs_height(root):<br>            visited = set([root])<br>            queue = deque([(root, 0)])<br>            max_depth = 0<br><br>            while queue:<br>                node, depth = queue.popleft()<br>                max_depth = max(max_depth, depth)<br><br>                for nei in adj[node]:<br>                    if nei not in visited:<br>                        visited.add(nei)<br>                        queue.append((nei, depth + 1))<br><br>            return max_depth<br><br>        min_height = float(&#39;inf&#39;)<br>        result = []<br><br>        # Try each node as root<br>        for node in range(n):<br>            height = bfs_height(node)<br><br>            if height &lt; min_height:<br>                min_height = height<br>                result = [node]<br>            elif height == min_height:<br>                result.append(node)<br><br>        return resultp</pre><h3>My First Optimization Attempt (and Why It Failed)</h3><p>To reduce complexity, I tried to be clever.</p><p>Instead of recomputing heights for every node, I thought:</p><blockquote><em>“What if I do a single DFS and, while traversing, compute some notion of height for each node?”</em></blockquote><p>I wrote a DFS that tracked depth and tried to infer which nodes could act as roots with minimum height.</p><p>Some test cases passed.<br> That gave me confidence.</p><pre>class Solution:<br>    def __init__(self):<br>        self.minimum_height_tree = 9999999999<br>        self.rootNodes = []<br><br>    def dfs(self, currentNode, adj, visited, incomingNode=0):<br>        if visited[currentNode] == -2:<br>            return incomingNode<br><br>        visited[currentNode] = -2<br><br>        max_no_of_nodes_on_current_Node_branches = incomingNode<br>        max_heighted_branch_from_current_node = 0<br><br>        for linkNode in adj[currentNode]:<br>            if visited[linkNode] == -2:<br>                continue<br><br>            max_no_of_nodes_through_visiting_node = self.dfs(<br>                linkNode, adj, visited, incomingNode + 1<br>            )<br><br>            max_heighted_branch_from_current_node = max(<br>                max_heighted_branch_from_current_node,<br>                max_no_of_nodes_through_visiting_node,<br>            )<br><br>            max_no_of_nodes_on_current_Node_branches = max(<br>                max_no_of_nodes_through_visiting_node,<br>                max_no_of_nodes_on_current_Node_branches,<br>            )<br><br>        if max_no_of_nodes_on_current_Node_branches &lt; self.minimum_height_tree:<br>            self.minimum_height_tree = max_no_of_nodes_on_current_Node_branches<br>            self.rootNodes = [currentNode]<br>        elif max_no_of_nodes_on_current_Node_branches == self.minimum_height_tree:<br>            self.rootNodes.append(currentNode)<br><br>        visited[currentNode] = 1<br>        return max_heighted_branch_from_current_node + 1<br><br>    def findMinHeightTrees(self, n, edges):<br>        adj = {c: set() for c in range(n)}<br>        visited = {c: -1 for c in range(n)}<br><br>        for u, v in edges:<br>            adj[u].add(v)<br>            adj[v].add(u)<br><br>        self.dfs(0, adj, visited)<br><br>        pq = []<br><br>        for node in self.rootNodes:<br>            heapq.heappush(pq, (-len(adj[node]), node))<br><br>        result = []<br><br>        i = 2 if len(self.rootNodes) % 2 == 0 else 1<br><br>        while i:<br>            _, node = heapq.heappop(pq)<br>            result.append(node)<br>            i -= 1<br><br>        return result</pre><p>Then a simple test case failed — and that failure changed everything.</p><p>The tree look like this</p><pre>    1<br>    |<br>    0 — 2<br>    |<br>    3</pre><p>Adjacency List</p><pre>0 → 1,2,3<br>1 → 0<br>2 → 0<br>3 → 0</pre><p>The correct answer is:</p><pre>[0]</pre><p>But my code returned:</p><pre>[ 0 , 1 ]</pre><h3>Dry Running My Code (The Key Realization)</h3><p>I noticed something subtle but critical:</p><ul><li>I always started DFS from node 0</li><li>When DFS moved from 0 → 1, node 1 looked like a leaf</li><li>From that direction, the height of 1 seemed small</li></ul><p>But that was an illusion.</p><p>If I <strong>re-rooted the tree at node </strong><strong>1</strong>, the structure would actually be:</p><pre>1<br>|<br>0<br>| \<br>2  3</pre><p>Now the height is <strong>2</strong>, not 1.</p><h3>The mistake I made:</h3><p>I was computing height <strong>relative to where I came from</strong>, not <strong>relative to the entire tree</strong>.</p><p>In other words:</p><blockquote><em>My DFS was directionally biased.</em></blockquote><p>That’s when it clicked — <strong>root-based DFS is fundamentally flawed for this problem</strong>.</p><h3>Why This Problem Is Not About Traversal</h3><p>At this point, I asked myself:</p><blockquote><em>“Why does choosing a root early cause so many problems?”</em></blockquote><p>And the answer was simple but profound:</p><blockquote><strong><em>Minimum Height Trees is not a traversal problem.<br> It’s a structural problem.</em></strong></blockquote><p>Traversal order should not affect the answer.</p><p>That’s when I stopped thinking in terms of:</p><ul><li>DFS</li><li>BFS</li><li>Starting nodes</li></ul><p>And started thinking in terms of <strong>tree shape</strong>.</p><h3>A New Mental Model: Peeling the Tree Like an Onion</h3><p>I went back to the definition of a tree.</p><p>Leaves (degree = 1 nodes) are always the <em>furthest</em> from the center.<br> So I asked:</p><blockquote><em>“What if I remove all leaves first?”</em></blockquote><p>Then remove the new leaves.<br> Then repeat.</p><p>This felt like <strong>peeling layers off an onion</strong>.</p><p>Visually, it made sense:</p><ul><li>Outer layers cannot be roots of minimum height</li><li>The center must survive the longest</li></ul><p>I didn’t fully know the algorithm yet — but the <em>direction</em> was finally right.</p><h3>Visualizing the Correct Process</h3><p>For the earlier failing example:</p><pre>    1<br>    |<br>    0 — 2<br>    |<br>    3</pre><p>Leaves: {1,2,3}<br>Remove them → remaining node: {0}</p><p>That’s the answer.</p><p>No traversal bias.<br>No root assumption.<br>Just structure.</p><h3>Another Important Insight I Almost Missed</h3><p>At one point, I tried to decide the number of roots based on whether n was even or odd.</p><p>That was wrong.</p><p>Two trees can have the same number of nodes but different centers.</p><p>The correct rule is:</p><blockquote><strong><em>The number of MHT roots depends on the tree’s diameter, not on </em></strong><strong><em>n.</em></strong></blockquote><ul><li>Odd diameter → 1 center</li><li>Even diameter → 2 centers</li></ul><p>And onion peeling naturally reveals this without explicitly computing the diameter.</p><pre>class Solution:<br>    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -&gt; List[int]:<br>        adj = {c:set() for c in range(n)}<br><br>        for edge in edges:<br>            adj[edge[0]].add(edge[1])<br>            adj[edge[1]].add(edge[0])<br>        <br>        queue = deque([])<br><br>        for i in range(n):<br>            if len(adj[i]) == 1:<br>                queue.append(i)<br>        <br>        remaining = n<br><br>        while remaining &gt; 2:<br>            size = len(queue)<br>            remaining -= size<br><br>            for _ in range(size):<br>                leaf = queue.popleft()<br>                neighbor = adj[leaf].pop()<br>                adj[neighbor].remove(leaf)<br><br>                if len(adj[neighbor]) == 1:<br>                    queue.append(neighbor)<br><br>                adj.pop(leaf)<br><br>        return list(adj.keys())</pre><h3>What I Learned (Beyond This Problem)</h3><p>This problem taught me lessons that go far beyond MHT:</p><ol><li><strong>Brute force is not bad</strong> — it helps you understand the problem</li><li><strong>Failed optimizations are valuable</strong> — they expose wrong assumptions</li><li><strong>Traversal ≠ structure</strong></li><li><strong>Visualization beats clever code</strong></li><li>Some problems require you to <em>remove information</em>, not accumulate it</li></ol><h3>Final Thought</h3><p>For a while, I wondered:</p><blockquote><em>“If my optimized solution failed, does that mean I’m a bad programmer?”</em></blockquote><p>Now I know the answer.</p><p>No.</p><p>It means I was <strong>thinking</strong>, testing boundaries, and learning how algorithms <em>actually work</em>.</p><p>Understanding <strong>why a solution fails</strong> is often more valuable than memorizing the one that passes.</p><p>And that’s when real progress starts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce09870a81eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Sharding Strategies in MongoDB]]></title>
            <link>https://medium.com/@farhanbajwa46/understanding-sharding-strategies-in-mongodb-95bf425a73fb?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/95bf425a73fb</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[sharding]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 06:28:49 GMT</pubDate>
            <atom:updated>2025-12-23T06:31:52.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*w2EgzKvm98k3J9Rj_V8kQQ.png" /></figure><p>When your MongoDB application starts to grow, a single database server eventually stops being enough. Reads slow down, writes queue up, and scaling vertically (adding more RAM or CPU) only gets you so far. This is where <strong>sharding</strong> comes in.</p><p>Sharding is MongoDB’s way of distributing data across multiple machines so your system can scale horizontally. MongoDB mainly supports <strong>two sharding strategies</strong>: <strong>range-based sharding</strong> and <strong>hashed sharding</strong>. Choosing the right one , and more importantly, choosing the right shard key , can make or break your system’s performance.</p><h3>Range-Based Sharding</h3><p>Range-based sharding is MongoDB’s <strong>default sharding strategy</strong>. It works by dividing data into continuous ranges based on the shard key.</p><p>If documents have similar shard key values, MongoDB groups them into the same chunk, and that chunk lives on a specific shard. This is especially useful for queries that ask for a <strong>range of values</strong>, such as dates or numeric intervals.</p><p>For example, if you shard on createdAt, documents created around the same time will usually end up together. That makes queries like “fetch records from last week” very efficient.</p><p>However, range-based sharding only works well <strong>if the shard key is chosen carefully</strong>.</p><h3>What Makes a Good Shard Key for Range Sharding?</h3><h3>1. High Cardinality</h3><p>Cardinality simply means <strong>how many unique values</strong> a field can have.</p><p>A shard key with high cardinality (like userId or _id) allows MongoDB to create many chunks and distribute them evenly across shards. This gives the balancer more flexibility and improves horizontal scaling.</p><p>On the other hand, a low-cardinality field (like status or gender) severely limits how many chunks MongoDB can create. Fewer chunks mean fewer opportunities to spread the load, which hurts scalability.</p><p><strong>Rule of thumb:</strong> more unique values → better distribution.</p><h3>2. Low Frequency per Value</h3><p>Frequency is about <strong>how often the same value appears</strong>.</p><p>Even if a field technically has many possible values, problems arise when most documents contain only a small subset of them. In such cases, a few chunks end up holding a massive amount of data.</p><p>These chunks can grow so large that MongoDB can no longer split them. When that happens, they turn into <strong>jumbo chunks</strong>. Jumbo chunks cannot be moved or balanced properly, which creates a bottleneck on a single shard while other shards sit idle.</p><p>In short, if one shard key value dominates your data, sharding won’t save you.</p><h3>3. Non-Monotonically Changing Values</h3><p>A monotonically changing value is one that <strong>always increases or decreases</strong>, such as timestamps, auto-incrementing IDs, or counters.</p><p>This pattern is dangerous for range-based sharding.</p><p>MongoDB always has a chunk that covers the highest possible range (ending at MaxKey). If your shard key keeps increasing, all new inserts will land in that single chunk , and therefore on a single shard.</p><p>The result?<br> A classic <strong>hot shard problem</strong>, where one shard handles all writes while others do almost nothing.</p><p>To avoid this, a shard key should change in a way that distributes inserts across many chunks, not just one.</p><h3>Hashed Sharding</h3><p>Hashed sharding takes a different approach.</p><p>Instead of using the raw shard key value, MongoDB first computes a <strong>hash</strong> of that value. The hash is then used to determine which chunk the document belongs to.</p><p>This means that even if shard key values look very close (like consecutive timestamps or ObjectIds), their hashed values will be spread out randomly across chunks.</p><p>The big advantage here is <strong>even data distribution</strong>, especially for write-heavy workloads.</p><h3>The Trade-off</h3><p>Hashing destroys natural ordering.</p><p>Because of that, <strong>range-based queries become inefficient</strong>. MongoDB can no longer target a specific shard for range queries and often has to query all shards instead.</p><p>So hashed sharding is excellent for:</p><ul><li>Equality lookups</li><li>High insert rates</li><li>Monotonically increasing fields</li></ul><p>But it’s a poor choice if your application heavily relies on range queries or sorted scans.</p><h3>Why _id Works So Well with Hashed Sharding</h3><p>The default _id field (when it uses ObjectId) is:</p><ul><li>Unique (high cardinality)</li><li>Appears once per document (low frequency)</li><li>Monotonically increasing</li></ul><p>On its own, _id is risky for range sharding. But once hashed, it becomes one of the safest and most reliable shard keys you can use.</p><h3>Compound Hashed Shard Keys (MongoDB 4.4+)</h3><p>Before MongoDB 4.4, hashed shard keys could only be single-field. Starting with 4.4, MongoDB allows <strong>compound shard keys with exactly one hashed field</strong>.</p><p>For example:</p><pre>db.planets.createIndex({ name: 1, _id: &quot;hashed&quot; })<br><br>sh.shardCollection(<br>  &quot;sample_guides.planets&quot;,<br>  { name: 1, _id: &quot;hashed&quot; }<br>)</pre><p>In this setup:</p><ul><li>name is a normal (range-based) field</li><li>_id is hashed</li></ul><p>MongoDB first uses name to group documents and then uses the hashed _id to distribute them evenly within those groups.</p><h3>Zone Sharding with Compound Hashed Keys</h3><p>Compound hashed sharding also works well with <strong>zone sharding</strong>.</p><p>Here’s how the responsibilities are split:</p><ul><li>The <strong>non-hashed prefix field(s)</strong> define zone boundaries</li><li>The <strong>hashed field</strong> ensures even distribution inside each zone</li></ul><p>This gives you control over <em>where</em> data lives while still maintaining good balance and avoiding hot shards.</p><p>Additionally, using a hashed prefix in a shard key can help solve distribution issues caused by fields that grow monotonically.</p><h3>Shard Key Index Requirement</h3><p>MongoDB requires an index that <strong>starts with the shard key</strong> in order to shard a collection.</p><ul><li>If the collection already has data, you must create this index manually before sharding.</li><li>If the collection is empty, MongoDB will automatically create the required index when you shard it.</li></ul><p>This requirement ensures MongoDB can efficiently route queries and manage chunks once sharding is enabled.</p><h3>Final Thoughts</h3><p>Sharding is not just about splitting data, it’s about <strong>splitting it intelligently</strong>.</p><p>Range-based sharding shines when you need fast range queries and your shard key distributes data evenly. Hashed sharding sacrifices ordering but excels at write scalability and avoiding hot shards, especially for monotonically increasing fields.</p><p>The real challenge isn’t choosing a strategy , it’s choosing the <strong>right shard key</strong> for your workload.</p><p>If you get that right, MongoDB scales beautifully. If you get it wrong, no amount of shards will save you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95bf425a73fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Sharding: A Simple Guide]]></title>
            <link>https://medium.com/@farhanbajwa46/mongodb-sharding-a-simple-guide-bf0f85b25a03?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf0f85b25a03</guid>
            <category><![CDATA[sharding]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[database-sharding]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 05:32:05 GMT</pubDate>
            <atom:updated>2025-12-23T05:32:05.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*rwcapfBhLVX0VHKGjHJDaQ.png" /><figcaption>Mongo db sharding Architecture</figcaption></figure><h3>What is Sharding?</h3><p>Sharding is MongoDB’s way of splitting your data across multiple servers (called shards) so that no single server gets overloaded. Think of it like distributing books across multiple libraries instead of keeping them all in one place.</p><h3>How Does It Work?</h3><h3>1. Shard Key — The Foundation</h3><ul><li>A shard key is one or more fields from your documents that MongoDB uses to decide where data goes</li><li>Example: If you use user_id as a shard key, MongoDB will distribute users based on their IDs</li><li>Choosing the right shard key is CRITICAL — a bad choice can ruin your performance</li></ul><h3>2. Chunks — Data Blocks</h3><ul><li>MongoDB divides your data into non-overlapping ranges called chunks</li><li>Each chunk contains documents with shard key values within a specific range</li><li>Example: Chunk 1 might have user_id 1–1000, Chunk 2 has 1001–2000, etc.</li><li>These ranges never overlap, so no data duplication</li></ul><h3>3. Distribution Across Shards</h3><ul><li>Each chunk is assigned to a different shard</li><li>MongoDB automatically balances chunks across all shards</li><li>This ensures even load distribution and prevents bottlenecks</li></ul><h3>Real-World Example</h3><p>Collection: Users</p><ul><li>Shard Key: user_id</li><li>Chunk 1 (user_id 1–1000) → Shard 1</li><li>Chunk 2 (user_id 1001–2000) → Shard 2</li><li>Chunk 3 (user_id 2001–3000) → Shard 3</li><li>Chunk 4 (user_id 3001–4000) → Shard 4</li></ul><p>Collection: Orders</p><ul><li>Shard Key: order_date</li><li>Chunk 1 (Jan-Mar 2024) → Shard 1</li><li>Chunk 2 (Apr-Jun 2024) → Shard 2</li><li>Chunk 3 (Jul-Sep 2024) → Shard 3</li><li>Chunk 4 (Oct-Dec 2024) → Shard 4</li></ul><h3>Why Sharding Matters</h3><p>✅ Scalability — Handle massive datasets by distributing across multiple servers</p><p>✅ Performance — Queries run faster because each shard only searches its portion of data</p><p>✅ Balanced Load — Prevents one server from becoming a bottleneck (hot shard)</p><p>✅ High Availability — If one shard goes down, others keep working</p><h3>The Critical Part: Choosing the Right Shard Key</h3><p>❌ Bad Shard Key = Uneven distribution, some shards overloaded, others underutilized, slow queries</p><p>✅ Good Shard Key = Even distribution, balanced load, optimal performance</p><h3>Key Takeaway</h3><p>Sharding is essential for scaling MongoDB, but success depends on choosing a shard key that evenly distributes your data. A poor choice can create a “hot shard” that becomes a performance bottleneck, defeating the purpose of sharding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf0f85b25a03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preserving and Resetting State In React js]]></title>
            <link>https://javascript.plainenglish.io/preserving-and-resetting-state-in-react-js-ec270fa95c49?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec270fa95c49</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[diffing-algorithm]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 07:55:41 GMT</pubDate>
            <atom:updated>2025-11-25T13:33:46.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSP8hhkIycBFxl3Wt6dCgQ.png" /></figure><p><em>We often spend a lot of time avoiding unnecessary re-renders, unmounts, and remounts in React. But sometimes, we intentionally want a component to unmount and mount again so that its state resets instead of being carried over to new data.</em></p><p>Below are two components, Scoreboard1 and Scoreboard2. At first glance, both seem to behave the same, but there’s a subtle difference.</p><pre>import { useState } from &#39;react&#39;;<br>export default function Scoreboard1() {<br>  const [isPlayerA, setIsPlayerA] = useState(true);<br>  return (<br>    &lt;div&gt;<br>      {isPlayerA ? (<br>        &lt;Counter person=&quot;Taylor&quot; /&gt;<br>      ) : (<br>        &lt;Counter person=&quot;Sarah&quot; /&gt;<br>      )}<br>      &lt;button onClick={() =&gt; {<br>        setIsPlayerA(!isPlayerA);<br>      }}&gt;<br>        Next player!<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>import { useState } from &#39;react&#39;;<br>export default function Scoreboard2() {<br>  const [isPlayerA, setIsPlayerA] = useState(true);<br>  return (<br>    &lt;div&gt;<br>      {isPlayerA &amp;&amp;<br>        &lt;Counter person=&quot;Taylor&quot; /&gt;<br>      }<br>      {!isPlayerA &amp;&amp;<br>        &lt;Counter person=&quot;Sarah&quot; /&gt;<br>      }<br>      &lt;button onClick={() =&gt; {<br>        setIsPlayerA(!isPlayerA);<br>      }}&gt;<br>        Next player!<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>function Counter({ person }) {<br>  const [score, setScore] = useState(0);<br>  const [hover, setHover] = useState(false);<br>  let className = &#39;counter&#39;;<br>  if (hover) {<br>    className += &#39; hover&#39;;<br>  }<br>  return (<br>    &lt;div<br>      className={className}<br>      onPointerEnter={() =&gt; setHover(true)}<br>      onPointerLeave={() =&gt; setHover(false)}<br>    &gt;<br>      &lt;h1&gt;{person}&#39;s score: {score}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setScore(score + 1)}&gt;<br>        Add one<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>In Scoreboard1, switching the player preserves the state inside the Counter component.</strong></p><p><strong>In Scoreboard2, switching the player unmounts the existing Counter and renders a fresh one, resetting its state.</strong></p><p>Both behaviours are valid depending on your use case. What’s important is understanding why they behave differently even though the JSX looks similar.</p><p>React’s official docs put it perfectly:</p><blockquote>Remember that it’s the position in the UI tree, not in the JSX markup that matters to React!</blockquote><p>So the natural question is: If the Counter appears as the first child of the parent div in both components, even after toggling players, why does React preserve state in one case and reset it in the other?</p><p>The key difference in behavior between two Scoreboard components boils down to how React’s reconciliation algorithm (the diffing process) handles the rendered output during re-renders.</p><p>Specifically:</p><ul><li>In the <strong>first component</strong> (ternary operator), React sees the &lt;Counter /&gt; as the <strong>same component type</strong> in the <strong>same position</strong> across renders, just with <strong>updated props</strong> (person changes from “Taylor” to “Sarah”). This triggers an <strong>update</strong> on the <em>existing</em>Counter instance, <strong>preserving its internal state</strong> (score and hover stay intact).</li><li>In the <strong>second component</strong> (separate &amp;&amp; conditions), React renders <em>two potential</em>&lt;Counter /&gt; instances in <em>different positions</em>. When isPlayerA toggles:</li><li>The previous &lt;Counter /&gt;<strong>unmounts</strong> (disappears from the DOM tree).</li><li>A <em>new</em>&lt;Counter /&gt;<strong>mounts</strong> in its place. This resets the state because useState is tied to the component <em>instance</em> — a fresh mount means fresh state initialization (score back to 0).</li></ul><p>Let’s break it down step-by-step.</p><h4>Step-by-Step: What Happens on Toggle</h4><p>Assume we start with isPlayerA = true (rendering Taylor’s Counter). User clicks “Add one” → score = 1. Now click “Next player!” → isPlayerA = false (tries to render Sarah’s Counter).</p><p><strong>First Component (Ternary: State Preserves)</strong></p><pre>{isPlayerA ? (<br>  &lt;Counter person=&quot;Taylor&quot; /&gt;  // Initial render<br>) : (<br>  &lt;Counter person=&quot;Sarah&quot; /&gt;   // After toggle<br>)}</pre><p><strong>Reconciliation View</strong>:</p><ul><li>Before toggle: Virtual DOM has &lt;Counter person=”Taylor” /&gt; at root position 0.</li><li>After toggle: Virtual DOM still has &lt;Counter person=”Sarah” /&gt; at root position 0.</li><li>React diffs: Same type (Counter), same position → <strong>Update props</strong> (person changes). No unmount/mount.</li><li><strong>State Effect</strong>: score remains 1 (now displayed as “Sarah’s score: 1”). Hover state also persists.</li><li><strong>Why?</strong> Ternary always outputs <em>one</em> element of type Counter. React optimizes by reusing the fiber (internal node) for efficiency.</li></ul><pre>{isPlayerA &amp;&amp;<br>  &lt;Counter person=&quot;Taylor&quot; /&gt;  // Renders when true, unmounts when false<br>}<br>{!isPlayerA &amp;&amp;<br>  &lt;Counter person=&quot;Sarah&quot; /&gt;   // Mounts when false<br>}</pre><p><strong>Reconciliation View</strong>:</p><ul><li>Before toggle (isPlayerA = true): Virtual DOM has &lt;Counter person=”Taylor” /&gt; at root position 0; nothing at position 1.</li><li>After toggle (isPlayerA = false): Virtual DOM has <em>nothing</em> at position 0 (unmounts Taylor’s); &lt;Counter person=”Sarah” /&gt; at root position 1.</li><li>React diffs: Position 0 removed (unmount), new type at position 1 (mount). These are treated as <em>separate subtrees</em>.</li><li><strong>State Effect</strong>: Taylor’s instance unmounts (loses score = 1), Sarah’s new instance mounts with score = 0.</li><li><strong>Why?</strong>&amp;&amp; creates <em>mutually exclusive branches</em> in <em>different tree positions</em>. React doesn’t “know” they’re the same component — just that the tree structure changed.</li></ul><h4>Visualizing the DOM Tree Positions</h4><p>Think of the output as an array of children:</p><ul><li><strong>Ternary</strong>: Always [ &lt;Counter /&gt; ] → Stable position.</li><li><strong>&amp;&amp;</strong>: Toggles between [ &lt;Counter-Taylor /&gt; ] and [ &lt;Counter-Sarah /&gt; ]<em>but in shifted positions</em> → Destabilizes the tree.</li></ul><h4>How to Fix the Second Component (Preserve State)</h4><p>To make the second one behave like the first, ensure React sees it as the <strong>same position and type</strong>. Options:</p><ol><li><strong>Use Ternary (Simplest)</strong>: Already works — switch back to it.</li><li><strong>Add a Stable key Prop</strong>: Forces React to track identity across position changes.</li></ol><pre>{isPlayerA &amp;&amp;<br>  &lt;Counter key=&quot;player&quot; person=&quot;Taylor&quot; /&gt;<br>}<br>{!isPlayerA &amp;&amp;<br>  &lt;Counter key=&quot;player&quot; person=&quot;Sarah&quot; /&gt;<br>}</pre><ul><li>key=”player” (same value) tells React: “These are the same logical component, even if positions shift.” → Updates props, preserves state.</li><li>Use <em>unique</em> keys only for lists (e.g., key={person} would <em>worsen</em> resets here).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec270fa95c49" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/preserving-and-resetting-state-in-react-js-ec270fa95c49">Preserving and Resetting State In React js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering this in JavaScript: A Complete Guide]]></title>
            <link>https://javascript.plainenglish.io/mastering-this-in-javascript-a-complete-guide-79493873138a?source=rss-c5f5764daa0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/79493873138a</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-this-keyword]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Farhan Asghar]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 10:41:13 GMT</pubDate>
            <atom:updated>2025-09-23T01:51:06.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1d2yXW6GQhMluseP_G-FA.png" /><figcaption>This keyword</figcaption></figure><p>If you’ve spent any time writing JavaScript, you’ve almost certainly encountered the this keyword. And if you&#39;re like most developers, you&#39;ve probably also experienced moments of head-scratching confusion trying to figure out what this actually refers to at any given moment. Don&#39;t worry, you&#39;re not alone! The this keyword is notorious for being one of JavaScript&#39;s trickiest features.</p><p>But here’s the good news: once you understand its core principles, this can be an incredibly powerful and flexible tool. This article will demystify this, breaking down how its value is determined in different scenarios, and giving you the clarity you need to wield it with confidence.</p><h3>What is this Anyway? The Heart of the Matter</h3><p>At its most fundamental, the <strong>this keyword refers to the context where a piece of code, such as a function&#39;s body, is supposed to run</strong>. Think of this as a hidden parameter that the JavaScript language creates for you when a function&#39;s body is evaluated.</p><p>The most common place you’ll see this is in object methods. In this scenario, <strong>this refers to the object that the method is attached to</strong>. This brilliant design allows the same method to be reused on different objects, making your code more modular and efficient.</p><p>But here’s the crucial twist: <strong>the value of </strong><strong>this in JavaScript depends on <em>how</em> a function is invoked (runtime binding), not how it is defined</strong>. This dynamic nature is the source of much of the confusion, but also its immense power.</p><pre>const test = {<br>  prop: 42,<br>  func() {<br>    return this.prop;<br>  },<br>};<br><br>console.log(test.func());<br>// Expected output: 42</pre><p>Let’s break down this&#39;s behavior in various contexts.</p><h3>1. The Function Context</h3><p>Inside a function, the value of this is heavily influenced by how that function is called.</p><h4>Regular Functions</h4><p>For a regular function (meaning not an arrow function, or bound function, which we’ll cover soon), <strong>this is the object that the function is accessed on</strong>.</p><p>Consider this classic example:</p><pre>function getThis() {<br>  return this;<br>}</pre><pre>const obj1 = { name: &quot;obj1&quot; };<br>const obj2 = { name: &quot;obj2&quot; };</pre><pre>obj1.getThis = getThis;<br>obj2.getThis = getThis;</pre><pre>console.log(obj1.getThis()); // { name: &#39;obj1&#39;, getThis: [Function: getThis] }<br>console.log(obj2.getThis()); // { name: &#39;obj2&#39;, getThis: [Function: getThis] }</pre><p>Notice how the getThis function is exactly the same, but the value of this is different based on which object it was called from (obj1 or obj2). This is a prime example of runtime binding.</p><p>Even if a function is defined directly on an object, if you “unbind” it and call it standalone, this will change:</p><pre>const obj4 = {<br>  name: &quot;obj4&quot;,<br>  getThis() {<br>    return this;<br>  },<br>};</pre><pre>const obj5 = { name: &quot;obj5&quot; };<br>obj5.getThis = obj4.getThis; // Assigning obj4&#39;s method to obj5</pre><pre>console.log(obj5.getThis()); // { name: &#39;obj5&#39;, getThis: [Function: getThis] }</pre><p>Here, obj4.getThis was assigned to obj5.getThis, and when invoked via obj5, this correctly pointed to obj5.</p><h4>Strict Mode vs. Non-Strict Mode: A Key Difference</h4><p>JavaScript has a “strict mode” (&quot;use strict&quot;;) that changes some behaviors, and this is one of them.</p><ul><li><strong>Non-strict mode:</strong> If a function is called standalone (not attached to an object, like func()), this typically refers to the <strong>global object</strong> (globalThis in modern JavaScript, or window in browsers). There&#39;s also this substitution: if this is undefined or null, it gets substituted with globalThis. If it&#39;s a primitive, it gets wrapped in an object (e.g., 7 becomes a Number object).</li><li><strong>Strict mode:</strong> If called standalone, this will be <strong>undefined</strong>. Also, if this is a primitive value (like a number or string), it will remain a primitive value and not be wrapped.</li></ul><pre>// Non-strict mode example<br>function getThisNonStrict() {<br>  return this;<br>}<br>console.log(getThisNonStrict() === globalThis); // true<br>console.log(typeof (1).getThisNonStrict()); // &quot;object&quot; (1 gets wrapped into Number object)</pre><pre>// Strict mode example<br>function getThisStrict() {<br>  &quot;use strict&quot;;<br>  return this;<br>}<br>console.log(typeof getThisStrict()); // &quot;undefined&quot;<br>console.log(typeof (1).getThisStrict()); // &quot;number&quot; (primitive remains primitive)</pre><p>This is a critical distinction to remember! Classes are <em>always</em> in strict mode.</p><h4>Explicitly Setting this: call(), apply(), and bind()</h4><p>You don’t always have to rely on implicit binding. JavaScript provides methods to explicitly control the value of this:</p><ul><li><strong>Function.prototype.call(thisArg, arg1, arg2, ...):</strong> Invokes the function immediately, setting this to thisArg and passing additional arguments individually.</li><li><strong>Function.prototype.apply(thisArg, [argsArray]):</strong> Similar to call(), but accepts arguments as an array.</li><li><strong>Function.prototype.bind(thisArg):</strong> Creates a <em>new function</em> with the same body and scope as the original, but <strong>permanently binds its </strong><strong>this value to </strong><strong>thisArg</strong>, regardless of how the new function is later called. This binding happens only once.</li></ul><pre>function add(c, d) {<br>  return this.a + this.b + c + d;<br>}<br>const o = { a: 1, b: 3 };</pre><pre>// Using call<br>console.log(add.call(o, 5, 7)); // 16 (this.a=1, this.b=3)</pre><pre>// Using apply<br>console.log(add.apply(o,)); // 34 (this.a=1, this.b=3)</pre><pre>// Using bind<br>function f() {<br>  return this.a;<br>}<br>const g = f.bind({ a: &quot;azerty&quot; });<br>console.log(g()); // azerty</pre><pre>const h = g.bind({ a: &quot;yoo&quot; }); // bind only works once!<br>console.log(h()); // azerty (still &quot;azerty&quot; from the first bind)</pre><p>bind() is especially useful for creating functions that need to maintain their context when passed around, like event handlers or callbacks.</p><h4>Callbacks</h4><p>When you pass a function as a callback, this can often be tricky because its value depends on how the API that receives the callback actually calls it. <strong>Callbacks are <em>typically</em> called with a </strong><strong>this value of </strong><strong>undefined</strong> (if called directly without an object), meaning in non-strict mode, this would be globalThis.</p><p>For example, iterative array methods like forEach() or the Promise() constructor usually call callbacks with this as undefined (or globalThis in non-strict mode).</p><pre>function logThis() {<br>  &quot;use strict&quot;; // Using strict mode to clearly show &#39;undefined&#39;<br>  console.log(this);<br>}</pre><pre>.forEach(logThis); // undefined, undefined, undefined</pre><p>However, <strong>some APIs allow you to set a </strong><strong>this value for the callback&#39;s invocations</strong>, often through an optional thisArg parameter.</p><pre>.forEach(logThis, { name: &quot;obj&quot; }); // { name: &#39;obj&#39; }, { name: &#39;obj&#39; }, { name: &#39;obj&#39; }</pre><h3>2. Arrow Functions: The Lexical this</h3><p>Arrow functions (=&gt;) are a game-changer when it comes to this, primarily because they handle it differently than regular functions. <strong>Arrow functions do not have their own </strong><strong>this binding</strong>. Instead, they <strong>inherit </strong><strong>this from the parent (enclosing lexical) scope at the time they are defined</strong>.</p><p>This “lexical this&quot; behavior means:</p><ul><li>Their this value is determined when they are <em>created</em>, not when they are invoked.</li><li>It cannot be set or changed by bind(), apply(), or call(). The thisArg parameter passed to these methods will simply be ignored.</li></ul><pre>const globalObject = this; // In a browser, this would be window (if not a module)<br>const foo = () =&gt; this;<br>console.log(foo() === globalObject); // true</pre><pre>const obj = {<br>  name: &quot;obj&quot;,<br>  getThisGetter() {<br>    const getter = () =&gt; this; // &#39;this&#39; here is lexically bound to getThisGetter&#39;s &#39;this&#39;<br>    return getter;<br>  },<br>};</pre><pre>const fn = obj.getThisGetter();<br>console.log(fn() === obj); // true - &#39;this&#39; inside the arrow function is obj</pre><p>This behavior makes arrow functions particularly useful for callbacks, as they allow you to easily preserve the context (this) of the surrounding code.</p><h3>3. Class Context: this in Modern JavaScript</h3><p>Classes in JavaScript also have specific rules for this. Classes are inherently in strict mode.</p><ul><li><strong>Constructors:</strong> When a function is used as a constructor (with the new keyword), this is bound to <strong>the new object being constructed</strong>. Unless the constructor explicitly returns another non-primitive value, this will be the newly created instance.</li><li><strong>Instance Methods:</strong> These behave much like methods in object literals. The this value is the <strong>object that the method was accessed on</strong>, which is typically an instance of the class.</li><li><strong>Static Methods and Fields:</strong> These are properties of the class itself, not an instance. Therefore, this within a static method or static field initializer refers to <strong>the class itself</strong> (or a subclass).</li></ul><pre>class C {<br>  instanceField = this; // &#39;this&#39; is the instance<br>  static staticField = this; // &#39;this&#39; is the class C<br>}</pre><pre>const c = new C();<br>console.log(c.instanceField === c); // true<br>console.log(C.staticField === C);   // true</pre><h4>Derived Class Constructors (extends)</h4><p>If you’re creating a derived class (using extends), there&#39;s a crucial rule: <strong>you must call </strong><strong>super() before referring to </strong><strong>this</strong> in the constructor. Failing to do so will throw a ReferenceError. Calling super() creates the this binding for the derived class.</p><pre>class Base {}<br>class Good extends Base {<br>  constructor() {<br>    super(); // Must call super() first!<br>    this.a = 5;<br>  }<br>}</pre><pre>class Bad extends Base {<br>  constructor() {<br>    // No super() call<br>    // console.log(this); // This would throw an error!<br>  }<br>}</pre><pre>new Good(); // Works fine<br>// new Bad();  // Throws ReferenceError: Must call super constructor in derived class...</pre><h4>Bound Methods in Classes</h4><p>Just like with regular functions, class methods can lose their this context if they are &quot;unbound&quot; from their instance (e.g., passed as a callback). Since classes are strict mode, this often leads to TypeError if this is undefined and you try to access properties on it.</p><p>To prevent this, you can explicitly bind methods in the constructor:</p><pre>class Car {<br>  constructor() {<br>    this.sayBye = this.sayBye.bind(this); // Binding &#39;sayBye&#39;<br>  }<br>  sayHi() {<br>    console.log(`Hello from ${this.name}`);<br>  }<br>  sayBye() {<br>    console.log(`Bye from ${this.name}`);<br>  }<br>  get name() { return &quot;Ferrari&quot;; }<br>}</pre><pre>const car = new Car();<br>const carSayHi = car.sayHi;<br>// carSayHi(); // TypeError: Cannot read properties of undefined (reading &#39;name&#39;)</pre><pre>const carSayBye = car.sayBye;<br>carSayBye(); // Bye from Ferrari (bound method retains &#39;this&#39;)</pre><p>While effective, remember that binding methods in the constructor means each instance gets its own copy of the bound method, potentially increasing memory usage. Use it where absolutely necessary.</p><h3>4. Global Context and Other Niche Scenarios</h3><ul><li><strong>Global Execution Context:</strong> Outside of any function or class, at the top level of a script, this refers to <strong>globalThis</strong> (which is window in web browsers) whether in strict mode or not.</li><li><strong>Modules:</strong> If your script is loaded as a module (&lt;script type=&quot;module&quot;&gt;), this is always <strong>undefined</strong> at the top level.</li><li><strong>Object Literals:</strong> Object literals themselves <strong>don’t create a new </strong><strong>this scope</strong>. If you use this directly in an object literal (outside a method), it inherits this from the surrounding scope.</li><li>const obj = { a: this, // &#39;this&#39; here refers to the global &#39;this&#39; (e.g., window in a browser script) }; // console.log(obj.a === window); // true (in a browser&#39;s script tag)</li><li><strong>DOM Event Handlers:</strong> When a function serves as a DOM event handler, its this parameter is bound to <strong>the DOM element on which the listener is placed</strong>.</li><li><strong>Getters and Setters:</strong> For getters and setters, this is based on <strong>which object the property is accessed on</strong>, not where it&#39;s defined.</li></ul><h3>Wrapping Up: Taming the this Beast</h3><p>The this keyword is undoubtedly one of JavaScript&#39;s most challenging concepts. However, by understanding these core rules, you can approach it with a clear strategy:</p><ol><li><strong>Identify the invocation type:</strong> Is it a method call (obj.func()), a standalone function call (func()), a constructor call (new Class()), or an arrow function?</li><li><strong>Consider strict mode:</strong> Is the code running in strict mode or non-strict mode? (Remember, classes are always strict!)</li><li><strong>Check for explicit binding:</strong> Are call(), apply(), or bind() being used?</li><li><strong>Remember arrow functions’ lexical </strong><strong>this:</strong> They don&#39;t have their own this; they inherit it from their definition scope.</li></ol><p>With practice, predicting the value of this will become second nature. You&#39;ll move from frustrated confusion to confident control, unlocking the full potential of this fundamental JavaScript feature.</p><p><strong>Citations:</strong></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this - JavaScript | MDN</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79493873138a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-this-in-javascript-a-complete-guide-79493873138a">Mastering this in JavaScript: A Complete Guide</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>