Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 1

Fronting three instances with a reverse proxy

Put Caddy in front of three local Python instances, compare round robin with least requests under uneven costs, watch health checks remove a crashed instance, drain one cleanly and see what sticky sessions cost.

Contentsand lesson path

What you will learn

  • Choose a balancing algorithm (round robin, least requests, power of two choices, hash-based) for a workload and explain its effect on tail latency.
  • Wire service discovery, health checks, connection draining and session affinity so instances can join, fail or be deployed without user-visible errors.

Prerequisites: Scalability Fundamentals

01. Goal and setup

You will run a real reverse proxy, Caddy, in front of three copies of a small Python service on your machine, then watch traffic spread, compare three balancing policies under uneven costs, see a health check remove a crashed instance, drain an instance without errors and find out what a sticky session costs.

You need a Linux or macOS shell (on Windows, use WSL), curl, Python 3.10 or newer and Caddy 2.11; the lab was run with Python 3.12.13 and Caddy v2.11.9. The Python code uses only the standard library. Install Caddy the normal way, following the official install page: on Debian or Ubuntu, add Caddy's apt repository as shown there and run sudo apt install caddy; on macOS, run brew install caddy; elsewhere, download a release binary from GitHub. The Debian package also starts a caddy service on other ports; it does not interfere.

Everything listens on 127.0.0.1 only: the instances on ports 18101 to 18103, the proxy on 18100 and 18110, and Caddy's admin API on 18199 instead of its default 2019. Use two terminals in the same folder: terminal 1 for commands, terminal 2 for Caddy and its log.

Terminal 1 · create the lab folder
mkdir lb-lab
cd lb-lab

02. Step 1: Check your tools

Terminal 1 · lb-lab/
caddy version
python3 --version
Expected output (your versions may be newer)
v2.11.9 h1:bhZtcRKQOq0fuLvEgCdPYvUxXyGn9kzjG4lh2332DTE=
Python 3.12.13

03. Step 2: Write and start three instances

Save the service below as app.py. Each copy has a name and a port. Four details matter for the lab:

  • /work?ms=N sleeps for N milliseconds while holding a lock, so each instance does one piece of work at a time, like a server with a single worker. A second request has to queue.
  • /health never waits for that lock, so a busy instance still answers its health check. It returns 503 while the instance is draining.
  • /cart/add keeps a cart count per session in memory and sets a sid cookie.
  • On SIGTERM the instance starts failing health checks but keeps serving for 5 s, then stops accepting connections and exits once the requests already in progress are finished.
Python · lb-lab/app.py
"""A small backend for the load-balancing lab (Python 3.12, stdlib only)."""
import signal
import sys
import threading
import time
import uuid
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

NAME, PORT = sys.argv[1], int(sys.argv[2])
DRAIN_WAIT = 5.0  # seconds to keep serving after SIGTERM, so the proxy notices
one_worker = threading.Lock()  # work runs one request at a time, like 1 worker
counts = threading.Lock()
state = {"draining": False, "in_flight": 0}
carts: dict[str, int] = {}  # in-memory session state: lost if this process dies


class Handler(BaseHTTPRequestHandler):
    def handle(self):  # count every open request, from parsing to reply
        with counts:
            state["in_flight"] += 1
        try:
            super().handle()
        finally:
            with counts:
                state["in_flight"] -= 1

    def do_GET(self):
        url = urlparse(self.path)
        if url.path == "/health":  # never waits behind real work
            if state["draining"]:
                return self.reply(503, "draining")
            return self.reply(200, "ok")
        if url.path == "/work":
            ms = int(parse_qs(url.query).get("ms", ["20"])[0])
            with one_worker:  # queue here if another request is working
                time.sleep(ms / 1000)
            return self.reply(200, NAME)
        if url.path == "/cart/add":
            jar = SimpleCookie(self.headers.get("Cookie", ""))
            sid = jar["sid"].value if "sid" in jar else uuid.uuid4().hex[:8]
            with counts:
                carts[sid] = carts.get(sid, 0) + 1
                items = carts[sid]
            return self.reply(200, f"{NAME} cart={items}", sid)
        self.reply(404, "not found")

    def reply(self, code: int, text: str, sid: str | None = None) -> None:
        body = (text + "\n").encode()
        self.send_response(code)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("X-Served-By", NAME)
        if sid:
            self.send_header("Set-Cookie", f"sid={sid}; Path=/")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):  # keep the terminal quiet
        pass


