Lesson 2 · Minutes 10-20

Chat: First Design

Problem

Forget the socket for ten minutes. Minutes ten to twenty draw chat as a table and a loop: a send writes a row, and every few seconds each client asks whether any rows are new. It sounds like a stopgap, and it gets the hardest requirements right on the first try.

You draw that, follow one message from a send to another phone's next poll, say what it already gets right, and name where the money goes. Four pushes from the interviewer close the page as its quiz. Answer each one yourself first.

A Table and a Loop

Plain HTTP goes through a load balancer to stateless app servers, and behind them sits one relational database. The messages table is keyed by conversation ID. Each row carries a number the database hands out inside that conversation, from a counter on the conversation's row. A membership table says who is in what, with each member's last number and last time.

The first design
Clientpolls every 3 s Load balancerany server App serversstateless One databasenumbered rows poll or send poll: list, after n send: next number readwrite

One Message, One Poll

A phone sends a POST with the body and a message ID it made itself. Any server opens one transaction. It takes the conversation's next number, say 13. It inserts the message, and it updates the row of each member. The server answers with 13, and the sender's phone shows the sent tick.

Another member's phone polls within three seconds. A poll is the list read from Scope: one request, which reads that user's member rows. The row says this conversation has reached 13, and the phone holds 12, so it reads on with the history call, after 12, and gets the new row. On its next poll it reports the number it now holds, which is the delivered tick. History is the same read, further back.

The send and the poll
POST /conversations/{id}/messages          {"message_id": "m-7f3a", "body": "on my way"}
                                           201 {"number": 13}

GET  /conversations                        every few seconds: last number per conversation
GET  /conversations/{id}/messages?after=12 only where a last number moved

What the Numbered Table Already Gets Right

A message is durable the moment its transaction commits. Every device reads the same numbered rows, so one order and history on several devices come free. A device back from a day away reads from its last number, with nothing special built for it. Groups work the same way, one member row each.

A delivery takes at most the polling interval. That is three seconds here, which misses the agreed second, and you say so rather than wait to be told. At 10,000 users online it is about 3,300 polls a second, and a small team's chat tool ships exactly this.

Order and catch-up carry over to the final design unchanged. What changes later is how a device hears that something moved.

What the Clock Costs

Name four limits and fix none of them yet. Polling's cost follows the people online, not the messages. Delivery is as slow as the interval, and shortening it costs in direct proportion: one second instead of three is three times the polls. One table outgrows one node within a week at full traffic. And one database is one failure.

Hand over the first limit yourself, in about ten seconds: "Polling costs what the people online cost, not what they send. Ten million every three seconds is about 3.3 million requests a second, and about 98 percent find nothing. I'd see the app tier grow while messages stay flat."

The 98 percent is generous to polling. Even if each of the 72,000 deliveries at peak took a poll of its own, that is about 2 percent of 3.3 million. And that sum counts one polling device a user. Both devices online would double it.

Two things go on a shelf by name, and one sentence puts them there: "Groups work the same way up to the thousand we agreed, so presence can wait, and I'll return to both."

Interview Pitfalls
  • Dismissing polling in a sentence, when it gets order and multi-device history right, and those carry over.
  • Drawing a gateway tier before anyone has counted a poll, which leaves the tier with no reason to exist.
  • Numbering messages with one global counter because the table has an auto-increment.
What Interviewers Listen For
  • One message walked from send to row to another phone's next poll.
  • What the numbered table already gets right, said out loud and kept.
  • A first limit given as a request rate that follows the people online.

Knowledge Check

"Ten million users are online and every client polls every three seconds. Talk me through that load, and what you would do about it."

  • "Poll every ten seconds instead, which brings the load down to a million a second."
  • "Hold one open connection per device, and push when a message actually arrives."
  • "Cache the poll responses, so that the empty answers never reach the message table."
  • "Use long polling, so that each request waits up to thirty seconds for a message."

"You have WebSockets now. The sender is on one gateway and the recipient on another, out of two hundred. How does the message get across?"

  • "Hash each user to a fixed gateway, which the sender's server can compute directly."
  • "Broadcast every message to all the gateways, and let the right one recognise it."
  • "Write it to the store, and let each gateway scan for its own users' new messages."
  • "Keep a registry of which gateway holds each device, and send to those gateways."

"Two people in a group hit send at the same moment. One phone shows A then B, and another shows B then A. Why, and what do you change?"

  • "Stamp each message with the sender's clock, and have every phone sort by that."
  • "The conversation's owner numbers every message, and each phone sorts by that."
  • "Give each message a time-ordered 64-bit ID on the server, and sort by that ID."
  • "Send every message in every chat through one global sequence service for order."

"A phone has been off for a day. Then its owner opens a laptop. What does each device do to catch up?"

  • "Hold a queue of undelivered messages per device, and drain it upon reconnecting."
  • "Mark a message delivered once any one device takes it, and send on only the rest."
  • "Each device keeps its own last number per conversation, and reads onward from there."
  • "Have each device download the last day of every conversation when it reconnects."

You got correct