Part 01 · How the Browser Works

Lab Setup: ShopLite

ViteReactExpressDocker Compose

One docker-compose lab for the whole course: the ShopLite React app, a mock API with tunable latency, errors and payload size, 10k seeded products, and a real-time server.

⏱ 12 min · Station 9 of 125

What you'll have at the end

One folder, shoplite/, that starts everything this course measures with one command:

ServicePortWhat it is
web5173ShopLite: a Vite + React + TypeScript storefront, served as a production build. Also hosts the lessons' experiment pages under /x/.
api4000A mock API on Express with 10,000 products, 50,000 reviews and 2,000 orders. Every route can be slowed down, made to fail, or padded with extra bytes.
rt4001A real-time server: live order status over WebSocket (/ws) and Server-Sent Events (/sse).
tools/Node scripts that drive real Chrome (through Playwright) with network and CPU throttling, and print what the browser measured.

The data comes from a seeded random generator, so your products, prices and ratings match ours exactly. Timings won't: your machine differs. Ours is an Intel i3-10110U (4 threads), 7 GB RAM, Ubuntu 26.04, Docker 29.8, Chrome 151.

You need Docker with Compose, Node.js 22.19 or newer on the host (for tools/), Google Chrome, and about 600 MB of free RAM while the lab runs.

The files

The layout:

shoplite/
  docker-compose.yml
  api/      package.json  seed.mjs  server.mjs
  rt/       package.json  server.mjs
  web/      package.json  tsconfig.json  vite.config.ts  index.html  gen-pages.mjs
            src/  main.tsx  App.tsx  api.ts  styles.css
            src/pages/  Home.tsx  Listing.tsx  ProductPage.tsx  Cart.tsx
            public/x/   (experiment pages, added lesson by lesson)
  tools/    package.json  lib.mjs  pageload.mjs  ws-check.mjs  (more, lesson by lesson)

docker-compose.yml:

# ShopLite lab: one command runs the app, the mock API and the real-time server.
#   docker compose up -d      then open http://localhost:5173
name: shoplite

x-node: &node
  image: node:22-slim
  user: node
  working_dir: /app
  restart: unless-stopped

services:
  api:
    <<: *node
    volumes: ["./api:/app"]
    command: sh -c "npm install --no-audit --no-fund && node seed.mjs && node server.mjs"
    environment:
      LATENCY_MS: 0
      ERROR_RATE: 0
    ports: ["4000:4000"]
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://localhost:4000/health').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"]
      interval: 3s
      retries: 40

  rt:
    <<: *node
    volumes: ["./rt:/app"]
    command: sh -c "npm install --no-audit --no-fund && node server.mjs"
    environment:
      TICK_MS: 2000
    ports: ["4001:4001"]
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://localhost:4001/health').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"]
      interval: 3s
      retries: 40

  web:
    <<: *node
    volumes: ["./web:/app"]
    # A production build, served as static files: what users actually download.
    command: sh -c "npm install --no-audit --no-fund && npm run build && npm run preview"
    environment:
      VITE_API: http://localhost:4000
    ports: ["5173:5173"]
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://localhost:5173/').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"]
      interval: 3s
      retries: 60
    depends_on:
      api: { condition: service_healthy }

Three things worth knowing about it:

  • node:22-slim, not node:22-alpine. On Alpine, Vite's build failed with Code is nested too deeply while parsing React. The Debian-based slim image builds fine.
  • web serves a production build (vite build + vite preview), not the dev server. The dev server sends hundreds of unbundled modules, which is not what users download, and it would make every measurement in this course wrong.
  • user: node so files the containers write into your folders (node_modules, dist, data) belong to your user, not root.

The mock API

api/package.json:

{
  "name": "shoplite-api",
  "private": true,
  "type": "module",
  "scripts": { "seed": "node seed.mjs", "start": "node server.mjs" },
  "dependencies": { "express": "5.1.0" }
}

api/seed.mjs generates the data with a fixed seed:

// Generates ShopLite's data: 10,000 products, 50,000 reviews, 2,000 orders.
// A fixed seed means every learner gets the exact same data.
import { mkdirSync, writeFileSync } from "node:fs";

let s = 42;
const rand = () => ((s = (s * 1103515245 + 12345) % 2147483648) / 2147483648);
const pick = (a) => a[Math.floor(rand() * a.length)];

const CATEGORIES = ["phones", "laptops", "audio", "cameras", "watches", "shoes", "bags", "books", "kitchen", "toys"];
const ADJ = ["Lite", "Pro", "Max", "Mini", "Air", "Plus", "Neo", "Ultra", "Go", "One"];
const BRANDS = ["Nova", "Orbit", "Pixel", "Kite", "Lumen", "Delta", "Fable", "Rivet", "Echo", "Mango"];
const WORDS = ["great", "fast", "solid", "cheap", "broke", "loud", "light", "sturdy", "late", "perfect", "battery", "screen"];

