A lightweight and simple WebSocket server built with FastAPI, designed to run on Google Cloud Run. This server enables real-time bidirectional communication between clients and the server using WebSocket protocol.
- WebSocket server implementation using FastAPI
- Broadcasting messages to all connected clients
- JSON message validation
- CORS support for web clients
- Basic error handling and logging
- Ready for Google Cloud Run deployment
- Health check endpoint
- Python 3.11 or higher
- Google Cloud SDK
- Docker (for local testing)
- A Google Cloud Project with billing enabled
.
├── main.py # Main application file
├── requirements.txt # Python dependencies
├── Dockerfile # Container configuration
└── README.md # This file-
Create a virtual environment and activate it:
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Run the server locally:
python main.py
The server will start at ws://localhost:8080.
- Build the Docker image:
docker build -t websocket-server .2.Run the container locally:
docker run -p 8080:8080 websocket-server-
Set up your Google Cloud project:
gcloud config set project [YOUR_PROJECT_ID] -
Build and push the container:
gcloud builds submit --tag gcr.io/[YOUR_PROJECT_ID]/websocket-server
-
Deploy to Cloud Run:
gcloud run deploy websocket-server \ --image gcr.io/[YOUR_PROJECT_ID]/websocket-server \ --platform managed \ --allow-unauthenticated \ --port 8080
Here's how to connect to the WebSocket server from a web client:
const wsUrl = 'wss://your-service-url.run.app/ws';
const ws = new WebSocket(wsUrl);
ws.onopen = () => {
console.log('Connected to WebSocket server');
// Send a message
ws.send(JSON.stringify({
message: "Hello, WebSocket!",
user: "John"
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};GET /- Health check endpointWebSocket /ws- WebSocket connection endpoint
Messages should be sent as JSON with the following structure:
{
"message": "Your message content",
"user": "Username"
}-
Cloud Run WebSocket Limitations:
- Maximum connection duration: 1 hour
- Automatic connection termination after 1 hour
- Need for client-side reconnection logic
-
Production Considerations:
- Implement authentication
- Configure specific CORS origins
- Add rate limiting
- Enhance message validation
- Set up monitoring and logging
- Consider using a message queue for scaling
The server handles several types of errors:
- Invalid JSON format
- Connection errors
- General WebSocket errors
All errors are logged and appropriate error messages are sent back to clients.
- In production, update CORS settings to allow only specific origins
- Implement authentication for WebSocket connections
- Regular security audits are recommended
- Keep dependencies updated