def on_sigterm(signum, frame):
    state["draining"] = True  # /health now answers 503
    print(f"{NAME}: SIGTERM, failing health checks", flush=True)

    def stop_later():
        time.sleep(DRAIN_WAIT)  # keep serving while the proxy notices
        server.shutdown()  # then stop accepting new connections

    threading.Thread(target=stop_later).start()


server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
signal.signal(signal.SIGTERM, on_sigterm)
print(f"{NAME} listening on 127.0.0.1:{PORT}", flush=True)
server.serve_forever()
server.server_close()
while state["in_flight"]:  # let requests that are still open finish
    time.sleep(0.05)
print(f"{NAME}: drained, exiting", flush=True)
Terminal 1 · start three instances in the background
python3 app.py a 18101 > a.log 2>&1 & echo $! > a.pid
python3 app.py b 18102 > b.log 2>&1 & echo $! > b.pid
python3 app.py c 18103 > c.log 2>&1 & echo $! > c.pid
sleep 1; cat a.log b.log c.log
curl -s "http://127.0.0.1:18101/work?ms=5"; curl -s http://127.0.0.1:18101/health
Expected output
a listening on 127.0.0.1:18101
b listening on 127.0.0.1:18102
c listening on 127.0.0.1:18103
a
ok

Each .pid file holds the process ID of one instance, so later steps can stop exactly that process.

04. Step 3: Put Caddy in front

Save this as Caddyfile. The global block moves the admin API to port 18199 and turns off automatic HTTPS, which a local lab does not need. The site on port 18100 balances over the three instances and checks /health on each every second; two failed checks in a row mark an instance down and two passes bring it back. Production checks usually run every 5 to 30 s. {$LB_POLICY:round_robin} reads the policy from an environment variable when the file is loaded, defaulting to round robin. The site on port 18110 uses the same instances with no health checks.

Caddyfile · lb-lab/Caddyfile
{
	admin 127.0.0.1:18199
	auto_https off
}

# The proxy you will use: three upstreams, actively health-checked
:18100 {
	bind 127.0.0.1
	reverse_proxy 127.0.0.1:18101 127.0.0.1:18102 127.0.0.1:18103 {
		lb_policy {$LB_POLICY:round_robin}
		health_uri /health
		health_interval 1s
		health_timeout 500ms
		health_fails 2
		health_passes 2
	}
}

# The same upstreams with no health checks, for comparison
:18110 {
	bind 127.0.0.1
	reverse_proxy 127.0.0.1:18101 127.0.0.1:18102 127.0.0.1:18103 {
		lb_policy round_robin
	}
}
Terminal 2 · lb-lab/ (leave it running)
export XDG_CONFIG_HOME="$PWD/caddy-config" XDG_DATA_HOME="$PWD/caddy-data"
caddy run --config Caddyfile

The export line keeps Caddy's saved configuration and data inside lb-lab/ instead of your home folder. Terminal 2 prints JSON log lines: look for two lines with "msg":"server running", one per site, and no "level":"error" line (warnings that HTTP/2 and HTTP/3 need TLS are expected). Then ask the admin API, from terminal 1, which upstreams the proxy knows about:

Terminal 1 · lb-lab/
curl -s http://127.0.0.1:18199/reverse_proxy/upstreams | python3 -m json.tool
Illustrative output (the order of the three entries can differ)
[
    {
        "address": "127.0.0.1:18101",
        "num_requests": 0,
        "fails": 0
    },
    {
        "address": "127.0.0.1:18102",
        "num_requests": 0,
        "fails": 0
    },
    {
        "address": "127.0.0.1:18103",
        "num_requests": 0,
        "fails": 0
    }
]

05. Step 4: Watch requests spread

