Lesson 4 · Minutes 30-45

Chat: Deep Dives and Curveballs

Problem

Presence and the large group have waited long enough, and both get their turn in the last fifteen minutes. First the round goes under the design: how connections are found and held, and what each crash does between a send and a tick. Then come groups up to the thousand you agreed, and four curveballs, with presence last, once it has a price.

Holding and Finding Connections

There are three ways to find a connection. A registry with direct calls is your choice so far. A pub-sub channel per user makes routing free, since the sender publishes and the right gateway is already subscribed, and the broker carries 20 million subscriptions that change with every connect. A broadcast sends each of the 72,000 deliveries to all 200 gateways, over 14 million messages a second, nearly all thrown away.

Connection Registry vs Channel per User

A registry answers "where is this device" with one lookup, and costs a small store and a moment of staleness. Use it while deliveries are few per connection, which is most chat.

A channel per user lets a broker do the routing, for a subscription per connection that changes on every reconnect. Use it when the broker is already in the design and the connection count is well inside its limits.

Holding is the other half. A deploy cannot simply kill 100,000 sockets, so it drains a gateway by telling its clients to reconnect over minutes. Assume five minutes a gateway, one at a time, and the 200 take about 17 hours. That number is the real argument for keeping business logic out of them.

A proxy on the route that kills idle connections is why the heartbeat is shorter than its timeout. How a connection works inside is the subject of Networking Deep Dive, in its lesson on WebSockets and Server-Sent Events.

From Send to Tick, With the Crashes In

Take one message through it. The message is written, and the ack carries its number. That is the sent tick.

Crash before the ack, and the client cannot know whether the write landed. It retries with its own ID and gets the same number. The owner can answer because it keeps the recent IDs of each active conversation beside its counter, and a new owner reads them back from the newest rows, and again after any write it loses. A phone away for longer catches up first, finds its own ID in the history, and drops the retry.

Crash after the write and before delivery, and nothing would push until the next message, which in a quiet conversation may be tomorrow. So delivery stops being a step of the send. The message service reads a log fed from the store's own writes, the outbox idea of Chapter 5's Transactions Across Partitions, and the log delivers at least once, the promise of Chapter 6's Delivery Semantics at Scale. The row itself is what gets published, so there is no second row to count.

This is a log and not a queue because a repeat is harmless. A phone drops it by number, and a member's row keeps the higher number, so one saved offset per partition is enough. Partitions keyed by conversation keep each conversation's messages in order. At 24,000 messages of 300 bytes, it carries about 7 MB a second at peak, small beside the 600 MB a second one vendor reports for three brokers.

That adds one box to the final board, between the store and the message service, and one hop inside the agreed second. If the log stalls, sends still succeed and stay safe. Live delivery and the member rows wait, so a returning device's list looks unchanged until the log recovers, while a history read still finds every message. When it returns, the readers pick up at their offsets.

The delivered tick is the member's high-water mark. Each device reports the highest number it holds, the row's delivered mark keeps the highest it has seen, and the sender's phone hears over its own socket. A report lost to a crash is covered by the next one. No failure here needs a transaction across services, because the number and the client-made ID answer all of them.

Groups, Up to the Agreed Thousand

The groups you parked in First Design come back here. One message to 1,000 members is 1,000 member-row writes. About 250 of those members are online, at the day's ratio of one in four, which makes about 500 pushes.

Every member's row takes a write here, just as every follower's list does in Chapter 17's News Feed. The difference is what gets written. That list takes an entry per post, built ahead for a reader who may be away. This row is overwritten with one number, the message is stored once, and the live fan-out goes only to devices connected right now.

Ticks reach the sender in the same batches, so a group of 1,000 sends a rollup every few seconds and not 1,000 separate marks. A joiner's row starts at the number at which they joined, and their reads start there. A leaver's row is deleted and the cached member list dropped at once, so pushes stop within a moment and a history read, which checks the row, is refused. Presence waits for the curveball, where its cost shows.

Curveballs

"Now support groups of a hundred thousand." Say what stops working first: 100,000 member-row writes per send. Above the agreed 1,000, change the mode. The group's own row alone holds the last number, and a member's list merges their large groups at read.

Live delivery goes per gateway. At the same one in four, 25,000 members are online, which is 50,000 connections, about 250 on each gateway. So one publish reaches 200 gateways, and each gateway pushes to its own 250, from a list of which connections are in the group that it rebuilds as devices connect. Drop delivered ticks and alerts, since 75,000 members away per message have no row being written to hold the time, and restrict who may post, because one partition's 1,000 writes a second now matters, and ten messages a second would already be 500,000 pushes.

"Add end-to-end encryption, so the server cannot read anything." The design survives, because the owner numbers envelopes and never reads a body. Search and link previews move to the device. A new device needs a key from an old one to read history.

