Part 01 · Thinking About Scale

Scaling Lab Setup

Docker ComposeGoPostgreSQLk6

Docker Compose দিয়ে নিজের laptop এ shop টা চালাও: একটা Go API, PostgreSQL, আর load test করার জন্য k6। এরপরের সব lab এখান থেকেই বড় হবে।

⏱ 18 মিনিট · Station 1 / 93

What you'll have at the end

একটা folder, syslab/, যেটা এক command এ তোমার laptop এ পুরো shop চালিয়ে দেয়। এই course এর সব lab এখান থেকেই শুরু হবে, আর আস্তে আস্তে বড় হবে: আরও app server, load balancer, Redis, queue।

Serviceতোমার machine এ portএটা কী
api58080Shop এর backend: Go তে লেখা ছোট একটা service। এতে product page, login, cart আছে, আর কিছু endpoint আছে যেগুলো দিয়ে lab এ ইচ্ছা করে problem তৈরি করা হয়
db55432PostgreSQL 17, এতে 20,000 product, 1,000,000 review আর 100,000 user
redis56379Redis 7। আজ কাজে লাগছে না, caching আর session এর lesson এ চালু হবে
k6(চলে, তারপর বন্ধ হয়)Load generator। Lab এর network এর ভেতরে চলে আর ছোট একটা summary print করে

Data টা SQL দিয়ে বানানো, random না। তাই তোমার product, price আর rating আমাদের সাথে হুবহু মিলবে। Timing মিলবে না, কারণ তোমার machine আলাদা। আমাদেরটা Intel i3-10110U laptop (2 core, 4 thread), 7 GB RAM, Ubuntu 26.04, Docker 29.8।

api আর db container প্রত্যেকে নিজের একটা CPU thread পায় (cpuset), আর k6 পায় বাকি দুইটা। এটা ইচ্ছা করে। 8 thread এর laptop এমন bottleneck লুকিয়ে ফেলতে পারে, যেটা একই size এর আসল server এ ঠিকই লাগতো। Pin করলে breaking point গুলো পরিষ্কার দেখা যায়, আর একটা ছোট cloud server যা করতো তার কাছাকাছি হয়।

লাগবে Compose সহ Docker, আর lab চলার সময় প্রায় 1 GB free RAM। Machine এ Go লাগবে না, image নিজেই binary build করে নেয়।

The files

syslab/
  docker-compose.yml
  k6.sh                 runs a k6 script inside the lab network
  db/seed.sql           tables and data, loaded the first time db starts
  shop/                 the Go service
    Dockerfile  go.mod  go.sum
    main.go  products.go  cache.go  session.go  ops.go
  k6/                   load test scripts (more are added lesson by lesson)
    summary.js  product.js

docker-compose.yml:

# The Systems Engineering lab: the shop API, PostgreSQL, and everything later lessons add.
#   docker compose up -d --build        the single-server shop (lesson 1)
#   docker compose --profile lb up -d   three instances behind Nginx (Part 2)
#   docker compose --profile obs up -d  Prometheus + Grafana (Reliability course)
name: syslab

x-shop: &shop
  build: ./shop
  image: syslab-shop
  restart: unless-stopped
  depends_on:
    db: { condition: service_healthy }
  environment: &shop-env
    DATABASE_URL: postgres://shop:shop@db:5432/shop
    DB_MAX_CONNS: 10
    SESSIONS: ${SESSIONS:-memory}
    CACHE: ${CACHE:-off}
    CACHE_TTL: ${CACHE_TTL:-60}
    INVALIDATE: ${INVALIDATE:-1}
    COALESCE: ${COALESCE:-0}
    FAIL_OPEN: ${FAIL_OPEN:-0}
    LOCAL_CACHE_MS: ${LOCAL_CACHE_MS:-0}
    FLUSH_MS: ${FLUSH_MS:-5000}
    WORKERS: ${WORKERS:-0}
    MAX_WAIT_MS: ${MAX_WAIT_MS:-0}
    HIST_BUCKETS: ${HIST_BUCKETS:-default}
  cpuset: "3"        # one CPU core of its own (api1..api3 override this in Part 2)
  mem_limit: 256m

