Prometheus exporter
The Prometheus exporter turns the in-process metrics registry
into the Prometheus text format that Prometheus / Grafana /
Thanos scrape from /metrics.
import { ActorSystem } from 'actor-ts';import { MetricsExtensionId, exportPrometheus } from 'actor-ts/metrics';
const system = ActorSystem.create('my-app');const metrics = system.extension(MetricsExtensionId);
// Inside an HTTP handler:get(async () => { const text = exportPrometheus(metrics.get()); return { status: 200, body: text, contentType: 'text/plain; version=0.0.4' };});Returns a single string in Prometheus 0.0.4 exposition format:
# HELP http_requests_total Total HTTP requests# TYPE http_requests_total counterhttp_requests_total{route="/orders"} 1234http_requests_total{route="/users"} 567
# HELP sessions_active Currently active sessions# TYPE sessions_active gaugesessions_active 123
# HELP http_request_duration_ms HTTP request latency# TYPE http_request_duration_ms histogramhttp_request_duration_ms_bucket{route="/orders",le="10"} 100http_request_duration_ms_bucket{route="/orders",le="50"} 250http_request_duration_ms_bucket{route="/orders",le="+Inf"} 300http_request_duration_ms_count{route="/orders"} 300http_request_duration_ms_sum{route="/orders"} 12450Via the management endpoint
Section titled “Via the management endpoint”The easiest path is via the management routes:
import { managementRoutes } from 'actor-ts/management';
// cluster can be null when you only need the metrics endpointconst routes = managementRoutes(system, null, { enableMetricsEndpoint: true, // ← exposes GET /metrics});await system.http(8558).bind(routes);Prometheus scrape config:
scrape_configs: - job_name: 'actor-ts' static_configs: - targets: ['my-app:8558']The management server runs on a separate port from your app’s main HTTP server. Typical pattern: app on 8080 (public), management on 8558 (internal-only).
This route reads the registry through collect(), so it needs a
registry that can be read that way — the framework’s own can. The
prom-client bridge
cannot: it forwards its writes and keeps no snapshot. With that
bridge installed the route answers 503 naming the conflict,
rather than 200 with an empty body that Prometheus would accept
as a healthy target with no series. Scrape prom-client’s own
/metrics route in that setup and leave enableMetricsEndpoint
off.
Scope: per process, per thread
Section titled “Scope: per process, per thread”Every ActorSystem owns its own registry, and GET /metrics exports
exactly the one belonging to the system that bound the route. Nothing
aggregates across systems, and two deployment shapes follow from that:
-
Cluster nodes. Each node exports itself. That is the Prometheus model — scrape every instance, aggregate in the TSDB — and it is the opposite of what DevTools does, which federates figures across nodes for its own views. A number that agrees across nodes in DevTools is expected to differ per target under
/metrics. -
Worker threads. Each worker of a worker mesh — including the ones
actor-ts.parallelism.workersstarts for you (parallelism) — boots its ownActorSystemwith its own registry, and no management endpoint runs inside a worker. The mesh relays them: everyactor-ts.worker-mesh.metrics-relay-interval(default10s) the main thread pulls each worker’s registry and exports it beside its own, soGET /metricson the main thread is the whole process. While the relay runs, every series carries athreadlabel —mainfor the main thread’s own samples,worker-0,worker-1, … for each worker’s (the slot, which is also the thread’s name) — because two threads report the same stock families under the same labels, and the label is what keeps them apart. Aggregate across it for a process figure:# Messages delivered by the whole process, all threadssum without (thread) (rate(actor_messages_delivered_total[5m]))# …and per thread, to see whether the offloaded actors carry the loadsum by (thread) (rate(actor_messages_delivered_total[5m]))# A worker that has stopped answering the relayworker_mesh_snapshot_age_seconds > 30A worker’s figures are at most one relay interval old. A worker that is alive but has stopped answering keeps its last snapshot exported — a series that vanishes is the failure mode
503above exists to prevent — andworker_mesh_snapshot_age_seconds{worker="worker-N"}on the main thread says for how long; a worker that leaves the mesh takes its series with it, and a respawned slot comes back under the same label with its counters starting over, a resetrate()handles. The first request goes out when the mesh starts and it is also what switches a worker’s registry on, so nothing has to be enabled inside a worker; a worker’s counting starts with its first request, so anenable()on the main thread after the mesh is up takes effect on the next tick.metrics-relay-interval = 0switches the relay off, and with it thethreadlabel: a single-threaded system, or a mesh with the relay off, exports exactly the bytes it exported before the relay existed. Switching workers on is therefore the one moment every series’ label set changes — a rule over a raw family (actor_mailbox_dropped_total > 0) keeps working, one that compares a family against itself across the change needs thesum without (thread)above. The relay covers a mesh started by hand withWorkerMesh.startand the one the parallelism extension starts alike; OffloadPool workers run noActorSystem, and theoffload_*families are the main thread’s already.
Manual wiring
Section titled “Manual wiring”If you’re not using the management routes, route a GET /metrics
yourself:
import { path, get } from 'actor-ts/http';import { exportPrometheus } from 'actor-ts/metrics';
const routes = path('metrics', get(async () => ({ status: 200, body: exportPrometheus(metrics.get()), contentType: 'text/plain; version=0.0.4', headers: {}, })),);exportPrometheus(registry) and prometheusHandler(registry) render
that registry — the main thread’s own — and nothing else. On a
system running a worker mesh the relayed worker
snapshots live on the MetricsExtension, not in the registry, so the
merged view the management route serves is
renderPrometheusSamples(collectAll()):
import { path, get } from 'actor-ts/http';import { MetricsExtensionId, renderPrometheusSamples } from 'actor-ts/metrics';
const routes = path('metrics', get(async () => ({ status: 200, body: renderPrometheusSamples(system.extension(MetricsExtensionId).collectAll()), contentType: 'text/plain; version=0.0.4', headers: {}, })),);collectAll() is collect() until a mesh registers its relay, so the
second form is safe to use everywhere and the first is a documented
half on a mesh.
Bind on a dedicated port if you can — Prometheus’s scrapes are periodic and shouldn’t share the app port.
The renderer trusts its input
Section titled “The renderer trusts its input”renderPrometheusSamples writes family names and label keys raw —
the text format offers no escaping for either position, because they
are its grammar. What makes that safe is the registry: it refuses a
name outside [a-zA-Z_:][a-zA-Z0-9_:]* and a label key outside
[a-zA-Z_][a-zA-Z0-9_]* when the series is minted, so anything it
collected has already been checked. The renderer does not check again,
deliberately — that would cost a regular expression per family on every
scrape, for a question that was answered once at registration.
So the obligation travels with the input. If you implement
MetricsRegistry yourself, or hand renderPrometheusSamples a list you
assembled rather than collected, you own that check. A sample named
x_total 1\nnode_up{job="prod"} 0\n# renders as those three lines, and
whatever scrapes it cannot tell the forged node_up from a real one —
an alert on node_up == 0 is silenced as effectively as by a fixed
outage. The two grammars are exported for exactly this, and the two
reserved keys with them:
import { PROMETHEUS_LABEL_NAME_PATTERN, PROMETHEUS_METRIC_NAME_PATTERN, RESERVED_LABEL_PREFIX, THREAD_LABEL, renderPrometheusSamples, type MetricSample,} from 'actor-ts/metrics';
const usableLabelKey = (key: string): boolean => PROMETHEUS_LABEL_NAME_PATTERN.test(key) && key !== THREAD_LABEL && !key.startsWith(RESERVED_LABEL_PREFIX);
const trustworthy = (sample: MetricSample): boolean => PROMETHEUS_METRIC_NAME_PATTERN.test(sample.name) && Object.keys(sample.labels).every(usableLabelKey);
// `samples` came from somewhere this package never checked.const renderForeign = (samples: ReadonlyArray<MetricSample>): string => renderPrometheusSamples(samples.filter(trustworthy));The grammars are the injection half; the two reserved keys are the forgery
the grammars do not catch. thread is the label the exposition stamps
itself while a worker mesh is relaying (#1570), and __ is the server’s
own namespace — a __name__ among a sample’s labels is honoured by a
scrape job running honor_labels: true, which then files the sample under
whatever name that label carries (#1513).
The worker-mesh relay is the worked example: a snapshot arriving from a
worker crosses a thread boundary, so the relay re-checks every name and
every label key — both grammars and both reservations, through the same
helper the registry uses — before the samples reach the renderer. Nothing
minted by system.metrics needs this: the check already happened at the
call that minted it.
Naming conventions
Section titled “Naming conventions”http_requests_total # counter — `_total` suffixsessions_active # gauge — no suffixhttp_request_duration_seconds # histogram — _bucket / _count / _sumprocess_cpu_seconds_total # counter again — Prometheus namingPrometheus has conventions (naming guide):
- Counters end in
_total(or describe what’s counted). - Histograms / timers include the unit in the name
(
_seconds,_ms,_bytes). _count/_sumare framework-appended suffixes for histograms.- Labels are snake_case strings.
The framework doesn’t enforce these — but Prometheus tooling expects them.
Scrape cadence vs gauge update rate
Section titled “Scrape cadence vs gauge update rate”- Scrape every 15-30 seconds — Prometheus default.
- Update gauges at any cadence — Prometheus only sees the value at scrape time.
- Counters can be incremented at any rate; Prometheus computes the rate from successive scrapes.
For very-fast-changing values (memory usage, mailbox depth), the gauge may be stale by the time it’s scraped. That’s fine — Prometheus is eventually consistent with its samples.
Exposition format details
Section titled “Exposition format details”| Series | Format |
|---|---|
| Counter | One line per series. metric_name{labels} value |
| Gauge | Same as counter. |
| Histogram | One _bucket{le=N} line per bucket + _count + _sum. |
The exporter handles the formatting; you don’t construct it manually.
A label value is the one field that carries data, and the 0.0.4 escape
table defines exactly three escapes for it — \\, \n and ". The
exporter emits those three and nothing else: every other C0 control
character (carriage return, NUL, the unit separator, …) is removed
from the value and from the # HELP text rather than escaped, because an
escape outside that table makes prometheus/common-based readers —
Pushgateway, the node_exporter textfile collector, promtool check metrics — reject the whole scrape body, not just the one series. A
tab survives; so does a line feed, as \n.
The same strip also runs when a series is minted, one layer below the
exporter, so two values that differ only in control characters are
one series whose counter sums rather than two. Measured:
counter('m_total', { msg: 'ab' }).inc(1) beside
counter('m_total', { msg: 'a\x1fb' }).inc(2) leaves the registry
holding one series and renders the single row m_total{msg="ab"} 3.
That the two merge is a correctness property, not a convenience. Until #1414 the strip ran at render time only, the registry kept two children, and the body carried two rows whose metric name and label set were byte-identical — a duplicated series, which a Prometheus scrape rejects by rejecting the whole body, so one label value with a unit separator in it took every other family down with it.
A control character in a label value is still a bug at its source, so strip or replace it there rather than relying on the exporter: the merge keeps the exposition valid, it does not make the two subjects one subject.
Where to next
Section titled “Where to next”- Observability overview — the bigger picture.
- Core metrics — the four primitives.
- Management overview —
the easy way to expose
/metrics. - Stock metrics — the framework’s auto-recorded metrics that appear here.
exportPrometheus, prometheusHandler and renderPrometheusSamples
ship from the actor-ts/metrics sub-path. The generated
API reference is built from the root actor-ts barrel alone,
so this page is the reference for the three of them.
