Part 01 · Why Distributed Is Hard
Cluster Lab Setup
Run a small cluster on your laptop with Docker Compose, plus the tools to break it on purpose: stop, pause, delay, drop and partition.
⏱ 18 min · Station 1 of 91
What you'll have at the end
A three-node cluster on your laptop, and the tools to break it on purpose. Every lesson in this course makes a distributed-systems failure happen for real (a node that stops, freezes, slows down, loses packets or lies) and watches what the rest of the system can and can't tell.
| Piece | What it is |
|---|---|
node1, node2, node3 | The same small Go service three times: a key-value store, a payment endpoint, a ping, and a blob download. Each node only knows its own memory |
client.sh | A client that runs inside the cluster's network, calls nodes with timeouts, and reports exactly what it observed |
netem.sh | Adds delay, packet loss or a bandwidth limit to everything one node sends (Linux tc netem) |
docker compose stop / pause | Kills a node, or freezes it so it's alive but silent |
Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Docker 29.8. The cluster needs about 100 MB of RAM. No Go is needed on your machine except to rebuild the client (or use the golang image).
The files
distlab/
docker-compose.yml
node/ main.go go.mod Dockerfile the node service
client/ main.go go.mod the client (built to client/client)
tc/ Dockerfile an Alpine image with tc, for netem.sh
client.sh netem.sh
docker-compose.yml: three identical nodes, two of which can be told to misbehave:
# The Distributed Systems lab: three identical nodes on one Docker network, plus the tools to
# break the network between them.
# docker compose up -d --build
# ./client.sh ping talk to the cluster from inside its network
# ./netem.sh node2 delay 100ms slow down everything node2 sends
# docker compose pause node2 freeze node2 (alive, but not answering)
name: distlab
x-node: &node
build: ./node
image: distlab-node
restart: unless-stopped
mem_limit: 64m
services:
node1: { <<: *node, environment: { NAME: node1 } }
node2: { <<: *node, environment: { NAME: node2, PAY_MS: "${PAY_MS:-0}" } }
node3: { <<: *node, environment: { NAME: node3, LIE: "${LIE:-0}" } }
The node. Notice that /pay records the charge before it replies: if the reply is lost on the way back, the money has still moved. That detail drives the next lessons.
// Command node is one machine of the Distributed Systems lab cluster. Every node runs the same
// binary; the labs make them fail in different ways (stopped, paused, cut off, slowed down, or
// lying) and watch what the rest of the system can and can't tell.
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
)
type node struct {
name string
lie bool // LIE=1: answer reads with wrong values (a Byzantine node)
payWait time.Duration // PAY_MS: how long a payment takes to process
mu sync.Mutex
kv map[string]string
charges map[string]int // order ID -> how many times it was charged
}
func main() {
ms, _ := strconv.Atoi(os.Getenv("PAY_MS"))
n := &node{
name: os.Getenv("NAME"),
lie: os.Getenv("LIE") == "1",
payWait: time.Duration(ms) * time.Millisecond,
kv: map[string]string{},
charges: map[string]int{},
}
http.HandleFunc("GET /ping", n.ping)
http.HandleFunc("GET /kv/{key}", n.get)
http.HandleFunc("PUT /kv/{key}", n.put)
http.HandleFunc("POST /pay", n.pay)
http.HandleFunc("GET /charges", n.listCharges)
http.HandleFunc("GET /blob", n.blob)
log.Printf("node %s listening on :7000", n.name)
log.Fatal(http.ListenAndServe(":7000", nil))
}
func reply(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
func (n *node) ping(w http.ResponseWriter, r *http.Request) {
reply(w, map[string]any{"node": n.name, "time": time.Now().UnixMilli()})
}
func (n *node) get(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
v, ok := n.kv[r.PathValue("key")]
n.mu.Unlock()
if !ok {
http.Error(w, "not found", http.StatusNotFound)
return
}
if n.lie {
v = v + "-corrupted" // a Byzantine node: answers, confidently, with the wrong value
}
reply(w, map[string]any{"node": n.name, "value": v})
}
func (n *node) put(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
n.kv[r.PathValue("key")] = r.URL.Query().Get("value")
n.mu.Unlock()
reply(w, map[string]any{"node": n.name, "ok": true})
}
// pay charges an order. The charge is recorded *before* the reply is sent, like a real payment
// provider: if the reply is lost, the money has still moved.
func (n *node) pay(w http.ResponseWriter, r *http.Request) {
order := r.URL.Query().Get("order")
time.Sleep(n.payWait)
n.mu.Lock()
n.charges[order]++
n.mu.Unlock()
reply(w, map[string]any{"node": n.name, "order": order, "charged": true})
}
func (n *node) listCharges(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
defer n.mu.Unlock()
total, orders, twice := 0, 0, 0
for _, c := range n.charges {
total += c
orders++
if c > 1 {
twice++
}
}
reply(w, map[string]any{"node": n.name, "charges": total, "orders": orders, "charged_more_than_once": twice})
}
// blob returns ?kb=N kilobytes, for the bandwidth experiments.
func (n *node) blob(w http.ResponseWriter, r *http.Request) {
kb, _ := strconv.Atoi(r.URL.Query().Get("kb"))
buf := make([]byte, 1024)
for i := range buf {
buf[i] = 'x'
}
for i := 0; i < kb; i++ {
w.Write(buf)
}
}
The client calls nodes with a timeout and sorts every outcome into what a caller can actually observe: an answer, a timeout, a refused connection, or a name that no longer resolves:
// Command client talks to the lab cluster the way a service would: with timeouts, and reporting
// exactly what it could and couldn't find out.
//
// client ping -nodes node1,node2,node3 [-timeout 500ms]
// client pay -node node1 -n 50 [-timeout 300ms] [-retries 0] [-every 20ms]
// client put -nodes node1,node2,node3 -key k -value v
// client get -nodes node1,node2,node3 -key k
// client calls -node node1 -n 20 (n sequential round trips)
// client fetch -node node1 -kb 1024 (download a blob, report the time)
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
var (
nodes = flag.String("nodes", "node1,node2,node3", "comma-separated node names")
one = flag.String("node", "node1", "a single node")
timeout = flag.Duration("timeout", 2*time.Second, "per-request timeout")
n = flag.Int("n", 1, "how many requests")
retries = flag.Int("retries", 0, "retries after a timeout or error")
every = flag.Duration("every", 20*time.Millisecond, "pause between payments")
key = flag.String("key", "price:42", "key")
value = flag.String("value", "4999", "value")
kb = flag.Int("kb", 1024, "kilobytes to fetch")
)
func call(method, node, path string) (map[string]any, time.Duration, error) {
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, method, "http://"+node+":7000"+path, nil)
start := time.Now()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, time.Since(start), err
}
defer resp.Body.Close()
var m map[string]any
json.NewDecoder(resp.Body).Decode(&m)
if resp.StatusCode != 200 {
return m, time.Since(start), fmt.Errorf("HTTP %d", resp.StatusCode)
}
return m, time.Since(start), nil
}
// kind turns an error into the three things a caller can actually observe.
func kind(err error) string {
switch {
case err == nil:
return "ok"
case errors.Is(err, context.DeadlineExceeded):
return "timeout (no answer)"
case strings.Contains(err.Error(), "connection refused"):
return "refused (nothing listening)"
case strings.Contains(err.Error(), "lookup"):
return "unknown host (name gone)"
default:
return "error: " + err.Error()
}
}
func ms(d time.Duration) string { return fmt.Sprintf("%.1f ms", float64(d.Microseconds())/1000) }
func main() {
cmd := os.Args[1]
flag.CommandLine.Parse(os.Args[2:])
switch cmd {
case "ping":
for _, nd := range strings.Split(*nodes, ",") {
_, d, err := call("GET", nd, "/ping")
fmt.Printf("%-6s %-28s after %s\n", nd, kind(err), ms(d))
}
case "pay":
counts := map[string]int{}
for i := 1; i <= *n; i++ {
order := fmt.Sprintf("o%d", i)
var err error
for try := 0; try <= *retries; try++ {
_, _, err = call("POST", *one, "/pay?order="+order)
if err == nil {
break
}
}
counts[kind(err)]++
time.Sleep(*every)
}
fmt.Printf("client view of %d payments:", *n)
for k, v := range counts {
fmt.Printf(" %s: %d", k, v)
}
fmt.Println()
case "put":
for _, nd := range strings.Split(*nodes, ",") {
_, _, err := call("PUT", nd, "/kv/"+*key+"?value="+*value)
fmt.Printf("put %s=%s on %-6s %s\n", *key, *value, nd, kind(err))
}
case "get":
for _, nd := range strings.Split(*nodes, ",") {
m, _, err := call("GET", nd, "/kv/"+*key)
fmt.Printf("get %s from %-6s %-10s value=%v\n", *key, nd, kind(err), m["value"])
}
case "calls":
start := time.Now()
for i := 0; i < *n; i++ {
if _, _, err := call("GET", *one, "/ping"); err != nil {
fmt.Println(kind(err))
}
}
fmt.Printf("%d sequential calls to %s took %s (%s each)\n", *n, *one, ms(time.Since(start)), ms(time.Since(start)/time.Duration(*n)))
case "fetch":
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://%s:7000/blob?kb=%d", *one, *kb), nil)
start := time.Now()
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(kind(err))
return
}
got, err := io.Copy(io.Discard, resp.Body)
resp.Body.Close()
d := time.Since(start)
fmt.Printf("fetched %d KB from %s in %s (%.1f Mbit/s) %s\n", got/1024, *one, ms(d), float64(got*8)/d.Seconds()/1e6, map[bool]string{true: "", false: kind(err)}[err == nil])
}
}
client.sh runs it on the cluster's network, so node names resolve:
#!/bin/sh
# Run the client inside the cluster's network: ./client.sh ping -nodes node1,node2,node3
docker run --rm --network distlab_default -v "$(pwd)/client/client:/client:ro" alpine:3.20 /client "$@"
netem.sh changes one node's outgoing network:
#!/bin/sh
# Change the network of one node: everything it sends is delayed, dropped, or rate-limited.
# ./netem.sh node2 delay 100ms ./netem.sh node2 loss 30% ./netem.sh node2 rate 1mbit ./netem.sh node2 off
docker image inspect distlab-tc >/dev/null 2>&1 || docker build -q -t distlab-tc ./tc >/dev/null
c=distlab-$1-1; shift
if [ "$1" = off ]; then
docker run --rm --net container:$c --cap-add NET_ADMIN distlab-tc qdisc del dev eth0 root 2>/dev/null || true
else
docker run --rm --net container:$c --cap-add NET_ADMIN distlab-tc qdisc replace dev eth0 root netem "$@"
fi
Start it and check it
cd client && CGO_ENABLED=0 go build -o client . && cd ..
docker compose up -d --build
Container distlab-node3-1 Started
Container distlab-node2-1 Started
Container distlab-node1-1 Started
ready after 2 s
Then ping every node, break two of them in two different ways, and add delay to a third:
$ ./client.sh ping
node1 ok after 1.1 ms
node2 ok after 0.9 ms
node3 ok after 1.4 ms
$ docker compose stop node2; docker compose pause node3; ./client.sh ping -timeout 1s
node1 ok after 1.2 ms
node2 unknown host (name gone) after 0.8 ms
node3 timeout (no answer) after 1000.4 ms
$ ./netem.sh node1 delay 100ms; ./client.sh ping
node1 ok after 302.1 ms
node2 ok after 4.2 ms
node3 ok after 5.8 ms
Reading the output
- All healthy: each node answers in about a millisecond.
node2stopped: the answer comes back in under a millisecond: "unknown host". Docker removes a stopped container from its DNS, so the name no longer resolves. On real networks a dead machine shows up as "connection refused" (the host is up, nothing listens) or as a timeout (the host is gone). Either way, the client knows quickly that something is wrong.node3paused: the client waited the full 1-second timeout and heard nothing. A paused node is alive (its memory, its connections), but frozen. From outside, that's indistinguishable from a node that's slow, overloaded, or on the other side of a broken network.node1with 100 ms delay: the ping took 302 ms, not 100. Each new connection needs a TCP handshake (one delayed reply from node1) before the request, then the delayed answer: several trips through the delay. Latency in distributed systems multiplies.
| What we did to the node | What the client saw | How long it took to find out |
|---|---|---|
| stopped | unknown host | under 1 ms |
| paused | timeout | the whole timeout (1 s) |
| 100 ms delay | ok, slowly | 302 ms |
When it doesn't work
network distlab_default not found: the cluster isn't running, or was started from a folder with a different name (the compose file fixes the project name todistlab).client.shsaysexec format erroror not found: rebuild the client for Linux:cd client && CGO_ENABLED=0 GOOS=linux go build -o client .. On a Mac, addGOARCH=arm64oramd64to match Docker.netem.shfails with "RTNETLINK answers: Operation not permitted": Docker must allowNET_ADMIN; rootless Docker sometimes doesn't. Run Docker normally for this course.- A node stays paused after an experiment:
docker compose unpause node3. And remove leftover delays with./netem.sh node1 off.
Key takeaway
You have three nodes and the means to stop, freeze, slow and cut them off. The first measurement already shows the core difficulty of distributed systems: a stopped node is detected in under a millisecond, but a frozen one just doesn't answer, and from outside there's no way to tell whether it's dead, slow, or unreachable.
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 →