services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: shop
      POSTGRES_DB: shop
    command: ["postgres", "-c", "shared_buffers=128MB", "-c", "shared_preload_libraries=pg_stat_statements"]
    volumes: ["./db/seed.sql:/docker-entrypoint-initdb.d/seed.sql:ro"]
    ports: ["55432:5432"]
    cpuset: "2"        # one CPU core of its own
    mem_limit: 512m
    healthcheck:
      # TCP only opens after the seed script has finished (during init Postgres listens on a socket only).
      test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "shop", "-d", "shop"]
      interval: 2s
      retries: 60

  redis:
    image: redis:7-alpine
    command: ["redis-server", "--save", "", "--appendonly", "no"]
    ports: ["56379:6379"]
    mem_limit: 128m

  # The single server. Later lessons stop it and start api1..api3 behind Nginx instead.
  api:
    <<: *shop
    environment:
      <<: *shop-env
      INSTANCE: api
    ports: ["58080:8080"]

  # Part 2: three copies of the shop, each on its own CPU thread, behind a load balancer.
  api1:
    <<: *shop
    profiles: ["lb"]
    cpuset: "1"
    environment: { <<: *shop-env, INSTANCE: api1 }
  api2:
    <<: *shop
    profiles: ["lb"]
    cpuset: "2"
    environment: { <<: *shop-env, INSTANCE: api2 }
  api3:
    <<: *shop
    profiles: ["lb"]
    cpuset: "3"
    environment: { <<: *shop-env, INSTANCE: api3 }

  lb:
    image: nginx:1.29-alpine
    profiles: ["lb"]
    volumes: ["./nginx/${LB_CONF:-round-robin}.conf:/etc/nginx/nginx.conf:ro"]
    ports: ["58081:80"]
    depends_on: [api1, api2, api3]

  # Reliability course: metrics. Prometheus scrapes every shop copy; Grafana shows the RED dashboard.
  prometheus:
    image: prom/prometheus:v3.0.0
    profiles: ["obs"]
    volumes: ["./obs/prometheus.yml:/etc/prometheus/prometheus.yml:ro"]
    ports: ["59090:9090"]
    mem_limit: 256m

  grafana:
    image: grafana/grafana:11.3.0
    profiles: ["obs"]
    environment:
      GF_AUTH_ANONYMOUS_ENABLED: "true"
      GF_AUTH_ANONYMOUS_ORG_ROLE: Admin
      GF_AUTH_DISABLE_LOGIN_FORM: "true"
    volumes:
      - ./obs/grafana/provisioning:/etc/grafana/provisioning:ro
      - ./obs/grafana/dashboards:/var/lib/grafana/dashboards:ro
    ports: ["53000:3000"]
    mem_limit: 256m

  haproxy:
    image: haproxy:3.2-alpine
    profiles: ["lb"]
    volumes: ["./haproxy/${HAPROXY_CONF:-haproxy}.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro"]
    ports: ["58082:80"]
    depends_on: [api1, api2, api3]

তিনটা জিনিস খেয়াল করো:

  • api আর db তে cpuset। তোমার laptop এ যত CPU ই থাকুক, প্রত্যেকে একটা CPU thread এ চলে (3 আর 2 নম্বর), এর বেশি না। প্রথমে আমরা cpus: 1.0 দিয়ে চেষ্টা করেছিলাম, যেটা সব thread মিলিয়ে এক CPU পরিমাণ সময় দেয়। Load এর সময় PostgreSQL একসাথে কয়েকটা thread use করলো, প্রতিটা 100 ms period এর শুরুতেই quota শেষ করে ফেললো, আর বাকি সময়টা freeze হয়ে থাকলো: throughput নেমে গেলো pin করা একটা thread এর চার ভাগের এক ভাগে। এই throttling production এর একটা আসল problem (Reliability course এ Kubernetes CPU limit এর সাথে আবার দেখা হবে), কিন্তু এখানে এটা সব measurement ঘোলা করে দিতো। তোমার machine এ 4 টার কম thread থাকলে number গুলো বদলে নাও, অথবা line দুইটা মুছে দাও।
  • Healthcheck এ -h 127.0.0.1। Seed script চলার সময় PostgreSQL শুধু একটা Unix socket এ listen করে। সাধারণ pg_isready data তৈরি হওয়ার আগেই "ready" বলে দিয়েছিল, আর API খালি table নিয়ে start হয়ে গিয়েছিল। TCP দিয়ে check করলে seed শেষ না হওয়া পর্যন্ত wait করে।
  • api1, api2, api3 আর lb আছে lb profile এর পেছনে, তাই এখন start হয় না। Part 2 এ এগুলো চালু হবে।

