Skip to main content

Angular SSR: Five Changes for TTFB and Core Web Vitals

Five steps on Angular SSR to lower TTFB and improve LCP, INP and CLS, with the measurements of the real case from February 2026.

What do you think about this article?

Angular SSR: Five Changes for TTFB and Core Web Vitals
Angular PerformancePhoto:Bibek ghoshPexels

At a Glance

Five steps on Angular SSR to lower TTFB and improve LCP, INP and CLS, with the measurements of the real case from February 2026.

To get TTFB <1s and Core Web Vitals >95 in Angular 21 SSR you need 5 combined steps: @defer loading for below-the-fold components, selective route prerendering, multi-layer caching (browser/CDN/backend), image optimization with NgOptimizedImage, and aggressive bundle splitting with tree shaking. This article shows how to reduce TTFB from 1.8s to 0.6s (-67%) in the real case of federicocalo.dev.

Introduction: Why TTFB <1s Today (2026)?

The Core Web Vitals are three metrics, LCP, INP and CLS, and a page passes them if it reaches the "good" values at the 75th percentile of real visits, separating mobile and desktop (web.dev, Web Vitals). TTFB is not a Core Web Vital: web.dev defines it as a rough guideline, with good values up to 0.8 seconds and poor ones above 1.8, useful because it comes before FCP and LCP and can therefore prevent them from reaching good values. For an Angular SSR app the challenge is to keep low the server response time (Step 2 and Step 3), the amount of bytes transferred (Step 4 and Step 5) and the JavaScript that blocks interaction (Step 1).

Revision note (2026-11-13). The general points about Angular and the Core Web Vitals were checked against the official documentation as of 2026-11-13 (list at the end). The figures concerning the site are the original ones from February 2026: they have not been re-measured. The code blocks are outlines to adapt and were not run for this revision.

This article documents 5 production-ready steps applied to federicocalo.dev (Angular 21.2.9 SSR, 1493 TS files, 702 IT+EN articles, 1014 prerendered routes, prod build with 4GB heap). Target: Angular engineers with 3+ years of experience who want to scale from Lighthouse 62 to 96+ while keeping the user experience smooth on mobile.

Baseline & Metrics: What We Measure

Before optimizing, we define the measurement framework. The Core Web Vitals are three (LCP, INP, CLS); FCP and TTFB are not, but we measure them together because they come before them and explain their values. "Good" thresholds from web.dev, to be read at the 75th percentile:

  • LCP (Largest Contentful Paint): When the main content loads. Good target: ≤2.5s. In the real case, TTFB contributes 40% to LCP.
  • FCP (First Contentful Paint): First visible pixel. Target: ≤1.8s. It depends on TTFB (server) + transfer (bundle size) + parse (main thread).
  • CLS (Cumulative Layout Shift): Visual stability. Target: ≤0.1. Cause: undeclared image/ad/font loading.
  • INP (Interaction to Next Paint): Latency of the response to input. Target: ≤200ms. Field metric. Cause: long tasks (JS blocking).
  • TTFB (Time To First Byte): Server latency. Good value: ≤0.8s (poor above 1.8s). It is not a Core Web Vital.

The five items do not have the same status: three are the Core Web Vitals that count for the pass threshold, two are supporting metrics. Where they are measured also matters: LCP, INP and CLS are evaluated on field data, that is on real visits; a lab run such as Lighthouse approximates them. In particular INP requires real interactions, so it does not appear in the Lighthouse Performance score, which is made up of FCP (10%), Speed Index (10%), LCP (25%), Total Blocking Time (30%) and CLS (25%) according to the Lighthouse 10 documentation consulted on 2026-11-13. A Lighthouse "95+" is therefore a lab score and is not, by itself, a pass of the Core Web Vitals.

Measurement tools: Lighthouse CI (local), WebPageTest (remote), Chrome DevTools (real browser), web-vitals npm (RUM field data). Configuration:


# Install web-vitals for RUM
npm install web-vitals

