WebSocket Reverse Tunnel Usage
Overview
WebSocket support enables real-time bidirectional communication between browsers and device web services through AWS IoT Secure Tunnels.Architecture
Connection Flow
1. Browser Connects
2. Lambda Handles Connection
The WebSocket Lambda handles three route events:$connect
- Validates device DSN from subdomain
- Looks up tunnel configuration in DynamoDB
- Verifies tunnel is OPEN
- Stores connection metadata
- Returns 200 to accept connection
$default (message)
- Establishes IoT tunnel WebSocket if not connected
- Forwards browser message to device
- Forwards device response back to browser
- Maintains bidirectional communication
$disconnect
- Closes IoT tunnel WebSocket
- Cleans up connection metadata
Use Cases
Live Sensor Dashboard
Interactive Terminal
Live Video Stream
Error Handling
The WebSocket Lambda returns specific error codes:Connection Errors
Deployment
After deploying the CDK stack, you’ll get two endpoints:-
HTTP API: For static content (HTML/CSS/JS)
-
WebSocket API: For real-time communication
Testing
Test WebSocket Connection
Monitor Connection
Check CloudWatch Logs for the WebSocket Lambda:Performance Considerations
Connection Limits
- API Gateway WebSocket: 500 concurrent connections per account by default
- Lambda concurrent executions: 1000 by default
- AWS IoT Secure Tunnel: 1 tunnel per device
Timeouts
- API Gateway idle timeout: 10 minutes
- Lambda execution timeout: 5 minutes (configured)
- IoT Secure Tunnel timeout: 12 hours (default)
Message Size
- API Gateway WebSocket max message size: 32 KB
- For larger data (video frames), chunk into multiple messages
Troubleshooting
Connection Refused
Problem: WebSocket connection fails immediately Solution:- Check device tunnel is enabled and not expired
- Verify DNS is resolving correctly
- Check CloudWatch logs for Lambda errors
Messages Not Delivered
Problem: Messages sent but no response Solution:- Verify device local proxy agent is running
- Check IoT tunnel status in CloudWatch
- Verify device service is listening on configured port
Connection Drops
Problem: WebSocket disconnects unexpectedly Solution:- Implement ping/pong heartbeat (every 30 seconds)
- Automatic reconnection logic in frontend
- Check Lambda CloudWatch logs for errors
Security
Authentication
Currently, WebSocket connections are authenticated via:- Valid device DSN in subdomain
- Active tunnel in DynamoDB cache
- OPEN tunnel status in AWS IoT
Rate Limiting
TODO: Implement per-device connection limitsEncryption
- TLS 1.2+ enforced by CloudFront
- AWS IoT Secure Tunnel uses end-to-end encryption