Skip to main content
Systems Engineering

Taming Version Skew in Module Federation

Fixing shared dependency version skew in Module Federation: singleton negotiation rules, semver range pitfalls, and CI gates that catch mismatches pre-deploy.

KBY Technologies11 min read
Taming Version Skew in Module Federation

A host application boots, mounts three independently deployed remotes, and within eleven minutes of runtime a support ticket lands: “Invalid hook call” errors scattered across the checkout flow. Nothing changed in the host. A remote team shipped a patch release of a UI library twenty minutes earlier. This is module federation version skew, and it is a common failure mode in production micro-frontend estates with several independently deployable remotes. The problem is not federation itself; it is the assumption that shared dependency resolution behaves the same way in a distributed, independently-versioned runtime as it does in a monolithic bundle graph.

#The Shared Scope Collision Problem

Webpack’s module federation plugin (and Module Federation 2.0, @module-federation/enhanced, which adds a runtime and plugin system) solves cross-application code sharing by exposing a shared scope object at runtime — effectively a registry mapping package names to loaded module factories, keyed by version. When Host A requests react@18.2.0 and Remote B has already registered react@18.3.1 as a singleton, the federation runtime must decide, at request time, which instance satisfies the consumer’s semver range. Get this wrong and you get one of two catastrophic outcomes: duplicate React instances causing hook context mismatches (typically when React is not shared as a singleton), or a runtime patch in a leaf remote breaking a host that has no visibility into that remote’s release cadence.

This is fundamentally a distributed systems problem wearing a frontend costume. You have independently deployed artefacts, no shared build step, and a runtime negotiation protocol that has to make correctness guarantees across trust boundaries it cannot fully inspect. Treating architectural patterns from service-oriented backends — contract versioning, negotiation, graceful degradation — is the only way to make this reliable at scale.

#Architectural Breakdown: How Module Federation Resolves Shared Dependencies

Every federated container exposes a shared scope populated at container init time. The resolution algorithm, roughly, is:

  • Each remote registers its shared dependencies against the global scope, tagged with version, singleton flag, eager flag, and a semver requiredVersion range.
  • When a consumer requests a shared module, the runtime scans the scope for a version satisfying the requiredVersion range.
  • If singleton: true is set, only one instance of the shared module is ever used. When that instance does not satisfy a consumer’s requested range, the runtime prints a console warning, or throws an error if strictVersion: true is also set. A warning-only mismatch is easy to miss and is the quiet failure vector.
  • If the share is not a singleton and no compatible version exists, a separate copy is loaded and registered, resulting in duplicate copies of the library at runtime. For singleton shares the already-loaded instance is reused, with a warning or error, rather than loading a second copy.

The critical architectural detail engineers miss: module federation does not perform a build-time compatibility check across remotes. There is no central registry validating that Remote B’s React 18.3.1 is compatible with Host A’s assumptions. Compatibility is asserted via semver ranges you configure manually, and it is only validated at runtime, in the browser, on the user’s device. Official documentation on the shared module resolution strategy is available in the Webpack Module Federation concept guide, but it deliberately leaves negotiation policy to the implementer.

#
Singleton Enforcement and the Semver Satisfaction Algorithm

Singleton enforcement matters most for libraries with global mutable state or context-based APIs: React, React DOM, state management libraries, routing libraries. Non-singleton shared dependencies (utility libraries, date formatters) tolerate duplication with only a bundle-size penalty. The failure mode you are engineering against is specifically singleton violation under version skew — where two remotes, each individually correct, produce an incompatible runtime when composed by a host that neither team controls.

Taming Version Skew in Module Federation architecture diagram 1

#Implementation Logic: Building a Version Negotiation Layer

The fix is not “pin everyone to the same version.” That reintroduces the coupled release train you adopted micro-frontends to escape. The fix is a formalised negotiation contract enforced through three layers: strict shared configuration, a runtime interception plugin, and a CI compatibility gate. Pilot each layer on one host and one remote in a staging environment before rolling it out to the whole estate, and keep the previous configuration in version control so you can revert.

