npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@onebun/metrics

v0.2.0

Published

Prometheus-compatible metrics for OneBun framework - HTTP, system, and custom metrics

Readme

@onebun/metrics

Prometheus-compatible metrics module for OneBun framework providing automatic HTTP request metrics, system metrics, and custom metrics API.

Features

  • 📊 Automatic HTTP Metrics - Automatically collects HTTP request duration, count, and status codes
  • 🖥️ System Metrics - Memory usage, CPU usage, and process uptime
  • 🗑️ GC Metrics - Garbage collection duration and frequency
  • 🎯 Custom Metrics - Easy to use API for creating counters, gauges, histograms, and summaries
  • 🏷️ Prometheus Compatible - Standard Prometheus exposition format
  • 🎨 Decorators - Method decorators for automatic metrics collection
  • Effect.js Integration - Full integration with Effect.js ecosystem

Installation

bun add @onebun/metrics

Basic Usage

Application Setup

import { OneBunApplication } from '@onebun/core';
import { AppModule } from './app.module';

const app = new OneBunApplication(AppModule, {
  metrics: {
    enabled: true,
    path: '/metrics',
    collectHttpMetrics: true,
    collectSystemMetrics: true,
    collectGcMetrics: true,
    prefix: 'myapp_'
  }
});

await app.start();

Custom Metrics in Services

import { Service } from '@onebun/core';
import { MetricsService, MetricType } from '@onebun/metrics';

@Service()
export class UserService {
  private userLoginCounter: Counter<string>;
  private activeUsersGauge: Gauge<string>;

  constructor(private metricsService: MetricsService) {
    // Create custom metrics
    this.userLoginCounter = this.metricsService.createCounter({
      name: 'user_logins_total',
      help: 'Total number of user logins',
      labelNames: ['method', 'status']
    });

    this.activeUsersGauge = this.metricsService.createGauge({
      name: 'active_users',
      help: 'Number of currently active users'
    });
  }

  async login(method: string): Promise<void> {
    try {
      // Login logic here
      this.userLoginCounter.inc({ method, status: 'success' });
      this.activeUsersGauge.inc();
    } catch (error) {
      this.userLoginCounter.inc({ method, status: 'failure' });
      throw error;
    }
  }
}

Method Decorators

import { Controller, Get } from '@onebun/core';
import { MeasureTime, CountCalls } from '@onebun/metrics';

@Controller('/api')
export class ApiController {
  
  @Get('/heavy-operation')
  @MeasureTime('heavy_operation_duration')
  @CountCalls('heavy_operation_calls')
  async heavyOperation(): Promise<any> {
    // This method's execution time and call count will be automatically tracked
    await someHeavyWork();
    return { success: true };
  }
}

Configuration Options

interface MetricsOptions {
  // Enable/disable metrics collection (default: true)
  enabled?: boolean;

  // HTTP path for metrics endpoint (default: '/metrics')
  path?: string;

  // Default labels for all metrics
  defaultLabels?: Record<string, string>;

  // Enable HTTP request metrics (default: true)
  collectHttpMetrics?: boolean;

  // Enable system metrics (default: true)
  collectSystemMetrics?: boolean;

  // Enable GC metrics (default: true)
  collectGcMetrics?: boolean;

  // System metrics collection interval in ms (default: 5000)
  systemMetricsInterval?: number;

  // Metric name prefix (default: 'onebun_')
  prefix?: string;

  // HTTP duration histogram buckets
  httpDurationBuckets?: number[];
}

Automatic Metrics

When enabled, the following metrics are automatically collected:

HTTP Metrics

  • {prefix}http_requests_total - Total HTTP requests by method, route, status code, controller, action
  • {prefix}http_request_duration_seconds - HTTP request duration histogram

System Metrics

  • {prefix}memory_usage_bytes - Memory usage by type (rss, heap_used, heap_total, external)
  • {prefix}cpu_usage_ratio - CPU usage ratio
  • {prefix}uptime_seconds - Process uptime

GC Metrics (from prom-client)

  • {prefix}nodejs_gc_duration_seconds - Garbage collection duration
  • {prefix}nodejs_heap_* - Various heap metrics
  • {prefix}nodejs_version_info - Node.js version information

Custom Metrics API

Counter

const requestCounter = metricsService.createCounter({
  name: 'requests_total',
  help: 'Total requests',
  labelNames: ['method', 'endpoint']
});

requestCounter.inc({ method: 'GET', endpoint: '/api/users' });

Gauge

const activeConnectionsGauge = metricsService.createGauge({
  name: 'active_connections',
  help: 'Active connections'
});

activeConnectionsGauge.set(42);
activeConnectionsGauge.inc();
activeConnectionsGauge.dec();

Histogram

const responseTimeHistogram = metricsService.createHistogram({
  name: 'response_time_seconds',
  help: 'Response time in seconds',
  buckets: [0.1, 0.5, 1, 2, 5]
});

responseTimeHistogram.observe(1.23);

Summary

const requestSizeSummary = metricsService.createSummary({
  name: 'request_size_bytes',
  help: 'Request size in bytes',
  percentiles: [0.5, 0.9, 0.95, 0.99]
});

requestSizeSummary.observe(1024);

Effect.js Integration

import { Effect } from 'effect';
import { measureExecutionTime, recordHttpMetrics } from '@onebun/metrics';

// Measure execution time with Effect
const timedOperation = measureExecutionTime(
  'my_operation_duration',
  Effect.succeed('Hello World')
);

// Record HTTP metrics
const recordMetrics = recordHttpMetrics({
  method: 'GET',
  route: '/api/test',
  statusCode: 200,
  duration: 0.123,
  controller: 'TestController',
  action: 'test'
});

Viewing Metrics

Once configured, metrics are available at the configured endpoint (default: /metrics):

curl http://localhost:3000/metrics

This returns metrics in Prometheus exposition format, which can be scraped by Prometheus or viewed directly.

Performance Considerations

  • System metrics collection interval can be adjusted based on your needs
  • HTTP metrics have minimal overhead (< 1ms per request)
  • GC metrics are collected by the underlying prom-client library
  • Consider using sampling for high-traffic applications

Integration with Monitoring

The metrics endpoint is compatible with:

  • Prometheus - For scraping and storage
  • Grafana - For visualization and dashboards
  • AlertManager - For alerting based on metrics
  • Any other Prometheus-compatible monitoring solution

License

LGPL-3.0