# Lighthouse CI config (.lighthouserc.json)
{
  "ci": {
    "collect": { "url": ["http://localhost:4200/it"] },
    "assert": {
      "assertions": {
        "first-contentful-paint": ["error", { "maxNumericValue": 1800 }],
        "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
        "cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }]
      }
    }
  }
}
  

The block shows the command to install web-vitals, which collects the field metrics, and a Lighthouse CI configuration with three lab assertions: FCP, LCP and CLS with the thresholds seen above, and the assertion fails (error) if the value exceeds them. The INP assertion, present in the original version, was removed: in the Lighthouse code the interaction-to-next-paint audit declares only timespan as a supported mode, while a collection of URLs like this one works in navigation mode. The block is an outline to adapt, not run.

Step 1: @defer Loading for Below-the-Fold Components (-300ms TTFB)

The template @defer block postpones loading a component's code until a trigger fires. It does not coincide with deferred hydration, which is a distinct feature and is activated with the hydrate triggers (see the paragraph on SSR below). In the case of federicocalo.dev, 50 ArticleCards and 15 ToolCards are below the fold: only the hero + navbar require sync hydration.

Basic Syntax:


<!-- Render now (critical path) -->
<article-hero />

<!-- Defer until the viewport reaches this block -->
@defer (on viewport; prefetch on idle) {
  <article-list [articles]="articles$ | async" />
} @placeholder {
  <div class="skeleton-card" />
}

<!-- Defer until the user interacts (click or keyboard) with the placeholder -->
@defer (on interaction) {
  <comment-section />
} @placeholder {
  <button>Show comments</button>
} @loading (after 200ms) {
  <p>Loading comments...</p>
}
  

The first block shows the difference between a component rendered immediately (article-hero) and two deferred components. In the second block, @placeholder is the content shown before the trigger and @loading (after 200ms) appears only if loading exceeds that wait: without the placeholder, the on interaction trigger would have nothing on which to observe clicks. The block is an outline to adapt, not run.

Trigger Options (angular.dev documentation, consulted on 2026-11-13): without a trigger the block fires on on idle, when the browser is idle; on viewport uses the IntersectionObserver on the placeholder or on a specified element; on interaction fires on click or keyboard; on hover is a separate trigger (mouseover and focusin); on timer(500ms) waits for an interval; there are also on immediate and when <condition>. Prefetch is declared separately, for example @defer (on interaction; prefetch on idle). Viewport and interaction require a @placeholder or a reference element to observe.

Real Case (federicocalo.dev): The article page loads the hero (title + date + author) in sync, but relatedArticles (15 cards) and comments are deferred. Result: TTFB 1.8s → 1.5s (-17%), but more importantly, LCP drops 3.1s → 2.4s (-23%) because the critical-path bundle is 300KB instead of 800KB.


// article-page.component.ts
import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-article-page',
  standalone: true,
  imports: [CommonModule],
  template: `
    <article-hero [article]="article$()" />

    <!-- Critical path: renders immediately -->
    <article-content [article]="article$()" />

    <!-- Below fold: defer sync hydration -->
    @defer (on viewport; prefetch on idle) {
      <related-articles [articles]="related$()" />
    } @placeholder {
      <div class="skeleton-grid">
        <div class="skeleton-card" *ngFor="let _ of [1,2,3]" />
      </div>
    }

    <!-- Interaction-driven: do not load if the user scrolls away -->
    @defer (on interaction) {
      <comment-section [articleId]="articleId$()" />
    } @placeholder {
      <button>Show comments</button>
    } @loading (after 500ms) {
      <p class="text-secondary">Loading comments...</p>
    }
  `
})
export class ArticlePageComponent implements OnInit {
  article$ = signal(null);
  related$ = signal([]);
  articleId$ = signal('');

  ngOnInit() {
    // Mock
    this.article$.set({ title: 'Angular Performance', body: '...' });
    this.related$.set([...Array(6)]);
  }
}
  

