Micro-Frontends and Large Frontend Architecture

Micro-frontends let many teams build and deploy parts of one web app on their own. This guide explains when that is worth the cost and how to build it so users still get one fast, consistent app.

Frontend system design · Pattern

Be able to decide whether a frontend should be split and pick a composition method. Then design shared dependencies, routing, communication, and deployment for a multi-team app.

Correctness contract: One app failing to load never breaks the rest of the page. Shared singletons such as React exist once per page. Every cross-app message follows a versioned contract, so one team's deploy cannot silently break another team's app.

You know JavaScript modules, bundlers such as webpack or Vite at a basic level, and React routing. Module Federation, import maps, and app shells are explained below. Numbers are teaching estimates.

A small team can ship one frontend from one repo with one pipeline. That stops working at a certain size. Picture 15 teams in one codebase. A build takes 25 minutes. A release needs sign-off from every team. One broken test blocks everyone's deploy. Micro-frontends answer this by splitting the app along team lines. Each team owns a slice, such as search, checkout, or account, and ships it on its own schedule. The cost is real, though. You pay in bundle size, network waterfalls, version conflicts, and harder debugging. Many teams adopt micro-frontends too early and regret it. This guide shows how to make the decision, and how to build it well if you do.

Contents

  1. Concepts to understand first
  2. 1. What problem this solves
  3. 2. When to split, and when not to
  4. 3. Scope and budgets
  5. 4. Build-time vs run-time composition
  6. 5. Module Federation in depth
  7. 6. Shared dependencies
  8. 7. Routing across apps
  9. 8. Design consistency and CSS isolation
  10. 9. Communication between apps
  11. 10. Monorepo vs polyrepo
  12. 11. Ownership, deploys, and rollback
  13. 12. Performance costs
  14. 13. Failure modes
  15. 14. Trade-offs
  16. 15. Interview angle
  17. 16. Summary
  18. 17. Common mistakes
  19. Worked example: a bad checkout deploy at noon
  20. Code lab: a tiny shell with isolated apps
  21. Check yourself
  22. Key terms
  23. Further reading

Concepts to understand first

Micro-frontend

A micro-frontend is a part of a web app that one team owns from code to production. It has its own repo or folder, its own build, and its own deploy. A shell puts the parts together in the browser or on the server.

Example. An online store has a search app, a product app, a checkout app, and an account app. The checkout team deploys three times a day without asking the search team.

Limit. The user still sees one product. Splitting the code does not split the user experience. Design, performance, and accessibility must still feel like one app.

Build-time vs run-time composition

Build-time composition joins parts when the shell is built, usually as npm packages. Run-time composition joins them in the browser or at the edge, when the page loads.

Example. Build-time: the shell depends on @shop/checkout@3.1.0 and must rebuild to get 3.2.0. Run-time: the shell reads a manifest and loads /checkout/3.2.0/remoteEntry.js with no shell rebuild.

Limit. Only run-time composition gives truly independent deploys. It also brings run-time failures that a build would have caught.

Module Federation

Module Federation is a bundler feature, first in webpack 5, now also in Rspack and through Vite plugins. One build can expose modules. Another build can load them at run time, and both can share libraries like React.

Example. The search app exposes ./App in a small remoteEntry.js file. The shell calls import("search/App"). The runtime fetches the file and the chunks it needs.

Limit. Types, versions, and contracts are not checked across builds by default. You must add contract tests and version rules.

Shared singleton

Some libraries must exist once per page. React keeps hook state in one module instance. A router or design system keeps context in one provider. Two copies break these silently.

Example. The shell provides React 18.2. A remote built with React 18.3 asks for ^18.2.0, so it accepts the shell's copy. One React, about 45 KB gzipped, loads once.

Limit. If one remote needs React 19 and the shell has 18, they cannot share. Major upgrades of singletons must be coordinated across all teams.

App shell (host)

The shell is the thin app that loads first. It owns the page layout, sign-in, top-level routing, error boundaries, and loading of the other apps. It should hold almost no business logic.

Example. The shell draws the header and side nav, checks the session, and mounts the checkout app into <main> when the URL starts with /checkout.

Limit. A shell that grows features becomes a new monolith that everyone must change. Keep it small and stable.

1. What problem this solves

Micro-frontends are an organizational tool first. They solve problems of team scale, not user problems. Be honest about this in design reviews and interviews.

Goals

Requirements that do not change

Intuition

Micro-frontends move complexity from the people process into the runtime. You trade "15 teams coordinating every release" for "one platform team managing loading, versions, and contracts". That trade is good only when the people cost is the bigger one.

2. When to split, and when not to

Signals that splitting helps

