Skip to content
Buy me a coffee

createStats

createStats() keeps rolling counts and latency percentiles in memory, from the same telemetry the metric exporters use. Use it for a health endpoint, a periodic log line, an admin page or a test assertion, when you don’t run Prometheus or OpenTelemetry (or want the numbers inside the process). It runs anywhere, browsers included.

import {
function createStats(options?: StatsOptions): Stats

Opossum-style in-process statistics for every pipeline (or the ones named in pipeline), built on onTelemetry: counts over a rolling window and since start, plus latency mean / max / percentiles of whole executions.

const stats = createStats({ pipeline: 'payments' });
app.get('/health/payments', () => stats.snapshot());
stats.onSnapshot((s) => log.info(s), '30s');

createStats
} from '@ylcnfrht/resilience';
const
const stats: Stats
stats
=
function createStats(options?: StatsOptions): Stats

Opossum-style in-process statistics for every pipeline (or the ones named in pipeline), built on onTelemetry: counts over a rolling window and since start, plus latency mean / max / percentiles of whole executions.

const stats = createStats({ pipeline: 'payments' });
app.get('/health/payments', () => stats.snapshot());
stats.onSnapshot((s) => log.info(s), '30s');

createStats
({
StatsOptions.pipeline?: string | string[] | undefined

Only count these pipelines (by name). Default: every pipeline in the process.

pipeline
: 'payments',
StatsOptions.window?: Duration | undefined

Length of the rolling window. Default 10 s, kept as 10 buckets: data ages out one bucket (window / 10) at a time.

window
: '1m' });
const
const s: StatsSnapshot
s
=
const stats: Stats
stats
.
Stats.snapshot(): StatsSnapshot
snapshot
();
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@see ― source

console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@since ― v0.1.100

log
(`${
const s: StatsSnapshot
s
.
Counts.failures: number
failures
}/${
const s: StatsSnapshot
s
.
Counts.executions: number

Finished pipeline executions (OnPipelineExecuted).

executions
} failed, p99 ${
const s: StatsSnapshot
s
.
Counts.latency: LatencyStats
latency
.
number
p99
.
Number.toFixed(fractionDigits?: number): string

Returns a string representing a number in fixed-point notation.

@param ― fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.

toFixed
(1)} ms, ${
const s: StatsSnapshot
s
.
Counts.rejections: number

Calls refused by an open circuit, a rate limiter, a bulkhead or a held lock.

rejections
} rejected`);
Option Type Default Description
pipeline string | string[] every pipeline Only count the pipelines with these names.
window Duration '10s' Length of the rolling window.
percentiles number[] [0.5, 0.9, 0.99] Latency percentiles to report, as fractions between 0 and 1.
timeProvider TimeProvider system clock, unref’d timers For tests.
{
"timestamp": 1762600000000, "window": 60000,
"executions": 1840, "successes": 1795, "failures": 45,
"timeouts": 12, "retries": 51, "rejections": 20, "fallbacks": 30,
"cacheHits": 0, "cacheMisses": 0, "coalesced": 0,
"latency": { "mean": 84.2, "max": 2003.1, "p50": 61.3, "p90": 140.9, "p99": 812.5 },
"total": { "executions": 90211, "successes": 89012, "...": "same fields, since createStats()" }
}
Field Counts
executions Finished executions (OnPipelineExecuted).
successes, failures Executions by final outcome. A call saved by a fallback is a success.
timeouts OnTimeout events: every timed-out attempt, so it can be higher than failures when retries recover.
retries OnRetry events.
rejections Calls refused by an open circuit, a rate limiter, a concurrency limiter or a held lock.
fallbacks OnFallback events.
cacheHits, cacheMisses, coalesced Cache strategy events.
latency Of whole executions, in ms: mean, max and one p<N> key per percentile (p50, p90, p99, p99.9…).
timestamp, window When the snapshot was taken (epoch ms) and the window length (ms).
total The same counts and latency since createStats() was called.
  • The window is kept as 10 buckets. Data ages out one bucket (window / 10) at a time, so a 1-minute window moves in 6-second steps.
  • Latency goes into a log-scale histogram with 2% wide bins. mean and max are exact; each percentile is within about 1% of the true sample, and clamped to the exact min and max, so small samples report real values.
  • Memory is bounded by the number of distinct bins (about 1100 between 1 µs and 1 hour), not by traffic.
