<?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 M. Farhan Siddique on Medium]]></title>
        <description><![CDATA[Stories by M. Farhan Siddique on Medium]]></description>
        <link>https://medium.com/@me_4885?source=rss-82af3360f691------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*moOEiuCqMly9F6PU9D2jDg.jpeg</url>
            <title>Stories by M. Farhan Siddique on Medium</title>
            <link>https://medium.com/@me_4885?source=rss-82af3360f691------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@me_4885/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[Scaling a React App: The Front-End Side of SaaS Scalability]]></title>
            <link>https://medium.com/@me_4885/scaling-a-react-app-the-front-end-side-of-saas-scalability-a40c87a86ea4?source=rss-82af3360f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40c87a86ea4</guid>
            <dc:creator><![CDATA[M. Farhan Siddique]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 06:03:41 GMT</pubDate>
            <atom:updated>2026-02-09T06:03:41.576Z</atom:updated>
            <content:encoded><![CDATA[<p>When we talk about scaling a SaaS application, the first things that come to mind are:</p><ul><li>Load balancers</li><li>Microservices</li><li>Multi-instance deployments</li><li>Async processing</li><li>Database replicas</li><li>CDNs</li></ul><p>In other words — backend scalability.</p><p>But what about <strong>front-end scaling?</strong></p><p>Front-end scaling is not only about serving more users.<br> It’s about performance, maintainability, and team productivity at scale.</p><p>And this is where many SaaS products struggle.</p><h3>Real-World Scenarios I’ve Seen</h3><ul><li>A front-end app taking <strong>4 seconds to First Contentful Paint (FCP)</strong> with an 8MB JS bundle and 500KB CSS</li><li>New engineers taking <strong>over a month to ship their first PR</strong></li><li>Feature teams creating duplicate components instead of reusable variants</li><li>A new feature triggering unexpected global re-renders that take days to debug</li><li>Pages repeatedly fetching the same user profile data — sometimes multiple times on the same screen</li></ul><p>None of these are rare.<br> They’re signs of a front-end that wasn’t designed to scale.</p><p>Let’s talk about patterns that help build future-proof React applications.</p><h3>1) Code Splitting</h3><p>One of the biggest front-end scaling mistakes is shipping too much JavaScript.</p><p>Unlike backend scaling, you can’t fix this by adding more servers.<br> Your bottleneck is the <strong>user’s device and CPU.</strong></p><p>Large bundles mean:</p><ul><li>Slower downloads</li><li>Slower parsing</li><li>Slower execution</li><li>Delayed first render</li></ul><h3>Start with route-based code splitting</h3><p>This is the easiest and highest-impact improvement.</p><p>Users should only download code for the pages they visit.</p><h3>Lazy-load third-party libraries</h3><p>Analytics tools, charting libraries, editors, and SDKs should be loaded only when needed.</p><p>Every KB matters at scale.</p><h3>2) State Management</h3><p>A common anti-pattern in scaling apps is overusing global state.</p><h3>Keep state close to where it belongs</h3><p>Local state is easier to reason about and avoids unnecessary re-renders.</p><p>Use global state for things that rarely change:</p><ul><li>Auth/user info</li><li>Theme</li><li>Feature flags</li></ul><h3>For data-heavy apps</h3><p>Tools like Redux Toolkit or Zustand can help — but they should be used intentionally.</p><p>Global state is powerful, but overusing it can hurt performance and maintainability.</p><h3>3) Data Fetching</h3><p>Repeated API calls may not hurt with a small user base.<br> At scale, they become expensive and inefficient.</p><p>Duplicate requests can:</p><ul><li>Increase backend load</li><li>Slow down UI</li><li>Create cascading performance issues</li></ul><p>Libraries like React Query or RTK Query help by:</p><ul><li>Caching responses</li><li>Deduplicating requests</li><li>Handling background refetching</li></ul><p>Good data fetching strategy is a scaling strategy.</p><h3>4) Component Performance</h3><p>Reusable components must be built with performance in mind.</p><p>Example:</p><p>A poorly designed dropdown that:</p><ul><li>Loads large datasets</li><li>Sorts and filters on every render</li></ul><p>If reused across the app, it becomes a hidden bottleneck — especially on lower-end devices.</p><p>Reusable components should be:</p><ul><li>Efficient</li><li>Predictable</li><li>Tested under load</li></ul><p>A shared component should never degrade the entire app.</p><h3>5) Developer Experience (DX)</h3><p>As teams grow, complexity grows even faster.</p><p>Without structure, you’ll see:</p><ul><li>Duplicate components</li><li>Inconsistent UX</li><li>Confusing APIs</li><li>Slow onboarding</li></ul><h3>Invest in a component library</h3><p>Centralize:</p><ul><li>Design tokens</li><li>Themes</li><li>Shared components</li></ul><p>Each component should define:</p><ul><li>Loading states</li><li>Error states</li><li>Accessibility behavior</li></ul><p>Consistency at scale is a competitive advantage.</p><h3>6) Storybook Is a Must-Have</h3><p>As teams expand, communication gaps appear.</p><p>Storybook becomes:</p><ul><li>Living documentation</li><li>A shared UI reference</li><li>A collaboration tool for devs, designers, and PMs</li></ul><p>Design tools like Figma are great for visuals, but Storybook shows real behavior.</p><p>It reduces duplication and improves alignment.</p><h3>7) Monorepo (When It Makes Sense)</h3><p>Monorepos are powerful but not for every team.</p><p>They shine when:</p><ul><li>UI and API share types</li><li>Multiple apps share logic/design systems</li><li>Teams collaborate closely</li></ul><p>Tools like Nx or Turborepo help manage scale.</p><p>But consider trade-offs:</p><ul><li>Code ownership clarity</li><li>Learning curve</li><li>CI complexity</li><li>PR conflicts</li></ul><p>Adopt a monorepo when it solves real problems — not because it’s trendy.</p><h3>8) React Profiling</h3><p>Most slow React apps aren’t slow because of React itself.</p><p>They’re slow because of:</p><ul><li>Unnecessary re-renders</li><li>Expensive render logic</li><li>Large lists</li><li>Poor state placement</li></ul><p>React profiling helps you identify real issues.</p><p>Profiling should be part of:</p><ul><li>Performance audits</li><li>PR reviews</li><li>Optimization cycles</li></ul><p>Measure first. Optimize second.</p><h3>9) Memoization &amp; Virtualization</h3><p>useMemo and useCallback are great tools when profiling shows real problems.</p><p>Examples:</p><ul><li>Sorting/filtering large datasets</li><li>Expensive derived data</li><li>Heavy reusable components</li></ul><p>But don’t use them blindly.</p><p>For very large datasets:</p><ul><li>react-window</li><li>react-virtualized</li></ul><p>These libraries drastically improve rendering performance and UX.</p><h3>10) Team Culture &amp; Knowledge Sharing</h3><p>Scaling isn’t only technical — it’s cultural.</p><p>Regular:</p><ul><li>Hackathons</li><li>Tech talks</li><li>Cross-team demos</li></ul><p>Help teams stay aligned and innovative.</p><p>A scalable front end requires scalable teams.</p><h3>Final Thoughts</h3><p>Front-end scaling is about more than performance.</p><p>It’s about:</p><ul><li>Maintainability</li><li>Developer velocity</li><li>Consistency</li><li>User experience</li></ul><p>A scalable React app:</p><ul><li>Performs well on real devices</li><li>Enables teams to move fast</li><li>Stays maintainable over time</li></ul><p>Backend scaling gets attention.<br> Front-end scaling deserves it too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40c87a86ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React code splitting: A basic building block, not an afterthought.]]></title>
            <link>https://medium.com/@me_4885/react-code-splitting-a-basic-building-block-not-an-afterthought-1a5df43133c2?source=rss-82af3360f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5df43133c2</guid>
            <dc:creator><![CDATA[M. Farhan Siddique]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 04:49:34 GMT</pubDate>
            <atom:updated>2026-02-03T04:49:34.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWibSw54qui99jmdbe-fsQ.jpeg" /></figure><p>A few years ago, I joined a project where my very first task was performance improvement. It was a flight booking engine, and from day one it was clear the app was struggling.</p><p>The initial bundle size was <strong>18MB</strong> — huge for a web app. It included everything from multi-language translation files to payment receipt templates that 95% of visitors would never even reach. The SEO score hovered around the low 40s for desktop and dropped to the mid-teens on mobile.</p><p>The project was screaming for code splitting.</p><p>That experience taught me one of the most important lessons in frontend engineering: <strong>performance is easy to ignore early on, but expensive to fix later.</strong></p><p>When we scaffold a new project, performance optimizations often feel premature. The app is small, the team wants to move fast, and priorities are focused on features and delivery. It’s tempting to think, <em>“We’ll optimize later.”</em></p><p>But projects rarely stay small.</p><p>As features pile up, dependencies grow, and quick fixes accumulate, the codebase can bloat faster than expected. What once felt like a simple app becomes a heavy, slow system. At that point, introducing performance strategies like code splitting, lazy loading, or bundle optimization isn’t just a quick win — it can require significant refactoring, coordination, and risk.</p><p>In other words, the cost curve flips.<br>Early optimization is cheap. Late optimization is expensive.</p><p>Code splitting, for example, is far easier to design into your architecture from the start than to retrofit into a mature system with tightly coupled modules.</p><p>If there’s one takeaway from that project, it’s this:</p><p><strong>Treat performance as a feature, not an afterthought.</strong></p><p>You don’t need to over-engineer on day one, but setting up good foundations — modular architecture, sensible bundling strategies, and lazy loading where it makes sense — pays off massively as the product scales.</p><p>Because one day, you might open your bundle analyzer and see 18MB staring back at you.</p><p>Code splitting is one of the highest-impact ways to improve a React app’s <strong>performance, load time, and perceived speed</strong>, especially as your bundle grows.</p><p>Without code splitting: Users download <strong>your entire JS bundle upfront</strong>, Slow first load (bad TTI, LCP, SEO), and Wasted JS for routes they never visit</p><p>With code splitting: Load only what’s needed, Faster initial render, Better Core Web Vitals, and Lower memory usage.</p><p>Here are a few ways you can add code splitting.</p><h3>Route-Based Code Splitting (Biggest Win)</h3><p>Split by pages/routes so each page loads on demand.</p><pre>import { lazy, Suspense } from &quot;react&quot;;<br>import { BrowserRouter, Routes, Route } from &quot;react-router-dom&quot;;<br><br>const Home = lazy(() =&gt; import(&quot;./pages/Home&quot;));<br>const Dashboard = lazy(() =&gt; import(&quot;./pages/Dashboard&quot;));<br>const Settings = lazy(() =&gt; import(&quot;./pages/Settings&quot;));<br><br>export default function App() {<br>  return (<br>    &lt;BrowserRouter&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;Routes&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>          &lt;Route path=&quot;/dashboard&quot; element={&lt;Dashboard /&gt;} /&gt;<br>          &lt;Route path=&quot;/settings&quot; element={&lt;Settings /&gt;} /&gt;<br>        &lt;/Routes&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/BrowserRouter&gt;<br>  );<br>}<br></pre><p>Users only download the page they visit. This is the must have and minimum you can do at the begining and this alone can solve most of the problems</p><h3>Component-Level Splitting</h3><p>Split heavy components:</p><ul><li>Charts</li><li>Maps</li><li>Rich editors</li><li>Large tables</li><li>Modals used rarely</li></ul><pre>const Chart = lazy(() =&gt; import(&quot;./Chart&quot;));<br>{showChart &amp;&amp; (<br>  &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>    &lt;Chart /&gt;<br>  &lt;/Suspense&gt;<br>)}</pre><p>Avoids loading heavy libs like Chart.js on initial load.</p><h3>Library-Level Splitting</h3><p>Dynamically import heavy libraries only when needed.</p><pre>async function loadEditor() {<br>  const { Editor } = await import(&quot;heavy-editor-lib&quot;);<br>  // use it<br>}</pre><p>Great for:</p><ul><li>PDF viewers</li><li>Markdown editors</li><li>Analytics tools</li><li>WYSIWYG editors</li></ul><h3>Preloading for UX</h3><p>Preload likely-to-visit routes.</p><pre>const Dashboard = lazy(() =&gt; import(&quot;./Dashboard&quot;));<br>// preload on hover<br>&lt;button<br>  onMouseEnter={() =&gt; import(&quot;./Dashboard&quot;)}<br>&gt;<br>  Go to Dashboard<br>&lt;/button&gt;</pre><p>I first encountered this approach when I started working with GatsbyJS, and I immediately appreciated it. Gatsby provides smart performance optimizations out of the box, including automatic code splitting, which makes a noticeable difference in real-world applications.</p><p>What I found even more interesting is how you can build on top of these defaults with your own strategies. For example, you can preload related chunks inside a useEffect hook. While the user is browsing content on the current page, the app can quietly load the most relevant next chunks in the background.</p><p>This way, when the user navigates to a related page, the resources are already available. The transition feels instant, and the user doesn’t experience the typical delay or visual side effects of lazy loading.</p><p>It’s a great reminder that performance optimization isn’t just about reducing bundle size — it’s also about <strong>predicting user behavior and loading the right code at the right time.</strong></p><p>Here are some tools that you can use to optimize code splitting.</p><h3>Bundle Analysis (Critical)</h3><p>You can’t optimize what you don’t measure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptn-OGHNbyZIzKI01Yrz3Q.png" /></figure><p>Use:</p><pre>npm run build<br>npx source-map-explorer build/static/js/*.js</pre><p>or</p><pre>webpack-bundle-analyzer</pre><p>I make it part of the commands and add this to package.json</p><pre>&quot;scripts&quot;: {<br>     ....<br>    &quot;report&quot;: &quot;npm run build -- --stats &amp;&amp; npx webpack-bundle-analyzer ./build/bundle-stats.json&quot;,<br>}</pre><p>Find:</p><ul><li>Duplicate deps</li><li>Large libraries</li><li>Unused code</li></ul><h3>Combine with Tree Shaking</h3><p>Ensure:</p><ul><li>ES modules used</li><li>No wildcard imports</li></ul><p>❌ Bad</p><pre>import * as _ from &quot;lodash&quot;;</pre><p>✅ Good</p><pre>import debounce from &quot;lodash/debounce&quot;;</pre><p>Final thought:<br>As I always say, don’t over-abuse anything. Here are a few tips.<br>Tips</p><h4>1) Split by user role</h4><p>Admin vs User panels.</p><h4>2) Split by feature flags</h4><p>Load features only when enabled.</p><h4>3) Micro-frontend style loading</h4><p>Load remote modules only when needed.</p><h4>4) Avoid over-splitting</h4><p>Too many small chunks → network overhead.</p><p>Rule of thumb:</p><blockquote><em>Split by meaningful boundaries, not every component.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a5df43133c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Stale Cache in React Query with Real-Time Invalidation (NestJS Microservices)]]></title>
            <link>https://medium.com/@me_4885/solving-stale-cache-in-react-query-with-real-time-invalidation-nestjs-microservices-e46409e13291?source=rss-82af3360f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/e46409e13291</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[client-side-caching]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[M. Farhan Siddique]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 21:34:33 GMT</pubDate>
            <atom:updated>2026-02-07T18:36:39.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJRKdDEHzyRWlFNXs3mUGQ.jpeg" /></figure><p>A year ago, I was looking for a good front-end cache and state management solution. I found React-Query, and it was love at first sight. I wanted to squeeze the maximum performance out of it. I got what I was looking for, but it came with a trade-off and an issue. If you’re using <strong>@tanstack/react-query</strong>, you’ve probably faced this problem:</p><p><em>User A updates something → User B still sees old data</em> <br><em> User B React Query says “cached” → but the cache is now wrong (outdated)</em></p><p>There are tons of different ways to solve this issue. But I was looking for maximum performance, the most efficient of resources (as I was in a startup) and keeping the data up to date in real time.</p><p>This article explains:</p><ul><li><em>Why this happens</em></li><li><em>Why polling is not enough (fetching data on timers)</em></li><li><em>And how to solve it properly using </em><strong><em>NestJS microservices + event-driven cache invalidation</em></strong></li></ul><h3>The Problem: Client Cache ≠ Source of Truth</h3><p>React Query is a <strong>client-side cache</strong>, not a distributed one.</p><p>It has no way of knowing when: <em>Another user updates data, A background job runs, or A different service mutates the database</em></p><p>So, unless you: <em>Manually invalidate, Poll (re-fetch data in time cycle), Or refetch on focus</em></p><p>Your UI can show <strong>stale data forever</strong>.</p><p>This is not a React Query bug — it’s a <strong>distributed systems problem</strong>.</p><h3>Why Polling Is a Bad Default</h3><p>Initially, I tried:</p><pre>refetchInterval: 5000</pre><p>But this: Wastes network resources, Adds server load, Still has delay and Doesn’t scale well</p><p>Instead of <em>asking the server repeatedly: “Did something change?”</em></p><p>We should let the <strong>server tell us</strong>: <em>“Something changed. Refetch now.”</em></p><p>This is called <strong>event-driven cache invalidation</strong>.</p><h3>The Architecture</h3><p>Here’s the pattern used by real-time SaaS dashboards, admin panels, and financial systems:</p><pre>Microservice updates DB<br>        |<br>        v<br>Emits domain event<br>        |<br>        v<br>Message Broker (Redis / NATS / Kafka)<br>        |<br>        v<br>NestJS API Gateway<br>        |<br>        v<br>WebSocket / SSE<br>        |<br>        v<br>React Query invalidates cache</pre><p>The idea is very close to the microservices architecture. If something changes, omit an event and let the other services listen and process the event.</p><p>Here, when a service omits a change, It let API gateway know, and that triggers an event for UI to invalidate the data and fetch a new one, but only invalidates the key that relates to pice of data changed, so the service can fetch the fresh one if it needs it.</p><h3>Step 1: Emit Cache Invalidation Events</h3><p>From any NestJS microservice:</p><pre>this.client.emit(&#39;cache.invalidate&#39;, {<br>  keys: [[&#39;orders&#39;, orderId], [&#39;orders&#39;]],<br>  scope: { orgId: order.orgId }<br>});</pre><p>This event does <strong>not</strong> know about React Query, browsers, or UI.<br> It only says: <em>“These entities changed.”.</em></p><p><strong>For now, I would ignore the elephant in the room. “How to manage keys properly so the server and UI can share them”.</strong></p><h3>Step 2: Subscribe in the API Gateway</h3><pre>@EventPattern(&#39;cache.invalidate&#39;)<br>handle(event) {<br>  this.gateway.broadcast(event);<br>}</pre><p>The gateway becomes the <strong>bridge</strong> between backend events and frontend updates.</p><h3>Step 3: WebSocket Gateway</h3><pre>@WebSocketGateway({ cors: true })<br>export class CacheGateway {<br>  @WebSocketServer()<br>  server: Server;<br>broadcast(event) {<br>    this.server<br>      .to(`org-${event.scope.orgId}`)<br>      .emit(&#39;invalidate&#39;, event.keys);<br>  }<br>handleConnection(socket) {<br>    socket.join(`org-${socket.handshake.query.orgId}`);<br>  }<br>}</pre><p>Now only users in the same org/project receive updates.</p><h3>Step 4: React Query Client</h3><pre>socket.on(&#39;invalidate&#39;, (keys) =&gt; {<br>  keys.forEach(key =&gt; {<br>    queryClient.invalidateQueries({ queryKey: key });<br>  });<br>});</pre><p>That’s it. React Query: Marks the cache stale, Automatically refetches, or UI updates instantly</p><h3>What This Solves</h3><pre><strong>Problem</strong>                 | <strong>Solution</strong><br>================================================<br>Stale UI                | Real-time invalidation<br>Polling waste           | Zero unnecessary calls<br>Microservice isolation  | Event-based<br>Scaling                 | Broker handles fanout</pre><h3>When You Should Use This</h3><p>Use real-time invalidation if:</p><ul><li><em>Multiple users see the same data</em></li><li><em>Updates matter instantly</em></li><li><em>You run microservices with react-query</em></li><li><em>You care about performance &amp; correctness</em></li></ul><p>Examples:</p><ul><li><em>Admin dashboards</em></li><li><em>Collaboration tools</em></li><li><em>Trading/finance apps</em></li><li><em>Monitoring panels</em></li></ul><h3>Final Thought</h3><p>React Query is excellent — but it can have cache issues when you try to maximize the performance</p><p>In distributed apps, <strong>the server must participate in cache coherence</strong>.</p><p>Once you move to event-driven invalidation, you’ll never go back to polling.</p><p>However, before all this, first you need to decide what is the best practice to share keys with the server side!</p><p>Also, this is not great for all the scenarios. In some cases, like fetching data dictionaries from APIs or fetching email templates that rarely change, we might prefer to keep the polling strategy as it is more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e46409e13291" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>