Part 01 · Measuring Performance

Production Lab Setup

Docker ComposeGoPrometheusGrafanak6

নিজের laptop এ Prometheus, Grafana আর k6 সহ shop টা চালাও। এরপরের সব lab এই setup এর উপরেই দাঁড়াবে।

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

What you'll have at the end

Scalable Systems course এর একই shop lab, সাথে এমন একটা জিনিস যেটা production system এ থাকে কিন্তু laptop এ সাধারণত থাকে না: metrics। এই course এর প্রতিটা lesson ইচ্ছা করে একটা production problem তৈরি করে, তারপর কাজের জায়গায় যেভাবে ধরতে, সেভাবে ধরে: service নিজের সম্পর্কে যে number report করে তা থেকে, load test এর summary থেকে না।

ServicePortএটা কী
api58080Shop এর Go backend, এখন Prometheus format এ /metrics দেখায়
db55432PostgreSQL 17: 20,000 product, 1,000,000 review
redis56379Redis 7, caching আর resilience lesson এর জন্য
prometheus59090প্রতি 5 second এ প্রতিটা shop copy র /metrics scrape করে আর time series হিসেবে রাখে
grafana53000তৈরি একটা dashboard: request rate, error, p50/p95/p99, চলমান request
k6(চলে, তারপর বন্ধ হয়)Load generator

Scalable Systems এর lab করে থাকলে এর বেশিরভাগ তোমার কাছে আছে; শুধু obs profile যোগ করবে। Intel i3-10110U laptop (2 core, 4 thread), 7 GB RAM, Ubuntu 26.04, Docker 29.8 এ measure করা; shop আর PostgreSQL প্রত্যেকে একটা CPU thread এ pin করা।

The files

Scalable Systems এর lab এর তুলনায় যা নতুন:

syslab/
  obs/
    prometheus.yml                       what to scrape, how often
    grafana/provisioning/datasources/    Prometheus as the default data source
    grafana/provisioning/dashboards/     load dashboards from a folder
    grafana/dashboards/shop.json         the RED dashboard
  prom.sh                                run a PromQL query from the terminal

প্রতিটা shop copy তিনটা metric record করে, ops.go তে:

// ops.go (excerpt): the metrics every shop copy exposes on /metrics
var (
	requests = promauto.NewCounterVec(prometheus.CounterOpts{
		Name: "http_requests_total", Help: "Requests by route and status code.",
	}, []string{"route", "code"})
	duration = promauto.NewHistogramVec(prometheus.HistogramOpts{
		Name:    "http_request_duration_seconds",
		Help:    "Request latency by route.",
		Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5},
	}, []string{"route"})
	inFlight = promauto.NewGauge(prometheus.GaugeOpts{
		Name: "http_requests_in_flight", Help: "Requests being handled right now.",
	})
)

// middleware tags every response with the instance name, applies /admin/stall, and records
// Prometheus metrics per route.
func (a *app) middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		a.stall.wait()
		inFlight.Inc()
		defer inFlight.Dec()
		w.Header().Set("X-Instance", a.cfg.Instance)
		rec := &recorder{ResponseWriter: w, code: 200}
		next.ServeHTTP(rec, r)
		a.stats.requests.Add(1)
		route := r.Pattern
		if route == "" {
			route = "other"
		}
		requests.WithLabelValues(route, strconv.Itoa(rec.code)).Inc()
		duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
	})
}
  • http_requests_total: প্রতি route আর status code এর একটা counter। Rate আর error ratio এখান থেকে আসে।
  • http_request_duration_seconds: একটা histogram। এটা প্রতিটা request এর সময় রাখে না; গোনে কতগুলো request কোন bucket boundary র নিচে পড়লো (5 ms, 10 ms, 25 ms...)। Percentile ওই সংখ্যাগুলো থেকে estimate করা হয়। Bucket list টা মনে রাখো: percentile lesson এ এটা matter করে।
  • http_requests_in_flight: একটা gauge, এই মুহূর্তে কতগুলো request সামলানো হচ্ছে।

Prometheus প্রতি 5 second এ এগুলো scrape করে:

# Scrape every shop copy's /metrics every 5 seconds.
global:
  scrape_interval: 5s
scrape_configs:
  - job_name: shop
    static_configs:
      - targets: ["api:8080", "api1:8080", "api2:8080", "api3:8080"]

পুরো docker-compose.yml, শেষের দিকে obs profile সহ:

# 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]

Grafana anonymous admin access দিয়ে চলে, যাতে login ছাড়াই খুলতে পারো। এটা শুধু laptop এর lab এর জন্য; এভাবে configure করা Grafana কখনো বাইরে খোলা রাখবে না।

prom.sh Prometheus এর HTTP API তে একটা PromQL query পাঠায় আর প্রতিটা series এর জন্য এক line print করে, যাতে প্রতিটা lesson আসল number text হিসেবে দেখাতে পারে:

#!/bin/sh
# Run a PromQL query against the lab's Prometheus and print each series on one line.
#   ./prom.sh 'sum(rate(http_requests_total[1m]))'
curl -s --get localhost:59090/api/v1/query --data-urlencode "query=$1" | python3 -c '
import json, sys
r = json.load(sys.stdin)
if r["status"] != "success":
    sys.exit(r.get("error"))
