prom-client Captcha Metrics for Node.js: Counter, Histogram, Gauge

For prom-client captcha metrics, wrap every capskip call in one function that adds its outcome to a Counter, times successful solves in a Histogram and moves an in-flight Gauge inside a finally block, then serve registry.metrics() from node:http. The rest covers what those numbers hide: the SDK finds a finished solve only at its next poll, two label choices can create thousands of series, and the package carries a deprecation notice. The CapSkip Node.js CAPTCHA solver runs on your own Windows PC, so the numbers describe a solver you own.
What you need
- CapSkip running on a Windows PC. Every number below comes from a mock of its API that I wrote, and timings come from a shared PC, so yours may differ by about a tenth of a second.
- Node.js 18 or 20 and later (19 is excluded by prom-client 15.1.3, whose engines field is ^16 || ^18 || >=20). I ran everything on 20.11.1, 24.22.0 and 25.2.1 under Windows 11, never on 18.
- The packages from Step 1. I ran no Prometheus server and you need none: the metrics are plain text, and a small script below reads them.
- A reCAPTCHA v2 page that you may automate. Its sitekey is in the page source (the reCAPTCHA v2 walkthrough for Node.js shows where).
- An address for CapSkip. In Local mode the API answers on 127.0.0.1 only. Server mode opens it to other machines, so the worker can live on a different PC. The connection settings part of the setup guide describes both.
Step 1: install, and read the npm notice
During the install in the next block, npm 11.19.1 printed a deprecation notice: prom-client has been replaced by @prometheus-io/client. The registry lists 15.1.3, published on 2024-06-27, as the last prom-client release. The replacement comes from the Prometheus project, and its changelog says 0.16.0 renamed the package and dropped Node.js 16, 18, 20, 21 and 23.
# Run in an empty folder, in PowerShell npm init -y npm pkg set type=module npm install prom-client capskip
I ran the finished script of this guide on both packages, changing only the import line, on Node.js 20.11.1, 24.22.0 and 25.2.1. All six runs printed the same counters and quantile estimates and wrote nothing to stderr. So this guide installs prom-client, the name people search for. For a new project, install @prometheus-io/client, which lists Node.js 22, 24 and 26 or later in its engines field (npm warned on 25.2.1 and 20.11.1, where it still ran). Stay on prom-client if you run Node.js 18, 20 or 23. The changelog also plans gauges that no longer start at zero; the script sets its gauge itself.
Step 2: count, time and gauge every call
Save the next five blocks as one file, metrics.mjs, in order. The first sets up the client and a registry of its own, because the global one refuses a second metric of the same name (two counters named dup_total threw "has already been registered").
// metrics.mjs: this block and the four after it go into one file, in order.
import http from "node:http";
import client from "prom-client";
import {
CapSkip, ApiException, NetworkException, TimeoutException, ValidationException,
} from "capskip";
const METRICS_PORT = 9464; // where /metrics listens
const WITH_DEFAULTS = false; // true adds the process and event loop metrics
const REPLACEMENT_TEXT = ""; // the replacement text from CapSkip Settings, if any
// Local mode. In Server mode, use the address of the PC that runs CapSkip.
export const solver = new CapSkip({ host: "127.0.0.1", port: 8080 });
// A registry of our own, so nothing else can add series to it.
export const registry = new client.Registry();
if (WITH_DEFAULTS) client.collectDefaultMetrics({ register: registry });
const OUTCOMES = ["ok", "unsolvable", "timeout", "network", "validation", "other"];The Counter has two labels, the CAPTCHA type and the outcome. The Histogram sees only successful solves, so a refused call that ends in a millisecond can’t drag the quantiles down.
const solves = new client.Counter({
name: "capskip_solves_total",
help: "Finished CapSkip calls by CAPTCHA type and outcome.",
labelNames: ["type", "outcome"],
registers: [registry],
});
const inFlight = new client.Gauge({
name: "capskip_solves_in_flight",
help: "CapSkip calls that have started and not yet finished.",
labelNames: ["type"],
registers: [registry],
});
const seconds = new client.Histogram({
name: "capskip_solve_seconds",
help: "Seconds from the call to a token, successful solves only.",
labelNames: ["type"],
// The SDK poll times 0.25, 0.75, 1.75, 3.75, 7.75, 12.75, then every 5, rounded up.
buckets: [0.5, 1, 2, 4, 8, 13, 18, 23, 33, 63, 124, 255],
registers: [registry],
});The function declare() creates every series at 0, because prom-client prints a labelled metric only after its first use: before any call, a script without declare() exposed 0 sample lines and one with it 22. An alert on the unsolvable share needs that series before the first failure. The function outcomeOf() maps the exception classes of the SDK to the label. The capskip source throws ValidationException before any request, NetworkException when a connection or status code fails, ApiException when an answer contains ERROR, and TimeoutException when polling passes its deadline. The SDK has no code field, so the unsolvable test reads the message.
// Create every series at 0 now, so rate() has a start value.
export function declare(type) {
for (const outcome of OUTCOMES) solves.inc({ type, outcome }, 0);
inFlight.set({ type }, 0);
seconds.zero({ type });
}
// Map the SDK exception classes onto the outcome label.
export function outcomeOf(err) {
if (err instanceof ValidationException) return "validation";
if (err instanceof TimeoutException) return "timeout";
if (err instanceof NetworkException) return "network";
if (err instanceof ApiException) {
// No code field: the error code sits in the message text.
return err.message.includes("ERROR_CAPTCHA_UNSOLVABLE") ? "unsolvable" : "other";
}
return "other";
}// measured("recaptcha", () => solver.recaptcha(sitekey, url))
export async function measured(type, call) {
inFlight.inc({ type });
const stop = seconds.startTimer({ type });
try {
const result = await call();
if (REPLACEMENT_TEXT !== "" && result.code === REPLACEMENT_TEXT) {
solves.inc({ type, outcome: "unsolvable" }); // a failed task may arrive as this text
return result;
}
stop(); // only a real token is timed
solves.inc({ type, outcome: "ok" });
return result;
} catch (err) {
solves.inc({ type, outcome: outcomeOf(err) });
throw err;
} finally {
inFlight.dec({ type }); // success, failure, or a throw before any request
}
}One call each through the blocks as written, timed from the call to the outcome (mock, Node.js 24.22.0).
| What the mock did | Label | Seconds |
|---|---|---|
| Solved after 2 s | ok | 3.80 |
| Reported a failed solve | unsolvable | 3.80 |
| Refused the key when the task was sent | other | 0.00 |
| Closed the socket when the task was sent | network | 0.00 |
| Answered HTTP 500 when the task was sent | network | 0.00 |
| Nothing listening on the port | network | 0.00 |
| An action option on a v2 call | validation | 0.00 |
| Dropped every poll, timeout 6 | timeout | 7.77 |
| Never finished, timeout 6 | timeout | 7.81 |
ApiException gave unsolvable and other, NetworkException network, ValidationException validation and TimeoutException timeout. In the timeout rows the last wait of 4 seconds runs past the 6 second deadline.
Two rows need a comment. A CapSkip that takes a task and then drops every poll ends as timeout, not network, because the source treats a failed poll as not ready yet, so the alert needs timeout too. The other concerns the reCAPTCHA section of the API docs, which says a failed task may come back as the replacement text from CapSkip Settings. A mock that answered such a text made result.code that text, and the counter read ok. Setting REPLACEMENT_TEXT in the first block moved it to unsolvable. Leave it empty if you set none.
The Gauge moves in a finally block, which also runs after a throw that never left the process. It read 0 after each of the nine calls above. A version that decremented only after a success sat at 3 after six calls with three failures. The gauge also counts the wait inside CapSkip. Twelve calls against a mock that solves 3 at a time (a stand-in for Max. Threads, the solves of one type that run at once, per the setup guide) showed 12 in flight after one second, and the histogram held that wait too: with 2.0 second solves, 3 calls took under 4 seconds, 6 more under 8 and 3 under 13.
Step 3: serve /metrics and scrape it yourself
The last block is the endpoint: /metrics with the content type the registry reports, 404 elsewhere, 127.0.0.1 only.
// The /metrics endpoint: the text format that a Prometheus server reads.
export function serveMetrics(port = METRICS_PORT) {
const server = http.createServer(async (req, res) => {
if (req.url.split("?")[0] !== "/metrics") {
res.writeHead(404).end();
return;
}
res.writeHead(200, { "Content-Type": registry.contentType });
res.end(await registry.metrics());
});
server.listen(port, "127.0.0.1"); // this PC only
return server;
}The driver starts N calls at once and keeps the port open. Lower the timeout to see the timeout label sooner.
// batch.mjs: run it with node batch.mjs 12, where 12 is how many solves to start at once.
import { solver, measured, declare, serveMetrics } from "./metrics.mjs";
const TIMEOUT_SECONDS = 300; // the SDK default for reCAPTCHA; lower it to see the timeout outcome sooner
const count = Number(process.argv[2] ?? 12);
declare("recaptcha");
serveMetrics();
const jobs = Array.from({ length: count }, (_, i) =>
measured("recaptcha", () =>
solver.recaptcha("YOUR_SITEKEY", "https://example.com/signup", { timeout: TIMEOUT_SECONDS }),
).then(
() => `ok job ${i + 1}`,
(err) => `${err.name} job ${i + 1}: ${err.message.slice(0, 50)}`,
),
);
(await Promise.all(jobs)).forEach((line) => console.log(line));
console.log("done, /metrics stays up on port 9464: press Ctrl+C to stop");The scraper reads what a Prometheus server reads: one sample per line, labels in braces, and a histogram as le buckets plus a sum and a count, as the exposition format documentation describes. Save the next three blocks as one file, scrape.mjs. Its quantile function repeats the linear estimate that the PromQL function histogram_quantile documents (per the docs, not run against Prometheus).
// scrape.mjs: node scrape.mjs reads /metrics once; node scrape.mjs 20 reads it twice, 20 s apart.
// This block and the two after it go into one file, in order.
const METRICS_URL = "http://127.0.0.1:9464/metrics";
const LINE = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(?:\{(.*)\})?\s+(\S+)$/;
// One sample per line, labels in braces.
async function scrape() {
const text = await (await fetch(METRICS_URL)).text();
const series = [];
for (const line of text.split("\n")) {
if (line === "" || line.startsWith("#")) continue;
const m = line.match(LINE);
if (!m) throw new Error(`not a sample line: ${line}`);
const labels = {};
for (const [, key, value] of (m[2] ?? "").matchAll(/(\w+)="((?:[^"\\]|\\.)*)"/g)) labels[key] = value;
series.push({ name: m[1], labels, value: Number(m[3]) });
}
return { series, bytes: Buffer.byteLength(text) };
}
const total = (series, name, want = {}) => series
.filter((s) => s.name === name && Object.entries(want).every(([k, v]) => s.labels[k] === v))
.reduce((sum, s) => sum + s.value, 0);// The linear estimate of PromQL histogram_quantile, inside the bucket that holds the rank.
function quantile(q, series, name) {
const byLe = new Map();
for (const s of series.filter((x) => x.name === `${name}_bucket`)) {
const le = s.labels.le === "+Inf" ? Infinity : Number(s.labels.le);
byLe.set(le, (byLe.get(le) ?? 0) + s.value);
}
const b = [...byLe].sort((x, y) => x[0] - y[0]);
const count = b.length ? b[b.length - 1][1] : 0;
if (count === 0) return NaN;
const rank = q * count;
const i = b.findIndex(([, n]) => n >= rank);
if (b[i][0] === Infinity) return b[i - 1][0]; // the top finite edge
const lower = i === 0 ? 0 : b[i - 1][0];
const below = i === 0 ? 0 : b[i - 1][1];
return lower + ((b[i][0] - lower) * (rank - below)) / (b[i][1] - below);
}const OUTCOMES = ["ok", "unsolvable", "timeout", "network", "validation", "other"];
const windowSeconds = Number(process.argv[2] ?? 0);
const first = await scrape();
let series = first.series;
if (windowSeconds > 0) {
await new Promise((resolve) => setTimeout(resolve, windowSeconds * 1000));
series = (await scrape()).series;
}
for (const outcome of OUTCOMES) {
console.log(outcome.padEnd(11), total(series, "capskip_solves_total", { outcome }));
}
console.log("in flight ", total(series, "capskip_solves_in_flight"));
console.log("seconds ", `count ${total(series, "capskip_solve_seconds_count")}`,
`p50 ${quantile(0.5, series, "capskip_solve_seconds").toFixed(2)}`,
`p90 ${quantile(0.9, series, "capskip_solve_seconds").toFixed(2)}`);
console.log("series ", series.length, `lines, ${first.bytes} bytes`);
if (windowSeconds > 0) {
// What increase() over the window gives: the share of unsolvable calls among the calls that finished in it.
const grew = (want) => total(series, "capskip_solves_total", want) - total(first.series, "capskip_solves_total", want);
const finished = grew({});
console.log(`window ${windowSeconds} s: ${finished} calls finished, ${grew({ outcome: "unsolvable" })} unsolvable`,
finished === 0 ? "(no share: nothing finished)" : `(${((100 * grew({ outcome: "unsolvable" })) / finished).toFixed(0)} %)`);
}# PowerShell window 1: start 12 solves and the /metrics endpoint node batch.mjs 12 # PowerShell window 2: read the endpoint once, then over a 20 second window node scrape.mjs node scrape.mjs 20
My mock gave this for 12 calls on Node.js 24.22.0, answering six ways twice: solved, solved, unsolvable, solved, refused key, dropped socket.
# Output of window 1, then of node scrape.mjs (mock, Node.js 24.22.0) ok job 1 ok job 2 ApiException job 3: ERROR_CAPTCHA_UNSOLVABLE ok job 4 ApiException job 5: ERROR_WRONG_USER_KEY NetworkException job 6: socket hang up ok job 7 ok job 8 ApiException job 9: ERROR_CAPTCHA_UNSOLVABLE ok job 10 ApiException job 11: ERROR_WRONG_USER_KEY NetworkException job 12: socket hang up done, /metrics stays up on port 9464: press Ctrl+C to stop ok 6 unsolvable 2 timeout 0 network 2 validation 0 other 2 in flight 0 seconds count 6 p50 3.00 p90 3.80 series 22 lines, 1619 bytes
Default metrics are a switch in the first block. With WITH_DEFAULTS true, prom-client 15.1.3 added 27 metric names and 50 to 60 sample lines (about 6.8 kB) in a fresh process on Windows, more once garbage collection has run, against 22 lines (1.6 kB) for the solve metrics. Turn them on for a worker that runs for days, because the histogram measures your event loop as well: a busy loop of 6 seconds that began one second into a 2.0 second mock solve turned a 3.78 second call into 7.02 seconds, and nodejs_eventloop_lag_max_seconds read 6.02. Without that metric, a slow tail looks like a slow CapSkip.
Why prom-client captcha metrics show the poll schedule
According to the capskip source, the SDK polls res.php straight after sending the task, then waits 0.25 seconds and doubles the wait up to polling_interval, which defaults to 5. One task at my mock got polls at 0.00, 0.26, 0.78, 1.79, 3.80, 7.81, 12.82 and 17.84 seconds. A solve that ends at 2.0 seconds is found at 3.80, so the histogram records when the SDK looked, not when the solve ended. Each row is a median of 40 calls against the mock.
| Mock solve | Call took | Edge: exact, padded |
|---|---|---|
| 0.1 s | 0.28 s | 0.75 and 0.5 |
| 1.0 s | 1.78 s | 3.75 and 2 |
| 2.0 s | 3.80 s | 7.75 and 4 |
| 5.0 s | 7.81 s | 12.75 and 8 |
| 9.0 s | 12.82 s | 17.75 and 13 |
| 14.0 s | 17.86 s | 22.75 and 18 |
The last column names the smallest edge above the call. Edges exactly on the poll times land one bucket too high, because a call is found a few milliseconds after its poll: every 2.0 second solve fell under 7.75, and the estimated median was 5.75. The default edges of prom-client stop at 10, so solves of 9 and 14 seconds both fell into the overflow bucket and the median read 10.00. So the Histogram edges round the poll times up. Their 0.25 seconds of room covered the 0.1 seconds of drift I saw over eight polls, and the last two edges have more.
Even then an estimate is not the solve time. For the 2.0 second solves, the padded edges gave a median of 3.00 and a 90th percentile of 3.80, because PromQL assumes an even spread across the 2 to 4 bucket, as its documentation says. Alert on a shift, not on one value. The option polling_interval is only a ceiling and it moves the ladder: with 1, the 2.0 second solve was found at 2.80 seconds and the 5.0 second one at 5.80.
Label cardinality, then an alert on unsolvable solves
Every distinct label value makes a new series, and a Histogram adds a line per edge. With two outcomes seen for one site value, the block below made 17 series: 2 for the Counter and 15 for the Histogram. The Prometheus instrumentation guide says to keep most metrics under a cardinality of 10, and to look for another design above 100.
// cardinality.mjs: node cardinality.mjs sitekey 1000 (modes: sitekey, url, allowlist)
// It needs no CapSkip and no network: it only counts the series a label creates.
import client from "prom-client";
const [mode = "sitekey", count = "100"] = process.argv.slice(2);
const registry = new client.Registry();
const solves = new client.Counter({
name: "capskip_solves_total", help: "Finished calls.",
labelNames: ["type", "outcome", "site"], registers: [registry],
});
const seconds = new client.Histogram({
name: "capskip_solve_seconds", help: "Seconds to a token.",
labelNames: ["type", "site"], registers: [registry],
buckets: [0.5, 1, 2, 4, 8, 13, 18, 23, 33, 63, 124, 255],
});
// Only the site you run gets its own value. Everything else shares one.
const KNOWN = new Map([["6Lc0000000000000000000000000000000000000", "signup"]]);
const sitekeyOf = (i) => `6Lc${String(i).padStart(37, "0")}`;
for (let i = 0; i < Number(count); i++) {
let site = "other";
if (mode === "sitekey") site = sitekeyOf(i);
if (mode === "url") site = `https://example.com/signup?ref=${i}`;
if (mode === "allowlist") site = KNOWN.get(sitekeyOf(i)) ?? "other";
for (const outcome of ["ok", "unsolvable"]) solves.inc({ type: "recaptcha", outcome, site });
seconds.observe({ type: "recaptcha", site }, 3.8);
}
const started = performance.now();
const text = await registry.metrics();
const lines = text.split("\n").filter((l) => l !== "" && !l.startsWith("#")).length;
console.log(mode, count, "values:", lines, "series,", Buffer.byteLength(text), "bytes,",
(performance.now() - started).toFixed(0), "ms to render");I ran it with each mode on Node.js 24.22.0. A render took about 25 ms at 1,000 values and about 225 ms at 10,000.
| Label value | Distinct values | Series, size, render |
|---|---|---|
| Sitekey | 100 | 1,700, 177 kB, 4 ms |
| Sitekey | 1,000 | 17,000, 1.77 MB, 25 ms |
| Sitekey | 10,000 | 170,000, 17.7 MB, 225 ms |
| URL with a query | 1,000 | 17,000, 1.67 MB, 24 ms |
| Allow-list, rest as other | 10,000 | 34, 2.6 kB, under 1 ms |
So never label by sitekey or URL: a crawler that meets a new address on every page grows the output without limit. To keep a site label, map the sitekeys you run to a name and send the rest to one shared value, as the last row did.
Now the alert. Take each rate before you sum, since the PromQL documentation warns that rate() cannot see a counter reset after an aggregation. The last line keeps one failure among three calls from paging you.
# PromQL for an alert rule on the unsolvable share (not run: I had no Prometheus server)
sum(rate(capskip_solves_total{outcome="unsolvable"}[10m]))
/ sum(rate(capskip_solves_total[10m])) > 0.25
and sum(increase(capskip_solves_total[10m])) > 20
# The 90th percentile of the solve seconds over the same window
histogram_quantile(0.9, sum by (le) (rate(capskip_solve_seconds_bucket[10m])))My scraper computes the same share between two reads. With steady traffic of 4 calls a second and a mock plan that answered 3 of every 10 as unsolvable, node scrape.mjs 20 reported "78 calls finished, 23 unsolvable (29 %)". With no traffic it gave no share, which is what the volume guard is for. Per the docs, an unsolvable answer means CapSkip tried the solve and failed, and the ERROR_CAPTCHA_UNSOLVABLE guide explains why the fix is a new task. A solve counted ok proves only that you got a token, so count the answer of the form post in a second Counter of your own.
Common errors
Rows marked seen come from a run against my mock.
| What you see | Cause, then fix |
|---|---|
| No unsolvable line before the first failure | A labelled series appears only after its first use (seen). Call declare() at start-up. |
| Metric already registered | Two files made the same name in the global registry (seen). Pass your own registry. |
| Gauge stays above 0 | The decrement sat outside the finally block (seen). Decrement inside the finally block. |
| Median stuck at 10 | Default edges, solves above 10 seconds (seen). Use edges that reach 255. |
| Counts one bucket too high | Edges sit exactly on poll times (seen). Round the edges up. |
| Network errors counted as other | Two copies of capskip are installed (seen once, by accident). Keep one copy. |
| Timeout instead of network | CapSkip stopped answering after it took the task (seen). Alert on both labels. |
| Solve seconds jump, CapSkip unchanged | The event loop was blocked (seen). Turn default metrics on. |
FAQ
Can the worker run on another PC than CapSkip?
Yes. Put CapSkip in Server mode, set the host option of the client to that PC, and pass your key as apiKey if API Key Validation is on. The setup guide has the steps. No second machine took part in my tests. Server mode makes the app add a Windows Firewall rule of its own that accepts any source address, so an allow rule of yours with a narrower scope changes nothing. A block rule for each address you do not trust works instead, because Microsoft documents that a matching block rule wins over an allow rule (I did not test that).
Do I need a Prometheus server to try prom-client captcha metrics?
No. The endpoint is plain text, and scrape.mjs reads it the way a server would. I did not run a real one, so the alert rule above is untested.
Good prom-client captcha metrics come down to one wrapper, round-up bucket edges, a gauge released in the finally block and labels you can count on your fingers. The numbers describe a local captcha solver on your own PC, where a retry costs seconds and no fee, and other CAPTCHA types are on the Node.js solver overview.
