This article details an architecture for managing long-lived WebSocket connections in a fleet of real-time streaming workers, addressing challenges like worker failures, deployments, and scaling. It focuses on using Amazon DynamoDB's conditional writes to implement a distributed lease pattern for connection ownership, ensuring high availability and automatic failover without external coordination services. The pattern significantly reduces recovery time and manual intervention.
Read original on AWS Architecture BlogManaging fleets of stateful real-time streaming workers that maintain hundreds of persistent WebSocket connections presents significant challenges in distributed systems. When workers fail, redeploy, or scale, ensuring that each connection is owned by exactly one healthy worker, and that ownership is gracefully transferred upon failure, is critical to prevent data loss and reduce operational overhead. This pattern demonstrates how to achieve resilient connection management using a lease-based approach with DynamoDB.
Unlike stateless HTTP requests, WebSocket connections are persistent and bidirectional, requiring workers to maintain an open TCP connection and handle continuous message flow. This statefulness introduces several operational challenges for a worker fleet acting as WebSocket *clients*:
The core of the solution is a distributed lease management system built on Amazon DynamoDB. Each WebSocket connection is represented by a lease record in DynamoDB, tracking its desired state, upstream URL, and crucially, its current owner (worker ID) and lease expiration time. DynamoDB's conditional writes are leveraged to provide atomic operations for acquiring and renewing leases, acting as a distributed lock.
Why DynamoDB for Leases?
DynamoDB is chosen over simpler SQS queues or generic lock clients because it provides persistent storage for connection state, supports complex queries (e.g., finding expired leases), and enables atomic conditional writes essential for distributed locking. This allows combining connection metadata and lock ownership in a single, highly available item.