#
Step 1 — Strict Mode Shared Configuration

Configure every remote and host to declare explicit semver ranges rather than relying on ranges inferred from package.json or loose wildcards, which make skew harder to see. Before changing anything, record the shared configuration currently deployed.

1// webpack.config.js — host application
2const { ModuleFederationPlugin } = require('webpack').container;
3
4module.exports = {
5  plugins: [
6    new ModuleFederationPlugin({
7      name: 'hostApp',
8      remotes: {
9        checkoutRemote: 'checkoutRemote@https://cdn.kby.tech/checkout/remoteEntry.js',
10      },
11      shared: {
12        react: {
13          singleton: true,
14          strictVersion: true,
15          requiredVersion: '^18.2.0',
16          eager: false,
17        },
18        'react-dom': {
19          singleton: true,
20          strictVersion: true,
21          requiredVersion: '^18.2.0',
22        },
23      },
24    }),
25  ],
26};

Setting strictVersion: true makes the runtime throw an error when the loaded version does not satisfy the required range, rather than only logging a warning, converting a hidden hook-context bug into an immediate, loud, diagnosable error. This is a deliberate architectural trade-off: you are exchanging a soft failure (broken UI, only a console warning) for a hard failure (visible error), which is often preferable in production federation. To undo it, remove strictVersion and redeploy.

#
Step 2 — Runtime Plugin for Dynamic Resolution

For estates running the newer @module-federation/enhanced runtime, you can intercept resolution decisions programmatically rather than relying purely on declarative semver. This lets you implement canary routing, override query parameters, and telemetry on every negotiation event — essential for diagnosing skew incidents post-hoc.

1// runtime-plugin.js — illustrative pseudocode; verify hook and argument names
2// against the runtime plugin documentation for your version before use.
3export default function versionTelemetryPlugin() {
4  return {
5    name: 'version-telemetry-plugin',
6    resolveShare(args) {
7      const { shareScopeMap, scope, pkgName, version } = args;
8      // Inspect what is registered in the share scope for this package.
9      const registered = shareScopeMap && shareScopeMap[scope] && shareScopeMap[scope][pkgName];
10      const registeredVersions = registered ? Object.keys(registered) : [];
11      if (registeredVersions.length > 1) {
12        fetch('/api/telemetry/version-skew', {
13          method: 'POST',
14          body: JSON.stringify({
15            package: pkgName,
16            selected: version,
17            registered: registeredVersions,
18            scope,
19          }),
20        });
21      }
22      return args;
23    },
24  };
25}

This plugin only observes resolution and returns the arguments unchanged. Treat the snippet as a sketch: the hook names and argument shapes must be checked against the Module Federation runtime plugin documentation for your version, and tested in staging first. In practice, the observability layer is what turns version skew from an unpredictable production incident into a measurable, alertable metric with a defined SLO.

#
Step 3 — CI Compatibility Gate

The negotiation contract is worthless if remotes can still deploy breaking changes without warning. Add a CI step that fetches the host’s published contract and checks proposed shared versions against the host’s declared requiredVersion ranges before allowing a remote deploy to proceed. The mf-manifest.json file does not necessarily list the host’s requiredVersion ranges, so the safest approach is to publish a separate contract file (for example, a small JSON file generated from the host’s build config) and gate on that. Start the gate in report-only mode before making it blocking.