Signals that splitting hurts

Split by business domain, not by technical layer

Good cuts follow user journeys: search, product page, cart, checkout, account. Each team then owns a vertical slice, from UI to its backend for frontend. Bad cuts follow layers, such as a "header team" and a "forms team". Every feature then needs several teams, which is the problem you wanted to remove.

Try a modular monolith first

A modular monolith is one deployable app with strict internal boundaries. Each domain lives in its own package with an owner, a public API, and lint rules that block deep imports. You get clear ownership and enforced boundaries. Later, if deploy independence is really needed, each package is already shaped like a micro-frontend.

Interview

If an interviewer asks "should we use micro-frontends?", do not say yes at once. Ask about team count, release pain, and shared state. Offer the modular monolith as a step. Recommending against micro-frontends with good reasons is a strong senior signal.

3. Scope and budgets

Example setup

Bytes

Requests and latency

Run-time loading adds steps in a chain. On a 4G link with 100 ms round trip time:

  1. HTML: 100 ms.
  2. Shell JavaScript: another 100 ms plus download.
  3. Manifest to find the app's URL: another 100 ms.
  4. remoteEntry.js: another 100 ms.
  5. The app's chunks: another 100 ms plus download.

That is 500 ms of round trips before the app's code even runs. A monolith needs about 200 ms. Section 12 shows how to cut this back with inlining and preload hints.

Memory

Each app that mounts and unmounts must clean up listeners, timers, and subscriptions. A leak of 5 MB per mount, across 20 navigations in a long session, adds 100 MB. Single-page app sessions can last hours, so cleanup is part of the contract.

4. Build-time vs run-time composition

Build-time: npm packages

Each team publishes its app as a package. The shell imports them and builds one bundle.

Server-side or edge composition

The server or a CDN edge worker stitches HTML fragments from each app into one page. Older forms use Server Side Includes or Edge Side Includes. Newer forms stream fragments from each team's server.

Run-time in the browser

Tip

Mixing is normal. Many large sites render the shell and the main content on the server. They load interactive widgets with Module Federation, and keep iframes only for third-party payment forms.

5. Module Federation in depth

Run-time composition diagram: the browser loads the shell from a CDN, the shell fetches a manifest, the federation runtime fetches a remote entry and chunks for the search app, negotiates shared singleton versions, and mounts the app. Apps talk through a versioned event bus. The checkout app loads lazily on navigation.
Figure 1. The shell only knows app names. The manifest maps names to URLs, so teams can deploy new versions without a shell release.

The remote's config

// webpack.config.js in the search app (a "remote")
new ModuleFederationPlugin({
  name: "search",
  filename: "remoteEntry.js",
  exposes: { "./App": "./src/mount.tsx" },
  shared: {
    react:                 { singleton: true, requiredVersion: "^18.2.0" },
    "react-dom":           { singleton: true, requiredVersion: "^18.2.0" },
    "react-router-dom":    { singleton: true, requiredVersion: "^6.20.0" },
    "@shop/design-system": { singleton: true, requiredVersion: "^5.0.0" },
  },
});

How a load works

  1. The shell's own bundle starts behind an async boundary. Its entry file only does import("./bootstrap"). This gives the runtime a moment to set up the shared scope before any shared module is used.
  2. The shell registers what it can provide in the shared scope: React 18.2.0, router 6.22, design system 5.3.
  3. On navigation to /search, the shell asks for search/App. The runtime fetches remoteEntry.js from the URL in the manifest. This file is small, often under 10 KB. It lists exposed modules and shared needs.
  4. The remote says "I need React ^18.2.0 as a singleton". The runtime finds 18.2.0 in the shared scope and uses it. No second React is downloaded.
  5. The runtime fetches only the chunks for ./App. The shell calls the exposed mount function.

Expose a mount function, not a component

Exposing a raw React component ties the shell to the remote's React version and internals. A framework-neutral contract is safer:

// src/mount.tsx in the search app
export function mount(el: HTMLElement, ctx: { basePath: string; bus: EventBus; user: User | null }) {
  const root = createRoot(el);
  root.render(<SearchApp basePath={ctx.basePath} bus={ctx.bus} user={ctx.user} />);
  return () => root.unmount();   // the shell calls this on navigation away
}

The contract is small: mount(el, ctx) returns an unmount function. The shell does not care which framework runs inside. A team could move from React to another framework without changing the shell.

Dynamic remotes from a manifest

Do not hard-code remote URLs in the shell build. Fetch a manifest at start-up, such as { "search": "https://cdn.shop.com/search/1.8.2/remoteEntry.js" }. The manifest is the deploy switch. Changing one URL releases or rolls back an app in seconds. Give the manifest a short cache, such as max-age=60. Give versioned app files max-age=31536000, immutable.

