@satoshibits/cache-metrics
v1.0.1
Published
Zero-dependency cache performance monitoring with event-based collection and multiple output formats
Maintainers
Readme
@satoshibits/cache-metrics
Zero-dependency cache performance monitoring with event-based collection and multiple output formats.
Features
- Zero Dependencies: Pure TypeScript implementation with no external dependencies
- Event-Based Architecture: Built on a lightweight EventEmitter for flexible handling
- Multiple Output Formats: Console, Prometheus, JSON, and NDJSON handlers included
- Time-Window Aggregation: Aggregate metrics over configurable time windows
- Flexible Handlers: Easy to extend with custom handlers
- Performance Tracking: Track hit rates, latencies, errors, and cache stampede prevention
Installation
npm install @satoshibits/cache-metrics
# or
pnpm add @satoshibits/cache-metricsQuick Start
import { CacheCollector } from '@satoshibits/cache-metrics';
// Create a metrics collector
const collector = new CacheCollector({
maxLatencySamples: 1000,
calculatePercentiles: true,
});
// Record cache operations
collector.recordHit('user:123', 1.5); // key, latency in ms
collector.recordMiss('user:456', 0.8);
collector.recordSet('user:789', 2.1);
collector.recordDelete('user:123', 0.5);
// Get snapshot
const snapshot = collector.getSnapshot();
console.log(`Hit rate: ${(snapshot.hitRate * 100).toFixed(2)}%`);With Handlers
import { CacheCollector, ConsoleHandler, PrometheusHandler } from '@satoshibits/cache-metrics';
// Create collector with handlers
const collector = new CacheCollector({
enableConsole: true,
enablePrometheus: true,
snapshotInterval: 60000, // emit snapshots every minute
});
// Use the collector
collector.recordHit('key', 1.2);Custom Event Handlers
import { CacheCollector, ConsoleHandler } from '@satoshibits/cache-metrics';
const collector = new CacheCollector();
// Add console handler for errors only
const errorHandler = new ConsoleHandler({
eventTypes: new Set(['error']),
includeTimestamp: true,
});
collector.on('event', (event) => errorHandler.handle(event));Prometheus Integration
import { CacheCollector, PrometheusHandler } from '@satoshibits/cache-metrics';
const collector = new CacheCollector();
const prometheusHandler = new PrometheusHandler({
// Send to your metrics endpoint
fetch('/metrics', { method: 'POST', body: text });
});
// Emit Prometheus format every 30 seconds
collector.on('snapshot', (snapshot) => prometheusHandler.handle(snapshot));
collector.startSnapshotTimer(30000);Aggregated Metrics
import { CacheCollector } from '@satoshibits/cache-metrics';
const collector = new CacheCollector();
const aggregator = new MetricsAggregator({
maxSnapshots: 60,
windowDuration: 3600000, // 1 hour
});
// Collect snapshots
collector.on('snapshot', (snapshot) => aggregator.addSnapshot(snapshot));
collector.startSnapshotTimer(60000); // every minute
// Get aggregated metrics
const aggregated = aggregator.getAggregatedMetrics();
const hitRateStats = aggregator.getHitRateStats();
console.log(`Average hit rate: ${(hitRateStats.average * 100).toFixed(2)}%`);
console.log(`Trend: ${hitRateStats.trend}`);API Reference
CacheCollector
The main class for collecting cache metrics.
Methods:
record(event)- Record a cache eventrecordHit(key, latency?)- Record a cache hitrecordMiss(key, latency?)- Record a cache missrecordSet(key, latency?)- Record a set operationrecordDelete(key, latency?)- Record a delete operationrecordError(operation, error?)- Record an errorrecordStampedePrevented()- Record a prevented cache stampedeupdateCacheSize(size)- Update cache size metricgetSnapshot()- Get current metrics snapshotreset()- Reset all metricsstartSnapshotTimer(intervalMs)- Start periodic snapshot emissionstopSnapshotTimer()- Stop periodic snapshots
Event Types
hit- Cache hitmiss- Cache missset- Set operationdelete- Delete operationerror- Error occurredclear- Cache cleared
Handlers
- ConsoleEventHandler - Log events to console
- ConsoleSnapshotHandler - Log snapshots to console
- PrometheusHandler - Format metrics in Prometheus exposition format
- JsonHandler - Format metrics as JSON
- NdjsonHandler - Stream metrics as newline-delimited JSON
License
ISC
