This document describes the implementation of the comprehensive metrics collection system for Stellar Bridge Watch, providing Prometheus-compatible metrics for monitoring, alerting, and performance analysis.
-
Metrics Service (
backend/src/services/metrics.service.ts)- Singleton service managing all application metrics
- Prometheus client library integration
- Counter, Gauge, and Histogram metric types
- Automatic Node.js default metrics collection
-
Metrics Middleware (
backend/src/api/middleware/metrics.ts)- Automatic HTTP request/response metrics collection
- Active connection tracking
- Request/response size tracking
- Latency measurement
-
Metrics Routes (
backend/src/api/routes/metrics.ts)/metrics- Prometheus text format endpoint/metrics/json- JSON format for debugging/metrics/health- Health check endpoint/metrics/reset- Admin-only reset endpoint
-
Grafana Dashboards
application-overview.json- Comprehensive application metricsbridge-monitoring.json- Bridge-specific monitoring
-
Prometheus Configuration
prometheus.yml- Scrape configurationprometheus-alerts.yml- Alert rulesalertmanager.yml- Alert routing configuration
-
Docker Compose Setup
docker-compose.monitoring.yml- Complete monitoring stack
-
Documentation
backend/docs/metrics-collection.md- Detailed technical documentationbackend/grafana/README.md- Grafana setup guide
http_requests_total- Total requests by method, route, statushttp_request_duration_seconds- Request latency histogramhttp_request_size_bytes- Request size histogramhttp_response_size_bytes- Response size histogramhttp_active_connections- Active connection gauge
db_query_duration_seconds- Query execution timedb_connections_active- Active connectionsdb_connections_idle- Idle connectionsdb_queries_total- Total queriesdb_query_errors_total- Query errors
queue_jobs_active- Active jobsqueue_jobs_waiting- Waiting jobsqueue_jobs_completed_total- Completed jobsqueue_jobs_failed_total- Failed jobsqueue_job_duration_seconds- Job duration
bridge_verifications_total- Total verificationsbridge_verification_success_total- Successful verificationsbridge_verification_failure_total- Failed verificationsbridge_health_score- Health score (0-100)asset_price_usd- Asset pricesliquidity_tvl_usd- Total Value Lockedalerts_triggered_total- Alerts triggeredcircuit_breaker_trips_total- Circuit breaker trips
cache_hits_total- Cache hitscache_misses_total- Cache missescache_size_bytes- Cache sizecache_evictions_total- Cache evictions
api_key_requests_total- Requests per API keyapi_key_rate_limit_hits_total- Rate limit hits
websocket_connections_active- Active connectionswebsocket_messages_total- Messages sent/received
The metrics system has been integrated into:
-
Bridge Verification Worker (
backend/src/workers/bridgeVerification.job.ts)- Records verification attempts, successes, and failures
- Tracks verification reasons
-
Alert Service (
backend/src/services/alert.service.ts)- Records alert triggers by type and priority
- Tracks alert distribution
-
Circuit Breaker Service (
backend/src/services/circuitBreaker.service.ts)- Records circuit breaker trips
- Tracks trip reasons
-
HTTP Middleware (automatic)
- All API endpoints automatically tracked
- Request/response metrics collected
The prom-client package has been added to package.json:
cd backend
npm installThe metrics endpoint is automatically available when the application starts:
npm run devAccess metrics at: http://localhost:3001/metrics
To run Prometheus and Grafana:
cd backend
docker-compose -f docker-compose.monitoring.yml up -dAccess:
- Prometheus:
http://localhost:9090 - Grafana:
http://localhost:3000(admin/admin)
Update backend/prometheus.yml with your application's host/port if different from defaults.
Dashboards are automatically provisioned if using the Docker Compose setup. Otherwise:
- Open Grafana at
http://localhost:3000 - Go to Dashboards → Import
- Upload
backend/grafana/dashboards/application-overview.json - Upload
backend/grafana/dashboards/bridge-monitoring.json
import { getMetricsService } from "./services/metrics.service";
const metricsService = getMetricsService();
// Record a bridge verification
metricsService.recordBridgeVerification("bridge-1", "Circle", "USDC", true);
// Update a gauge
metricsService.bridgeHealthScore.set(
{ bridge_id: "bridge-1", bridge_name: "Circle" },
95,
);
// Increment a counter
metricsService.alertsTriggered.inc({
alert_type: "supply_mismatch",
priority: "critical",
bridge_id: "bridge-1",
});# Request rate
rate(http_requests_total[5m])
# 95th percentile latency
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
# Bridge verification success rate
rate(bridge_verification_success_total[5m]) / rate(bridge_verifications_total[5m]) * 100
# Cache hit rate
rate(cache_hits_total[5m]) / (rate(cache_hits_total[5m]) + rate(cache_misses_total[5m])) * 100
The system includes 20+ pre-configured alert rules covering:
- HTTP error rates and latency
- Database performance and connection pool
- Bridge health and verification failures
- Queue job failures and delays
- Cache performance
- System resources (CPU, memory, event loop)
- Circuit breaker trips
- Service availability
See backend/prometheus-alerts.yml for complete list.
- HTTP request metrics
- Database performance
- Queue job status
- Cache hit rates
- Memory and CPU usage
- WebSocket connections
- API key usage
- Bridge verification rates
- Success vs failure rates
- Health scores over time
- Failure reason breakdown
- Circuit breaker status
- Asset price tracking
- TVL monitoring
- Metrics collection adds ~1-2ms overhead per request
- Prometheus stores ~1-2 bytes per sample
- Estimated storage: ~100MB per day for typical workload
- Default retention: 15 days
- Label cardinality is kept low to avoid performance issues
- Start the application
- Access metrics endpoint:
curl http://localhost:3001/metrics - Verify metrics are being collected
- Make API requests and observe metric changes
- Start Prometheus
- Check targets:
http://localhost:9090/targets - Verify scraping is successful
- Query metrics in Prometheus UI
- Open Grafana dashboards
- Verify data is displayed
- Test time range selection
- Verify alerts are configured
- Check that metrics service is initialized
- Verify middleware is registered in
src/index.ts - Check application logs for errors
- Verify Prometheus configuration
- Check network connectivity
- Verify metrics endpoint is accessible
- Verify Prometheus datasource is configured
- Check Prometheus is scraping successfully
- Verify metric names in queries match
backend/src/services/metrics.service.tsbackend/src/api/middleware/metrics.tsbackend/src/api/routes/metrics.tsbackend/docs/metrics-collection.mdbackend/grafana/README.mdbackend/grafana/dashboards/application-overview.jsonbackend/grafana/dashboards/bridge-monitoring.jsonbackend/grafana/provisioning/datasources/prometheus.ymlbackend/grafana/provisioning/dashboards/dashboards.ymlbackend/prometheus.ymlbackend/prometheus-alerts.ymlbackend/alertmanager.ymlbackend/docker-compose.monitoring.yml
backend/package.json- Addedprom-clientdependencybackend/src/index.ts- Registered metrics middlewarebackend/src/api/routes/index.ts- Registered metrics routesbackend/src/workers/bridgeVerification.job.ts- Added metrics recordingbackend/src/services/alert.service.ts- Added metrics recordingbackend/src/services/circuitBreaker.service.ts- Added metrics recording
- Add more integrations: Integrate metrics into additional services as needed
- Tune alert thresholds: Adjust alert thresholds based on production data
- Add custom dashboards: Create team-specific or feature-specific dashboards
- Configure alerting: Set up Slack/PagerDuty/email notifications
- Add recording rules: Create Prometheus recording rules for complex queries
- Monitor performance: Track metrics collection overhead and optimize if needed
- Prometheus Documentation
- Grafana Documentation
- prom-client Library
- Prometheus Best Practices
- PromQL Basics
Closes #124