TExcelTAD
Home › Web Servers in Depth: Nginx, HAProxy, Caddy & Traefik › Mini Project: A Front End for linkly

Mini Project: A Front End for linkly

linkly is the link shortener at the heart of the DevOps Capstone: POST /links stores a URL and returns a short code, GET /{code} redirects to it, /healthz and /metrics are for the platform. In this project you build its front door: a load-balanced, cached, rate-limited Nginx front end with blue/green switching, and prove each property with requests. A ~30-line Python program stands in for the real Go service.

The plan

Requirement How
Two instances per release, balanced upstream blue and upstream green, least_conn, keepalive (Upstreams)
Blue/green: switch releases instantly, no failed requests a one-line include sets $active_pool; switch = rewrite it + nginx -t + reload (Reloads)
Redirects are cached at the edge proxy_cache for GET /{code}, honouring the app's Cache-Control (Proxy Caching)
Creating links is rate-limited per client limit_req keyed only for POST with a map (Rate Limits, map)
Platform endpoints are internal /metrics only from internal networks; /healthz answered for the load balancer
Observable JSON access log with upstream and cache fields (Access Log Formats)

The build

The whole project in one session: the stand-in app, four instances, the Nginx configuration, then a test for every requirement.

bash · try it yourself
# --- 1. the linkly stand-in: links are kept in a shared JSON file so all instances agree
cat > linkly.py <<'EOF'
import json, os, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PORT, NAME = int(sys.argv[1]), sys.argv[2]
DB = "links.json"
def load(): return json.load(open(DB)) if os.path.exists(DB) else {}
class H(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    def reply(self, code, body=b"", headers=()):
        self.send_response(code)
        for k, v in [("X-Served-By", NAME), ("Content-Length", str(len(body)))] + list(headers): self.send_header(k, v)
        self.end_headers(); self.wfile.write(body)
    def do_POST(self):
        url = self.rfile.read(int(self.headers["Content-Length"])).decode().removeprefix("url=")
        links = load(); code = format(len(links) + 125, "x"); links[code] = url
        json.dump(links, open(DB, "w"))
        self.reply(201, json.dumps({"code": code}).encode() + b"\n", [("Content-Type", "application/json")])
    def do_GET(self):
        if self.path == "/healthz": return self.reply(200, b"ok\n")
        if self.path == "/metrics": return self.reply(200, b"linkly_links_total 2\n")
        target = load().get(self.path.split("?")[0].lstrip("/"))
        if target is None: return self.reply(404, b"no such link\n")
        time.sleep(0.2)                                              # pretend the database is slow
        self.reply(302, headers=[("Location", target), ("Cache-Control", "public, max-age=60")])
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
EOF
for spec in 9001:blue-1 9002:blue-2 9011:green-1 9012:green-2; do python3 linkly.py ${spec%:*} ${spec#*:} & done
for p in 9001 9002 9011 9012; do for i in $(seq 50); do curl -s 127.0.0.1:$p/healthz > /dev/null && break; sleep 0.1; done; done

# --- 2. the front end
mkdir -p conf
echo 'map "" $active_pool { default blue; }' > conf/active.conf
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  include conf/active.conf;                         # sets $active_pool: blue or green
  upstream blue  { least_conn; server 127.0.0.1:9001; server 127.0.0.1:9002; keepalive 16; }
  upstream green { least_conn; server 127.0.0.1:9011; server 127.0.0.1:9012; keepalive 16; }

  proxy_cache_path cache keys_zone=links:1m max_size=100m inactive=10m use_temp_path=off;

  map $request_method $create_key { POST $binary_remote_addr; default ""; }   # only POSTs count
  limit_req_zone $create_key zone=create:1m rate=1r/s;
  limit_req_status 429;

  log_format edge escape=json '{"method":"$request_method","uri":"$request_uri","status":$status,'
    '"upstream":"$upstream_addr","cache":"$upstream_cache_status","pool":"$active_pool"}';
  access_log access.json edge;

  server {
    listen 127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    add_header X-Pool $active_pool always;

    location = /healthz { access_log off; return 200 "edge ok\n"; }      # for the load balancer
    location = /metrics { allow 10.0.0.0/8; deny all; proxy_pass http://$active_pool; }
    location = /links {
      limit_req zone=create burst=2 nodelay;
      proxy_pass http://$active_pool;
    }
    location / {
      proxy_pass http://$active_pool;
      proxy_cache links;
      proxy_cache_lock on;
      proxy_cache_use_stale error timeout updating http_502 http_503;
      add_header X-Cache $upstream_cache_status always;
      add_header X-Pool  $active_pool always;        # repeated: add_header here drops the server-level one
    }
  }
}
EOF
nginx -t -p "$PWD" -c nginx.conf -e stderr 2>&1 | tail -1
nginx -p "$PWD" -c nginx.conf -e stderr

# --- 3. tests
E=127.0.0.1:8080
echo "== create a link"
curl -s -X POST -d 'url=https://example.com/a/very/long/path' $E/links
echo "== follow it three times (first from the app, then from the edge cache)"
for i in 1 2 3; do
  curl -s -o /dev/null -D h.txt -w '%{http_code} %{redirect_url} %{time_total}\n' $E/7d > r.txt
  awk -v c="$(grep -i '^x-cache' h.txt | cut -d' ' -f2 | tr -d '\r')" '{print $1, $2, "cache=" c, ($3 < 0.1 ? "fast (<0.1 s)" : "slow (app)")}' r.txt
done
echo "== unknown code: $(curl -s -w '[%{http_code}]' $E/nope | tr -d '\n')"
echo "== platform endpoints: healthz $(curl -s -o /dev/null -w '%{http_code}' $E/healthz), metrics $(curl -s -o /dev/null -w '%{http_code}' $E/metrics)"
sleep 2                                                  # let the create bucket refill
echo "== 6 rapid creates (burst 2, then 1 per second):"
echo "   $(for i in $(seq 6); do curl -s -o /dev/null -w '%{http_code} ' -X POST -d "url=https://example.com/$i" $E/links; done)"
sleep 3
echo "== balancing over the blue pool (uncached POSTs, within the rate limit):"
for i in 1 2 3 4; do curl -s -D - -o /dev/null -X POST -d "url=https://example.com/b$i" $E/links | grep -i '^x-served-by' | tr -d '\r'; sleep 1.1; done | sort | uniq -c

echo "== blue/green switch under load"
(for i in $(seq 40); do curl -s -o /dev/null -w '%{http_code}\n' $E/7d?n=$i; done) > during.txt &    # uncached: ~0.2 s each
sleep 0.3
echo 'map "" $active_pool { default green; }' > conf/active.conf
nginx -t -p "$PWD" -c nginx.conf -e stderr 2>/dev/null && nginx -p "$PWD" -c nginx.conf -e stderr -s reload 2>/dev/null
wait %5
echo "   40 requests during the switch: $(sort during.txt | uniq -c | xargs)"
sleep 0.5
echo "   pools that served them (access log): $(jq -r 'select(.uri | startswith("/7d?n=")) | .pool' access.json | sort -u | xargs)"
echo "   now: $(curl -s -D - -o /dev/null $E/7d?after | grep -iE '^x-(served-by|pool)' | tr -d '\r' | sed 's/-[12]$//' | xargs)"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1 %2 %3 %4
nginx: configuration file /home/learner/nginx.conf test is successful
== create a link
{"code": "7d"}
== follow it three times (first from the app, then from the edge cache)
302 https://example.com/a/very/long/path cache=MISS slow (app)
302 https://example.com/a/very/long/path cache=HIT fast (<0.1 s)
302 https://example.com/a/very/long/path cache=HIT fast (<0.1 s)
== unknown code: no such link[404]
== platform endpoints: healthz 200, metrics 403
== 6 rapid creates (burst 2, then 1 per second):
   201 201 201 429 429 429
== balancing over the blue pool (uncached POSTs, within the rate limit):
      2 X-Served-By: blue-1
      2 X-Served-By: blue-2
== blue/green switch under load
   40 requests during the switch: 40 302
   pools that served them (access log): blue green
   now: X-Served-By: green X-Pool: green

Walkthrough

  • Caching. The first GET /7d went to the app (which takes 0.2 s), and the redirect, marked Cache-Control: public, max-age=60 by the app, was stored; the next ones came from the edge in a few milliseconds instead of the app's 0.2 s. A link shortener is an ideal cache case: the redirect for a code never changes. The ?n= requests during the switch were each a separate cache key, so they really exercised the backends.
  • Rate limiting. Only POST /links has a key ($create_key is empty for other methods), so redirects are never limited. After a pause to let the bucket refill, six quick creates got one at the rate plus a burst of 2, then 429; the slower creates that follow stay within the limit.
  • Internal endpoints. /healthz is answered by Nginx itself (a load balancer in front checks the edge, not one backend), and /metrics is refused for anyone outside 10.0.0.0/8; Prometheus scrapes the instances directly.
  • Balancing. least_conn spread the creates over both blue instances.
  • Blue/green. The switch is a one-line file, validated with nginx -t before the reload. All 40 requests sent during the switch got their redirect; the access log shows that the first ones were served by blue and the rest by green, and new requests go to green (the X-Pool header). Rolling back is the same command with blue.

The X-Pool header is set twice in the configuration on purpose: location / has its own add_header (for X-Cache), which drops every inherited add_header (the inheritance rule); without the repeat, redirects would silently lose X-Pool.

Note what was not needed for the switch: no DNS change, no editing of the main configuration, no restart. Because the access log records the pool for every request, you can compare error rates between blue and green right after a switch, and switch back if green is worse.

Check from outside

On a real deployment, repeat the tests from a machine outside the network, with the real name and TLS:

bash
# Sample session against a deployed edge
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://lnk.example/7d
302 https://example.com/a/very/long/path
$ curl -sI https://lnk.example/7d | grep -iE 'x-cache|x-pool'
x-pool: green
x-cache: HIT
$ for i in $(seq 6); do curl -s -o /dev/null -w '%{http_code} ' -X POST -d url=https://example.com https://lnk.example/links; done; echo
201 201 201 429 429 429
$ curl -s -o /dev/null -w '%{http_code}\n' https://lnk.example/metrics
403

Extend it

  1. TLS and HTTP/2: add a listen 8443 ssl http2; server with a certificate from a session CA, redirect HTTP to HTTPS, add HSTS (TLS Tuning).
  2. Canary instead of blue/green: replace the map with split_clients on a cookie or $remote_addr to send 10 % to green (map & split_clients).
  3. Rebuild it in HAProxy: two backends, use_backend %[var(txn.pool)] or a map file switched through the Runtime API without any reload; rate-limit POST /links with a stick table.
  4. Rebuild it in Traefik: a weighted service for blue/green and rateLimit + chain middlewares (Traefik Middlewares).
  5. Purge on delete: add DELETE /links/{code} to the app and work out how the edge cache learns about it (short max-age, a bypass header from the app's admin tool, or versioned cache keys).

Test yourself

Why is the rate limit keyed with a map that is empty for every method except POST?

  1. POST is faster
  2. Requests with an empty key are not counted, so redirects (GET) are never limited while link creation is
  3. map is required by limit_req
  4. To cache POST requests

How does the project switch from blue to green?

  1. Changing DNS
  2. Rewriting a one-line include that sets $active_pool, checking with nginx -t, then a graceful reload
  3. Restarting Nginx
  4. Stopping the blue instances

Why does the edge answer /healthz itself instead of proxying it?

  1. To save bandwidth
  2. A load balancer in front checks whether this edge node works; it shouldn't be taken out because one backend is down
  3. Backends can't answer it
  4. Caching