Recipes
Common metrics patterns and real-world examples.
1. API Request Metrics
Track HTTP requests with method, endpoint, and status labels. Registers a counter for total requests, a histogram for request duration, and a counter for errors.
typescript
import { Injectable, Inject, OnModuleInit } from '@nestjs/common';
import { METRICS_SERVICE, IMetricsService } from '@nestjs-redisx/metrics';
@Injectable()
export class ApiMetrics implements OnModuleInit {
constructor(
@Inject(METRICS_SERVICE) private readonly metrics: IMetricsService,
) {}
onModuleInit(): void {
this.metrics.registerCounter(
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status'],
);
this.metrics.registerHistogram(
'http_request_duration_seconds',
'HTTP request duration',
['method', 'endpoint'],
[0.01, 0.05, 0.1, 0.5, 1, 2, 5],
);
this.metrics.registerCounter(
'http_errors_total',
'Total HTTP errors',
['method', 'endpoint', 'code'],
);
}
trackRequest(
method: string,
endpoint: string,
status: number,
duration: number,
): void {
this.metrics.incrementCounter('http_requests_total', {
method,
endpoint,
status: status.toString(),
});
this.metrics.observeHistogram('http_request_duration_seconds', duration, {
method,
endpoint,
});
if (status >= 400) {
this.metrics.incrementCounter('http_errors_total', {
method,
endpoint,
code: status.toString(),
});
}
}
}2. E-commerce Metrics
Business-specific metrics for order tracking, revenue distribution, processing duration per step, and inventory levels. Uses counters for orders, histograms for order value and processing time, and gauges for current inventory.
typescript
import { Injectable, Inject, OnModuleInit } from '@nestjs/common';
import { METRICS_SERVICE, IMetricsService } from '@nestjs-redisx/metrics';
import { Order } from '../types';
@Injectable()
export class OrderMetrics implements OnModuleInit {
constructor(
@Inject(METRICS_SERVICE) private readonly metrics: IMetricsService,
) {}
onModuleInit(): void {
this.metrics.registerCounter(
'orders_created_total',
'Total orders created',
['status', 'payment_method', 'country'],
);
this.metrics.registerHistogram(
'order_value_dollars',
'Order value in dollars',
[],
[10, 50, 100, 500, 1000, 5000],
);
this.metrics.registerHistogram(
'order_processing_duration_seconds',
'Time to process order',
['step'],
[0.1, 0.5, 1, 2, 5],
);
this.metrics.registerGauge(
'inventory_level',
'Current inventory level',
['product_id'],
);
}
trackOrderCreated(order: Order): void {
this.metrics.incrementCounter('orders_created_total', {
status: order.status,
payment_method: order.paymentMethod,
country: order.shippingAddress.country,
});
this.metrics.observeHistogram('order_value_dollars', order.total);
}
trackInventoryChange(productId: string, newLevel: number): void {
this.metrics.setGauge('inventory_level', newLevel, {
product_id: productId,
});
}
}3. Background Job Metrics
Track job execution across your worker fleet. Registers counters for processed jobs by type and status, histograms for job duration, and gauges for active jobs and queue depth.
typescript
import { Injectable, Inject, OnModuleInit } from '@nestjs/common';
import { METRICS_SERVICE, IMetricsService } from '@nestjs-redisx/metrics';
import { Job } from '../types';
@Injectable()
export class JobMetrics implements OnModuleInit {
constructor(
@Inject(METRICS_SERVICE) private readonly metrics: IMetricsService,
) {}
onModuleInit(): void {
this.metrics.registerCounter(
'jobs_processed_total',
'Total jobs processed',
['type', 'status'],
);
this.metrics.registerHistogram(
'job_duration_seconds',
'Job processing duration',
['type'],
[1, 5, 10, 30, 60, 300, 600],
);
this.metrics.registerGauge(
'jobs_active',
'Currently active jobs',
['type'],
);
this.metrics.registerGauge(
'job_queue_size',
'Jobs waiting in queue',
['type'],
);
}
async processJob(type: string, job: Job): Promise<void> {
this.metrics.incrementGauge('jobs_active', { type });
const stopTimer = this.metrics.startTimer('job_duration_seconds', { type });
try {
await this.executeJob(job);
this.metrics.incrementCounter('jobs_processed_total', {
type,
status: 'success',
});
stopTimer();
} catch (error) {
this.metrics.incrementCounter('jobs_processed_total', {
type,
status: 'error',
});
stopTimer();
throw error;
} finally {
this.metrics.decrementGauge('jobs_active', { type });
}
}
private async executeJob(_job: Job): Promise<void> {
// Process the job
}
}Next Steps
- Troubleshooting — Debug common issues
- Overview — Back to overview