@quicore/tracelet-runtime
v0.5.0
Published
Dependency-free Node.js process and event-loop sampler with explicit lifecycle and cached snapshots
Readme
@quicore/tracelet-runtime 0.5.0
A dependency-free Node.js process/runtime sampler, independent of Tracelet core, OpenTelemetry, exporters and network access. Collection is explicit.
Install
npm install @quicore/tracelet-runtimeRequires Node.js 18 or newer. Ready-to-run CommonJS and ESM imports are supported.
Quick start
import { createRuntimeSampler } from '@quicore/tracelet-runtime';
const sampler = createRuntimeSampler().start();
// Application work continues; collection runs every 10 seconds by default.
const snapshot = sampler.toSnapshot(); // Detached cached data; no recollection.
// During application shutdown:
sampler.stop();CommonJS: const { createRuntimeSampler } = require('@quicore/tracelet-runtime').
Exports: createRuntimeSampler and RUNTIME_SCHEMA_VERSION (currently 1).
API
| API | Behavior |
| --- | --- |
| createRuntimeSampler(options = {}) | Passive construction, no timer or monitor |
| start() | Chainable/idempotent; initial sample, fresh baselines, unref'ed timer |
| stop() | Chainable/idempotent; releases timer/monitor and ownership, retains cached data |
| sample() | Collects once if running, then returns a snapshot; stopped samplers only read cache |
| toSnapshot() | Detached cached snapshot; only freshness ages use a new monotonic clock read |
| isRunning | Boolean lifecycle state |
| Option | Default | Constraint | | --- | --- | --- | | intervalMs | 10000 | Integer 10–2147483647 | | resolutionMs | 20 | Integer 1–1000; event-loop monitor resolution | | allowWorker | false | Boolean; workers require explicit true |
One active sampler is allowed per JavaScript realm. A shared symbol claim protects against duplicate package copies in that realm. Another active sampler makes start throw until the owner stops. This does not coordinate other VM realms, unrelated instrumentation or processes. Select one source for each runtime metric.
No signal handlers are installed. Running timers/monitors do not keep Node alive. Unref is not cleanup: call stop when sampling is no longer needed. Restart creates a fresh monitor and delta baselines, excluding stopped time. Diagnostics survive restarts. No module import starts sampling.
Snapshot fields (schema 1)
| Field | Meaning | | --- | --- | | running | Current controller state | | scope | pid, threadId, isMainThread, processMetricsEnabled | | config | intervalMs, resolutionMs | | status | uninitialized, ok, partial, error; describes the last collection | | sampledAtEpochMs | Wall-clock timestamp of last attempt, or null | | intervalSeconds | Monotonic elapsed time since prior attempt, or null | | sampleAgeSeconds | Age of newest attempt, including partial/error attempts | | lastSuccessfulSampleAgeSeconds | Age of latest collection with no source failures | | process.cpu | userSeconds, systemSeconds, totalSeconds, utilization | | process.rssBytes / uptimeSeconds | Process RSS and process uptime | | node.memory | heapUsedBytes, heapTotalBytes, externalBytes, arrayBuffersBytes | | node.eventLoop.utilization | Active/(active+idle) over the observed interval | | node.eventLoop.delay | sampleCount, intervalSeconds, meanSeconds, maxSeconds, p50Seconds, p95Seconds, p99Seconds | | diagnostics | samples, successfulSamples, partialSamples, failedSamples, skippedSamples, errors |
Values/groups can be null. A worker's whole process group is null. Fixed error keys are clock, cpu, memory, uptime, eventLoopUtilization, eventLoopDelay, monitor and timer. Counters saturate at MAX_SAFE_INTEGER; raw error strings are not retained.
CPU totals are cumulative process seconds. CPU utilization is delta user+system CPU seconds / actual monotonic elapsed seconds, in core equivalents, and may exceed 1. It is not percent of host/container capacity. RSS is process-wide while heap/external/array-buffer values are isolate-local. Array buffers are included in external memory: do not sum both. Native memory collection can be expensive for large processes. Node process API
Very short/manual intervals can produce noisy CPU ratios because of operating-system counter granularity. Prefer the default cadence unless the actual workload justifies another interval; accepted configuration limits are not precision guarantees.
Event-loop utilization is distinct from CPU utilization. Delay monitor observations are converted from nanoseconds to seconds; they include timer scheduling effects and resolution, and are not request latencies. Node performance APIs
Initial delta metrics and nonpositive intervals are null. An empty delay histogram has sampleCount 0 and null statistics; unavailable histograms have sampleCount null. No internal sentinel/NaN values are emitted. Capture resets the monitor once; cached readers never reset it. Local delay percentiles cannot be merged into a global percentile or recorded as raw latency observations.
Failures invalidate affected metric groups instead of retaining stale values. Failed delta sources establish a fresh baseline on recovery. Clock reversal invalidates the interval; wall-clock epoch timestamps may independently move back. Status ok includes valid initial samples with unavailable deltas/empty histograms. A stopped sampler can retain an ok cached sample with increasing age. Fresh sampleAgeSeconds does not establish that a partial/error sample succeeded; consult status and lastSuccessfulSampleAgeSeconds too.
Threads, failures and limits
Worker construction requires { allowWorker: true }. Workers expose their own heap
and event-loop observations, labeled with threadId; process CPU/uptime are not read
and process RSS is not emitted. Main-thread heap and event-loop measurements are
not totals across worker isolates. PM2/cluster/child processes may each sample;
external resource identity and aggregation are the application's responsibility.
Failed memory fields make that memory group unavailable. Failed monitor setup degrades delay metrics; other sources continue. Failed histogram reset disables the monitor to prevent replaying old intervals. Restart retries initialization. Invalid options, duplicate ownership and timer setup failure throw at startup; timer setup failure cleans up owned resources. Cleanup failures are diagnosed. Sampling is synchronous and reentrant attempts are skipped/countable.
The sampler keeps one cache, small delta baselines and one native histogram, with no event history/export queue. This is not a hard process CPU/RSS budget. It does not read tenants, credentials or environment variables, normalize against unknown container limits, or collect host disk/network/Kubernetes inventory. Host metrics remain Collector/deployment work. This package contains no exporter or vendor connection.
OpenTelemetry integration
Pass this sampler to @quicore/tracelet-otel through its runtimeSampler option
when using an application-owned OpenTelemetry meter. The application remains
responsible for starting and stopping this sampler. No core or OpenTelemetry
dependency is required for standalone use.
Compatibility and limitations
Tested on Windows with Node 18.20.8, 20.20.0, 22.22.0 and 24.13.0. Choose a maintained Node release for deployment. Other operating systems, sustained-load behavior and application-specific resource budgets need deployment validation. Process metrics are not host or container-capacity metrics.
License
MIT. See LICENSE.
