Lab3: atomic one-statement idempotent write, tuned stand, level-4/5 measurement tooling

This commit is contained in:
Ivan Melnikov
2026-12-02 18:45:01 +03:00
parent e9bf138053
commit c19d092b63
7 changed files with 701 additions and 72 deletions
+365
View File
@@ -0,0 +1,365 @@
#!/usr/bin/env python3
"""Level-5 track 1: the price of scaling.
Experiment design (documented in evidence/track1/methodology.md):
A. Fix total API CPU/RAM at 0.8 cores / 512 MiB and compare 1, 2 and 4
replicas on the same closed-loop message-POST profile. DB, Valkey and LB
limits stay fixed.
B. At 4 replicas, grow total API CPU through 0.4 -> 0.7 -> 0.9 cores while
keeping RAM fixed, to find where more HTTP capacity stops helping.
C. At the saturated 4x0.2 profile, compare the baseline image (explicit
transaction + 3 SQL statements per new message) with the final image
(one atomic data-modifying CTE statement).
Each run records real timestamps, cgroup CPU/throttle, PostgreSQL deltas,
HAProxy queues/errors and pgx pool waits. The VM has only 2 vCPU; the sum of
container CPU limits in every configuration is kept <= 1.9 cores.
Python 3.9+, standard library only.
"""
import argparse
import datetime as dt
import json
import math
import os
import statistics
import subprocess
import sys
import threading
import time
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'scripts'))
import lab3_metrics as M # noqa: E402
OUT = ROOT / 'evidence/track1'
LOADGEN = Path('/tmp/mtusi-lab3-loadgen-track1')
FINAL_IMAGE = 'mtusi-messenger-lab3-melnikov:local'
BASELINE_IMAGE = 'mtusi-messenger-lab3-melnikov:track-baseline'
DURATION = 20
WARMUP = 5
CONCURRENCY = 32
def now():
return M.iso()
def build_loadgen():
result = subprocess.run(['go', 'build', '-ldflags=-X main.version=lab3-track1',
'-o', str(LOADGEN), './cmd/loadgen'],
cwd=str(ROOT), text=True, capture_output=True, check=False)
if result.returncode != 0:
raise RuntimeError('loadgen build failed: ' + result.stderr[-800:])
def config(replicas, cpu_per, mem_per, cpu_total, mem_total, image, label):
return {
'replicas': replicas,
'api_cpu_per_replica': cpu_per,
'api_cpu_total': cpu_total,
'api_mem_per_replica': mem_per,
'api_mem_total': mem_total,
'image': image,
'label': label,
}
def run_one(label, cfg, revision, raw_dir, run_dir):
M.set_stack_profile(cfg['image'], revision, cfg['replicas'], cfg['api_cpu_per_replica'],
cfg['api_mem_per_replica'], cfg['gomemlimit'])
time.sleep(2) # let HAProxy's resolver drop a removed backend
before = M.snapshot()
activity_samples = []
sampler_stop = threading.Event()
def sample_activity():
while not sampler_stop.is_set():
try:
activity_samples.append(M.db_activity_sample())
except Exception:
pass
sampler_stop.wait(0.5)
sampler = threading.Thread(target=sample_activity, name='db-activity-sampler', daemon=True)
sampler.start()
wall_start = time.monotonic()
wall_start_utc = M.iso()
raw_path = raw_dir / (label + '.json')
load = M.run_loadgen(LOADGEN, raw_path, DURATION, WARMUP, CONCURRENCY,
'track1 %s; replicas=%d cpu_per=%s mem_per=%s' % (
label, cfg['replicas'], cfg['api_cpu_per_replica'],
cfg['api_mem_per_replica']))
wall_end = time.monotonic()
wall_end_utc = M.iso()
sampler_stop.set()
sampler.join(timeout=5)
after = M.snapshot()
elapsed = wall_end - wall_start
record = M.summarize_run(label, cfg, before, after, elapsed, load)
record['wall_window'] = {'started_at': wall_start_utc, 'finished_at': wall_end_utc,
'seconds': round(elapsed, 3),
'note': 'cgroup/DB/LB counters are sampled just outside this wall window'}
waits = Counter()
max_active = 0
max_waiting = 0
for item in activity_samples:
if not isinstance(item, dict):
continue
max_active = max(max_active, item.get('active', 0))
max_waiting = max(max_waiting, item.get('waiting', 0))
for key, value in (item.get('waits') or {}).items():
waits[key] += value
record['db_activity_sampler'] = {
'samples': len(activity_samples),
'interval_seconds': 0.5,
'max_active_connections': max_active,
'max_waiting_connections': max_waiting,
'wait_event_connection_samples': dict(waits.most_common(12)),
'note': 'counts are active-connection samples, not seconds; the sampler itself is a light DB client',
}
record['containers'] = {
'api': after['containers']['api'],
'postgres': after['containers']['postgres'],
'valkey': after['containers']['valkey'],
'lb': after['containers']['lb'],
}
record['snapshot_before'] = before
record['snapshot_after'] = after
run_path = run_dir / (label + '.json')
run_path.write_text(json.dumps(record, indent=2, ensure_ascii=False) + '\n')
print('%s: %.1f RPS, p95 %.1f ms, errors %d, api %.3f/%.3f cores, db %.3f/%.3f cores' % (
label, load['successful_rps'], load['successful_latency_ms']['p95'],
load['failed_requests'], record['resource']['api_used_cores'],
record['resource']['api_limit_cores'], record['resource']['db_used_cores'],
record['resource']['db_limit_cores']))
return record
def medians_for(runs, group_key):
values = {}
for run in runs:
label = run['config'][group_key]
values.setdefault(str(label), []).append(run)
result = {}
for label, items in values.items():
result[label] = {
'runs': len(items),
'successful_rps': M.median([item['loadgen']['successful_rps'] for item in items]),
'error_ratio': M.median([item['loadgen']['error_ratio'] for item in items]),
'p50_ms': M.median([item['loadgen']['successful_latency_ms']['p50'] for item in items]),
'p95_ms': M.median([item['loadgen']['successful_latency_ms']['p95'] for item in items]),
'p99_ms': M.median([item['loadgen']['successful_latency_ms']['p99'] for item in items]),
'api_used_cores': M.median([item['resource']['api_used_cores'] for item in items]),
'api_limit_cores': M.median([item['resource']['api_limit_cores'] for item in items]),
'api_utilization': M.median([item['resource']['api_utilization'] for item in items]),
'api_throttled_seconds': M.median([item['resource']['api_throttled_seconds'] for item in items]),
'db_used_cores': M.median([item['resource']['db_used_cores'] for item in items]),
'db_limit_cores': M.median([item['resource']['db_limit_cores'] for item in items]),
'db_utilization': M.median([item['resource']['db_utilization'] for item in items]),
'db_throttled_seconds': M.median([item['resource']['db_throttled_seconds'] for item in items]),
'lb_used_cores': M.median([item['resource']['lb_used_cores'] for item in items]),
'lb_qmax': M.median([item['lb']['qmax_after'] for item in items]),
'lb_5xx': M.median([item['lb']['hrsp_5xx_delta'] for item in items]),
'pool_waits_per_acquire': M.median([item['postgres']['pool_waits_per_acquire'] for item in items]),
'commits_per_second': M.median([item['postgres']['commits_per_second'] for item in items]),
'wal_bytes': M.median([item['wal']['wal_bytes'] for item in items]),
'wal_sync_time_ms': M.median([item['wal']['wal_sync_time'] for item in items]),
'checkpoints_req': M.median([item['bgwriter']['checkpoints_req'] for item in items]),
'db_throttled_periods': M.median([item['resource']['db_throttled_periods'] for item in items]),
'buffer_hit_ratio': M.median([item['postgres']['buffer_hit_ratio'] for item in items]),
'messages_after': M.median([item['postgres']['datasets_after']['messages'] for item in items]),
'image_ids': sorted({image for item in items for image in
[c['image_id'] for c in item['containers']['api']]}),
'revision': sorted({item['config'].get('revision') for item in items if item['config'].get('revision')}),
}
return result
def main():
parser = argparse.ArgumentParser(description='Track 1 scaling experiment')
parser.add_argument('--baseline-image', default=BASELINE_IMAGE)
parser.add_argument('--final-image', default=FINAL_IMAGE)
parser.add_argument('--reps', type=int, default=3)
parser.add_argument('--output-dir', default='evidence/track1')
parser.add_argument('--quick', action='store_true', help='one repetition per configuration')
args = parser.parse_args()
global OUT
OUT = (ROOT / args.output_dir).resolve()
raw_dir = OUT / 'raw'
run_dir = OUT / 'runs'
raw_dir.mkdir(parents=True, exist_ok=True)
run_dir.mkdir(parents=True, exist_ok=True)
reps = 1 if args.quick else args.reps
for image in (args.final_image, args.baseline_image):
result = subprocess.run(['docker', 'image', 'inspect', image], text=True,
capture_output=True, check=False)
if result.returncode != 0:
raise RuntimeError('image not found: %s (build it first)' % image)
build_loadgen()
revision = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=str(ROOT), text=True,
capture_output=True, check=True).stdout.strip()
metadata = M.build_metadata(args.final_image)
metadata.update({
'experiment_started_at': now(),
'profile': {
'load': 'closed-loop POST messages through the LB; unique Idempotency-Key per request',
'duration_seconds': DURATION,
'warmup_seconds': WARMUP,
'concurrency': CONCURRENCY,
'loadgen': 'cmd/loadgen (Go, HTTP acknowledgement throughput)',
},
'vm_capacity_note': 'Colima VM has 2 vCPU / 2 GiB; all API processes, PostgreSQL, Valkey and HAProxy share one kernel and one Docker host. The experiment proves process-level scaling limits, not node-level HA.',
'limits': {
'postgres_cpu': 0.7, 'postgres_mem': '512M',
'valkey_cpu': 0.1, 'valkey_mem': '128M',
'lb_cpu': 0.2, 'lb_mem': '64M',
'sum_cpu_fixed_total': 1.8,
'sum_cpu_growth_max': 1.9,
},
})
# Warm the stack and apply the shared DB/LB limits once, preserving volumes.
M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB', recreate_state=True)
if not M.wait_ready(120):
raise RuntimeError('stack not ready')
fixed = []
for rep in range(reps):
for replicas, cpu, mem, gomem in ((1, 0.8, '512M', '480MiB'),
(2, 0.4, '256M', '240MiB'),
(4, 0.2, '128M', '112MiB')):
label = 'fixed-r%d-rep%d' % (replicas, rep + 1)
cfg = config(replicas, cpu, mem, 0.8, '512M', args.final_image, 'r%d' % replicas)
cfg['gomemlimit'] = gomem
cfg['revision'] = revision
fixed.append(run_one(label, cfg, revision, raw_dir, run_dir))
growth = []
for rep in range(reps):
for total, cpu, gomem in ((0.4, 0.1, '112MiB'), (0.7, 0.175, '112MiB'), (0.9, 0.225, '112MiB')):
label = 'growth-cpu%s-rep%d' % (str(total).replace('.', 'p'), rep + 1)
cfg = config(4, cpu, '128M', total, '512M', args.final_image, 'cpu%s' % total)
cfg['gomemlimit'] = gomem
cfg['revision'] = revision
growth.append(run_one(label, cfg, revision, raw_dir, run_dir))
improvement = []
for rep in range(reps):
for image, name in ((args.baseline_image, 'baseline'), (args.final_image, 'optimized')):
label = 'improve-%s-rep%d' % (name, rep + 1)
cfg = config(4, 0.2, '128M', 0.8, '512M', image, name)
cfg['gomemlimit'] = '112MiB'
cfg['revision'] = revision if name == 'optimized' else revision + '+baseline-image'
improvement.append(run_one(label, cfg, revision, raw_dir, run_dir))
# Leave the stand in the documented default profile and final image.
M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB')
time.sleep(2)
summary = {
'metadata': metadata,
'finished_at': now(),
'run_count': len(fixed) + len(growth) + len(improvement),
'runs': {'fixed_total': fixed, 'resource_growth': growth, 'improvement': improvement},
'medians': {
'fixed_total': medians_for(fixed, 'replicas'),
'resource_growth': medians_for(growth, 'api_cpu_total'),
'improvement': medians_for(improvement, 'label'),
},
}
(OUT / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n')
methodology = (METHODOLOGY
.replace('__REPS__', str(reps))
.replace('__DURATION__', str(DURATION))
.replace('__WARMUP__', str(WARMUP))
.replace('__CONCURRENCY__', str(CONCURRENCY)))
(OUT / 'methodology.md').write_text(methodology + '\n')
print('wrote', OUT / 'summary.json')
base = summary['medians']['improvement'].get('baseline', {}).get('successful_rps')
opt = summary['medians']['improvement'].get('optimized', {}).get('successful_rps')
if base and opt:
print('improvement: baseline %.1f RPS -> optimized %.1f RPS (%.1f%%)' % (
base, opt, (opt - base) / base * 100.0))
print('fixed medians:', json.dumps(summary['medians']['fixed_total'], indent=1)[:1500])
print('growth medians:', json.dumps(summary['medians']['resource_growth'], indent=1)[:1500])
METHODOLOGY = """# Track 1 methodology: price of scaling
## Hypothesis
At a fixed total API CPU/RAM budget, adding API replicas raises HTTP
acknowledgement throughput only until a shared component saturates. On this
single Docker host the candidate shared bottlenecks are PostgreSQL CPU/WAL,
the pgx pool, HAProxy and the 2-vCPU VM itself. Once DB CPU is throttled, more
replicas add contention rather than throughput. Folding the message insert and
the idempotency record into one atomic statement should reduce DB work per
acknowledged message and raise throughput at the same limits.
## Fixed profile
* Load: closed-loop POST /api/v1/chats/{id}/messages through the LB, unique
Idempotency-Key and unique text per request, __CONCURRENCY__ Go workers,
__WARMUP__ s warmup, __DURATION__ s measured.
* Total API budget: 0.8 vCPU and 512 MiB, split 1x0.8 / 2x0.4 / 4x0.2 and
1x512M / 2x256M / 4x128M. PostgreSQL, Valkey and HAProxy limits are fixed.
* The whole stand runs on one Colima VM with 2 vCPU and 2 GiB RAM. The sum of
CPU limits is 1.8 cores in the fixed profile and 1.9 in the growth profile.
These are process-level replicas on one kernel, not independent nodes.
## Resource-growth series
At 4 replicas, total API CPU grows 0.4 -> 0.7 -> 0.9 vCPU (0.1/0.175/0.225 per
replica), RAM stays 512 MiB total, DB/Valkey/LB limits stay fixed. This
separates "HTTP capacity is the limit" from "shared DB is the limit".
## Improvement
At the saturated 4x0.2 profile the baseline image uses an explicit transaction,
a message INSERT and an idempotency INSERT (three SQL statements plus
BEGIN/COMMIT). The final image uses one data-modifying CTE that inserts the
message and the idempotency row atomically; a concurrent unique conflict aborts
the whole statement and is replayed. The client, profile and limits are
identical. Reported improvement is the median of __REPS__ alternating runs.
## Metric sources and units
| Field | Source | Unit / meaning |
| --- | --- | --- |
| successful_rps | loadgen JSON | HTTP 2xx acknowledgements / measured seconds; not COMMIT count |
| successful_latency_ms | loadgen JSON | per-request wall time for successful requests, p50/p95/p99 |
| api_used_cores | cgroup v2 cpu.stat usage_usec delta / window | cores actually consumed by all API containers |
| api_throttled_seconds | cgroup v2 throttled_usec delta | CPU throttling, not load average |
| db_used_cores | cgroup v2 cpu.stat of PostgreSQL | cores consumed by the DB container |
| db_throttled_seconds | cgroup v2 throttled_usec of PostgreSQL | evidence of the DB CPU quota being hit |
| commits_per_second | pg_stat_database.xact_commit delta / window | DB transactions, includes auth/chat metadata |
| pool_waits_per_acquire | pgxpool.Stat EmptyAcquireCount delta / AcquireCount delta | fraction of pool acquisitions that had to wait |
| lb_qmax, lb_5xx | HAProxy stats CSV | queue maximum and 5xx on the public frontend |
| buffer_hit_ratio | pg_stat_database blks_hit/(hit+read) | shared-buffer locality |
| memory | cgroup v2 memory.current | cgroup working set, not process RSS |
## Limitations
* One Docker VM and one DB instance: no node failover, no DB replication.
* Closed-loop load has coordinated omission; the loadgen reports only
successful-request latency and separately counts failures.
* The load generator and the stack share the same 2-vCPU host; client cost is
visible and is part of the measured system.
* Absolute RPS is local and is not a production SLA.
"""
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001
import traceback
traceback.print_exc()
print('FAIL:', exc)
raise SystemExit(1)