Part 01 · Thinking About Scale
Scaling Lab Setup
Run the shop on your laptop with Docker Compose: a Go API, PostgreSQL and k6 ready to load test it. Every later lab grows from this.
⏱ 18 min · Station 1 of 93
What you'll have at the end
One folder, syslab/, that runs the shop on your laptop with one command. Every lab in this course starts here and grows from it: more app servers, a load balancer, Redis, queues.
| Service | Port on your machine | What it is |
|---|---|---|
api | 58080 | The shop's backend: a small Go service with a product page, login, cart and a few endpoints the labs use to create problems on purpose |
db | 55432 | PostgreSQL 17 with 20,000 products, 1,000,000 reviews and 100,000 users |
redis | 56379 | Redis 7. Unused today; the caching and session lessons turn it on |
k6 | (runs and exits) | The load generator. It runs inside the lab's network and prints a short summary |
The data is generated by SQL, not random, so your products, prices and ratings match ours exactly. Timings won't: your machine is different. Ours is an Intel i3-10110U laptop (2 cores, 4 threads), 7 GB RAM, Ubuntu 26.04, Docker 29.8.
The api and db containers each get one CPU thread of their own (cpuset), and k6 gets the other two. That's on purpose. A laptop with 8 threads can hide a bottleneck that a real server of the same size would hit; pinning makes the breaking points clear and closer to what a small cloud server would do.
You need Docker with Compose and about 1 GB of free RAM while the lab runs. You don't need Go on your machine: the image builds the binary.
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]
Three things to notice:
cpusetonapianddb. Each runs on one CPU thread (numbers 3 and 2), no more, however many your laptop has. We first triedcpus: 1.0, which allows one CPU's worth of time spread over all threads. Under load PostgreSQL used several threads at once, burned the quota early in each 100 ms period and was frozen for the rest of it: throughput fell to a quarter of what one pinned thread does. That throttling is a real production problem (the Reliability course meets it again with Kubernetes CPU limits), but it would blur every measurement here. If your machine has fewer than 4 threads, change the numbers or remove the lines.- The healthcheck uses
-h 127.0.0.1. While the seed script runs, PostgreSQL only listens on a Unix socket. A plainpg_isreadysaid "ready" before the data existed and the API started against empty tables. Checking over TCP waits until the seed is done. api1,api2,api3andlbsit behind thelbprofile, so they don't start yet. Part 2 turns them on.
The shop is built in two stages: compile in the Go image, run in a 13 MB Alpine image.
# 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"]
Every behaviour that changes between lessons is an environment variable (CACHE, SESSIONS, WORKERS and so on, read in main.go), so the same binary plays every role.
The product page
This is the request most labs measure. One page needs three queries: the product, its rating, and eight best sellers from the same category.
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)
}
The third query has no index on category, so PostgreSQL scans the 20,000 products to find the best sellers. That's deliberate: it makes the database the first thing to run out of CPU, like a real shop where one heavy query hides on the most visited page. We'll find it with measurements before we fix it.
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 runs the official k6 image on the lab's Docker network, so scripts can call http://api:8080 directly:
#!/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 asks for random product pages at a fixed rate, RATE requests per second:
// 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 replaces k6's long default report with four lines:
// 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
From the syslab/ folder:
docker compose up -d --build
The first run downloads the images and compiles the shop. On our machine, from nothing to 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
Then check each piece:
$ 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: the shop answers, and it tells you which instance answered. That name matters in Part 2, when there are three.- The product page came back with all three queries' results: the product,
ratingandreviews(the review aggregate) and 8 related products. - The counts are exactly 20,000, 1,000,000 and 100,000. If yours are lower, the seed didn't finish: see below.
- The k6 line is the one you will read in every lesson. At 20 requests per second nothing is under pressure: every request succeeded and p95 is under 20 ms. p99 is higher on a fresh start because PostgreSQL is still reading pages from disk into its cache; later runs warm it up first. Remember roughly where yours landed. The next lessons push the rate up until it breaks.
| Line | Meaning |
|---|---|
requests | how many requests k6 sent, and the rate it actually achieved |
failed | errors and timeouts as a share of all requests |
latency | the average and the percentiles: p95 means 95% of requests were at least this fast |
dropped | requests k6 wanted to send but couldn't, because all its virtual users were stuck waiting. Only shown when it happens |
When it doesn't work
port is already allocated: something else uses 58080, 55432 or 56379. Change the left side ofports:indocker-compose.yml, for example"58090:8080".- The API logs
connection refusedand the counts are 0: an old volume from a half-finished seed. Rundocker compose down -v(the-vdeletes the database volume) and start again. k6.shsaysnetwork syslab_default not found: the lab isn't running, or you started it from a folder with a different name. The network takes the project name, which is fixed tosyslabin the compose file.- Everything is very slow: check free memory with
free -h. The lab needs about 1 GB. Stop it when you're done withdocker compose stop.
Key takeaway
You now have a shop that behaves like a small production system: one app server, one database, both limited to one CPU, and a load generator that reports the four numbers this course lives on. Every lesson changes one thing in this setup and measures what happened.
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 →