In the block, article$, related$ and articleId$ are signals, which are read by calling them as functions (article$()): the original version passed them to the async pipe, which accepts Observables and Promises and not signals. The two @defer blocks are below the fold and the second has a clickable @placeholder. Like all the examples here, it is an outline to adapt and has not been run.

SSR Pitfall: with server-side rendering, a @defer block without a hydrate trigger produces only the @placeholder in the HTML: the deferred content is not in the page a crawler receives, and is loaded by the client at the trigger. With a hydrate trigger (hydrate on viewport, hydrate on idle, hydrate on interaction, hydrate when, hydrate never) the server instead renders the main template, and the client hydrates it later: this is incremental hydration, enabled by default by provideClientHydration() (angular.dev, Incremental Hydration, consulted on 2026-11-13). A block above the fold with hydrate avoids the placeholder-content swap and the related layout shift. The line of the original version about a "skip SSR" option for @defer blocks from "Angular 21.1+" was removed because I did not find that option in the documentation.

Step 2: Selective Route Prerendering (-40% build time, -2.1s TTFB for static)

Prerendering means generating static HTML at build time for specific routes. In Angular CLI, it is configured in angular.json and routes.[server].ts. In the case of federicocalo.dev, 702 IT articles + EN versions = 1400 prerendered HTML files. Without this, every article request would require server-side SSR rendering (100-200ms).

angular.json config:


{
  "projects": {
    "portfolio": {
      "architect": {
        "build": {
          "configurations": {
            "production": {
              "prerender": {
                "discoverRoutes": true,
                "routesFile": "dist-routes.txt"
              }
            }
          }
        }
      }
    }
  }
}
  

In the block, discoverRoutes asks the builder to discover the routes from the router configuration and routesFile points to a text file with one path per line, useful for routes with parameters; in the original the key was written routeFiles, which does not exist in the schema of the application builder (angular-cli repository schema, main branch, consulted on 2026-11-13). In current versions the documentation also describes an alternative, the app.routes.server.ts file with RenderMode.Prerender and getPrerenderParams for parametric routes, and specifies that by default Angular prerenders the whole application and generates the server file. Outline to adapt, not run.

Route Discovery: Angular crawls app.routes.ts to find lazy routes. For dynamic (slug-based) articles, create the dist-routes.txt file manually or programmatically:


// scripts/generate-routes.js
const fs = require('fs');
const articles = require('./data/articles.json');

const routes = [
  '/it',
  '/it/blog',
  '/it/about',
  '/it/servizi',
  ...articles.map(a => `/it/blog/${a.slug}`),
  ...articles.map(a => `/en/blog/${a.slug}`)
];

fs.writeFileSync('dist-routes.txt', routes.join('\n'));
  

The script builds the list of routes to prerender: four fixed pages plus one route for each article, in Italian and in English, and writes everything, one per line, to the file that routesFile reads. It must be run before the build and its result depends on the articles.json file: if that is not up to date, new articles are not prerendered. Outline to adapt, not run.

Build Time Trade-off: 1400 prerendered routes = 5-10 min build time (4GB heap). On CI/CD, this is acceptable 1x/day. For dev, disable prerender (ng build --no-prerender) and use the local SSR server (npm run serve:ssr).

Cache & Expiry: Prerendered HTML is static but the content (articles, comments, stats) might be stale. Solution: suspend prerender for articles with > 100 views/day and serve them via dynamic SSR (Angular routing detects the route, matches against a whitelist, falls back to SSR).

Step 3: Multi-Layer Caching Strategy (L0-L4) (-1.2s TTFB)

Caching is not a single level but a pyramid: browser, CDN, SSR server, backend, database. Each level has a TTL (Time To Live) and an invalidation strategy.

L0 Browser Cache: HTTP Cache-Control headers. Valid for 1 year for hashed assets (main.abc123.js), 60s for prerendered HTML, 5min for API responses.


// server.ts (Angular SSR) - Express middleware
import express from 'express';

const app = express();

// 1 year cache for hashed assets
app.use('/:file([a-z0-9]+\\.[a-z0-9]+\\.js)', (req, res, next) => {
  res.set('Cache-Control', 'public, max-age=31536000, immutable');
  next();
});

