Part 01 · How the Browser Works
Lab Setup: ShopLite
পুরো course এর জন্য একটাই docker-compose lab: ShopLite React app, latency, error আর payload size বদলানো যায় এমন mock API, seed করা 10k product, আর একটা real-time server।
⏱ 12 মিনিট · Station 9 / 125
What you'll have at the end
একটা folder, shoplite/, যেটা এক command এ এই course এ যা যা measure করা হয় সবকিছু চালু করে:
| Service | Port | এটা কী |
|---|---|---|
web | 5173 | ShopLite: একটা Vite + React + TypeScript storefront, production build হিসেবে serve করা। Lesson গুলোর experiment page ও এখানে, /x/ এর নিচে। |
api | 4000 | Express এর উপর একটা mock API: 10,000 product, 50,000 review আর 2,000 order। প্রতিটা route কে slow করা যায়, fail করানো যায়, বা বাড়তি byte দিয়ে ভারী করা যায়। |
rt | 4001 | একটা real-time server: WebSocket (/ws) আর Server-Sent Events (/sse) দিয়ে live order status। |
tools/ | Node script, যেগুলো network আর CPU throttle করে real Chrome চালায় (Playwright দিয়ে), আর browser যা measure করল সেটা print করে। |
Data আসে একটা fixed seed ওয়ালা random generator থেকে। তাই তোমার product, price আর rating আমাদের সাথে হুবহু মিলবে। Timing মিলবে না, কারণ তোমার machine আলাদা। আমাদেরটা Intel i3-10110U (4 thread), 7 GB RAM, Ubuntu 26.04, Docker 29.8, Chrome 151।
লাগবে Compose সহ Docker, host এ Node.js 22.19 বা তার নতুন (tools/ এর জন্য), Google Chrome, আর lab চলার সময় প্রায় 600 MB free RAM।
The files
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 }
এটার তিনটা জিনিস জেনে রাখো:
node:22-slim,node:22-alpineনা. Alpine এ React parse করার সময় Vite এর build fail করেছিলCode is nested too deeplyদিয়ে। Debian-basedslimimage এ build ঠিকঠাক হয়।webproduction build serve করে (vite build+vite preview), dev server না। Dev server শত শত unbundled module পাঠায়। User রা এটা download করে না, আর এটা দিয়ে measure করলে এই course এর প্রতিটা number ভুল হতো।user: node, যাতে container গুলো তোমার folder এ যে file লেখে (node_modules,dist,data) সেগুলো তোমার user এর হয়, 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 একটা fixed seed দিয়ে data generate করে:
// 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। উপরের দিকের middleware টাই আসল অংশ: কোনো route run হওয়ার আগেই সে query string থেকে, বা per-route config থেকে latency, error আর padKb read করে:
// 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, একটা ছোট্ট router সহ, যাতে app এর React ছাড়া আর কোনো dependency না লাগে:
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 সেই experiment page গুলো লেখে যেগুলো হাতে type করার জন্য অনেক বড় (Parsing HTML and CSS আর Critical Rendering Path এ use হয়)। প্রতিবার build এর সময় এটা run হয়:
// 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 দিলে Playwright এর নিজের browser download না করেই install হয়। Script গুলো তোমার install করা Chrome use করে (/usr/bin/google-chrome এ না থাকলে CHROME=/path/to/chrome set করো):
{
"name": "shoplite-tools",
"private": true,
"type": "module",
"dependencies": { "lighthouse": "13.6.0", "playwright": "1.64.1" }
}
tools/lib.mjs, সব script এটা share করে। PROFILES.slow4g হলো সেই throttling যেটা Lighthouse mobile এর জন্য use করে, DevTools যেভাবে apply করে সেভাবে:
// 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 real-time server কে দুইভাবেই শোনে:
// 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
Lab চালু করো, আর সব container healthy না হওয়া পর্যন্ত wait করো:
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
তারপর এর প্রতিটা অংশ একটু খুঁচিয়ে দেখো:
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}
শেষে browser এ http://localhost:5173 খোলো: home page এ 12 টা top-rated product, /products এ 60 টা card, /p/42 এ একটা product আর তার review, আর /cart।
Reading the output
- "ready in 15 s", আমাদের machine এ,
node:22-slimimage আগে থেকে pull করা অবস্থায়। প্রতিবার start এ প্রতিটা container এর ভেতরেnpm installচলে, তারপর API data seed করে আর web app build হয়। Slow connection এ প্রথমবার Docker image pull করার জন্য বেশি সময় লাগবে। /healthseed টা confirm করে: 10,000 product, 50,000 review, 2,000 order। তোমার count হুবহু মিলতে হবে।- Top-rated product হলো 10 আর 128, সবার জন্য একই, কারণ seed fixed।
- Latency knob কাজ করছে: একই product এ knob ছাড়া লেগেছে 4 ms,
?latency=800দিয়ে 803 ms। Slow network কী করে সেটা আন্দাজ না করে, প্রতিটা lesson এই knob (বাslow4gprofile) use করে। - Error knob random:
error=0.5দিলে মোটামুটি অর্ধেক request 503 return করে। এই run এ 10 টার মধ্যে 3 টা fail করেছে। আবার run করলে অন্যরকম মিশ্রণ পাবে। Part 5 এ এটা দিয়ে retry test করা হবে। - Per-route config দিয়ে বাকিগুলোতে হাত না দিয়ে একটা endpoint slow করা যায় (
PUT /__config), আর{}দিলে reset হয়। - Real-time server দুই transport দিয়েই প্রতি 2 second এ order 7 এর status পাঠায়। WebSocket আর SSE এর message আসে একে অপরের কয়েক millisecond এর মধ্যে: local machine এ দুইটা সমান fast। খারাপ network এ দুইটার তুলনা Part 8 এ।
Lesson গুলো তাদের experiment page যোগ করে web/public/x/ এ, আর script যোগ করে tools/ এ। Page যোগ করার পর docker compose restart web run করো: container আবার build করে প্রায় 10 second এ serve করবে।
Troubleshooting
port is already allocated: 4000, 4001 বা 5173 অন্য কেউ use করছে। সেটা বন্ধ করো, অথবাports:এর বাম পাশ বদলাও (API সরালেVITE_APIও)।- Web build এ
Code is nested too deeply: তুমি Alpine image এ আছো।node:22-slimuse করো। node_modulesলিখতে গিয়েEACCES: folder টা আগে root বানিয়েছিল। একবারsudo chown -R $USER shoplite/চালাও, তারপর আবার start করো।tools/এbrowserType.launch: Failed to launch: Chrome/usr/bin/google-chromeএ নেই।CHROME=এ তার path set করো।- Lesson এর সাথে number মিলছে না: timing এর ক্ষেত্রে এটাই স্বাভাবিক। কিন্তু shape যদি না মেলে (যে page block করার কথা সেটা করছে না), check করো মাঝে কোনো browser extension বা proxy আছে কিনা, আর তুমি
localhost:5173(production build) test করছ কিনা, dev server না। - RAM কম: lab use না করলে
docker compose stopদাও। Data আর build folder এ থেকে যায়।
Key takeaway
একটা docker compose up দেয় app, এমন একটা mock API যার speed আর failure তোমার হাতে, আর একটা real-time server। tools/ এগুলোর উপর real Chrome চালায়। এই course এর প্রতিটা number এই lab থেকে আসা, আর তুমি প্রতিটা নিজে reproduce করতে পারবে।
Station stamp
Chapter শেষ করো
পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +15 XP পেতে।
Pro নিয়ে XP পাও →