WebSocket Error Handling & Rate Limiting Enhancement
Overview
Enhanced the Next.js app's WebSocket-based CV pipeline with robust error handling, rate limiting, and debugging features to prevent browser hangs and improve reliability.
Key Enhancements
1. Advanced Error Handling
Connection State Management:
- Added detailed
connectionStateenum:'disconnected' | 'connecting' | 'connected' | 'error' - Enhanced status tracking with visual indicators and appropriate UI states
- Comprehensive error messages based on WebSocket close codes
Error Categorization:
- Network errors (offline detection)
- Security errors (SSL/CORS issues)
- Protocol errors (malformed data)
- Timeout errors (unresponsive service)
- Server errors (service unavailable)
2. Rate Limiting & Connection Management
Rate Limiting Features:
- Minimum 3-second interval between connection attempts
- Maximum 5 reconnection attempts with exponential backoff
- Progressive delays: 2s, 4s, 8s, 16s, 32s (capped)
- Automatic reset of counters on successful connection
Connection Timeouts:
- 15-second connection timeout to prevent hanging
- Automatic cleanup of stale connections
- Proper WebSocket state tracking
3. Heartbeat Mechanism
Keep-Alive System:
- Automatic ping/pong every 30 seconds
- Connection health monitoring
- Early detection of connection issues
- Graceful handling of stale connections
4. Enhanced User Interface
Connection Status Component:
- Real-time connection state visualization
- Color-coded status indicators (green/yellow/red/gray)
- Manual reconnect button for failed connections
- Animated loading states during connection attempts
Error Display:
- Detailed error messages with technical context
- Dismissible error notifications
- Debug information in browser console
- User-friendly troubleshooting guidance
5. Debugging Features
Console Logging:
- Detailed connection attempt logs
- WebSocket state change tracking
- Message send/receive logging
- Error context and timing information
Error Context:
- Browser environment detection
- Network status monitoring
- SSL/security issue identification
- Service availability feedback
Technical Implementation
Enhanced Pipeline Hook
interface PipelineHook {
isConnected: boolean;
connectionState: 'disconnected' | 'connecting' | 'connected' | 'error';
messages: PipelineMessage[];
sendMessage: (pipelineType: string, payload: PipelinePayload) => void;
clearMessages: () => void;
reconnect: () => void; // Manual reconnect function
}
Rate Limiting Configuration
const maxReconnectAttempts = 5; // Maximum auto-reconnect attempts
const minConnectionInterval = 3000; // 3 seconds between attempts
const connectionTimeout = 15000; // 15 second connection timeout
const heartbeatInterval = 30000; // 30 second heartbeat
Error Handling Examples
// Network error detection
if (!navigator.onLine) {
errorMessage = 'No internet connection detected';
}
// SSL/Security error detection
if (wsUrl.startsWith('wss://') && location.protocol === 'http:') {
errorMessage = 'Cannot connect to secure WebSocket from insecure page';
}
// Connection timeout handling
connectionTimeoutRef.current = setTimeout(() => {
if (ws.readyState === WebSocket.CONNECTING) {
ws.close(1000, 'Connection timeout');
setConnectionState('error');
}
}, connectionTimeout);
Updated Components
1. ConnectionStatus Component
- Enhanced visual states for all connection phases
- Manual reconnect button with proper state handling
- Improved accessibility and user feedback
2. CV Processor Hook
- Exposed
connectionStateandreconnectfunctions - Integrated with enhanced pipeline error handling
- Improved error propagation to UI components
3. UI Components Updated
CVExtractor.tsx- Enhanced connection managementcandidateAdd.tsx- Improved error handling and user feedbackaddCandidate/page.tsx- Better connection state managementUploadCvStep.tsx- Streamlined connection handling
Benefits
1. Reliability
- Prevents browser hangs from infinite connection loops
- Graceful degradation when service is unavailable
- Automatic recovery from temporary network issues
2. User Experience
- Clear visual feedback on connection status
- Informative error messages with actionable advice
- Manual retry options for failed connections
3. Debugging
- Comprehensive logging for troubleshooting
- Detailed error context for developers
- Network and security issue identification
4. Performance
- Rate-limited connections prevent resource waste
- Efficient cleanup of stale connections
- Optimized reconnection strategies
Testing Scenarios
- Network Interruption: Graceful handling and auto-reconnect
- Service Unavailable: Clear error messaging and manual retry
- SSL/Security Issues: Specific error identification
- Connection Timeout: Prevents hanging with clear timeout
- Rate Limiting: Prevents spam connection attempts
Production Readiness
The enhanced WebSocket implementation is now production-ready with:
- Robust error handling for all failure scenarios
- Rate limiting to prevent service overload
- Comprehensive debugging capabilities
- User-friendly error recovery mechanisms
- Proper resource cleanup and memory management
Configuration
All rate limiting and timeout values are configurable:
maxReconnectAttempts: Adjust based on service reliabilityminConnectionInterval: Balance between responsiveness and rate limitingconnectionTimeout: Adjust based on expected connection timesheartbeatInterval: Balance between connection health and traffic
Future Enhancements
- Adaptive Rate Limiting: Adjust intervals based on success rates
- Service Discovery: Automatic fallback to backup servers
- Connection Pooling: Multiple connections for high-throughput scenarios
- Metrics Collection: Track connection statistics for monitoring