<?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 Lofty Khanna on Medium]]></title>
        <description><![CDATA[Stories by Lofty Khanna on Medium]]></description>
        <link>https://medium.com/@loftykhanna?source=rss-5bcd368d6b5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q4GZvF64SvvxyVZfkLJDEQ.png</url>
            <title>Stories by Lofty Khanna on Medium</title>
            <link>https://medium.com/@loftykhanna?source=rss-5bcd368d6b5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:46:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@loftykhanna/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[The Token Refresh Succeeded. The Caller Still Lost.]]></title>
            <link>https://medium.com/physicswallah-engineering/the-token-refresh-succeeded-the-caller-still-lost-cd0e497f495f?source=rss-5bcd368d6b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0e497f495f</guid>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Lofty Khanna]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 10:01:08 GMT</pubDate>
            <atom:updated>2026-07-12T10:01:08.598Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why parallel 401s log users out — and why a successful retry can still break the caller.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SW7ouM9FAElq5m_RG6zY8w.png" /></figure><p>The token expires mid-session. Five API calls are in flight. All five come back 401.</p><p>If your interceptor is not careful, what happens next is a <strong>refresh storm</strong> — five simultaneous calls to your token endpoint. Most auth servers rotate the refresh token on the first successful call. The next four arrive with a stale token and get rejected. Your user is now logged out — not because their session expired, but because your error handling fired too eagerly.</p><p>So you add a queue. Catch the 401, hold the request, refresh once, retry everything. The network panel cleans up. One refresh call. Retries return 200s.</p><p>The dashboard still shows three spinners and two blank cards.</p><p>You fixed the storm. You didn’t fix the callers. This post covers both.</p><h3>The four-question checklist</h3><p>Before going deep, the takeaway up front. If your refresh queue cannot answer all four, it is not a queue — it is a to-do list nothing awaits.</p><ol><li><strong>Does the caller get a Promise back immediately?</strong> If not, await has nothing to suspend on.</li><li><strong>Does each queued entry store </strong><strong>resolve and </strong><strong>reject?</strong> If not, you cannot return control later.</li><li><strong>On success, do you call </strong><strong>resolve with the retried result?</strong> If not, the original caller never continues.</li><li><strong>On failure, do you call </strong><strong>reject on every queued entry?</strong> If not, callers hang forever instead of failing cleanly.</li></ol><p>The rest of this post explains why each question matters — and the storm-shaped problem you have to solve before any of them apply.</p><h3>Part 1 — The storm: many 401s, one refresh</h3><p>This is the first problem, and the one you can actually see. Open the network panel during a token expiry and you will watch it happen in real time.</p><p>A naive interceptor looks like this:</p><pre>async function apiCall(url: string) {<br>  const response = await fetch(url, { headers: authHeaders() });<br><br>  if (response.status === 401) {<br>    await refreshAccessToken();<br>    const retry = await fetch(url, { headers: authHeaders() });<br>    return retry.json();<br>  }<br><br>  return response.json();<br>}</pre><p>Reads fine. Catches 401, refreshes, retries. The bug is invisible until two requests fail at once.</p><pre>const [user, orders, batches, profile, settings] = await Promise.all([<br>  apiCall(&#39;/user&#39;),<br>  apiCall(&#39;/orders&#39;),<br>  apiCall(&#39;/batches&#39;),<br>  apiCall(&#39;/profile&#39;),<br>  apiCall(&#39;/settings&#39;),<br>]);</pre><p>Five concurrent requests. Five concurrent 401s. Five concurrent calls to refreshAccessToken(). The auth server processes the first one, rotates the refresh token, and rejects the next four because they presented a token that is now invalid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoBsc1z9Wm0ZaRg6nOD8lw.png" /></figure><p>The user is logged out. Not because their session expired — because your client triggered a refresh storm against an auth server that does the correct thing.</p><p><strong>The fix is a single-flight refresh.</strong> Hold one in-flight refresh Promise. Every concurrent 401 waits on the same Promise. Only one network call goes out.</p><pre>let isRefreshing = false;<br>let refreshPromise: Promise&lt;void&gt; | null = null;<br><br>async function getFreshToken(): Promise&lt;void&gt; {<br>  if (isRefreshing &amp;&amp; refreshPromise) {<br>    return refreshPromise;<br>  }<br><br>  isRefreshing = true;<br>  refreshPromise = refreshAccessToken().finally(() =&gt; {<br>    isRefreshing = false;<br>    refreshPromise = null;<br>  });<br><br>  return refreshPromise;<br>}</pre><p><em>Now five concurrent 401s trigger one refresh call. Storm gone. Network panel clean.<br>If each caller retries inline after </em><em>await getFreshToken(), you are done — five callers, one refresh, five retries, five results. The bug below appears when teams centralize retries in a queue but wire the Promises wrong.</em></p><h3>Part 2 — The ghost: where most implementations break</h3><blockquote>Single-flight fixes the storm. It does not fix a broken queue.<br>Many teams add a shared queue after refresh — hold the 401s, refresh once, retry everything. That is reasonable. The failure mode is not “queue bad, inline retry good.” It is: queue the request URL but drop the caller’s Promise.<br>This is where the queue shows up — and where almost every hand-rolled implementation I have reviewed has the same bug.</blockquote><p>The intuitive version:</p><pre>const pendingRequests: { url: string }[] = [];<br><br>async function apiCall(url: string) {<br>  const response = await fetch(url, { headers: authHeaders() });<br><br>  if (response.status === 401) {<br>    pendingRequests.push({ url });<br>    await getFreshToken();<br>    retryAllPending();<br>    return;<br>  }<br><br>  return response.json();<br>}<br><br>function retryAllPending() {<br>  for (const req of pendingRequests) {<br>    fetch(req.url, { headers: authHeaders() }).then(r =&gt; r.json());<br>  }<br>  pendingRequests.length = 0;<br>}</pre><p>The structure reads as correct: 401 caught, request queued, token refreshed, queue drained.</p><p>The caller experiences something else:</p><pre>async function loadDashboard() {<br>  const [user, orders] = await Promise.all([<br>    apiCall(&#39;/user&#39;),<br>    apiCall(&#39;/orders&#39;),<br>  ]);<br>  render(user, orders);<br>}</pre><p>user is undefined. orders is undefined. Both slots in the Promise.all already settled — no hang, no error. render runs with garbage data, or a loading spinner never clears because the UI treats falsy values as “still fetching.”</p><p>Refresh succeeded. Retries returned 200. Caller still lost.</p><p><em>Note: this is not what happens with inline retry after </em><em>getFreshToken(). There, each caller’s own Promise chain does the retry and returns data. The bug is specific to fire-and-forget queue drains that never call the original </em><em>resolve.</em></p><h3>Why the original Promise is lost</h3><p>This is the general mistake. It is a Promise lifecycle bug, not an auth bug.</p><p>When loadDashboard writes await apiCall(&#39;/user&#39;), the runtime does three things:</p><ol><li><strong>Promise A</strong> is created — the one returned by apiCall(&#39;/user&#39;).</li><li>loadDashboard suspends, holding a reference to Promise A.</li><li>The function resumes only when Promise A settles.</li></ol><p>In the broken implementation, the moment the 401 path runs return;, Promise A resolves with undefined. The caller is released immediately, with no data.</p><p>Later, retryAllPending fires a new fetch. That new fetch creates <strong>Promise B</strong> — an entirely separate promise the caller has no reference to. Promise B may resolve with the correct response, but there is no wire connecting it back to Promise A. The result is dropped on the floor.</p><p>Two promises. No bridge between them. That is the entire bug.</p><p>And no — rejecting instead of returning undefined does not fix it. In this scenario the refresh succeeded and the retry returned 200; the data exists, just on Promise B. Throwing from Promise A only trades a blank screen for a false error — the caller sees a failure for a request that actually worked. undefined fails silently, throw fails loudly, but both settle Promise A with the wrong outcome. Reject is the right move only when the work genuinely cannot complete — a failed refresh, which clearQueue handles below. The cure is never which value you settle with; it is bridging the two Promises so the caller gets the result that already exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1InsNyRUbVYyHBHZqs0Brg.png" /></figure><h3>Why this is so hard to spot</h3><p>Half the system looks healthy:</p><p>Refresh request returned 200 — the original await already settled with undefined.</p><p><em>Retried /user returned 200 — the user variable never received the data; a separate Promise did.</em></p><p>Queue drained cleanly — code after await already ran with wrong values.</p><p>No errors thrown — callers resumed with undefined. The UI shows blank cards, missing fields, or a spinner that never clears because the app treats falsy data as “still loading.”</p><p>You can stare at the network panel for an hour and not see it. The bug is not on the wire. It is in the missing connection between two Promises in memory.</p><h3>The fix: queue the waiter, not the request</h3><p><em>Inline retry is one correct design. The queue below is another — useful when you want one place to drain retries, park requests during refresh, or mirror interceptor-style SDKs. Both work; both must settle the same Promise the caller is awaiting.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uL7PT8nQHIEMKwgocVhDwg.png" /></figure><p>The retry must resolve the <strong>same</strong> Promise the caller is suspended on. To do that, you store the resolve and reject handlers of Promise A at the moment you create it, then call them when the retry settles.</p><p>The complete implementation — isRefreshing and getFreshToken() carry over from Part 1; the queue is the new piece:</p><pre>interface QueuedRequest {<br>  resolve: (value: unknown) =&gt; void;<br>  reject: (reason?: unknown) =&gt; void;<br>  url: string;<br>  options: RequestInit;<br>}<br><br>// isRefreshing and getFreshToken from Part 1<br>const pendingRequests: QueuedRequest[] = [];<br><br>async function apiCall(url: string, options: RequestInit = {}): Promise&lt;unknown&gt; {<br>  if (isRefreshing) {<br>    return new Promise((resolve, reject) =&gt; {<br>      pendingRequests.push({ resolve, reject, url, options });<br>    });<br>  }<br><br>  const response = await fetch(url, { ...options, headers: authHeaders() });<br><br>  if (response.status === 401) {<br>    return new Promise((resolve, reject) =&gt; {<br>      pendingRequests.push({ resolve, reject, url, options });<br>      <br>      // Only the first request entering this branch registers the drain handlers.<br>      // getFreshToken() dedups the refresh call itself; this guard prevents<br>      // duplicate processQueue() invocations on the same in-flight refresh.<br>      //<br>      // This guard holds because getFreshToken() sets isRefreshing synchronously<br>      // before returning — so a second concurrent 401 sees true immediately<br>      // and only parks, never registering a second processQueue().<br>      if (!isRefreshing) {<br>        getFreshToken()<br>          .then(() =&gt; processQueue())<br>          .catch(err =&gt; clearQueue(err));<br>      }<br>    });<br>  }<br><br>  return response.json();<br>}<br><br>async function processQueue() {<br>  const queue = pendingRequests.splice(0);<br><br>  for (const req of queue) {<br>    try {<br>      const response = await fetch(req.url, { ...req.options, headers: authHeaders() });<br><br>      if (response.status === 401) {<br>        req.reject(new Error(&#39;Session expired&#39;));<br>        continue;<br>      }<br>      if (!response.ok) {<br>        req.reject(new Error(`Request failed with ${response.status}`));<br>        continue;<br>      }<br><br>      req.resolve(await response.json());<br>    } catch (error) {<br>      req.reject(error);<br>    }<br>  }<br>}<br><br>function clearQueue(error: unknown) {<br>  const queue = pendingRequests.splice(0);<br>  for (const req of queue) {<br>    req.reject(error);<br>  }<br>}<br></pre><p><em>Two implementation notes before this is production-ready. </em><em>authHeaders() must read the freshly-minted token after </em><em>getFreshToken() resolves — either from the storage that </em><em>refreshAccessToken writes to, or by being passed the new token directly. If </em><em>authHeaders() is cached at module load, every retry sends the expired token and you ship a silent refresh loop. Separately, in real code you would parameterize this as </em><em>apiCall&lt;T&gt;(...); the example uses </em><em>unknown to keep the focus on control flow rather than type plumbing.</em></p><p>Two primitives doing two jobs:</p><ul><li><strong>isRefreshing</strong> is the deduplication primitive. It solves the storm. One refresh request, no matter how many 401s.</li><li><strong>The queue of </strong><strong>{ resolve, reject, ... }</strong> is the fan-out primitive. It solves the ghost. Five waiters parked, five resolve calls, five resumed awaits.</li></ul><p>loadDashboard now behaves the way every reader expects:</p><pre>async function loadDashboard(): Promise&lt;void&gt; {<br>  const [user, orders] = await Promise.all([<br>    apiCall(&#39;/user&#39;),<br>    apiCall(&#39;/orders&#39;),<br>  ]);<br>  render(user, orders);<br>}</pre><p>The call site is identical to the broken example. The only thing that changed is when the answer arrives — which is the entire job description of await.</p><h3>Where this pattern already lives</h3><p>This is the same pattern that powers axios-auth-refresh and most of the interceptor logic you have used without thinking about it. The reason hand-rolled versions still get this wrong, even when those libraries exist, is that the libraries hide the queue — you wire up a refreshAuthLogic callback and never see the { resolve, reject } parking happen under the hood. When teams build their own SDK from scratch, they reach for the network-level abstraction (<em>queue the request</em>) instead of the Promise-level abstraction (<em>queue the waiter</em>). The code looks correct because the network behavior is correct. The control flow is what breaks.</p><h3>Walking through one full cycle</h3><p>To make the control flow concrete, here is what happens when loadDashboard runs into an expired token. Two parallel calls, one refresh, two resumed awaits.</p><ol><li>apiCall(&#39;/user&#39;) fires and the server returns 401.</li><li>A new Promise is created. resolve and reject are captured into the queue alongside the URL and options. getFreshToken() is called synchronously inside the Promise constructor — it flips isRefreshing to true and fires one refresh request.</li><li>That Promise is returned to the caller. loadDashboard suspends on the first await.</li><li>apiCall(&#39;/orders&#39;) fires and also returns 401. (If it had started <em>after</em> the refresh began, the top-level isRefreshing guard would park it immediately with no fetch at all — either path lands it in the same queue.)</li><li>A second Promise is created and queued. loadDashboard suspends on the second await.</li><li>The refresh resolves. New tokens are stored. isRefreshing flips back to false and processQueue() runs.</li><li>The queue drains /user: retry returns 200, req.resolve(userData) settles Promise A, and loadDashboard resumes on the first await with real data.</li><li>The queue drains /orders: retry returns 200, req.resolve(ordersData) settles Promise B, and loadDashboard resumes on the second await. render(user, orders) runs with real data.</li></ol><p>One refresh. Two retries. Two resumed callers. No orphan Promises. No accidental logout.</p><p>The same sequence as a diagram — both calls enter the queue, either via a 401 or the isRefreshing guard, a single refresh runs, and both resolve when processQueue() drains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JT5f0rGpD9t126qTdAkmRQ.png" /></figure><blockquote><em>The queue is not a list of URLs. It is a list of unfinished async conversations.</em></blockquote><h3>Production checklist</h3><p>Six decisions to make before this code ships:</p><ul><li><strong>Guard the refresh endpoint.</strong> The refresh call must opt out of the 401 interceptor or it will try to refresh itself — an infinite loop that ends in logout. Write this first, not last:</li></ul><pre> if (url.endsWith(&#39;/auth/refresh&#39;)) {<br>  throw new Error(&#39;Refresh token expired&#39;);<br>}</pre><ul><li><strong>Decide what a second 401 means.</strong> A retry that comes back 401 should fail with a session-expired error, not re-enter the queue — otherwise you have shipped an infinite loop.</li><li><strong>Pick sequential or parallel drain.</strong> Sequential is safer; parallel Promise.allSettled is faster but multiplies load on a backend that just rotated a token.</li><li><strong>Cap the queue.</strong> Unbounded queues during long auth outages become their own incident; fast-reject overflow callers.</li><li><strong>Support cancellation.</strong> Attach an AbortSignal to each queued entry so unmounted components drop out instead of resolving into dead consumers.</li><li><strong>Consider the shared-Promise alternative.</strong> If every caller can replay its own request, returning the same in-flight refresh Promise is simpler than storing resolve/reject — but breaks down when request bodies are non-trivial to reconstruct.</li></ul><h3>The invariant</h3><p>Two problems, one rule that solves both.</p><p>Every await is a contract. If you intercept the call that returns a Promise, you inherit the contract:</p><ul><li>Return a Promise.</li><li>Store how to settle it.</li><li>Settle it when the underlying work completes.</li><li>Reject it when the work cannot complete.</li></ul><p>A queue that respects this contract is a waiting room. A queue that ignores it is a graveyard.</p><p>Don’t just queue what to retry. <strong>Queue who is waiting for the answer.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0e497f495f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/physicswallah-engineering/the-token-refresh-succeeded-the-caller-still-lost-cd0e497f495f">The Token Refresh Succeeded. The Caller Still Lost.</a> was originally published in <a href="https://medium.com/physicswallah-engineering">PhysicsWallah Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Study V2: The Microfrontend Routing Trap Nobody Talks About]]></title>
            <link>https://medium.com/physicswallah-engineering/building-study-v2-the-microfrontend-routing-trap-nobody-talks-about-a91fd945714c?source=rss-5bcd368d6b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91fd945714c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <category><![CDATA[dynamic-routing]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Lofty Khanna]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 18:14:41 GMT</pubDate>
            <atom:updated>2026-06-16T18:14:41.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrmnoLeZMD86kFIcbjKi6Q.png" /></figure><blockquote>How we identified routing as a foundational microfrontend problem during POC — and gave it back to the teams who owned the features, before writing a single line of production code.</blockquote><p>When we started planning PhysicsWallah’s Study platform — what became Study V2 — the public conversation around microfrontends was almost entirely about bundling. How do you split code? How do you share dependencies? How do you deploy independently?</p><p>Nobody was talking about the things that quietly break first.<br>Before we wrote a single line of production code, we ran a proof of concept. Its only job was to surface the problems that get expensive after you commit to an architecture, not before.</p><p>This is the story of one of those problems — routing.</p><p>The model we landed on in the POC is what ships today. Study V2 is in production, running with twenty-plus independently deployed microfrontends behind a single shell, serving students on every page load.</p><h3>The POC Came Before the Architecture</h3><p>A microfrontend platform is not something you should architect first and validate later.</p><p>The cost of getting it wrong is too distributed.</p><p>If the shell is built on the wrong assumptions, every team in the company pays for it — every PR, every new page, every deploy. So before we committed to anything, we built a small POC whose only purpose was to stress-test the foundational concerns.</p><p>We analyzed:</p><ul><li><strong>Theming</strong> — can independently deployed apps share one visual identity, with tokens that survive a shell deploy?</li><li><strong>CSS</strong> — whose styles win when two remotes load on the same page, and how do we prevent leakage across boundaries?</li><li><strong>Security</strong> — how do remotes share auth without leaking tokens?</li><li><strong>Session sharing</strong> — can one login propagate to every microfrontend without race conditions, and survive a hard refresh on a deep link?</li><li><strong>Routing</strong> — who owns which URL, and where does navigation actually live?</li><li><strong>Dependency sharing</strong> — can we share React, Router, and the SDK as singletons safely, or do we end up with two React copies on the page?</li><li><strong>Error isolation</strong> — can one broken remote fail gracefully without taking down the shell?</li><li><strong>Observability</strong> — can we attribute errors and performance directly to the owning team?</li><li><strong>Local dev</strong> — can a team run their remote standalone <em>and</em> inside the shell without maintaining two versions of the same app?</li></ul><p>Some of these had answers we could borrow. CSS Modules and a shared design system solve isolation. Tokens applied at the shell solve theming. The auth SDK solves session propagation. Singleton sharing in Module Federation solves dependency duplication.</p><p>A few didn’t.</p><p><strong>Routing was the one that didn’t.</strong></p><p>The wrong routing model would force every team to coordinate with the shell forever. The right one would let them ship independently for years.</p><p>So we solved it in the POC, before architecture.</p><h3>The Trap We Were Avoiding</h3><p>The reason routing kept showing up as a risk is that the obvious starting point for any microfrontend shell looks like this:</p><pre>&lt;Routes&gt;<br>  &lt;Route path=&quot;/product-a/home&quot; element={&lt;ProductAHome /&gt;} /&gt;<br>  &lt;Route path=&quot;/product-a/videos&quot; element={&lt;Videos /&gt;} /&gt;<br>  &lt;Route path=&quot;/product-a/videos/:id&quot; element={&lt;VideoDetail /&gt;} /&gt;<br>  &lt;Route path=&quot;/product-b/:id/overview&quot; element={&lt;Overview /&gt;} /&gt;<br>  &lt;Route path=&quot;/product-b/:id/checkout&quot; element={&lt;Checkout /&gt;} /&gt;<br>  &lt;Route path=&quot;/product-c/dashboard&quot; element={&lt;Dashboard /&gt;} /&gt;<br>  {/* ...forty more routes */}<br>&lt;/Routes&gt;</pre><p>It’s easy. It’s familiar. It’s how you’d structure a single React app.</p><p>And it’s exactly what makes the shell a permanent bottleneck.</p><p>In that model, every product team wanting a new page means a shell PR. The platform team reviews, merges, deploys.</p><blockquote><strong><em>The trap, named explicitly</em></strong><em> The shell becomes a central route registry. Every team depends on it to ship. That’s not a routing bug — it’s an ownership bug. And once you ship it, you’re stuck with it</em></blockquote><h3>A Different Question</h3><p>The reframe that unlocked everything was changing the question we were asking.</p><p>The default question is: <em>what route should the shell render?</em></p><p>We replaced it with: <em>which remote owns this URL prefix?</em></p><p>That’s a small shift in language. The architectural difference is enormous.</p><p>The first question requires the shell to know every URL in every product. The second question requires the shell to know only one thing per product: which first path segment belongs to which remote.</p><pre>export const routesMFMap = {<br>  &#39;/content&#39;:    &#39;MFContent/Content&#39;,<br>  &#39;/courses&#39;:    &#39;MFCourses/Courses&#39;,<br>  &#39;/profile&#39;:    &#39;MFProfile/Profile&#39;,<br>  &#39;/assistant&#39;:  &#39;MFAssistant/Assistant&#39;,<br>  &#39;/payments&#39;:   &#39;MFPayments/Payments&#39;,<br>  &#39;/community&#39;:  &#39;MFCommunity/Community&#39;,<br>  // ...one entry per product<br>};</pre><p>That object is the entire route ownership model for twenty-plus microfrontends.</p><blockquote><strong><em>The shell knows prefixes. Remotes own everything beneath them.</em></strong></blockquote><h3>Why Prefix Ownership Works</h3><p>This is the architectural insight worth making explicit.</p><pre>   /content       →   Content team<br>   /courses       →   Courses team<br>   /profile       →   Profile team<br>   /assistant     →   Assistant team<br>   /payments      →   Payments team</pre><p><strong>Product boundaries become URL boundaries.</strong></p><p>The URL itself encodes who owns the code. If you can’t tell which team owns a path by reading it, the architecture is wrong.</p><p>This sounds obvious, but most microfrontend shells lose it almost immediately. The moment one team’s route lives inside another team’s prefix, ownership becomes ambiguous, deploys start coordinating, and the shell drifts back toward being a central registry.</p><p>Three properties fall out for free once prefixes are sacred:</p><ul><li><strong>A new product = one map entry.</strong> No code review of routes. No URL design committee.</li><li><strong>Ownership is greppable.</strong> Find an incident URL, look up its prefix, know who to page.</li><li><strong>Deploys are isolated.</strong> A team can ship anything under their prefix without touching another team’s code.</li></ul><p>The whole architecture is built around protecting this property.</p><h3>Why Our Build Config Has Zero Remotes</h3><p>This is the part most Module Federation tutorials get wrong, and it’s the single most important decision in our setup.</p><p>The shell’s rsbuild.config.ts does not declare any remotes. None. The remotes object in the federation plugin is empty:</p><pre>pluginModuleFederation({<br>  name: &#39;shell&#39;,<br>  shared: {<br>    ...<br>  },<br>  runtimePlugins: [<br>   ...<br>  ],<br>  remotes: {<br>    // intentionally empty — every remote is registered at runtime<br>  },<br>}),</pre><p>That empty block is the entire architecture, in one decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1Vp5GuFPpbQr5r-n63fqA.png" /></figure><p>What this buys us:</p><ul><li><strong>Adding a new route does not require a shell rebuild. </strong>Product teams can evolve their route trees independently while the shell remains unchanged.</li><li><strong>A bad remote deploy cannot corrupt the shell.</strong> The shell bundle has no compiled-in remote URLs, so there is no remote-specific code path in the shell that can break when a remote changes shape.</li></ul><h3>Register ≠ Load</h3><p>There’s a misconception in almost every Module Federation system I review: treating registration and loading as the same operation.</p><p>They are not.</p><p>At boot, the shell registers the available remotes:</p><pre>init({<br>  name: &#39;shell&#39;,<br>  remotes: [<br>    { name: &#39;MFContent&#39;, entry: `${env.CONTENT}/mf-manifest.json` },<br>    { name: &#39;MFCourses&#39;, entry: `${env.COURSES}/mf-manifest.json` },<br>    { name: &#39;MFProfile&#39;, entry: `${env.PROFILE}/mf-manifest.json` },<br>    // ...all twenty<br>  ],<br>});</pre><p>This downloads nothing.</p><p>It builds an in-memory registry — a phone book. Names mapped to manifest URLs. No feature code, no UI, no vendor bundles. Just metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0vD9bz22WfwvWhY4G2tOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEUydZVZa1zEkdjD4SFXwQ.png" /></figure><p>A user who opens one product area, finishes their task, and closes the app — they never downloaded any other remote.</p><p>This is the difference between <em>eager Module Federation</em> (every remote loaded at boot) and what we built. The shell’s bundle size stays small and constant regardless of how many products live on the platform.</p><h3>How a Remote Is Actually Consumed</h3><p>The full path from URL bar to rendered page is six steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKB6HKNqQqh0hmgvUoHDmw.png" /></figure><pre>onRouteChange(url):<br><br>  1. Resolve route ownership<br>     &#39;/product-b&#39; → MFProductB<br><br>  2. Load owning remote<br>     loadRemote(MFProductB)<br><br>  3. Retrieve route tree<br>     &lt;Route ... /&gt;<br><br>  4. Inject into shell router<br><br>  5. Render matching page</pre><p>That is the entire mechanism that lets twenty-plus product teams ship independently.</p><h3>The Contract Between Shell and Remote</h3><p>A remote being “loadable” is not enough. The shell needs the remote to expose <strong>the exact shape it expects</strong>.</p><p>The contract is one line on each side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcxTXB0nvwUExJeJhzmRXg.png" /></figure><p>The remote exposes a module. The shell imports it under a known name. The default export must be a &lt;Route&gt; element.</p><p>If a remote breaks the contract — renames the exposed module, changes the default export — the fallback plugin catches the failure and shows a graceful error rather than crashing the shell.</p><p>The contract is small on purpose. The smaller the contract, the fewer reasons there are for teams to coordinate.</p><h3>The Dual-Mode Remote: Standalone in Dev, Federated in Prod</h3><p>A remote team needs to develop without running the shell. Spinning up the whole platform locally to iterate on one product is the kind of friction that kills team velocity.</p><p>So every remote in Study V2 is <strong>dual-mode</strong> — the same RouteList.tsx plays two roles:</p><pre>RouteList.tsx<br>                  (pure route definitions, no router)<br>                          │<br>            ┌─────────────┴─────────────┐<br>            ▼                           ▼<br>       STANDALONE                  FEDERATED<br>       (own port)                  (inside shell)   &lt;BrowserRouter&gt;              <br>exposes: {<br>     &lt;Routes&gt;                     &#39;./Module&#39;:<br>       {RouteList}                  &#39;./routes/RouteList.tsx&#39;<br>       &lt;404 /&gt;                  }<br>     &lt;/Routes&gt;                  Shell wraps the same<br>   &lt;/BrowserRouter&gt;             RouteList in its own<br>                                &lt;Routes&gt; + Layout. <br>// Remote: routes/RouteList.tsx — the federated export<br>const RouteList = (<br>  &lt;Route element={&lt;AuthGuard /&gt;}&gt;<br>    &lt;Route path={ROUTES.PROFILE}        element={...} /&gt;<br>    &lt;Route path={ROUTES.STUDENT_MASTER} element={...} /&gt;<br>    &lt;Route path={ROUTES.PDF_VIEWER}     element={...} /&gt;<br>  &lt;/Route&gt;<br>);<br>export default RouteList;// Remote: routes/index.tsx — the standalone wrapper, reusing the same RouteList<br>const Router = () =&gt; (<br>  &lt;Routes&gt;<br>    {RouteList}<br>    &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br>    &lt;Route path=&quot;*&quot;      element={&lt;NotFound /&gt;} /&gt;<br>  &lt;/Routes&gt;<br>);// Remote: rsbuild.config.ts<br>exposes: { &#39;./Module&#39;: &#39;./src/app/routes/RouteList.tsx&#39; }</pre><p>One file, two integration paths. The remote team writes routes once. Federated mode wraps them in the shell’s router. Standalone mode wraps them in the remote’s own router. Same routes. Same components. Same auth guards.</p><h3>The Architecture End to End</h3><p>Putting it together for /study-v2/product-b/123/overview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtZj5jkLZ_x9qRwTPbYQeg.png" /></figure><p>The shell never declared /product-b/:id/overview.</p><p>It never needed to.</p><h3>Two Routing Patterns</h3><p>Not every remote fits the same shape. We use two integration patterns, and the distinction is intentional.</p><h3>Pattern 1 — The Remote Owns a Full Route Tree</h3><p>For mature product areas, the remote exports a complete &lt;Routes&gt; element as its default. The shell maps the prefix, loads the module, and injects the whole tree.</p><pre>const RouteList = (<br>  &lt;Route<br>    element={<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;Outlet /&gt;<br>      &lt;/QueryClientProvider&gt;<br>    }<br>  &gt;<br>    &lt;Route path=&quot;/product-b/:id/overview&quot; element={&lt;Overview /&gt;} /&gt;<br>    &lt;Route path=&quot;/product-b/:id/checkout&quot; element={&lt;Checkout /&gt;} /&gt;<br>    &lt;Route path=&quot;/product-b/:id/lesson/:lessonId&quot; element={&lt;Lesson /&gt;} /&gt;<br>    &lt;Route path=&quot;*&quot; element={&lt;NotFound /&gt;} /&gt;<br>  &lt;/Route&gt;<br>);</pre><pre>export default RouteList;</pre><p>The shell owns the router. The remote plugs into it.</p><h3>Pattern 2 — Shell Owns the Route, Remote Owns the Page</h3><p>For platform flows like payments or contact-us, the shell declares the top-level route but lazy-loads the remote component:</p><pre>&lt;Route path=&quot;/contact-us&quot; element={&lt;ContactUs /&gt;} /&gt;<br>const ContactUs = lazy(async () =&gt; {<br>  const res = await loadRemote(&#39;MFHelpCentre/ContactUsMf&#39;);<br>  return res;<br>});</pre><p>The remote owns the internal workflow — different views driven by query parameters, internal state machines, feature-specific providers. The shell simply decides that the route exists and is responsible for loading the corresponding remote.</p><p>For <strong>large product areas</strong>, the remote owns an entire route tree and can independently add, remove, or modify routes within its namespace without coordinating with the shell. For <strong>workflow-oriented experiences</strong>, the shell owns the top-level route while the remote owns everything inside.</p><p>Both patterns follow the same principle: <strong>one React Router, owned by the shell</strong>. Remotes participate by contributing routes or pages. They do not create competing router instances — which avoids nested-router complexity, navigation inconsistencies, and history synchronization issues.</p><h3>Why This Routing Model Is the Right One</h3><p>It’s easy to make that claim without comparison. Here’s the honest version — what we considered, and why each alternative was worse.</p><h3>Alternative 1 — Eager build-time remotes</h3><p>Most Module Federation tutorials show this:</p><pre>   ┌─────────────────────────────────────────┐<br>   │   SHELL rsbuild.config.ts               │<br>   │                                         │<br>   │   remotes: {                            │<br>   │     MFContent: &#39;MFContent@.../entry.js&#39;,│<br>   │     MFCourses: &#39;MFCourses@.../entry.js&#39;,│<br>   │     ...all twenty hard-coded here       │<br>   │   }                                     │<br>   └─────────────────────────────────────────┘<br>                       ↓<br>   The shell now has 20 deploy-time dependencies.<br>   Each remote URL change requires a shell rebuild.</pre><p>Why we didn’t: every new product team would need a shell PR just to <em>exist</em>. The shell becomes a quiet centralization of every team’s URL. We’d have replaced one bottleneck with another.</p><h3>Alternative 2 — Each remote owns its own router</h3><p>The opposite extreme: each remote brings its own &lt;BrowserRouter&gt; and the shell just mounts them.</p><p>Why we didn’t: nested routers in React Router behave subtly wrong. Two routers reading the same history object race for state. Cross-remote navigation becomes a full mount/unmount with lost scroll position, lost state, and double-rendering. We tried this in the POC. It was worse than the bottleneck.</p><h3>Alternative 3 — Iframe shell</h3><p>Each remote mounted in its own iframe. Full isolation.</p><p>Why we didn’t: cross-iframe auth is painful, design system consistency is impossible without CSS injection, deep linking is fragile, and the single-page-app experience we wanted was simply unbuildable. Iframes solve isolation by killing integration.</p><h3>Alternative 4 — A single-spa-style “top-level config” object</h3><p>A central JSON or JS file that describes every route and which remote serves it.</p><p>Why we didn’t: this is the eager-imports problem with extra steps. If the config lives in the shell, you’re back to shell PRs. If it lives in a separate repo, you’ve created a third team to coordinate with.</p><h3>What we built instead</h3><pre>   ┌──────────────────────────────────────────┐<br>   │  Shell knows: prefix → remote name       │<br>   │  (one line per product, in a flat map)   │<br>   └──────────────────────────────────────────┘<br>                       ↓<br>   ┌──────────────────────────────────────────┐<br>   │  Remote knows: its own routes            │<br>   │  (lives in the remote&#39;s own repo)        │<br>   └──────────────────────────────────────────┘<br>                       ↓<br>   ┌──────────────────────────────────────────┐<br>   │  Module Federation runtime: the bridge   │<br>   │  (lazy load, only when visited)          │<br>   └──────────────────────────────────────────┘</pre><p>One router. One source of truth for ownership. Routes live with the team that owns them. The shell stays thin.</p><p>It’s not novel because the libraries are exotic. It’s correct because the ownership boundaries land in the right place.</p><h3>Flat Routes: A Small Decision That Scales</h3><p>Early in the redesign, there was a temptation to be clever about relative routing — let remotes declare paths relative to their base, infer the prefix at load time. It seemed elegant.</p><p>We abandoned it quickly.</p><p>At scale, “clever” routing becomes impossible to debug.</p><p>Every remote defines fully qualified, absolute paths:</p><pre>const PRODUCT_B_ROUTES = {<br>  OVERVIEW: &#39;/product-b/:id/overview&#39;,<br>  CHECKOUT: &#39;/product-b/:id/checkout&#39;,<br>  LESSON:   &#39;/product-b/:id/lesson/:lessonId&#39;,<br>};</pre><p>Verbose, yes. But when you’re looking at a Sentry trace at 2am and trying to figure out which team owns a URL, you want the answer to be obvious.</p><p>It is.</p><blockquote>A navigation bug in a microfrontend system is usually an ownership ambiguity wearing a technical mask.</blockquote><h3>What Happens When a Remote Fails</h3><p>Remote loading is a network operation. It will fail. CDN hiccups, stale manifests after a deploy, version mismatches — treating failure as exceptional is how you get blank screens in production.</p><p>We handle it at three layers.</p><pre>   ┌─────────────────────────────────────────────────────┐<br>   │  LAYER 3 — Render-time error                        │<br>   │  React Error Boundary inside the remote             │<br>   │  → product area shows a contained error UI          │<br>   ├─────────────────────────────────────────────────────┤<br>   │  LAYER 2 — Retry on transient network failure       │<br>   │  useRemoteModule → registerRemotes({ force: true }) │<br>   │  → user sees retry UI and can recover               │<br>   ├─────────────────────────────────────────────────────┤<br>   │  LAYER 1 — Runtime fallback plugin                  │<br>   │  errorLoadRemote returns a safe fallback module     │<br>   │  → shell never sees an unhandled rejection          │<br>   └─────────────────────────────────────────────────────┘<br>                              ▲<br>                  Shell stays stable.<br>                  Remote failures stay contained.</pre><p>The mental model:</p><ul><li>Remote <strong>load</strong> failure is infrastructure.</li><li>Remote <strong>render</strong> failure is a product bug.</li></ul><p>Both need separate handling, and neither should take down the shell.</p><h3>Results</h3><p><strong>The shell stays stable while the platform grows.</strong></p><p>At the time of writing, Study V2 runs:</p><ul><li><strong>Twenty-plus independently deployed microfrontends</strong> behind a single shell.</li><li><strong>Hundreds of routes</strong> owned entirely by product teams — the shell knows none of them by name.</li><li><strong>A flat prefix map</strong> — one line per product — instead of hundreds of child routes in the shell.</li></ul><p>Operationally:</p><ul><li><strong>Smaller initial load.</strong> Users download only the product area they visit. One product doesn’t cost the others.</li><li><strong>Team autonomy.</strong> Product teams ship new routes without a shell PR. Platform team removed from the critical path.</li><li><strong>Clearer ownership.</strong> Any URL can be traced to an owning team from the prefix map in seconds.</li><li><strong>Deep links intact.</strong> Direct navigation works exactly as expected — shell resolves the prefix and loads the right remote.</li><li><strong>Independent caching.</strong> Each remote has its own cache lifecycle. One team’s deploy doesn’t bust another team’s cache.</li><li><strong>No shell rebuild on new product/feature.</strong> A new microfrontend goes from idea to production traffic without touching the shell artifact.</li></ul><blockquote><strong>A user opening one product shouldn’t have to download every other product on the platform. With federated routes, they don’t.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91fd945714c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/physicswallah-engineering/building-study-v2-the-microfrontend-routing-trap-nobody-talks-about-a91fd945714c">Building Study V2: The Microfrontend Routing Trap Nobody Talks About</a> was originally published in <a href="https://medium.com/physicswallah-engineering">PhysicsWallah Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This in-house solution helped ClearTax save 10,000 man hours!]]></title>
            <link>https://medium.com/cleartax-engineering/cleartax-javascript-data-grid-3ee082afb7c0?source=rss-5bcd368d6b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee082afb7c0</guid>
            <category><![CDATA[ctgrid]]></category>
            <category><![CDATA[cleartax]]></category>
            <dc:creator><![CDATA[Lofty Khanna]]></dc:creator>
            <pubDate>Sat, 17 Oct 2020 18:58:45 GMT</pubDate>
            <atom:updated>2020-10-29T12:38:50.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJxx9Zhn4V1FogREjrDRJQ.jpeg" /></figure><p>Computation of taxes involves a lot of tables for data entry, data visualization, and report downloads. Our ClearTax website is full of such tables. <strong>CTGrid</strong> (ClearTax Javascript Data Grid) is an official table component of ClearTax and is developed inhouse. It is a react component that provides a consistent experience across the entire website.</p><p>CTGrid is a wrapper on top of <a href="https://handsontable.com/">Handsontable</a>. When we mention Handsontable (HOT), two questions are very commonly asked -</p><p><strong>What is Handsontable (HOT)?<br></strong>Handsontable is a data grid with the features and the look &amp; feel of a spreadsheet. Handsontable is written in JavaScript and works with the most popular frameworks such as Angular, Vue, and React.</p><p><strong>Why CTgrid when you can directly use HOT?</strong></p><ul><li>Grid or data tables are the main supporting pillars of our business. We, at ClearTax, keep on exploring new grid libraries (until we can develop it on our own 😜 ) and these libraries keep on getting updated. At present, we are using HOT. In the near future, if we want to use another library, we will just have to write a transformer for backward compatibility. No changes would be required at the application level</li><li>At Cleartax, we believe in making simpler fin-tech products. CTGrid has helped us a lot in maintaining consistency across the organization through its features, renderer, UI, etc.</li><li>We were not very satisfied with the API of Handsontable. One can find it confusing (example: column header name needs to be passed as separate config in the same order as column order) and limited (example: configuration for a column is based on the column index, while it is nicer to have configuration based on column identifier). We were able to tune the API of CT Grid to be simpler and more in line with the way we use grids in our product</li><li>CTGrid supports all features by HOT and also certain additional features. In other words, it is not a wrapper but a superset of HOT.</li></ul><h3><strong>Features of CTGrid -</strong></h3><p><strong>Renderer : </strong>Renderers define what to render inside a particular cell or column. CTGrid supports the default renderer provided by HOT along with the following renderers -</p><ul><li>Button Renderer</li><li>Link Renderer</li><li>Tag Renderer</li><li>Money Renderer: It formats the numeric value.</li><li>Custom Render: <strong>Render your own HTML in cells.</strong></li><li>Conditional Renderer: Renderers in HOT are at the column level. CTGrid allows you to have different types of renderers in the same column conditionally.</li></ul><p><strong>Filters </strong>: In HOT when you add filters, they are added to all columns but in CTGrid you can control for which specific column you want to add filters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8052c90c686d25d3844df376182358b0/href">https://medium.com/media/8052c90c686d25d3844df376182358b0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*7Dj2emUUZr3WotCr" /></figure><p><strong>Validators : </strong>CTGrid provides inbuilt validators for email, phone number and GSTIN. If someone enters a wrong value it highlights it in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*Qp5yH8Xle_w3tXJB" /></figure><p><strong>Select One Radio Button : </strong>We can select one particular record from the grid. It’s a small configuration you need to pass for this. We can also pass a callback function which is executed when a record is selected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c58a73e54ce6d351faa3e7086095a9e/href">https://medium.com/media/6c58a73e54ce6d351faa3e7086095a9e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*2RX3IYkWuaB4ecfT" /></figure><p><strong>Select multiple records : </strong>We can select multiple records or all records from the grid. The callback is executed when we select/deselect all records or multiple records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/0*4Wmg6qFE99Ai8FPp" /></figure><p><strong>Theme : </strong>There is no concept of theming in HOT, on other hand CTGrid Support two themes — <strong>Light</strong> and <strong>Excel</strong>. This is done to maintain UI consistency and reduce the efforts of other developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*WhaE2YtT9IsNn55-" /></figure><p><strong>Displaying Errors :</strong> Sometimes we want to show an error for a particular row or cell but row and cell number keep on changing, so the only thing we rely on for showing errors is data. If a Data object has ‘errorDetails property’, CTGrid would read it and show an error for row or cell. Row-level errors should be resolved before showing cell level error. Below is the contact for error Details:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c97a9668ef16367caf0961e230b8941/href">https://medium.com/media/9c97a9668ef16367caf0961e230b8941/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*KItuuDzmyRjRN_lp" /></figure><h3>Upcoming features in CTGrid -</h3><p><strong>Custom Filters </strong>: HOT’s default filters do not completely solve our purpose/requirement and HOT custom filters are quite confusing to implement. We are building our own configuration based to ease custom filters implementation in CTGrid.</p><p><strong>Inbuilt Pagination </strong>: HOT doesn&#39;t provide any pagination, although CTGrid performance doesn&#39;t lag for 45000 data rows, still at certain instances it is required to paginate the data.</p><p><strong>More Renderers </strong>: We will be adding more renderers to ease the development and latest UI design implementation.</p><p><strong>More Themes </strong>: To give a more rich user experience, we will be adding more themes.</p><p><strong>CTGrid has helped us save more than 10,000 man-hours and with continued improvements helps us provide a rich user experience across the ClearTax website.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee082afb7c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cleartax-engineering/cleartax-javascript-data-grid-3ee082afb7c0">This in-house solution helped ClearTax save 10,000 man hours!</a> was originally published in <a href="https://medium.com/cleartax-engineering">ClearTax Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>