← Back to Home / Coding Prompts

Python FastAPI WebSocket Chat

Build real-time chat with WebSockets.

Act as a senior backend engineer specializing in real-time applications with WebSockets, having built chat systems handling 100,000+ concurrent connections with sub-second latency for social platforms, customer support tools, and collaborative applications. Generate a complete WebSocket chat application using FastAPI, including connection management, message handling, room management, typing indicators, read receipts, and presence tracking. Begin with WebSocket endpoint implementation including @app.websocket("/ws/{room_id}/{user_id}") with WebSocket object parameter, connection validation (authentication token, user permissions, room access), disconnection handling (try/except WebSocketDisconnect), active connection tracking dictionary (room_id -> list of WebSocket connections), connection limit enforcement per room or user, and reconnection logic with state recovery. Develop message handling including message type enum (text, typing, read_receipt, join, leave, system, image, file), message validation using Pydantic models (timestamp, sender, room, content, metadata), message processing switch by type, broadcast to room function (exclude sender when appropriate), private message handling (direct user-to-user within room), message persistence to database (SQLModel or SQLAlchemy with async), and message_id generation for idempotency. Implement room management including room creation endpoint (POST /rooms), room listing for user, room join/leave notification broadcast, room user list maintenance, room admin functions (mute, kick, ban), room settings configuration (message retention, file sharing allowed, typing indicators on/off), room invitation system with expiring tokens, and room search by name or members. Add real-time features including typing indicators (client sends typing_start/typing_end, broadcast to room except sender, auto-expiry after 3 seconds of no events), read receipts (message delivered, message seen, seen timestamp, client stores last read time), presence tracking (online, offline, idle, away, do not disturb, last seen timestamp), typing status aggregation (typing_users list per room), and message reactions (emoji reactions with counters). Include user management including user authentication (JWT token passed as query parameter or header), user profile fetching from database, user presence status update on WebSocket connect/disconnect, user blocking for spam prevention, user role determination (admin, moderator, member, guest), rate limiting per user (messages per minute), and user activity logging for analytics. Add performance optimization including connection pooling for database, message queue for broadcast distribution (Redis pub/sub horizontal scaling), message batch processing for high-volume rooms, compression for large payloads, and binary message support for images and files. Provide frontend integration examples (JavaScript WebSocket API, reconnection logic, heartbeat mechanism), testing strategy (pytest with WebSocket test client, load testing with Locust), deployment considerations (replica management, sticky sessions, SSL termination), and monitoring metrics (active connections, messages per second, latency percentiles).