A body is encrypted per device, or once with a key each sender hands to every device in the group: the Sender Keys of the Signal protocol, which Signal and WhatsApp both use. Per device, a group of 1,000 at two devices each is 2,000 copies of 300 bytes, 600 KB for one message, so a group takes Sender Keys. What it costs: when a member leaves, every sender starts over and hands a new key to every device. The server still sees who, when and how much, and you say so before anyone asks.

"A gateway dies holding a hundred thousand connections." Nothing acknowledged is lost, only pushes in flight. The load balancer's health check takes it out of rotation. The clients see their sockets drop and reconnect with jitter, a random delay that spreads them out. Over 30 seconds, that is 3,300 a second. The other 199 gateways take about 500 each, which running at half the limit allows. Each device re-registers and catches up by number.

Scale that to a zone, a third of the fleet. Now 6.7 million reconnects over the same 30 seconds would be 222,000 a second, more than the registry's three nodes have left above their 140,000. Assume five minutes of jitter instead: about 22,000 a second, at the cost of a device waiting up to that long for its socket. The surviving gateways end up holding 150,000 each, still under the assumed 200,000. The catch-up reads are what you watch: at least 22,000 list reads a second, and the jitter window is the dial that protects the stores.

"Show presence for five hundred friends." This is the presence you parked. Pushing every change is the trap. Assume 10 changes a user a day, and forty million users make 400 million changes. Sent to 500 friends each, that is 200 billion a day, or 2 million a second, far more than the messages.

Read it instead, and only for what is on screen. Assume one online user in twenty has a list open, reading 20 contacts every 30 seconds. That is 500,000 users and about 333,000 simple reads a second, pipelined, about one node at half of 1 million.

Presence pushed against presence read
Pushed40 million users, 10 changes a day, 500 friends
About 2 million a second, around the clock, for people who are mostly not looking.
Read1 online user in 20, 20 contacts every 30 seconds
About 333,000 reads a second, about one node. 30 seconds old or more.

That node joins the registry, which already knows the answer: a user with an entry is online. A separate key renewed on every 30-second heartbeat would cost 667,000 writes a second, and this costs none. A gateway removes an entry when a heartbeat stops, and the TTL covers a gateway that dies. What it costs: presence up to 30 seconds old after a clean close, over a minute when a phone just goes silent, a few minutes after a gateway's death for someone who never reconnects, and up to five minutes of wrongly offline if a registry node is lost.

How Each Level Answers

A mid-level candidate moves from polling to WebSockets once the polls are counted, and reaches a registry or a pub-sub channel once the second gateway is drawn. They fix the order with a server-assigned number when shown the two phones. They handle offline with a catch-up read, and need a push to get to several devices.

A senior candidate keeps the numbered history as the source of truth from the first design onward, and says the live path may lose a push. They give the owner and its condition, the gap rule and the retry rule without being asked. They size the gateways and the member-row writes, and they treat a gateway's death as an ordinary event.

A staff candidate frames the large group and presence as products with their own rules, and asks who may post and what a tick means there. They plan the loss of a zone as a reconnect storm with a stated jitter, and the deploy as a drain. They ask whether the server may read messages at all before the design hardens, and they say what changing that later would cost.

Interview Pitfalls
  • Using the feed's reasoning, which precomputes for readers who are away. Here the store already has the answer for them.
  • Answering the gateway's death with "the client reconnects", and no word on the rate or what is lost.
  • Pushing presence to everyone because messages are pushed.
What Interviewers Listen For
  • A crash at each step answered with the same two tools, the number and the client-made ID.
  • Presence priced before it is designed.
  • Each curveball taken as a change of mode with a threshold, not a new system.

Knowledge Check

The interviewer now asks for groups of a hundred thousand. What stops working first?

  • The numbering, as one owner has no way to number a group of that size
  • The writes: every send would rewrite a row for each of the 100,000 members
  • The gateways, as 25,000 online members are too many for one gateway to hold
  • The history, as a group that size can no longer fit its messages in the store

End-to-end encryption is added, so the server cannot read a body. What has to move to the device?

  • The numbering, since an owner cannot order a message it is not able to read
  • The retry rule, since a server cannot recognise a client ID inside an envelope
  • The history, since the server is no longer able to keep what it cannot read
  • Search and link previews, since each of those has to read the message body

A gateway dies holding 100,000 connections. What has actually been lost?

  • Pushes in flight, since each device reconnects and catches up by its own number
  • Messages not yet read by its devices, unless a second gateway held a copy of them
  • Every send acknowledged in the 30 seconds before the heartbeat could notice
  • Each device's position, since the gateway held them and reads restart from zero

Why is presence read on demand here, when messages are pushed?

  • A push cannot reach a device unless it holds a socket at the moment of the change
  • A read is fresher, since a pushed change can arrive up to 30 seconds after it happens
  • Pushing every change costs 2 million a second, and reading what is on screen 333,000
  • Presence has to be kept for three years, and a pushed change leaves no row to keep

You got correct