Ch.50: Slack System Design: Catch Up Without Loading Everything
Outline
- 0:00 A returning teammate and an old phone
- 0:40 The proposed architecture
- 1:31 Requirements and workload assumptions
- 2:30 Accepting an ordered message
- 3:58 Compact startup and history on demand
- 5:09 Downloaded does not mean read
- 6:06 Progress within one unread intent
- 6:58 Choosing a message unread
- 7:44 Committing the reset safely
- 9:12 When the click reply disappears
- 10:33 Keeping delayed responses in order
- 11:44 Recovering gaps after reconnect
- 13:09 Scaling connections and hot channels
- 14:15 Permissions and failure policies
- 15:38 Tracing the full design
- 16:29 Protecting the return point
Transcript
0:00 Slack is an app for team conversations and coordination. Work happens in shared channels and direct messages. Nia is returning from vacation to catch up on her team's decisions. Our design problem: hundreds of channels leave Nia waiting behind a spinner. We'll design a team chat backend that prioritizes Nia's conversation, fetches other history as needed, and protects her deliberate unread choice across devices. Her laptop read through 120. She chose 110 unread. The phone brings earlier reading through 125.
0:27 Why shouldn't the larger position win? She left herself a reminder, and her phone is tidying it away. Slack's official help documents Mark unread; source links are in the description. Preserving that behavior is our exercise. First, map the paths to Nia's screen. Authenticated APIs check membership before allowing message actions or access to channel information. Startup batches small channel summaries with personal state. A channel head means its latest committed position. History arrives in limited pages for the conversation she asked to open.
0:57 A write owner assigns positions and durably records each channel's messages in order. PostgreSQL stores the personal reading record. Large bodies and attachments stay off the startup path. A log worker reads committed history, relays a hint through a WebSocket gateway to her device, and updates summaries. Gateways keep the connections; history keeps the message. Right. Losing the connection doesn't lose her conversation. Compact summaries can open her screen while durable history and personal state keep their own jobs. We'll revisit this same map with Nia's choices flowing through it.
1:31 With those paths mapped, what must still work for Nia while the sidebar is incomplete? Functional requirements: Nia can send a message, open an authorized conversation's ordered history, see compact unread indicators, keep reading across devices, leave a reminder deliberately, and recover content after a disconnect. Non-functional requirements say under what conditions. Sending is the job; accepting 95 out of 100 small messages within 500 milliseconds is its timing constraint. Choose that healthy-region target, and 800 milliseconds to open her selected channel.
2:03 Her useful conversation gets a deadline, not every archive. Durable acknowledgments and authorized reads must still hold. For capacity, assume a peak of 100,000 connected clients and 10,000 messages per second. Those are invented assumptions for our design exercise. Those connections motivate separate gateways; those writes need partitioning. Membership stays fixed in the phone race. Search, attachments and richer reading rules for threads or edited messages need separate designs. Before showing a send as successful, consider a message Nia sends.
2:34 The API authenticates her and checks membership before admitting the write. A cached channel card cannot grant permission. For that channel, the owner stores the message at its next ordered position and advances the head in one transaction. That establishes what the summaries describe. When can her screen change from pending to sent if reaching one database machine is insufficient? Our send receipt requires two durable copies: one at the primary and one at its required standby in the home region.
3:03 Like waiting for both stamped copies before issuing a receipt. Confirming only the primary leaves her send pending. That's our choice for channel messages and personal state. PostgreSQL's synchronous mode can wait for that required standby's durable copy. Default asynchronous replication confirms without waiting for that standby acknowledgment. Her send stays pending until the required confirmations arrive. But if the log commits and event delivery fails, does the accepted message disappear from view?
3:30 Recover delivery from the committed log. A worker follows new log entries, saves its delivery position and retries gateway notifications and summary updates. Worker failure delays those hints without deleting history. Nia can fetch the committed message through history while delivery catches up. Retried events may duplicate an earlier notification, so clients reconcile by channel position. Slack's published April 2023 architecture describes channel services routing events through subscribed gateways to clients.
3:55 That is published history, not Slack's current private diagram. Now turn stored history into a small sidebar. Startup pages through membership and batches authorized metadata reads. For each included channel, combine its known committed head with Nia's personal reading record. The sidebar works like a directory: listing the files doesn't require opening them. Its committed head says where history ends; her personal row supplies the reading marker. We can fetch those small records separately from message bodies.
4:22 Okay, her channel list is taking shape, but the chat window is still empty. Do we finish every sidebar page before opening her conversation? No. Prioritize its bounded history request. Nia can read that conversation while later sidebar pages arrive, each with explicit limits on work and response size. Slack's historical lazy-loading article describes avoiding history fetches for every channel, getting unread and mention metadata first, and fetching useful history later. That decision lets Nia open her conversation without waiting for the other archives.
4:52 It supports our loading pattern without supplying our personal-state schema. For our simplified channel, a head beyond the reading marker indicates unread activity. Slack distinguishes that bold conversation from a numbered mention badge. We aren't calculating that badge, and an unavailable head remains unknown. With the sidebar loaded, imagine Nia's phone already holding messages. What qualifies as reading, beyond possessing those bytes? Delivery is a network fact. Reading needs Nia's chosen screen behavior.
5:20 Her phone can hold history through 125 while the reading marker stays at 109. Think of downloaded history as pages she has, and recorded reading as a bookmark. Possessing more pages doesn't move that bookmark. Fetched coverage records which ranges were actually downloaded and reconciled. Gaps still matter; having a later page doesn't fill earlier missing pages. Then the interface needs a fresh view or scroll that qualifies under its chosen reading behavior. A delivery acknowledgment can't stand in for that interaction.
5:50 Slack documents configurable read preferences. Our interface must honor its chosen behavior. The phone waking before Nia doesn't count. Otherwise her phone has done the reading for her and removed the reminder before she's even opened the conversation. Very industrious. Unhelpful. So the phone can fetch her vacation backlog. It still doesn't get to do her reading. For actual reading, my instinct is to keep the greatest position any device reports, so late updates can't move her backward. Where does that rule stop? The reset version.
6:20 It identifies the current unread intent and changes only for an explicit unread action. Ordinary progress carries the version under which reading occurred. So ordinary progress maxes only within its current reset version. For example, Nia reading from 118 through 120 under version 1 moves the marker forward. Store 120 and ignore a late 118 for that same intent. PostgreSQL's row lock serializes competing changes to one personal record through transaction completion; it doesn't lock everybody's reading.
6:49 First check access and reject positions beyond the latest stored message. Inside the personal-row transaction, compare reset versions before accepting that maximum. Now suppose her laptop has reached 120 and she chooses message 110 unread. With our fictional consecutive positions, the marker belongs at 109, immediately before that message. A permanently forward-moving maximum would refuse her request. The messages haven't changed; Nia has deliberately changed where she wants to return. Her phone still carries the old bookmark.
7:17 The laptop's new choice must survive that older view. Could we timestamp the click and keep whichever update is newer? That seems simpler than changing the meaning of forward progress. Receipt time would call the reconnecting phone newest, although its reading happened earlier. A client timestamp also doesn't establish which unread intent that reading belongs to. Then the reset must change the intent version and reading marker together. Otherwise an ordinary update could slip between those changes.
7:44 Next, suppose Nia's explicit unread request carries expected reset version 1 and selected visible message 110. After access and message validation, the personal-row transaction requires version 1, increments it to 2 and writes the marker at 109. It also increments a personal-state revision, a counter that orders personal responses. We'll need it when an older response arrives late. Acknowledge after the required primary and standby durable confirmations. Once accepted, that row rejects the phone's ordinary progress through 125 because it still carries version 1.
8:15 Hold on. What stops the phone from refreshing, replacing version 1 with version 2, and sending that same old progress through 125 again? The client must discard the rejected old-version action. Never relabel and replay it. The original reading happened under the old intent, however fresh the retry looks. Learning the current version updates the phone's knowledge. It doesn't turn an old reading action into a new interaction under Nia's refreshed state. What if the phone's progress arrives before the reset?
8:45 Have we protected the intent only when the network delivers things in our preferred order? If it arrives first, it may advance to 125; the reset then writes 109. After the reset, its old version is rejected. Both leave version 2, position 109. The arrival order changes the intermediate marker, but her accepted choice survives. Nia can advance again through a new qualifying interaction under refreshed state; reconnecting alone doesn't supply one. Her laptop sends that unread click with expected version 1.
9:16 The reply disappears, and the button stays pending. The laptop retries the identical request. The server reports a conflict: the row's reset label is now 2. A request still expecting 1 cannot apply the reset again. We've reached the next version. Can the laptop finally show saved? We know someone changed the intent. Imagine Nia also pressed Mark unread on the phone. That phone request could have won before the laptop request reached the transaction. So version 2 fits either story: the laptop click committed and lost its reply, or the phone click won and the laptop click never applied.
9:54 Even position 109 can't identify the click. Both could select message 110. Reading current state tells us where the bookmark is, not which request put it there. Ah, the laptop can load that current bookmark while leaving its old click unconfirmed. Nia sees her current place, but the button doesn't invent a receipt. She may choose Mark unread again using the current expected version. Only that fresh choice requests another reset; an automatic retry cannot make it for her. To recover a particular click's result, we'd need to store and retrieve that command result separately, with bounded retention.
10:30 That receipt mechanism is an extension. Now the laptop shows Nia's reminder. A delayed reply would erase it from her screen. I'm trying to avoid another counter here. Could the reset version maybe order the replies too? Several ordinary advances can share a reset version. That version distinguishes unread intent, but can't tell us which personal response reflects the later accepted change. One intent can contain newer reading positions. For example, the reset changes personal revision 41 to 42 while setting version 2, position 109.
11:02 Merge personal responses by that revision. A delayed revision 41 cannot replace confirmed revision 42, regardless of arrival order or the client's wall clock. What if the same response carries an older personal revision and a newer channel head? Throwing away the whole response would lose useful channel information. Her marker remains 109 with personal revision 42. That old personal reply can't change it. But the channel head can update from 120 to 128: more messages, without claiming more reading.
11:31 Later, Nia actually opens and scrolls the phone under refreshed version 2. Qualifying progress through 125 can produce personal revision 43. The reset label follows Nia's unread choice. Revision stamps identify the later personal record. With her bookmark protected, take a phone whose reconciled history reaches 120. Its stored head is 128, and a socket event arrives at 126. Can its downloaded coverage jump to that event? No. Having page 126 doesn't fill the missing pages before it. Fetch the missing range in bounded batches and deduplicate by channel position.
12:05 Extend coverage only across content actually reconciled. Where does the live subscription fit? Fetch history first and a message could arrive before the phone starts listening. Start listening first, then observe the committed head and fill missing ranges against durable history. The subscription supplies live hints; reconciling through the observed head covers the startup gap. And if a hint disappears while the connection still looks healthy? Nia could keep staring at yesterday's last message. Periodically fetch a fresh head.
12:34 When it advances, request the unseen positions through small history reads. Recovery still works when no live hint survives, and downloading them still doesn't advance her reading marker. If her saved catch-up position is unusable, does opening the conversation require rebuilding the archive? Refresh bounded current metadata and useful history. Mark earlier coverage incomplete; more pages may be needed. We don't promise every old range remains available. If the head or personal state can't be retrieved, show unknown or refreshing, perhaps with labeled last-known information.
13:05 Missing state cannot mean everything is read. Now stress those paths under our chosen peak workload: would adding gateways make the busiest channel accept messages faster? Both paths carry messages, so the distinction can disappear on a diagram. Two entrances can feed one ordering desk. Another gateway opens an entrance; it doesn't add a second writer for this channel. The channel owner still has to commit those ordered appends. Partition channel appends and history by channel. A hot channel still needs measured limits, including fanout, sending copies to its subscribers across gateways.
13:39 In a hypothetical overload, Nia's send could remain pending while another channel still opens. That send is waiting for its ordered append to commit. Personal state has a different partition key: user and channel. Delivering a message doesn't require advancing every recipient's reading record. Combine ordinary progress only within the same reset version, keeping the greatest qualifying position. Rate-limit excess updates without stripping versions or combining across a reset. Suppose Nia's membership response reaches its size limit.
14:09 Return the limited page and tell the client where to continue. Her conversation can keep loading while the sidebar fills. That scaling plan still needs privacy: authorize each content request at admission. A cached head, subscription or previously received message doesn't grant permission for a fresh private-channel request. Removing Nia from a channel can't recall content already delivered to her device. Admission checks don't promise immediate revocation across every device and cache. Now imagine Nia clicking Mark unread, and the required standby confirmation hasn't arrived.
14:41 What does her screen show while the system waits? Show her chosen return point as pending, distinguishable from last-confirmed state. She can see the intended change without being told it's durably saved. Could the action commit even though that confirmation times out? Yes. A timeout can leave the actual outcome uncertain. A required-copy outage keeps the action pending or unavailable; confirming just the primary still can't justify success. If messages arrive while the personal store cannot respond, keep unread state unknown or refreshing.
15:12 Useful message delivery cannot settle that separate pending choice. She can still read available, authorized content while that unread choice remains pending. Both required copies share our selected region. Have we earned any promise that the same behavior survives losing that entire region? Her change stays unavailable if those home-region copies are unreachable. Regional recovery and automatic takeover need a separate availability design. Finally, on this same map, find Nia's next screen update.
15:41 Authorized startup combines compact channel summaries and her reading record. Her chosen conversation opens through bounded history reads. Bulky content travels separately, rather than delaying that first screen. And if Nia hits Send while live delivery is lagging, when can her screen call it accepted? Her send is accepted once the owner commits message and head with both required durable acknowledgments. The log worker then feeds gateways and summaries. Missing hints lead back to history and head checks; accepted messages remain recoverable.
16:11 Mark unread uses the PostgreSQL transaction to set the reset version with the bookmark Nia requested, atomically. Ordinary progress must belong to that current intent. Personal revisions filter stale replies while channel updates merge independently. The picture now explains what opens, what waits and why her reminder survives. Now check whether her reminder survived. Her laptop reached 120 under version 1. Choosing message 110 unread created version 2 at position 109, immediately before the message she wanted to revisit.
16:39 The returning phone's progress through 125 still belongs to version 1. Reject and discard it. Never relabel that queued action with the refreshed version. The phone may still hold history through 125. That fetched coverage doesn't move her marker. A delayed response cannot overwrite its newer personal revision. If the reset reply disappears, a conditional conflict proves neither the original outcome nor which reset won. Refresh actual state; another reset requires a fresh user choice. When Nia actually reads again under refreshed state, qualifying progress may advance.
17:12 Until then, the phone has its pages, and she keeps her bookmark. Thanks for listening to Learning Podcasts.