// 60s cache for prerendered HTML
app.get('/:lang(it|en)/blog/:slug', (req, res, next) => {
  res.set('Cache-Control', 'public, max-age=60, s-maxage=300');
  next();
});

// 5min API cache
app.get('/api/v1/articles', (req, res, next) => {
  res.set('Cache-Control', 'public, max-age=300');
  next();
});
  

L1 CDN Cache (Cloudflare): Custom cache rules by path pattern. Editor → Cache Rules → Hostname match + Path match + Set cache TTL.


Rule 1: Static assets (hashed)
  Match: example.com/assets/* AND file matches /\.[a-z0-9]{8}\./
  Cache: 1 year

Rule 2: Prerendered pages
  Match: example.com/it/blog/* OR example.com/en/blog/*
  Cache: 5 minutes

Rule 3: API endpoints
  Match: example.com/api/v1/*
  Cache: 1 minute (only GET, not POST/PUT/DELETE)
  

The three rules are an example of a per-path policy, with example.com in place of the real domain: hashed assets for one year (the name changes with every build, so there is no risk of serving an old version), prerendered pages for five minutes, API for one minute and only on GET. The reason for the different TTLs is the cost of a mistake: a hashed asset cannot become obsolete, a page can. It is not the real configuration of any site: it is an outline to adapt, and the Cloudflare cache rules interface must be read in its documentation.

L2 SSR Server Cache: Express middleware wrapper caching rendered HTML (beyond prerender).


// cache.middleware.ts
import { Request, Response, NextFunction } from 'express';

const ssrCache = new Map<string, { html: string; time: number }>();
const CACHE_TTL = 60_000; // 1 minute

export function ssrCacheMiddleware(req: Request, res: Response, next: NextFunction) {
  const cacheKey = `${req.hostname}${req.path}`;
  const cached = ssrCache.get(cacheKey);

  if (cached && Date.now() - cached.time < CACHE_TTL) {
    res.set('X-Cache', 'HIT');
    return res.send(cached.html);
  }

  // Intercept res.send() to cache the response
  const originalSend = res.send.bind(res);
  res.send = function(html) {
    if (res.statusCode === 200 && typeof html === 'string') {
      ssrCache.set(cacheKey, { html, time: Date.now() });
      res.set('X-Cache', 'MISS');
    }
    return originalSend(html);
  };

  next();
}

// server.ts
app.use(ssrCacheMiddleware);
  

The middleware keeps the already rendered HTML in an in-memory Map, keyed by host plus path and lasting one minute (CACHE_TTL); if it finds a valid entry it responds immediately with the X-Cache: HIT header, otherwise it intercepts res.send to save the response with status 200 and lets it through. It works for a single process: a Map is not shared between instances and grows without limit, so in production it needs a cap on size or an external cache. Outline to adapt, not run.

L3 Backend Cache (@Cacheable Spring Boot): Repository query cache via Redis.


@Service
public class ArticleService {
  @Cacheable(value = "articles", key = "#slug", cacheManager = "redisCacheManager")
  public ArticleResponse getBySlug(String slug) {
    // Query the DB only if not cached
    return repository.findBySlug(slug);
  }

  @CacheEvict(value = "articles", key = "#slug")
  public void invalidate(String slug) {
    // Evict the cache when a new article is published
  }
}
  

L4 Database Cache: Redis Stack for complex queries (RediSearch + aggregations).

Invalidation Strategy: Cache buster query param (v=timestamp) or event-driven invalidation (Spring Cloud Stream Pub/Sub broadcast to CDN purge). Recommendation: set realistic TTLs (5-60min) rather than immediate invalidation (overhead).

Step 4: Image Optimization with NgOptimizedImage + AVIF/WebP (-0.8s FCP)

The NgOptimizedImage directive, according to angular.dev (consulted on 2026-11-13), sets fetchpriority on the LCP image, loads the others lazily by default, generates the srcset and the preconnect, and with SSR also generates a preload; it requires width and height. For on-the-fly transformation it is paired with an image service: the directive includes ready-made loaders, among them provideCloudflareLoader.

NgOptimizedImage Syntax:


<!-- Before (slow) -->
<img src="/assets/article.jpg" alt="Article" />

<!-- After (optimized) -->
<img
  ngSrc="/assets/article.jpg"
  alt="Article"
  width="1200"
  height="630"
  priority="false"
  loading="lazy"
  [ngSrcset]="'
    /assets/article-small.webp 640w,
    /assets/article-medium.webp 1024w,
    /assets/article-large.webp 1280w
  '"
  sizes="(max-width: 640px) 100vw, (max-width: 1024px) 80vw, 1200px"
/>
  

The comparison shows the move from a plain src to ngSrc with width and height (intrinsic, with the same aspect ratio as the file), ngSrcset with three widths and sizes, which tells the browser how much space the image will occupy so that it picks the right variant. The loading="lazy" and priority="false" attributes are the ones already implied: the directive loads lazily by default, and priority is needed only for the LCP image. Outline to adapt, not run.

Priority Images: priority on the LCP image sets fetchpriority=high and loading=eager and, with SSR, generates a preload; the others stay lazy. Native browser loading="lazy" loads only on scroll.

Format Selection Strategy: AVIF, then WebP, then JPG as a fallback. With the Cloudflare transformation service you pass format=auto among the URL options: the format depends on the browser (Cloudflare documentation, consulted on 2026-11-13).


// image.component.ts
import { Component, Input } from '@angular/core';
import { NgOptimizedImage } from '@angular/common';

@Component({
  selector: 'app-image-optimized',
  standalone: true,
  imports: [NgOptimizedImage],
  template: `
    <img
      [ngSrc]="imageUrl | cloudflareOptimize: width:height"
      [alt]="alt"
      [width]="width"
      [height]="height"
      loading="lazy"
      priority="false"
      sizes="(max-width: 640px) 100vw, 80vw"
    />
  `
})
export class ImageOptimizedComponent {
  @Input() imageUrl!: string;
  @Input() alt!: string;
  @Input() width = 1200;
  @Input() height = 630;
}

// cloudflare-optimize.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'cloudflareOptimize',
  standalone: true
})
export class CloudflareOptimizePipe implements PipeTransform {
  transform(url: string, width: number, height: number): string {
    // Cloudflare: the options go in the path, /cdn-cgi/image/<options>/<source>
    return `/cdn-cgi/image/width=${width},height=${height},fit=scale-down,quality=85,format=auto/${url}`;
  }
}
  

The component applies the ngSrc directive to a URL produced by the cloudflareOptimize pipe, and always declares width and height (the directive requires them, and they serve to reserve space). The pipe fixes a mistake of the original: Cloudflare's transformation options go in the /cdn-cgi/image/ path and not in a query string, fit accepts scale-down and not scale, and quality accepts an integer from 1 to 100 or a perceptual level such as high, not auto. The transformation works only if it is enabled on the Cloudflare zone; alternatively you register provideCloudflareLoader. Outline to adapt, not run.

Responsive Breakpoints: Define srcset for 3-4 breakpoints (mobile 640w, tablet 1024w, desktop 1280w). Tool: responsiveImages.ts generator or sharp (Node.js) batch.

Lazy Loading Pitfall: Below-the-fold images risk layout shift if width/height are missing. Always declare width/height (aspect ratio). Cloudflare Images recommended to reduce server storage (on-the-fly transform).

Step 5: Aggressive Bundle Splitting (-77% initial bundle, -600ms LCP)

In the federicocalo.dev case, the initial bundle was 1.2 MB (main.js 800KB + polyfill 200KB + vendor 200KB). After aggressive splitting: 280 KB initial + 18 lazy chunks = 1.1 MB total. Download time saved: 600ms on 3G.

Strategies:

Route-Level Lazy Loading (Angular default):


// app.routes.ts
export const routes: Routes = [
  {
    path: 'it',
    component: LayoutComponent,
    children: [
      { path: '', component: HomePageComponent }, // Eager
      {
        path: 'blog/:slug',
        loadComponent: () => import('./pages/article-page.component').then(m => m.ArticlePageComponent)
      }, // Lazy
      {
        path: 'dev-tools',
        loadComponent: () => import('./pages/dev-tools-page.component').then(m => m.DevToolsPageComponent)
      }
    ]
  }
];
  

Component-Level Lazy with Dynamic Import:


// analytics.service.ts
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({ providedIn: 'root' })
export class AnalyticsService {
  constructor(@Inject(PLATFORM_ID) private platformId: string) {}

  initGoogleAnalytics() {
    if (!isPlatformBrowser(this.platformId)) return; // Skip SSR

    // Dynamic import: loads gtag.js on the client only
    import('gtag').then(m => {
      m.gtag('config', 'G-S3TS9T66B6');
    });
  }
}
  

The initGoogleAnalytics method returns immediately if the code runs on the server (isPlatformBrowser), so prerendering and SSR never run tracking scripts; the package is then loaded with a dynamic import(), so it ends up in a separate chunk and does not weigh on the initial bundle. The module name gtag and the m.gtag(...) call are those of the original and I did not verify them on the package registry. Outline to adapt, not run.

Production build options (formerly "vendor splitting"):


{
  "projects": {
    "portfolio": {
      "architect": {
        "build": {
          "configurations": {
            "production": {
              "optimization": {
                "scripts": true,
                "styles": true,
                "fonts": true
              },
              "outputHashing": "all",
              "namedChunks": false,
              "aot": true,
              "sourceMap": false
            }
          }
        }
      }
    }
  }
}
  

The configuration lists the production options for optimization, file-name hashing and AOT, which are in the schema of the application builder. The vendorChunk option, which the original set to true, belongs to the old webpack-based builder and is not in the schema of the application builder (schema consulted on 2026-11-13): I removed it. Outline to adapt, not run.

Tree Shaking & Dead Code Elimination:


// package.json
{
  "sideEffects": false,
  "dependencies": {
    "@angular/common": "^21.0.0"
  }
}
  

The block sets sideEffects to false in package.json. That field is read by bundlers for the packages that declare it: its effectiveness in the application's own package.json I did not verify against the documentation, so treat it as an outline to evaluate and measure.

Bundle Analysis Tools: source-map-explorer (local) or webpack-bundle-analyzer (post-build).


# Analyze bundle size
npm install -D source-map-explorer
npm run build -- --source-map
npx source-map-explorer 'dist/portfolio/browser/**/*.js'

