Skip to content

Monitor ​

Introduction ​

@plinthjs/monitor records high-volume numeric measurements and rolls them up into aggregates. Where the Inspector keeps individual entries you read one by one, the monitor is for questions you answer in bulk: which routes are slowest, what is the 95th-percentile duration of a query, which users make the most requests, how often does the cache miss.

bash
pnpm add @plinthjs/monitor

The recorder class is called Monitor. Each measurement is a small entry with a type, a key (the thing measured: a route, a SQL string, a queue name), an optional numeric value (usually a duration in milliseconds) and a timestamp. A store keeps the entries and computes aggregates grouped by key.

INFO

The monitor does not watch the framework by itself. You call the recorder from your own middleware, listeners and hooks. The package supplies builders for the common measurements so those calls stay short.

Creating a recorder ​

Create one Monitor per application and share it, for instance by binding it in a service provider.

ts
import { Monitor } from '@plinthjs/monitor'

const monitor = new Monitor()

Every option is optional:

ts
import { ArrayMonitorStore, Monitor } from '@plinthjs/monitor'

const monitor = new Monitor({
  store: new ArrayMonitorStore(), // where entries are kept
  now: () => Date.now(), // epoch-millisecond clock
  lazy: false, // buffer writes until flush() when true
})

Recording measurements ​

record(type, key, value?, tags?) stores one measurement and returns the MonitorEntry, or undefined if recording is disabled or a filter rejected it.

ts
monitor.record('slow_request', 'GET /reports', 2300)
monitor.record('user_request', '42')
monitor.record('custom_metric', 'checkout', 18, ['beta'])

The type is a free-form string. The built-in recorders use the names exposed on MonitorType:

ConstantValueKeyed byCarries a value
MonitorType.SlowQueryslow_querythe SQLduration (ms)
MonitorType.SlowRequestslow_requestthe routeduration (ms)
MonitorType.Exceptionexceptionerror classno
MonitorType.CacheHitcache_hitcache keyno
MonitorType.CacheMisscache_misscache keyno
MonitorType.UserRequestuser_requestuser idno
MonitorType.Queuequeuequeue nameduration (ms)

An entry without a value is an occurrence metric: you count it. An entry with a value can be summed, averaged or ranked.

Using the recorders ​

Each recorder is a pure function that returns an EntryDraft ({ type, key, value?, tags? }) ready to hand to ingestDraft. The threshold-gated ones return undefined for measurements that are not worth recording, so check before you ingest:

ts
import { slowQuery, slowRequest } from '@plinthjs/monitor'

const draft = slowRequest('GET /reports', 2300)
if (draft !== undefined) monitor.ingestDraft(draft)

The recorders are:

  • slowRequest(route, durationMs, options?) records a slow_request keyed by the route.
  • slowQuery(sql, durationMs, options?) records a slow_query keyed by the SQL.
  • exceptionEntry(error) records an exception keyed by the error class name, and tags it with that name.
  • cacheInteraction(key, hit) records cache_hit or cache_miss keyed by the cache key.
  • userRequest(userId) records a user_request keyed by the user id as a string.
  • queueEntry(queue, durationMs) records a queue entry keyed by the queue name, with the duration as its value.

Thresholds ​

slowRequest and slowQuery ignore anything faster than the threshold, which defaults to DEFAULT_SLOW_THRESHOLD (1000 ms). A measurement exactly at the threshold is recorded; anything strictly below returns undefined. Override it with { threshold }:

ts
slowRequest('GET /a', 900) // => undefined
slowRequest('GET /a', 1500) // => { type: 'slow_request', key: 'GET /a', value: 1500 }
slowQuery('select 1', 400, { threshold: 250 }) // recorded

Wiring a recorder into middleware ​

A middleware that times each request and records the slow ones:

ts
import { slowRequest, userRequest } from '@plinthjs/monitor'
import type { Middleware } from '@plinthjs/http'

const recordMetrics: Middleware = async (request, next) => {
  const started = Date.now()
  const response = await next(request)
  const draft = slowRequest(`${request.method()} ${request.path()}`, Date.now() - started)
  if (draft !== undefined) monitor.ingestDraft(draft)
  return response
}

Use the route pattern rather than the raw path as the key when you can, so that /users/1 and /users/2 aggregate together. For exceptions, call monitor.ingestDraft(exceptionEntry(error)) from your error handler; for cache and queue timings, call the matching recorder from the place that already knows the result.

Reading aggregates ​

aggregate(type, query?) groups the entries of one type by key and computes one value per group. Each row is { key, value, count }, plus a bucket when you ask for periods. Rows are sorted by value, largest first by default.

ts
monitor.aggregate('slow_request')
// => [
//   { key: 'GET /a', value: 2, count: 2 },
//   { key: 'GET /b', value: 1, count: 1 },
// ]

With no aggregate option the function is count, so the value above is how many times each route was slow. The other functions work on the numeric values:

