Document scaling experiment, measured database boundary and verified failure recovery

This commit is contained in:
2026-11-06 18:16:18 +03:00
parent 029bf9b377
commit a0ca0af168
52 changed files with 28893 additions and 95 deletions
+48
View File
@@ -0,0 +1,48 @@
# Трек1 — цена масштабирования
Гипотеза: при общей ограниченной PostgreSQL рост числа API не даёт линейного роста подтверждённых записей. Выделение CPU общей БД должно повысить пропускную способность, если именно её квота является активным ограничением.
## Повторение
Из корня отдельного репозитория, без других нагрузок на Docker-хосте:
```sh
make up
uv sync --locked --python 3.12
uv run --locked python research/run.py --duration 6 --rates 100,400,900 --repeats 3 --output evidence/scaling-repeat.json
uv run --locked python research/analyze.py evidence/scaling-repeat.json
```
Скрипт создаёт синтетические данные. Существующие данные не удаляются. После опыта возвращает штатные2API,0.5CPU/256MiBкаждая, PostgreSQL1CPU/768MiB. Не запускайте одновременно тесты отказов, другие labs, backup или компиляцию. Сессия должна успеть остаться действительной на протяжении опыта.
## Матрица
1. Fixed-total: 1/2/4API, суммарно1CPU и1024MiB (1×1CPU/1024,2×0.5/512,4×0.25/256).
2. Growth: 1/2/4API, по0.5CPU/256MiB на процесс.
3. Controlled improvement: те же4API по0.5CPU/256MiB; CPU PostgreSQL0.25→0.5, RAM768MiB неизменна.
БД в исходной матрице **намеренно** ограничена0.25CPU, чтобы экспериментально установить её ресурсную границу. Это не утверждение о максимальной производительности PostgreSQL или штатного стенда.
Для каждой конфигурации offered rates100/400/900POST/s, три повтора по6s, порядок скоростей чередуется. Fresh chat на каждый прогон; одинаковые пользователь, авторизация, payload и семантика уникальных Idempotency-Key. Короткая история растёт внутри прогона; накопление строк в общей БД и checkpoint могут влиять на результат.
## Генератор и метрики
Собственный asyncio/aiohttp open-loop генератор с keepalive. Планирует определённое число запросов по времени, не ждёт окончания предыдущего. При128in-flight или отставании планировщика>250ms слот считается dropped, скрытая бесконечная очередь не создаётся. Таймаут6s; прозрачных повторов нет.
Сохраняются scheduled, attempted, successful201, ошибки по классам/HTTPкоду, dropped, schedulerlag, successfulRPS и attemptedRPS отдельно. RPS считается по реальному времени, включающему завершение отправленных запросов. Percentiles включают только успешные запросы, поэтому при ошибках/дропах их нельзя читать отдельно от этих счётчиков.
Docker inspect сохраняет actual CPU/RAM каждой API и БД, проверяются точные значения и число реплик. Docker stats сохраняет исходные временные samples всех сервисов. CPU складывается по API на одном timestamp, память тоже суммируется, затем агрегируется — не усредняется между репликами.
## Ограничения
Один Docker Desktop хост, короткие локальные серии и ограниченный генератор. Schedulerlag/drops ограничивают интерпретацию offered ceiling. Для вывода о DBquota нужны совместно: достигнутая CPUквота БД, плато при ростеAPI/нагрузки и контролируемое улучшение при изменении **только** CPU БД. Внешнюю сеть, отказ узла, репликацию БД, промышленный SLA и exactly-once доставку опыт не доказывает.
Первичные источники: [HAProxy3.2](https://docs.haproxy.org/3.2/configuration.html), [Compose service specification](https://docs.docker.com/reference/compose-file/services/).
## Калибровка генератора
HTTPxpilot при300offered/s показал schedulerlag312ms и633drops. Он исключён из основной матрицы. В окончательном генераторе aiohttp при900offered/s на4API driverCPU составлял0.174/0.316одногоядра, scheduler drops0; рост PGquota0.25→0.5 дал380.165→879.395successfulRPS. Это калибровка, отдельная от63измерений основной матрицы; сырые pilotфайлы сохранены.
## Дополнительный обратный контроль
После основной матрицы `uv run --locked python research/reversal.py` возвращает PostgreSQL0.25CPUпри техже4API, выполняет3×6sна900offered/s и восстанавливает штатный стенд. Результат отдельно в evidence/scaling-reversal.json, в63основных прогона он не включается. После основного опыта CPUконтроль далмедиану465.411RPSпротив881.06при0.5CPU, что снижает риск объяснить выигрыш только поздним прогревом.
+166
View File
@@ -0,0 +1,166 @@
"""Summarize successes separately from offered/attempted requests and sum replica resources."""
import json
import re
import statistics
import sys
from collections import defaultdict
from pathlib import Path
def memory_bytes(text):
value, unit = re.fullmatch(r"([0-9.]+)([A-Za-z]+)", text.strip()).groups()
factors = {
"B": 1,
"KiB": 1024,
"MiB": 1024**2,
"GiB": 1024**3,
"kB": 1000,
"MB": 1000**2,
"GB": 1000**3,
}
return float(value) * factors[unit]
def resource_summary(run):
cpu, ram, db_cpu, lb_cpu = [], [], [], []
by_id = {c["id"][:12]: c["service"] for c in run["actual_containers"]}
for sample in run["resource_samples"]:
api_cpu = api_ram = 0
for row in sample["containers"]:
role = by_id.get(row["ID"][:12])
percent = float(row["CPUPerc"].rstrip("%"))
if role == "api":
api_cpu += percent
api_ram += memory_bytes(row["MemUsage"].split("/")[0].strip())
elif role == "postgres":
db_cpu.append(percent)
elif role == "lb":
lb_cpu.append(percent)
cpu.append(api_cpu)
ram.append(api_ram / 1024**2)
return {
"mean_api_cpu_percent_sum": statistics.mean(cpu) if cpu else None,
"max_api_memory_mib_sum": max(ram, default=0),
"mean_db_cpu_percent": statistics.mean(db_cpu) if db_cpu else None,
"mean_lb_cpu_percent": statistics.mean(lb_cpu) if lb_cpu else None,
}
def main():
source = Path(sys.argv[1])
data = json.loads(source.read_text())
groups = defaultdict(list)
for run in data["runs"]:
assert run["scheduled"] == run["attempted"] + run["dropped"]
assert run["attempted"] == run["successful"] + sum(run["errors"].values())
run["resources"] = resource_summary(run)
groups[run["configuration"], run["offered_rate"]].append(run)
rows = []
for (name, rate), runs in groups.items():
row = {
"configuration": name,
"offered_rate": rate,
"repeats": len(runs),
"median_successful_rps": statistics.median(r["successful_rps"] for r in runs),
"median_p95_ms": statistics.median(r["latency_success_ms"]["p95"] for r in runs),
"total_successful": sum(r["successful"] for r in runs),
"total_errors": sum(sum(r["errors"].values()) for r in runs),
"total_dropped": sum(r["dropped"] for r in runs),
"total_scheduler_dropped": sum(r["dropped_scheduler"] for r in runs),
"max_driver_cpu_fraction": max(r["driver_cpu_fraction_one_core"] for r in runs),
"total_scheduled": sum(r["scheduled"] for r in runs),
"median_db_cpu_percent": statistics.median(
r["resources"]["mean_db_cpu_percent"] for r in runs
),
"median_api_cpu_percent_sum": statistics.median(
r["resources"]["mean_api_cpu_percent_sum"] for r in runs
),
"max_api_memory_mib_sum": max(r["resources"]["max_api_memory_mib_sum"] for r in runs),
}
rows.append(row)
dest = source.with_name(source.stem + "-summary.json")
dest.write_text(json.dumps(rows, indent=2) + "\n")
text = [
"# Scaling results",
"",
"CPU%: 100% means one logical CPU. Memory is summed Docker MemUsage, not heap RSS.",
"",
"|Configuration|Offered/s|Success/s median|p95 ms median|Errors total|Dropped total|DB CPU% median|API CPU% sum median|API peak MiB sum|",
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
]
for row in rows:
text.append(
"|{configuration}|{offered_rate}|{median_successful_rps:.2f}|{median_p95_ms:.2f}|{total_errors}|{total_dropped}|{median_db_cpu_percent:.2f}|{median_api_cpu_percent_sum:.2f}|{max_api_memory_mib_sum:.2f}|".format(
**row
)
)
source.with_name(source.stem + "-summary.md").write_text("\n".join(text) + "\n")
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(15, 4), constrained_layout=True)
for ax, series in zip(axes[:2], ["fixed", "growth"], strict=True):
for name in [f"{series}-{n}" for n in [1, 2, 4]]:
points = sorted(
[r for r in rows if r["configuration"] == name], key=lambda r: r["offered_rate"]
)
ax.plot(
[p["offered_rate"] for p in points],
[p["median_successful_rps"] for p in points],
"o-",
label=name,
)
ax.set(
title=series + " API budgets",
xlabel="Offered requests/s",
ylabel="Successful requests/s",
)
ax.grid(alpha=0.3)
ax.legend()
for name in ["growth-4", "db-improved"]:
points = sorted(
[r for r in rows if r["configuration"] == name], key=lambda r: r["offered_rate"]
)
axes[2].plot(
[p["offered_rate"] for p in points],
[p["median_successful_rps"] for p in points],
"o-",
label=name,
)
axes[2].set(
title="Controlled PostgreSQL CPU change",
xlabel="Offered requests/s",
ylabel="Successful requests/s",
)
axes[2].grid(alpha=0.3)
axes[2].legend()
fig.savefig(source.with_name(source.stem + ".svg"))
fig.savefig(source.with_name(source.stem + ".png"), dpi=130)
plt.close(fig)
fig, axes = plt.subplots(1, 3, figsize=(15, 4), constrained_layout=True)
for name in ["growth-4", "db-improved"]:
points = sorted([r for r in rows if r["configuration"] == name], key=lambda r: r["offered_rate"])
xs = [p["offered_rate"] for p in points]
axes[0].plot(xs, [p["median_db_cpu_percent"] for p in points], "o-", label=name)
axes[1].plot(xs, [p["max_driver_cpu_fraction"] * 100 for p in points], "o-", label=name)
axes[2].plot(xs, [p["total_dropped"] / p["total_scheduled"] * 100 for p in points], "o-", label=name)
axes[0].axhline(25, linestyle="--", color="gray", label="baseline quota25%")
axes[0].axhline(50, linestyle=":", color="gray", label="improved quota50%")
axes[0].set(title="PostgreSQL CPU", ylabel="CPU% (100%=one core)")
axes[1].set(title="Driver process CPU, maximum repeat", ylabel="CPU% (100%=one core)")
axes[2].set(title="Dropped scheduling slots", ylabel="Dropped / scheduled %")
for ax in axes:
ax.set_xlabel("Offered requests/s")
ax.grid(alpha=.3)
ax.legend()
fig.savefig(source.with_name(source.stem + "-resources.svg"))
fig.savefig(source.with_name(source.stem + "-resources.png"), dpi=130)
plt.close(fig)
print("\n".join(text))
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Open-loop HTTP message writes; count attempts, successes, errors and drops separately."""
import asyncio
import json
import math
import time
import uuid
from collections import Counter
import aiohttp
async def run_load(base, actor, chat_id, *, rate, duration, concurrency=128):
latencies, errors, instances = [], Counter(), Counter()
pending = set()
dropped = 0
dropped_lag = dropped_concurrency = 0
lag = []
total_slots = int(rate * duration)
async with aiohttp.ClientSession(
base_url=base,
connector=aiohttp.TCPConnector(limit=concurrency),
timeout=aiohttp.ClientTimeout(total=6),
trust_env=False,
) as client:
started = time.perf_counter()
cpu_started = time.process_time()
async def request(index):
start = time.perf_counter()
try:
async with client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={
"Authorization": "Bearer " + actor["token"],
"Idempotency-Key": f"study-{uuid.uuid4().hex}",
},
json={"text": f"synthetic-{index}"},
) as response:
await response.read()
if response.status == 201:
latencies.append(time.perf_counter() - start)
instances[response.headers.get("X-Instance-Id", "missing")] += 1
else:
errors[str(response.status)] += 1
except (aiohttp.ClientError, TimeoutError) as exc:
errors[type(exc).__name__] += 1
for index in range(total_slots):
scheduled = started + index / rate
await asyncio.sleep(max(0, scheduled - time.perf_counter()))
delay = time.perf_counter() - scheduled
lag.append(delay)
if delay > 0.25:
dropped += 1
dropped_lag += 1
continue
if len(pending) >= concurrency:
dropped += 1
dropped_concurrency += 1
continue
task = asyncio.create_task(request(index))
pending.add(task)
task.add_done_callback(pending.discard)
await asyncio.gather(*pending)
elapsed = time.perf_counter() - started
latencies.sort()
def percentile(p):
return (
round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 3)
if latencies
else None
)
return {
"profile": "open-loop unique POST messages, no automatic retries",
"offered_rate": rate,
"requested_duration_seconds": duration,
"elapsed_including_drain_seconds": round(elapsed, 4),
"scheduled": total_slots,
"attempted": len(latencies) + sum(errors.values()),
"successful": len(latencies),
"errors": dict(errors),
"dropped": dropped,
"dropped_scheduler": dropped_lag,
"dropped_concurrency": dropped_concurrency,
"driver_cpu_seconds": time.process_time() - cpu_started,
"driver_cpu_fraction_one_core": (time.process_time() - cpu_started) / elapsed,
"successful_rps": round(len(latencies) / elapsed, 3),
"attempted_rps": round((len(latencies) + sum(errors.values())) / elapsed, 3),
"latency_success_ms": {
"p50": percentile(0.5),
"p95": percentile(0.95),
"p99": percentile(0.99),
},
"max_schedule_lag_ms": round(max(lag, default=0) * 1000, 3),
"instances": dict(instances),
"concurrency_cap": concurrency,
}
if __name__ == "__main__":
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client
parser = argparse.ArgumentParser()
parser.add_argument("--rate", type=int, default=300)
parser.add_argument("--duration", type=float, default=8)
parser.add_argument("--output")
args = parser.parse_args()
c = Client("http://127.0.0.1:8083")
actor = c.user("research")
chat = c.call(
"POST",
"/api/v1/chats",
201,
actor=actor,
body={"title": "study", "member_ids": [actor["id"]]},
schema="Chat",
)["json"]
result = asyncio.run(
run_load(c.base, actor, chat["id"], rate=args.rate, duration=args.duration)
)
text = json.dumps(result, indent=2)
if args.output:
Path(args.output).write_text(text + "\n")
print(text)
+40
View File
@@ -0,0 +1,40 @@
"""Return PostgreSQL to the original quota to check time/warm-cache confounding."""
import asyncio
import json
import subprocess
import threading
from pathlib import Path
from load import run_load
from run import ROOT, Client, configure, sample_services
def main():
profile = {"name": "db-reverted", "replicas": 4, "api_cpu": .5,
"api_memory": "256m", "pg_cpu": .25}
rows = []
try:
actual = configure(profile)
c = Client("http://127.0.0.1:8083")
actor = c.user("reversal")
for repeat in range(3):
chat = c.call("POST", "/api/v1/chats", 201, actor=actor,
body={"title": "reversal", "member_ids": [actor["id"]]}, schema="Chat")["json"]
samples, stop = [], threading.Event()
thread = threading.Thread(target=sample_services, args=(stop, samples, actual))
thread.start()
result = asyncio.run(run_load(c.base, actor, chat["id"], rate=900, duration=6))
stop.set()
thread.join()
result.update(configuration="db-reverted", repeat=repeat + 1,
actual_containers=actual, resource_samples=samples)
rows.append(result)
print(json.dumps({k: result[k] for k in ["repeat", "successful_rps", "dropped", "errors"]}), flush=True)
finally:
subprocess.run(["docker", "compose", "up", "-d", "--scale", "api=2", "--wait"], cwd=ROOT, check=True,
stdout=subprocess.DEVNULL)
Path(ROOT / "evidence/scaling-reversal.json").write_text(json.dumps({"runs": rows}, indent=2) + "\n")
if __name__ == "__main__":
main()
+225
View File
@@ -0,0 +1,225 @@
"""Reproducible scaling matrix with actual quotas and service resource samples."""
import argparse
import asyncio
import hashlib
import json
import os
import platform
import subprocess
import sys
import threading
import time
from datetime import UTC, datetime
from pathlib import Path
from load import run_load
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
def command(args, *, env=None):
return subprocess.check_output(args, cwd=ROOT, env=env, text=True)
def inventory():
ids = command(["docker", "compose", "ps", "-q"]).split()
result = []
for cid in ids:
raw = json.loads(command(["docker", "inspect", cid]))[0]
result.append(
{
"id": cid,
"service": raw["Config"]["Labels"]["com.docker.compose.service"],
"image_id": raw["Image"],
"image": raw["Config"]["Image"],
"nano_cpus": raw["HostConfig"]["NanoCpus"],
"memory_bytes": raw["HostConfig"]["Memory"],
"started_at": raw["State"]["StartedAt"],
}
)
return result
def sample_services(stop, samples, containers):
while not stop.is_set():
raw = command(
[
"docker",
"stats",
"--no-stream",
"--format",
"{{json .}}",
*[c["id"] for c in containers],
]
)
rows = [json.loads(line) for line in raw.splitlines() if line.strip()]
samples.append({"monotonic": time.monotonic(), "containers": rows})
stop.wait(0.5)
def configure(profile):
env = {
**os.environ,
"API_REPLICAS": str(profile["replicas"]),
"API_CPUS": str(profile["api_cpu"]),
"API_MEMORY": profile["api_memory"],
"PG_CPUS": str(profile["pg_cpu"]),
"PG_MEMORY": "768m",
}
subprocess.run(
["docker", "compose", "up", "-d", "--scale", "api=" + str(profile["replicas"]), "--wait"],
cwd=ROOT,
env=env,
check=True,
stdout=subprocess.DEVNULL,
)
subprocess.run(
[sys.executable, "scripts/wait_replicas.py", str(profile["replicas"])], cwd=ROOT, check=True
)
actual = inventory()
apis = [c for c in actual if c["service"] == "api"]
assert len(apis) == profile["replicas"]
assert all(c["nano_cpus"] == int(profile["api_cpu"] * 1e9) for c in apis)
assert all(c["memory_bytes"] == int(profile["api_memory"][:-1]) * 1024**2 for c in apis)
db = next(c for c in actual if c["service"] == "postgres")
assert db["nano_cpus"] == int(profile["pg_cpu"] * 1e9)
return actual
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--duration", type=float, default=6)
parser.add_argument("--rates", default="100,300,600")
parser.add_argument("--repeats", type=int, default=3)
parser.add_argument("--output", default="evidence/scaling.json")
args = parser.parse_args()
profiles = []
for replicas in [1, 2, 4]:
profiles.append(
{
"name": f"fixed-{replicas}",
"series": "fixed",
"replicas": replicas,
"api_cpu": 1 / replicas,
"api_memory": f"{1024 // replicas}m",
"pg_cpu": 0.25,
}
)
for replicas in [1, 2, 4]:
profiles.append(
{
"name": f"growth-{replicas}",
"series": "growth",
"replicas": replicas,
"api_cpu": 0.5,
"api_memory": "256m",
"pg_cpu": 0.25,
}
)
profiles.append(
{
"name": "db-improved",
"series": "improvement",
"replicas": 4,
"api_cpu": 0.5,
"api_memory": "256m",
"pg_cpu": 0.5,
}
)
source_manifest = {
str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
for folder in ["src", "migrations"]
for p in sorted((ROOT / folder).rglob("*"))
if p.is_file() and "__pycache__" not in p.parts
}
report = {
"source_manifest": source_manifest,
"source_revision": command(["git", "rev-parse", "HEAD"]).strip(),
"started_at": datetime.now(UTC).isoformat(),
"host": platform.platform(),
"docker": json.loads(command(["docker", "info", "--format", "{{json .}}"])),
"profiles": profiles,
"runs": [],
"notes": [
"PostgreSQL intentionally constrained to 0.25CPU to expose its resource boundary.",
"Open-loop scheduler drops if concurrency cap128 or lag>250ms; no hidden backlog.",
"Only successes enter latency percentiles; wall time includes draining requests.",
],
}
# Keep only non-sensitive engine inventory fields.
report["docker"] = {
k: report["docker"].get(k)
for k in ["ServerVersion", "NCPU", "MemTotal", "Architecture", "OperatingSystem"]
}
dest = ROOT / args.output
dest.parent.mkdir(parents=True, exist_ok=True)
try:
c = Client("http://127.0.0.1:8083")
actor = c.user("study")
for profile in profiles:
actual = configure(profile)
for repeat in range(args.repeats):
rates = [int(x) for x in args.rates.split(",")]
if repeat % 2:
rates.reverse()
for rate in rates:
chat = c.call(
"POST",
"/api/v1/chats",
201,
actor=actor,
body={"title": "synthetic-study", "member_ids": [actor["id"]]},
schema="Chat",
)["json"]
samples, stop = [], threading.Event()
thread = threading.Thread(
target=sample_services, args=(stop, samples, actual), daemon=True
)
thread.start()
result = asyncio.run(
run_load(c.base, actor, chat["id"], rate=rate, duration=args.duration)
)
stop.set()
thread.join()
result.update(
{
"configuration": profile["name"],
"repeat": repeat + 1,
"actual_containers": actual,
"resource_samples": samples,
}
)
report["runs"].append(result)
dest.write_text(json.dumps(report, indent=2) + "\n")
print(
json.dumps(
{
k: result[k]
for k in [
"configuration",
"repeat",
"offered_rate",
"successful_rps",
"errors",
"dropped",
]
}
),
flush=True,
)
finally:
subprocess.run(
["docker", "compose", "up", "-d", "--scale", "api=2", "--wait"],
cwd=ROOT,
check=True,
stdout=subprocess.DEVNULL,
)
report["ended_at"] = datetime.now(UTC).isoformat()
dest.write_text(json.dumps(report, indent=2) + "\n")
if __name__ == "__main__":
main()