feat(lab3): HAProxy LB, stateless API replicas, X-Instance-Id, Idempotency-Key, Grade 5 Track 1
This commit is contained in:
@@ -0,0 +1,444 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 4 verification suite for Lab 3:
|
||||
1. Resource limits, no exposed API ports bypassing LB, single migration execution.
|
||||
2. Cross-replica stateless sessions & shared logout.
|
||||
3. Concurrent Idempotency-Key across multiple replicas, canonical JSON replay, 409 conflict, scope isolation.
|
||||
4. Sequential failover of each API replica under load with RPS, error count, and recovery time.
|
||||
5. Rolling replacement of API replicas under active write load.
|
||||
"""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime as dt
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE_PATH = ROOT / "evidence" / "grade4_checks.json"
|
||||
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
|
||||
|
||||
def run_cmd(cmd):
|
||||
return subprocess.run(cmd, cwd=str(ROOT), text=True, capture_output=True, check=True)
|
||||
|
||||
|
||||
def http_call(method, path, body=None, raw_bytes=None, headers=None, timeout=5):
|
||||
h = {"Accept": "application/json"}
|
||||
data = raw_bytes
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw_bytes is not None:
|
||||
h["Content-Type"] = "application/json"
|
||||
if headers:
|
||||
h.update(headers)
|
||||
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
return (
|
||||
resp.code,
|
||||
{k.lower(): v for k, v in resp.headers.items()},
|
||||
json.loads(raw.decode("utf-8")) if raw else None,
|
||||
time.monotonic() - start,
|
||||
)
|
||||
except urllib.error.HTTPError as err:
|
||||
raw = err.read()
|
||||
return (
|
||||
err.code,
|
||||
{k.lower(): v for k, v in err.headers.items()},
|
||||
json.loads(raw.decode("utf-8")) if raw else None,
|
||||
time.monotonic() - start,
|
||||
)
|
||||
|
||||
|
||||
def register_and_login(label):
|
||||
username = f"g4_{label}_{uuid.uuid4().hex[:8]}"
|
||||
password = f"Grade4Pass-{uuid.uuid4().hex}"
|
||||
st, _, user, _ = http_call("POST", "/api/v1/users", {
|
||||
"username": username,
|
||||
"display_name": f"Student {label}",
|
||||
"password": password,
|
||||
})
|
||||
assert st == 201, f"register failed: {st}"
|
||||
basic = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
||||
st, _, sess, _ = http_call("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"})
|
||||
assert st == 201, f"login failed: {st}"
|
||||
return {"id": user["id"], "username": username, "token": sess["token"], "headers": {"Authorization": f"Bearer {sess['token']}"}}
|
||||
|
||||
|
||||
def wait_ready(timeout_s=45):
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
st, _, _, _ = http_call("GET", "/health/ready", timeout=2)
|
||||
if st == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("LB/API did not become ready within timeout")
|
||||
|
||||
|
||||
def get_api_containers():
|
||||
out = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.strip().splitlines()
|
||||
result = []
|
||||
for cid in out:
|
||||
cid = cid.strip()
|
||||
if not cid:
|
||||
continue
|
||||
info = json.loads(run_cmd(["docker", "inspect", cid]).stdout)[0]
|
||||
result.append({
|
||||
"id": cid,
|
||||
"short_id": cid[:12],
|
||||
"name": info["Name"].lstrip("/"),
|
||||
"hostname": info["Config"]["Hostname"],
|
||||
"running": info["State"]["Running"],
|
||||
"nano_cpus": info["HostConfig"]["NanoCpus"],
|
||||
"memory": info["HostConfig"]["Memory"],
|
||||
"ports": info["NetworkSettings"]["Ports"],
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def wait_two_instances(headers, timeout_s=30):
|
||||
deadline = time.monotonic() + timeout_s
|
||||
seen = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
st, hdrs, _, _ = http_call("GET", "/api/v1/users/me", headers=headers, timeout=2)
|
||||
if st == 200:
|
||||
inst = hdrs.get("x-instance-id", "")
|
||||
if inst:
|
||||
seen.add(inst)
|
||||
if len(seen) >= 2:
|
||||
return sorted(seen)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError(f"Expected >=2 active instances behind LB, saw {seen}")
|
||||
|
||||
|
||||
def test_infra_and_migrations():
|
||||
containers = get_api_containers()
|
||||
assert len(containers) >= 2, f"Expected >=2 API replicas, got {len(containers)}"
|
||||
for c in containers:
|
||||
assert c["nano_cpus"] > 0, f"{c['name']} missing CPU limit"
|
||||
assert c["memory"] > 0, f"{c['name']} missing Memory limit"
|
||||
for port_key, bindings in (c["ports"] or {}).items():
|
||||
assert not bindings, f"{c['name']} exposes host port {port_key}: {bindings}"
|
||||
|
||||
pg_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"]).stdout.strip()
|
||||
migs = run_cmd([
|
||||
"docker", "exec", pg_cid, "psql", "-U", "messenger", "-d", "messenger", "-tA",
|
||||
"-c", "SELECT version FROM schema_migrations ORDER BY version;",
|
||||
]).stdout.strip().splitlines()
|
||||
assert migs == ["001_init.sql", "002_idempotency.sql"], f"Unexpected schema_migrations: {migs}"
|
||||
return {
|
||||
"status": "PASS",
|
||||
"api_replicas": len(containers),
|
||||
"containers": [{"name": c["name"], "short_id": c["short_id"], "nano_cpus": c["nano_cpus"], "memory": c["memory"]} for c in containers],
|
||||
"applied_migrations": migs,
|
||||
}
|
||||
|
||||
|
||||
def test_stateless_sessions():
|
||||
alice = register_and_login("stateless")
|
||||
instances = set()
|
||||
for _ in range(30):
|
||||
st, hdrs, data, _ = http_call("GET", "/api/v1/users/me", headers=alice["headers"])
|
||||
assert st == 200 and data["id"] == alice["id"]
|
||||
instances.add(hdrs.get("x-instance-id", ""))
|
||||
assert len(instances) >= 2, f"Expected >=2 instances serving single session, saw {instances}"
|
||||
|
||||
# Logout once -> must immediately invalidate across all replicas
|
||||
st, _, _, _ = http_call("DELETE", "/api/v1/auth/sessions/current", headers=alice["headers"])
|
||||
assert st == 204
|
||||
for _ in range(10):
|
||||
st, _, _, _ = http_call("GET", "/api/v1/users/me", headers=alice["headers"])
|
||||
assert st == 401
|
||||
return {"status": "PASS", "observed_instances": sorted(instances)}
|
||||
|
||||
|
||||
def test_concurrent_idempotency():
|
||||
alice = register_and_login("idem_a")
|
||||
bob = register_and_login("idem_b")
|
||||
st, _, chat1, _ = http_call("POST", "/api/v1/chats", {
|
||||
"title": "Idempotency Race Chat 1",
|
||||
"member_ids": [alice["id"], bob["id"]],
|
||||
}, headers=alice["headers"])
|
||||
assert st == 201
|
||||
st, _, chat2, _ = http_call("POST", "/api/v1/chats", {
|
||||
"title": "Idempotency Race Chat 2",
|
||||
"member_ids": [alice["id"], bob["id"]],
|
||||
}, headers=alice["headers"])
|
||||
assert st == 201
|
||||
|
||||
shared_key = f"race-{uuid.uuid4().hex}"
|
||||
text = f"Concurrent payload {shared_key}"
|
||||
|
||||
def send_once(_i):
|
||||
return http_call("POST", f"/api/v1/chats/{chat1['id']}/messages", {"text": text}, headers={
|
||||
**alice["headers"],
|
||||
"Idempotency-Key": shared_key,
|
||||
})
|
||||
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
results = list(pool.map(send_once, range(20)))
|
||||
|
||||
msg_ids = set()
|
||||
insts = set()
|
||||
for st, hdrs, msg, _ in results:
|
||||
assert st == 201, f"Expected 201 on concurrent idempotent send, got {st}"
|
||||
msg_ids.add(msg["id"])
|
||||
insts.add(hdrs.get("x-instance-id", ""))
|
||||
assert len(msg_ids) == 1, f"Expected single message ID across 20 concurrent calls, got {msg_ids}"
|
||||
assert len(insts) >= 2, f"Expected >=2 replicas handling concurrent retries, saw {insts}"
|
||||
winning_id = next(iter(msg_ids))
|
||||
|
||||
# Canonical JSON formatting equivalence (escaped unicode / whitespace)
|
||||
escaped_text = "".join(f"\\u{ord(ch):04x}" if ch.isalpha() else ch for ch in text)
|
||||
raw_equiv = ('{ "text" : "' + escaped_text + '" }').encode("utf-8")
|
||||
st, _, msg_equiv, _ = http_call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat1['id']}/messages",
|
||||
raw_bytes=raw_equiv,
|
||||
headers={**alice["headers"], "Idempotency-Key": shared_key},
|
||||
)
|
||||
assert st == 201 and msg_equiv["id"] == winning_id, f"Canonical JSON replay mismatch: {st}"
|
||||
|
||||
# Different body with same key -> 409 conflict
|
||||
st, _, err_body, _ = http_call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat1['id']}/messages",
|
||||
{"text": text + " altered"},
|
||||
headers={**alice["headers"], "Idempotency-Key": shared_key},
|
||||
)
|
||||
assert st == 409 and err_body["error"]["code"] == "conflict", f"Expected 409 conflict, got {st}"
|
||||
|
||||
# Different user with SAME key in SAME chat -> independent message (201, new ID)
|
||||
st, _, bob_msg, _ = http_call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat1['id']}/messages",
|
||||
{"text": "Bob message with same key"},
|
||||
headers={**bob["headers"], "Idempotency-Key": shared_key},
|
||||
)
|
||||
assert st == 201 and bob_msg["id"] != winning_id
|
||||
|
||||
# Same user + same key in DIFFERENT chat -> independent message (201, new ID)
|
||||
st, _, c2_msg, _ = http_call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat2['id']}/messages",
|
||||
{"text": text},
|
||||
headers={**alice["headers"], "Idempotency-Key": shared_key},
|
||||
)
|
||||
assert st == 201 and c2_msg["id"] != winning_id
|
||||
|
||||
# Verify history of chat1 has strictly 2 messages (alice once + bob once)
|
||||
st, _, page, _ = http_call("GET", f"/api/v1/chats/{chat1['id']}/messages?limit=100", headers=alice["headers"])
|
||||
assert st == 200 and len(page["items"]) == 2, f"Expected 2 messages in chat1, got {len(page['items'])}"
|
||||
|
||||
return {
|
||||
"status": "PASS",
|
||||
"concurrent_requests": 20,
|
||||
"unique_message_ids": len(msg_ids),
|
||||
"replicas_involved": sorted(insts),
|
||||
"canonical_json_replay": "201_same_id",
|
||||
"different_body_conflict": 409,
|
||||
"scope_isolation_verified": True,
|
||||
}
|
||||
|
||||
|
||||
def stop_and_measure_failover(actor, chat, target_container, duration_s=10.0):
|
||||
stop_flag = threading.Event()
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
started = time.monotonic()
|
||||
|
||||
def worker(wid):
|
||||
idx = 0
|
||||
while not stop_flag.is_set():
|
||||
key = f"seq-{target_container['short_id']}-{wid}-{idx}"
|
||||
idx += 1
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
st, hdrs, msg, lat = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": f"Failover msg {key}",
|
||||
}, headers={**actor["headers"], "Idempotency-Key": key}, timeout=3)
|
||||
with lock:
|
||||
results.append((t0 - started, st == 201, st, hdrs.get("x-instance-id", ""), lat))
|
||||
except Exception:
|
||||
with lock:
|
||||
results.append((t0 - started, False, 0, "", time.monotonic() - t0))
|
||||
time.sleep(0.03)
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
|
||||
for th in threads:
|
||||
th.start()
|
||||
|
||||
time.sleep(1.5)
|
||||
t_stop_start = time.monotonic()
|
||||
run_cmd(["docker", "stop", "-t", "5", target_container["id"]])
|
||||
t_stop_done = time.monotonic()
|
||||
|
||||
# Continue load after stop
|
||||
time.sleep(duration_s - 1.5)
|
||||
stop_flag.set()
|
||||
for th in threads:
|
||||
th.join()
|
||||
|
||||
total = len(results)
|
||||
ok = [r for r in results if r[1]]
|
||||
errs = [r for r in results if not r[1]]
|
||||
# Find recovery window: last error timestamp relative to stop start (or 0 if 0 errors)
|
||||
post_stop_errs = [r[0] - (t_stop_start - started) for r in errs if r[0] >= (t_stop_start - started)]
|
||||
recovery_s = max(post_stop_errs) if post_stop_errs else 0.0
|
||||
after_stop_insts = sorted({r[3] for r in ok if r[0] > (t_stop_done - started) + 2.0 and r[3]})
|
||||
assert target_container["short_id"] not in after_stop_insts, f"Stopped container still served after 2s: {after_stop_insts}"
|
||||
|
||||
return {
|
||||
"stopped_container": target_container["name"],
|
||||
"stopped_short_id": target_container["short_id"],
|
||||
"stop_duration_s": round(t_stop_done - t_stop_start, 3),
|
||||
"total_requests": total,
|
||||
"successful_writes": len(ok),
|
||||
"failed_requests": len(errs),
|
||||
"error_rate": round(len(errs) / total, 5) if total else 0.0,
|
||||
"rps": round(len(ok) / duration_s, 2),
|
||||
"recovery_seconds_after_stop": round(max(0.0, recovery_s), 3),
|
||||
"serving_instances_after_failover": after_stop_insts,
|
||||
}
|
||||
|
||||
|
||||
def test_sequential_failover():
|
||||
alice = register_and_login("seq_fail")
|
||||
st, _, chat, _ = http_call("POST", "/api/v1/chats", {
|
||||
"title": "Sequential Failover Chat",
|
||||
"member_ids": [alice["id"]],
|
||||
}, headers=alice["headers"])
|
||||
assert st == 201
|
||||
|
||||
wait_two_instances(alice["headers"])
|
||||
containers = get_api_containers()
|
||||
assert len(containers) == 2
|
||||
|
||||
step1 = stop_and_measure_failover(alice, chat, containers[0], duration_s=10.0)
|
||||
run_cmd(["docker", "start", containers[0]["id"]])
|
||||
wait_two_instances(alice["headers"])
|
||||
|
||||
step2 = stop_and_measure_failover(alice, chat, containers[1], duration_s=10.0)
|
||||
run_cmd(["docker", "start", containers[1]["id"]])
|
||||
wait_two_instances(alice["headers"])
|
||||
|
||||
return {"status": "PASS", "replica_1_failover": step1, "replica_2_failover": step2}
|
||||
|
||||
|
||||
def test_rolling_update():
|
||||
alice = register_and_login("rolling")
|
||||
st, _, chat, _ = http_call("POST", "/api/v1/chats", {
|
||||
"title": "Rolling Update Chat",
|
||||
"member_ids": [alice["id"]],
|
||||
}, headers=alice["headers"])
|
||||
assert st == 201
|
||||
|
||||
wait_two_instances(alice["headers"])
|
||||
old_containers = get_api_containers()
|
||||
old_ids = [c["id"] for c in old_containers]
|
||||
|
||||
stop_flag = threading.Event()
|
||||
stats = {"ok": 0, "err": 0, "insts": set()}
|
||||
lock = threading.Lock()
|
||||
|
||||
def writer(wid):
|
||||
idx = 0
|
||||
while not stop_flag.is_set():
|
||||
key = f"roll-{wid}-{idx}"
|
||||
idx += 1
|
||||
try:
|
||||
st_c, hdrs, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
||||
"text": f"Rolling msg {key}",
|
||||
}, headers={**alice["headers"], "Idempotency-Key": key}, timeout=4)
|
||||
with lock:
|
||||
if st_c == 201:
|
||||
stats["ok"] += 1
|
||||
stats["insts"].add(hdrs.get("x-instance-id", ""))
|
||||
else:
|
||||
stats["err"] += 1
|
||||
except Exception:
|
||||
with lock:
|
||||
stats["err"] += 1
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=writer, args=(i,)) for i in range(4)]
|
||||
for th in threads:
|
||||
th.start()
|
||||
|
||||
try:
|
||||
# Step 1: Surge capacity 2 -> 3 before replacing old replicas one by one
|
||||
run_cmd(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--scale", "api=3", "--no-recreate", "api"])
|
||||
time.sleep(3.5)
|
||||
|
||||
# Step 2: Gracefully replace each old replica one at a time
|
||||
for cid in old_ids:
|
||||
run_cmd(["docker", "stop", "-t", "8", cid])
|
||||
run_cmd(["docker", "rm", cid])
|
||||
run_cmd(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--scale", "api=3", "--no-recreate", "api"])
|
||||
time.sleep(3.5)
|
||||
|
||||
# Step 3: Scale back down cleanly 3 -> 2
|
||||
current = get_api_containers()
|
||||
extra = [c for c in current if c["id"] not in old_ids][-1]
|
||||
run_cmd(["docker", "stop", "-t", "8", extra["id"]])
|
||||
run_cmd(["docker", "rm", extra["id"]])
|
||||
finally:
|
||||
stop_flag.set()
|
||||
for th in threads:
|
||||
th.join()
|
||||
|
||||
new_ids = sorted(c["short_id"] for c in get_api_containers())
|
||||
assert set(new_ids).isdisjoint({c["short_id"] for c in old_containers}), "Old containers were not all replaced"
|
||||
total = stats["ok"] + stats["err"]
|
||||
return {
|
||||
"status": "PASS",
|
||||
"old_replicas": [c["short_id"] for c in old_containers],
|
||||
"new_replicas": new_ids,
|
||||
"total_requests_during_rollout": total,
|
||||
"successful_writes": stats["ok"],
|
||||
"failed_requests": stats["err"],
|
||||
"error_rate": round(stats["err"] / total, 5) if total else 0.0,
|
||||
"observed_serving_instances": sorted(x for x in stats["insts"] if x),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
wait_ready()
|
||||
report = {
|
||||
"timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"base_url": BASE_URL,
|
||||
"checks": {},
|
||||
}
|
||||
report["checks"]["infra_and_migrations"] = test_infra_and_migrations()
|
||||
print("PASS: infra_and_migrations")
|
||||
report["checks"]["stateless_sessions"] = test_stateless_sessions()
|
||||
print("PASS: stateless_sessions")
|
||||
report["checks"]["concurrent_idempotency"] = test_concurrent_idempotency()
|
||||
print("PASS: concurrent_idempotency")
|
||||
report["checks"]["sequential_failover"] = test_sequential_failover()
|
||||
print("PASS: sequential_failover")
|
||||
report["checks"]["rolling_update"] = test_rolling_update()
|
||||
print("PASS: rolling_update")
|
||||
|
||||
EVIDENCE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
EVIDENCE_PATH.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS: all Grade 4 checks succeeded; evidence saved to {EVIDENCE_PATH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,372 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 5 Track 1: Cost of Scaling experiment for Lab 3.
|
||||
Measures:
|
||||
- Series A: Fixed total API resource budget (2.0 CPU, 512M RAM) across 1/2/4 replicas.
|
||||
- Series B: Scaling with resource growth (0.5 CPU, 256M RAM per replica) against 0.5 CPU DB to locate saturation point.
|
||||
- Series C: Confirmed optimization at 4-replica saturation (WRITE_MODE=sequential, DB_MAX_CONNS=25 -> WRITE_MODE=pipeline, DB_MAX_CONNS=8).
|
||||
Restores the default 2-replica stand on completion.
|
||||
"""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime as dt
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE_JSON = ROOT / "evidence" / "track1_scaling.json"
|
||||
EVIDENCE_SVG = ROOT / "evidence" / "track1_scaling_chart.svg"
|
||||
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
|
||||
|
||||
def run_cmd(cmd, env=None):
|
||||
merged_env = os.environ.copy()
|
||||
if env:
|
||||
merged_env.update(env)
|
||||
return subprocess.run(cmd, cwd=str(ROOT), env=merged_env, text=True, capture_output=True, check=True)
|
||||
|
||||
|
||||
def wait_ready(min_replicas=1, timeout_s=60):
|
||||
parsed = urllib.parse.urlparse(BASE_URL)
|
||||
host = parsed.hostname or "localhost"
|
||||
port = parsed.port or 80
|
||||
deadline = time.monotonic() + timeout_s
|
||||
seen = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
conn = http.client.HTTPConnection(host, port, timeout=2)
|
||||
conn.request("GET", "/health/ready")
|
||||
resp = conn.getresponse()
|
||||
_ = resp.read()
|
||||
if resp.status == 200:
|
||||
inst = resp.getheader("X-Instance-Id", "")
|
||||
if inst:
|
||||
seen.add(inst)
|
||||
if len(seen) >= min_replicas:
|
||||
conn.close()
|
||||
return sorted(seen)
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
raise RuntimeError(f"Expected >= {min_replicas} ready replicas, observed {seen}")
|
||||
|
||||
|
||||
def apply_topology(replicas, api_cpu, api_mem, db_cpu, db_mem, db_max_conns, write_mode):
|
||||
env_overrides = {
|
||||
"API_REPLICAS": str(replicas),
|
||||
"API_CPU_LIMIT": str(api_cpu),
|
||||
"API_MEM_LIMIT": str(api_mem),
|
||||
"DB_CPU_LIMIT": str(db_cpu),
|
||||
"DB_MEM_LIMIT": str(db_mem),
|
||||
"DB_MAX_CONNS": str(db_max_conns),
|
||||
"WRITE_MODE": str(write_mode),
|
||||
}
|
||||
run_cmd(
|
||||
["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--force-recreate", "--scale", f"api={replicas}", "postgres", "api"],
|
||||
env=env_overrides,
|
||||
)
|
||||
run_cmd(["docker", "compose", "--env-file", ".env", "restart", "lb"], env=env_overrides)
|
||||
time.sleep(2.0)
|
||||
return wait_ready(min_replicas=replicas, timeout_s=60)
|
||||
|
||||
|
||||
def sample_docker_stats():
|
||||
out = run_cmd(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"]).stdout.strip().splitlines()
|
||||
stats = {}
|
||||
for line in out:
|
||||
parts = line.split("\t")
|
||||
if len(parts) != 3:
|
||||
continue
|
||||
name, cpu, mem = parts
|
||||
if not name.startswith("lab3-"):
|
||||
continue
|
||||
stats[name] = {"cpu": cpu.strip(), "mem": mem.strip()}
|
||||
return stats
|
||||
|
||||
|
||||
def percentile(sorted_vals, p):
|
||||
if not sorted_vals:
|
||||
return None
|
||||
idx = max(0, math.ceil(p * len(sorted_vals)) - 1)
|
||||
return round(sorted_vals[idx] * 1000.0, 3)
|
||||
|
||||
|
||||
def bootstrap_actor(host, port):
|
||||
conn = http.client.HTTPConnection(host, port, timeout=10)
|
||||
uname = f"bench_{uuid.uuid4().hex[:10]}"
|
||||
pw = f"ScaleBench-{uuid.uuid4().hex}"
|
||||
body = json.dumps({"username": uname, "display_name": "Bench", "password": pw}).encode("utf-8")
|
||||
conn.request("POST", "/api/v1/users", body, {"Content-Type": "application/json", "Accept": "application/json"})
|
||||
r1 = conn.getresponse()
|
||||
u = json.loads(r1.read().decode("utf-8"))
|
||||
assert r1.status == 201
|
||||
|
||||
basic = base64.b64encode(f"{uname}:{pw}".encode("utf-8")).decode("ascii")
|
||||
conn.request("POST", "/api/v1/auth/sessions", None, {"Authorization": f"Basic {basic}", "Accept": "application/json"})
|
||||
r2 = conn.getresponse()
|
||||
s = json.loads(r2.read().decode("utf-8"))
|
||||
assert r2.status == 201
|
||||
|
||||
chat_body = json.dumps({"title": "Scale Chat", "member_ids": [u["id"]]}).encode("utf-8")
|
||||
conn.request("POST", "/api/v1/chats", chat_body, {
|
||||
"Authorization": f"Bearer {s['token']}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
})
|
||||
r3 = conn.getresponse()
|
||||
chat = json.loads(r3.read().decode("utf-8"))
|
||||
assert r3.status == 201
|
||||
|
||||
# Seed one message so GET /messages returns data immediately
|
||||
msg_body = json.dumps({"text": "Initial message"}).encode("utf-8")
|
||||
conn.request("POST", f"/api/v1/chats/{chat['id']}/messages", msg_body, {
|
||||
"Authorization": f"Bearer {s['token']}",
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": f"init-{uuid.uuid4().hex}",
|
||||
})
|
||||
r4 = conn.getresponse()
|
||||
_ = r4.read()
|
||||
assert r4.status == 201
|
||||
conn.close()
|
||||
return {"username": uname, "basic": basic, "token": s["token"], "chat_id": chat["id"]}
|
||||
|
||||
|
||||
def run_benchmark(label, concurrency=20, warmup_s=2.0, duration_s=10.0, login_every=20):
|
||||
"""Mixed messenger workload:
|
||||
- 1 in `login_every` (5%): POST /api/v1/auth/sessions (Argon2id CPU bound)
|
||||
- ~75%: POST /api/v1/chats/{id}/messages (DB transactional write + Idempotency-Key + Redis INCR)
|
||||
- ~20%: GET /api/v1/chats/{id}/messages?limit=20 (Redis/DB read)
|
||||
"""
|
||||
parsed = urllib.parse.urlparse(BASE_URL)
|
||||
host = parsed.hostname or "localhost"
|
||||
port = parsed.port or 80
|
||||
|
||||
actor = bootstrap_actor(host, port)
|
||||
barrier = threading.Barrier(concurrency + 2)
|
||||
stop_at = time.monotonic() + warmup_s + duration_s + 0.2
|
||||
record_after = time.monotonic() + warmup_s
|
||||
|
||||
captured_stats = {}
|
||||
stats_done = threading.Event()
|
||||
|
||||
def stats_sampler():
|
||||
barrier.wait()
|
||||
time.sleep(warmup_s + duration_s * 0.5)
|
||||
try:
|
||||
captured_stats.update(sample_docker_stats())
|
||||
except Exception as exc:
|
||||
captured_stats["error"] = str(exc)
|
||||
stats_done.set()
|
||||
|
||||
def worker(wid):
|
||||
conn = http.client.HTTPConnection(host, port, timeout=10)
|
||||
latencies = []
|
||||
write_latencies = []
|
||||
errors = 0
|
||||
insts = set()
|
||||
i = 0
|
||||
barrier.wait()
|
||||
while time.monotonic() < stop_at:
|
||||
t0 = time.monotonic()
|
||||
ok = False
|
||||
is_write = False
|
||||
try:
|
||||
if i % login_every == 0:
|
||||
conn.request("POST", "/api/v1/auth/sessions", None, {
|
||||
"Authorization": f"Basic {actor['basic']}",
|
||||
"Accept": "application/json",
|
||||
})
|
||||
resp = conn.getresponse()
|
||||
_ = resp.read()
|
||||
ok = resp.status == 201
|
||||
elif i % 5 == 1:
|
||||
conn.request("GET", f"/api/v1/chats/{actor['chat_id']}/messages?limit=20", None, {
|
||||
"Authorization": f"Bearer {actor['token']}",
|
||||
"Accept": "application/json",
|
||||
})
|
||||
resp = conn.getresponse()
|
||||
_ = resp.read()
|
||||
ok = resp.status == 200
|
||||
else:
|
||||
is_write = True
|
||||
payload = json.dumps({"text": f"m-{wid}-{i}"}).encode("utf-8")
|
||||
conn.request("POST", f"/api/v1/chats/{actor['chat_id']}/messages", payload, {
|
||||
"Authorization": f"Bearer {actor['token']}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"Idempotency-Key": f"k-{wid}-{i}-{uuid.uuid4().hex[:8]}",
|
||||
})
|
||||
resp = conn.getresponse()
|
||||
_ = resp.read()
|
||||
ok = resp.status == 201
|
||||
inst = resp.getheader("X-Instance-Id", "")
|
||||
if inst:
|
||||
insts.add(inst)
|
||||
except Exception:
|
||||
ok = False
|
||||
try:
|
||||
conn.close()
|
||||
conn = http.client.HTTPConnection(host, port, timeout=10)
|
||||
except Exception:
|
||||
pass
|
||||
t1 = time.monotonic()
|
||||
if t0 >= record_after:
|
||||
if ok:
|
||||
lat = t1 - t0
|
||||
latencies.append(lat)
|
||||
if is_write:
|
||||
write_latencies.append(lat)
|
||||
else:
|
||||
errors += 1
|
||||
i += 1
|
||||
conn.close()
|
||||
return latencies, write_latencies, errors, insts
|
||||
|
||||
sampler_th = threading.Thread(target=stats_sampler)
|
||||
sampler_th.start()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
futs = [pool.submit(worker, wid) for wid in range(concurrency)]
|
||||
barrier.wait()
|
||||
res = [f.result() for f in futs]
|
||||
sampler_th.join()
|
||||
|
||||
all_lat = sorted(x for lat, _, _, _ in res for x in lat)
|
||||
w_lat = sorted(x for _, wl, _, _ in res for x in wl)
|
||||
total_err = sum(e for _, _, e, _ in res)
|
||||
all_inst = sorted({inst for _, _, _, insts in res for inst in insts})
|
||||
total_ok = len(all_lat)
|
||||
rps = round(total_ok / duration_s, 2)
|
||||
|
||||
result = {
|
||||
"label": label,
|
||||
"concurrency": concurrency,
|
||||
"warmup_s": warmup_s,
|
||||
"duration_s": duration_s,
|
||||
"successful_requests": total_ok,
|
||||
"failed_requests": total_err,
|
||||
"error_rate": round(total_err / (total_ok + total_err), 5) if (total_ok + total_err) else 0.0,
|
||||
"successful_rps": rps,
|
||||
"latency_ms": {
|
||||
"p50": percentile(all_lat, 0.50),
|
||||
"p95": percentile(all_lat, 0.95),
|
||||
"p99": percentile(all_lat, 0.99),
|
||||
},
|
||||
"write_latency_ms": {
|
||||
"p50": percentile(w_lat, 0.50),
|
||||
"p95": percentile(w_lat, 0.95),
|
||||
"p99": percentile(w_lat, 0.99),
|
||||
},
|
||||
"observed_instances": all_inst,
|
||||
"container_stats_midpoint": captured_stats,
|
||||
}
|
||||
print(f"[{label}] RPS={rps} ok={total_ok} err={total_err} p50={result['latency_ms']['p50']}ms p95={result['latency_ms']['p95']}ms p99={result['latency_ms']['p99']}ms instances={len(all_inst)}", flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def generate_svg_chart(series_a, series_b, improvement):
|
||||
# Clean SVG bar chart comparing Series A (Fixed Budget), Series B (Scaling + Saturation), Series C (Improvement)
|
||||
items = (
|
||||
[("A: 1x2.0c", series_a[0]["successful_rps"], "#3b82f6"),
|
||||
("A: 2x1.0c", series_a[1]["successful_rps"], "#3b82f6"),
|
||||
("A: 4x0.5c", series_a[2]["successful_rps"], "#3b82f6"),
|
||||
("B: 1x0.5c", series_b[0]["successful_rps"], "#10b981"),
|
||||
("B: 2x0.5c", series_b[1]["successful_rps"], "#10b981"),
|
||||
("B: 4x0.5c", series_b[2]["successful_rps"], "#f59e0b"),
|
||||
("Opt: 4x0.5c", improvement["after"]["successful_rps"], "#8b5cf6")]
|
||||
)
|
||||
max_rps = max(v for _, v, _ in items) or 100.0
|
||||
width, height = 780, 360
|
||||
pad_l, pad_b, pad_t = 70, 65, 50
|
||||
chart_w = width - pad_l - 40
|
||||
chart_h = height - pad_b - pad_t
|
||||
bar_w = 64
|
||||
gap = (chart_w - len(items) * bar_w) / (len(items) + 1)
|
||||
|
||||
lines = [
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" style="background:#ffffff;font-family:sans-serif">',
|
||||
' <text x="390" y="28" text-anchor="middle" font-size="16" font-weight="bold" fill="#111827">Lab 3 Track 1: Cost of Scaling & Saturation Point (RPS)</text>',
|
||||
f' <line x1="{pad_l}" y1="{pad_t}" x2="{pad_l}" y2="{pad_t + chart_h}" stroke="#9ca3af" stroke-width="1"/>',
|
||||
f' <line x1="{pad_l}" y1="{pad_t + chart_h}" x2="{width - 30}" y2="{pad_t + chart_h}" stroke="#9ca3af" stroke-width="1"/>',
|
||||
]
|
||||
for i in range(5):
|
||||
y = pad_t + chart_h - (chart_h * i / 4.0)
|
||||
val = int(round(max_rps * i / 4.0))
|
||||
lines.append(f' <line x1="{pad_l}" y1="{y:.1f}" x2="{width - 30}" y2="{y:.1f}" stroke="#e5e7eb" stroke-width="1"/>')
|
||||
lines.append(f' <text x="{pad_l - 8}" y="{y + 4:.1f}" text-anchor="end" font-size="11" fill="#4b5563">{val}</text>')
|
||||
|
||||
for idx, (label, val, color) in enumerate(items):
|
||||
x = pad_l + gap + idx * (bar_w + gap)
|
||||
bh = (val / max_rps) * chart_h * 0.92
|
||||
y = pad_t + chart_h - bh
|
||||
lines.append(f' <rect x="{x:.1f}" y="{y:.1f}" width="{bar_w}" height="{bh:.1f}" rx="4" fill="{color}"/>')
|
||||
lines.append(f' <text x="{x + bar_w / 2:.1f}" y="{y - 6:.1f}" text-anchor="middle" font-size="11" font-weight="bold" fill="#111827">{val:.1f}</text>')
|
||||
lines.append(f' <text x="{x + bar_w / 2:.1f}" y="{pad_t + chart_h + 18}" text-anchor="middle" font-size="11" fill="#374151">{label}</text>')
|
||||
|
||||
lines.append(' <text x="390" y="346" text-anchor="middle" font-size="11" fill="#6b7280">Blue: Fixed 2.0 CPU Budget | Green: Resource Growth | Orange: DB Saturation | Purple: Batch Pipeline + Pool Tuning</text>')
|
||||
lines.append("</svg>")
|
||||
EVIDENCE_SVG.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main():
|
||||
report = {
|
||||
"timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"base_url": BASE_URL,
|
||||
"series_a_fixed_budget": [],
|
||||
"series_b_resource_growth": [],
|
||||
"confirmed_improvement": {},
|
||||
}
|
||||
|
||||
try:
|
||||
# Series A: Fixed total API CPU=2.0, RAM=512M, DB=1.0 CPU
|
||||
print("=== Series A: Fixed Total Budget (2.0 CPU, 512M RAM) ===")
|
||||
for replicas, cpu, mem in [(1, "2.0", "512M"), (2, "1.0", "256M"), (4, "0.5", "128M")]:
|
||||
apply_topology(replicas, cpu, mem, db_cpu="1.0", db_mem="512M", db_max_conns=12, write_mode="pipeline")
|
||||
res = run_benchmark(f"A_fixed_{replicas}x{cpu}cpu", concurrency=16, warmup_s=2.0, duration_s=10.0)
|
||||
res["config"] = {"replicas": replicas, "api_cpu": cpu, "api_mem": mem, "db_cpu": "1.0", "db_max_conns": 12, "write_mode": "pipeline"}
|
||||
report["series_a_fixed_budget"].append(res)
|
||||
|
||||
# Series B: Resource growth per replica (0.5 CPU, 256M RAM each) vs DB=0.5 CPU (unoptimized sequential + pool=25)
|
||||
print("=== Series B: Scaling with Resource Growth (0.5 CPU/replica vs 0.5 CPU DB) ===")
|
||||
for replicas in [1, 2, 4]:
|
||||
apply_topology(replicas, "0.5", "256M", db_cpu="0.5", db_mem="256M", db_max_conns=25, write_mode="sequential")
|
||||
res = run_benchmark(f"B_growth_{replicas}x0.5cpu", concurrency=20, warmup_s=2.0, duration_s=10.0)
|
||||
res["config"] = {"replicas": replicas, "api_cpu": "0.5", "api_mem": "256M", "db_cpu": "0.5", "db_max_conns": 25, "write_mode": "sequential"}
|
||||
report["series_b_resource_growth"].append(res)
|
||||
|
||||
# Series C: Confirmed Improvement at 4-replica saturation point (same 4x0.5 CPU API vs 0.5 CPU DB)
|
||||
print("=== Series C: Confirmed Improvement at 4-replica Saturation ===")
|
||||
before = report["series_b_resource_growth"][-1]
|
||||
apply_topology(4, "0.5", "256M", db_cpu="0.5", db_mem="256M", db_max_conns=8, write_mode="pipeline")
|
||||
after = run_benchmark("C_optimized_4x0.5cpu", concurrency=20, warmup_s=2.0, duration_s=10.0)
|
||||
after["config"] = {"replicas": 4, "api_cpu": "0.5", "api_mem": "256M", "db_cpu": "0.5", "db_max_conns": 8, "write_mode": "pipeline"}
|
||||
|
||||
rps_gain_pct = round(((after["successful_rps"] - before["successful_rps"]) / before["successful_rps"]) * 100.0, 2)
|
||||
p95_delta_pct = round(((after["latency_ms"]["p95"] - before["latency_ms"]["p95"]) / before["latency_ms"]["p95"]) * 100.0, 2)
|
||||
report["confirmed_improvement"] = {
|
||||
"change": "Enabled pgx.Batch SQL pipelining in CreateMessage tx (5 RTT -> 2 RTT) and tuned DB_MAX_CONNS per replica (25 -> 8, limiting total connections from 100 to 32 against 0.5 CPU PostgreSQL)",
|
||||
"before": before,
|
||||
"after": after,
|
||||
"rps_change_percent": rps_gain_pct,
|
||||
"p95_latency_change_percent": p95_delta_pct,
|
||||
}
|
||||
|
||||
EVIDENCE_JSON.parent.mkdir(parents=True, exist_ok=True)
|
||||
EVIDENCE_JSON.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
generate_svg_chart(report["series_a_fixed_budget"], report["series_b_resource_growth"], report["confirmed_improvement"])
|
||||
print(f"PASS: Track 1 scaling benchmark complete. RPS delta: {rps_gain_pct:+.2f}%, p95 delta: {p95_delta_pct:+.2f}%")
|
||||
finally:
|
||||
print("Restoring default 2-replica Lab 3 topology...")
|
||||
apply_topology(2, "1.0", "256M", db_cpu="1.0", db_mem="512M", db_max_conns=12, write_mode="pipeline")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user