Concurrent Multi-Room TCP Chat Server with Python asyncio
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement a concurrent, multi-room TCP chat server in pure standard-library Python using asyncio. Each connected client communicates over a UTF-8, newline-delimited ("\n") text protocol, and every line sent by the server ends with "\n".
Implement ChatServer with the following interface and observable state:
DEFAULT_ROOM = "lobby"
MAX_NAME = 32
class ChatServer:
def __init__(self, max_line: int = 4096, max_buffer: int = 256 * 1024) -> None: ...
async def start(self, host: str = "127.0.0.1", port: int = 0) -> asyncio.Server: ...
async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: ...
self.clients: dictionary mapping each currently logged-inusernameto its client object.self.rooms: dictionary mapping each activeroom_nameto thesetof client objects currently inside it. Whenever a room's member set becomes empty, remove that room key immediately.start(host, port)starts listening withasyncio.start_server(port=0selects an available OS port) and returns theasyncio.Serverinstance, spawning onehandle_clienttask per connection.
Wire Framing & Decoding
- Incoming lines terminate with
"\n"or"\r\n"(strip trailing"\r"and"\n"). Decode bytes as UTF-8 with replacement so invalid byte sequences becomeU+FFFDrather than crashing the server. - If a client closes the connection cleanly (EOF) or disconnects mid-line without a trailing
"\n", discard any incomplete line fragment and clean up the session. - If an incoming line exceeds
max_linebytes, send"! line too long"to that client and close its connection without disrupting anyone else. - If a recipient already has strictly more than
max_bufferbytes of unsent data queued in its transport write buffer, abort that recipient's connection immediately so a stalled reader never blocks room broadcasts.
Login Handshake
- Immediately upon TCP connection, send
"* welcome! enter a username". - Read candidate lines until login succeeds or the client disconnects. Strip leading and trailing whitespace from each line:
- If the stripped name is empty, exceeds
MAX_NAME(32characters), contains any whitespace character, or starts with"/", reply"! invalid username, try again"and wait for another line. - Otherwise, if the name is already present in
self.clients, reply"! username taken, try again"and wait for another line. - Otherwise, register the user in
DEFAULT_ROOM("lobby"), broadcast"* <name> joined lobby"to everyone else already in"lobby", and send"* welcome <name>, you are in lobby"to the new user.
- If the stripped name is empty, exceeds
Chat Messages & Slash Commands
After login, each incoming line is either a slash command (starts with "/") or a chat message:
- Chat messages (not starting with
"/"): Ignore empty or whitespace-only lines. Broadcast any other line to all other members of the sender's current room as"<name>: <line>"(never echo back to the sender). - Slash commands (starting with
"/"): Split at the first whitespace so the first token is the command and the stripped remainder (if any) is the argument:/join <room>:- If
<room>is empty, send"! usage: /join <room>"privately to the requester. - If
<room>equals the user's current room, send"! already in <room>"privately to the requester. - Otherwise, remove the user from their previous room (broadcasting
"* <name> left <old_room>"to remaining members, or deleting<old_room>if empty), add them to<room>(creating it if needed and broadcasting"* <name> joined <room>"to existing members), and send"* you joined <room>"privately to the user.
- If
/who: Send"* in <room>: <names>"privately to the requester, where<names>joins the lexicographically sorted usernames in the requester's current room with", "./quit: Send"* bye"privately to the requester and close their connection cleanly.- Any other command token
<cmd>: Send"! unknown command <cmd>"privately to the requester.
Disconnect Cleanup
Whenever a logged-in user disconnects—whether via /quit, EOF, socket error/reset, overlong line, or buffer overflow—remove them from their current room (broadcasting "* <name> left <room>" to remaining members or deleting the room if empty), delete their entry from self.clients so the username can be reused immediately, and close the socket.
Examples
Example 1
Input / Session Trace:
1. Client 1 connects -> receives "* welcome! enter a username"
2. Client 1 sends "bad name" -> receives "! invalid username, try again"
3. Client 1 sends "maya" -> receives "* welcome maya, you are in lobby"
4. Client 2 connects -> receives "* welcome! enter a username"
5. Client 2 sends "maya" -> receives "! username taken, try again"
6. Client 2 sends "liam" -> maya receives "* liam joined lobby"
liam receives "* welcome liam, you are in lobby"
7. maya sends "ready to deploy?" -> liam receives "maya: ready to deploy?"
8. liam sends "/quit" -> liam receives "* bye" (and socket closes)
maya receives "* liam left lobby"
Walk-through: Invalid names with internal spaces and duplicate active names are rejected without dropping the TCP connection. Once both users are in "lobby", "maya"'s chat line goes only to "liam", and "liam"'s /quit triggers a private "* bye" followed by a room departure notice to "maya".
Example 2
Input / Session Trace:
1. "omar", "nina", and "Eli" log in (all start in "lobby")
2. nina sends "/who" -> nina receives "* in lobby: Eli, nina, omar"
3. omar sends "/join backend" -> omar receives "* you joined backend"
nina and Eli each receive "* omar left lobby"
4. Eli sends "/join backend" -> Eli receives "* you joined backend"
omar receives "* Eli joined backend"
nina receives "* Eli left lobby"
5. omar sends "ship it" -> Eli receives "omar: ship it" (nina hears nothing)
6. nina sends "/ping" -> nina receives "! unknown command /ping"
Walk-through: /who sorts usernames in standard ASCII/lexicographic order ("Eli" before "nina" and "omar") and replies only to "nina". Switching rooms scopes subsequent chat messages and join/leave notices strictly to "backend", while command errors stay private to "nina".
Constraints
- Up to
1,000concurrent TCP client connections on a singleasyncioevent loop. - Pure Python standard library only (
asyncio,socket,typing); no external packages. - Usernames are
1to32non-whitespace characters and must not begin with"/". - Default safety thresholds:
max_line = 4096bytes per incoming line andmax_buffer = 262144bytes (256KiB) per client send buffer.
Step-by-step walkthrough
Agree on the wire protocol and server state
Before touching sockets, pin down the exact line protocol and edge-case rules so clients and server agree on every message:
- Clear prefixes: chat lines look like
<name>: <message>. Server announcements start with*(such as* liam joined lobby), and private error replies start with!(such as! username taken, try again). Disallowing spaces inside usernames guarantees a user can never spoof a server announcement. - Unique, validated usernames: names must be 1–32 characters, contain no whitespace, and not start with
/. If a name is invalid or currently in use, the server sends an error line and lets the client try again. - Default room (
lobby): every logged-in user enterslobbyautomatically so everyone starts in a shared room before anyone runs/join. - Commands vs. chat: any line starting with
/is parsed as a command (/join <room>,/who,/quit, or! unknown command ...). Blank chat lines are ignored. - Safety bounds: lines longer than
max_linebytes (default 4 KiB) get! line too longand close that client's socket. A slow client whose unsent outgoing buffer passesmax_bufferbytes (default 256 KiB) is dropped immediately so it cannot stall others or exhaust memory.
Two dictionaries hold the entire in-memory state of the server:
self.clients: "maya" -> Client(name="maya", room="lobby", writer=...) "liam" -> Client(name="liam", room="backend", writer=...) self.rooms: "lobby" -> { Client("maya") } "backend" -> { Client("liam") } (empty rooms are deleted immediately)from typing import Dict, List, Optional, Set import asyncio DEFAULT_ROOM = "lobby" MAX_NAME = 32 class Client: """Represents one logged-in user: chosen username, TCP writer, and current room name.""" def __init__(self, name: str, writer: asyncio.StreamWriter) -> None: self.name = name self.writer = writer self.room = DEFAULT_ROOM class ChatServer: def __init__(self, max_line: int = 4096, max_buffer: int = 256 * 1024) -> None: # max_line: maximum bytes allowed per incoming line before disconnecting that client. self.max_line = max_line # max_buffer: maximum unsent outgoing bytes buffered per client before dropping them. self.max_buffer = max_buffer # clients: maps username -> Client for every currently logged-in user, e.g. {"alice": Client(...)}. self.clients: Dict[str, Client] = {} # rooms: maps room_name -> set of Client members; empty rooms are removed immediately. self.rooms: Dict[str, Set[Client]] = {}- Clear prefixes: chat lines look like
Spawn one task per client with guaranteed cleanup
With 1,000 connected users, almost everyone is idle waiting for the next line of text over the network. Instead of spawning 1,000 OS threads,
asyncio.start_serverrunshandle_client(reader, writer)as a lightweight coroutine task on a single event-loop thread. Passinglimit=self.max_linetellsStreamReader.readline()to stop buffering and raiseValueErrorif a client sends more thanmax_linebytes without a"\n".A client can disconnect in many ways: typing
/quit, closing their terminal (EOF), losing Wi-Fi (OSError/ConnectionResetError), sending an overlong line, or task cancellation. Putting room removal, username release, and socket closure inside afinallyblock guarantees zero leaked "ghost" users on every exit path:async def start(self, host: str = "127.0.0.1", port: int = 0) -> asyncio.Server: # Passing limit=self.max_line caps how many bytes StreamReader.readline() will buffer # while searching for "\n", preventing a single endless line from exhausting RAM. return await asyncio.start_server(self.handle_client, host, port, limit=self.max_line) async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: """Serve one TCP connection as an independent task from connect to disconnect.""" client: Optional[Client] = None try: # Phase 1: prompt for a valid, unused username and register the client. client = await self._login(reader, writer) # Phase 2: process chat lines and slash commands until disconnect or /quit. if client is not None: await self._chat_loop(client, reader) except OSError: # Peer reset the socket or broke the pipe; treat like a normal disconnect below. pass finally: # Phase 3: guaranteed cleanup on every exit path (/quit, EOF, reset, error, cancel). if client is not None: self._leave_room(client) del self.clients[client.name] writer.close() try: await writer.wait_closed() except OSError: passRead lines defensively from the network
Real TCP clients send messy input, so
_read_linehandles four network edge cases in one place:- Overlong line:
reader.readline()raisesValueErrorwhen the line exceedslimit=self.max_line. Reply! line too longand returnNoneto close that client cleanly. - Clean disconnect (EOF):
readline()returnsb""(which does not end withb"\n"). ReturnNone. - Mid-line disconnect: the client sent
b"half a li"and dropped without a newline. Becauseraw.endswith(b"\n")isFalse, we discard the incomplete fragment instead of broadcasting half a sentence. - Malformed UTF-8 and Windows/telnet line endings:
decode("utf-8", errors="replace")replaces bad bytes with the replacement characterU+FFFDinstead of crashing withUnicodeDecodeError, and.rstrip("\r\n")strips both\nand\r\n.
async def _read_line(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Optional[str]: """Read one '\\n'-terminated UTF-8 line, or return None if the client disconnected.""" try: raw = await reader.readline() except ValueError: # StreamReader raises ValueError when incoming bytes exceed limit=self.max_line. self._send(writer, "! line too long") return None # Empty bytes (clean EOF) or partial bytes without '\n' (mid-line disconnect) end the session. if not raw.endswith(b"\n"): return None # Replace malformed UTF-8 bytes with U+FFFD and strip both '\n' and telnet-style '\r\n'. decoded = raw.decode("utf-8", errors="replace") return decoded.rstrip("\r\n")- Overlong line:
Log users in without race conditions
In single-threaded
asyncio, tasks switch only atawaitexpressions. Any stretch of synchronous code with noawaitruns atomically from start to finish.Look at what would go wrong if we put
await writer.drain()between checkingname in self.clientsand insertingself.clients[name] = client, or after inserting intoself.clientsbefore_loginreturnsclienttohandle_client:BUGGY ORDER 1 (race between two logins): Task A: "alice" in self.clients -> False Task A: await writer.drain() <--- yields to event loop! Task B: "alice" in self.clients -> False! Both claim "alice"! BUGGY ORDER 2 (ghost leak if drain fails inside _login): _login: self.clients["alice"] = client; self._enter_room(client, "lobby") _login: await writer.drain() <--- raises ConnectionResetError! handle_client: `client` was never assigned (still None) -> finally skips cleanup!By doing the uniqueness check, registering
clientinself.clientsandself.rooms, queuing the welcome line, and returningclientwith zeroawaits in between (and flushingawait client.writer.drain()at the top of_chat_loop), both bugs become impossible:def _valid_username(name: str) -> bool: # Reject empty names, names over 32 chars, or names starting with "/" (looks like a command). if not name or len(name) > MAX_NAME or name.startswith("/"): return False # Disallow whitespace so "<name>: <msg>" cannot spoof server notices like "* bob joined lobby". for ch in name: if ch.isspace(): return False return Trueasync def _login(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Optional[Client]: self._send(writer, "* welcome! enter a username") while True: await writer.drain() line = await self._read_line(reader, writer) if line is None: return None name = line.strip() if not _valid_username(name): self._send(writer, "! invalid username, try again") elif name in self.clients: self._send(writer, "! username taken, try again") else: break # Critical concurrency invariant: do NOT `await` between checking `name in self.clients`, # inserting into `self.clients` / `self.rooms`, and returning `client` to `handle_client`. # That prevents two tasks from claiming the same name AND ensures `handle_client` holds # the `client` reference before the next `await writer.drain()` can fail. client = Client(name, writer) self.clients[name] = client self._enter_room(client, DEFAULT_ROOM) self._send(writer, f"* welcome {name}, you are in {DEFAULT_ROOM}") return clientBroadcast without letting one slow reader stall everyone
A tempting broadcast loop writes to every member in the room and runs
await member.writer.drain()on each one. That fails under load:drain()pauses whenever a recipient's outgoing buffer fills up, so one frozen laptop would freeze the sender's task and stop everyone else in the room from receiving messages.Instead, decouple queuing from waiting:
_sendis synchronous (noawait). It appends bytes to the recipient's outgoing buffer and returns immediately.- Before appending,
_sendcheckswriter.transport.get_write_buffer_size(). If a stuck client already has more thanself.max_bufferbytes waiting,writer.transport.abort()drops their TCP socket right away (unlikewriter.close(), which tries to flush unread bytes first). Their ownhandle_clienttask then wakes up with EOF and runsfinallycleanup. - Each sender task awaits
client.writer.drain()only on its own socket after processing each input line.
def _broadcast(self, room: str, text: str, exclude: Client) -> None: # Safe to iterate directly: `_send` never awaits and never mutates `self.rooms`. for member in self.rooms[room]: if member is not exclude: self._send(member.writer, text) def _send(self, writer: asyncio.StreamWriter, text: str) -> None: """Queue one outgoing line without awaiting; abort clients whose send buffer overflows.""" if writer.is_closing(): return if writer.transport.get_write_buffer_size() > self.max_buffer: # abort() drops the socket immediately without waiting for unread bytes to flush; # that client's own reader will then see EOF and run `finally` cleanup. writer.transport.abort() return writer.write((text + "\n").encode("utf-8"))Keep rooms and members in sync
Every logged-in user belongs to exactly one room at a time. That means
client.room(which room the client thinks it is in) andself.rooms[room](the set of clients the room thinks it holds) must always mirror each other.Routing every room transition through
_enter_roomand_leave_roomguarantees two invariants:- Moving rooms notifies the remaining members of the old room (
* liam left lobby), enters the new room and notifies its existing members (* liam joined backend), and confirms* you joined backendtoliam. - Whenever the last member leaves a room (via
/joinor disconnect),del self.rooms[client.room]garbage-collects the empty set so creating thousands of temporary rooms never leaks memory.
def _join(self, client: Client, room: str) -> None: if not room: self._send(client.writer, "! usage: /join <room>") elif room == client.room: self._send(client.writer, f"! already in {room}") else: self._leave_room(client) self._enter_room(client, room) self._send(client.writer, f"* you joined {room}") def _enter_room(self, client: Client, room: str) -> None: # Update both client -> room and room -> members together so they never drift apart. client.room = room if room not in self.rooms: self.rooms[room] = set() self.rooms[room].add(client) self._broadcast(room, f"* {client.name} joined {room}", exclude=client) def _leave_room(self, client: Client) -> None: members = self.rooms[client.room] members.discard(client) if members: self._broadcast(client.room, f"* {client.name} left {client.room}", exclude=client) else: # Delete empty rooms immediately so `self.rooms` cannot grow without bound. del self.rooms[client.room]- Moving rooms notifies the remaining members of the old room (
Parse slash commands and trace a multi-client session
In
_chat_loop, lines beginning with/go to_run_command. Usingline.split(maxsplit=1)splits only at the first space, so/join quiet roomcleanly extracts command"/join"and room name"quiet room". Command replies (/who) and error messages (! unknown command ...) are sent privately toclient.writer, never broadcast to the room:async def _chat_loop(self, client: Client, reader: asyncio.StreamReader) -> None: # Flush the login welcome message now that `handle_client` owns `client` for cleanup. await client.writer.drain() while True: line = await self._read_line(reader, client.writer) if line is None: return if line.startswith("/"): keep_going = self._run_command(client, line) if not keep_going: return elif line.strip(): # Ignore blank chat lines; broadcast non-empty messages to peers in the same room. self._broadcast(client.room, f"{client.name}: {line}", exclude=client) # Drain only the sender's own writer so a slow peer never stalls this loop. await client.writer.drain() def _run_command(self, client: Client, line: str) -> bool: """Execute a slash command. Return False only when the client ran /quit.""" parts = line.split(maxsplit=1) command = parts[0] argument = "" if len(parts) == 2: argument = parts[1].strip() if command == "/quit": self._send(client.writer, "* bye") return False if command == "/join": self._join(client, argument) elif command == "/who": member_names: List[str] = [] for member in self.rooms[client.room]: member_names.append(member.name) member_names.sort() roster = ", ".join(member_names) self._send(client.writer, f"* in {client.room}: {roster}") else: self._send(client.writer, f"! unknown command {command}") return TrueTrace a session with two clients (
mayaandliam) from connect to disconnect:client input messages sent by server self.rooms state ---------------------- --------------------------------------------- ---------------------------------- maya connects -> maya: "* welcome! enter a username" {} maya: "maya" -> maya: "* welcome maya, you are in lobby" {"lobby": {maya}} liam connects -> liam: "* welcome! enter a username" {"lobby": {maya}} liam: "liam" -> maya: "* liam joined lobby" -> liam: "* welcome liam, you are in lobby" {"lobby": {maya, liam}} maya: "ready to deploy?"-> liam: "maya: ready to deploy?" (no echo) {"lobby": {maya, liam}} liam: "/join backend" -> maya: "* liam left lobby" -> liam: "* you joined backend" {"lobby": {maya}, "backend": {liam}} liam: "/quit" -> liam: "* bye", socket closes, finally runs: "backend" becomes empty and is deleted {"lobby": {maya}}Complete solution
from typing import Dict, List, Optional, Set import asyncio DEFAULT_ROOM = "lobby" MAX_NAME = 32 class Client: """Represents one logged-in user: chosen username, TCP writer, and current room name.""" def __init__(self, name: str, writer: asyncio.StreamWriter) -> None: self.name = name self.writer = writer self.room = DEFAULT_ROOM def _valid_username(name: str) -> bool: # Reject empty names, names over 32 chars, or names starting with "/" (looks like a command). if not name or len(name) > MAX_NAME or name.startswith("/"): return False # Disallow whitespace so "<name>: <msg>" cannot spoof server notices like "* bob joined lobby". for ch in name: if ch.isspace(): return False return True class ChatServer: def __init__(self, max_line: int = 4096, max_buffer: int = 256 * 1024) -> None: # max_line: maximum bytes allowed per incoming line before disconnecting that client. self.max_line = max_line # max_buffer: maximum unsent outgoing bytes buffered per client before dropping them. self.max_buffer = max_buffer # clients: maps username -> Client for every currently logged-in user, e.g. {"alice": Client(...)}. self.clients: Dict[str, Client] = {} # rooms: maps room_name -> set of Client members; empty rooms are removed immediately. self.rooms: Dict[str, Set[Client]] = {} async def start(self, host: str = "127.0.0.1", port: int = 0) -> asyncio.Server: # Passing limit=self.max_line caps how many bytes StreamReader.readline() will buffer # while searching for "\n", preventing a single endless line from exhausting RAM. return await asyncio.start_server(self.handle_client, host, port, limit=self.max_line) async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: """Serve one TCP connection as an independent task from connect to disconnect.""" client: Optional[Client] = None try: # Phase 1: prompt for a valid, unused username and register the client. client = await self._login(reader, writer) # Phase 2: process chat lines and slash commands until disconnect or /quit. if client is not None: await self._chat_loop(client, reader) except OSError: # Peer reset the socket or broke the pipe; treat like a normal disconnect below. pass finally: # Phase 3: guaranteed cleanup on every exit path (/quit, EOF, reset, error, cancel). if client is not None: self._leave_room(client) del self.clients[client.name] writer.close() try: await writer.wait_closed() except OSError: pass async def _login(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Optional[Client]: self._send(writer, "* welcome! enter a username") while True: await writer.drain() line = await self._read_line(reader, writer) if line is None: return None name = line.strip() if not _valid_username(name): self._send(writer, "! invalid username, try again") elif name in self.clients: self._send(writer, "! username taken, try again") else: break # Critical concurrency invariant: do NOT `await` between checking `name in self.clients`, # inserting into `self.clients` / `self.rooms`, and returning `client` to `handle_client`. # That prevents two tasks from claiming the same name AND ensures `handle_client` holds # the `client` reference before the next `await writer.drain()` can fail. client = Client(name, writer) self.clients[name] = client self._enter_room(client, DEFAULT_ROOM) self._send(writer, f"* welcome {name}, you are in {DEFAULT_ROOM}") return client async def _chat_loop(self, client: Client, reader: asyncio.StreamReader) -> None: # Flush the login welcome message now that `handle_client` owns `client` for cleanup. await client.writer.drain() while True: line = await self._read_line(reader, client.writer) if line is None: return if line.startswith("/"): keep_going = self._run_command(client, line) if not keep_going: return elif line.strip(): # Ignore blank chat lines; broadcast non-empty messages to peers in the same room. self._broadcast(client.room, f"{client.name}: {line}", exclude=client) # Drain only the sender's own writer so a slow peer never stalls this loop. await client.writer.drain() async def _read_line(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Optional[str]: """Read one '\\n'-terminated UTF-8 line, or return None if the client disconnected.""" try: raw = await reader.readline() except ValueError: # StreamReader raises ValueError when incoming bytes exceed limit=self.max_line. self._send(writer, "! line too long") return None # Empty bytes (clean EOF) or partial bytes without '\n' (mid-line disconnect) end the session. if not raw.endswith(b"\n"): return None # Replace malformed UTF-8 bytes with U+FFFD and strip both '\n' and telnet-style '\r\n'. decoded = raw.decode("utf-8", errors="replace") return decoded.rstrip("\r\n") def _run_command(self, client: Client, line: str) -> bool: """Execute a slash command. Return False only when the client ran /quit.""" parts = line.split(maxsplit=1) command = parts[0] argument = "" if len(parts) == 2: argument = parts[1].strip() if command == "/quit": self._send(client.writer, "* bye") return False if command == "/join": self._join(client, argument) elif command == "/who": member_names: List[str] = [] for member in self.rooms[client.room]: member_names.append(member.name) member_names.sort() roster = ", ".join(member_names) self._send(client.writer, f"* in {client.room}: {roster}") else: self._send(client.writer, f"! unknown command {command}") return True def _join(self, client: Client, room: str) -> None: if not room: self._send(client.writer, "! usage: /join <room>") elif room == client.room: self._send(client.writer, f"! already in {room}") else: self._leave_room(client) self._enter_room(client, room) self._send(client.writer, f"* you joined {room}") def _enter_room(self, client: Client, room: str) -> None: # Update both client -> room and room -> members together so they never drift apart. client.room = room if room not in self.rooms: self.rooms[room] = set() self.rooms[room].add(client) self._broadcast(room, f"* {client.name} joined {room}", exclude=client) def _leave_room(self, client: Client) -> None: members = self.rooms[client.room] members.discard(client) if members: self._broadcast(client.room, f"* {client.name} left {client.room}", exclude=client) else: # Delete empty rooms immediately so `self.rooms` cannot grow without bound. del self.rooms[client.room] def _broadcast(self, room: str, text: str, exclude: Client) -> None: # Safe to iterate directly: `_send` never awaits and never mutates `self.rooms`. for member in self.rooms[room]: if member is not exclude: self._send(member.writer, text) def _send(self, writer: asyncio.StreamWriter, text: str) -> None: """Queue one outgoing line without awaiting; abort clients whose send buffer overflows.""" if writer.is_closing(): return if writer.transport.get_write_buffer_size() > self.max_buffer: # abort() drops the socket immediately without waiting for unread bytes to flush; # that client's own reader will then see EOF and run `finally` cleanup. writer.transport.abort() return writer.write((text + "\n").encode("utf-8"))✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a single fast switchboard operator managing 1,000 chat lines at once. Because almost every caller spends most of their time reading or typing rather than sending bytes at that exact microsecond, one operator can juggle all 1,000 lines effortlessly—as long as the operator never waits on hold for any single caller. Whenever someone finishes speaking a line, the operator drops a copy into the outgoing mailbox of everyone else in the same room and immediately moves on; if a caller stops picking up their outgoing mail and their mailbox overflows, the operator hangs up that one line so the rest of the room keeps talking smoothly.
A naive server design fails in three common ways. Spawning one OS thread per client wastes megabytes of thread-stack memory and forces mutex locks around every dictionary access; calling await writer.drain() on every recipient inside the broadcast loop lets a single frozen client pause the sender's task and stall the whole room; and cleaning up users only when they type /quit leaves permanent "ghost" members behind whenever a socket resets or disconnects unexpectedly.
Instead, we run one coroutine (an async function that can pause at await while waiting for network I/O and resume later) per client on Python's single-threaded event loop (the scheduler that wakes up whichever coroutine just received network data). Because cooperative multitasking (where tasks yield control voluntarily only at await points rather than being interrupted mid-line) runs synchronous blocks atomically, our clients and rooms dictionaries need no locks as long as we never await partway through an update. Walk through four events to see how it works:
mayaandliamconnect; each gets its ownhandle_clienttask, passes_login, and entersself.rooms["lobby"] = {maya, liam}.mayasends"ready to deploy?\n":_broadcastqueues"maya: ready to deploy?\n"intoliam's outgoing buffer without awaiting, skippingmayaso she never hears an echo.liamsends"/join backend\n":_leave_roomremovesliamfrom"lobby"(announcing* liam left lobbytomaya), and_enter_roomcreatesself.rooms["backend"] = {liam}.liamcloses his terminal abruptly:reader.readline()returnsb""(EOF, end-of-file signaling the peer closed the connection),finallyremovesliamfrom"backend", deletes the now-empty"backend"room, frees"liam"inself.clients, and closes the socket.
Complexity
Let C be the total number of logged-in clients, r be the number of members in the client's current room, and L be the length of an incoming line in bytes.
- Broadcasting a chat line: O(L + r · L) time, because reading and decoding the sender's line takes O(L) time, and
_broadcastloops over thermembers ofself.rooms[client.room]and queues an O(L) encoded copy to each of ther - 1peers without waiting on the network. - Login,
/join, and disconnect cleanup: O(r) time, because updatingself.clientsand theself.roomssets takes O(1) average dictionary/set operations, followed by broadcasting a short join or leave notice to thermembers of the affected room(s). /who: O(r log r) time, because we collect therusernames in the requester's room, sort them alphabetically, and send one line back to the requester.- Space: O(C) for the
clientsand non-emptyroomsstructures (since every client sits in at most one room set and empty rooms are deleted), plus O(C · (max_line + max_buffer)) worst-case buffered network bytes acrossCactive connections becauseStreamReadercaps incoming lines vialimit=max_lineand_sendaborts any client whose outgoing buffer exceedsmax_buffer.
Edge cases
- No self-echo:
_broadcastchecksif member is not excludeso senders never receive their own chat lines or join/leave notices. - Disconnect before completing login:
clientis stillNoneinhandle_client, sofinallysimply closes the socket without touchingself.clientsorself.rooms. - Disconnect right after username registration:
_loginreturnsclientsynchronously right after inserting intoself.clientsandself.rooms(before anyawait), so aConnectionResetErrorduring the welcome flush is still cleaned up byfinally. - Disconnect mid-line: bytes without a trailing
b"\n"are discarded rather than broadcast as a broken message. - Invalid UTF-8 and
\r\nendings: malformed bytes become the replacement characterU+FFFDinstead of crashing the task, and both\nand\r\nare stripped cleanly. - Overlong lines: exceeding
max_linereplies! line too longand disconnects only the offending client. - Empty rooms and freed usernames: when the last member leaves a room, the room key is deleted; when a user leaves or disconnects, their username is immediately available again.
Common mistakes
- Awaiting
member.writer.drain()inside_broadcast: backpressure (the mechanism that slows a writer down when a receiver stops reading) on one stuck socket then pauses the sender's coroutine and blocks messages to every healthy user in the room. - Using
writer.close()instead ofwriter.transport.abort()on a stuck client:close()waits for buffered bytes to flush to the peer, which hangs forever when the peer is not reading. - Putting an
awaitbetween checkingname in self.clientsand insertingself.clients[name](or before returningclient): another coroutine can claim the same username during theawait, or a disconnect during thatawaitcan bypassfinallycleanup and leave a ghost user. - Cleaning up only inside
/quit: abrupt TCP resets or EOF bypass/quitand leak users inself.clientsandself.roomsunless cleanup lives infinally. - Swallowing
except Exception: pass: hides real programming bugs; catchOSErrorfor expected network disconnects and let unexpected bugs surface whilefinallystill cleans up state. - Forgetting
limit=self.max_lineonasyncio.start_server: an attacker who streams gigabytes without a newline can exhaust server memory beforereadline()ever returns.
Follow-up questions
- How would you scale this architecture horizontally across multiple machines so users connected to different nodes can still chat in the same room? Introduce a distributed pub/sub backbone (a publish-subscribe message bus such as Redis Pub/Sub, NATS, or Kafka where nodes publish to named topics and subscribers receive matching events) behind a Layer-4 TCP load balancer: each chat node subscribes only to topics for rooms that have at least one local member, publishes local messages to
room:<name>, and fans incoming bus events out to local sockets. Claim global usernames in Redis with atomic set-if-absent (SET user:<name> <node_id> NX) backed by a heartbeat-renewed TTL (time-to-live lease timer) so names owned by a dead node automatically release, and maintain room membership sets in shared Redis storage for/who. - What happens when a connected peer stops reading from its TCP socket, and what backpressure or timeout mechanisms prevent one stalled connection from degrading the room? Unread outgoing bytes accumulate in the server's per-socket write buffer; if the broadcast path awaited
writer.drain()on every recipient, backpressure on that full socket would suspend the sender's task and freeze the room. Avoid awaiting peer writers during broadcast: either checktransport.get_write_buffer_size()and calltransport.abort()once queued bytes exceedmax_buffer(as implemented here), or push lines into a bounded per-clientasyncio.Queuedrained by an independent writer task guarded byasyncio.wait_for(writer.drain(), timeout=10.0), paired with read/login idle timeouts (asyncio.wait_for(reader.readline(), timeout=300.0)) to reap silent half-open sockets. - How would you orchestrate a clean server shutdown when the process receives
SIGTERMso active clients are notified and pending writes flush safely? Register a signal callback vialoop.add_signal_handler(signal.SIGTERM, shutdown_event.set)to trigger an orderly teardown coroutine. First callserver.close()to stop accepting new TCP handshakes, broadcast* server shutting downto all active clients, wait up to a bounded grace window (such as 5 seconds) forasyncio.gather(*(w.drain() for w in writers))wrapped inasyncio.wait_for, close all remaining client writers (callingtransport.abort()on any stragglers that failed to flush before the deadline), and finallyawait server.wait_closed(). - Which resource caps and rate-limiting controls would you put in place to defend the server against memory exhaustion and spam? Alongside
limit=max_lineon incoming reads andmax_bufferon outgoing buffers, enforce a global active-connection ceiling and a per-IP connection cap (immediately closing excess sockets with! server full), cap room-name length and total active rooms, and apply short login and idle timeouts. To throttle chat floods, give eachClienta token bucket rate limiter (refillingRmessage credits per second up to a burst ceilingB) and drop or disconnect clients that send lines when their bucket is empty.
Follow-up questions
- How would you scale this architecture horizontally across multiple machines so users connected to different nodes can still chat in the same room?
- What happens when a connected peer stops reading from its TCP socket, and what backpressure or timeout mechanisms prevent one stalled connection from degrading the room?
- How would you orchestrate a clean server shutdown when the process receives `SIGTERM` so active clients are notified and pending writes flush safely?
- Which resource caps and rate-limiting controls would you put in place to defend the server against memory exhaustion and spam?
Similar questions
- Single-Character Occurrence Count
- Streaming Per-User Session Aggregator
- Words Unique to Either Message
- Engineering Workflow for AI-Assisted Coding Interviews
- Persistent Multi-Room Chat Server over Raw TCP
- Redis Lease-Based Distributed Leader Election
More Discord interview questions
- Persistent Multi-Room Chat Server over Raw TCP Medium
- Single-Character Occurrence Count Medium
- Engineering Workflow for AI-Assisted Coding Interviews Medium Pro
- Redis Lease-Based Distributed Leader Election Medium Pro
- Experimentation Plan for Propensity-Targeted Subscription Pushes Medium Pro
- Driving a Business Decision with Causal Inference Medium Pro
- Streaming Per-User Session Aggregator Hard Pro
- Words Unique to Either Message Medium Pro
- Career Arc, Storage Project, and Production On-Call Hard Pro
- Experiment Design for Subscription Prompts and Friend Autocomplete Medium Pro