- normalize sslmode=require/prefer/verify-ca to verify-full so pg's 8-line SECURITY WARNING no longer precedes every Neon probe - --repeat/--timeout/--every-seconds/--cold-threshold-ms are validated; a bad or missing value used to exit 1 silently - reject non-postgres:// arguments and unknown flags with a clear message - pay one-time DNS/TLS process costs before probe 1 - output ends with one plain line pointing at the Neon cold-start page - README: 10-second quickstart, real output sample, copy matches the page Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
252 lines
9.9 KiB
JavaScript
Executable File
252 lines
9.9 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
|
|
// 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';
|
|
import { readFileSync } from 'node:fs';
|
|
import { lookup } from 'node:dns/promises';
|
|
|
|
const CTA_URL =
|
|
'https://scribase.com/neon-compute-limit-cold-start?utm_source=cli&utm_medium=cli-output&utm_campaign=neon-cold-start-probe';
|
|
const CTA_LINE = `Neon cold starts and compute limits explained, with the fix: ${CTA_URL}`;
|
|
const VALUE_FLAGS = new Set(['--url', '--repeat', '--every-seconds', '--timeout', '--cold-threshold-ms']);
|
|
|
|
function version() {
|
|
try {
|
|
return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
} catch {
|
|
return 'unknown';
|
|
}
|
|
}
|
|
|
|
function parseArgs(argv) {
|
|
const out = { repeat: 1, every: 0, timeout: 15, threshold: 500, errors: [] };
|
|
const positional = [];
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const a = argv[i];
|
|
const next = () => {
|
|
const value = argv[++i];
|
|
if (value === undefined || (VALUE_FLAGS.has(value))) {
|
|
out.errors.push(`${a} needs a value`);
|
|
return undefined;
|
|
}
|
|
return value;
|
|
};
|
|
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;
|
|
case '--version': case '-v': out.version = true; break;
|
|
default:
|
|
if (a.startsWith('-')) out.errors.push(`unknown option ${a}`);
|
|
else 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
|
|
--version Print the version
|
|
--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.
|
|
|
|
Neon cold starts and compute limits explained, with the fix:
|
|
https://scribase.com/neon-compute-limit-cold-start?utm_source=cli&utm_medium=cli-help&utm_campaign=neon-cold-start-probe`);
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
// pg >= 8.16 prints an 8-line SECURITY WARNING to stderr for sslmode=require
|
|
// (the mode every Neon connection string ships with), because it already
|
|
// treats require/prefer/verify-ca as verify-full and plans to change that in
|
|
// pg 9. Asking for verify-full explicitly is the exact same behavior today,
|
|
// stays strict after pg 9, and keeps the probe output clean.
|
|
function normalizeSslMode(connectionString) {
|
|
return connectionString.replace(/([?&]sslmode=)(require|prefer|verify-ca)(?=&|$)/i, '$1verify-full');
|
|
}
|
|
|
|
function validate(args, url) {
|
|
if (args.errors.length) return [...args.errors];
|
|
const errors = [];
|
|
if (!url) {
|
|
errors.push('a connection string is required (positional arg, --url, or DATABASE_URL)');
|
|
} else if (!/^postgres(ql)?:\/\//i.test(url)) {
|
|
errors.push('the connection string must start with postgres:// or postgresql://');
|
|
}
|
|
if (!Number.isInteger(args.repeat) || args.repeat < 1) errors.push('--repeat must be a whole number >= 1');
|
|
if (!Number.isFinite(args.every) || args.every < 0) errors.push('--every-seconds must be a number >= 0');
|
|
if (!Number.isInteger(args.timeout) || args.timeout < 1) errors.push('--timeout must be a whole number of seconds >= 1');
|
|
if (!Number.isInteger(args.threshold) || args.threshold < 1) errors.push('--cold-threshold-ms must be a whole number >= 1');
|
|
return errors;
|
|
}
|
|
|
|
// One-time process costs (first DNS lookup, loading Node's TLS stack and CAs) are
|
|
// not the database waking up, and a long-running app never pays them per
|
|
// connection. Pay them once before probe 1 so they are not billed to it.
|
|
async function warmProcess(connectionString) {
|
|
try {
|
|
const { hostname } = new URL(connectionString);
|
|
const [tls] = await Promise.all([import('node:tls'), hostname ? lookup(hostname) : null]);
|
|
tls.createSecureContext(); // loads the root CA store, a one-time cost
|
|
} catch {
|
|
// A bad host surfaces as a normal failed probe with its real error.
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
if (args.version) {
|
|
console.log(version());
|
|
return 0;
|
|
}
|
|
const rawUrl = args.url || process.env.DATABASE_URL || '';
|
|
const errors = validate(args, rawUrl);
|
|
if (errors.length) {
|
|
for (const message of errors) console.error(`error: ${message}.`);
|
|
console.error('Run with --help for usage.');
|
|
return 1;
|
|
}
|
|
const url = normalizeSslMode(rawUrl);
|
|
|
|
await warmProcess(url);
|
|
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)`
|
|
);
|
|
}
|
|
|
|
// One plain closing line. In --json mode it goes to stderr so stdout stays
|
|
// valid JSON for whatever is piping it.
|
|
if (args.json) console.error(CTA_LINE);
|
|
else console.log(`\n${CTA_LINE}`);
|
|
|
|
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);
|
|
});
|