Edge-Side Includes: Composing Micro-Frontends
How Varnish and Fastly assemble micro-frontend fragments at the CDN edge using edge-side includes, with cache-key isolation and origin failure fallbacks.

In this guide
Table of Contents
Table of contents
Client-side micro-frontend composition — whether via Module Federation, iframes, or a runtime shell fetching remote entries — pushes the assembly cost onto the browser. Every fragment requires a JavaScript execution context, a network round trip past the CDN edge, and a hydration cycle before it becomes visible. For latency-sensitive storefronts and content platforms, that model is frequently the wrong trade-off. Edge-side includes (ESI) move fragment assembly into the CDN’s edge PoP, before the response ever reaches the client, turning composition into an HTTPThe KBY LexiconHTTPHTTP is a stateless application-level protocol for request and response messages. Safe validation requires a bounded target and both protocol and application evidence. -layer concern rather than a JavaScript-runtime concern.
This is not a new idea — ESI was specified by Akamai, Oracle and others and submitted to the W3C as a Note back in 2001 — but it has re-emerged as a serious architecture for teams running multiple independently deployed frontend teams against a shared edge cache. The problem it solves is specific: how do you compose a page from fragments owned by different teams, with independent deploy cadences and independent cache lifetimes, without shipping a client-side orchestration framework or coupling teams to a single origin.
#The Bottleneck: Origin-Coupled Composition
In a monolithic frontend, a single origin renders the full page and the CDN caches one object per URL. Once you split ownership across teams — navigation, product data, recommendations, footer — you either force all teams to render into one origin process (a distributed monolith with a shared release train), or you push composition to the client and accept the JavaScript execution tax.
Both options have measurable costs. Server-side composition in a single origin means one team’s slow database query blocks the entire page’s TTFB. Client-side composition means the browser cannot start painting until multiple round trips resolve, and any fragment failure becomes visible as a layout shift or a blank panel. Neither approach lets the CDN cache fragments at different TTLs — the header banner might be cacheable for an hour, the recommendation panel for thirty seconds, and the price block never at all.
Edge-side includes decouple these concerns. The CDN retrieves a base HTML document containing ESI directives, resolves each <esi:include> tag against its own origin (or against another cache tier), and stitches the result into a single response before it leaves the PoP. Each fragment carries its own cache-control semantics. The client receives one fully composed HTML document with zero additional round trips.

