prometheus.ts
Overview
The [prometheus.ts](/projects/291/69100) file provides a dedicated class to encapsulate Prometheus metrics collection for blockchain API servers within the Unchained project. It leverages the `prom-client` library to define and register key runtime metrics that enable observability of HTTP request patterns and WebSocket client connections.
This file’s primary purpose is to initialize a Prometheus metrics registry scoped by a blockchain coinstack (e.g., Bitcoin, Ethereum) and to define three core metrics:
HTTP request count (with labels for method, route, and status code)
HTTP request latency histogram (duration in seconds)
WebSocket client connection count
In addition, it collects default Node.js process metrics (CPU, memory, garbage collection) automatically.
This modular setup facilitates consistent instrumentation of API servers, enabling Prometheus to scrape metrics for monitoring, alerting, and visualization.
Class: Prometheus
Description
The `Prometheus` class encapsulates the setup and registration of Prometheus metrics relevant to blockchain API servers. It abstracts the creation of a metrics registry with default labels and exposes pre-configured metrics for HTTP requests and WebSocket connections.
Constructor
constructor({ coinstack }: PrometheusArgs)
Parameters:
coinstack(string): The identifier for the blockchain coinstack (e.g.,"bitcoin","ethereum"). This label scopes all metrics to distinguish multiple blockchain services in a multi-service environment.
Behavior:
Creates a new Prometheus
Registryinstance.Sets the default label
coinstackon the registry.Registers default Node.js process metrics with the registry.
Registers the defined custom metrics (
httpRequestCounter,httpRequestDurationSeconds,websocketCount) with the registry.
Usage example:
import { Prometheus } from './prometheus'
const metrics = new Prometheus({ coinstack: 'bitcoin' })
Properties
register: client.Registry
The Prometheus
Registryinstance where all metrics are registered.Used to expose metrics for scraping.
metrics: {}
An object containing the following Prometheus metric instances:
Metric Name | Type | Description | Labels |
|---|---|---|---|
`httpRequestCounter` | Counter | Counts HTTP requests received | `method`, `route`, `statusCode` |
`httpRequestDurationSeconds` | Histogram | Measures HTTP request durations in seconds | `method`, `route`, `statusCode` |
`websocketCount` | Gauge | Tracks current number of connected WS clients | None |
Metrics Details
httpRequestCounterType:
CounterPurpose: Incremented each time an HTTP request is received.
Labels:
method(e.g.,GET,POST)route(the API route path)statusCode(HTTP response status code)
Usage: Used to measure request volume segmented by method, route, and response status.
httpRequestDurationSecondsType:
HistogramPurpose: Records the duration of individual HTTP requests.
Labels: Same as above (
method,route,statusCode)Usage: Enables latency analysis and tracking of slow endpoints.
websocketCountType:
GaugePurpose: Represents the current number of active WebSocket client connections.
Labels: None.
Usage: Tracks real-time connection load on WebSocket servers.
Implementation Details and Algorithms
The class uses
prom-client'sRegistryabstraction to group metrics and attach default labels. This design allows multiple coinstack services to run metrics collectors concurrently, each isolated by thecoinstacklabel.Default system metrics (CPU, memory, event loop lag, garbage collection stats) are automatically collected by calling
client.collectDefaultMetricswith the custom registry.Metrics are registered explicitly by iterating over the
metricsobject values and callingregister.registerMetric, ensuring all custom metrics are included in the registry.The use of label names on counters and histograms allows dimensioned metric aggregation in Prometheus, supporting queries like request counts and latencies per HTTP method or route.
Interaction with Other System Components
API Server Middleware: This class is intended to be instantiated in the API server setup code. HTTP request handlers and middleware will use the exposed metrics to increment counters and observe request durations.
WebSocket Connection Handlers: WebSocket server code updates the
websocketCountgauge in response to client connect and disconnect events.Prometheus Scraping: The
registerinstance exposes the/metricsendpoint through HTTP, which Prometheus scrapers query at intervals to collect metric samples.Kubernetes Monitoring Stack: Metrics exported by this class feed into cluster-wide Prometheus and Grafana setups for monitoring multi-blockchain deployments.
Alerting and Visualization: The data collected is foundational for alerting rules (e.g., high latency or dropped connections) and dashboard visualizations.
Usage Example
import { Prometheus } from './prometheus'
// Initialize metrics with blockchain coinstack label
const prometheusMetrics = new Prometheus({ coinstack: 'ethereum' })
// Increment HTTP request counter when a request arrives
function onHttpRequest(method: string, route: string, statusCode: string, durationSeconds: number) {
prometheusMetrics.metrics.httpRequestCounter.inc({ method, route, statusCode })
prometheusMetrics.metrics.httpRequestDurationSeconds.observe({ method, route, statusCode }, durationSeconds)
}
// Update WebSocket client count on connect/disconnect
function onWebSocketConnect() {
prometheusMetrics.metrics.websocketCount.inc()
}
function onWebSocketDisconnect() {
prometheusMetrics.metrics.websocketCount.dec()
}
Mermaid Class Diagram
classDiagram
class Prometheus {
+register: Registry
+metrics: object
+constructor({ coinstack: string })
}
class Counter {
<<from prom-client>>
}
class Histogram {
<<from prom-client>>
}
class Gauge {
<<from prom-client>>
}
Prometheus "1" o-- "1" Counter : httpRequestCounter
Prometheus "1" o-- "1" Histogram : httpRequestDurationSeconds
Prometheus "1" o-- "1" Gauge : websocketCount
Prometheus "1" o-- "1" Registry : register
Summary
The [prometheus.ts](/projects/291/69100) file defines a reusable `Prometheus` class that sets up a metrics registry tailored for blockchain API servers. It provides instrumentation points for HTTP request count and latency, as well as WebSocket client connections, all labeled by the blockchain coinstack.
This design supports scalable, multi-blockchain observability, seamlessly integrates with the Node.js runtime metrics, and enables comprehensive monitoring and alerting through the Prometheus ecosystem.
By isolating metrics setup in this class, the system promotes consistent instrumentation practices and simplifies integration with the broader monitoring and alerting infrastructure.