const products = [];
for (let id = 1; id <= 10_000; id++) {
  const category = CATEGORIES[(id - 1) % CATEGORIES.length];
  products.push({
    id,
    name: `${pick(BRANDS)} ${category.slice(0, -1)} ${pick(ADJ)} ${id}`,
    category,
    price: Math.round((5 + rand() * 995) * 100) / 100,
    rating: Math.round((2.5 + rand() * 2.5) * 10) / 10,
    stock: Math.floor(rand() * 200),
    image: `/img/${id}.svg`,
    description: Array.from({ length: 30 }, () => pick(WORDS)).join(" "),
  });
}

const reviews = [];
for (let i = 1; i <= 50_000; i++) {
  reviews.push({
    id: i,
    productId: 1 + Math.floor(rand() * 10_000),
    stars: 1 + Math.floor(rand() * 5),
    text: Array.from({ length: 12 }, () => pick(WORDS)).join(" "),
  });
}

const STATUS = ["placed", "packed", "shipped", "out-for-delivery", "delivered"];
const orders = [];
for (let id = 1; id <= 2_000; id++) {
  orders.push({
    id,
    items: Array.from({ length: 1 + Math.floor(rand() * 4) }, () => ({ productId: 1 + Math.floor(rand() * 10_000), qty: 1 + Math.floor(rand() * 3) })),
    status: pick(STATUS),
  });
}

mkdirSync("data", { recursive: true });
for (const [name, rows] of Object.entries({ products, reviews, orders })) {
  writeFileSync(`data/${name}.json`, JSON.stringify(rows));
  console.log(`${name.padEnd(9)} ${String(rows.length).padStart(6)} rows`);
}

api/server.mjs. The middleware near the top is the important part: it reads latency, error and padKb from the query string or from a per-route config, before any route runs:

// ShopLite mock API. Every route can be slowed down, made to fail, or padded with extra bytes,
// so lessons can show what slow networks and flaky servers do to the page.
//
//   per request:  ?latency=300&error=0.2&padKb=100
//   per route:    curl -X PUT localhost:4000/__config -H 'content-type: application/json' \
//                   -d '{"/api/products": {"latency": 300, "error": 0.1}}'
import express from "express";
import { readFileSync } from "node:fs";

const load = (n) => JSON.parse(readFileSync(new URL(`./data/${n}.json`, import.meta.url)));
const products = load("products");
const reviews = load("reviews");
const orders = load("orders");
const byId = new Map(products.map((p) => [p.id, p]));

const app = express();
app.use(express.json());
app.use((req, res, next) => {
  res.set("access-control-allow-origin", "*");
  res.set("access-control-allow-headers", "content-type");
  res.set("access-control-allow-methods", "GET,POST,PUT,DELETE");
  res.set("timing-allow-origin", "*");
  if (req.method === "OPTIONS") return res.end();
  next();
});

// Knobs: route config first, the query string wins.
const config = {};
app.put("/__config", (req, res) => {
  Object.assign(config, req.body);
  res.json(config);
});
app.get("/__config", (req, res) => res.json(config));

app.use((req, res, next) => {
  const route = Object.keys(config).find((r) => req.path.startsWith(r));
  const c = { ...(route ? config[route] : {}), ...req.query };
  const latency = Number(c.latency ?? process.env.LATENCY_MS ?? 0);
  const error = Number(c.error ?? process.env.ERROR_RATE ?? 0);
  const padKb = Number(c.padKb ?? 0);
  if (padKb) {
    const json = res.json.bind(res);
    res.json = (body) => json({ ...body, _pad: "x".repeat(padKb * 1024) });
  }
  setTimeout(() => {
    if (Math.random() < error) return res.status(503).json({ error: "injected failure" });
    next();
  }, latency);
});

app.get("/health", (req, res) => res.json({ ok: true, products: products.length, reviews: reviews.length, orders: orders.length }));

app.get("/api/products", (req, res) => {
  const { category, q, sort } = req.query;
  const limit = Math.min(Number(req.query.limit ?? 20), 10_000);
  const page = Number(req.query.page ?? 1);
  let rows = products;
  if (category) rows = rows.filter((p) => p.category === category);
  if (q) rows = rows.filter((p) => p.name.toLowerCase().includes(String(q).toLowerCase()));
  if (sort === "price") rows = [...rows].sort((a, b) => a.price - b.price);
  if (sort === "rating") rows = [...rows].sort((a, b) => b.rating - a.rating);
  res.json({ total: rows.length, page, items: rows.slice((page - 1) * limit, page * limit) });
});

