WEB PERFORMANCE
ENGINEERING
MIT-Level Condensed Guide
Browser Internals · Network Protocols · Frontend Optimization
Backend Scalability · Caching Architecture · DevOps Performance
19 Chapters · Comprehensive Coverage · Interview-Ready
Edition: May 2026 · Academic Reference
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter Table of Contents
1. Introduction to Web Performance Core concepts, metrics, UX/SEO impact
2. Performance Fundamentals Latency, RTT, DNS, TCP/TLS, CRP
3. Browser Rendering Pipeline DOM, CSSOM, reflow, paint, compositing
4. Core Web Vitals LCP, CLS, INP, FCP, TTFB — thresholds & fixes
5. Frontend Optimization Bundling, lazy loading, images, JS execution
6. Backend Optimization Caching, DB, compression, load balancing
7. Network Performance CDN, HTTP/1.1/2/3, QUIC, multiplexing
8. Caching Masterclass Browser, CDN, service workers, invalidation
9. Nginx for Performance Config tuning, proxy cache, rate limiting
1 JavaScript Performance Event loop, memory, virtual DOM, React
0.
1 Database Performance Indexing, N+1, Redis, CAP theorem
1.
1 Monitoring & Measurement Lighthouse, RUM, APM, perf budgets
2.
1 Security vs Performance TLS, WAF, compression vulnerabilities
3.
1 Scaling Architecture Monolith vs microservices, stateless, queues
4.
1 Common Bottlenecks Render blocking, large bundles, cold starts
5.
1 Advanced Concepts Edge SSR, streaming, speculation rules
6.
1 Comparative Tables Quick-reference decision matrices
7.
1 Deployment Checklists Frontend, backend, Nginx, monitoring
8.
1 Rapid Revision 50 key points, interview Q&A;, formula sheet
9.
Anthropic Claude | Academic Reference | Not for redistribution Page 2
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 1 Introduction to Web Performance
1.1 Definition & Scope
Web performance quantifies how efficiently a system delivers and renders content to users. It encompasses three
orthogonal dimensions:
• Frontend: rendering speed, JavaScript execution, asset delivery
• Backend: server response time, database latency, compute efficiency
• Network: protocol overhead, geographic distance, packet loss, CDN
Perceived vs. Actual Speed: Users perceive performance through visual feedback milestones (FCP, LCP), not absolute
completion time. A page that renders meaningful content in 1s feels faster than one that renders fully in 0.8s after a blank
screen.
1.2 Business Impact
Company Finding Metric
Amazon 100ms delay → 1% revenue loss Latency–Revenue
Google 500ms slowdown → 20% traffic drop Speed–Traffic
Pinterest 40% load time reduction → 15% signup increase LCP–Conversion
Walmart 1s improvement → 2% conversion increase Speed–Revenue
BBC 1s delay → 10% user loss Latency–Retention
1.3 Core Metric Overview
• TTFB — Time to First Byte: server responsiveness
• FCP — First Contentful Paint: first visual feedback
• LCP — Largest Contentful Paint: main content loaded
• CLS — Cumulative Layout Shift: visual stability
• INP — Interaction to Next Paint: responsiveness to input
• TTI — Time to Interactive: fully interactive state
• TBT — Total Blocking Time: main thread lock duration
■ Professor Note: Performance is a spectrum: optimize for P50 (median user), but monitor P95/P99. Median metrics
hide tail latency which disproportionately affects retention.
■ Exam Focus: Performance = f(perceived_speed), not f(actual_speed). Distinguish skeleton screens, SSR, and
streaming as perceptual strategies vs. raw optimization.
Anthropic Claude | Academic Reference | Not for redistribution Page 3
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 2 Performance Fundamentals
2.1 Core Formulas
Latency = Propagation Delay + Processing Delay + Queuing Delay + Transmission Delay
Throughput = Total Requests / Time Interval [req/s]
Bandwidth = Throughput × Avg Payload Size [bits/s]
RTT = 2 × Propagation Delay (one-way * 2)
Bandwidth-Delay Product (BDP) = Bandwidth × RTT [bits in-flight]
2.2 DNS Resolution Chain
DNS adds 20–120ms on first lookup. Chain: Browser Cache → OS Cache → Resolving Resolver → Root Nameserver →
TLD Nameserver → Authoritative Nameserver.
Step Location Typical Cost
Browser DNS cache Local RAM 0 ms
OS DNS cache Local 0–1 ms
ISP/Resolver cache Network 5–50 ms
Root nameserver Global anycasted 10–30 ms
TLD (.com) server Regional 10–30 ms
Authoritative NS Origin 10–60 ms
2.3 TCP Handshake
TCP requires 1 RTT before data transfer (SYN → SYN-ACK → ACK). TLS 1.3 adds 1 RTT (vs 1.3's 0-RTT for resumed
sessions). Total cold-start overhead:
Cold Start Delay = DNS + TCP (1 RTT) + TLS (1 RTT) + HTTP Request/Response
Minimum First Byte = DNS_lookup + 3×RTT (HTTP/1.1 + TLS 1.2)
With TLS 1.3 + HTTP/2: Minimum = DNS + 2×RTT
2.4 Critical Rendering Path (CRP)
The CRP defines the sequence of steps a browser must complete before rendering a pixel. Minimizing CRP length is the
primary frontend performance objective.
HTML Build CSS → Render
Parse → DOM → CSSOM → Tree → Layout → Paint
■ Professor Note: Any render-blocking resource (synchronous <script>, non-async CSS) pauses the CRP. Quantify
CRP length as: max(DOM depth, CSS depth) × avg_node_processing_time.
■ Exam Focus: TCP slow-start: initial congestion window = 10 segments (~14KB). Large assets require multiple RTTs
even with perfect latency. BDP determines how much data can be in-flight.
Anthropic Claude | Academic Reference | Not for redistribution Page 4
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 3 Browser Rendering Pipeline
3.1 Pipeline Stages
Stage Input Output Bottleneck
HTML Parsing Bytes/tokens DOM tree Network, large DOM
Style Calculation DOM + CSS Computed styles CSS specificity, selector complexity
Layout (Reflow) Render tree Box model geometry Nested flexbox, table, % widths
Paint Layout tree Pixel records (display lists) Complex shadows, gradients
Composite Paint layers Final frame to GPU Too many layers, large layers
3.2 Render-Blocking Resources
• Synchronous <script>: Parser stops, fetches, executes JS — blocks DOM construction
• CSS in <head>: Blocks rendering (not parsing) — CSSOM must complete before paint
• @import in CSS: Serial CSS loads — each import adds an RTT
• Web fonts: FOIT (Flash of Invisible Text) if font not loaded at paint time
3.3 GPU Acceleration & Compositing
Elements with transform, opacity, will-change, or position:fixed are promoted to GPU compositor layers. GPU
compositing bypasses Layout and Paint stages for animations.
CSS Property Triggers Reflow? Triggers Repaint? Composited?
width/height/margin Yes Yes No
color/background No Yes No
transform: translate() No No Yes — GPU
opacity No No Yes — GPU
box-shadow No Yes No
top/left (positioned) Yes Yes No
3.4 Main Thread Architecture
• Main thread handles: JS execution, style, layout, paint — single-threaded
• Compositor thread: handles scroll, CSS animations (GPU) — does NOT block main
• Raster threads: convert paint records to pixels
• Network thread: independent — fetches resources concurrently
• Long JS tasks (>50ms) block user input → increases INP
■ Professor Note: Use Chrome DevTools Performance tab to profile frame timeline. A dropped frame at 60fps =
16.67ms budget per frame. Long tasks exceeding this budget cause jank.
■ Exam Focus: Reflow is expensive because it invalidates the geometry of all dependent elements. A reflow on a
parent can cascade to all children. Minimize DOM depth; batch DOM mutations.
Anthropic Claude | Academic Reference | Not for redistribution Page 5
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 4 Core Web Vitals
4.1 LCP — Largest Contentful Paint
Attribute Details
Definition Time until largest above-fold element (img, video, h1, p block) finishes rendering
Good ≤ 2.5s
Needs Improvement 2.5–4.0s
Poor > 4.0s
Root Causes Slow server (TTFB), render-blocking resources, slow image load, client-side rendering
Fixes Optimize TTFB, preload LCP image, use CDN, eliminate render-blocking CSS/JS, SSR
SEO Impact Google Search ranking signal since 2021
4.2 CLS — Cumulative Layout Shift
Attribute Details
Definition Cumulative score of unexpected layout shifts: CLS = Σ(impact_fraction × distance_fraction)
Good ≤ 0.1
Needs Improvement 0.1–0.25
Poor > 0.25
Root Causes Images without dimensions, late-loading fonts (FOIT/FOUT), dynamic content injection, ads
Fixes Set explicit width/height on img/video, font-display:optional, reserve ad space, avoid DOM
insertion above viewport
SEO Impact Core ranking signal
4.3 INP — Interaction to Next Paint (replaced FID in 2024)
Attribute Details
Definition 98th percentile of all interaction-to-next-paint latencies during page visit
Good ≤ 200ms
Needs Improvement 200–500ms
Poor > 500ms
Root Causes Long JS tasks, synchronous event handlers, heavy re-renders, main thread contention
Fixes Break long tasks with setTimeout/scheduler, use Web Workers, reduce JS bundle, defer
non-critical code
SEO Impact Replaced FID as Core Web Vital — March 2024
4.4 FCP — First Contentful Paint
Attribute Details
Anthropic Claude | Academic Reference | Not for redistribution Page 6
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Definition Time until first text/image pixel renders (not blank screen)
Good ≤ 1.8s
Needs Improvement 1.8–3.0s
Poor > 3.0s
Root Causes Render-blocking JS/CSS, slow TTFB, large HTML, no SSR
Fixes Inline critical CSS, async/defer scripts, HTTP/2 push, SSR, preconnect to origins
4.5 TTFB — Time to First Byte
Attribute Details
Definition Time from navigation start to first response byte received
Good ≤ 800ms
Needs Improvement 800ms–1.8s
Poor > 1.8s
Root Causes Slow DB queries, unoptimized server code, no edge caching, geographic distance
Fixes CDN, edge caching, DB indexing, server-side caching (Redis), reduce server compute
■ Professor Note: TTFB is a backend metric masquerading as a frontend issue. A TTFB > 800ms almost always
indicates server-side problems: slow queries, missing cache, cold starts, or geographic distance.
■ Exam Focus: Core Web Vitals are measured in field data (Chrome UX Report) and lab data (Lighthouse). Field data
weights real users; lab data is reproducible. Google uses 75th percentile field data for ranking.
Anthropic Claude | Academic Reference | Not for redistribution Page 7
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 5 Frontend Performance Optimization
5.1 Asset Optimization
Technique Mechanism Savings
Minification Remove whitespace, shorten vars 10–40% size reduction
Bundling Merge modules → fewer HTTP requests Reduces request count
Tree Shaking Dead code elimination at build time 20–70% JS reduction
Code Splitting Dynamic import() → per-route chunks Reduces initial bundle
Compression (Brotli) Server-side content encoding 20–30% better than gzip
Compression (gzip) Deflate algorithm 60–80% text compression
5.2 Image Optimization
• Format hierarchy: AVIF > WebP > PNG/JPEG (AVIF: ~50% smaller than JPEG)
• Responsive images: srcset + sizes attributes — serve correct resolution per viewport
• Lazy loading: loading='lazy' on off-screen <img> — defer network request
• Dimensions: Always set width/height to prevent CLS
• Preload LCP image: <link rel='preload' as='image'> for above-fold hero images
• CDN + image transformation: Cloudinary/imgix serve optimized formats automatically
5.3 JavaScript Loading Strategies
Attribute Behavior Use Case
(none) Blocks parser, executes immediately Never for external scripts
async Non-blocking download; executes when ready (no order) Analytics, ads
defer Non-blocking download; executes after DOM parsed, in order App scripts
type=module Deferred by default, strict mode ES module entry points
5.4 Resource Hints
Hint Directive Effect
DNS Prefetch <link rel='dns-prefetch' href='//[Link]'> Resolves DNS early
Preconnect <link rel='preconnect' href='[Link] DNS+TCP+TLS early
Preload <link rel='preload' as='font|image|script'> High-priority fetch
Prefetch <link rel='prefetch' href='/[Link]'> Low-priority next-nav
Prerender Speculation Rules API Pre-renders next page
5.5 Rendering Strategies
Strategy TTFB FCP JS Load SEO Best For
CSR (SPA) Fast Slow Heavy Poor Dashboards, apps
Anthropic Claude | Academic Reference | Not for redistribution Page 8
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
SSR Slower Fast Medium Excellent Content sites, e-commerce
SSG Instant Instant Light Excellent Blogs, docs, marketing
ISR Fast Instant Light Excellent Semi-dynamic content
Streaming SSR Fast Progressive Medium Good Large pages, AI content
5.6 Font Optimization
• font-display: swap — show fallback immediately, swap when loaded (prevents FOIT)
• Subset fonts — include only required Unicode ranges (unicode-range descriptor)
• Preload critical font: <link rel='preload' as='font' crossorigin>
• Self-host fonts — eliminates third-party DNS lookup + connection overhead
• Variable fonts — single file replaces multiple weight/style files
■ Professor Note: Hydration cost in SSR frameworks: the browser must download, parse, and execute the full JS
bundle to make an SSR page interactive. Islands architecture (Astro) hydrates only interactive components.
■■ Industry Focus: For e-commerce: prioritize LCP (hero image preload + CDN), eliminate CLS (explicit
dimensions), and defer all non-critical JS. Every 100ms improvement ≈ 1% conversion lift.
Anthropic Claude | Academic Reference | Not for redistribution Page 9
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 6 Backend Performance Optimization
6.1 Server Response Time
Server Response Time = DB Query Time + Business Logic + Serialization + Network Overhead
Target TTFB < 200ms at the server (before CDN). Breakdown priorities:
• Database: typically 60–80% of server response time — optimize first
• Caching: Redis cache hit → sub-millisecond vs. 50–200ms DB query
• Connection pooling: reuse TCP connections to DB — eliminates per-request handshake
• Serialization: [Link] bottleneck for large payloads — use streaming JSON
6.2 Caching Layers
Layer TTL Hit Rate Target Invalidation
Redis/Memcached (L1) Seconds–minutes 95%+ Key deletion, pub/sub
Application cache (in-process) Seconds High LRU eviction
Reverse proxy cache (Nginx) Minutes–hours 90%+ Cache purge API
CDN edge cache Hours–days 85%+ Cache-Control, purge
Browser cache Days–years 80%+ Cache-busting (versioned URLs)
6.3 Compression
Algorithm Ratio CPU Cost Best For
gzip ~70% text reduction Low Universal support, HTML/CSS/JS
Brotli ~80% text reduction Medium Modern browsers, HTTPS only
(20% > gzip)
Zstandard (zstd) ~75% + fast Low APIs, streaming, real-time
decompress
lz4 ~50%, fastest Minimal Internal microservice traffic
6.4 Horizontal vs. Vertical Scaling
Dimension Vertical (Scale Up) Horizontal (Scale Out)
Approach Larger server (more CPU/RAM) More servers (same size)
Cost Exponential beyond threshold Linear
Complexity Simple (no distributed state) Requires stateless design, LB
Availability Single point of failure High availability (N+1)
Limit Hardware ceiling (~96 cores) Theoretically unlimited
Best For Databases (vertical first) Web/API servers (stateless)
6.5 Queue Systems
• Decouple heavy processing from request/response cycle (email, image resize, reports)
Anthropic Claude | Academic Reference | Not for redistribution Page 10
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
• RabbitMQ: AMQP protocol, message acknowledgment, dead letter queues
• Redis Pub/Sub: lightweight, fire-and-forget, no persistence guarantee
• Kafka: distributed log, high-throughput, replay capability, ordered partitions
• SQS (AWS): managed, at-least-once delivery, visibility timeout
■ Professor Note: API pagination is not optional — it's critical. Without LIMIT/OFFSET or cursor-based pagination, a
single endpoint can return millions of rows, causing OOM crashes and multi-second responses.
■ Exam Focus: Microservices overhead: each service boundary adds 1+ network hop (0.5–5ms LAN latency). For
high-frequency internal calls, evaluate gRPC (binary, multiplexed) vs. REST (text, 1:1 connections).
Anthropic Claude | Academic Reference | Not for redistribution Page 11
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 7 Network Performance
7.1 HTTP Protocol Comparison
Feature HTTP/1.1 HTTP/2 HTTP/3
Transport TCP TCP QUIC (UDP)
Multiplexing No (HOL blocking) Yes (streams) Yes (independent streams)
Header Compression None HPACK QPACK
Connection Setup Slow (1 RTT TCP + TLS) 1 RTT (TLS 1.3) 0-RTT resumption
Head-of-Line Blocking Per-connection No (stream level) No (packet level)
Server Push No Yes (deprecated) No (removed)
Packet Loss Impact High High (TCP) Low (per-stream only)
Adoption (2024) ~25% ~60% ~30%+ growing
7.2 CDN Architecture
CDN (Content Delivery Network): geographically distributed PoPs (Points of Presence) cache content close to users,
reducing propagation delay.
Effective Latency with CDN = User→PoP RTT (20–50ms) vs. User→Origin RTT (100–300ms)
• Static assets: CSS, JS, images — cache aggressively (long TTL, cache-busted URLs)
• Dynamic content: Vary header enables per-header caching (Accept-Encoding, Accept-Language)
• Edge functions: Run code at CDN PoP — sub-10ms logic without origin round-trip
• CDN providers: Cloudflare, Fastly, AWS CloudFront, Akamai — differ in PoP count and edge compute
7.3 QUIC Protocol
• Built on UDP — eliminates TCP's OS-level head-of-line blocking
• Connection migration: maintains connection when switching networks (WiFi → LTE) via Connection ID
• 0-RTT resumption: previously connected clients skip handshake on reconnect
• Independent streams: packet loss in one stream doesn't block others
• Integrated TLS 1.3: encryption mandatory, reduces handshake to 1 RTT (vs. 2 for TCP+TLS)
7.4 Geographic Latency
Route Propagation Latency
Within same datacenter < 1ms
Same city 1–5ms
US East ↔ US West 60–70ms
US ↔ Europe 80–120ms
US ↔ Asia Pacific 150–200ms
US ↔ Australia 180–220ms
Anthropic Claude | Academic Reference | Not for redistribution Page 12
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
■ Professor Note: Speed of light in fiber ≈ 200,000 km/s (2/3 of vacuum speed). NY→London = 5,570km → minimum
27.8ms one-way. Real RTT = 80ms+ due to routing, peering, processing.
■ Exam Focus: HTTP/2 multiplexing solves HOL blocking at the HTTP level but not the TCP level. Under packet loss,
TCP retransmission blocks all HTTP/2 streams. HTTP/3/QUIC solves this by using independent UDP streams.
Anthropic Claude | Academic Reference | Not for redistribution Page 13
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 8 Caching Masterclass
8.1 Cache-Control Header
Directive Effect Use Case
max-age=N Cache for N seconds Static assets with versioning
s-maxage=N CDN cache N seconds (overrides max-age) CDN-specific TTL
no-cache Revalidate with server before use Dynamic HTML pages
no-store Never cache (anywhere) Sensitive data, banking
private Browser-only cache (not CDN) Logged-in user responses
public Any cache can store Shared static content
immutable Never revalidate (even on F5) Versioned assets (JS bundles)
stale-while-revalidate=N Serve stale, revalidate in background API responses
must-revalidate Strict — no serving stale Critical data
8.2 Cache Validation
• ETag: Server sends hash of content; client sends If-None-Match → 304 if unchanged
• Last-Modified: Server sends timestamp; client sends If-Modified-Since → 304 if unchanged
• 304 Not Modified: No body transferred — bandwidth saved, but still 1 RTT for validation
• Cache busting: Append content hash to filename ([Link]) → forces fresh fetch
8.3 Service Workers & Offline Architecture
• Service Worker: JavaScript proxy between browser and network — intercepts fetch events
• Cache Storage API: programmatic control over cached responses
• Strategies:
Strategy Logic Best For
Cache First Serve cache, fallback network Static assets, fonts
Network First Try network, fallback cache API calls, fresh data
Stale While Revalidate Cache instantly, update in BG News feeds, social
Cache Only Cache always (no network) Offline-only resources
Network Only No cache (pass-through) Real-time data
8.4 Cache Invalidation Strategies
• TTL expiry: Simplest — cache expires after N seconds. Risk: stale data during TTL
• Event-driven invalidation: Purge CDN/proxy cache on content update (Cloudflare Cache Purge API)
• Surrogate keys / Cache tags: Tag cached responses; invalidate by tag (Fastly, Cloudflare)
• Versioned URLs: Change URL = new cache entry (fingerprinting). Never stale, no purge needed
• Stale-while-revalidate: Serve stale immediately; fetch fresh in background — zero user-visible delay
Anthropic Claude | Academic Reference | Not for redistribution Page 14
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
■ Professor Note: "There are only two hard things in CS: cache invalidation and naming things." — Phil Karlton.
Stale-while-revalidate + surrogate keys is the industry-standard solution to the cache coherence problem.
■ Exam Focus: Browser cache hierarchy: Memory cache (RAM, tab-lifetime) > Disk cache (persistent) > Service
Worker cache (programmatic) > HTTP cache. Memory cache is checked first, fastest (sub-ms).
Anthropic Claude | Academic Reference | Not for redistribution Page 15
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter 9 Nginx for Performance
9.1 Core Tuning Configuration
# /etc/nginx/[Link] — Performance-Optimized Template
worker_processes auto; # 1 per CPU core; 'auto' detects
worker_rlimit_nofile 65535; # match OS ulimit -n
events {
worker_connections 4096; # per worker; total = processes × connections
multi_accept on; # accept all queued connections at once
use epoll; # Linux kernel: most efficient I/O model
}
http {
# --- Compression ---
gzip on;
gzip_comp_level 6; # 1=fast, 9=max; 6 = optimal CPU/ratio balance
gzip_types text/plain text/css application/javascript
application/json image/svg+xml;
gzip_min_length 1024; # don't compress tiny responses
gzip_vary on; # add Vary: Accept-Encoding header
# --- File Transfer ---
sendfile on; # kernel-mode file transfer (zero-copy)
tcp_nopush on; # batch headers + first chunk (with sendfile)
tcp_nodelay on; # disable Nagle for keepalive connections
# --- Keepalive ---
keepalive_timeout 65; # idle keepalive seconds
keepalive_requests 100; # max requests per connection
# --- Buffers ---
client_body_buffer_size 128k;
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
# --- Timeouts ---
client_header_timeout 15s;
client_body_timeout 15s;
send_timeout 15s;
proxy_read_timeout 60s;
# --- Cache (static files) ---
open_file_cache max=10000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
}
9.2 Proxy Cache Configuration
http {
proxy_cache_path /var/cache/nginx levels=1:2
Anthropic Claude | Academic Reference | Not for redistribution Page 16
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
keys_zone=STATIC:10m # 10MB shared memory for cache keys
inactive=60m # purge if not accessed in 60min
max_size=2g; # max disk usage
server {
location /api/ {
proxy_pass [Link]
proxy_cache STATIC;
proxy_cache_valid 200 302 10m; # cache 2xx for 10 minutes
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
proxy_cache_lock on; # coalesce simultaneous requests
add_header X-Cache-Status $upstream_cache_status;
}
}
}
9.3 Load Balancing
upstream backend_pool {
least_conn; # route to server with fewest active connections
keepalive 32; # maintain 32 idle keepalive connections per worker
server [Link]:8080 weight=3; # 3× more traffic
server [Link]:8080 weight=1;
server [Link]:8080 backup; # used only when others are down
}
# Algorithms: round_robin (default), least_conn, ip_hash, hash $var, random
9.4 Rate Limiting
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/m;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
# burst: allow 20 extra requests queued; nodelay: reject over-burst
}
}
}
9.5 Nginx Tuning Checklist
Parameter Recommended Value Impact
worker_processes auto Saturates all CPU cores
worker_connections 4096 Max concurrent connections
gzip_comp_level 6 Optimal CPU/compression ratio
sendfile on Zero-copy file transfer
keepalive_timeout 65 Reduces connection overhead
proxy_cache Enabled Absorbs DB/backend load
Anthropic Claude | Academic Reference | Not for redistribution Page 17
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
open_file_cache max=10000 Avoids repeated file stat() syscalls
■ Professor Note: worker_connections is per-worker. With 4 workers × 4096 connections = 16,384 simultaneous
connections. Each connection consumes ~1KB memory. Plan accordingly.
■■ Industry Focus: Use Nginx as SSL terminator + gzip + proxy cache + rate limiter in production. This offloads
all these concerns from your application server, which should only handle business logic.
Anthropic Claude | Academic Reference | Not for redistribution Page 18
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
10 JavaScript Performance Engineering
10.1 Event Loop Architecture
JavaScript is single-threaded. The event loop processes one task at a time from the call stack. Understanding this model is
prerequisite to all JS performance optimization.
Component Description Performance Implication
Call Stack LIFO execution context stack Deep recursion → stack overflow
Heap Unstructured memory for objects Memory leaks accumulate here
Task Queue (Macro) setTimeout, setInterval, I/O callbacks Run after current task + microtasks
Microtask Queue [Link], queueMicrotask, Run before next task — can starve UI
MutationObserver
Web APIs setTimeout, fetch, DOM events Async operations off main thread
(browser-side)
10.2 Long Task Mitigation
Frame Budget (60fps) = 16.67ms | Long Task Threshold = 50ms
• Yield to main thread: await [Link]() or setTimeout(fn, 0) to break long tasks
• Web Workers: offload heavy computation to background thread (no DOM access)
• requestIdleCallback: execute non-urgent work during browser idle periods
• requestAnimationFrame: schedule visual updates at correct frame timing
10.3 Memory Management
• Memory leaks — common causes:
– Global variables accumulating references
– Event listeners not removed on component unmount
– Closures capturing large objects
– setInterval / setTimeout not cleared
– DOM references held after node removal
10.4 Debounce vs Throttle
Pattern Behavior Formula Use Case
Debounce Execute after N ms of silence Wait N ms after last call Search autocomplete, resize
Throttle Execute at most once per N ms Execute, then ignore for N ms Scroll handlers, mousemove
10.5 React Rendering Optimization
Technique Mechanism When to Use
[Link] Shallow prop comparison; skip re-render if Pure functional components
props unchanged
useMemo Memoize expensive computations Heavy calculations in render
useCallback Stable function reference Prevent child re-renders
Anthropic Claude | Academic Reference | Not for redistribution Page 19
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Virtualization (react-window) Render only visible list items Long lists (100+ items)
Code splitting [Link] + Suspense Route-level or component-level
Concurrent Mode Interrupt low-priority renders Large tree updates
10.6 Bundle Analysis
• webpack-bundle-analyzer: visual treemap of bundle composition
• source-map-explorer: analyze exact bytes per module
• [Link]: check npm package size before adding
• Import cost (VS Code extension): inline import size display
• Target: Initial JS bundle < 170KB compressed (Google threshold)
■ Professor Note: Virtual DOM diffing (reconciliation) is O(n) with heuristics, not O(n³) like naive tree diffing. React
assumes: (1) different element types produce different trees, (2) keys identify stable children.
■ Exam Focus: Microtasks (Promises) run before the next task. A microtask loop that continually enqueues microtasks
will starve the task queue — no timers fire, no UI updates. This is a starvation bug.
Anthropic Claude | Academic Reference | Not for redistribution Page 20
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
11 Database Performance
11.1 SQL Indexing
Index Type Data Structure Best For Cost
B-Tree (default) Balanced tree Range queries, ORDER BY, Low write overhead
equality
Hash Hash table Equality only (=) O(1) lookup, no range
GiST/GIN Generalized Full-text search, JSON, arrays High write overhead
Partial B-Tree on subset WHERE condition subsets Small, targeted
Covering/Composite Multi-column B-Tree Multi-column WHERE + SELECT Column order matters
Index selectivity rule: High-cardinality columns (userId, email) benefit most. Low-cardinality (boolean, status) indexes
often ignored by query planner — composite with high-cardinality column.
11.2 N+1 Query Problem
N+1 occurs when fetching N records, then issuing 1 additional query per record. Results in N+1 total queries.
# PROBLEM — N+1 (1 query for users + N queries for posts)
users = [Link]("SELECT * FROM users")
for user in users:
posts = [Link]("SELECT * FROM posts WHERE user_id = " + str([Link])) # N queries!
# SOLUTION — Eager loading / JOIN
users_with_posts = [Link](
"SELECT u.*, p.* FROM users u LEFT JOIN posts p ON p.user_id = [Link]"
)
# ORMs: use .include() / .with() / .eager_load() / prefetch_related()
11.3 Query Optimization
• EXPLAIN ANALYZE: examine query plan — look for Seq Scan on large tables (needs index)
• SELECT only needed columns — avoid SELECT * (increases I/O and network)
• Pagination: LIMIT/OFFSET has O(n) cost at high offsets — use cursor-based (WHERE id > last_id)
• Avoid functions in WHERE: WHERE YEAR(created_at) = 2024 prevents index use
• Denormalization: store computed aggregates to avoid expensive JOINs at read time
11.4 Redis Caching Patterns
Pattern Flow Use Case
Cache-Aside (Lazy) App checks cache → miss → DB → write cache → Most common, flexible
return
Write-Through Write to cache + DB simultaneously Strong consistency
Write-Behind Write to cache, async flush to DB High write throughput
Read-Through Cache fetches from DB on miss automatically ORM-integrated caching
Anthropic Claude | Academic Reference | Not for redistribution Page 21
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
11.5 CAP Theorem
Distributed systems can guarantee only 2 of 3: Consistency, Availability, Partition Tolerance. Since networks always
partition, choose CP or AP:
System Type Tradeoff
PostgreSQL, MySQL CA (single-node) No partition tolerance in distributed mode
Redis Cluster CP May reject writes during partition
Cassandra, DynamoDB AP Returns stale data during partition
MongoDB (default) CP Writes blocked during primary election
CockroachDB CP Distributed SQL with consensus (Raft)
■ Professor Note: Read replicas solve read scalability but introduce replication lag. For write-after-read consistency
(user sees their own write), route post-write reads to primary or use sticky sessions.
■ Exam Focus: EXPLAIN output keywords to flag: 'Seq Scan' (full table scan), 'Hash Join' (no index join), 'Sort'
(filesort). Each indicates optimization opportunity. Always run EXPLAIN ANALYZE (with actual execution data).
Anthropic Claude | Academic Reference | Not for redistribution Page 22
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
12 Monitoring and Measurement
12.1 Tool Comparison
Tool Type Strengths Limitations
Lighthouse Lab/Synthetic Full CWV audit, reproducible No real users, lab conditions
PageSpeed Insights Lab + Field CWV field data from CrUX Origin-level, not page-level for
field
WebPageTest Synthetic Waterfall, filmstrip, multistep Manual, not continuous
Chrome DevTools Lab Frame-by-frame profiling Single user, manual
New Relic APM RUM + APM Full-stack, traces, alerts Cost, complexity
Datadog APM + Infra Unified observability, dashboards Enterprise cost
SpeedCurve RUM + Synthetic Perf budgets, visual regression Cost
Sentry (Perf) RUM Error + perf correlation, lightweight Limited infra visibility
12.2 Performance Budgets
Performance budgets enforce limits on metrics, preventing regressions. Types:
Budget Type Example Limit Enforcement
Metric budget LCP ≤ 2.5s, CLS ≤ 0.1 CI/CD gate (Lighthouse CI)
Quantity budget Total JS ≤ 200KB gzipped Build-time bundle analysis
Rule budget No image > 200KB Asset lint in CI
Timing budget TTFB ≤ 200ms Synthetic monitoring alert
12.3 Real User Monitoring (RUM)
• PerformanceObserver API: browser-native RUM without third-party scripts
• web-vitals library: Google's CWV measurement library (1KB) — captures LCP, CLS, INP
• Long Tasks API: observe tasks > 50ms for INP debugging
• Navigation Timing API: programmatic access to TTFB, DOM load, network timing
• Resource Timing API: per-asset latency breakdown
12.4 Observability Stack (Production)
Layer Tool Purpose
Frontend RUM web-vitals + custom beacon CWV field data collection
APM New Relic / Datadog / Jaeger Distributed traces, service maps
Metrics Prometheus + Grafana Time-series infra + app metrics
Logging Elasticsearch + Kibana (ELK) Log aggregation + search
Alerting PagerDuty + Grafana Alerts On-call incident routing
Anthropic Claude | Academic Reference | Not for redistribution Page 23
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Synthetic Checkly / WebPageTest API Continuous lab measurement
■ Professor Note: Lab data (Lighthouse) and field data (CrUX) frequently disagree. Lab uses controlled network
throttling; field data reflects real device diversity and network variability. Both are necessary.
■■ Industry Focus: Implement performance budgets in CI/CD. Block PRs that regress LCP > 100ms or increase
JS bundle > 5KB. Lighthouse CI (lhci) integrates directly with GitHub Actions.
Anthropic Claude | Academic Reference | Not for redistribution Page 24
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
13 Security vs. Performance Tradeoffs
13.1 TLS Overhead
Aspect TLS 1.2 TLS 1.3 Mitigation
Handshake RTTs 2 RTT 1 RTT (0-RTT resumption) Use TLS 1.3, enable session
resumption
CPU cost High (RSA key exchange) Lower (ECDHE) Hardware acceleration (AES-NI)
Session tickets Yes Yes Enable for connection reuse
OCSP Stapling Optional Recommended Eliminates revocation check RTT
13.2 WAF (Web Application Firewall) Latency
• Rule evaluation cost: 1–5ms per request for regex-based rule sets
• CDN-integrated WAF (Cloudflare WAF) adds ~0.5ms vs. dedicated appliance (5–15ms)
• OWASP CRS: Core Rule Set in paranoia mode adds 3–10ms — tune for your application
• Rate limiting: negligible overhead when using edge-based counters
13.3 Compression Vulnerabilities
Attack Mechanism Mitigation
CRIME Exploits TLS + gzip compression correlation Disable compression for sensitive headers
(cookies)
BREACH HTTP body compression oracle CSRF tokens, secret masking, disable brotli for
HTML
Time-based side Timing differences in crypto ops Constant-time comparisons
channels
13.4 Caching Sensitive Data
• Never cache: authentication tokens, personal data, session-specific responses
• Cache-Control: private — prevents CDN/proxy caching, browser-only
• Cache-Control: no-store — strictest — no storage anywhere
• Vary: Cookie, Authorization — prevents shared cache serving auth'd response to anonymous
• CDN purge on logout — critical for cached personalized content
13.5 Zero Trust Overhead
• mTLS (mutual TLS): adds 5–15ms for service-to-service auth vs. no auth
• JWT validation: asymmetric verify (RS256) ~0.1ms; symmetric (HS256) ~0.01ms
• API Gateway: auth + rate limit + routing adds 2–10ms per request
• Service mesh (Istio): sidecar proxy adds 1–5ms; worth it for observability + security
■ Professor Note: Security and performance are not opposites. TLS 1.3, HTTP/2, HSTS preloading, and OCSP
stapling simultaneously improve both security and performance vs. their predecessors.
Anthropic Claude | Academic Reference | Not for redistribution Page 25
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
■ Exam Focus: CRIME/BREACH attacks require: (1) attacker controls part of plaintext, (2) compression enabled, (3)
can observe ciphertext length changes. Mitigation: don't compress secrets alongside attacker-controlled data.
Anthropic Claude | Academic Reference | Not for redistribution Page 26
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
14 Scaling Architecture
14.1 Monolith vs. Microservices
Dimension Monolith Microservices
Latency In-process calls (~µs) Network calls (1–10ms per hop)
Deployment All-or-nothing Independent per service
Scaling Scale entire app Scale individual bottleneck services
Complexity Low (one codebase) High (distributed system)
Failure isolation None (one crash = all down) Partial (circuit breakers)
Data management Single DB Per-service DB (polyglot)
Ideal team size < 50 engineers 100+ engineers (Conway's Law)
14.2 Stateless Design — Prerequisite for Scaling
• No session state on server — use JWT or server-side session store (Redis)
• No in-memory caches that differ per instance — use shared Redis
• No local file storage — use S3/GCS for uploads
• Idempotent request handling — retry-safe without side effects
• Health check endpoints — load balancer removes unhealthy instances
14.3 Load Balancing Algorithms
Algorithm Logic Best For
Round Robin Rotate through servers Homogeneous servers, uniform requests
Least Connections Route to server with fewest active conns Variable request duration
IP Hash Hash client IP → same server Session affinity (stateful apps)
Weighted Round Robin Proportional by server capacity Heterogeneous server pools
Random with 2 choices Pick 2 random, route to least loaded Large server pools (P2C)
14.4 Distributed Systems Patterns
Pattern Problem Solved Implementation
Circuit Breaker Cascading failures Hystrix, Resilience4j, Polly
Bulkhead Resource isolation Thread pool isolation per service
Retry with Backoff Transient failures Exponential backoff + jitter
Saga Distributed transactions Choreography or orchestration
CQRS Read/write optimization Separate read model (projections)
Event Sourcing Audit trail + replay Append-only event log (Kafka)
Anthropic Claude | Academic Reference | Not for redistribution Page 27
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
■ Professor Note: Auto-scaling lag is 2–5 minutes for VM-based scaling. Design for over-provisioning baseline +
queue-based smoothing for traffic spikes. Container-based scaling (K8s) is ~30s; serverless is ~100ms cold start.
■ Exam Focus: CAP theorem practical: choose between consistency (CP: Redis, Zookeeper) or availability (AP:
DynamoDB, Cassandra) when partitions occur. PACELC extends CAP to also consider latency tradeoffs during normal
operation.
Anthropic Claude | Academic Reference | Not for redistribution Page 28
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
15 Common Performance Bottlenecks
15.1 Bottleneck Catalog
Bottleneck Symptom Root Cause Fix
Render-blocking JS High FCP, blank screen Sync script in async/defer, move to
Large JS bundle High TTI, long parse Monolithic bundle Code splitting, tree shaking
Unoptimized images High LCP, bandwidth PNG/JPEG at original size WebP/AVIF, srcset, CDN
waste
Excessive DB queries High TTFB N+1, missing index Eager load, index, cache
Missing cache DB overload under traffic No Redis / proxy cache Redis cache-aside, CDN
Cold starts Latency spikes (P99) Serverless function boot Provisioned concurrency, warm
Third-party scripts LCP/INP regression Synchronous async load, facade pattern
chat/ads/analytics
DNS delays Initial load latency No dns-prefetch for origins dns-prefetch, preconnect
Large DOM Slow layout/interaction 100k+ DOM nodes Virtualization, pagination
Memory leaks Degrading perf over time Event listener accumulation Remove listeners on unmount
Synchronous Main thread I/O block Blocking storage read Use IndexedDB async or cache
localStorage
15.2 Third-Party Script Impact
• Category impact (typical): Chat widgets (+200ms), A/B testing (+100ms), Tag managers (+150ms)
• Facade pattern: Replace chat widget iframe with static placeholder; load full widget on hover/click
• Partytown: Runs third-party JS in Web Worker, off main thread
• Resource hints: preconnect to third-party domains to reduce their connection cost
• Audit regularly: Remove unused scripts — each adds parse + execution overhead
15.3 Cold Start Analysis
Platform Cold Start Mitigation
AWS Lambda (Node) 100–500ms Provisioned concurrency, smaller bundles
AWS Lambda (JVM) 1–10s SnapStart (Lambda), GraalVM native
Vercel Edge Functions < 10ms V8 isolates, no cold start
Cloudflare Workers < 5ms V8 isolates, global edge
Kubernetes Pod 5–30s Pod pre-scaling, warm pool
■ Professor Note: The facade pattern for third-party scripts is one of the highest-ROI single optimizations. Replacing an
always-loaded chat widget with a facade image saves 200–400ms LCP at zero functionality cost for users who never
interact with it.
Anthropic Claude | Academic Reference | Not for redistribution Page 29
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
16 Advanced Performance Concepts
16.1 Edge SSR
Run server-side rendering at CDN edge nodes (PoPs) rather than origin servers. Combines SSR's SEO/FCP benefits with
CDN's geographic proximity.
Platform Edge Runtime Max Response Latency Advantage
Size
Cloudflare Workers V8 Isolates (not Node) < 1MB Global, ~10ms to user
Vercel Edge Runtime V8 Isolates < 4MB Vercel PoP network
Fastly Compute Wasm-based Unlimited Fastly PoP network
AWS Lambda@Edge [Link] subset 1MB viewer, 40MB CloudFront PoPs
origin
16.2 Streaming SSR
Stream HTML to browser as it's generated, rather than waiting for full render. Browser receives and renders early content
while server continues generating.
• React 18 renderToPipeableStream: streams components as they resolve
• Suspense boundaries: stream placeholders first, content when ready
• Benefit: TTFB = first chunk time; FCP improves even for slow-generating pages
• Limitation: HTTP headers sent with first chunk — late redirects impossible
• Out-of-order streaming: React can stream later components before earlier ones if ready
16.3 Speculation Rules API
Browser API to declaratively prerender or prefetch next-page navigations. Prerendered pages load instantly on navigation.
{
"prerender": [{
"where": {"href_matches": "/products/*"},
"eagerness": "moderate" // conservative|moderate|eager
}],
"prefetch": [{
"urls": ["/api/critical-data"],
"eagerness": "immediate"
}]
}
// Note: prerender consumes ~50–100MB RAM per page. Use selectively.
16.4 HTTP Prioritization
HTTP/2 and HTTP/3 allow explicit resource priority signaling. Browsers auto-assign priorities; developers can override with
Fetch Priority API.
Anthropic Claude | Academic Reference | Not for redistribution Page 30
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
// In JS:
fetch('/critical-data', { priority: 'high' });
16.5 Green Web Performance
• Energy ∝ Data transferred × Device processing × Server compute
• Carbon-aware hosting: schedule batch jobs during low-carbon grid periods
• Image optimization: WebP/AVIF reduces both bytes and decode CPU
• Reduce JS: JS has highest carbon cost — parse + execute + JIT compilation
• CDN edge caching: reduces origin compute, saves data center energy
• Website Carbon Calculator: [Link] — measures CO■ per page visit
■ Professor Note: ISR (Incremental Static Regeneration — [Link]) regenerates static pages on-demand after TTL
expiry, triggered by the first post-expiry request. Combines static speed with dynamic content freshness.
Anthropic Claude | Academic Reference | Not for redistribution Page 31
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
17 Comparative Reference Tables
17.1 Rendering Strategies
Strategy TTFB FCP SEO Freshness Infra Cost
CSR Fast (empty Slow Poor Real-time Low
HTML)
SSR Slow (compute) Fast Excellent Real-time High
SSG Instant (CDN) Instant Excellent Stale (rebuild) Minimal
ISR Fast Instant Excellent Near-real-time Low
(CDN+regen)
Streaming SSR Medium Progressive Good Real-time Medium
Edge SSR Fast (PoP) Fast Excellent Real-time Medium
17.2 HTTP Protocol Versions
Feature HTTP/1.1 HTTP/2 HTTP/3
Multiplexing No Yes Yes
Header compression No HPACK QPACK
Transport TCP TCP QUIC/UDP
HOL Blocking HTTP + TCP TCP only None
0-RTT resumption No No (TLS 1.3) Yes
Server push No Yes No
Binary protocol No Yes Yes
17.3 Caching Types
Cache Location Scope TTL Control Invalidation
Memory cache Browser RAM Tab-level Browser controlled Tab close
Disk cache Browser storage Profile-level Cache-Control Cache-Control expiry
Service Worker Browser App-controlled Programmatic JS code
Reverse proxy Nginx/Varnish Shared (all users) proxy_cache_valid Purge API
CDN Edge PoP Global Cache-Control Purge API, cache tags
Redis Server RAM Application TTL (EXPIRE) DEL command
17.4 CDN vs Reverse Proxy
Dimension CDN Reverse Proxy (Nginx)
Location Edge PoPs globally Your datacenter
Primary use Static + cacheable content SSL termination, load balance, cache
Anthropic Claude | Academic Reference | Not for redistribution Page 32
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Latency reduction Yes (geographic) No (same location as server)
DDoS protection Yes (Cloudflare, AWS) Limited
Cost Usage-based Infrastructure
Examples Cloudflare, CloudFront, Fastly Nginx, HAProxy, Caddy
Anthropic Claude | Academic Reference | Not for redistribution Page 33
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
18 Practical Deployment Checklists
18.1 Frontend Launch Checklist
■ Images
• ■ All images served as WebP/AVIF with JPEG/PNG fallback
• ■ LCP image has fetchpriority='high' and is preloaded
• ■ All img/video elements have explicit width and height (prevents CLS)
• ■ Off-screen images use loading='lazy'
• ■ Images served via CDN with long max-age + cache-busted URLs
■ JavaScript
• ■ No synchronous scripts in
• ■ async for analytics/ads; defer for app scripts
• ■ Initial JS bundle < 170KB gzipped
• ■ Code splitting implemented (per-route, lazy components)
• ■ Third-party scripts loaded async or via facade pattern
• ■ No unused dependencies (audited with bundle-analyzer)
■ CSS
• ■ Critical CSS inlined in
• ■ Non-critical CSS loaded with preload + onload trick
• ■ No @import in CSS files
• ■ Unused CSS purged (PurgeCSS / Tailwind JIT)
■ Fonts
• ■ Fonts preloaded for critical above-fold text
• ■ font-display: swap or optional
• ■ Self-hosted or preconnect to Google Fonts origin
• ■ Subset to required Unicode ranges
■ Resource Hints
• ■ preconnect to critical third-party origins
• ■ dns-prefetch for secondary origins
• ■ Speculation Rules for predictable navigation
18.2 Backend Launch Checklist
• ■ Redis cache implemented for DB query results (cache-aside pattern)
• ■ All DB queries have EXPLAIN ANALYZE run — no Seq Scans on large tables
• ■ N+1 queries eliminated — verify with SQL query log
• ■ Connection pooling configured (PgBouncer for PostgreSQL)
• ■ API responses paginated (cursor-based for large datasets)
• ■ Brotli/gzip enabled on all text responses
• ■ TTFB < 200ms measured under expected load
• ■ Health check endpoint returns 200 in < 100ms
• ■ Graceful shutdown implemented (drains connections before exit)
• ■ Rate limiting on all public endpoints
• ■ Slow query log enabled and monitored
Anthropic Claude | Academic Reference | Not for redistribution Page 34
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
18.3 Nginx Tuning Checklist
• ■ worker_processes auto
• ■ worker_connections ≥ 1024 (set to 4096 for high traffic)
• ■ gzip on with types and min_length set
• ■ sendfile on + tcp_nopush on
• ■ keepalive_timeout 65
• ■ proxy_cache configured for API responses
• ■ Rate limiting zones defined
• ■ open_file_cache configured
• ■ SSL session cache and tickets enabled
• ■ OCSP stapling enabled
• ■ HTTP/2 enabled (listen 443 ssl http2)
18.4 Monitoring Checklist
• ■ Core Web Vitals monitored in field (web-vitals library + analytics)
• ■ Synthetic monitoring running every 5 minutes from 3+ regions
• ■ TTFB alert if > 800ms for 5 minutes
• ■ Error rate alert if > 0.1% for 5 minutes
• ■ P99 response time alert configured
• ■ DB slow query log reviewed weekly
• ■ JS bundle size tracked in CI (fails if > budget)
• ■ Lighthouse CI integrated into PR pipeline
• ■ Memory usage trended (detect leaks before OOM)
• ■ Cache hit rate monitored (Redis: > 90% target)
Anthropic Claude | Academic Reference | Not for redistribution Page 35
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Chapter
19 Rapid Revision
19.1 Formula Sheet
Propagation_Delay + Transmission_Delay + Processing_Delay +
Latency
Queuing_Delay
Throughput Total_Requests / Time_Interval [req/s]
Bandwidth-Delay Product Bandwidth × RTT (bytes in-flight on network)
Cold Start Delay DNS_lookup + TCP (1×RTT) + TLS (1×RTT) + HTTP_request/response
Σ (impact_fraction × distance_fraction) for each unexpected
CLS Score
layout shift
Frame Budget (60fps) 1000ms / 60 = 16.67ms per frame
Long Task Threshold Any main-thread task > 50ms
LCP Good Threshold ≤ 2.5s | Poor: > 4.0s
INP Good Threshold ≤ 200ms | Poor: > 500ms
CLS Good Threshold ≤ 0.1 | Poor: > 0.25
FCP Good Threshold ≤ 1.8s | Poor: > 3.0s
TTFB Good Threshold ≤ 800ms | Poor: > 1.8s
19.2 50 Key Points
01 LCP measures largest above-fold element render time; target ≤ 2.5s
02 INP (98th percentile input latency) replaced FID as Core Web Vital in March 2024
03 CLS = sum of (impact_fraction × distance_fraction) for all unexpected shifts; target ≤ 0.1
04 TTFB > 800ms almost always indicates server-side bottleneck, not frontend
05 DNS lookup: browser cache → OS cache → resolver → root → TLD → authoritative
06 TCP requires 1 RTT before data; TLS 1.2 adds 2 RTT; TLS 1.3 adds 1 RTT
07 TCP slow start: initial congestion window ≈ 14KB — first round is size-limited
08 Critical Rendering Path: HTML Parse → DOM → CSSOM → Render Tree → Layout → Paint → Composite
09 Reflow (layout) is expensive — invalidates geometry of all dependent elements
10 transform/opacity are GPU-composited — bypass Layout and Paint stages entirely
11 async loads script without blocking parser but executes as soon as ready (no order)
12 defer loads script without blocking parser and executes after DOM parsed, in order
13 Brotli achieves ~20% better compression than gzip; requires HTTPS
14 HTTP/2 multiplexing eliminates HTTP head-of-line blocking but not TCP HOL blocking
15 HTTP/3/QUIC uses UDP — eliminates TCP-level HOL blocking entirely
16 BDP (Bandwidth-Delay Product) = bandwidth × RTT = bytes in-flight on network
17 CDN reduces effective latency from 100–300ms to 20–50ms via geographic proximity
Anthropic Claude | Academic Reference | Not for redistribution Page 36
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
18 Cache-Control: immutable + versioned URL = perfect caching with no revalidation
19 stale-while-revalidate serves cached response instantly, fetches fresh in background
20 Service Worker cache sits between browser and network; fully programmable
21 N+1 query: 1 query for N records + N additional queries = N+1 total. Fix: eager load + JOIN
22 EXPLAIN ANALYZE (not just EXPLAIN) shows actual row counts vs estimated — critical for debugging
23 Cursor-based pagination O(1) vs OFFSET-based O(n) at large offsets
24 Redis cache-aside: check cache → miss → query DB → write cache → return
25 Connection pooling eliminates per-request TCP handshake to database
26 Stateless servers are prerequisite for horizontal scaling (no session affinity needed)
27 CAP theorem: distributed systems can guarantee only 2 of Consistency, Availability, Partition Tolerance
28 Load balancing: least_conn is better than round-robin for variable request durations
29 Cold start for AWS Lambda (Node): 100–500ms; Cloudflare Workers: < 5ms (V8 isolates, no container)
30 Nginx worker_processes auto = 1 per CPU core; worker_connections × processes = total capacity
31 sendfile + tcp_nopush enables zero-copy file transfer from disk to socket
32 Microtasks (Promises) run before the next task — can starve task queue if loop continues
33 [Link] does shallow prop comparison; deep comparisons via useMemo with custom equality
34 Virtual DOM reconciliation is O(n) with heuristics: same type = update, different type = recreate
35 Long task threshold = 50ms; frame budget at 60fps = 16.67ms
36 Web Workers run JS in background thread — no DOM access; use for heavy computation
37 Bundle size target: initial JS < 170KB gzipped (Google PageSpeed threshold)
38 font-display: swap shows fallback immediately; font-display: optional skips web font if slow
39 preconnect hint does DNS + TCP + TLS early — saves 1–2 RTTs for critical origins
40 Speculation Rules API prerenders entire next page — near-instant navigation
41 CRIME/BREACH attacks exploit TLS compression — disable for sensitive responses
42 TLS 1.3 supports 0-RTT session resumption for previously connected clients
43 Streaming SSR: TTFB = first chunk time; browser renders early while server continues
44 ISR: regenerates static pages on-demand after TTL, triggered by first post-expiry request
45 Green web: JS has highest carbon cost (parse + JIT); fewer bytes = less energy
46 HPACK (HTTP/2) compresses headers using static + dynamic table — repeat headers = ~0 bytes
47 Lighthouse CI can gate PRs: block merges that regress LCP or inflate JS bundle
48 WAF adds 1–5ms per request; CDN-integrated WAF (Cloudflare) adds ~0.5ms
49 mTLS between services adds 5–15ms — weigh against security requirement per route
50 Partytown runs third-party scripts in Web Worker, off main thread, preserving INP
19.3 Common Interview Questions & Answers
Q: What is the Critical Rendering Path and how do you optimize it?
A: The CRP is the sequence HTML→DOM→CSSOM→Render Tree→Layout→Paint→Composite. Optimize by:
eliminating render-blocking resources (async/defer JS, preload CSS), inlining critical CSS, minimizing DOM depth, and
using GPU-composited animations.
Anthropic Claude | Academic Reference | Not for redistribution Page 37
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
Q: How does HTTP/2 multiplexing differ from HTTP/3?
A: HTTP/2 multiplexes multiple streams over one TCP connection, eliminating HTTP-level HOL blocking. HTTP/3 uses
QUIC (UDP), which eliminates TCP-level HOL blocking — packet loss in one stream doesn't block others.
Q: Explain the difference between debounce and throttle.
A: Debounce: execute after N ms of inactivity (waits for silence — e.g., search). Throttle: execute at most once per N ms
regardless of call frequency (rate-limits — e.g., scroll).
Q: What causes high CLS and how do you fix it?
A: CLS is caused by: images/videos without dimensions, late-loading fonts (FOIT/FOUT), dynamic content injection
above viewport, and ads without reserved space. Fix: explicit width/height on media, font-display: optional, reserve space
for dynamic content.
Q: What is the N+1 query problem and how do you solve it?
A: N+1 occurs when fetching N records then issuing 1 DB query per record = N+1 queries. Fix: eager loading (JOIN or
ORM .include()), DataLoader (batching + caching for GraphQL), or application-level caching.
Q: How does Redis cache invalidation work?
A: Strategies: (1) TTL expiry — key auto-expires after N seconds; (2) explicit deletion — DEL key on data update; (3)
event-driven — pub/sub triggers invalidation; (4) versioned keys — change key name instead of invalidating.
Q: What is TTFB and what causes it to be high?
A: TTFB (Time to First Byte) is time from request start to first response byte. High TTFB indicates: slow DB queries,
missing server-side cache, unoptimized server code, cold start (serverless), or geographic distance (fix with CDN/edge).
Q: How do you reduce LCP?
A: Priority order: (1) optimize TTFB (CDN, server cache), (2) eliminate render-blocking resources, (3) preload LCP image
with fetchpriority=high, (4) use WebP/AVIF, (5) use SSR/SSG instead of CSR.
Q: Explain the difference between SSR, SSG, and ISR.
A: SSR: HTML generated per-request on server (fresh, slower TTFB). SSG: HTML generated at build time (instant, stale
until rebuild). ISR: SSG with per-page TTL — regenerates on-demand after expiry ([Link]).
Q: What is the purpose of stale-while-revalidate?
A: SWR directive serves a stale cached response immediately (zero user-visible latency), then fetches a fresh response
in the background to update the cache. Combines performance (instant serve) with freshness (background update).
19.4 Performance Debugging Workflow
Step Tool Question to Answer
1. Lighthouse + WebPageTest What are current CWV scores?
Measure
baseline
2. Chrome DevTools Network tab What resources are on the critical path?
Identify
bottlene
ck
Anthropic Claude | Academic Reference | Not for redistribution Page 38
Web Performance Engineering — MIT-Level Condensed Guide © 2025 MIT OCW Style
3. DevTools Performance tab Where is time spent in the browser?
Profile r
endering
4. Audit TTFB measurement + APM Is server response time > 200ms?
server
5. EXPLAIN ANALYZE + slow Any Seq Scans or N+1 queries?
Check d query log
atabase
6. Bundle analyzer + Coverage tab Unused code? Large dependencies?
Analyze
JS
7. Fix + Re-run Lighthouse + RUM Did the metric improve?
measure
8. Set Lighthouse CI in pipeline Will future changes regress?
budget
19.5 Common Mistakes
• 1. Optimizing without measuring — always establish baseline before changing
• 2. Using SELECT * in production queries — specifies columns to reduce I/O
• 3. Setting Cache-Control: no-cache on static assets — misses CDN caching entirely
• 4. Loading all JS synchronously in — blocks HTML parsing
• 5. Using HTTP/1.1 without CDN — misses free HTTP/2 upgrade and geographic acceleration
• 6. Serving uncompressed API responses — 60–80% savings with gzip enabled
• 7. Not setting image dimensions — guarantees CLS on every load
• 8. Event listeners not cleaned up in React useEffect — accumulates memory leaks
• 9. Database queries inside render functions — triggers per-render DB hits
• 10. Conflating lab metrics (Lighthouse) with field data (CrUX) — they measure different things
End of Document — Web Performance Engineering: MIT-Level Condensed Guide
Generated for academic and professional reference. Always verify metrics against current browser specifications.
Anthropic Claude | Academic Reference | Not for redistribution Page 39