Fresh-connection probe (never pooled) that times connect/query/total for a Neon-style scale-to-zero compute, with --repeat/--every-seconds to catch the real cold-vs-warm gap and a --json summary (min/p50/p95/max). Verified for real against a local Postgres 16 container: happy path, --repeat/--every-seconds, --json, and all three failure paths (wrong port, wrong password, missing connection string) — see test-fixtures/local-postgres-verification.md for the full transcript, including an honest note on two false "cold" readings that transcript caught (local network/load jitter, not a real suspend/resume). No real Neon account was available in this environment (no credentials, and the Neon MCP needs an interactive browser OAuth this session can't complete) so the real Neon suspend/resume cycle itself is not verified live — logged honestly in the README's "Honest limits" section rather than claimed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
184 lines
6.9 KiB
JavaScript
Executable File
184 lines
6.9 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
'use strict';
|
|
|
|
// neon-cold-start-probe
|
|
//
|
|
// Neon's (and most serverless Postgres) free/autoscaling computes suspend
|
|
// after a few minutes idle. The next connection has to wake the compute
|
|
// before it can answer, so it is slower than every connection after it.
|
|
// Nobody ships a number for *your* database's wake-up time; this measures
|
|
// it for real, from a brand-new TCP+TLS+auth connection each probe (a
|
|
// pooled client would hide exactly the thing you're trying to see).
|
|
//
|
|
// Usage:
|
|
// neon-cold-start-probe "postgres://user:pass@host/db?sslmode=require"
|
|
// neon-cold-start-probe --url "$DATABASE_URL" --repeat 5 --every-seconds 60
|
|
//
|
|
// Each probe opens a fresh connection, runs `select 1`, closes it, and
|
|
// prints connect time / query time / total. With --repeat, it also waits
|
|
// --every-seconds between probes and prints a summary (min/p50/p95/max) so
|
|
// you can see the first (often cold) probe against the rest (warm).
|
|
|
|
import pg from 'pg';
|
|
|
|
function parseArgs(argv) {
|
|
const out = { repeat: 1, every: 0, timeout: 15, threshold: 500 };
|
|
const positional = [];
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const a = argv[i];
|
|
const next = () => argv[++i];
|
|
switch (a) {
|
|
case '--url': out.url = next(); break;
|
|
case '--repeat': out.repeat = parseInt(next(), 10); break;
|
|
case '--every-seconds': out.every = parseFloat(next()); break;
|
|
case '--timeout': out.timeout = parseInt(next(), 10); break;
|
|
case '--cold-threshold-ms': out.threshold = parseInt(next(), 10); break;
|
|
case '--json': out.json = true; break;
|
|
case '--help': case '-h': out.help = true; break;
|
|
default:
|
|
if (!a.startsWith('-')) positional.push(a);
|
|
break;
|
|
}
|
|
}
|
|
if (!out.url && positional.length) out.url = positional[0];
|
|
return out;
|
|
}
|
|
|
|
function help() {
|
|
console.log(`neon-cold-start-probe - measure real wake-up latency on a serverless Postgres endpoint
|
|
|
|
Usage:
|
|
neon-cold-start-probe <connection-string> [options]
|
|
neon-cold-start-probe --url "$DATABASE_URL" [options]
|
|
|
|
Options:
|
|
--url <conn-string> Postgres connection string (or positional arg, or DATABASE_URL)
|
|
--repeat <n> Number of probes, each a brand-new connection (default 1)
|
|
--every-seconds <s> Seconds to wait between probes (default 0 = back-to-back)
|
|
--timeout <s> Per-probe connect timeout in seconds (default 15)
|
|
--cold-threshold-ms <ms> Total ms above which a probe is labelled "cold" (default 500)
|
|
--json Print machine-readable JSON instead of a table
|
|
--help This help
|
|
|
|
What the 500ms default is based on: not a Neon-published number (Neon
|
|
documents that autoscaling computes suspend and resume on demand, but does
|
|
not publish a wake-up SLA) — it's the midpoint of a real measurement done
|
|
building this tool's sibling project (a Postgres-as-a-service that also
|
|
scales to zero): cold 0.93-1.47s vs warm 0.09-0.24s, sleep API then first
|
|
request, 3 runs. Pass --cold-threshold-ms to use your own.
|
|
|
|
To actually see a cold probe, the first probe in a --repeat run needs to
|
|
hit a compute that has been idle past its suspend timeout (5 minutes on
|
|
Neon's default/free settings) BEFORE you run this. Back-to-back probes
|
|
(the default) will almost always all look warm, because the first probe
|
|
itself keeps the compute awake for the rest.
|
|
|
|
Comparison, if cold starts are a dealbreaker: https://scribase.com/neon-compute-limit-cold-start?utm_source=cli&utm_medium=cli&utm_campaign=neon-cold-start-probe
|
|
(honest numbers both ways: Scribase's own Free/Hobby tier also scales to
|
|
zero and pays the same kind of cold-start cost; only its Pro tier stays
|
|
always-warm.)`);
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async function probe(connectionString, timeoutSec) {
|
|
const client = new pg.Client({
|
|
connectionString,
|
|
connectionTimeoutMillis: timeoutSec * 1000,
|
|
statement_timeout: timeoutSec * 1000,
|
|
});
|
|
const t0 = process.hrtime.bigint();
|
|
try {
|
|
await client.connect();
|
|
} catch (err) {
|
|
return { ok: false, error: err.message, connectMs: null, queryMs: null, totalMs: null };
|
|
}
|
|
const t1 = process.hrtime.bigint();
|
|
try {
|
|
await client.query('select 1');
|
|
} catch (err) {
|
|
await client.end().catch(() => {});
|
|
return { ok: false, error: err.message, connectMs: Number(t1 - t0) / 1e6, queryMs: null, totalMs: null };
|
|
}
|
|
const t2 = process.hrtime.bigint();
|
|
await client.end().catch(() => {});
|
|
const connectMs = Number(t1 - t0) / 1e6;
|
|
const queryMs = Number(t2 - t1) / 1e6;
|
|
return { ok: true, error: null, connectMs, queryMs, totalMs: connectMs + queryMs };
|
|
}
|
|
|
|
function percentile(sorted, p) {
|
|
if (sorted.length === 0) return null;
|
|
const idx = Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1);
|
|
return sorted[Math.max(0, idx)];
|
|
}
|
|
|
|
async function main() {
|
|
const args = parseArgs(process.argv.slice(2));
|
|
if (args.help) {
|
|
help();
|
|
return 0;
|
|
}
|
|
const url = args.url || process.env.DATABASE_URL || '';
|
|
if (!url) {
|
|
console.error('error: a connection string is required (positional arg, --url, or DATABASE_URL). Run with --help.');
|
|
return 1;
|
|
}
|
|
if (args.repeat < 1) {
|
|
console.error('error: --repeat must be >= 1.');
|
|
return 1;
|
|
}
|
|
|
|
const results = [];
|
|
for (let i = 0; i < args.repeat; i++) {
|
|
if (i > 0 && args.every > 0) {
|
|
await sleep(args.every * 1000);
|
|
}
|
|
const r = await probe(url, args.timeout);
|
|
results.push(r);
|
|
if (!args.json) {
|
|
if (r.ok) {
|
|
const label = r.totalMs >= args.threshold ? 'COLD' : 'warm';
|
|
console.log(
|
|
`probe ${i + 1}/${args.repeat}: connect=${r.connectMs.toFixed(0)}ms query=${r.queryMs.toFixed(0)}ms total=${r.totalMs.toFixed(0)}ms [${label}]`
|
|
);
|
|
} else {
|
|
console.log(`probe ${i + 1}/${args.repeat}: FAILED (${r.error})`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const ok = results.filter((r) => r.ok);
|
|
const failed = results.length - ok.length;
|
|
const totals = ok.map((r) => r.totalMs).sort((a, b) => a - b);
|
|
|
|
const summary = {
|
|
probes: results.length,
|
|
failed,
|
|
minMs: totals.length ? totals[0] : null,
|
|
p50Ms: percentile(totals, 50),
|
|
p95Ms: percentile(totals, 95),
|
|
maxMs: totals.length ? totals[totals.length - 1] : null,
|
|
coldThresholdMs: args.threshold,
|
|
coldCount: ok.filter((r) => r.totalMs >= args.threshold).length,
|
|
};
|
|
|
|
if (args.json) {
|
|
console.log(JSON.stringify({ results, summary }, null, 2));
|
|
} else if (results.length > 1 && totals.length) {
|
|
console.log(
|
|
`\nsummary: min=${summary.minMs.toFixed(0)}ms p50=${summary.p50Ms.toFixed(0)}ms p95=${summary.p95Ms.toFixed(0)}ms max=${summary.maxMs.toFixed(0)}ms (${summary.coldCount}/${ok.length} probes >= ${args.threshold}ms, ${failed} failed)`
|
|
);
|
|
}
|
|
|
|
if (failed === results.length) return 1;
|
|
return 0;
|
|
}
|
|
|
|
main().then((code) => process.exit(code), (err) => {
|
|
console.error('error:', err && err.message ? err.message : err);
|
|
process.exit(1);
|
|
});
|