for s in r["data"]["result"]:
    labels = ",".join("%s=%s" % (k, v) for k, v in s["metric"].items() if k != "__name__") or "value"
    print("%-40s %.4g" % (labels, float(s["value"][1])))'

Start it and check it

docker compose up -d --build
docker compose --profile obs up -d prometheus grafana
$ docker compose --profile obs ps
api	Up About a minute
db	Up 4 hours (healthy)
grafana	Up About a minute
prometheus	Up About a minute
redis	Up 7 minutes

$ curl -s localhost:59090/-/ready
Prometheus Server is Ready.

$ curl -s localhost:53000/api/health
grafana 11.3.0 database ok

তারপর shop এর মধ্যে দিয়ে এক minute traffic পাঠাও আর Prometheus কে জিজ্ঞেস করো সে কী দেখলো:

$ ./k6.sh product.js -e RATE=300 -e DURATION=60s
requests   18001 (300.0/s)
failed     0.00%
latency    avg 2.0 ms  p50 1.7 ms  p95 3.7 ms  p99 6.1 ms  max 22 ms
vus max    50

$ ./prom.sh "sum by (route) (rate(http_requests_total[1m]))"
route=GET /products/{id}                 297.5
route=GET /metrics                       0.2
$ ./prom.sh 'histogram_quantile(0.5, ...product page...)'
value                                    0.00254
$ ./prom.sh 'histogram_quantile(0.95, ...product page...)'
value                                    0.004825
$ ./prom.sh 'histogram_quantile(0.99, ...product page...)'
value                                    0.007115
$ ./prom.sh "(sum(rate(http_requests_total{code=~\"5..\"}[1m])) or vector(0)) / sum(rate(http_requests_total[1m]))"
value                                    0

http://localhost:53000 খুলে "Shop: RED" dashboard দেখো: একই number graph হিসেবে, প্রতি 5 second এ refresh হয়।

Reading the output

  • Rate: second এ 297.5 request product page এর জন্য, shop নিজে measure করেছে, k6 পাঠিয়েছিল 300। পার্থক্যটা হলো 1 minute এর window test এর শুরুটাও ধরে ফেলেছে।
  • Prometheus থেকে p50 2.5 ms, p95 4.8 ms, p99 7.1 ms, অথচ k6 report করেছে p50 1.7 ms, p95 3.7 ms, p99 6.1 ms। দুইটা কারণে আলাদা: k6 বাইরে থেকে measure করে (network সহ), আর Prometheus bucket এর সংখ্যা থেকে percentile estimate করে। 5 ms আর 10 ms এ bucket থাকায় 0 থেকে 5 ms এর মধ্যের প্রতিটা request histogram এর কাছে একই রকম। Percentile lesson এটা নিয়ে বিস্তারিত।
  • Error ratio: 0। or vector(0) টা খেয়াল করো: এখনো কোনো request fail না করলে 5xx series টাই থাকে না, আর ভাগ করলে কিছুই ফেরত আসতো না। "Data নেই" আর "error শূন্য" আলাদা জিনিস, আর alert কে জানতে হবে সে কোনটা দেখছে।
প্রশ্নউত্তর কোথা থেকে আসে
Second এ কতগুলো request?rate(http_requests_total[1m])
কতগুলো fail করে?5xx rate / মোট rate
কত slow?Duration bucket এর উপর histogram_quantile(0.95, ...)
এই মুহূর্তে কত ব্যস্ত?http_requests_in_flight

When it doesn't work

  • api1..api3 এর জন্য up 0: এটাই স্বাভাবিক। ওই copy গুলো শুধু load-balancing lesson এ চলে; Prometheus চেষ্টা করতে থাকে।
  • PromQL কিছুই ফেরত দেয় না: window খালি (শেষ এক minute এ কোনো traffic নেই), অথবা series টা এখনো তৈরি হয়নি (কখনো কোনো 5xx হয়নি)। কিছু traffic পাঠাও, অথবা or vector(0) যোগ করো।
  • Grafana "No data" দেখাচ্ছে: time range দেখো (উপরে ডানে), আর data source Prometheus কিনা। docker compose logs grafana provisioning এর error দেখায়।
  • Port 53000 বা 59090 ব্যস্ত: grafana বা prometheus এর ports: এর বাম পাশ বদলাও।
  • Memory: metrics সহ পুরো lab এ প্রায় 1.5 GB লাগে। দরকার না থাকলে docker compose --profile obs stop prometheus grafana।

Key takeaway

Shop এখন নিজের rate, error, latency percentile আর চলমান request report করে, আর Prometheus এগুলো time series হিসেবে রাখে যেগুলো query করা যায়। এখন থেকে problem খোঁজা হবে production এর নিয়মে: service নিজের সম্পর্কে যা বলে তা থেকে, load generator শুধু traffic তৈরি করবে।

Station stamp

Chapter শেষ করো

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

Pro নিয়ে XP পাও →