Persistent Multi-Room Chat Server over Raw TCP

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a multi-room chat service accessed directly over raw TCP sockets (such as via telnet, nc, or PuTTY) where multiple concurrent users exchange line-oriented text messages.

Support the following core capabilities:

  • Line protocol and slash commands: Accept newline-delimited text commands including /help (command reference), /nick <name> (claim or rename a handle), /users (display online participants—specify whether scoped to the active room, server-wide, or both), and /quit (close the session cleanly).
  • Channel management and live fan-out: Allow users to create channels, list existing channels, and join them; deliver every message posted in a channel to all currently connected members of that channel, and replay the channel's 10 most recent messages whenever a user joins.
  • Session resumption and crash durability: Specify how a returning client authenticates over a fresh TCP connection to restore prior channel memberships after a network drop, and ensure user accounts, channels, memberships, and message history survive server restarts.
  • Concurrency and horizontal scale: Detail your wire framing, storage schema, concurrency model, slow-reader backpressure, crash-safe write path, and evolution from a single process to a multi-node deployment.

Scope & Expectations

  • Define a defensive raw-TCP byte-stream protocol (line framing, Telnet control-byte stripping, max-length bounds, and secure credential-based reconnection without custom client SDKs).
  • Present a durable data model and single-node concurrency design that preserves per-room message ordering, atomic 10-message history replay on join, and isolation from stalled TCP readers.
  • Show how connection gateways and sharded room owners scale fan-out, ordering, and failover across multiple hosts.

