// PulseCast SSE load test: 120 concurrent clients for 5 minutes. // // The native k6 http module buffers the whole response, so it cannot read // Server-Sent Events incrementally. This script uses the community // `k6/x/sse` extension (github.com/phymbert/xk6-sse), which is not in the // stock k6 binary. Build the pinned binary once: // make k6-build // // Run: // API_URL=https://api-pulse.noelsabia.dev ./k6/k6-sse run k6/sse.js // make load // // Recorded metrics: // sse_connections_opened counter, expected >= SSE_VUS (120) // sse_connections_closed counter, expected to equal connections_opened // sse_open_success rate of VUs that opened a stream // sse_event_latency p95 server-timestamp-to-client latency, ms // sse_scenario_latency same, scenario events only (if any occur) // sse_ping_latency same, heartbeat events only // sse_events_received total events // // Each VU closes its stream after SSE_HOLD_PINGS heartbeats (20 * 15 s = 5 min). // That keeps 120 streams open for the full window and closes cleanly. import http from 'k6/http'; import sse from 'k6/x/sse'; import { check } from 'k6'; import { Counter, Rate, Trend } from 'k6/metrics'; const API_URL = (__ENV.API_URL || 'https://api-pulse.noelsabia.dev').replace(/\/+$/, ''); const STREAM_URL = __ENV.SSE_URL || `${API_URL}/api/stream`; const VUS = Math.max(1, Number(__ENV.SSE_VUS || 120)); const HOLD_PINGS = Math.max(1, Number(__ENV.SSE_HOLD_PINGS || 20)); const MAX_DURATION = __ENV.SSE_MAX_DURATION || '6m'; const connectionsOpened = new Counter('sse_connections_opened'); const connectionsClosed = new Counter('sse_connections_closed'); const openSuccess = new Rate('sse_open_success'); const connectionErrors = new Counter('sse_connection_errors'); const eventsReceived = new Counter('sse_events_received'); const eventLatency = new Trend('sse_event_latency', true); const scenarioLatency = new Trend('sse_scenario_latency', true); const pingLatency = new Trend('sse_ping_latency', true); const thresholds = { sse_open_success: ['rate>=0.99'], sse_event_latency: ['p(95)<2000'], }; thresholds[`sse_connections_opened`] = [`count>=${VUS}`]; export const options = { scenarios: { sse_clients: { executor: 'per-vu-iterations', vus: VUS, iterations: 1, maxDuration: MAX_DURATION, gracefulStop: '30s', }, }, thresholds, // Every VU owns one long-lived connection; do not pool them. noConnectionReuse: true, summaryTrendStats: ['avg', 'min', 'med', 'p(90)', 'p(95)', 'p(99)', 'max', 'count'], }; export function setup() { const res = http.get(`${API_URL}/api/healthz`, { tags: { endpoint: 'setup' } }); if (res.status !== 200) { throw new Error(`API healthz returned ${res.status}; refusing to start the SSE load test`); } return { api: API_URL, stream: STREAM_URL, vus: VUS }; } export default function () { let opened = false; let closedByUs = false; let firstScenario = true; let pings = 0; const params = { method: 'GET', headers: { Accept: 'text/event-stream', 'Cache-Control': 'no-cache', }, // Outlive the scenario; the 20th heartbeat closes the stream first. timeout: __ENV.SSE_TIMEOUT || '7m', tags: { endpoint: 'sse' }, }; const res = sse.open(STREAM_URL, params, function (client) { client.on('open', function () { opened = true; connectionsOpened.add(1); }); client.on('event', function (event) { eventsReceived.add(1); const name = event.name || 'message'; const now = Date.now(); let payload = null; if (event.data) { try { payload = JSON.parse(event.data); } catch (_) { payload = null; } } // The contract puts the emit time in `t` (ping) or `at` (scenario). // The first scenario event on connect replays the current state and // carries the original state-change timestamp, not the send time, so // exclude it per VU. Only scenario changes broadcast during the run // are valid samples. const initialScenario = name === 'scenario' && firstScenario; if (name === 'scenario') { firstScenario = false; } // Latency is server timestamp -> client receipt, in milliseconds. const stamp = payload && (payload.t || payload.at); if (stamp && !initialScenario) { const emitted = Date.parse(stamp); if (!Number.isNaN(emitted)) { const lag = now - emitted; // Ignore bad stamps and absurd clock skew (> 1 h). if (lag >= 0 && lag < 3600000) { eventLatency.add(lag); if (name === 'scenario') scenarioLatency.add(lag); if (name === 'ping') pingLatency.add(lag); } } } if (name === 'ping') { pings += 1; if (pings >= HOLD_PINGS && !closedByUs) { closedByUs = true; client.close(); } } }); client.on('error', function (e) { if (!closedByUs) { connectionErrors.add(1); console.error(`SSE error: ${e && e.error ? e.error() : e}`); } }); }); if (opened) { connectionsClosed.add(1); } check(res, { 'sse status 200': (r) => r && r.status === 200, 'sse content-type': (r) => r && String(r.headers['Content-Type'] || '').includes('text/event-stream'), 'sse opened': () => opened, }); if (!opened) { connectionErrors.add(1); } openSuccess.add(opened); }