AggregateMeaning
countHow many entries (ignores values)
sumTotal of the values
avgMean of the values
minSmallest value
maxLargest value
p9595th percentile (nearest-rank on the sorted values)

Entries without a value are skipped by the value-based functions, and a group with no values at all folds to 0.

ts
monitor.aggregate('slow_request', { aggregate: 'max', limit: 5 }) // the five slowest routes
monitor.aggregate('queue', { aggregate: 'avg' }) // => [{ key: 'default', value: 50, count: 2 }]
monitor.aggregate('queue', { aggregate: 'p95' }) // => [{ key: 'default', value: 60, count: 2 }]

The query accepts:

  • aggregate: one of the functions above (default count).
  • orderBy: 'desc' (default) or 'asc', applied to the row values.
  • limit: keep only the first N rows after ordering, which gives you a top-N list.
  • since and before: restrict to entries at or after since and strictly before before (epoch milliseconds).
  • period: bucket entries into time windows (see below).

Time windows ​

Set period to a width in seconds to group by (key, window). Windows are aligned to the epoch, and each row gets a bucket: the window's start instant in epoch milliseconds.

ts
monitor.aggregate('queue', { aggregate: 'sum', period: 60, orderBy: 'asc' })
// => [
//   { key: 'default', value: 100, count: 2, bucket: 0 },
//   { key: 'default', value: 100, count: 1, bucket: 60000 },
// ]

Rows are sorted by value across all buckets, not by time. If you are drawing a time series, sort the rows by bucket yourself.

Combine since with period for charts over a recent range, for example the last hour in one-minute windows:

ts
const hourAgo = Date.now() - 60 * 60 * 1000
monitor.aggregate('slow_request', { aggregate: 'count', period: 60, since: hourAgo })

Reading raw entries and values ​

entries(filter?) returns raw measurements, newest first. The filter takes type, key, tag, since, before and limit, all combined with AND.

ts
monitor.entries({ type: 'queue', since: Date.now() - 60_000 })
monitor.entries({ type: 'exception', tag: 'TypeError', limit: 10 })

values(type) returns just the numeric values for a type, newest first, which is handy for computing your own statistics:

ts
monitor.values('queue') // => [100, 60, 40]

Lazy mode and flushing ​

By default every record call writes straight to the store. In lazy mode the recorder buffers entries and writes them in one go, which is cheaper on a hot path or when the store is slow.

ts
const monitor = new Monitor({ lazy: true })

monitor.record('queue', 'default', 40)
monitor.record('queue', 'default', 60)
monitor.pending() // => 2

monitor.flush() // => 2 (entries written to the store)
monitor.pending() // => 0

ingest() is a synonym for flush(). In either mode, every read (aggregate, values, entries) flushes the buffer first, so you never see stale results. Call flush() yourself on an interval, and on shutdown, so buffered entries are not lost. With the persistent server that is one line:

ts
worker.onTick(() => monitor.flush(), 5_000).onTerminate(() => void monitor.flush())

WARNING

Buffered entries live only in the process that recorded them. Anything still pending when the process exits is gone unless you flush first.

Turning recording off and filtering ​

disable() stops recording (record returns undefined), enable() resumes, and recording() reports the state.

filter() registers a gate that can reject an entry before it is buffered. Return false to drop it. Use it to ignore noise such as health checks:

ts
monitor.filter((entry) => entry.key !== 'GET /health')

Both return the recorder, so they chain.

Pruning ​

Entries accumulate forever until you remove them. prune(before) deletes everything recorded strictly before an epoch-millisecond instant and returns how many entries it removed; clear() empties the buffer and the store.

ts
const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
monitor.prune(sevenDaysAgo) // => 4210

Run it from a scheduled task so storage stays bounded. Note that prune does not flush first, so call flush() before it if you want buffered entries considered.

Writing a custom store ​

ArrayMonitorStore is in-memory and process-local. To persist measurements, implement MonitorStore and pass it as the store option. It needs four methods: record(entries) to append a batch, entries(filter?) to list newest first, aggregate(type, options) to compute rows (the options carry aggregate, period, since and before), and prune(before) plus clear(). The recorder does the ordering and limit of aggregate rows itself, so the store only has to return the grouped rows.

Testing ​

Inject the clock so timestamps and time windows are deterministic:

ts
import { expect, it } from 'vitest'
import { Monitor, queueEntry } from '@plinthjs/monitor'

it('averages queue timings', () => {
  const monitor = new Monitor({ now: () => 10_000 })
  monitor.ingestDraft(queueEntry('default', 40))
  monitor.ingestDraft(queueEntry('default', 60))

  expect(monitor.aggregate('queue', { aggregate: 'avg' })).toEqual([
    { key: 'default', value: 50, count: 2 },
  ])
})

See Testing for the rest of the framework's test seams.

Released under the MIT License.