Move lab3 to lab4

This commit is contained in:
2026-11-04 22:57:50 +03:00
parent ec540a1a72
commit 319f0d519e
167 changed files with 7591 additions and 1 deletions
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Runs EXPLAIN (ANALYZE, BUFFERS) of the chat history query against the Compose PostgreSQL on 70 000 synthetic
# messages. The data is inserted and rolled back in one transaction; the plans are saved to evidence/.
set -eu
cd "$(dirname "$0")/.."
mkdir -p evidence
docker compose exec -T postgres psql -U messenger -d messenger -X -q < scripts/sql/explain-history.sql \
| tee evidence/explain-history.txt
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Sends one message with the SAME Idempotency-Key many times in parallel through the balancer.
Expects every response to be 201 with the same message, at least two replicas answering (X-Instance-Id)
and exactly one message in the chat history. Synthetic users only; the token stays in memory.
"""
import argparse
import base64
import json
import threading
import urllib.error
import urllib.request
import uuid
from collections import Counter
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--parallel', type=int, default=32)
parser.add_argument('--rounds', type=int, default=20)
args = parser.parse_args()
def call(method, path, body=None, headers=None):
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(args.base_url + path, data=data, method=method, headers={
'Content-Type': 'application/json', **(headers or {})})
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, response.headers, json.loads(response.read() or b'null')
except urllib.error.HTTPError as error:
return error.code, error.headers, json.loads(error.read() or b'null')
username = 'race_' + uuid.uuid4().hex[:12]
password = 'race-password-' + uuid.uuid4().hex
status, _, user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'race', 'password': password})
assert status == 201, status
basic = base64.b64encode(f'{username}:{password}'.encode()).decode()
status, _, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + basic})
assert status == 201, status
auth = {'Authorization': 'Bearer ' + session['token']}
status, _, chat = call('POST', '/api/v1/chats', {'title': 'race', 'member_ids': [user['id']]}, auth)
assert status == 201, status
path = f"/api/v1/chats/{chat['id']}/messages"
statuses, instances, violations = Counter(), Counter(), 0
for round_number in range(args.rounds):
key = uuid.uuid4().hex
results = []
barrier = threading.Barrier(args.parallel)
def send():
barrier.wait()
results.append(call('POST', path, {'text': f'race {round_number}'}, {**auth, 'Idempotency-Key': key}))
threads = [threading.Thread(target=send) for _ in range(args.parallel)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
ids = {body['id'] for status, _, body in results if status == 201}
for status, headers, _ in results:
statuses[status] += 1
instances[headers.get('X-Instance-Id', '-')] += 1
if len(ids) != 1:
violations += 1
status, _, page = call('GET', path + '?limit=100', headers=auth)
texts = [m['text'] for m in page['items']]
print(json.dumps({
'rounds': args.rounds,
'parallel_requests_per_round': args.parallel,
'statuses': dict(statuses),
'requests_per_instance': dict(instances),
'rounds_with_more_than_one_message_id': violations,
'messages_in_history': len(texts),
'distinct_texts_in_history': len(set(texts)),
}, indent=2))
ok = violations == 0 and len(texts) == args.rounds == len(set(texts)) and len(instances) >= 2 and set(statuses) == {201}
print('PASS' if ok else 'FAIL')
raise SystemExit(0 if ok else 1)
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Creates local secrets for the Compose stack. Never overwrites an existing secret:
# the PostgreSQL volume is initialised with the first password and keeps it.
set -eu
cd "$(dirname "$0")/.."
mkdir -p secrets
# Readable by the non-root users inside the containers (bind-mounted as is).
umask 022
for name in db_password redis_password; do
if [ ! -s "secrets/$name" ]; then
openssl rand -hex 24 > "secrets/$name"
echo "created secrets/$name"
else
echo "secrets/$name already exists, keeping it"
fi
done
+55
View File
@@ -0,0 +1,55 @@
#!/bin/sh
# One replica fault under constant load through the balancer, then its restoration.
# MODE=stop docker stop (SIGTERM: drain, graceful shutdown) MODE=kill docker kill (SIGKILL: crash)
# TARGET=api-1|api-2 RATE=150 req/s DURATION=45 s fault at 10 s, restore at 25 s
# Output: evidence/load/failover-<mode>-<target>/{k6.txt,events.json,haproxy.log,per-second.csv,summary.json}
set -eu
cd "$(dirname "$0")/../.."
MODE=${MODE:-stop}
TARGET=${TARGET:-api-1}
RATE=${RATE:-150}
DURATION=${DURATION:-45}
FAULT_AT=${FAULT_AT:-10}
RESTORE_AT=${RESTORE_AT:-25}
out=evidence/load/failover-$MODE-$TARGET
rm -rf "$out" && mkdir -p "$out"
now() { python3 -c 'import time; print(int(time.time() * 1000))'; }
# Sleeps until <seconds> after the load started, so the schedule does not drift with slow docker commands.
sleep_until() { python3 -c "import time; time.sleep(max(0, $start / 1000 + $1 - time.time()))"; }
container=mtusi-messenger-lab4-$TARGET
target_instance=$(docker inspect -f '{{.Config.Hostname}}' "$container")
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
K6_CSV_TIME_FORMAT=unix_milli k6 run --quiet --out csv="$out/requests.csv" \
-e RATE="$RATE" -e DURATION="${DURATION}s" scripts/load/mixed.js > "$out/k6.txt" 2>&1 &
k6_pid=$!
# Load starts after k6 setup (users, sessions, chat): wait for the first request of the scenario.
until grep -q ',load,' "$out/requests.csv" 2>/dev/null; do sleep 0.2; done
start=$(now)
sleep_until "$FAULT_AT"
fault=$(now)
if [ "$MODE" = kill ]; then docker kill "$container" >/dev/null; else docker stop --time 9 "$container" >/dev/null; fi
fault_done=$(now)
sleep_until "$RESTORE_AT"
restore_begin=$(now)
docker start "$container" >/dev/null
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$container")" = healthy ]; do sleep 0.2; done
restore_healthy=$(now)
restored_instance=$(docker inspect -f '{{.Config.Hostname}}' "$container")
wait "$k6_pid" || true
docker compose logs --timestamps --no-log-prefix --since "$since" lb 2>/dev/null | grep -E 'Server api/|SH--|5[0-9][0-9] ' > "$out/haproxy.log" || true
cat > "$out/events.json" <<JSON
{"mode": "$MODE", "target": "$TARGET", "target_instance": "$target_instance", "restored_instance": "$restored_instance",
"load_start": $start, "fault": $fault, "fault_done": $fault_done, "restore_begin": $restore_begin, "restore_healthy": $restore_healthy}
JSON
python3 scripts/load/summarize.py "$out" > /dev/null
# Raw per-request data stays out of Git (evidence keeps aggregates only); KEEP_RAW=1 keeps it for analysis.
[ "${KEEP_RAW:-0}" = 1 ] || rm -f "$out/requests.csv"
cat "$out/summary.json"
+67
View File
@@ -0,0 +1,67 @@
// Open-model load through the balancer: RATE requests per second regardless of response time.
// 70 % GET /users/me (session lookup), 30 % POST message with a unique Idempotency-Key.
// Every response adds a `served_by` sample tagged with X-Instance-Id and status, so the summary can show
// which replica answered each second. Tokens live only in this process.
import http from 'k6/http';
import encoding from 'k6/encoding';
import { Counter } from 'k6/metrics';
const BASE = __ENV.BASE_URL || 'http://localhost:8080';
const RATE = Number(__ENV.RATE || 150);
const DURATION = __ENV.DURATION || '40s';
const USERS = 10;
const PASSWORD = 'load-test-password';
const servedBy = new Counter('served_by');
export const options = {
scenarios: {
load: {
executor: 'constant-arrival-rate',
rate: RATE,
timeUnit: '1s',
duration: DURATION,
preAllocatedVUs: 50,
maxVUs: 300,
},
},
summaryTrendStats: ['avg', 'med', 'p(95)', 'p(99)', 'max'],
};
export function setup() {
const json = { headers: { 'Content-Type': 'application/json' } };
const users = [];
for (let i = 0; i < USERS; i++) {
const username = `load_${Date.now().toString(36)}_${i}`;
const user = http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: 'load', password: PASSWORD }), json).json();
const basic = encoding.b64encode(`${username}:${PASSWORD}`);
const session = http.post(`${BASE}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${basic}` } }).json();
users.push({ id: user.id, token: session.token });
}
const chat = http.post(`${BASE}/api/v1/chats`, JSON.stringify({ title: 'load', member_ids: users.map((u) => u.id) }), {
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${users[0].token}` },
}).json();
return { users, chatId: chat.id };
}
export default function (data) {
const user = data.users[Math.floor(Math.random() * data.users.length)];
const auth = { Authorization: `Bearer ${user.token}` };
let response;
if (Math.random() < 0.7) {
response = http.get(`${BASE}/api/v1/users/me`, { headers: auth, tags: { name: 'me' }, timeout: '5s' });
} else {
response = http.post(
`${BASE}/api/v1/chats/${data.chatId}/messages`,
JSON.stringify({ text: `load ${__VU}-${__ITER}` }),
{
headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': `load-${__VU}-${__ITER}-${Date.now()}` },
tags: { name: 'send' },
timeout: '5s',
},
);
}
servedBy.add(1, { instance: response.headers['X-Instance-Id'] || 'none', code: String(response.status) });
}
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# scripts/rolling-update.sh while k6 keeps RATE req/s through the balancer.
# Output: evidence/load/rolling-update/{k6.txt,rolling.log,events.json,per-second.csv,summary.json}
set -eu
cd "$(dirname "$0")/../.."
RATE=${RATE:-150}
DURATION=${DURATION:-70}
out=evidence/load/rolling-update
rm -rf "$out" && mkdir -p "$out"
now() { python3 -c 'import time; print(int(time.time() * 1000))'; }
# Build outside the measured window: compiling would compete with the API for CPU.
docker compose build --quiet api
{ echo "# before"; docker compose ps api --format '{{.Name}} {{.ID}} {{.Image}}'; } > "$out/rolling.log"
K6_CSV_TIME_FORMAT=unix_milli k6 run --quiet --out csv="$out/requests.csv" \
-e RATE="$RATE" -e DURATION="${DURATION}s" scripts/load/mixed.js > "$out/k6.txt" 2>&1 &
k6_pid=$!
until grep -q ',load,' "$out/requests.csv" 2>/dev/null; do sleep 0.2; done
start=$(now)
sleep 10
begin=$(now)
scripts/rolling-update.sh >> "$out/rolling.log" 2>&1
end=$(now)
wait "$k6_pid" || true
{ echo "# after"; docker compose ps api --format '{{.Name}} {{.ID}} {{.Image}}'; } >> "$out/rolling.log"
echo "{\"load_start\": $start, \"rolling_begin\": $begin, \"rolling_end\": $end}" > "$out/events.json"
python3 scripts/load/summarize.py "$out" > /dev/null
# Raw per-request data stays out of Git (evidence keeps aggregates only); KEEP_RAW=1 keeps it for analysis.
[ "${KEEP_RAW:-0}" = 1 ] || rm -f "$out/requests.csv"
cat "$out/rolling.log" "$out/summary.json"
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Per-second view of one k6 run (requests.csv) plus the events of the experiment (events.json).
Writes per-second.csv and summary.json next to the input. An error is any response that is not 2xx
(including k6 status 0: connection reset or timeout). Times are seconds from the start of the load.
"""
import csv
import json
import math
import sys
from collections import Counter, defaultdict
from pathlib import Path
from urllib.parse import parse_qsl
run = Path(sys.argv[1])
events = json.loads((run / 'events.json').read_text()) if (run / 'events.json').exists() else {}
durations = [] # (t_ms, duration_ms, status)
served = [] # (t_ms, instance, status)
with open(run / 'requests.csv') as f:
for row in csv.DictReader(f):
if row['metric_name'] == 'http_req_duration' and row['scenario'] == 'load':
durations.append((int(row['timestamp']), float(row['metric_value']), int(row['status'] or 0)))
elif row['metric_name'] == 'served_by':
tags = dict(parse_qsl(row['extra_tags']))
served.append((int(row['timestamp']), tags.get('instance', 'none'), int(tags.get('code', 0))))
t0 = min(t for t, _, _ in durations)
rel = lambda ms: (ms - t0) / 1000
def percentile(values, p):
if not values:
return None
values = sorted(values)
return values[min(len(values) - 1, math.ceil(p / 100 * len(values)) - 1)]
per_second = defaultdict(lambda: {'ok': 0, 'errors': 0, 'durations': [], 'instances': Counter()})
for t, d, status in durations:
second = per_second[math.floor(rel(t))]
second['durations'].append(d)
if 200 <= status < 300:
second['ok'] += 1
else:
second['errors'] += 1
for t, instance, status in served:
if 200 <= status < 300:
per_second[math.floor(rel(t))]['instances'][instance] += 1
instances = sorted({i for s in per_second.values() for i in s['instances']})
with open(run / 'per-second.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['second', 'ok', 'errors', 'p99_ms', 'max_ms'] + instances)
for second in sorted(per_second):
s = per_second[second]
writer.writerow([second, s['ok'], s['errors'], round(percentile(s['durations'], 99), 1), round(max(s['durations']), 1)]
+ [s['instances'].get(i, 0) for i in instances])
errors = sorted(rel(t) for t, _, status in durations if not 200 <= status < 300)
seconds = max(per_second) + 1
summary = {
'requests': len(durations),
'ok': len(durations) - len(errors),
'errors': len(errors),
'error_codes': dict(Counter(str(status) for _, _, status in durations if not 200 <= status < 300)),
'ok_rps': round((len(durations) - len(errors)) / seconds, 1),
'p50_ms': round(percentile([d for _, d, _ in durations], 50), 1),
'p95_ms': round(percentile([d for _, d, _ in durations], 95), 1),
'p99_ms': round(percentile([d for _, d, _ in durations], 99), 1),
'max_ms': round(max(d for _, d, _ in durations), 1),
'requests_per_instance': dict(Counter(i for _, i, status in served if 200 <= status < 300)),
}
for name, value in events.items():
if isinstance(value, (int, float)):
summary[f'event_{name}_s'] = round(rel(value), 2)
if 'fault' in events:
fault = rel(events['fault'])
after = [e - fault for e in errors if e >= fault - 0.5]
summary['errors_after_fault'] = len(after)
summary['last_error_after_fault_s'] = round(max(after), 2) if after else None
target = events.get('target_instance')
end = rel(events['restore_begin']) if 'restore_begin' in events else float('inf')
last = [rel(t) - fault for t, i, status in served if i == target and fault <= rel(t) < end]
summary['target_last_response_after_fault_s'] = round(max(last), 2) if last else None
if 'restore_begin' in events and events.get('restored_instance'):
begin = rel(events['restore_begin'])
first = [rel(t) - begin for t, i, status in served
if i == events['restored_instance'] and 200 <= status < 300 and rel(t) >= begin]
summary['restored_replica_first_response_after_start_s'] = round(min(first), 2) if first else None
# HAProxy state changes (docker log timestamps): when the balancer took the target out and put it back.
log = run / 'haproxy.log'
if log.exists() and 'fault' in events:
from datetime import datetime
def at(line):
stamp = line.split()[0].rstrip('Z')
whole, _, fraction = stamp.partition('.')
return datetime.fromisoformat(whole + '+00:00').timestamp() * 1000 + float('0.' + (fraction or '0')) * 1000
changes = [(at(line), line) for line in log.read_text().splitlines() if 'Server api/' in line and '[WARNING]' not in line]
down = [t for t, line in changes if ('is DOWN' in line or 'going DOWN' in line) and t >= events['fault']]
summary['lb_marked_down_after_fault_s'] = round((min(down) - events['fault']) / 1000, 2) if down else None
if 'restore_begin' in events:
up = [t for t, line in changes if 'is UP, reason' in line and t >= events['restore_begin']]
summary['lb_marked_up_after_start_s'] = round((min(up) - events['restore_begin']) / 1000, 2) if up else None
(run / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False))
print(json.dumps(summary, indent=2, ensure_ascii=False))
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Restarts the balancer, every API replica, PostgreSQL and Redis, keeping the named volume (no `down -v`, no re-seed).
set -eu
cd "$(dirname "$0")/.."
docker compose stop lb api redis postgres
docker compose up -d --wait
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Reproduces the review scenario on the running stack, everything through the balancer:
# session + message, warm the session on both replicas, CLIENT PAUSE <ms> WRITE on Redis (reads keep working),
# logout, then read and repeat the original message with the old token and key.
# Expected: logout is 204 only once the tombstone is in Redis; afterwards every replica answers 401.
# PAUSE_MS=5000 (default): the logout waits for the pause and answers 204.
# PAUSE_MS=12000: longer than the logout deadline (8 s): the logout answers 503 and every replica still rejects the token.
set -euo pipefail
cd "$(dirname "$0")/.."
PAUSE_MS=${PAUSE_MS:-5000}
B=${BASE_URL:-http://localhost:8080}/api/v1
U=pause_$RANDOM$RANDOM
PW=pause-test-password
KEY=pause-$RANDOM$RANDOM
redis() { docker compose exec -T redis redis-cli --no-auth-warning -a "$(cat secrets/redis_password)" "$@"; }
now() { python3 -c 'import time; print(time.time())'; }
status() { curl -s -o /dev/null -w '%{http_code} %header{x-instance-id}' "$@"; }
curl -s -o /dev/null -X POST "$B/users" -H 'Content-Type: application/json' \
-d "{\"username\":\"$U\",\"display_name\":\"pause\",\"password\":\"$PW\"}"
T=$(curl -s -X POST "$B/auth/sessions" -u "$U:$PW" | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')
ME=$(curl -s "$B/users/me" -H "Authorization: Bearer $T" | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')
CHAT=$(curl -s -X POST "$B/chats" -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
-d "{\"title\":\"pause\",\"member_ids\":[\"$ME\"]}" | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')
send() { status -X POST "$B/chats/$CHAT/messages" -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
-H "Idempotency-Key: $KEY" -d '{"text":"original message"}'; }
echo "send message with Idempotency-Key: $(send)"
echo "warm the session on both replicas:"
for i in 1 2 3 4; do echo " GET /users/me -> $(status "$B/users/me" -H "Authorization: Bearer $T")"; done
echo "redis: CLIENT PAUSE $PAUSE_MS WRITE -> $(redis CLIENT PAUSE "$PAUSE_MS" WRITE)"
start=$(now)
echo "DELETE /auth/sessions/current -> $(status -X DELETE "$B/auth/sessions/current" -H "Authorization: Bearer $T") after $(python3 -c "print(round($(now) - $start, 2))") s"
sleep 1.5 # replicas check pending revocations once a second; only matters for the unconfirmed (503) case
echo "old token after logout (redis writes still paused: $(python3 -c "print('yes' if $(now) - $start < $PAUSE_MS / 1000 else 'no')")):"
for i in 1 2 3 4; do echo " GET /users/me -> $(status "$B/users/me" -H "Authorization: Bearer $T")"; done
for i in 1 2; do echo " POST message, same key -> $(send)"; done
python3 -c "import time; time.sleep(max(0, $start + $PAUSE_MS / 1000 + 2 - time.time()))"
echo "after the pause: session key in redis = $(redis GET "session:$(printf %s "$T" | shasum -a 256 | cut -d' ' -f1)")"
for i in 1 2; do echo " GET /users/me -> $(status "$B/users/me" -H "Authorization: Bearer $T")"; done
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Replaces the API replicas one by one with a freshly built image while the balancer keeps serving.
# 1. build the new image, 2. apply migrations once (they must be compatible with the running version),
# 3. for every old replica: start one new replica, wait until HAProxy has it UP, then stop (drain) and remove the old.
# The number of serving replicas never drops below the configured count.
set -euo pipefail
cd "$(dirname "$0")/.."
build_id=${BUILD_ID:-$(git rev-parse --short HEAD)-$(date +%s)}
log() { echo "$(date -u +%H:%M:%S) $*"; }
up_in_lb() {
docker compose exec -T lb wget -qO- 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1 == "api" && $2 != "BACKEND" && $18 == "UP"' | wc -l
}
log "build image (BUILD_ID=$build_id)"
docker compose build --quiet --build-arg BUILD_ID="$build_id" api
log "migrate"
docker compose run --rm --no-deps migrate > /dev/null
old=$(docker compose ps -q api)
count=$(echo "$old" | wc -l | tr -d ' ')
for container in $old; do
before=$(docker compose ps -q api | sort)
docker compose up -d --no-deps --no-recreate --scale api=$((count + 1)) api 2> /dev/null
new=$(comm -13 <(echo "$before") <(docker compose ps -q api | sort))
log "started $(docker inspect -f '{{.Name}}' "$new") ($(echo "$new" | cut -c1-12))"
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ]; do sleep 0.5; done
until [ "$(up_in_lb)" -ge $((count + 1)) ]; do sleep 0.5; done
log "new replica is UP in HAProxy"
docker stop --time 9 "$container" > /dev/null
docker rm "$container" > /dev/null
log "stopped and removed $(echo "$container" | cut -c1-12)"
done
log "done: $(docker compose ps -q api | while read -r c; do docker inspect -f '{{.Name}} {{index .Config.Labels "org.opencontainers.image.revision"}}' "$c"; done | tr '\n' ' ')"
+100
View File
@@ -0,0 +1,100 @@
-- EXPLAIN (ANALYZE, BUFFERS) of the chat history query on synthetic data.
-- Everything runs in one transaction that is rolled back: the database is left untouched.
-- The queries are the ones ExposedMessageRepository.findPageByChatId generates (page size 50 + 1 look-ahead row).
\set ON_ERROR_STOP on
\pset pager off
BEGIN;
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ('00000000-0000-0000-0000-000000000001', 'explain_alice', 'Alice', 'not-a-hash', now()),
('00000000-0000-0000-0000-000000000002', 'explain_bob', 'Bob', 'not-a-hash', now());
-- One large chat (20 000 messages) and 50 neighbours with 1 000 messages each: 70 000 rows in total,
-- so the plan has to skip foreign chats instead of reading a table that only holds the target chat.
INSERT INTO chats (id, title, created_at)
SELECT ('00000000-0000-0000-0001-' || lpad(n::text, 12, '0'))::uuid, 'explain chat ' || n, now()
FROM generate_series(0, 50) AS n;
INSERT INTO chat_members (chat_id, user_id, position)
SELECT c.id, u.id, u.position
FROM chats c
CROSS JOIN (VALUES ('00000000-0000-0000-0000-000000000001'::uuid, 0),
('00000000-0000-0000-0000-000000000002'::uuid, 1)) AS u (id, position)
WHERE c.title LIKE 'explain chat %';
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
'00000000-0000-0000-0001-000000000000',
CASE WHEN n % 2 = 0 THEN '00000000-0000-0000-0000-000000000001'::uuid
ELSE '00000000-0000-0000-0000-000000000002'::uuid END,
'message #' || n,
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second'
FROM generate_series(1, 20000) AS n;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
('00000000-0000-0000-0001-' || lpad(c::text, 12, '0'))::uuid,
'00000000-0000-0000-0000-000000000001',
'neighbour message #' || n,
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second'
FROM generate_series(1, 50) AS c, generate_series(1, 1000) AS n;
ANALYZE users, chats, chat_members, messages;
\echo
\echo '== Data volume'
SELECT count(*) AS total_messages,
count(*) FILTER (WHERE chat_id = '00000000-0000-0000-0001-000000000000') AS target_chat_messages
FROM messages;
-- Cursor of the 15 000th message: a deep page, where OFFSET pagination would have to skip 15 000 rows.
SELECT created_at AS cursor_created_at, id AS cursor_id
FROM messages
WHERE chat_id = '00000000-0000-0000-0001-000000000000'
ORDER BY created_at, id
OFFSET 14999 LIMIT 1 \gset
\echo
\echo '== 1. First page: WHERE chat_id = ? ORDER BY created_at, id LIMIT 51'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at
FROM messages
WHERE messages.chat_id = '00000000-0000-0000-0001-000000000000'
ORDER BY messages.created_at ASC, messages.id ASC
LIMIT 51;
\echo
\echo '== 2. Deep page after the 15 000th message: (created_at, id) > (?, ?)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at
FROM messages
WHERE (messages.chat_id = '00000000-0000-0000-0001-000000000000')
AND ((messages.created_at, messages.id) > (:'cursor_created_at', :'cursor_id'))
ORDER BY messages.created_at ASC, messages.id ASC
LIMIT 51;
\echo
\echo '== 3. Same deep page with OFFSET instead of a cursor (for comparison, not used by the API)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at
FROM messages
WHERE messages.chat_id = '00000000-0000-0000-0001-000000000000'
ORDER BY messages.created_at ASC, messages.id ASC
LIMIT 51 OFFSET 15000;
\echo
\echo '== 4. Deep page without messages_chat_id_created_at_id_idx (index scans disabled for this query only)'
SET LOCAL enable_indexscan = off;
SET LOCAL enable_bitmapscan = off;
SET LOCAL enable_indexonlyscan = off;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at
FROM messages
WHERE (messages.chat_id = '00000000-0000-0000-0001-000000000000')
AND ((messages.created_at, messages.id) > (:'cursor_created_at', :'cursor_id'))
ORDER BY messages.created_at ASC, messages.id ASC
LIMIT 51;
ROLLBACK;
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Stops the ONE API replica named by TARGET_INSTANCE_ID and leaves it stopped (no DB/LB/volume changes).
# The replica's X-Instance-Id is its container hostname, i.e. the short container id.
# Restore afterwards with: docker compose start api
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]* | "") echo "unexpected instance id" >&2; exit 2 ;;
esac
# Only containers of the api service are candidates, so a wrong id can never stop the database or the balancer.
container=$(docker compose ps -q api | grep "^$TARGET_INSTANCE_ID" || true)
if [ -z "$container" ] || [ "$(printf '%s\n' "$container" | wc -l)" -ne 1 ]; then
echo "no single api replica matches $TARGET_INSTANCE_ID" >&2
exit 1
fi
docker stop --time 9 "$container" >/dev/null