const
const stats: Stats
stats
=
function createStats(options?: StatsOptions): Stats

Opossum-style in-process statistics for every pipeline (or the ones named in pipeline), built on onTelemetry: counts over a rolling window and since start, plus latency mean / max / percentiles of whole executions.

const stats = createStats({ pipeline: 'payments' });
app.get('/health/payments', () => stats.snapshot());
stats.onSnapshot((s) => log.info(s), '30s');

createStats
({
StatsOptions.pipeline?: string | string[] | undefined

Only count these pipelines (by name). Default: every pipeline in the process.

pipeline
: ['payments', 'inventory'] });
const
const stop: () => void
stop
=
const stats: Stats
stats
.
Stats.onSnapshot(listener: (snapshot: StatsSnapshot) => void, interval: Duration): () => void

Calls listener with a snapshot every interval. Returns a function that stops it.

onSnapshot
((
s: StatsSnapshot
s
) =>
const log: {
info(o: object): void;
}
log
.
function info(o: object): void
info
({
msg: string
msg
: 'resilience stats', ...
s: StatsSnapshot
s
}), '30s');
// on shutdown:
const stop: () => void
stop
(); // this listener only
const stats: Stats
stats
.
Stats.dispose(): void

Stops listening to telemetry and every onSnapshot timer.

dispose
(); // stop counting, and every listener

Timers are unref’d: they don’t keep the process alive.

const
const stats: Stats
stats
=
function createStats(options?: StatsOptions): Stats

Opossum-style in-process statistics for every pipeline (or the ones named in pipeline), built on onTelemetry: counts over a rolling window and since start, plus latency mean / max / percentiles of whole executions.

const stats = createStats({ pipeline: 'payments' });
app.get('/health/payments', () => stats.snapshot());
stats.onSnapshot((s) => log.info(s), '30s');

createStats
({
StatsOptions.pipeline?: string | string[] | undefined

Only count these pipelines (by name). Default: every pipeline in the process.

pipeline
: 'payments',
StatsOptions.window?: Duration | undefined

Length of the rolling window. Default 10 s, kept as 10 buckets: data ages out one bucket (window / 10) at a time.

window
: '1m' });
export function
function paymentsHealth(): {
status: string;
errorRate: number;
p99Ms: number;
rejections: number;
window: string;
}
paymentsHealth
() {
const
const s: StatsSnapshot
s
=
const stats: Stats
stats
.
Stats.snapshot(): StatsSnapshot
snapshot
();
const
const errorRate: number
errorRate
=
const s: StatsSnapshot
s
.
Counts.executions: number

Finished pipeline executions (OnPipelineExecuted).

executions
?
const s: StatsSnapshot
s
.
Counts.failures: number
failures
/
const s: StatsSnapshot
s
.
Counts.executions: number

Finished pipeline executions (OnPipelineExecuted).

executions
: 0;
const
const status: "degraded" | "ok"
status
=
const errorRate: number
errorRate
> 0.2 ||
const s: StatsSnapshot
s
.
Counts.latency: LatencyStats
latency
.
number
p99
> 2000 ? 'degraded' : 'ok';
return {
status: string
status
,
errorRate: number
errorRate
:
var Number: NumberConstructor
(value?: any) => number

An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

Number
(
const errorRate: number
errorRate
.
Number.toFixed(fractionDigits?: number): string

Returns a string representing a number in fixed-point notation.

@param ― fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.

toFixed
(3)),
p99Ms: number
p99Ms
:
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.round(x: number): number

Returns a supplied numeric expression rounded to the nearest integer.

@param ― x The value to be rounded to the nearest integer.

round
(
const s: StatsSnapshot
s
.
Counts.latency: LatencyStats
latency
.
number
p99
),
rejections: number
rejections
:
const s: StatsSnapshot
s
.
Counts.rejections: number

Calls refused by an open circuit, a rate limiter, a bulkhead or a held lock.

rejections
,
window: string
window
: `${
const s: StatsSnapshot
s
.
StatsSnapshot.window: number

Length of the rolling window the top-level counts cover, in ms.

window
/ 1000}s`,
};
}
// app.get('/health/payments', (req, res) => res.json(paymentsHealth()));

For breaker states, add registry.circuitBreakers() from a ResiliencePipelineRegistry.