Save the load generator below as load.py. It sends N requests through the proxy from one or more concurrent clients and counts which instance answered, using the X-Served-By header. With --heavy-every 10, every tenth request asks for 300 ms of work instead of 20 ms, and the script counts cheap requests that took over 100 ms, which means they waited in a queue.

Python · lb-lab/load.py
"""Send requests through the proxy and count who answered (stdlib only)."""
import argparse
import threading
import time
import urllib.error
import urllib.request
from collections import Counter

parser = argparse.ArgumentParser()
parser.add_argument("n", type=int, help="number of requests")
parser.add_argument("--url", default="http://127.0.0.1:18100")
parser.add_argument("--clients", type=int, default=1, help="concurrent clients")
parser.add_argument("--ms", type=int, default=20, help="work per request")
parser.add_argument("--heavy-every", type=int, default=0, help="k: 1 in k is 300 ms")
args = parser.parse_args()

served, status, latencies, slow_light = Counter(), Counter(), [], 0
lock = threading.Lock()
todo = iter(range(args.n))


def cost(i: int) -> int:
    if args.heavy_every and i % args.heavy_every == 0:
        return 300
    return args.ms


def client() -> None:
    global slow_light
    while True:
        with lock:
            i = next(todo, None)
        if i is None:
            return
        start = time.perf_counter()
        try:
            url = f"{args.url}/work?ms={cost(i)}"
            with urllib.request.urlopen(url, timeout=10) as resp:
                who, code = resp.headers["X-Served-By"], resp.status
        except urllib.error.HTTPError as err:  # e.g. 502 from the proxy
            who, code = "none", err.code
        except OSError:  # the proxy itself refused or dropped us
            who, code = "none", "conn-error"
        with lock:
            served[who] += 1
            status[code] += 1
            latencies.append((time.perf_counter() - start) * 1000)
            if cost(i) < 300 and latencies[-1] > 100:
                slow_light += 1  # a cheap request that waited in a queue


