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-in username to its client object.
  • self.rooms: dictionary mapping each active room_name to the set of client objects currently inside it. Whenever a room's member set becomes empty, remove that room key immediately.
  • start(host, port) starts listening with asyncio.start_server (port=0 selects an available OS port) and returns the asyncio.Server instance, spawning one handle_client task 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 become U+FFFD rather 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_line bytes, send "! line too long" to that client and close its connection without disrupting anyone else.
  • If a recipient already has strictly more than max_buffer bytes 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

  1. Immediately upon TCP connection, send "* welcome! enter a username".
  2. 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 (32 characters), 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.

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.
    • /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,000 concurrent TCP client connections on a single asyncio event loop.
  • Pure Python standard library only (asyncio, socket, typing); no external packages.
  • Usernames are 1 to 32 non-whitespace characters and must not begin with "/".
  • Default safety thresholds: max_line = 4096 bytes per incoming line and max_buffer = 262144 bytes (256 KiB) per client send buffer.

Step-by-step walkthrough

  1. 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 enters lobby automatically 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_line bytes (default 4 KiB) get ! line too long and close that client's socket. A slow client whose unsent outgoing buffer passes max_buffer bytes (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]] = {}
    
  2. 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_server runs handle_client(reader, writer) as a lightweight coroutine task on a single event-loop thread. Passing limit=self.max_line tells StreamReader.readline() to stop buffering and raise ValueError if a client sends more than max_line bytes 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 a finally block 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:
                    pass
    
  3. Read lines defensively from the network

    Real TCP clients send messy input, so _read_line handles four network edge cases in one place:

    1. Overlong line: reader.readline() raises ValueError when the line exceeds limit=self.max_line. Reply ! line too long and return None to close that client cleanly.
    2. Clean disconnect (EOF): readline() returns b"" (which does not end with b"\n"). Return None.
    3. Mid-line disconnect: the client sent b"half a li" and dropped without a newline. Because raw.endswith(b"\n") is False, we discard the incomplete fragment instead of broadcasting half a sentence.
    4. Malformed UTF-8 and Windows/telnet line endings: decode("utf-8", errors="replace") replaces bad bytes with the replacement character U+FFFD instead of crashing with UnicodeDecodeError, and .rstrip("\r\n") strips both \n and \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")
    
  4. Log users in without race conditions

    In single-threaded asyncio, tasks switch only at await expressions. Any stretch of synchronous code with no await runs atomically from start to finish.

    Look at what would go wrong if we put await writer.drain() between checking name in self.clients and inserting self.clients[name] = client, or after inserting into self.clients before _login returns client to handle_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 client in self.clients and self.rooms, queuing the welcome line, and returning client with zero awaits in between (and flushing await 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 True
    
        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
    
  5. Broadcast 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:

    • _send is synchronous (no await). It appends bytes to the recipient's outgoing buffer and returns immediately.
    • Before appending, _send checks writer.transport.get_write_buffer_size(). If a stuck client already has more than self.max_buffer bytes waiting, writer.transport.abort() drops their TCP socket right away (unlike writer.close(), which tries to flush unread bytes first). Their own handle_client task then wakes up with EOF and runs finally cleanup.
    • 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"))
    
  6. 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) and self.rooms[room] (the set of clients the room thinks it holds) must always mirror each other.

    Routing every room transition through _enter_room and _leave_room guarantees two invariants:

    1. 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 backend to liam.
    2. Whenever the last member leaves a room (via /join or 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]
    
  7. Parse slash commands and trace a multi-client session

    In _chat_loop, lines beginning with / go to _run_command. Using line.split(maxsplit=1) splits only at the first space, so /join quiet room cleanly extracts command "/join" and room name "quiet room". Command replies (/who) and error messages (! unknown command ...) are sent privately to client.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 True
    

    Trace a session with two clients (maya and liam) 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}}
    
  8. 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:

  1. maya and liam connect; each gets its own handle_client task, passes _login, and enters self.rooms["lobby"] = {maya, liam}.
  2. maya sends "ready to deploy?\n": _broadcast queues "maya: ready to deploy?\n" into liam's outgoing buffer without awaiting, skipping maya so she never hears an echo.
  3. liam sends "/join backend\n": _leave_room removes liam from "lobby" (announcing * liam left lobby to maya), and _enter_room creates self.rooms["backend"] = {liam}.
  4. liam closes his terminal abruptly: reader.readline() returns b"" (EOF, end-of-file signaling the peer closed the connection), finally removes liam from "backend", deletes the now-empty "backend" room, frees "liam" in self.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 _broadcast loops over the r members of self.rooms[client.room] and queues an O(L) encoded copy to each of the r - 1 peers without waiting on the network.
  • Login, /join, and disconnect cleanup: O(r) time, because updating self.clients and the self.rooms sets takes O(1) average dictionary/set operations, followed by broadcasting a short join or leave notice to the r members of the affected room(s).
  • /who: O(r log r) time, because we collect the r usernames in the requester's room, sort them alphabetically, and send one line back to the requester.
  • Space: O(C) for the clients and non-empty rooms structures (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 across C active connections because StreamReader caps incoming lines via limit=max_line and _send aborts any client whose outgoing buffer exceeds max_buffer.

Edge cases

  • No self-echo: _broadcast checks if member is not exclude so senders never receive their own chat lines or join/leave notices.
  • Disconnect before completing login: client is still None in handle_client, so finally simply closes the socket without touching self.clients or self.rooms.
  • Disconnect right after username registration: _login returns client synchronously right after inserting into self.clients and self.rooms (before any await), so a ConnectionResetError during the welcome flush is still cleaned up by finally.
  • Disconnect mid-line: bytes without a trailing b"\n" are discarded rather than broadcast as a broken message.
  • Invalid UTF-8 and \r\n endings: malformed bytes become the replacement character U+FFFD instead of crashing the task, and both \n and \r\n are stripped cleanly.
  • Overlong lines: exceeding max_line replies ! line too long and 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 of writer.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 await between checking name in self.clients and inserting self.clients[name] (or before returning client): another coroutine can claim the same username during the await, or a disconnect during that await can bypass finally cleanup and leave a ghost user.
  • Cleaning up only inside /quit: abrupt TCP resets or EOF bypass /quit and leak users in self.clients and self.rooms unless cleanup lives in finally.
  • Swallowing except Exception: pass: hides real programming bugs; catch OSError for expected network disconnects and let unexpected bugs surface while finally still cleans up state.
  • Forgetting limit=self.max_line on asyncio.start_server: an attacker who streams gigabytes without a newline can exhaust server memory before readline() 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 check transport.get_write_buffer_size() and call transport.abort() once queued bytes exceed max_buffer (as implemented here), or push lines into a bounded per-client asyncio.Queue drained by an independent writer task guarded by asyncio.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 SIGTERM so active clients are notified and pending writes flush safely? Register a signal callback via loop.add_signal_handler(signal.SIGTERM, shutdown_event.set) to trigger an orderly teardown coroutine. First call server.close() to stop accepting new TCP handshakes, broadcast * server shutting down to all active clients, wait up to a bounded grace window (such as 5 seconds) for asyncio.gather(*(w.drain() for w in writers)) wrapped in asyncio.wait_for, close all remaining client writers (calling transport.abort() on any stragglers that failed to flush before the deadline), and finally await 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_line on incoming reads and max_buffer on 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 each Client a token bucket rate limiter (refilling R message credits per second up to a burst ceiling B) and drop or disconnect clients that send lines when their bucket is empty.

Follow-up questions

Similar questions

More Discord interview questions

All 15 Discord questions →