Part 01 · Measuring Performance
Production Lab Setup
Run the shop with Prometheus, Grafana and k6 on your laptop, the setup every later lab builds on.
⏱ 18 min · Station 1 of 95
What you'll have at the end
The same shop lab as the Scalable Systems course, plus what a production system has and a laptop usually doesn't: metrics. Every lesson in this course creates a production problem on purpose, then detects it the way you would at work: from the numbers the service reports about itself, not from a load test's summary.
| Service | Port | What it is |
|---|---|---|
api | 58080 | The shop's Go backend, now exposing /metrics in Prometheus format |
db | 55432 | PostgreSQL 17: 20,000 products, 1,000,000 reviews |
redis | 56379 | Redis 7, for the caching and resilience lessons |
prometheus | 59090 | Scrapes every shop copy's /metrics every 5 seconds and stores the time series |
grafana | 53000 | A ready-made dashboard: request rate, errors, p50/p95/p99, requests in flight |
k6 | (runs and exits) | The load generator |
If you did the Scalable Systems lab, you already have most of this; you only add the obs profile. Measured on an Intel i3-10110U laptop (2 cores, 4 threads), 7 GB RAM, Ubuntu 26.04, Docker 29.8; the shop and PostgreSQL each pinned to one CPU thread.
The files
What's new compared with the 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
Every shop copy records three metrics, in 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: a counter per route and status code. Rates and error ratios come from it.http_request_duration_seconds: a histogram. It doesn't store each request's time; it counts how many requests fell under each bucket boundary (5 ms, 10 ms, 25 ms...). Percentiles are estimated from those counts. Remember the bucket list: it matters in the percentiles lesson.http_requests_in_flight: a gauge, how many requests are being handled right now.
Prometheus scrapes them every 5 seconds:
# 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"]
The full docker-compose.yml, with the obs profile near the end:
# 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 runs with anonymous admin access so you can open it without logging in. That's for a laptop lab only; never expose a Grafana configured like this.
prom.sh sends a PromQL query to Prometheus's HTTP API and prints one line per series, so every lesson can show real numbers as 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
Then put a minute of traffic through the shop and ask Prometheus what it saw:
$ ./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
Open http://localhost:53000 and the "Shop: RED" dashboard: the same numbers as graphs, refreshing every 5 seconds.
Reading the output
- Rate: 297.5 requests per second for the product page, measured by the shop itself, against k6's 300 sent. The difference is the 1-minute window catching the start of the test.
- p50 2.5 ms, p95 4.8 ms, p99 7.1 ms from Prometheus, while k6 reported p50 1.7 ms, p95 3.7 ms, p99 6.1 ms. They differ for two reasons: k6 measures from outside (including the network), and Prometheus estimates percentiles from bucket counts. With buckets at 5 ms and 10 ms, every request between 0 and 5 ms looks the same to the histogram. The percentiles lesson digs into this.
- Error ratio: 0. Note the
or vector(0): when no request has failed yet, the 5xx series doesn't exist and the division would return nothing at all. "No data" and "zero errors" are different things, and alerts need to know which one they're looking at.
| Question | Where the answer comes from |
|---|---|
| How many requests per second? | rate(http_requests_total[1m]) |
| How many fail? | 5xx rate / total rate |
| How slow? | histogram_quantile(0.95, ...) over the duration buckets |
| How busy right now? | http_requests_in_flight |
When it doesn't work
upis 0 forapi1..api3: expected. Those copies only run in the load-balancing lessons; Prometheus keeps trying them.- PromQL returns nothing: the window is empty (no traffic in the last minute), or the series doesn't exist yet (no 5xx ever happened). Send some traffic, or add
or vector(0). - Grafana shows "No data": check the time range (top right) and that Prometheus is the data source.
docker compose logs grafanashows provisioning errors. - Port 53000 or 59090 already used: change the left side of
ports:forgrafanaorprometheus. - Memory: the full lab with metrics needs about 1.5 GB.
docker compose --profile obs stop prometheus grafanawhen you don't need them.
Key takeaway
The shop now reports its own rate, errors, latency percentiles and in-flight requests, and Prometheus keeps them as time series you can query. From here on, problems are found the production way: from what the service says about itself, with the load generator only creating the traffic.
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 →