#Architectural Breakdown
An edge-side includes deployment has three logical tiers:
- Shell origin — serves the base template containing ESI markup. This is typically a thin, highly cacheable document with no user-specific data.
- Fragment origins — independent services, one per team or domain, each returning an HTML fragment with its own
Cache-ControlandSurrogate-Controlheaders. - Edge processor — the CDN or reverse proxy (Varnish, Fastly, Akamai) that parses ESI tags, issues sub-requests to fragment origins, and assembles the final response.
The critical architectural decision is cache-key granularity. The shell document’s cache key should be broad (path plus a small cookie set), while each fragment’s cache key should be scoped to only the parameters that affect that fragment. A recommendations fragment might vary on a user segment cookie; a navigation fragment might not vary on anything at all. Getting this wrong is the single most common cause of edge-side includes deployments underperforming client-side composition — over-broad fragment cache keys collapse hit ratios to near zero.
Rendering diagram...
#Implementation Logic
Rolling out edge-side includes for an existing micro-frontend estate follows a predictable sequence:
- Identify page regions with divergent cache lifetimes and ownership boundaries — these become fragment boundaries.
- Define a fragment contract: each fragment origin must return a self-contained HTML block with no reliance on shell-level JavaScript state, plus explicit
Surrogate-Controlheaders. - Configure the shell template with
<esi:include>directives, includingonerror="continue"fallbacks for graceful degradation. - Configure the edge processor (Varnish VCL, Fastly VCL, or Akamai property manager) to enable ESI processing and set per-fragment cache-key rules.
- Instrument fragment-level cache hit ratios separately from the shell hit ratio — they will diverge significantly and need independent alerting thresholds.
#Shell Template with Edge-Side Includes
1<!-- shell for SKU 12345, written by the shell origin; Surrogate-Control: max-age=3600 -->
2<!DOCTYPE html>
3<html>
4<head><title>Product Page</title></head>
5<body>
6 <esi:include src="/fragments/nav" onerror="continue"/>
7 <main>
8 <esi:include src="/fragments/product-details?sku=12345" onerror="continue"/>
9 <esi:include src="/fragments/price?sku=12345" onerror="continue"/>
10 <esi:include src="/fragments/recommendations" onerror="continue"/>
11 </main>
12 <esi:include src="/fragments/footer" onerror="continue"/>
13</body>
14</html>#Varnish VCL for ESI Processing
1sub vcl_backend_response {
2 if (bereq.url ~ "^/shell/") {
3 set beresp.do_esi = true;
4 set beresp.ttl = 1h;
5 }
6 if (bereq.url ~ "^/fragments/price") {
7 # fallback only: vcl_recv already passes these; a 120s hit-for-miss
8 # marker stops requests queueing behind each other
9 set beresp.uncacheable = true;
10 set beresp.ttl = 120s;
11 }
12 if (bereq.url ~ "^/fragments/recommendations") {
13 set beresp.ttl = 30s;
14 set beresp.http.Vary = "X-User-Segment";
15 }
16}
17
18sub vcl_recv {
19 if (req.url ~ "^/fragments/price") {
20 return (pass);
21 }
22 if (req.url ~ "^/fragments/recommendations") {
23 if (req.http.Cookie ~ "(^|;\s*)segment=") {
24 # matches segment= as the first or a later cookie, but not xsegment=
25 set req.http.X-User-Segment = regsub(req.http.Cookie, "^(?:.*;\s*)?segment=([^;]*).*$", "\1");
26 } else {
27 set req.http.X-User-Segment = "default";
28 }
29 # the built-in vcl_recv passes any request that carries a Cookie header
30 unset req.http.Cookie;
31 }
32}The do_esi = true flag tells Varnish to parse the response body for ESI tags and issue sub-requests through the same cache, meaning fragment responses benefit from the existing cache pool rather than requiring a separate fragment cache tier. Fastly’s VCL enables ESI with the esi; statement, which only takes effect in vcl_fetch, and supports only the include, comment and remove directives, as documented in the Fastly VCL reference. Teams building on the open standard should also review the original W3C ESI Language specification, since vendor implementations diverge on error-handling verbs and variable substitution syntax. The template has the shell origin write the SKU into each src URL because neither Varnish nor Fastly’s VCL evaluates ESI variables such as $(QUERY_STRING{sku}); Akamai’s dialect does, but a literal URL works everywhere. It also uses no <esi:remove> block: an ESI processor deletes that content, so it appears only when the page is served without ESI processing and is never a fallback for a failed include. Fallback content needs esi:try with esi:attempt and esi:except, which Akamai supports and Varnish and Fastly do not. Varnish also ignores onerror unless the esi_include_onerror feature flag is enabled, and its handling of failed includes has changed between releases, so check the documentation for your version.