app.get("/api/products/:id", (req, res) => {
  const p = byId.get(Number(req.params.id));
  p ? res.json(p) : res.status(404).json({ error: "not found" });
});

app.get("/api/products/:id/reviews", (req, res) => {
  const id = Number(req.params.id);
  res.json({ items: reviews.filter((r) => r.productId === id) });
});

app.get("/api/search", (req, res) => {
  const q = String(req.query.q ?? "").toLowerCase();
  res.json({ q, items: q ? products.filter((p) => p.name.toLowerCase().includes(q)).slice(0, 8) : [] });
});

const cart = new Map();
app.get("/api/cart", (req, res) => res.json({ items: [...cart.entries()].map(([productId, qty]) => ({ productId, qty })) }));
app.post("/api/cart", (req, res) => {
  const { productId, qty } = req.body;
  if (!byId.has(productId)) return res.status(400).json({ error: "unknown product" });
  qty > 0 ? cart.set(productId, qty) : cart.delete(productId);
  res.json({ items: [...cart.entries()].map(([productId, qty]) => ({ productId, qty })) });
});

app.get("/api/orders/:id", (req, res) => {
  const o = orders.find((o) => o.id === Number(req.params.id));
  o ? res.json(o) : res.status(404).json({ error: "not found" });
});

// A product image: a coloured SVG card, cacheable for a year.
app.get("/img/:id.svg", (req, res) => {
  const id = Number(req.params.id);
  const hue = (id * 37) % 360;
  res.set("content-type", "image/svg+xml").set("cache-control", "public, max-age=31536000, immutable");
  res.send(`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300"><rect width="400" height="300" fill="hsl(${hue} 60% 55%)"/><text x="200" y="165" font-size="48" text-anchor="middle" fill="#fff" font-family="sans-serif">#${id}</text></svg>`);
});

// Test assets for the browser lessons: a CSS, JS or image file of `kb` kilobytes, sent after `delay` ms.
app.get("/asset/:name", (req, res) => {
  const kb = Number(req.query.kb ?? 10);
  const busy = Number(req.query.busy ?? 0);
  const ext = req.params.name.split(".").pop();
  const filler = "/*" + "x".repeat(Math.max(kb * 1024 - 4, 0)) + "*/";
  res.set("cache-control", req.query.cache ?? "no-store");
  if (ext === "css") res.type("text/css").send(`${req.query.css ?? ""}\n${filler}`);
  else if (ext === "js")
    res.type("text/javascript").send(
      `(()=>{const t=performance.now();while(performance.now()-t<${busy});performance.mark("${req.params.name}-ran")})();\n${filler}`,
    );
  else res.redirect(`/img/${kb}.svg`);
});

const port = Number(process.env.PORT ?? 4000);
app.listen(port, () => console.log(`api listening on :${port}`));

The real-time server

rt/package.json:

{
  "name": "shoplite-rt",
  "private": true,
  "type": "module",
  "scripts": { "start": "node server.mjs" },
  "dependencies": { "ws": "8.18.3" }
}

rt/server.mjs:

// ShopLite real-time server: live order status over WebSocket (/ws) and Server-Sent Events (/sse).
// Each connection gets the order's status every `every` ms, moving through the five steps.
import { createServer } from "node:http";
import { WebSocketServer } from "ws";

const STEPS = ["placed", "packed", "shipped", "out-for-delivery", "delivered"];
const every = Number(process.env.TICK_MS ?? 2000);

const server = createServer((req, res) => {
  const url = new URL(req.url, "http://x");
  if (url.pathname === "/health") return res.end(JSON.stringify({ ok: true }));
  if (url.pathname !== "/sse") return res.writeHead(404).end();
  const order = Number(url.searchParams.get("order") ?? 1);
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", "access-control-allow-origin": "*" });
  let i = 0;
  const send = () => res.write(`id: ${i}\ndata: ${JSON.stringify({ order, status: STEPS[i % STEPS.length], seq: i++ })}\n\n`);
  send();
  const t = setInterval(send, every);
  req.on("close", () => clearInterval(t));
});

const wss = new WebSocketServer({ server, path: "/ws" });
wss.on("connection", (ws, req) => {
  const order = Number(new URL(req.url, "http://x").searchParams.get("order") ?? 1);
  let i = 0;
  const send = () => ws.send(JSON.stringify({ order, status: STEPS[i % STEPS.length], seq: i++ }));
  send();
  const t = setInterval(send, every);
  ws.on("close", () => clearInterval(t));
});