# Output: an interactive tree for every chunk, revealing the large imports
  

The block installs source-map-explorer, rebuilds with source maps and opens the chunk tree to show which dependencies weigh the most. It serves to decide what to extract into a lazy chunk, and the result must be compared with the numbers in the table that follows before moving any code. Outline to adapt, not run.

Realistic Target Size: For an Angular SSR app with 1000+ routes, initial JS <150 KB gzip is, according to the author, an empirical rule (no primary source). federicocalo.dev: 280 KB initial (high but acceptable for 702 inline JSON articles). Refactor: extract the JSON articles into separate endpoints (lazy load on demand).

Benchmark Results: Before vs After (federicocalo.dev Real Data)

Metric Pre-Optimization Post-Optimization Improvement
TTFB 1.8s 0.6s -67%
FCP 2.4s 1.1s -54%
LCP 3.1s 1.7s -45%
CLS 0.18 0.04 -78%
INP 320ms 140ms -56%
Initial JS Bundle 1.2 MB 280 KB -77%
Lighthouse Score (Performance) 62 96 +55%

Methodology Note: Local Lighthouse CI measurement (8 runs avg), Fast 3G throttling (simulates real conditions). ±5% variance due to system load and cache state. In production (Hetzner VPS, CloudFlare CDN), the real TTFB is 0.4-0.8s.

