KatInterview

Build a Multi-Room Async TCP Chat Server

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesconcurrencyasyncionetworking

Last 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:

  1. Stage 1 (Global Server): Manage client connections, authenticate users via a prompt, and handle basic message broadcasting across all active sessions.
  2. Stage 2 (Rooms & Commands): Add multi-room support and slash-command handling while maintaining consistent shared state and preventing resource leaks.

Core Requirements & Constraints

  1. Standard Library Only: Rely exclusively on asyncio and Python's built-in modules.
  2. Protocol Standard:
    • Input and output must be line-delimited (ending in \n).
    • Every line must be valid UTF-8 text.
  3. 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.
  4. 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.
  5. 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.