threads = [threading.Thread(target=client) for _ in range(args.clients)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("served by:", dict(sorted(served.items())))
print("status:   ", dict(sorted(status.items(), key=str)))
if args.clients > 1:
    latencies.sort()
    p50 = latencies[len(latencies) // 2]
    print(f"latency ms: p50 {p50:.0f}  max {latencies[-1]:.0f}")
if args.heavy_every:
    print(f"cheap requests that took over 100 ms: {slow_light}")
Terminal 1 · lb-lab/
python3 load.py 30
Expected output
served by: {'a': 10, 'b': 10, 'c': 10}
status:    {200: 30}

One client sends 30 requests in turn, and round robin gives each instance exactly 10, whichever instance it starts with.

06. Step 5: Compare policies under uneven costs

Now send 300 requests from four concurrent clients, one in ten of them expensive, with round robin, then with least_conn and random_choose 2 (power of two choices). caddy reload reads the Caddyfile again with the LB_POLICY you give it and applies it without stopping the proxy.

Terminal 1 · round robin
python3 load.py 300 --clients 4 --heavy-every 10
Illustrative output (the counts per instance are exact; timings vary)
served by: {'a': 100, 'b': 100, 'c': 100}
status:    {200: 300}
latency ms: p50 38  max 309
cheap requests that took over 100 ms: 86
Terminal 1 · least requests
LB_POLICY=least_conn caddy reload --config Caddyfile --address 127.0.0.1:18199
python3 load.py 300 --clients 4 --heavy-every 10
Illustrative output (two JSON log lines from caddy reload not shown)
served by: {'a': 85, 'b': 91, 'c': 124}
status:    {200: 300}
latency ms: p50 22  max 437
cheap requests that took over 100 ms: 23
Terminal 1 · power of two choices
LB_POLICY="random_choose 2" caddy reload --config Caddyfile --address 127.0.0.1:18199
python3 load.py 300 --clients 4 --heavy-every 10
Illustrative output (two JSON log lines from caddy reload not shown)
served by: {'a': 78, 'b': 117, 'c': 105}
status:    {200: 300}
latency ms: p50 22  max 329
cheap requests that took over 100 ms: 30

Round robin gives every instance exactly 100 requests, yet 86 cheap requests waited more than 100 ms, because it keeps sending work to an instance that is busy with a 300 ms request. Least requests used an idle instance whenever one existed, and only 23 cheap requests waited. Power of two choices landed in between: with only three instances, a random pair often leaves out the idle one. Repeated runs on the test machine moved the numbers but not the order.

The median barely changed while the slow-request count moved a lot: the tail effect from the previous lesson, measured on a real proxy.

07. Step 6: Let health checks remove a crashed instance

Go back to round robin, crash instance c with SIGKILL (it gets no chance to drain), wait three seconds for two failed health checks, then send 30 requests to each site.

Terminal 1 · lb-lab/
caddy reload --config Caddyfile --address 127.0.0.1:18199
kill -KILL "$(cat c.pid)"; sleep 3
python3 load.py 30
python3 load.py 30 --url http://127.0.0.1:18110
Expected output (reload log lines and the shell's "Killed" notice not shown)
$ python3 load.py 30
served by: {'a': 15, 'b': 15}
status:    {200: 30}
$ python3 load.py 30 --url http://127.0.0.1:18110
served by: {'a': 10, 'b': 10, 'none': 10}
status:    {200: 20, 502: 10}

On port 18100 the health checker has marked c down, so round robin alternates between a and b and every request succeeds. On port 18110 nothing has told the proxy that c is gone: every third request still goes there, the connection is refused, and Caddy answers 502 Bad Gateway. Terminal 2 shows the health checker's lines, with "msg":"HTTP request failed" and connect: connection refused for 127.0.0.1:18103. Now restart c and check that it rejoins after two passing checks:

Terminal 1 · lb-lab/
python3 app.py c 18103 > c.log 2>&1 & echo $! > c.pid; sleep 3
python3 load.py 30
Expected output
served by: {'a': 10, 'b': 10, 'c': 10}
status:    {200: 30}

08. Step 7: Drain one instance, crash another, under load

The first command sends 150 requests of 100 ms from three clients and, two seconds in, sends SIGTERM to b, which drains. Then restart b and repeat with SIGKILL on c, which crashes.

Terminal 1 · drain b
(sleep 2; kill -TERM "$(cat b.pid)") & python3 load.py 150 --clients 3 --ms 100
sleep 4; cat b.log
Illustrative output (counts and timings vary; status should show 200 only)
$ (sleep 2; kill -TERM "$(cat b.pid)") & python3 load.py 150 --clients 3 --ms 100
served by: {'a': 60, 'b': 29, 'c': 61}
status:    {200: 150}
latency ms: p50 102  max 202
$ sleep 4; cat b.log
b listening on 127.0.0.1:18102
b: SIGTERM, failing health checks
b: drained, exiting
Terminal 1 · restart b, then crash c
python3 app.py b 18102 > b.log 2>&1 & echo $! > b.pid; sleep 3
(sleep 2; kill -KILL "$(cat c.pid)") & python3 load.py 150 --clients 3 --ms 100
python3 app.py c 18103 > c.log 2>&1 & echo $! > c.pid; sleep 3
Illustrative output (the number of 502s varies from run to run)
served by: {'a': 57, 'b': 56, 'c': 18, 'none': 19}
status:    {200: 131, 502: 19}
latency ms: p50 103  max 199

The drain finished with 150 successful requests. b kept answering while its health check returned 503, Caddy stopped choosing it about two seconds later, and b closed its listener only after five seconds, when no new requests were arriving. The crash cost 19 failed requests in this run: those in progress on c when it died, plus those Caddy sent to c before two health checks had failed.

Caddy can also retry. With lb_try_duration set, a request whose connection is refused is retried on another upstream; requests that already reached an upstream are retried only for GET by default. Retries hide some crash errors but do not replace draining, because a request with side effects cannot always be sent twice safely.

09. Step 8: Sticky sessions and what they cost

First add three items to a cart with round robin, keeping cookies in jar.txt as a browser would.

Terminal 1 · no affinity
URL=http://127.0.0.1:18100/cart/add
rm -f jar.txt
for i in 1 2 3; do curl -s -b jar.txt -c jar.txt "$URL"; done
Illustrative output (the order of instances can differ)
b cart=1
c cart=1
a cart=1

Each instance has its own memory, so three requests on three instances leave three carts of one item. Now switch to Caddy's cookie policy. On the first request Caddy picks an instance (at random by default) and sets a cookie named lb whose value is an HMAC-SHA256 of that instance's address; later requests with the cookie go to the same instance while it is available.

Terminal 1 · cookie affinity
LB_POLICY=cookie caddy reload --config Caddyfile --address 127.0.0.1:18199
rm -f jar.txt
for i in 1 2 3; do curl -s -b jar.txt -c jar.txt "$URL"; done
grep -o "lb.*" jar.txt
Illustrative output (your instance and cookie value can differ)
a cart=1
a cart=2
a cart=3
lb	8ce6c3458f41ba162d5c0c014067038767e9f713d043b2ed3f27f05852b98a85

The cart now grows. Next, find the sticky instance, stop it gracefully with SIGTERM and add one more item.

Terminal 1 · stop the sticky instance
WHO=$(curl -s -b jar.txt -c jar.txt "$URL" | cut -d" " -f1)
echo "sticky instance: $WHO"
kill -TERM "$(cat "$WHO.pid")"; sleep 3
curl -s -b jar.txt -c jar.txt "$URL"
python3 load.py 30
Illustrative output (instance names can differ)
sticky instance: a
c cart=1
served by: {'b': 15, 'c': 15}
status:    {200: 30}

Even a clean drain lost the cart: once the sticky instance failed its health checks, Caddy sent the cookie's owner to another instance, which started a new cart at 1. The last command shows the other side of the policy: load.py keeps no cookies, so each request is placed at random. A client that does keep its cookie stays on one instance however much it sends, so one heavy user can overload one instance while the others idle.

10. Step 9: Clean up

Stop Caddy with Ctrl+C in terminal 2, or through the admin API as below. Then stop the instances; each one drains for five seconds before it exits.

Terminal 1 · lb-lab/
caddy stop --address 127.0.0.1:18199
for n in a b c; do kill "$(cat $n.pid)" 2>/dev/null; done; sleep 6
curl -s -m 2 http://127.0.0.1:18100/ || echo "proxy stopped"
curl -s -m 2 http://127.0.0.1:18102/health || echo "b stopped"
Expected output
proxy stopped
b stopped

11. Check your understanding

Practice check · 3 questions

Reading the lab results

Three questions about retries, drain timing and cookie affinity in this lab.

Q1. In step 6, port 18110 (no health checks) returned 10 errors in 30 requests after c crashed. Suppose you add `lb_try_duration 2s` to that site, still with no health checks, and send the same 30 GET requests. What do you expect?
Q2. Suppose you change `DRAIN_WAIT` in `app.py` from 5.0 to 0.5 and repeat the drain of b in step 7. Caddy still checks `/health` every second and needs two failures. What do you expect?
Q3. With `lb_policy cookie`, one customer runs a script that sends 50 requests per second and keeps its cookie jar. Other users are spread evenly. What do you expect on the three instances?
Practice only: not graded, not saved, not evidence.

12. Apply it

To finish the skill's practice task, write a short report from your own runs:

  1. Run step 5 three times per policy and report the median and range of the slow cheap-request count.
  2. Repeat step 7 three times for drain and for crash, and report the error rate (failed ÷ 150) for each, then repeat the crash with health checks removed from the 18100 site.
  3. Add lb_try_duration 2s to the 18100 site, repeat the crash, and explain which errors disappear and which would remain for POST requests.
  4. Stretch goal: rebuild the same setup with NGINX, HAProxy or Envoy using their documentation, and note which settings map to health_uri, health_fails and lb_policy.

13. Review prompt

Without looking back, explain why round robin gave every instance exactly the same number of requests but still made cheap requests wait. Then describe, in order, what app.py does after SIGTERM and why each step is needed, and explain why the cart was lost in step 8 even though the instance stopped cleanly.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check