This implementation adds a comprehensive analytics aggregation service to Bridge Watch that computes and caches statistics across all monitored bridge and asset data for dashboard displays and reporting.
Closes #65
The AnalyticsService class provides:
- Protocol-wide statistics: TVL, volume (24h/7d/30d), active bridges/assets, transaction counts, average health scores
- Bridge comparison metrics: TVL rankings, volume comparisons, market share, transaction analytics, trend analysis
- Asset rankings: Health score rankings, liquidity depth, volume rankings, price stability, bridge counts
- Volume aggregations: Time-series data (hourly/daily/weekly/monthly) with inflow/outflow tracking
- Trend calculations: Percentage changes, period-over-period comparisons, trend indicators
- Top performers: Configurable rankings for assets and bridges by various metrics
- Custom metrics: Extensible framework for user-defined analytics queries
- Historical comparisons: Time-series data for trending analysis
- Cache management: Redis-based caching with configurable TTLs
2. TimescaleDB Continuous Aggregates (backend/src/database/migrations/007_analytics_continuous_aggregates.ts)
Created materialized views with automatic refresh policies:
- prices_hourly / prices_daily: Price statistics with OHLC data, volatility metrics
- health_scores_hourly / health_scores_daily: Aggregated health scores across all components
- liquidity_hourly / liquidity_daily: Cross-DEX liquidity aggregations
- alert_events_hourly: Alert frequency and delivery success metrics
- verification_results_hourly: Verification success rates and proof depth statistics
All continuous aggregates include:
- Automatic refresh policies (hourly/daily)
- Optimized indexes for fast queries
- Retention aligned with base hypertables
Background worker that pre-computes and caches analytics:
- Protocol stats (every 2 minutes)
- Bridge comparisons (every 3 minutes)
- Asset rankings (every 3 minutes)
- Volume aggregations (every 5 minutes)
- Top performers (every 5 minutes)
- Trend calculations (on-demand)
- Cache invalidation support
RESTful API endpoints:
GET /api/v1/analytics/protocol- Protocol-wide statisticsGET /api/v1/analytics/bridges/comparison- Bridge comparison metricsGET /api/v1/analytics/assets/rankings- Asset rankingsGET /api/v1/analytics/volume- Volume aggregations (with filters)GET /api/v1/analytics/trends/:metric- Trend calculationsGET /api/v1/analytics/top-performers- Top performing assets/bridgesGET /api/v1/analytics/historical/:metric- Historical comparison dataGET /api/v1/analytics/summary- Comprehensive analytics summaryGET /api/v1/analytics/custom-metrics- List custom metricsGET /api/v1/analytics/custom-metrics/:metricId- Execute custom metricPOST /api/v1/analytics/cache/invalidate- Cache invalidation
Pre-defined custom metrics:
- Bridge Reliability Score: Verification success rate analysis
- Liquidity Concentration Index: Herfindahl index for liquidity distribution
- Alert Effectiveness: Alert delivery success and response times
- Cross-Chain Flow Analysis: Net flow direction and magnitude
- Price Volatility Ranking: Asset volatility over time periods
- Bridge Market Dominance Trends: Market share stability analysis
Redis-based caching strategy:
- Cache key pattern:
analytics:{category}:{subcategory} - Default TTL: 5 minutes (300 seconds)
- Custom metric TTLs: Configurable per metric
- Pattern-based cache invalidation
- Automatic cache warming via scheduled jobs
Comprehensive test coverage:
- Cache hit/miss scenarios
- Protocol statistics computation
- Bridge comparison calculations
- Asset ranking logic
- Volume aggregation with filters
- Trend calculation for multiple metrics
- Top performers selection
- Custom metric execution
- Cache invalidation
- Historical data retrieval
- Error handling
Complete documentation including:
- Feature overview
- Architecture details
- API endpoint specifications
- Custom metrics guide
- Performance considerations
- Monitoring recommendations
- Testing instructions
- Future enhancement ideas
- Leverages continuous aggregates for efficient pre-computation
- Automatic materialized view refresh policies
- Optimized indexes for fast time-series queries
- Retention policies aligned with data lifecycle
- Multi-level caching with Redis
- Configurable TTLs per metric type
- Pattern-based cache invalidation
- Pre-warming via scheduled jobs
- Cache hit rate optimization
- Background workers for expensive computations
- Staggered job schedules to distribute load
- Automatic retry on failure
- Job monitoring and logging
- Extensible framework for user-defined queries
- SQL-based metric definitions
- Independent caching per metric
- Parameter support for dynamic queries
- Scheduled jobs ensure fresh data
- Configurable refresh intervals
- On-demand cache invalidation
- Support for real-time metric queries
-
Query Optimization
- Use of continuous aggregates instead of raw hypertables
- Indexed columns for fast lookups
- Limited result sets with pagination support
-
Caching
- Aggressive caching of expensive queries
- Tiered TTLs based on data volatility
- Pre-computation via background jobs
-
Database
- TimescaleDB compression for historical data
- Retention policies to manage data growth
- Optimized indexes on time-series data
backend/src/services/analytics.service.ts- Core analytics servicebackend/src/workers/analyticsAggregation.worker.ts- Background aggregation workerbackend/src/database/migrations/007_analytics_continuous_aggregates.ts- TimescaleDB continuous aggregatesbackend/src/api/routes/analytics.ts- Analytics API endpointsbackend/src/config/customMetrics.ts- Custom metric definitionsbackend/tests/services/analytics.service.test.ts- Service testsbackend/docs/analytics-service.md- Complete documentation
backend/src/api/routes/index.ts- Registered analytics routesbackend/src/workers/index.ts- Added analytics aggregation jobs
Run the analytics service tests:
cd backend
npm test -- analytics.service.test.tsRun the migration:
cd backend
npm run migratecurl http://localhost:3001/api/v1/analytics/protocolcurl http://localhost:3001/api/v1/analytics/bridges/comparisoncurl http://localhost:3001/api/v1/analytics/assets/rankingscurl "http://localhost:3001/api/v1/analytics/volume?period=daily&symbol=USDC"curl "http://localhost:3001/api/v1/analytics/trends/health_score?symbol=USDC"curl "http://localhost:3001/api/v1/analytics/top-performers?type=assets&metric=health&limit=10"curl http://localhost:3001/api/v1/analytics/custom-metrics/bridge-reliabilitycurl -X POST http://localhost:3001/api/v1/analytics/cache/invalidate \
-H "Content-Type: application/json" \
-d '{"pattern": "protocol"}'Key metrics to monitor:
- Cache Hit Rate: Should be >80%
- Query Execution Time: Monitor slow queries
- Job Success Rate: Ensure aggregation jobs complete
- Redis Memory Usage: Monitor cache growth
- Real-time WebSocket updates for live analytics
- ML-based predictive analytics and forecasting
- Automated anomaly detection
- CSV/JSON export capabilities
- User-defined custom dashboards
- Alert integration based on analytics thresholds
feat: create analytics aggregation service
- Add AnalyticsService with protocol-wide statistics computation
- Implement TimescaleDB continuous aggregates for efficient queries
- Create time-series aggregations (hourly, daily, weekly, monthly)
- Add bridge comparison metrics with market share calculations
- Implement asset ranking by health score, volume, and TVL
- Add volume and TVL aggregation with trend calculations
- Create top performers identification system
- Implement scheduled aggregation jobs with BullMQ
- Add Redis caching layer with configurable TTLs
- Support historical comparison and trend analysis
- Implement custom metric framework with 6 pre-defined metrics
- Add comprehensive API endpoints for all analytics
- Include cache invalidation support
- Add comprehensive test coverage
- Create detailed documentation
Closes #65
- All analytics queries are cached for optimal performance
- TimescaleDB continuous aggregates automatically maintain pre-aggregated data
- Background jobs ensure fresh data without impacting API response times
- Custom metrics can be easily extended by adding definitions to customMetrics.ts
- The service is designed to scale with data growth through TimescaleDB features