Mistake

Serving remoteEntry.js from a fixed URL with long caching. Users keep the old entry file, which points to chunk names that no longer exist. Put the version in the path, and keep old versions on the CDN for days so open tabs still work.

6. Shared dependencies

Which libraries to share

Version rules

Govern versions centrally

Keep one file, owned by the platform team, that lists the allowed range for each shared singleton. Every app's CI checks its package.json against this file. A team that bumps React to 19 alone fails CI, not production.

Upgrading a singleton across all apps

  1. The platform team announces the target, such as React 19, with a date.
  2. Each team makes its app compatible with both versions and widens its range, such as "^18.2.0 || ^19.0.0".
  3. When all apps accept both, the shell switches to provide React 19.
  4. Later, teams drop the old range.

This is slow. It is the main ongoing tax of micro-frontends. Plan for one or two such upgrades per year.

7. Routing across apps

Two levels of routing

One history

All apps must share the browser's one history stack. Use a single router instance from the shared scope, or have each app's router listen to the same history object. Two routers that each call pushState without knowing about each other break the back button.

Links between apps

Search links to a product page owned by another team. If it uses a plain <a href>, the browser reloads the whole page. Instead, give apps a shell-provided navigate(url) function or a shared Link component. The shell intercepts the navigation, unmounts search, and mounts the product app with no reload.

Navigation and accessibility

After each navigation, the shell moves focus to the new page's main heading or to <main>. It updates document.title and announces the new page in a polite live region. A screen reader user then knows the page changed, as with a full reload.

Race conditions

A user clicks "Search" then "Account" quickly. The search app is still loading when account is requested. The shell must track a navigation id and ignore results from older navigations. Otherwise search could mount after account and win. The code lab shows this guard.

8. Design consistency and CSS isolation

One design system

Users must not see five button styles. Every app uses the same design system package. Load its tokens and theme CSS once from the shell. Share its JavaScript as a singleton, so all apps see one theme provider. A design system major version is upgraded like React: coordinated, with a window where both versions work.

CSS collisions

Two apps can both define .card or .button. When both are on the page, or when one app's styles stay loaded after it unmounts, they fight. Defenses:

Shared layout pieces

The header, footer, and nav belong to the shell. Apps never draw their own header. If an app needs to change the header, such as showing a cart count, it sends an event or calls a shell API. It never reaches into the shell's DOM.

9. Communication between apps

Every channel between apps is a contract between teams. Fewer, simpler channels are better. In order of preference:

1. The URL

The URL is the best shared state. It is visible, shareable, and survives reload. Search passes a product to the product app through /product/123, not through a message.

2. Props from the shell

The shell passes stable facts to mount: the user, the locale, feature flags, and the base path. These change rarely. When they do, the shell calls an update(ctx) function or remounts.

3. Events with versioned contracts

For "something happened" messages, use a small event bus. It can be built on CustomEvent dispatched on window, or as a tiny library from the shell.

4. Shared state store, rarely

A global store that all apps read and write couples them tightly. A change to its shape breaks everyone. Avoid it. If two apps need deep shared state, they may belong in one app.

Across tabs

Signing out in one tab should sign out all tabs. The shell owns this. It uses BroadcastChannel or the storage event, and tells each mounted app through the bus.

Mistake

Letting apps import each other's internal modules through federation, such as checkout/utils/formatPrice. Now checkout cannot refactor without breaking search. Only expose public entry points such as mount. Put shared helpers in a versioned package.

10. Monorepo vs polyrepo

Monorepo

All apps live in one repository, with tools such as Nx or Turborepo, and still deploy separately.

Polyrepo

Each app has its own repository and pipeline.

A common choice

Use a monorepo with separate deploy pipelines per app. Enforce boundaries with code owner files and import lint rules. Independence comes from deploys and ownership, not from separate repos.

11. Ownership, deploys, and rollback

Deploy flow diagram: team A merges to main, CI builds and runs contract and shared version checks, uploads hashed files to an immutable asset store, and registers a canary in the manifest service. Shells in user browsers read the manifest and load the new version for 5 percent of users. Errors are reported tagged by app and version, on-call is alerted, and the manifest pointer is rolled back.
Figure 2. A deploy uploads new files and moves a pointer. A rollback moves the pointer back. No file is ever overwritten.

Ownership rules

Safe deploys

Integration testing

Each team tests its own app with the shell and a mocked bus. A shared end-to-end suite runs the main user journeys, such as "search, add to cart, check out". It uses the current production manifest with one app swapped for the candidate. This catches cross-app breaks before users do.

