Implement Angular Universal API pre-rendering with a cache warming script. Before deploying, crawl the sitemap, trigger SSR render for each route, save HTML to Redis cache, and only switch the load balancer to the new deployment once 90% of high-traffic pages are cached.
Assistant
Proposing Angular Universal cache warming design
I'll provide a high-level approach with sample Node.js code showing how to crawl a sitemap, fetch SSR-rendered pages, store them in Redis, track caching of high-traffic pages, and only switch the load balancer after reaching a 90% cache threshold. This balances clear guidance with concise implementation detail.
Below is a suggested approach and sample code to implement pre-rendering with Angular Universal, warm your Redis cache by crawling the sitemap, and only switch traffic when you’ve reached a target cache coverage (e.g., 90% of high-traffic pages).
Overview
Add Angular Universal to your Angular app (if not already done).
Implement server-side rendering using the Express engine and integrate Redis as a caching layer.
Cache warming script:
Parse your sitemap to collect routes.
For each route, trigger SSR render from the newly deployed environment.
Store the rendered HTML in Redis.
Track progress; once ≥90% of your “high-traffic” routes are cached, switch your load balancer to the new deployment.
1) Setup Angular Universal (Express) with Redis Caching
If you haven’t already:
bash
ng add @nguniversal/express-engine
A minimal server.ts example with Redis caching (using ioredis):
typescript
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { AppServerModule } from './src/main.server';
import { existsSync } from 'fs';
import { join } from 'path';
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
const app = express();
const distFolder = join(process.cwd(), 'dist/your-app/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
// Express Engine
app.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
app.set('view engine', 'html');
app.set('views', distFolder);
// Middleware: check Redis, else SSR, then cache
app.get('*', async (req, res) => {
try {
const cacheKey = `html:${req.url}`;
const cached = await redis.get(cacheKey);
if (cached) {
res.setHeader('Content-Type', 'text/html');
return res.status(200).send(cached);
}
// Render via Angular Universal
res.render(indexHtml, { req }, async (err: any, html: string) => {
if (err) {
console.error(err);
return res.status(500).send(err.message || err);
}
// Cache SSR result
await redis.set(cacheKey, html, 'EX', 3600); // 1 hour TTL, adjust as needed
res.status(200).send(html);
});
} catch (e) {
console.error(e);
res.status(500).send('Server error');
}
});
// Start up
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Node server listening on http://localhost:${port}`));
2) Cache-Warming Script
You can run this script in your CI/CD pipeline right after deploying to a staging or pre-production environment but before flipping traffic.
Key Steps:
Fetch and parse the sitemap XML.
For each route:
Request the SSR-rendered page from your new deployment endpoint (e.g., https://new-env.example.com/route).
Store the HTML in Redis under a known key (like html:/route).
Keep track of which routes are cached successfully.
Mark “high-traffic” routes (either in a separate list or tagged in the sitemap) and calculate percentage cached.
Example warm-cache.js (Node + TypeScript-ish):
typescript
import axios from 'axios';
import { parseStringPromise } from 'xml2js';
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
const SITEMAP_URL = process.env.SITEMAP_URL || 'https://new-env.example.com/sitemap.xml';
const TARGET_ENV_URL = process.env.TARGET_ENV_URL || 'https://new-env.example.com';
const HIGH_TRAFFIC_ROUTES = [
'/home',
'/products',
'/pricing',
'/blog',
// ... populate from analytics or a config file
];
async function fetchSitemapUrls(): Promise<string[]> {
const xml = await axios.get(SITEMAP_URL).then(r => r.data);
const parsed = await parseStringPromise(xml);
const urls = parsed.urlset.url.map((u: any) => u.loc[0]);
return urls;
}
// Convert full URL to route path
function toRoute(url: string): string {
try {
const u = new URL(url);
return u.pathname + (u.search || '');
} catch {
return url; // fallback
}
}
async function warmRoute(route: string) {
// SSR endpoint on the new environment
const fullUrl = `${TARGET_ENV_URL}${route}`;
const res = await axios.get(fullUrl, { timeout: 10000 });
const html = res.data;
const cacheKey = `html:${route}`;
await redis.set(cacheKey, html, 'EX', 3600); // TTL can be adjusted
return true;
}
async function warmCache() {
const routes = (await fetchSitemapUrls()).map(toRoute);
console.log(`Found ${routes.length} routes in sitemap.`);
let warmed = 0;
let warmedHighTraffic = 0;
for (const route of routes) {
try {
await warmRoute(route);
warmed++;
if (HIGH_TRAFFIC_ROUTES.includes(route)) {
warmedHighTraffic++;
}
console.log(`Warmed: ${route}`);
} catch (err) {
console.warn(`Failed to warm ${route}`, err.message || err);
}
}
// Calculate % of high-traffic routes cached
const totalHighTraffic = HIGH_TRAFFIC_ROUTES.length;
const pctHighTrafficCached = totalHighTraffic
? (warmedHighTraffic / totalHighTraffic) * 100
: 100; // if none defined, treat as fully warmed
console.log(`Total routes warmed: ${warmed}/${routes.length}`);
console.log(`High-traffic warmed: ${warmedHighTraffic}/${totalHighTraffic} (${pctHighTrafficCached.toFixed(2)}%)`);
return pctHighTrafficCached;
}
// Main
warmCache()
.then(pct => {
console.log('Cache warming complete.');
if (pct >= 90) {
console.log('>= 90% of high-traffic routes warmed. Safe to switch load balancer.');
// Trigger LB switch logic here:
// e.g. call your cloud API / load balancer config to route traffic to new deployment
// switchLoadBalancerToNewDeployment();
} else {
console.warn('Below 90% threshold. Not switching load balancer yet.');
}
process.exit(0);
})
.catch(err => {
console.error('Cache warming failed:', err);
process.exit(1);
});
Notes:
You can run this script from a CI/CD pipeline step after deploying to your new environment but before changing the load balancer.
The script checks the percentage of “high-traffic” routes that were cached. If the threshold is not met, it can fail the pipeline or keep the old deployment active.
You might want to add retry logic and concurrency to speed up warming (e.g., Promise.all with a concurrency limiter such as p-limit).
3) Load Balancer Switching Strategy
Once warm-cache.js confirms the target coverage (≥90%), call your infrastructure’s API (AWS ALB, GCP, Nginx config, etc.) to switch traffic to the new deployment.
Optionally, keep monitoring (post-switch) that your Redis remains healthy and that the warmed cache hits are working as expected.
4) Operational Tips
Make the “high-traffic” routes list dynamic from real analytics data.
Use short but sufficient TTLs on Redis for SSR HTML; the cache should refresh on subsequent requests if stale.
Add alerts/metrics to track Redis hit ratio and any SSR render errors.
This approach ensures your new Angular Universal deployment is “primed” before receiving user traffic, minimizing cold SSR renders and improving perceived performance.