Step-by-step walkthrough

  1. Clarify requirements and pin down protocol choices

    Because clients connect using raw terminal tools like telnet, PuTTY, or nc rather than a custom mobile or browser SDK, there is no client-side code to attach headers, retry lost packets, or store cookies. State your explicit choices for every open question up front:

    • Protocol format: human-readable UTF-8 text, one command or chat message per newline-terminated line.
    • Identity for reconnection: when a new user runs /nick alice, the server creates account alice and prints a random 128-bit resume key once. After a disconnect or server restart, /login alice <key> authenticates her on the new TCP socket and restores her state. Neither IP addresses (shared behind office NAT and changing across Wi-Fi/cellular) nor bare nicknames (trivially spoofed by anyone typing /nick alice) can safely identify a returning user.
    • Persistent membership vs. ephemeral presence: a user can belong to multiple rooms at once. Membership ("Alice belongs to #general and #rust") is saved in the database; disconnecting is not leaving. Presence ("Alice currently has an open socket") lives only in memory. Plain text goes to the user's single active room, while incoming messages from all joined rooms stream to their terminal prefixed with [#room HH:MM].
    • /users scope: /users lists online users in the caller's active room; /users all lists up to 100 online users globally plus the total count.
    • Message history: /join <room> switches the active room (adding membership if needed) and prints its last 10 messages. /login prints the last 10 messages of the user's active room plus unread message counts for their other joined rooms.
    • Persistence across restarts: users, rooms, memberships, messages, active rooms, and per-room read markers survive server restarts. Live TCP sockets cannot survive an OS process restart, so clients reconnect and /login.

    Non-functional targets:

    • Single-node capacity: 10,000 concurrent TCP connections across 2,000 rooms, with p99 broadcast latency < 100 ms.
    • Crash-safe history (visible implies durable): no message already displayed to any user may disappear from room history if the server crashes.
    • Per-room total order: every member of #general sees #general's messages in the exact same sequence.
    • Slow-client isolation: one stalled or malicious terminal must never freeze broadcasts for everyone else.
    • Horizontal scale path: clean evolution from one process to multi-host gateways and sharded room owners.
  2. Back-of-the-envelope capacity estimates

    Metric                      Single-node math and capacity implication
    --------------------------  -----------------------------------------------------------------------
    Concurrent connections      10,000 open TCP sockets (raise OS file-descriptor ulimit above 1,024)
    Rooms & message rate        2,000 rooms; avg 1 msg per user every 120s -> ~83 msg/s in normal rooms
                                + 1 hot room (2,000 online, 10 msg/s) -> ~93 msg/s total
    Fan-out deliveries          Normal rooms: 83 msg/s x ~25 online = ~2,100 socket writes/s
                                Hot room:     10 msg/s x 2,000 online = 20,000 socket writes/s
                                Total = ~22,100 non-blocking writes/s (~0.2 core on 1 Python event loop)
    Disk growth                 93 msg/s x 86,400 s x ~160 B/row = ~1.29 GB/day (~470 GB/year)
    Durable commit rate         10 ms group-commit batching -> <= 100 fsyncs/s (easy on local NVMe SSD)
    Memory footprint            ~4 KB state + 64 KB max send buffer/socket -> ~50 MB typical, 640 MB cap
                                Room history cache: 2,000 rooms x 10 lines x ~100 B = ~2 MB RAM
    Post-restart login storm    10,000 /login calls over 30s = ~333 logins/s -> SHA-256 on 128-bit key
                                takes < 1 us each (< 0.4 ms/s CPU), whereas 50 ms password hashes would
                                burn ~17 CPU cores!
    

    Three concrete takeaways shape the single-node design:

    • One hot room dominates fan-out (90% of all socket writes): format each outgoing message into UTF-8 bytes once and pass that shared immutable bytes buffer to all 2,000 sockets.
    • Unbounded send buffers are the #1 out-of-memory threat: one stalled terminal in the hot room accumulates 10 msg/s x 100 B = 1 KB/s forever; thousands of stalled sockets would exhaust RAM unless every socket's send buffer is strictly capped.
    • High-entropy random keys beat human passwords on reconnect storms: because a server-generated 128-bit key has 2^128 possibilities, a fast SHA-256 hash is unguessable and survives 10,000 simultaneous reconnects effortlessly.
  3. Wire protocol and defensive TCP byte-stream framing

    A sample interactive session over telnet (in production, expose TLS on port 4443 via openssl s_client alongside plaintext 4000 for local testing):

    $ telnet chat.example.com 4000
    * Welcome! Use /nick <name> to register, /login <name> <key> to reconnect, /help for commands.
    /nick alice
    * Registered as alice. Save your resume key: 3f9c2a7e5b1d4c8e9a0f6b2d7c1e5a93
    /create general
    * Created and joined #general (active).
    hello everyone!
    [#general 14:02] alice: hello everyone!
    [#general 14:02] bob: welcome alice!
    /users
    * #general online (2): alice, bob
    /quit
    * Goodbye.
    

    Supported commands and distinct server line prefixes:

    Client command               Behavior
    ---------------------------  --------------------------------------------------------------------
    /help                        Print command summary
    /nick <name>                 Unauthenticated: register <name> & issue key; Logged in: rename user
    /login <name> <key>          Authenticate, rejoin saved rooms, print active history + unread counts
    /create <room>               Create room, join it, and set it as active room
    /join <room>                 Join (if not a member), set active room, print last 10 messages
    /leave [room]                Remove persistent membership from active or named room
    /rooms                       List rooms with online and total member counts
    /users [all]                 List online users in active room (or up to 100 globally + total)
    /quit                        Gracefully close socket (memberships stay saved)
    <plain text>                 Post chat message to caller's active room
    
    Server output prefix         Meaning
    ---------------------------  --------------------------------------------------------------------
    [#room HH:MM] author: text   Broadcast chat message
    * text                       Informational server notice
    ! ERR <code>: explanation    Machine- and human-readable error
    

    Five raw-TCP framing traps we must guard against:

    1. TCP is a byte stream, not a line stream: one read() call can return half a word or three commands glued together. Buffer incoming bytes until \n and strip optional \r (telnet sends \r\n; nc sends \n).
    2. Telnet IAC (0xFF) option bytes: PuTTY in Telnet mode sends binary RFC 854 negotiation packets like 255 251 31 (IAC WILL NAWS) or 255 250 ... 255 240 (IAC SB ... IAC SE), which can even contain byte 10 (\n, e.g., a 10-row window height!). Strip Telnet IAC sequences on the raw byte stream before splitting on \n. Byte 255 never appears in valid UTF-8, so real text is untouched.
    3. Over-long lines without newlines: cap lines at 2,000 bytes; if a client sends 10 MB without \n, enter a discarding state that drops incoming bytes until the next \n so server RAM stays bounded.
    4. Terminal escape injection: strip ASCII control characters and ANSI escape sequences (ESC[2J would wipe every recipient's terminal; bare \r would overwrite [#general] bob: to spoof another user!).
    5. Per-user flood protection: apply a token bucket rate limiter (5 messages per 5 seconds per user) to block chat floods.
    import re
    
    MAX_LINE_BYTES = 2000
    # Strip ANSI CSI sequences (ESC [ ...) plus C0/C1 terminal control characters.
    UNSAFE_CHARS_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|[\x00-\x08\x0b-\x1f\x7f-\x9f]")
    
    
    def consume_telnet_iac(buf):
        """Strip complete Telnet IAC (255) sequences; return (clean_bytes, partial_tail)."""
        clean_bytes = bytearray()
        i = 0
        n = len(buf)
        while i < n:
            if buf[i] != 255:
                clean_bytes.append(buf[i])
                i += 1
            elif i + 1 >= n:
                # Trailing 255 at chunk boundary; wait for next socket read.
                break
            elif buf[i + 1] == 255:
                clean_bytes.append(255)
                i += 2
            elif buf[i + 1] in (251, 252, 253, 254):
                # 3-byte IAC WILL/WONT/DO/DONT <option>.
                if i + 2 >= n:
                    break
                i += 3
            elif buf[i + 1] == 250:
                # Subnegotiation: IAC SB (255, 250) ... IAC SE (255, 240).
                end = buf.find(bytes([255, 240]), i + 2)
                if end == -1:
                    if n - i > 256:
                        i = n  # Drop malformed oversized subnegotiation.
                    break
                i = end + 2
            else:
                i += 2
        return bytes(clean_bytes), buf[i:]
    
    
    def sanitize_line(raw_line):
        text = raw_line.decode("utf-8", errors="replace")
        return UNSAFE_CHARS_RE.sub("", text).strip()
    
    
    async def read_client_lines(reader, session, server):
        raw_tail = b""
        line_buf = b""
        discarding_overlong = False
    
        while not session.closed:
            chunk = await reader.read(4096)
            if not chunk:
                return  # Peer closed TCP connection cleanly (EOF).
            cleaned, raw_tail = consume_telnet_iac(raw_tail + chunk)
            line_buf += cleaned
    
            while b"\n" in line_buf and not session.closed:
                raw_line, line_buf = line_buf.split(b"\n", 1)
                if discarding_overlong:
                    discarding_overlong = False
                elif len(raw_line) > MAX_LINE_BYTES:
                    session.send_error("line_too_long", "Max 2000 bytes per line")
                else:
                    server.handle_line(session, sanitize_line(raw_line))
    
            if len(line_buf) > MAX_LINE_BYTES:
                if not discarding_overlong:
                    session.send_error("line_too_long", "Max 2000 bytes per line")
                line_buf = b""
                discarding_overlong = True
    
  4. Relational data model for rooms, memberships, and history

    Four tables capture all durable state. On one host, SQLite in WAL mode (Write-Ahead Logging: appending writes sequentially to a log file so concurrent reads and writes do not block each other) handles the load easily; the exact same schema runs on PostgreSQL.

    CREATE TABLE users (
      user_id      INTEGER PRIMARY KEY,
      name         TEXT NOT NULL UNIQUE,           -- normalized lowercase [a-z0-9_-]{2,20}
      key_hash     BLOB NOT NULL,                  -- SHA-256 digest of 128-bit resume key
      active_room  INTEGER REFERENCES rooms(room_id),
      created_at   INTEGER NOT NULL,
      last_seen_at INTEGER
    );
    
    CREATE TABLE rooms (
      room_id      INTEGER PRIMARY KEY,
      name         TEXT NOT NULL UNIQUE,
      owner_epoch  INTEGER NOT NULL DEFAULT 1,     -- fencing epoch used in multi-host failover
      created_by   INTEGER NOT NULL REFERENCES users(user_id),
      created_at   INTEGER NOT NULL
    );
    
    CREATE TABLE memberships (
      user_id       INTEGER NOT NULL REFERENCES users(user_id),
      room_id       INTEGER NOT NULL REFERENCES rooms(room_id),
      joined_at     INTEGER NOT NULL,
      last_seen_seq INTEGER NOT NULL DEFAULT 0,    -- powers unread counts on /login
      PRIMARY KEY (user_id, room_id)
    );
    
    CREATE TABLE messages (
      room_id     INTEGER NOT NULL REFERENCES rooms(room_id),
      seq         INTEGER NOT NULL,                -- 1, 2, 3... strictly monotonic per room
      user_id     INTEGER NOT NULL REFERENCES users(user_id),
      author      TEXT NOT NULL,                   -- snapshot of sender's name at send time
      body        TEXT NOT NULL,
      created_at  INTEGER NOT NULL,
      PRIMARY KEY (room_id, seq)
    );
    

    Why each schema detail matters:

    • Per-room seq (PRIMARY KEY (room_id, seq)) instead of a global message_id: defines a gap-detectable total order per room, makes WHERE room_id = ? ORDER BY seq DESC LIMIT 10 read exactly 10 contiguous B-tree entries even in a 50-million-message room, and makes unread counts pure subtraction (room.latest_seq - last_seen_seq).
    • Lazy last_seen_seq flushing: updating memberships on every delivered line would turn 93 msg/s into 22,100 DB writes/s! Instead, keep last_seen_seq in memory per session and flush dirty markers on disconnect and every 60 seconds in small 500-row batches.
  5. Single-node architecture: event loop plus group-commit writer

       telnet / PuTTY / nc clients
                  |  TCP :4000 (and TLS :4443)
                  v
     +----------------------------- Chat Server Process ------------------------------+
     |  SINGLE EVENT-LOOP THREAD (owns all in-memory state; zero mutex locks!)        |
     |                                                                                |
     |  TCP Acceptor ---> Session (1 per open socket)                                 |
     |                      - read_client_lines() -> command & message router         |
     |                      - send_bytes(): non-blocking; drops socket if > 64 KB     |
     |                                                                                |
     |  In-Memory Registry                                                            |
     |    - sessions_by_user: dict[user_id, Session]                                  |
     |    - rooms: dict[room_id, Room(next_seq, online=set[Session],                  |
     |                                recent=deque(maxlen=10))]                       |
     |                                                                                |
     |         | submit(sql, params, on_commit, on_error)    ^ call_soon_threadsafe   |
     |         v                                             |   (FIFO order)         |
     |  STORE WRITER THREAD: drains up to 10 ms / 500 ops -> 1 transaction -> 1 fsync |
     +-----------------------------------|--------------------------------------------+
                                         v
                            SQLite (WAL, synchronous=FULL) / PostgreSQL
    
  6. Deep dive 1: Lock-free concurrency, backpressure, and atomic joins

    An event loop runs a single OS thread over non-blocking sockets (epoll on Linux, kqueue on macOS), stepping whichever socket is ready without thread context switches or shared-memory locks. By keeping all room sets, user maps, and recent history deques solely on the event-loop thread—and offloading blocking disk fsync calls to the single Store Writer thread—race conditions and lock-ordering deadlocks disappear by construction.

    Contrast this with spawning 10,000 OS threads guarded by per-room mutexes: if Thread A acquires #general's lock to broadcast a line and calls a blocking socket.send() on a user whose Wi-Fi just stalled, everyone in #general freezes behind that one slow socket.

    We enforce three strict single-node invariants:

    1. Backpressure via bounded send buffers: backpressure occurs when outgoing messages arrive faster than a slow client reads them from TCP. Session.send_bytes checks the transport's queued bytes; if a client lags past 64 KB (~600 chat lines, over a minute behind even in the 10-msg/s hot room), we immediately abort that socket rather than stalling others or silently dropping lines:
    MAX_SEND_BUFFER_BYTES = 64 * 1024
    
    
    class Session:
        def __init__(self, writer):
            self.writer = writer
            self.user_id = None
            self.name = None
            self.active_room = None
            self.closed = False
    
        def send_bytes(self, payload):
            """Queue pre-encoded UTF-8 bytes without blocking; drop stalled readers."""
            if self.closed:
                return
            if self.writer.transport.get_write_buffer_size() > MAX_SEND_BUFFER_BYTES:
                self.close(abort=True)  # Drop kernel/user buffer immediately; client can /login.
                return
            self.writer.write(payload)
    
        def close(self, abort=False):
            if self.closed:
                return
            self.closed = True
            if abort:
                self.writer.transport.abort()
            else:
                self.writer.close()
    
    1. Total order per room: room.next_seq is incremented synchronously on the event loop, the Store Writer commits batches in FIFO submission order, and call_soon_threadsafe fires on_message_committed in that exact seq order.
    2. Zero-gap, zero-duplicate /join: when Bob joins #general, join_room adds Bob to room.online and sends room.recent (deque(maxlen=10), preloaded for all 2,000 rooms at startup) with no await in between. Because both join_room and on_message_committed execute synchronously on the single event-loop thread without yielding, every message executes strictly before join_room (so Bob gets it once in room.recent) or strictly after join_room (so Bob gets it once via live room.online broadcast)—never twice and never missed!
    def on_message_committed(room, formatted_bytes):
        """Runs on the event loop strictly in seq order after disk commit."""
        room.recent.append(formatted_bytes)
        # Copy room.online with list() in case send_bytes() closes a stalled session!
        for member_session in list(room.online):
            member_session.send_bytes(formatted_bytes)
    
    
    def join_room_on_loop(session, room, replay_history=True):
        """Add session to room and replay last 10 messages atomically (no await!)."""
        room.online.add(session)
        session.active_room = room
        if replay_history:
            for historical_line in room.recent:
                session.send_bytes(historical_line)
    
  7. Deep dive 2: Reconnection identity, session takeover, and dead sockets

    Why name + 128-bit server-issued resume key wins for raw TCP:

    Approach                     Why it fails or wins
    ---------------------------  -----------------------------------------------------------------
    Client IP address            Breaks across Wi-Fi/cellular switches; collides behind shared NAT
    Nickname alone               Anyone can type /nick alice and hijack Alice's rooms
    Nickname + human password    Humans pick weak reused passwords -> requires slow Argon2/scrypt
                                 hashing (~50 ms CPU), burning ~17 cores during a 10k login storm
    Nickname + 128-bit key       Server generates 32 random hex chars; unguessable, fast SHA-256
      (chosen)                   verification, and /rekey rotates it if compromised
    

    Exact /login alice <key> flow:

    1. Compute SHA-256(key) and compare against users.key_hash with constant-time hmac.compare_digest.
    2. On failure, return ! ERR bad_login: invalid credentials and rate-limit failures by client IP (5/min), never per username—otherwise an attacker could lock Alice out of her own account by spamming wrong keys for alice!
    3. Newest login wins (ghost-session takeover): if sessions_by_user[alice] already holds an older socket (for example, Alice closed her laptop lid and TCP hasn't timed out yet), send * Logged in from another location on the old socket and close it so Alice is never locked out by her own zombie connection.
    4. Re-add Alice's new session to room.online for every row in memberships, restore active_room, replay its room.recent (last 10 lines), and print unread counts (room.latest_seq - last_seen_seq) for her other rooms.

    Detecting silently vanished TCP peers: if a router loses power, no FIN or RST packet ever arrives, and default Linux TCP waits 2 hours (7,200s) on idle sockets or ~15 minutes (tcp_retries2) when unacknowledged broadcast bytes sit in flight. Configure every accepted socket with both SO_KEEPALIVE (TCP_KEEPIDLE=60, TCP_KEEPINTVL=10, TCP_KEEPCNT=3 for idle connections) and TCP_USER_TIMEOUT=90000 (90s timeout on unacknowledged writes). Within ~90 seconds of a cable pull, the OS fails the socket, we remove the session from room.online and flush last_seen_seq, and all memberships remain safely stored.

  8. Deep dive 3: Crash-safe durability ("visible implies durable") and group commit

    If we broadcast a chat line before committing it to disk, a power loss 5 ms later erases messages users already read and replied to. Instead, every message and state-changing command replies/broadcasts only inside its post-commit callback.

    To make synchronous=FULL durable commits fast without blocking the event loop, the Store Writer thread uses group commit: it collects all SQL operations submitted within a 10 ms window (up to 500 ops) into a single transaction and a single disk fsync, wrapping each operation in a SQL SAVEPOINT so one user's constraint error never aborts 499 other users' chat messages in the same batch:

    import functools
    import queue
    import sqlite3
    import time
    
    
    class DurableStore:
        """Dedicated SQLite WAL writer thread using 10 ms group commit."""
    
        def __init__(self, db_path, loop):
            self.db = sqlite3.connect(db_path, isolation_level=None, check_same_thread=False)
            self.db.execute("PRAGMA journal_mode=WAL")
            self.db.execute("PRAGMA synchronous=FULL")
            self.loop = loop
            self.work_queue = queue.Queue()
    
        def submit(self, sql, params, on_commit, on_error):
            self.work_queue.put((sql, params, on_commit, on_error))
    
        def run_forever(self):
            while True:
                batch = [self.work_queue.get()]
                deadline = time.monotonic() + 0.010
                while len(batch) < 500 and time.monotonic() < deadline:
                    remaining = max(0.0, deadline - time.monotonic())
                    try:
                        batch.append(self.work_queue.get(timeout=remaining))
                    except queue.Empty:
                        break
    
                outcomes = []
                try:
                    self.db.execute("BEGIN")
                    for idx, (sql, params, on_commit, on_error) in enumerate(batch):
                        try:
                            # SAVEPOINT isolates one bad statement from the rest of the batch.
                            self.db.execute(f"SAVEPOINT sp_{idx}")
                            self.db.execute(sql, params)
                            self.db.execute(f"RELEASE sp_{idx}")
                            outcomes.append((on_commit, None))
                        except sqlite3.Error as err:
                            self.db.execute(f"ROLLBACK TO sp_{idx}")
                            self.db.execute(f"RELEASE sp_{idx}")
                            outcomes.append((None, (on_error, err)))
                    self.db.execute("COMMIT")
                except sqlite3.Error as batch_err:
                    # Disk full / I/O failure: nothing committed, notify all senders!
                    self.db.execute("ROLLBACK")
                    outcomes = [(None, (op[3], batch_err)) for op in batch]
    
                for on_commit, err_pair in outcomes:
                    if on_commit is not None:
                        self.loop.call_soon_threadsafe(on_commit)
                    elif err_pair is not None and err_pair[0] is not None:
                        on_err_fn, err_obj = err_pair
                        self.loop.call_soon_threadsafe(functools.partial(on_err_fn, err_obj))
    

    On graceful shutdown (SIGTERM), stop accepting sockets, broadcast * Server restarting—reconnect shortly with /login, drain work_queue, flush last_seen_seq, and exit cleanly. After an unexpected crash, SQLite/PostgreSQL replays its WAL automatically; every message ever displayed on any screen is intact.

  9. Scaling beyond one process and one host

    When connection counts or hot-room fan-out outgrow one CPU core and one machine, split connection holding (TCP Gateways) from ordering and persistence (Sharded Room Owners):

     Clients --TCP--> [ L4 TCP Load Balancer ]
                       |              |              |
                  [Gateway 1]    [Gateway 2] .. [Gateway N]
                   Holds TCP sockets, Telnet parsing, /login, local room fan-out
                       | RPC: post(room_id, msg)     ^ Pub/Sub: {room_id, seq, bytes}
                       v                             |
                  [Room Owner Shards: hash(room_id) -> active owner via etcd lease]
                   Single writer per room: assigns seq, checks epoch, group-commits
                       |                             |
                       v                             v
             [Partitioned Message Store]      [Pub/Sub Bus (NATS / Redis)]
              Keyed by (room_id, time_bucket)  + [Presence Store (TTL 60s)]
    
    1. Hierarchical fan-out cuts cross-network bandwidth: when Alice posts in a 2,000-user room spread across 10 Gateways, the Room Owner publishes the message once per subscribed Gateway (10 network hops, not 2,000), and each Gateway fans the bytes out to its local sockets.
    2. Race-free distributed /join using seq: because history RPCs and Pub/Sub messages travel over separate network paths, a Gateway handles /join by (a) subscribing to #room's Pub/Sub topic first and buffering incoming live messages for that session, (b) fetching the last 10 durable messages up to highest seq = H, (c) sending those 10 lines followed by any buffered live messages with seq > H, and (d) tracking last_sent_seq to deduplicate overlaps or fetch missing seq gaps from the store if Pub/Sub drops a packet.
    3. Split-brain fencing via owner_epoch: each etcd lease grant increments a lease epoch (a monotonically increasing term number). Before serving a room, the new Room Owner sets UPDATE rooms SET owner_epoch = :my_epoch WHERE room_id = :r AND owner_epoch < :my_epoch, and every message batch checks owner_epoch = :my_epoch. Without owner_epoch, a GC-paused old owner could insert seq = 101 before the new owner writes anything, causing the new owner's seq = 101 insert to fail PRIMARY KEY (room_id, seq)!
    4. Storage at massive scale: partition messages by (room_id, time_bucket) (for example, 10-day buckets) in a wide-column store—matching Discord's publicly documented Cassandra and ScyllaDB message architecture—so hot rooms never create unbounded partitions while "last 10 messages" reads only the newest bucket. Keep users, rooms, and memberships in PostgreSQL.
  10. Failure handling and trade-off summary

    Failure scenario                     System response
    -----------------------------------  ---------------------------------------------------------------
    Client pauses terminal (Ctrl-S)      Socket send buffer hits 64 KB -> connection aborted; room safe
    Laptop lid closed / Wi-Fi lost       SO_KEEPALIVE / TCP_USER_TIMEOUT cleans up in ~90s; early /login
                                         immediately closes the ghost socket and restores rooms
    Oversized line / ANSI escape attack  Capped at 2,000 B with stream discard; IAC & escapes stripped
    Disk full / DB write error           Batch rolls back before broadcast; sender gets ! ERR not_saved
    Gateway node crash (multi-host)      Clients reconnect via L4 LB to surviving Gateways and /login
    Room Owner crash (multi-host)        etcd lease expires (~10s); new owner bumps owner_epoch, reads
                                         MAX(seq), and resumes while fencing out any paused old owner
    Pub/Sub drops a message              Gateway spots seq jump (or periodic heartbeat lag) and backfills
                                         missing (room_id, seq) range directly from the message store
    

    Core trade-offs summarized:

    • Single event loop + writer thread vs. thread-per-socket with locks: eliminates mutex deadlocks and slow-socket lock convoys, trading away multi-core execution within one process until horizontally sharded.
    • Persist-then-broadcast vs. broadcast-then-persist: adds ~5–15 ms of group-commit latency (imperceptible in human chat) in exchange for strict crash consistency (visible implies durable).
    • Drop slow readers at 64 KB vs. block or drop individual lines: bounds server RAM and never hides silent message gaps; /login makes catching up trivial.
    • Single writer per room (seq + owner_epoch): caps one room at thousands of durable messages/s (far above human typing/reading speed) in exchange for strict total order, O(1) 10-message tail reads, and trivial gap detection.

Intuition & how it works

Think of the chat server like a live courtroom stenographer sitting in front of a room of listeners wearing headphones. When Alice speaks, she hands her note to the stenographer, who stamps the next sequential line number (seq) for that room, writes it into a permanent bound ledger on disk, and only then reads that exact stamped line into everyone's headphones—while immediately unplugging any listener whose headphone queue backs up past a fixed limit so one broken headset never freezes the room.

A naive server spawns one thread per TCP connection, calls socket.recv() assuming one call equals one chat line, grabs a room lock to loop over socket.send() for every member, and writes to the database asynchronously in the background. That design fails under real network conditions: TCP delivers arbitrary byte fragments (half a command or three lines together), one user on stalled Wi-Fi blocks socket.send() while holding the room lock and freezes everyone in the room, identifying users by IP or nickname fails or allows impersonation on reconnect, and a server crash erases messages people already read on screen before the background database write finished.

Follow a concrete 4-step trace of Alice and Bob on a single node:

  1. Registration (/nick alice): the server normalizes "alice", generates a 128-bit random resume key 3f9c..., commits SHA-256(key) to users via the writer thread, and prints the key once so Alice can later /login alice 3f9c... from any new TCP socket.
  2. Posting (hello in #general): the single event loop (one non-blocking I/O thread owning all in-memory room state without locks) assigns seq = 41, encodes b"[#general 14:02] alice: hello\r\n" once, and queues the SQL INSERT to the writer thread.
  3. Group commit & broadcast: the writer thread batches all writes arriving within 10 ms into one WAL (Write-Ahead Log: a sequential append-only recovery log) transaction and one disk fsync, then schedules on_message_committed back on the event loop in seq order—appending seq = 41 to #general's 10-line memory deque and writing the shared bytes into every online member's non-blocking socket buffer.
  4. Joining (/join general by Bob): on the same event loop with no await in between, Bob is added to #general.online and sent the 10-line deque, guaranteeing he receives seq = 41 either in history or live—never twice and never missed.

Key trade-offs

  • Single-threaded event loop + dedicated DB writer vs. thread-per-connection with mutexes. Owning all room sets and history caches on one event-loop thread eliminates race conditions, lock-ordering deadlocks, and the classic bug of holding a room mutex across a slow socket write. The trade-off is strict non-blocking discipline (never run disk I/O or CPU-heavy work on the loop) and scaling past one CPU core via multi-process gateways and room shards.
  • Persist-then-broadcast vs. broadcast-then-persist. Waiting for the group commit (batching up to 10 ms of SQL writes into a single disk fsync) adds ~5–15 ms before a message appears, which humans in a terminal cannot perceive, while guaranteeing visible implies durable so crashes never erase displayed chat history.
  • Disconnecting slow clients at 64 KB vs. blocking senders or silently dropping lines. Enforcing backpressure (protecting memory when a producer outpaces a slow consumer) by aborting sockets whose outbound buffer exceeds 64 KB bounds server RAM to <= 640 MB at 10,000 connections and keeps rooms fast. Blocking stalls innocent users, and dropping individual lines leaves silent holes in a user's conversation; disconnecting is explicit and cleanly recovered via /login.
  • 128-bit random resume key vs. human password vs. nickname-only. A server-issued 128-bit random key has enough entropy that a fast SHA-256 check (< 1 microsecond) is safe against guessing, letting 10,000 users reconnect in seconds without burning 16+ CPU cores on slow password hashes like Argon2—trading user convenience (saving the printed key) for speed and security.
  • Single writer per room (seq + owner_epoch) vs. multi-writer timestamps. Funneling each room through one owner shard that assigns 1, 2, 3... gives exact total ordering, O(1) 10-row tail queries, and gap detection when scaling across hosts, fenced by a lease epoch (an incrementing ownership term number checked on every write so a paused old owner cannot write stale messages). One owner caps a single room at thousands of messages/s, which is orders of magnitude above readable human chat.
  • Lazy last_seen_seq flushing vs. per-delivery read receipts. Flushing per-user read markers every 60 seconds and on disconnect avoids multiplying 93 msg/s into 22,100 DB writes/s, at the minor cost that unread counts after a sudden crash may overcount by up to 60 seconds of messages.

Common mistakes

  • Assuming socket.recv(4096) returns one complete line, forgetting that TCP is an unstructured byte stream that splits and merges lines arbitrarily across packets.
  • Buffering until \n with no maximum line length, allowing one malicious client sending gigabytes without a newline to trigger an out-of-memory crash.
  • Splitting on \n before stripping Telnet IAC (0xFF) option bytes, or allowing raw ANSI escape codes, which breaks when PuTTY sends binary window-size bytes containing 0x0A (\n) and lets pranksters send ESC[2J or \r to wipe terminals or spoof sender names.
  • Performing blocking socket writes or disk fsync calls directly inside the room broadcast path, letting one frozen TCP client or slow disk sync stall every room on the server.
  • Deleting memberships on TCP disconnect or storing online presence in the database, which either breaks "rejoin previous rooms on reconnect" or leaves ghost "online" users stranded forever after a server crash.
  • Fetching the last 10 messages from disk and subscribing to live room broadcasts across an await without sequence-number reconciliation, creating a race window that drops or duplicates messages sent during /join.
  • Relying on default OS TCP timeouts, where a silently unplugged laptop stays "online" for 2 hours unless SO_KEEPALIVE and TCP_USER_TIMEOUT (~90s) are enabled—and locking that user out if a new /login doesn't close their stale ghost session.

Follow-up questions

  • How would you guarantee a reconnecting user misses zero messages, rather than only seeing the last 10? Use each membership's last_seen_seq to query WHERE room_id = ? AND seq > ? ORDER BY seq ASC LIMIT 200 on /login, printing a prompt like * 340 more unread—type /more #general if a room had heavy traffic while offline. Because bytes written to the OS kernel socket buffer may not have reached the user's screen before a sudden Wi-Fi drop, advance last_seen_seq conservatively (or replay a small overlap such as the 5 messages prior to last_seen_seq), since seeing a few context lines again is much friendlier than missing a message. If strict exactly-once replay is ever required, add an optional machine protocol mode where clients send explicit ACK <room> <seq> lines.
  • How would you support direct messages (1-on-1 private chats) cleanly in this architecture? Represent a direct-message conversation between users u1 and u2 as an ordinary rooms row with a canonical private name such as dm:<min_id>:<max_id> and a kind = 'dm' column that hides it from /rooms and blocks unauthorized /join calls. Add /msg <username> <text> as protocol shorthand that auto-creates the DM room and both memberships on first message, then reuses the exact same per-room seq, group-commit persistence, 10-message history cache, unread counters, and multi-host sharding unchanged.
  • How would you let automated bots or a rich GUI client connect alongside human telnet users? Support an opt-in framing upgrade command /proto json as a connection's first line, switching that session's serializer from human prefixes ([#general 14:02] alice: hi) to newline-delimited JSON events ({"type":"msg","room":"general","seq":41,"author":"alice","ts":1767225600,"body":"hi"}) with client req_id correlation on command replies and explicit ack support. Keep internal room events structured until serialization (encoding at most once per output format—once for text clients and once for JSON clients per room broadcast) so human telnet users and bots share the exact same server core with near-zero extra CPU overhead.

Follow-up questions

Similar questions

More Discord interview questions

All 15 Discord questions →