Tip

Show app versions in a hidden debug panel, such as when the URL has ?debug=1. Support engineers can then see which versions a user had when a bug happened.

12. Performance costs

Where the cost comes from

Fixes

A worked number

Before fixes: 5 round trips at 100 ms, plus 300 KB of JavaScript with 60 KB duplicated. LCP was 3.4 seconds on mid-range phones. After inlining the manifest, preloading the route's remote, and fixing a router version mismatch that duplicated 60 KB: 3 round trips and 240 KB. LCP fell to 2.3 seconds.

Intuition

Users do not care how many teams built the page. Every millisecond of micro-frontend overhead is a cost your org chart puts on the user. Measure it, budget it, and remove as much as you can.

13. Failure modes

14. Trade-offs

Micro-frontends vs modular monolith

Module Federation vs import maps

Web Components vs framework mount functions

Client composition vs server composition

15. Interview angle

Common prompts: "Our frontend has 20 teams and releases are slow. What do you do?" or "Design the architecture for a large e-commerce frontend." A strong answer goes in this order:

  1. Diagnose. Ask for team count, release pain, build time, shared state, and legacy code. Decide if the problem is organizational or technical.
  2. Consider the cheaper option. Modular monolith with affected-only builds and code owners.
  3. If splitting, cut by domain. Name the apps and their owners.
  4. Pick composition. Server rendering for the shell and main content, Module Federation for apps, iframes only for third-party content.
  5. Contracts. mount and unmount, shell props, versioned events, the URL as shared state.
  6. Shared dependencies. Singleton list, central version policy, coordinated upgrades.
  7. Operations. Manifest-based deploys, canaries, rollback, error attribution, per-app budgets.
  8. Costs. Show the waterfall numbers and how to cut them.
Interview

Draw the request waterfall on the board with times. Then show which arrows disappear with an inlined manifest and preload hints. Concrete numbers make the trade-off real and set you apart.

16. Summary

17. Common mistakes

Worked example: a bad checkout deploy at noon

The checkout team merges a change at 12:00. It has a bug: the payment step throws when a saved card has no expiry date. Here is how the system limits the damage.

  1. CI builds checkout 3.2.0. The central version check passes: React ^18.2.0, router ^6.20.0, design system ^5.0.0. Contract tests pass: mount exists and events match types.
  2. CI uploads hashed files to /checkout/3.2.0/. Version 3.1.0 stays on the CDN untouched.
  3. CI tells the manifest service to serve 3.2.0 to 5 percent of users, chosen by a hash of their user id.
  4. At 12:04 a user in the canary loads the store. The HTML has the manifest inlined, with checkout: /checkout/3.2.0/remoteEntry.js. The shell preloads it only when the user enters the cart.
  5. The user clicks "Pay". The payment step throws. The shell's error boundary around the checkout slot catches it. The header, the cart count, and the nav still work. The slot shows "Something went wrong in checkout. Try again."
  6. The boundary reports the error with tags app=checkout, version=3.2.0, and the route.
  7. By 12:09, real user monitoring shows the checkout error rate for 3.2.0 at 4 percent against 0.1 percent for 3.1.0. The alert goes to the checkout on-call, not to the search or platform teams.
  8. The on-call engineer moves the manifest pointer back to 3.1.0 at 12:11. No build is needed.
  9. Within a minute, new page loads get 3.1.0. Users who retry in an open tab trigger a route change, which re-reads the manifest and loads 3.1.0.
  10. About 5 percent of users who reached payment in 11 minutes saw the error. With a monolith and no canary, every user would have seen it until a full redeploy, which takes about 30 minutes.
  11. The team adds a test for cards with no expiry, ships 3.2.1 through the same canary, and promotes it to 100 percent at 15:00.

Code lab: a tiny shell with isolated apps

This script models a shell. It routes by prefix, loads each app once, mounts and unmounts it, isolates load failures, guards against navigation races, and passes a versioned event bus. Remotes are fake async functions, so it runs in Node. Save it as shell.mjs and run node shell.mjs with Node 18 or later.

// Fake remotes. In a browser these would be dynamic import() of remoteEntry files.
const remotes = {
  search: async () => ({ mount: (el) => { el.html = "Search UI"; return () => { el.html = ""; }; } }),
  checkout: async () => { throw new Error("remoteEntry.js 503"); },
  account: async () => ({ mount: (el, { bus }) => {
    el.html = "Account UI";
    const off = bus.on("cart:updated@1", (e) => console.log("  account sees cart count", e.count));
    return () => { off(); el.html = ""; };
  } }),
};
const routes = [["/search", "search"], ["/checkout", "checkout"], ["/account", "account"]];

