# Redis Pub/Sub for Realtime Analytics

## Overview

Event-driven realtime updates using Redis pub/sub to replace database polling.

## Architecture

```
Processor Service                    Realtime Service
    ↓                                      ↓
[AggregationService]              [AnalyticsGateway]
    ↓                                      ↓
[RedisPublisherService]   →→→   [RedisPubSubService]
    ↓                                      ↓
Redis Channel: analytics:realtime:updates
                                           ↓
                                    [WebSocket Clients]
```

## Components

### RedisPubSubService (`redis-pubsub.service.ts`)

**Purpose**: Subscribe to Redis pub/sub channel and notify WebSocket gateway of updates.

**Key Features**:
- Automatic reconnection with exponential backoff
- Multiple handler registration (observer pattern)
- Connection health monitoring
- Message parsing and validation

**Configuration**:
- Redis host/port from environment variables
- Channel: `analytics:realtime:updates`
- Max reconnect attempts: 10

### AnalyticsGateway Updates

**Changes**:
- Removed `setInterval` polling (was 5 seconds)
- Added Redis pub/sub subscription on gateway initialization
- Broadcasts to all connected clients when Redis message received
- Fallback polling (60 seconds) if Redis disconnects
- Client subscriptions stored without timers (push-based)

**Flow**:
1. Client connects and subscribes to metrics
2. Gateway stores subscription (no polling timer)
3. On Redis message, gateway fetches fresh data and broadcasts
4. If Redis is down, fallback polls every 60 seconds

## Message Format

```typescript
interface MetricsUpdateMessage {
  type: 'metrics_updated';
  timestamp: Date;
  metrics: {
    metricType: string;
    granularity: string;
    value: number;
    dimension?: string;
    dimensionValue?: string;
  }[];
}
```

## Configuration

### Environment Variables

```bash
REDIS_HOST=localhost      # Redis server host
REDIS_PORT=6379           # Redis server port
```

### Channel Name

```
analytics:realtime:updates
```

## Benefits

1. **No Polling Load**: Database queries only on actual updates
2. **Lower Latency**: Near-instant updates (<100ms)
3. **Horizontal Scaling**: Multiple realtime instances share Redis
4. **Resilience**: Fallback polling if Redis fails
5. **Efficient**: Batches metrics every 5 seconds before publishing

## Monitoring

### Health Checks

```typescript
redisPubSub.isHealthy()  // Check if connected
redisPubSub.getStatus()  // Get detailed status
```

### Logs

- Connection/reconnection events
- Message receive/parse errors
- Handler execution errors
- Fallback polling activation

## Future Enhancements

- [ ] Metric-specific channels (e.g., `analytics:pageviews`)
- [ ] Client filtering (only send subscribed metrics)
- [ ] Rate limiting on publish frequency
- [ ] Compression for large metric batches