How to read the INP row: the Lighthouse Performance score does not contain INP (see above), and in a lab run in navigation mode INP is not produced. The INP value in the table is therefore a separate datum, not a component of the 96: the original article does not say which field tool it comes from.

Anti-Patterns: 5 Traps to Avoid

1. Importing Heavy Libraries in the Root Component

❌ WRONG: Chart library (Chart.js 200KB) imported in app.component → loaded for every visitor.

✅ CORRECT: Lazy load ChartComponent only for the /analytics page → separate chunk.

2. Service Worker that Caches API Endpoints

❌ WRONG: Service Worker caches .get('/api/articles') for 7 days → stale data during a bug fix.

✅ CORRECT: Cache only static (hashed) assets, API excluded or TTL <5min.

3. Preloading All Routes

❌ WRONG: PreloadAllModules strategy → 3 MB bundle, 2s idle.

✅ CORRECT: Custom PreloadingStrategy that preloads only routes with a high probability of being visited (nav link hover detection).

4. Images Without Declared Dimensions

❌ WRONG: <img src="article.jpg" /> without width/height → CLS 0.2 at load.

✅ CORRECT: <img ngSrc="article.jpg" width="1200" height="630" /> → the browser reserves space.

5. @defer on Above-the-Fold Components

❌ WRONG: @defer on the hero title → artificial LCP delay.