function createBus() {
  const subs = new Map();
  return {
    on(type, fn) { (subs.get(type) ?? subs.set(type, new Set()).get(type)).add(fn); return () => subs.get(type).delete(fn); },
    emit(type, payload) { for (const fn of subs.get(type) ?? []) fn(payload); },
  };
}

function createShell(el) {
  const bus = createBus();
  const cache = new Map(); // app name -> promise of module, loaded once
  let unmount = null, navId = 0;
  async function navigate(path) {
    const id = ++navId;
    const match = routes.find(([prefix]) => path.startsWith(prefix));
    if (unmount) { unmount(); unmount = null; }
    if (!match) { el.html = "Not found"; return; }
    const name = match[1];
    el.html = `Loading ${name}...`;
    try {
      if (!cache.has(name)) cache.set(name, remotes[name]());
      const mod = await cache.get(name);
      if (id !== navId) return; // user navigated again while loading
      unmount = mod.mount(el, { bus, basePath: match[0] });
    } catch (err) {
      cache.delete(name); // allow a retry on the next visit
      if (id === navId) el.html = `${name} is unavailable (${err.message}). Other pages still work.`;
    }
  }
  return { navigate, bus };
}

const el = { html: "" };
const shell = createShell(el);
for (const path of ["/search?q=shoes", "/checkout", "/account"]) {
  await shell.navigate(path);
  console.log(path.padEnd(16), "->", el.html);
}
shell.bus.emit("cart:updated@1", { count: 3 });
shell.navigate("/search"); shell.navigate("/account"); // fast double click
await new Promise((r) => setTimeout(r, 0));
console.log("after race      ->", el.html);

Expected output: search mounts, checkout shows a fallback message while the shell keeps working, and account mounts. Account then logs account sees cart count 3. After the fast double click, the result is Account UI, because the stale search load is ignored. Try removing the if (id !== navId) return line. Then make the search loader slower with a setTimeout, and watch search win the race by mistake.

Check yourself

  1. A company has 3 frontend teams and slow builds. Should they adopt micro-frontends?
    Answer

    Probably not. The coordination cost among 3 teams is small, and micro-frontends add runtime cost and governance. Fix builds first with a modular monolith, affected-only builds, and remote caching.

  2. Why is build-time composition with npm packages not "independent deploy"?
    Answer

    Every app release must be pulled into the shell, rebuilt, and redeployed. Teams depend on the shell's release, which recreates the shared release train.

  3. What breaks if two micro-frontends each load their own copy of React?
    Answer

    The page downloads about 45 KB extra. Worse, hooks and context break when a component from one copy renders inside a tree owned by the other. Mark React as a shared singleton with a compatible range.

  4. Why should a remote expose mount(el, ctx) instead of a React component?
    Answer

    A mount function is a framework-neutral contract. The shell does not depend on the remote's framework or its internals. The returned unmount function makes cleanup explicit.

  5. The checkout team wants to rename the count field in cart:updated@1. What is the safe process?
    Answer

    Create cart:updated@2 with the new field. Emit both versions until all consumers have moved to version 2, checked by contract tests and a usage search. Then stop emitting version 1.

  6. Name two ways to cut the run-time loading waterfall.
    Answer

    Inline the manifest in the HTML to remove one round trip. Add modulepreload or preload links for the current route's remote entry and main chunk, so they download in parallel with the shell. Serving from one origin and prefetching on hover also help.

  7. How do you roll back one micro-frontend in under a minute?
    Answer

    Point the manifest entry for that app back to the previous version's immutable URL. The old files are still on the CDN, so no build is needed. New loads and route changes pick it up.

Key terms

Micro-frontend
A part of a web app owned, built, and deployed by one team on its own.
Shell (host)
The thin app that loads first and owns layout, auth, top routing, and loading other apps.
Remote
In Module Federation, a build that exposes modules for other builds to load at run time.
remoteEntry.js
The small file a remote publishes that lists its exposed modules and shared needs.
Shared scope
The run-time registry where builds offer and request shared libraries and their versions.
Singleton
A shared library that must have exactly one instance per page, such as React.
Import map
A standard JSON script that maps bare module names to URLs for native ES modules.
Manifest
A file or service that maps each app name to the URL of its current version.
Modular monolith
One deployable app with strict internal module boundaries and owners.
Contract test
A test that checks an app still meets its agreed interface, such as exports and event shapes.
Canary release
Serving a new version to a small share of users first, then widening it if healthy.
Error boundary
A component that catches render errors in its subtree and shows a fallback.

Further reading

Primary references