# Custom metrics from Node.js

You need a metric source token (`WT15_METRICS_TOKEN`, `wt15ms_…`): see [metric sources](https://docs.watchtower15.com/metrics/sources/) and the [ingest API](https://developer.watchtower15.com/ingest/metrics/) it wraps.

## Push points

```ts
const result = await wt15.ingest.metrics.push([
  { metric: 'orders.completed', metric_type: 'count', value: 1 },
  { metric: 'queue.depth', metric_type: 'level', value: 42, recorded_at: new Date() },
]);
result.accepted; // true when any chunk was accepted
result.count; // points stored
result.rejected; // every rejection reason, 0 where none
```

-   A point that names a `metric` carries `metric_type`, `count` or `level`; one by `metric_uuid` may omit it. A `value` must be a finite number.
-   The SDK stamps no time. A point without `recorded_at` is stamped by the server; a `Date` becomes epoch milliseconds.
-   `push()` cuts the points into chunks of at most 1,000 points and 1,000,000 bytes, gzips each and sends them in order. A chunk that fails throws with `partialResult` holding the chunks before it.
-   Keys: each chunk is sent under an `Idempotency-Key`. A chunk holding a point older than 30 days is keyed by its content, so a retry is the same batch; any other chunk gets a per-call nonce. Pass `{ idempotencyKey }` (1 to 100 visible ASCII characters) to choose your own: one chunk uses it as given, several use `<key>/0`, `<key>/1`, …. **Never reuse your own key for other points.**
-   `wt15.ingest.metrics.list()` returns the source’s metrics with their status, `maxMetrics` and `used`.

## The aggregator

```ts
import { Aggregator } from '@watchtower15/sdk';

const metrics = new Aggregator({
  client: wt15,
  allowList: { 'orders.created': 'count', 'queue.depth': 'level' },
  heartbeat: 'app.alive',
});
metrics.increment('orders.created'); // microseconds, never throws, never sends from here
metrics.gauge('queue.depth', 812);
process.on('SIGTERM', async () => {
  await metrics.close();
  process.exit(0);
});
```

`increment` and `gauge` only update memory. Buckets of 60 seconds are closed 5 seconds after their end and sent by a flush: one push per closed bucket, oldest first, without retries, within `maxRequests` (10) and 90 seconds a run. An **allow-list** names every key you count with its type: a key not listed is counted `not_allowed` and nothing is stored; each entry and the `heartbeat` key is checked at construction and a bad one is listed in `configProblems`. `enabled: false` stores and sends nothing.

-   **The timer.** The first `increment` or `gauge` starts a real interval (`flushIntervalMs`, 10 seconds by default, `false` for none) that sends closed buckets; it is `unref`’d, so it never keeps the process alive.
-   **`flush({ final })`** resolves to a `FlushReport` (`status`, `bucketsSent`, `requests`, `points`, `rejected`, `stopReason`, `errors`, `configProblems`), never rejects. `final: true` sends the open bucket too.
-   **`close({ timeoutMs })`** stops the timer and sends every bucket within its timeout (10 seconds), resolving to the report. A `beforeExit` hook runs one final flush if you forget.
-   **Failures are counted, never thrown.** A 401, a bad configuration, a redirect or a transport failure ends the run with the matching `stopReason` and keeps the bucket for the next run.
-   **One store per aggregator, per process.** Custom metrics keep every sample, so two processes’ points both count; there is nothing to share.

## Serverless

A function may freeze before the next minute: send what you counted before the invocation answers, or hand it to the platform. See [Serverless](https://developer.watchtower15.com/sdks/node/serverless/).

Source: https://developer.watchtower15.com/sdks/node/metrics/