Taming Version Skew in Module Federation architecture diagram 2
1#!/usr/bin/env bash
2# ci/check-mf-compat.sh
3set -euo pipefail
4CONTRACT_FILE=$(mktemp)
5# Hypothetical contract file published by the host build, e.g.
6# {"shared":[{"name":"react","requiredVersion":"^18.2.0"}]}
7# Confirm the URL and field names match what your host actually publishes.
8curl -fsS https://cdn.kby.tech/host/shared-contract.json -o "$CONTRACT_FILE"
9export CONTRACT_FILE
10
11node -e '
12  const fs = require("fs");
13  const semver = require("semver");
14  const contract = JSON.parse(fs.readFileSync(process.env.CONTRACT_FILE, "utf8"));
15  const entry = (contract.shared || []).find((s) => s.name === "react");
16  if (!entry || !entry.requiredVersion) {
17    console.error("react not found in host contract");
18    process.exit(1);
19  }
20  const pkgRange = require("./package.json").dependencies.react;
21  const proposed = semver.minVersion(pkgRange);
22  if (!semver.satisfies(proposed, entry.requiredVersion)) {
23    console.error("Incompatible react version for host contract: " + entry.requiredVersion);
24    process.exit(1);
25  }
26'

This converts an implicit runtime assumption into an explicit, enforced deployment gate — the same discipline you would apply to a gRPC contract or an OpenAPI schema on a backend service mesh.

#Failure Modes and Edge Cases

Several edge cases surface repeatedly once module federation is running at scale across more than five remotes:

  • Eager consumption conflicts — setting eager: true on a shared dependency includes the shared module in the initial chunk instead of loading it asynchronously. Use it sparingly and test any combination of remotes that share the same dependency with differing versions.
  • SSR hydration mismatch — server-rendered hosts resolve shared scope at request time on the server, which may differ from the client-side CDN cache state if a remote deployed between the two phases. This produces hydration warnings that are extremely difficult to reproduce locally.
  • Cascading singleton failure — a single remote pushing a major version bump on a singleton dependency without coordinating the host’s requiredVersion range causes every other remote sharing that scope to fail simultaneously, even remotes that made no changes. This is the micro-frontend equivalent of a noisy-neighbour incident.
  • Stale CDN edge caches — remoteEntry.js files cached beyond your deployment’s TTL cause hosts to negotiate against a manifest that no longer matches the deployed container, producing 404s on dynamically imported chunks.

The common thread across all four is that module federation failures are almost always invisible at build time and only manifest under specific runtime composition — meaning your CI pipeline can be fully green while production is broken. This is precisely why the negotiation observability layer in Step 2 is not optional at any meaningful scale.

#Scaling and Security Trade-offs in Module Federation

Beyond correctness, there are structural trade-offs to weigh once federation crosses organisational boundaries — multiple teams, multiple deployment cadences, potentially multiple CDNs.

  • Strict singleton enforcement vs. availability — strictVersion: true improves correctness but converts a version mismatch into a hard runtime crash for the end user rather than a degraded-but-functional experience. Consider a fallback UI boundary around every federated remote import.
  • Runtime negotiation overhead — dynamic resolution via the enhanced runtime adds some per-navigation cost compared to static, build-time bundling. Measure it in your own environment; at high remote counts it is likely small against network latency, but worth profiling under load.
  • Remote script integrity — because remoteEntry.js files are fetched from potentially separate origins, apply Subresource Integrity (SRI) hashes and a strict Content Security Policy restricting script-src to your known CDN origins. An unpinned remote origin is a direct supply-chain attack surface.
  • Version pinning vs. team autonomy — tight semver ranges reduce skew incidents but reintroduce coordination overhead between teams, partially undermining the independence micro-frontends are meant to deliver. The negotiation-plus-telemetry approach above is explicitly designed to preserve autonomy while still surfacing incompatibility before users hit it.
  • CDN cache invalidation strategy — use content-hashed filenames for all federated chunks and a short TTL (under five minutes) on the manifest file itself; this keeps deploy propagation fast without sacrificing chunk-level cache longevity.

None of these trade-offs are resolved by tooling alone. Module federation gives you the mechanism for runtime composition; the negotiation policy, observability, and CI gating described here are what turn that mechanism into a reliable distributed architecture rather than a recurring incident source.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01Webpack Module Federation concept guidewebpack.js.org

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on Taming Version Skew in Module Federation. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.