✅ CORRECT: @defer only below the fold (comments, related, sidebar).

FAQ: 8 Common Questions

Q1. SSR vs SSG (Prerender) for a Blog with 1000+ Articles?

A: Prerender (SSG) is ideal for static content (articles, docs). Dynamic SSR for user-specific pages (account, dashboard). Hybrid: prerender 1000 articles as static HTML, serve via Nginx static caching (0ms TTFB); dynamic SSR for search, comments, user profile. Prerender build time for 1000 routes: 10-15 min (once/day). Avoid prerender if the content changes >1x/hour.

Q2. Partial Hydration (Island Architecture) in Angular 21?

A: Yes, in the form of incremental hydration: @defer blocks with a hydrate trigger (hydrate on viewport, idle, interaction, hover, when, never) are rendered by the server and stay unhydrated until the trigger fires; user events before hydration are queued and replayed afterwards (event replay). According to the angular.dev documentation consulted on 2026-11-13 it is enabled by default with provideClientHydration(), and is disabled with withNoIncrementalHydration(). The original line about the "roadmap: partial hydration likely in 22.0 (2027)" was removed: it was outdated and without a source.

Q3. Service Worker on an SSR App: Best Practice?

A: Service Worker for offline + asset cache, not for APIs. The Angular service worker (@angular/service-worker) is configured with ngsw-config.json, where assetGroups describes the application's resources and dataGroups the data: cache of hashed assets, precache of the app shell, network fallback, and /api/* and user data excluded. It does not use Workbox: the original line about the workbox:* metric was wrong and was removed.

Q4. Is an Edge Runtime (Cloudflare Workers) Compatible with Angular SSR?

A: It depends on the runtime. The angular.dev documentation (consulted on 2026-11-13) describes two engines: AngularNodeAppEngine for Node.js and AngularAppEngine, based on the Web API Request and Response objects, meant to integrate SSR "in various server environments". Whether a specific runtime, for example Cloudflare Workers, is usable I have not verified: check the provider's instructions. The original line, which gave the incompatibility as a fact, was outdated.

Q5. Measuring INP in Real User Monitoring (RUM)?

A: The web-vitals npm package sends INP to an analytics endpoint. Config:


import { onINP } from 'web-vitals';

onINP(({ value, attribution, delta }) => {
  fetch('/api/analytics', {
    method: 'POST',
    body: JSON.stringify({
      metric: 'INP',
      value: Math.round(value),
      attribution,
      delta
    })
  });
});
  