Shop দুই ধাপে build হয়: Go image এ compile, তারপর 13 MB এর Alpine image এ run।

# Build the Go binary in one image, run it in a tiny one.
FROM golang:1.26-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
RUN CGO_ENABLED=0 go build -o /shop .

FROM alpine:3.20
COPY --from=build /shop /shop
EXPOSE 8080
ENTRYPOINT ["/shop"]

এক lesson থেকে আরেক lesson এ যা যা বদলায়, সবই একটা environment variable (CACHE, SESSIONS, WORKERS এরকম, main.go তে read হয়)। তাই একই binary দিয়েই সব role চালানো যায়।

The product page

বেশিরভাগ lab এই request টাই measure করে। একটা page এর জন্য তিনটা query লাগে: product টা, তার rating, আর একই category এর আটটা best seller।

package main

import (
	"context"
	"encoding/json"
	"net/http"
	"strconv"
)

type related struct {
	ID    int     `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

// page is everything the product page shows. Building it takes three queries.
type page struct {
	ID       int       `json:"id"`
	Name     string    `json:"name"`
	Category int       `json:"category"`
	Price    float64   `json:"price"`
	Stock    int       `json:"stock"`
	Rating   float64   `json:"rating"`
	Reviews  int       `json:"reviews"`
	Related  []related `json:"related"`
}

// loadPage reads one product page straight from PostgreSQL.
func (a *app) loadPage(ctx context.Context, id int) (*page, error) {
	a.stats.dbPageLoads.Add(1)
	p := &page{ID: id}
	err := a.db.QueryRow(ctx,
		`SELECT name, category, price, stock FROM products WHERE id = $1`, id,
	).Scan(&p.Name, &p.Category, &p.Price, &p.Stock)
	if err != nil {
		return nil, err
	}
	err = a.db.QueryRow(ctx,
		`SELECT coalesce(avg(rating), 0)::float8, count(*) FROM reviews WHERE product_id = $1`, id,
	).Scan(&p.Rating, &p.Reviews)
	if err != nil {
		return nil, err
	}
	// "Customers also bought": the best sellers in the same category.
	rows, err := a.db.Query(ctx,
		`SELECT id, name, price FROM products
		  WHERE category = $1 AND id <> $2
		  ORDER BY sold DESC LIMIT 8`, p.Category, id)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var r related
		if err := rows.Scan(&r.ID, &r.Name, &r.Price); err != nil {
			return nil, err
		}
		p.Related = append(p.Related, r)
	}
	return p, rows.Err()
}

func (a *app) productPage(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		http.Error(w, "bad id", http.StatusBadRequest)
		return
	}
	p, hit, err := a.cache.get(r.Context(), id)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if hit {
		w.Header().Set("X-Cache", "hit")
	} else {
		w.Header().Set("X-Cache", "miss")
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(p)
}

func (a *app) setPrice(w http.ResponseWriter, r *http.Request) {
	id, err1 := strconv.Atoi(r.PathValue("id"))
	price, err2 := strconv.ParseFloat(r.URL.Query().Get("value"), 64)
	if err1 != nil || err2 != nil {
		http.Error(w, "need /products/{id}/price?value=N", http.StatusBadRequest)
		return
	}
	if err := a.cache.setPrice(r.Context(), id, price); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

তৃতীয় query টার জন্য category তে কোনো index নেই। তাই best seller খুঁজতে PostgreSQL কে 20,000 product scan করতে হয়। এটা ইচ্ছা করে রাখা। এতে database ই সবার আগে CPU শেষ করে ফেলে, ঠিক আসল shop এর মতো, যেখানে সবচেয়ে বেশি visit হওয়া page এ একটা ভারী query লুকিয়ে থাকে। Fix করার আগে আমরা measure করে সেটা খুঁজে বের করবো।

The data

-- The shop's data. Deterministic: every learner gets the same products and reviews.
CREATE TABLE products (
  id       int PRIMARY KEY,
  name     text NOT NULL,
  category int NOT NULL,          -- 50 categories
  price    numeric(10,2) NOT NULL,
  stock    int NOT NULL,
  sold     int NOT NULL           -- units sold so far, for "customers also bought"
);
INSERT INTO products
SELECT g, 'Product ' || g, g % 50, 100 + (g * 7919) % 9900 + ((g * 13) % 100) / 100.0, (g * 31) % 500, (g * 104729) % 10000
FROM generate_series(1, 20000) g;

CREATE TABLE reviews (
  id         bigint PRIMARY KEY,
  product_id int NOT NULL REFERENCES products(id),
  rating     int NOT NULL
);
INSERT INTO reviews
SELECT g, (g % 20000) + 1, 1 + ((g / 20000) * 3 + g) % 5
FROM generate_series(1, 1000000) g;
CREATE INDEX reviews_product_id ON reviews (product_id);

CREATE TABLE users (id int PRIMARY KEY, name text NOT NULL);
INSERT INTO users SELECT g, 'user' || g FROM generate_series(1, 100000) g;

CREATE TABLE orders (
  id         bigserial PRIMARY KEY,
  user_id    int NOT NULL REFERENCES users(id),
  total      numeric(10,2) NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

ANALYZE;

k6 and its summary

k6.sh official k6 image টা lab এর Docker network এ চালায়, তাই script গুলো সরাসরি http://api:8080 call করতে পারে:

#!/bin/sh
# Run a k6 script from ./k6 inside the lab's network, so "http://api:8080" works.
#   ./k6.sh product.js -e RATE=100 -e DURATION=30s
script=$1; shift
docker run --rm -i --network syslab_default --cpuset-cpus "${K6_CPUS:-0,1}" -v "$(pwd)/k6:/scripts:ro" \
  grafana/k6:0.54.0 run --quiet --summary-trend-stats "avg,med,p(95),p(99),max" "$@" "/scripts/$script"

k6/product.js একটা fixed rate এ random product page চায়, second এ RATE টা request:

// Product pages for random products, at a fixed arrival rate (requests per second).
import http from "k6/http";
import { summary } from "./summary.js";

const TARGET = __ENV.TARGET || "http://api:8080";

export const options = {
  scenarios: {
    pages: {
      executor: "constant-arrival-rate",
      rate: Number(__ENV.RATE || 50),
      timeUnit: "1s",
      duration: __ENV.DURATION || "30s",
      preAllocatedVUs: 50,
      maxVUs: Number(__ENV.MAX_VUS || 500),
    },
  },
  // -e P95=50 makes the run fail (exit code 99) if p95 latency is 50 ms or more.
  thresholds: __ENV.P95 ? { http_req_duration: [`p(95)<${__ENV.P95}`] } : {},
};

export default function () {
  // -e SKEW=4 makes a few products far more popular than the rest, like real shops:
  // the top 1% of products then get about 32% of the views, the top 10% about 56%.
  const skew = Number(__ENV.SKEW || 1);
  const id = 1 + Math.floor(Math.pow(Math.random(), skew) * Number(__ENV.PRODUCTS || 20000));
  // -e PATH_TPL="/work?ms=5" sends the load to another endpoint ({id} is replaced).
  const path = (__ENV.PATH_TPL || "/products/{id}").replace("{id}", id);
  http.get(TARGET + path, { timeout: __ENV.TIMEOUT || "10s" });
}

export const handleSummary = summary;

k6/summary.js k6 এর লম্বা default report এর বদলে চার line দেখায়:

// A short, stable summary printed at the end of every run (replaces k6's long default one).
export function summary(data) {
  const m = data.metrics;
  const d = m.http_req_duration.values;
  const ms = (v) => (v < 10 ? v.toFixed(1) : Math.round(v)) + " ms";
  const lines = [
    `requests   ${m.http_reqs.values.count} (${m.http_reqs.values.rate.toFixed(1)}/s)`,
    `failed     ${(m.http_req_failed.values.rate * 100).toFixed(2)}%`,
    `latency    avg ${ms(d.avg)}  p50 ${ms(d.med)}  p95 ${ms(d["p(95)"])}  p99 ${ms(d["p(99)"])}  max ${ms(d.max)}`,
  ];
  if (__ENV.LINE) {
    // One row for ramp tables: target rate, what got through, latency, errors.
    const row = [
      String(__ENV.RATE || __ENV.VUS).padStart(5),
      m.http_reqs.values.rate.toFixed(0).padStart(8),
      ms(d.med).padStart(9),
      ms(d["p(95)"]).padStart(9),
      ms(d["p(99)"]).padStart(9),
      ((m.http_req_failed.values.rate * 100).toFixed(1) + "%").padStart(7),
      String(m.dropped_iterations ? m.dropped_iterations.values.count : 0).padStart(8),
    ];
    return { stdout: row.join("") + "\n" };
  }
  if (m.dropped_iterations) lines.push(`dropped    ${m.dropped_iterations.values.count} (k6 could not start them in time)`);
  if (m.vus_max) lines.push(`vus max    ${m.vus_max.values.value}`);
  return { stdout: lines.join("\n") + "\n" };
}

Start it and check it

syslab/ folder থেকে:

docker compose up -d --build

প্রথমবার image download হয় আর shop compile হয়। আমাদের machine এ শূন্য থেকে ready হতে লাগলো:

Container syslab-db-1 Started
Container syslab-redis-1 Started
Container syslab-db-1 Healthy
Container syslab-api-1 Started
ready after 27 s
api	Up Less than a second
db	Up 25 seconds (healthy)
redis	Up 25 seconds

তারপর প্রতিটা অংশ check করো:

$ curl -s localhost:58080/health
ok api

$ curl -s localhost:58080/products/42
{"id": 42, "name": "Product 42", "category": 42, "price": 5998.46, "stock": 302, "rating": 3, "reviews": 50}
related: 8 products, first: {"id": 8192, "name": "Product 8192", "price": 7748.96}

$ docker compose exec db psql -U shop -c "select ..."
 products | reviews | users 
----------+---------+--------
    20000 | 1000000 | 100000
(1 row)

$ ./k6.sh product.js -e RATE=20 -e DURATION=10s
requests   201 (20.1/s)
failed     0.00%
latency    avg 12 ms  p50 10 ms  p95 19 ms  p99 62 ms  max 66 ms
vus max    50

Reading the output

  • ok api: shop উত্তর দিচ্ছে, আর বলে দিচ্ছে কোন instance উত্তর দিলো। Part 2 এ যখন তিনটা instance থাকবে, তখন এই নামটা কাজে লাগবে।
  • Product page তিনটা query এর result নিয়েই এসেছে: product টা, rating আর reviews (review এর হিসাব), আর 8 টা related product।
  • Count গুলো হুবহু 20,000, 1,000,000 আর 100,000। তোমার কম হলে seed শেষ হয়নি, নিচে দেখো।
  • k6 এর line টা প্রতিটা lesson এ পড়বে। Second এ 20 request এ কোনো চাপ নেই: সব request সফল, p95 20 ms এর নিচে। নতুন start এ p99 একটু বেশি, কারণ PostgreSQL তখনো disk থেকে page পড়ে নিজের cache এ তুলছে। পরের run গুলোতে আগে cache গরম করে নেওয়া হয়। তোমার number মোটামুটি কোথায় এলো মনে রাখো। পরের lesson গুলোতে rate বাড়াতে বাড়াতে এটা ভেঙে ফেলা হবে।
Lineমানে
requestsk6 কতগুলো request পাঠালো, আর আসলে কত rate এ পাঠাতে পারলো
failedError আর timeout, সব request এর কত ভাগ
latencyAverage আর percentile গুলো: p95 মানে 95% request অন্তত এতটা fast ছিল
droppedযে request k6 পাঠাতে চেয়েছিল কিন্তু পারেনি, কারণ তার সব virtual user wait করে আটকে ছিল। শুধু তখনই দেখায়

When it doesn't work

  • port is already allocated: 58080, 55432 বা 56379 অন্য কিছু use করছে। docker-compose.yml এ ports: এর বাম পাশ বদলে দাও, যেমন "58090:8080"।
  • API log এ connection refused আর count 0: অর্ধেক হওয়া seed এর পুরনো volume রয়ে গেছে। docker compose down -v চালাও (-v database এর volume delete করে), তারপর আবার start করো।
  • k6.sh বলছে network syslab_default not found: lab চলছে না, অথবা অন্য নামের folder থেকে start করেছো। Network project এর নাম নেয়, আর compose file এ সেটা syslab এ fixed করা।
  • সব কিছু খুব slow: free -h দিয়ে free memory দেখো। Lab এর প্রায় 1 GB লাগে। কাজ শেষ হলে docker compose stop দিয়ে বন্ধ রাখো।

Key takeaway

এখন তোমার কাছে এমন একটা shop আছে যেটা ছোট একটা production system এর মতো আচরণ করে: একটা app server, একটা database, দুইটাই এক CPU তে limit করা, আর একটা load generator যেটা যে চারটা number নিয়ে এই course চলে, সেগুলো report করে। প্রতিটা lesson এই setup এ একটা জিনিস বদলাবে, আর measure করবে কী হলো।

Station stamp

Chapter শেষ করো

পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +15 XP পেতে।

Pro নিয়ে XP পাও →