const port = Number(process.env.PORT ?? 4001);
server.listen(port, () => console.log(`rt listening on :${port} (ws /ws, sse /sse)`));

The ShopLite app

web/package.json:

{
  "name": "shoplite-web",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host",
    "build": "node gen-pages.mjs && tsc -b && vite build",
    "preview": "vite preview --host --port 5173 --strictPort"
  },
  "dependencies": { "react": "19.1.1", "react-dom": "19.1.1" },
  "devDependencies": {
    "@types/react": "19.1.8",
    "@types/react-dom": "19.1.6",
    "@vitejs/plugin-react": "4.7.0",
    "typescript": "5.8.3",
    "vite": "6.3.5"
  }
}

web/tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "types": ["vite/client"]
  },
  "include": ["src"]
}

web/vite.config.ts:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: { port: 5173, strictPort: true },
  preview: { port: 5173, strictPort: true },
});

web/index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ShopLite</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

web/src/main.tsx:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
import "./styles.css";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

web/src/App.tsx, with a tiny router so the app has no dependencies besides React:

import { useEffect, useState } from "react";
import { Home } from "./pages/Home";
import { Listing } from "./pages/Listing";
import { ProductPage } from "./pages/ProductPage";
import { Cart } from "./pages/Cart";

// A tiny router: enough for four pages without pulling in a library.
export function navigate(to: string) {
  history.pushState(null, "", to);
  dispatchEvent(new PopStateEvent("popstate"));
}

export function Link({ to, children }: { to: string; children: React.ReactNode }) {
  return (
    <a href={to} onClick={(e) => (e.preventDefault(), navigate(to))}>
      {children}
    </a>
  );
}

export function App() {
  const [path, setPath] = useState(location.pathname);
  useEffect(() => {
    const on = () => setPath(location.pathname);
    addEventListener("popstate", on);
    return () => removeEventListener("popstate", on);
  }, []);

  const product = path.match(/^\/p\/(\d+)$/);
  return (
    <>
      <header className="top">
        <Link to="/">ShopLite</Link>
        <nav>
          <Link to="/products">Products</Link>
          <Link to="/cart">Cart</Link>
        </nav>
      </header>
      <main>
        {path === "/" && <Home />}
        {path === "/products" && <Listing />}
        {product && <ProductPage id={Number(product[1])} />}
        {path === "/cart" && <Cart />}
      </main>
    </>
  );
}

web/src/api.ts:

export const API = import.meta.env.VITE_API ?? "http://localhost:4000";

export type Product = {
  id: number;
  name: string;
  category: string;
  price: number;
  rating: number;
  stock: number;
  image: string;
  description: string;
};

export async function get<T>(path: string): Promise<T> {
  const res = await fetch(API + path);
  if (!res.ok) throw new Error(`${res.status} ${path}`);
  return res.json();
}

export const img = (p: Product) => API + p.image;

web/src/pages/Home.tsx:

import { useEffect, useState } from "react";
import { get, img, type Product } from "../api";
import { Link } from "../App";

export function Home() {
  const [items, setItems] = useState<Product[]>([]);
  useEffect(() => {
    get<{ items: Product[] }>("/api/products?limit=12&sort=rating").then((r) => setItems(r.items));
  }, []);
  return (
    <>
      <section className="hero">
        <h1>Everything you need, delivered fast</h1>
        <p>10,000 products across 10 categories.</p>
      </section>
      <h2>Top rated</h2>
      <div className="grid">
        {items.map((p) => (
          <Link key={p.id} to={`/p/${p.id}`}>
            <article className="card">
              <img src={img(p)} alt={p.name} width={400} height={300} />
              <h3>{p.name}</h3>
              <p>
                ${p.price} · {p.rating}★
              </p>
            </article>
          </Link>
        ))}
      </div>
    </>
  );
}

web/src/pages/Listing.tsx:

import { useEffect, useState } from "react";
import { get, img, type Product } from "../api";
import { Link } from "../App";

export function Listing() {
  const params = new URLSearchParams(location.search);
  const limit = Number(params.get("limit") ?? 60);
  const [data, setData] = useState<{ total: number; items: Product[] }>();
  useEffect(() => {
    get<{ total: number; items: Product[] }>(`/api/products?limit=${limit}`).then(setData);
  }, [limit]);
  if (!data) return <p>Loading…</p>;
  return (
    <>
      <h1>
        Products <small>({data.total})</small>
      </h1>
      <div className="grid">
        {data.items.map((p) => (
          <Link key={p.id} to={`/p/${p.id}`}>
            <article className="card">
              <img src={img(p)} alt={p.name} width={400} height={300} loading="lazy" />
              <h3>{p.name}</h3>
              <p>${p.price}</p>
            </article>
          </Link>
        ))}
      </div>
    </>
  );
}