The backend aggregates via Prometheus (histogram). Target: INP <200ms at the 75th percentile (Google's Good threshold).

Q6. Bundle Splitting Too Aggressive: Tipping Point?

A: The author's empirical rules, without a primary source: chunk <10 KB = HTTP request overhead (prefetch, parallel loading cost). Sweet spot: 30-100 KB per lazy chunk. Beyond 10 lazy chunks = request fatigue on the mobile client side. Monitor: Source Map Explorer, report chunk interdependencies (duplication detection).

Q7. Route Lazy Loading vs Prefetch - Hybrid Strategy?

A: Lazy load by default, prefetch (predictive) on successful interaction (link hover 200ms). Custom strategy:


@Injectable({ providedIn: 'root' })
export class SmartPreloadingStrategy implements PreloadingStrategy {
  constructor(private router: Router) {}

  preload(route: Route, load: () => Observable<any>): Observable<any> {
    // Preload only if route.data.preload === true AND network === 'fast'
    const shouldPreload = route.data?.['preload'] === true;
    const fastNetwork = navigator?.connection?.effectiveType === '4g';

    return shouldPreload && fastNetwork ? load() : of(null);
  }
}
  

Q8. Web Vitals as SLIs: Defining Realistic SLOs?

A: SLO (Service Level Objective) = business expectation. Example federicocalo.dev: "99% of traffic sees LCP <2.5s, P95 TTFB <800ms". Measure: client-side PercentileObserver (web-vitals) + backend percentile aggregation. Alert: if P95 TTFB exceeds 1s for 5min → incident.

Conclusions: 5 Step Recap

Getting TTFB <1s and Core Web Vitals 95+ requires a holistic approach: it is not a single "trick" but a disciplined combination of 5 layers:

  1. @defer and incremental hydration: They reduce the JavaScript needed for the first render.
  2. Selective prerendering: Eliminates server-rendering latency for static content.
  3. Multi-layer caching: Browser → CDN → server → database.
  4. Image optimization: Responsive srcset + lazy load + format auto.
  5. Aggressive bundle splitting: Route lazy, vendor split, tree shaking.

The five layers work on different points: hydration and the bundle on JavaScript, prerendering and the caches on response time, images on transferred bytes. They are not interchangeable, and the order of priority depends on where your page loses time: measure it first, as described in the section on metrics. A Lighthouse score of 95+ remains a lab result; the Core Web Vitals are passed with LCP ≤2.5s, INP ≤200ms and CLS ≤0.1 at the 75th percentile of the field.

In the real federicocalo.dev case, applying the 5 steps was a 60h effort (development + testing), but the ROI (TTFB -67%, Lighthouse 62→96, +45% engagement) justifies the investment. For a small team (1-2 developers), prioritize in this order: Step 5 (bundle splitting, 8h), Step 3 (caching, 6h), Step 4 (image, 4h), Step 1 (@defer, 8h), Step 2 (prerender, 2h).

Next steps: Implement RUM monitoring (web-vitals) to keep tracking performance in production, monitor regressions with Lighthouse CI on CI/CD, involve the frontend team in a performance-first culture (SLOs, budget alerts, monthly training).

Sources

The measurements, redone command by command (2026-11-08)

The numbers in this article - "Lighthouse 62→96", "TTFB -67%" - are from February 2026 and do not have next to them the command that redoes them. In November 2026 I re-measured the same site with Playwright, publishing scripts and outputs: the three-part series is summarised here (for now it exists only in Italian, so the items below are not linked), and where its numbers contradict this page, its numbers prevail, because they are reproducible.

  • 01 - Measuring LCP, CLS and TTFB with Playwright: median TTFB 187 ms on the home page, LCP 1104 ms, and 2864 ms on an article page - with three runs giving three different results.
  • 02 - The page that scrolls sideways at 320 px: two culprits stacked, 1fr and a monospace title.
  • 03 - How many JavaScript files a page downloads: 69 files for 801 KB on an article, 51 for 638 KB on the home page.

The reason this pointer sits here and not in a footnote is that the three parts partly contradict the promise of the title: this site's TTFB is low, around 110-190 ms median, but the LCP of an article page stays above two seconds. The lever was not where this article looked for it.

Further reading: 04 - Angular SSR PageSpeed: From 59 to 88 with Four Fixes.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects