Build a Multi-Room Async TCP Chat Server
Stacks & QueuesModel answerLast updated
Implement a concurrent, room-based TCP chat server in Python using asyncio, featuring command processing, scoped broadcasts, backpressure handling, and strict resource cleanup.
Design and implement an asynchronous TCP chat server using Python's standard asyncio library. The server must handle up to ~1,000 concurrent client connections over a line-delimited UTF-8 protocol.
You will structure the solution in two stages:
- Stage 1 (Global Server): Manage client connections, authenticate users via a prompt, and handle basic message broadcasting across all active sessions.
- Stage 2 (Rooms & Commands): Add multi-room support and slash-command handling while maintaining consistent shared state and preventing resource leaks.
Core Requirements & Constraints
- Standard Library Only: Rely exclusively on
asyncioand Python's built-in modules. - Protocol Standard:
- Input and output must be line-delimited (ending in
\n). - Every line must be valid UTF-8 text.
- Input and output must be line-delimited (ending in
- Stage 1 Behavior:
- Upon establishing a connection, prompt the client for a username.
- The first line received from the client is treated as their identity.
- All subsequent non-command lines are broadcast to every other connected client using the layout:
<username>: <message>\n. - The sender must not receive a duplicate echo of their own message.
- Stage 2 Behavior:
- New connections start in a default room named
"lobby". - Support the following slash commands (lines starting with
/):/join <room_name>: Moves the client to<room_name>(creating it if non-existent). Leaving the old room and joining the new room should notify members of both rooms./who: Returns a formatted list of all usernames currently in the client's current room (sent only to the requester)./quit: Gracefully terminates the client connection.
- Messages sent by a user are broadcast only to other clients inside the exact same room.
- New connections start in a default room named
- Robustness & Concurrency:
- Disconnections (graceful or abrupt connection resets) must cleanly remove the client from shared registries.
- Empty custom rooms should be garbage-collected automatically.
- Faults or malformed payloads from one client must never crash the server or impair other active connections.
- Utilize standard asyncio backpressure mechanics to ensure high-throughput streams do not saturate host memory.
Hints
Hint 1
Use `asyncio.start_server` to create an event-driven socket server. It passes a dedicated `StreamReader` and `StreamWriter` pair to your connection handler for each incoming socket.
Hint 2
Always wrap network writes with `writer.drain()`. This yields control back to the event loop if the underlying OS socket buffer is full, providing natural backpressure for slow clients.
Hint 3
Ensure registry mutation (adding/removing users from room sets) takes place inside `try ... finally` blocks associated with each client connection task so cleanup is guaranteed on unexpected client disconnects.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Technical Approach
Building an asynchronous chat server with Python's asyncio relies on an event loop running a single thread that context-switches between concurrent I/O tasks.
Key Architectural Components
-
Connection Lifecycle (
handle_client): Each incoming TCP connection triggers an asynchronous handler function running as a independentasyncio.Task. The handler manages reading lines fromStreamReader, executing commands, and writing responses back toStreamWriter. -
State & Registry Management: We use an object-oriented
ChatServercontainer holding mapping structures:self.clients: Maps clientStreamWriterinstances to their metadata (e.g., username and room name).self.rooms: Maps room names to asetofStreamWriterobjects belonging to clients in that room.
Because Python's
asyncioruns on a single-threaded cooperative event loop, synchronous state mutations (modifying dictionaries and sets) do not require explicit async locks likeasyncio.Lock, provided noawaitstatements occur during the mutation window. -
Backpressure & Slow Consumers: When writing to network sockets via
StreamWriter.write(), data is staged in an internal buffer. Callingawait writer.drain()suspends execution of the current connection handler until the socket buffer flushes below the high-water mark. If a writer raises an exception (e.g.,ConnectionResetError), we catch it and immediately drop that connection to prevent resource leaks.
Implementation
import asyncio
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
class ChatServer:
def __init__(self, host: str = "127.0.0.1", port: int = 8888):
self.host = host
self.port = port
# Client mapping: writer -> {"username": str, "room": str}
self.clients: dict[asyncio.StreamWriter, dict[str, str]] = {}
# Room mapping: room_name -> set of writers
self.rooms: dict[str, set[asyncio.StreamWriter]] = {}
async def start(self):
server = await asyncio.start_server(self.handle_client, self.host, self.port)
logging.info(f"Server started on {self.host}:{self.port}")
async with server:
await server.serve_forever()
async def send_direct(self, writer: asyncio.StreamWriter, message: str):
"""Send a private message to a specific client with backpressure management."""
try:
writer.write(message.encode("utf-8"))
await writer.drain()
except (ConnectionResetError, BrokenPipeError, OSError):
# Failed writes will be caught and cleaned up in the main connection task
pass
async def broadcast(self, room_name: str, message: str, exclude: asyncio.StreamWriter | None = None):
"""Broadcast a message to all clients within a given room, optionally skipping sender."""
if room_name not in self.rooms:
return
# Snap a copy of target sockets to avoid mutation during iteration
target_writers = list(self.rooms[room_name])
for writer in target_writers:
if writer is not exclude:
await self.send_direct(writer, message)
def _add_to_room(self, writer: asyncio.StreamWriter, room_name: str):
if room_name not in self.rooms:
self.rooms[room_name] = set()
self.rooms[room_name].add(writer)
self.clients[writer]["room"] = room_name
def _remove_from_room(self, writer: asyncio.StreamWriter) -> str | None:
client_info = self.clients.get(writer)
if not client_info:
return None
current_room = client_info.get("room")
if current_room and current_room in self.rooms:
self.rooms[current_room].discard(writer)
# Garbage collect empty non-lobby rooms
if not self.rooms[current_room] and current_room != "lobby":
del self.rooms[current_room]
return current_room
async def _change_room(self, writer: asyncio.StreamWriter, new_room: str):
user = self.clients[writer]["username"]
old_room = self._remove_from_room(writer)
if old_room:
await self.broadcast(old_room, f"*** {user} has left the room.\n")
self._add_to_room(writer, new_room)
await self.send_direct(writer, f"*** Switched to room '{new_room}'.\n")
await self.broadcast(new_room, f"*** {user} has joined the room.\n", exclude=writer)
async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
peer = writer.get_extra_info("peername")
logging.info(f"New connection from {peer}")
try:
# 1. Registration Phase
await self.send_direct(writer, "Enter your username: ")
username_bytes = await reader.readline()
if not username_bytes:
return
username = username_bytes.decode("utf-8").strip()
if not username:
await self.send_direct(writer, "Invalid username. Goodbye.\n")
return
self.clients[writer] = {"username": username, "room": ""}
self._add_to_room(writer, "lobby")
await self.send_direct(writer, f"Welcome {username}! You are in room 'lobby'. Type /quit to exit.\n")
await self.broadcast("lobby", f"*** {username} has connected.\n", exclude=writer)
# 2. Command & Message Processing Loop
while True:
line_bytes = await reader.readline()
if not line_bytes: # Client EOF (disconnected)
break
line = line_bytes.decode("utf-8").rstrip("\r\n")
if not line:
continue
if line.startswith("/"):
parts = line.split(" ", 1)
cmd = parts[0].lower()
arg = parts[1].strip() if len(parts) > 1 else ""
if cmd == "/quit":
break
elif cmd == "/join":
if not arg:
await self.send_direct(writer, "Usage: /join <room_name>\n")
else:
await self._change_room(writer, arg)
elif cmd == "/who":
room = self.clients[writer]["room"]
members = [
self.clients[w]["username"]
for w in self.rooms.get(room, set())
if w in self.clients
]
await self.send_direct(writer, f"Users in '{room}': {', '.join(members)}\n")
else:
await self.send_direct(writer, f"Unknown command: {cmd}\n")
else:
# Normal message broadcast
room = self.clients[writer]["room"]
msg = f"<{username}> {line}\n"
await self.broadcast(room, msg, exclude=writer)
except (asyncio.IncompleteReadError, ConnectionResetError):
logging.warning(f"Connection lost abruptly from {peer}")
except Exception as e:
logging.error(f"Error handling client {peer}: {e}")
finally:
# 3. Ensured Cleanup Phase
client_info = self.clients.pop(writer, None)
if client_info:
username = client_info.get("username")
room = self._remove_from_room(writer)
if room and username:
await self.broadcast(room, f"*** {username} has disconnected.\n")
writer.close()
await writer.wait_closed()
logging.info(f"Connection closed for {peer}")
if __name__ == "__main__":
server = ChatServer()
try:
asyncio.run(server.start())
except KeyboardInterrupt:
logging.info("Server shut down cleanly.")
Complexity & Performance Analysis
-
Time Complexity:
- Message Broadcast: $O(K)$ per chat message, where $K$ is the number of active clients in the specific room.
/whoCommand: $O(K)$ to extract and return usernames for the room./joinCommand: $O(1)$ set addition/removal operations, plus $O(K_1 + K_2)$ notification broadcasts for the left and joined rooms.
-
Space Complexity:
- State Overhead: $O(N)$ where $N$ is total active global connections. Stored data per connection is lightweight (holds references to writer streams, username strings, and small dictionary keys).
- Memory Buffers: Bounded by socket stream low/high water marks managed by Python's
asyncio.StreamWriter.
Edge Cases & Production Considerations
- Slow Consumer Problem:
If a client network slows down, awaiting
writer.drain()blocks only the processing task for that specific slow client. Other clients are processed independently by the event loop. If memory bounds are critical, setting explicit high/low watermarks viaasyncio.StreamReaderand custom write queues with drop policies (e.g., dropping messages for clients whose buffer exceeds 1MB) protects against slow-loris conditions. - Abrupt Disconnects & Stale Sockets:
Network drops often don't send TCP
FINpackets immediately. Wrapping operations intry ... finallyguaranteeswriter.close()and dictionary cleanup are executed when socket tasks encounter errors. - Data Framing & Unbounded Lines:
Using
reader.readline()without length bounds can allow a malicious client to stream gigabytes of continuous text without a newline, causing an Out-Of-Memory (OOM) crash. In production, cap line reading lengths usingreader.readuntil(b'\n')combined with limit parameters or manual chunk inspection.