#Failure Modes and Edge Cases
Edge-side includes introduce failure surfaces that do not exist in monolithic rendering. The most common in production:
- Cascading sub-request timeouts — if a fragment origin degrades, the edge processor blocks assembly until its sub-request timeout expires. Without aggressive per-fragment timeouts (typically 200–400ms) a single slow origin inflates the composed response’s TTFB for every page using that fragment.
- Cache-key collision — two teams naming fragment query parameters identically (
?id=) can cause the edge processor’s cache-key normalisation to conflate unrelated fragments if the CDN config was copied across properties without adjustment. - Nested ESI depth limits — Varnish’s
max_esi_depthparameter defaults to 5; includes nested deeper than that are not processed and Varnish logs an error, so a fragment-of-fragment architecture that exceeds it returns a page with content missing rather than failing loudly. Other CDNs set their own limits, so check your vendor’s documentation. - Cookie leakage into cache keys — a fragment origin returning
Vary: Cookiewithout scoping to a specific cookie name will collapse hit ratios across the entire fragment tier, since every unique session becomes its own cache entry. - Partial-failure UX —
onerror="continue"prevents a fragment failure from breaking the whole page, but it also means broken fragments fail silently unless surrogate-side loggingThe KBY LexiconLoggingLogging is the practice of recording timestamped system events to durable storage for later diagnosis, correlation and audit. is wired to capture sub-request status codes.
#Decision Matrix: Composition Strategies
| Strategy | Assembly Location | Cache Granularity | Failure Isolation | Client JS Cost |
|---|---|---|---|---|
| Edge-side includes | CDN edge PoP | Per-fragment TTL/key | High (onerror fallback) | None |
| Module Federation | Browser runtime | Bundle-level only | Medium (error boundaries) | High |
| Iframe composition | Browser (isolated context) | Per-frame HTTP cache | Very high | Medium |
| Server-side monolith | Single origin | Page-level only | Low | None |
#Scaling and Security Trade-offs
Adopting edge-side includes shifts operational responsibility toward CDN configuration ownership, which has consequences worth weighing against the alternatives discussed in these architectural patterns for distributed frontends:
- Scaling gains — fragment origins scale independently and can be deployed on entirely different stacks; a Node.js recommendations service and a Java pricing service coexist behind the same shell without coordination.
- Reduced client compute — no bundle parsing or hydration cost for composition logic, which matters disproportionately on low-end mobile devices where JavaScript execution, not network, dominates render time.
- Vendor lock-in risk — ESI dialect differences between Varnish, Fastly and Akamai mean fragment contracts are not portable across CDN vendors without a compatibility shim.
- Expanded attack surface — sub-requests to fragment origins bypass client-facing WAF rules unless the edge processor re-applies inspection on each internal fetch; SSRF-style risks emerge if fragment
srcattributes accept unsanitised query input. - Cache poisoning exposure: the edge caches the shell and each fragment separately and assembles them on delivery, so a malformed fragment response is cached under its own key and served inside every page that includes it until its TTL expires, making fragment-origin input validation non-negotiable.
- Debuggability cost — request tracing across shell, edge processor, and multiple fragment origins requires surrogate-side header propagation (e.g. injecting a shared trace ID before sub-requests fire) that most teams underinvest in until an incident forces the issue.
Edge-side includes are not a universal replacement for client-side composition; they suit content-heavy, cache-friendly page structures far better than highly interactive, stateful UI regions. The pragmatic pattern in most estates we have reviewed is hybrid: ESI for the outer shell and largely static regions, with a lightweight client-side island reserved for genuinely interactive fragments such as cart state or live pricing widgets that cannot tolerate edge-cache staleness.
Evidence trail
Sources and verification
Primary documentation and external technical references used in this article.
About this page
Credited to
Dates
Published
Last updated
Corrections
- : Corrected during a review of published articles. Details
Read-only scripts
- Windows devices with no BitLocker recovery key in Entra IDMicrosoft Entra ID, Windows
- Intune devices that haven't synced in N daysMicrosoft Intune
- Mailboxes forwarding to external addressesExchange Online
- BitLocker status of every volume on this PCWindows
Upcoming deadlines
- Intune moves to macOS 15 and laterQ4 2026
- SAP SuccessFactors provisioning: move from basic auth to workload identityNovember 2026
- Intune November release: JIT registration reminder at APNs renewal and automatic JIT for eligible tenantsNovember 2026
Explore KBY
The KBY Brief
A short email about twice a week with new runbooks, configuration traps and fixes from KBY Technologies.
SubscribeRelated Engineering Labs
Related articles
Software Architecture
Digital Cinema Architecture as a Distributed System
Mapping the DCP payload from ingest through KDM decryption to projection reveals digital cinema architecture as an edge cryptography system.
Software Architecture
Speculation Rules API: Architecting Safe Prerendering
How document rules, score-based heuristics and No-Vary-Search headers let the Speculation Rules API prerender navigations without wasting origin compute.
Software Architecture
Backend-for-Frontend Patterns for API Fan-Out
How client-specific BFF layers, aggregation logic and edge deployment stop API fan-out from strangling mobile and web latency budgets.
Software Architecture
API Returns 429 Too Many Requests: Fixing Retry Storms with Backoff
How to diagnose persistent HTTP 429 responses and replace synchronised retries with Retry-After handling, jittered backoff and client-side throttling.
Learn More About KBY
About KBY
Learn about our mission, how our content is produced, and how we handle corrections.
Why Trust KBY
How KBY content is produced, what is checked automatically, and how errors are corrected.
The KBY Brief
A short email about twice a week with new runbooks, configuration traps and fixes from KBY Technologies.
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.
Comments
Add a thoughtful note on Edge-Side Includes: Composing Micro-Frontends. Comments are checked for spam and held for moderation before appearing.