web/src/pages/ProductPage.tsx:

import { useEffect, useState } from "react";
import { API, get, img, type Product } from "../api";

type Review = { id: number; stars: number; text: string };

export function ProductPage({ id }: { id: number }) {
  const [p, setP] = useState<Product>();
  const [reviews, setReviews] = useState<Review[]>([]);
  const [added, setAdded] = useState(false);
  useEffect(() => {
    get<Product>(`/api/products/${id}`).then(setP);
    get<{ items: Review[] }>(`/api/products/${id}/reviews`).then((r) => setReviews(r.items));
  }, [id]);
  if (!p) return <p>Loading…</p>;
  const add = async () => {
    await fetch(`${API}/api/cart`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ productId: p.id, qty: 1 }),
    });
    setAdded(true);
  };
  return (
    <article className="product">
      <img src={img(p)} alt={p.name} width={400} height={300} />
      <div>
        <h1>{p.name}</h1>
        <p className="price">${p.price}</p>
        <p>{p.description}</p>
        <button onClick={add}>{added ? "Added" : "Add to cart"}</button>
        <h2>Reviews ({reviews.length})</h2>
        <ul>
          {reviews.map((r) => (
            <li key={r.id}>
              {"★".repeat(r.stars)} {r.text}
            </li>
          ))}
        </ul>
      </div>
    </article>
  );
}

web/src/pages/Cart.tsx:

import { useEffect, useState } from "react";
import { get } from "../api";

export function Cart() {
  const [items, setItems] = useState<{ productId: number; qty: number }[]>();
  useEffect(() => {
    get<{ items: { productId: number; qty: number }[] }>("/api/cart").then((r) => setItems(r.items));
  }, []);
  if (!items) return <p>Loading…</p>;
  if (!items.length) return <p>Your cart is empty.</p>;
  return (
    <ul>
      {items.map((i) => (
        <li key={i.productId}>
          Product #{i.productId} × {i.qty}
        </li>
      ))}
    </ul>
  );
}

web/src/styles.css:

* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; color: #1d1d1f; background: #fafafa; }
a { color: inherit; text-decoration: none; }
.top { display: flex; justify-content: space-between; padding: 12px 24px; background: #fff; border-bottom: 1px solid #eee; font-weight: 600; }
.top nav { display: flex; gap: 16px; }
main { max-width: 1100px; margin: 0 auto; padding: 24px; }
.hero { padding: 48px 24px; border-radius: 12px; background: linear-gradient(120deg, #ffcf70, #ff8a5c); }
.hero h1 { margin: 0 0 8px; font-size: 40px; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; }
.card { background: #fff; border-radius: 10px; padding: 10px; border: 1px solid #eee; }
.card img, .product img { width: 100%; height: auto; border-radius: 6px; }
.card h3 { font-size: 15px; margin: 8px 0 4px; }
.card p { margin: 0; color: #555; }
.product { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
.price { font-size: 24px; font-weight: 700; }
button { padding: 10px 18px; border-radius: 8px; border: 0; background: #1d1d1f; color: #fff; font-size: 15px; cursor: pointer; }

web/gen-pages.mjs writes the experiment pages that are too big to type (used in Parsing HTML and CSS and Critical Rendering Path). The build runs it every time:

// Generates the experiment pages in public/x/ that are too big or too repetitive to write by hand.
import { writeFileSync } from "node:fs";

const A = "http://localhost:4000";

// big.html: 10,000 product cards and 2,000 CSS rules, to see what parsing costs.
const cards = [];
for (let i = 1; i <= 10_000; i++)
  cards.push(`<article class="card"><img src="data:," width="200" height="150" alt=""><h3>Product ${i}</h3><p>$${(i % 997) + 0.99}</p><button>Add to cart</button></article>`);
const rules = [];
for (let i = 0; i < 2000; i++) rules.push(`.c${i} .card:hover > h3 + p { color: hsl(${i % 360} 50% 40%); margin: ${i % 7}px; }`);
writeFileSync(
  "public/x/big.html",
  `<!doctype html><html><head><title>10k cards</title><style>${rules.join("\n")}\n.card{display:inline-block;width:210px;margin:4px}</style></head><body><h1>All products</h1>\n${cards.join("\n")}\n</body></html>`,
);

// crp-*.html: the same product page with three different <head>s.
const CSS = `<link rel="stylesheet" href="${A}/asset/app.css?latency=1000&kb=60" />`;
const JS = `src="${A}/asset/app.js?latency=1500&kb=150"`;
const heads = {
  blocking: `${CSS}\n  <script ${JS}></script>`,
  defer: `${CSS}\n  <script defer ${JS}></script>`,
  // practice: app.css starts with an @import of a second, 800 ms stylesheet
  import: `<link rel="stylesheet" href="${A}/asset/app.css?latency=1000&kb=60&css=${encodeURIComponent('@import url("' + A + '/asset/theme.css?latency=800");')}" />\n  <script defer ${JS}></script>`,
  critical: `<style>/* critical CSS: only what the first screen needs */ body{font-family:system-ui;margin:0} .hero{padding:32px;background:#ffcf70}</style>
  <link rel="stylesheet" href="${A}/asset/app.css?latency=1000&kb=60" media="print" onload="this.media='all'" />
  <script defer ${JS}></script>`,
};
for (const [name, head] of Object.entries(heads))
  writeFileSync(
    `public/x/crp-${name}.html`,
    `<!doctype html>
<html>
<head>
  <title>crp ${name}</title>
  ${head}
</head>
<body>
  <section class="hero"><h1>Nova phone Pro 7</h1><p>$499 · 4.6★</p></section>
  <p>Free delivery in Dhaka. 30-day returns.</p>
</body>
</html>
`,
  );
console.log("pages written");

The measurement tools

tools/package.json. PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install installs it without downloading Playwright's own browsers; the scripts use your installed Chrome (set CHROME=/path/to/chrome if it isn't at /usr/bin/google-chrome):

{
  "name": "shoplite-tools",
  "private": true,
  "type": "module",
  "dependencies": { "lighthouse": "13.6.0", "playwright": "1.64.1" }
}

tools/lib.mjs, shared by every script. PROFILES.slow4g is the throttling Lighthouse uses for mobile, applied the way DevTools applies it:

// Shared helpers for the lab's measurement scripts: open Chrome with real network and CPU
// throttling, read the browser's own timing APIs, and boil a performance trace down to text.
import { chromium } from "playwright";

export const WEB = process.env.WEB ?? "http://localhost:5173";
export const API = process.env.API ?? "http://localhost:4000";

// The same "slow 4G" numbers Lighthouse uses for mobile, applied the DevTools way: every
// request waits 562.5 ms, downloads at 1.47 Mbps, and the CPU runs 4x slower.
export const PROFILES = {
  none: null,
  slow4g: { latency: 562.5, down: (1.6 * 1024 * 0.9 * 1024) / 8, up: (750 * 0.9 * 1024) / 8, cpu: 4 },
};

export async function open({ profile = "none", cpu, viewport = { width: 1280, height: 800 } } = {}) {
  const browser = await chromium.launch({ executablePath: process.env.CHROME ?? "/usr/bin/google-chrome" });
  const context = await browser.newContext({ viewport });
  const page = await context.newPage();
  const cdp = await context.newCDPSession(page);
  const p = PROFILES[profile];
  await cdp.send("Network.enable");
  await cdp.send("Network.setCacheDisabled", { cacheDisabled: false });
  if (p) {
    await cdp.send("Network.emulateNetworkConditions", {
      offline: false,
      latency: p.latency,
      downloadThroughput: p.down,
      uploadThroughput: p.up,
    });
  }
  const rate = cpu ?? p?.cpu ?? 1;
  if (rate > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate });
  page.on("pageerror", (e) => console.error("pageerror:", e.message));
  return { browser, context, page, cdp };
}

/** Navigation Timing, paint timings and LCP, in ms from the start of navigation. */
export async function pageTimings(page) {
  return page.evaluate(
    () =>
      new Promise((resolve) => {
        let lcp = 0;
        new PerformanceObserver((l) => {
          for (const e of l.getEntries()) lcp = e.startTime;
        }).observe({ type: "largest-contentful-paint", buffered: true });
        setTimeout(() => {
          const n = performance.getEntriesByType("navigation")[0];
          const paint = Object.fromEntries(performance.getEntriesByType("paint").map((e) => [e.name, e.startTime]));
          resolve({
            dns: n.domainLookupEnd - n.domainLookupStart,
            connect: n.connectEnd - n.connectStart,
            tls: n.secureConnectionStart ? n.connectEnd - n.secureConnectionStart : 0,
            requestStart: n.requestStart,
            ttfb: n.responseStart,
            responseEnd: n.responseEnd,
            domInteractive: n.domInteractive,
            dcl: n.domContentLoadedEventEnd,
            load: n.loadEventEnd,
            fp: paint["first-paint"],
            fcp: paint["first-contentful-paint"],
            lcp,
            htmlBytes: n.transferSize,
          });
        }, 300);
      }),
  );
}

/** Every resource the page fetched: when it started, when it finished, how many bytes. */
export async function resources(page) {
  return page.evaluate(() =>
    performance.getEntriesByType("resource").map((r) => ({
      name: r.name.replace(location.origin, "").replace(/^https?:\/\/localhost:\d+/, ""),
      type: r.initiatorType,
      start: r.startTime,
      end: r.responseEnd,
      bytes: r.transferSize,
      blocking: r.renderBlockingStatus,
    })),
  );
}

/** Text waterfall: one row per request, bars on a shared time axis. */
export function waterfall(rows, width = 40) {
  const max = Math.max(...rows.map((r) => r.end));
  const scale = width / max;
  return rows
    .map((r) => {
      const a = Math.round(r.start * scale);
      const b = Math.max(Math.round(r.end * scale), a + 1);
      const bar = " ".repeat(a) + "#".repeat(b - a) + " ".repeat(Math.max(width - b, 0));
      return `${r.label.padEnd(26).slice(0, 26)} |${bar}| ${ms(r.start).padStart(7)} -> ${ms(r.end).padStart(7)}`;
    })
    .join("\n");
}

export const ms = (x) => (x == null ? "-" : `${Math.round(x)} ms`);
export const kb = (x) => `${(x / 1024).toFixed(1)} KB`;

/** Record a Chrome trace around fn() and return its events. */
export async function trace(browser, page, fn) {
  await browser.startTracing(page, {
    categories: ["devtools.timeline", "disabled-by-default-devtools.timeline", "blink.user_timing", "v8.execute"],
  });
  await fn();
  const buf = await browser.stopTracing();
  return JSON.parse(buf.toString()).traceEvents;
}

/** Main-thread time per event name (complete events only, top-level per name). */
export function mainThreadSummary(events, names) {
  const main = events.find((e) => e.name === "thread_name" && e.args?.name === "CrRendererMain");
  const mine = events.filter((e) => main && e.pid === main.pid && e.tid === main.tid && e.ph === "X");
  const out = {};
  for (const n of names) {
    const list = mine.filter((e) => e.name === n);
    out[n] = { count: list.length, ms: list.reduce((s, e) => s + (e.dur ?? 0), 0) / 1000 };
  }
  return out;
}

tools/ws-check.mjs listens to the real-time server both ways:

// node ws-check.mjs: listen to order 7's live status over WebSocket and SSE for 5 seconds.
const RT = process.env.RT ?? "localhost:4001";
const t0 = Date.now();
const at = () => `${String(Date.now() - t0).padStart(5)} ms`;

const ws = new WebSocket(`ws://${RT}/ws?order=7`);
ws.onmessage = (e) => console.log(`${at()}  ws   ${e.data}`);

const res = await fetch(`http://${RT}/sse?order=7`);
const reader = res.body.getReader();
const dec = new TextDecoder();
setTimeout(() => (ws.close(), reader.cancel()), 5000);
for (;;) {
  const { value, done } = await reader.read().catch(() => ({ done: true }));
  if (done) break;
  for (const line of dec.decode(value).split("\n")) if (line.startsWith("data: ")) console.log(`${at()}  sse  ${line.slice(6)}`);
}

Start and check it

Start the lab and wait until every container reports healthy:

cd ../lab
docker compose down >/dev/null 2>&1
start=$(date +%s)
docker compose up -d --wait >/dev/null 2>&1
echo "ready in $(( $(date +%s) - start )) s"
docker compose ps --format "table {{.Service}}\t{{.Status}}\t{{.Ports}}"
docker compose logs api | grep -E "rows|listening" | sed 's/^api-1  | //'
ready in 15 s
SERVICE   STATUS                    PORTS
api       Up 14 seconds (healthy)   0.0.0.0:4000->4000/tcp, [::]:4000->4000/tcp
rt        Up 13 seconds (healthy)   0.0.0.0:4001->4001/tcp, [::]:4001->4001/tcp
web       Up 10 seconds (healthy)   0.0.0.0:5173->5173/tcp, [::]:5173->5173/tcp
products   10000 rows
reviews    50000 rows
orders      2000 rows
api listening on :4000

Then poke every part of it:

cd ../lab
echo '$ curl localhost:4000/health'
curl -s localhost:4000/health; echo
echo
echo '$ curl "localhost:4000/api/products?limit=2&sort=rating"'
curl -s "localhost:4000/api/products?limit=2&sort=rating" | node -e 'const r=JSON.parse(require("fs").readFileSync(0));console.log(JSON.stringify({total:r.total,items:r.items.map(({description,...p})=>p)},null,1))'
echo
echo '# the latency knob: the same request, held for 800 ms'
curl -s -o /dev/null -w "%{http_code} in %{time_total}s\n" "localhost:4000/api/products/42"
curl -s -o /dev/null -w "%{http_code} in %{time_total}s\n" "localhost:4000/api/products/42?latency=800"
echo
echo '# the error knob: 10 requests with error=0.5'
for i in 1 2 3 4 5 6 7 8 9 10; do curl -s -o /dev/null -w "%{http_code} " "localhost:4000/api/products/42?error=0.5"; done; echo
echo
echo '# per-route config: every /api/search request now waits 300 ms'
curl -s -X PUT localhost:4000/__config -H 'content-type: application/json' -d '{"/api/search": {"latency": 300}}'; echo
curl -s -o /dev/null -w "search: %{http_code} in %{time_total}s\n" "localhost:4000/api/search?q=nova"
curl -s -X PUT localhost:4000/__config -H 'content-type: application/json' -d '{"/api/search": {}}' >/dev/null
echo
echo '$ node tools/ws-check.mjs'
node tools/ws-check.mjs
$ curl localhost:4000/health
{"ok":true,"products":10000,"reviews":50000,"orders":2000}

$ curl "localhost:4000/api/products?limit=2&sort=rating"
{
 "total": 10000,
 "items": [
  {
   "id": 10,
   "name": "Orbit toy One 10",
   "category": "toys",
   "price": 183.96,
   "rating": 5,
   "stock": 26,
   "image": "/img/10.svg"
  },
  {
   "id": 128,
   "name": "Kite book Lite 128",
   "category": "books",
   "price": 530.15,
   "rating": 5,
   "stock": 176,
   "image": "/img/128.svg"
  }
 ]
}

# the latency knob: the same request, held for 800 ms
200 in 0.003946s
200 in 0.803337s

# the error knob: 10 requests with error=0.5
503 200 200 200 200 200 503 200 200 503

# per-route config: every /api/search request now waits 300 ms
{"/api/search":{"latency":300}}
search: 200 in 0.308077s

$ node tools/ws-check.mjs
   69 ms  ws   {"order":7,"status":"placed","seq":0}
   72 ms  sse  {"order":7,"status":"placed","seq":0}
 2064 ms  ws   {"order":7,"status":"packed","seq":1}
 2066 ms  sse  {"order":7,"status":"packed","seq":1}
 4066 ms  ws   {"order":7,"status":"shipped","seq":2}
 4067 ms  sse  {"order":7,"status":"shipped","seq":2}

Finally, open http://localhost:5173 in your browser: the home page with 12 top-rated products, /products with 60 cards, /p/42 for a product with its reviews, and /cart.

Reading the output

  • "ready in 15 s" on our machine with the node:22-slim image already pulled. npm install runs inside each container on every start, then the API seeds its data and the web app builds. The first start on a slow connection takes longer while Docker pulls the image.
  • /health confirms the seed: 10,000 products, 50,000 reviews, 2,000 orders. Your counts should match exactly.
  • Top-rated products are 10 and 128, the same for everyone, because the seed is fixed.
  • The latency knob works: the same product took 4 ms without it and 803 ms with ?latency=800. Every lesson uses this knob (or the slow4g profile) instead of guessing what a slow network does.
  • The error knob is random: with error=0.5 about half the requests return 503. In this run 3 of 10 failed; run it again and you'll get a different mix. Part 5 uses this to test retries.
  • Per-route config makes one endpoint slow without touching the others (PUT /__config), and {} resets it.
  • The real-time server sends order 7's status every 2 seconds over both transports. The WebSocket and SSE messages arrive within a few milliseconds of each other: on a local machine the two are equally fast. Part 8 compares them on a bad network.

Lessons add their experiment pages to web/public/x/ and their scripts to tools/. After adding a page, run docker compose restart web: the container rebuilds and serves it in about 10 seconds.

Troubleshooting

  • port is already allocated: something else uses 4000, 4001 or 5173. Stop it, or change the left side of ports: (and VITE_API if you move the API).
  • Code is nested too deeply during the web build: you're on an Alpine image. Use node:22-slim.
  • EACCES writing node_modules: the folder was created by root earlier. sudo chown -R $USER shoplite/ once, then start again.
  • browserType.launch: Failed to launch in tools/: Chrome isn't at /usr/bin/google-chrome. Set CHROME= to its path.
  • Numbers differ from the lessons: expected for timings. If the shape differs (a page that should block doesn't), check that no browser extension or proxy is involved, and that you're testing localhost:5173 (the production build), not a dev server.
  • Low on RAM: docker compose stop when you're not using the lab; the data and builds stay in the folder.

Key takeaway

One docker compose up gives you the app, a mock API whose speed and failures you control, and a real-time server; tools/ drives real Chrome against them. Every number in this course comes from this lab, and you can reproduce each one.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +15 XP.

Go Pro to earn XP →