One WebSocket Per Client: Gateway, Channel, Admin

Why a Persistent Connection at All

The alternative is polling: the client asks "anything new?" every couple of seconds. Do the arithmetic on 10 million clients polling every 2 seconds and you get 5 million requests per second of pure overhead, of which ~99% return "nothing new," and you still have up to 2 seconds of added latency on every message. A WebSocket inverts it: the client pays once to connect, then the server speaks only when there is something to say.

PollingPersistent socket
Server cost when idleHigh — every poll is a full requestNear zero — just memory for the connection
LatencyUp to the poll intervalNetwork time only
Server stateStateless — any box can answerStateful — this box owns this client
Expensive momentSteady stateConnect and reconnect

The work doesn't go away — it moves. Polling charges you a little, constantly. A socket charges you almost nothing while it is open, and a lot at the moment it opens. So the system's whole cost piles up into one instant: connect. That is what the boot payload part is about — and it is why a deploy frightens Slack more than a traffic spike does. A spike adds a few thousand new connects; a deploy drops every socket at once, and every client tries to reconnect in the same second.

The same bargain applies one tier inward, between servers. A persistent connection there is one TCP socket, TLS on top, opened at process start and reused for hours: no handshake per message, traffic in both directions so the far side can push, and warm congestion/TLS/HTTP‑2 state that a reconnect throws away. Hold that thought — it is what makes the Admin Server exist at all.

The Four Services

Slack's real-time tier is four Java services — three stateful, each sharded on a different key, and one deliberately not. The last column says which ones you actually have to keep in your head — two of them come back repeatedly, and two do their job in this part and are never heard from again.

ServiceStateSharded byJobComes back in
Gateway Server (GS)StatefulUser / regionHolds the client's WebSocket. Knows who this user is and which channels they belong to, and subscribes to all of them on their behalf. Deployed in many geographic regions so the socket is short.Everywhere on Axis A. boot payload, Flannel, channel fan-out, presence.
Channel Server (CS)Stateful, in-memoryChannel ID, via consistent hashingOwns a set of channels and their recent history. Does the fan-out. At peak, Slack reports ~16 million channels per host (remember: a "channel" is any topic, including every user).The channel fan-out part, heavily. The two-level tree is its design, the per-recipient cost is what that design fails to fix, and "one channel is one CS" is the hot-shard ceiling.
Admin Server (AS)Stateless—The bridge from the web backend into the CS ring. Takes "publish this event to channel X," consistent-hashes X, forwards it.Nowhere — and that is the point. It holds no state, so it has no failure story, no capacity story and no scaling story. Learn what it does once, then stop thinking about it.
Presence Server (PS)Stateful, in-memoryUser IDWho is online. Answers presence queries and pushes presence changes.The presence part, which is entirely its problem — though under the name "presence" rather than the service's. The green dot is the worst-behaved event type in Slack.

One clarification on the “sharded by” column, because the two stateful rows mean different things by it. A Channel Server's channels are computed — hash the ID, get the owner, as the rest of this part explains. A Gateway Server's users are assigned: when your client connects, Envoy hands it to a GS in the nearest region with spare capacity, and that machine is “yours” for as long as the socket lasts. There is no hash anyone could run to find which GS holds Priya, and nothing in the system ever needs to — events reach her GS because it subscribed to the topics she cares about, not because somebody looked her up. “Sharded by user” means each user's socket state lives on exactly one GS; “by region” means that GS is near them. Slack states this is the one tier deployed across multiple geographic regions, with a draining mechanism that moves a failed region's users to the nearest healthy one.

In front of all of it sits Envoy, doing load balancing and TLS termination. Behind it sits the Webapp: the original Slack application, still one large codebase rather than a fleet of services, and the owner of durable writes and business logic — auth, permissions, validation, what a message actually means.

The Send Path, End to End

Now walk one real message through: you post “hello” in #general, a channel with 10,000 members, and it has to land on every one of their screens.

One message, from the sender's keyboard to every online member's screen. Five numbered hops run down the left as a single copy. One: your client hits enter and sends an ordinary HTTPS POST, not the WebSocket — the socket only ever carries events coming down to you. Two: Envoy terminates TLS and picks a Webapp host. Three: the Webapp, Hack code, authenticates and validates, and writes first to MySQL, where the message becomes durable and gets its identity, a ts unique within the channel, before anyone is told. Four: only after that write succeeds does the Admin Server hash the channel ID and forward the event; it keeps nothing, so killing one mid-deploy loses nothing. Five: the path widens here, because this is where fan-out starts. The one Channel Server that owns general sends one copy to each Gateway Server that has a listener — about 200 machines, never 10,000 people. That is fan-out level one: one copy per machine, shown dropping to Gateway Servers in US-East, EU-West and AP-South plus about 197 more. Fan-out level two happens inside each Gateway Server, which multiplies its single copy to the roughly 50 client sockets it personally holds, in memory, with no further network calls; the remaining Gateway Servers carry about 9,850 more sockets. So 10,000 socket writes happen but no machine does 10,000 units of work: the Channel Server makes about 200 sends and each Gateway Server about 50 local writes, parallel rather than serial. The sender waited for none of it — their HTTPS request returned as soon as MySQL had the row.
One message, from sender's keyboard to every online member's screen
  1. You hit enter — and your client does not send it down the WebSocket. It makes an ordinary HTTPS request to the Webapp. The socket carries incoming events only: things flow down it to you, and your own messages go up a separate HTTP path. Sending has real work attached — are you allowed to post here, is the message well-formed, are you spamming, and above all save it so it is never lost. All of that logic already lives in the monolith, so the send goes where the logic is rather than dragging a copy of it into the socket tier.

  2. The Webapp writes to the database before it tells anyone. The message lands in MySQL (see workspace sharding) and gets its identity: a ts, a timestamp-shaped ID that is unique within the channel and is also the value everything sorts by. (How it is minted is not published. The shape that works: the Webapp's clock plus a sub-second counter, with (channel, ts) unique in the database, so two Webapp hosts posting to the same channel in the same instant cannot collide — one insert fails and retries with the next value.) Save first, announce second: by the time anyone hears about this message it is already durable. The other order leaves thousands of people looking at a message a crash erased. Only once the write succeeds does the Webapp hand the event to an Admin Server.

  3. The Admin Server is a switchboard — it decides only where to send this. Every channel is owned by exactly one Channel Server, chosen by hashing the channel ID. The AS does that arithmetic, forwards the event to the CS that owns #general, and keeps nothing. Add Admin Servers, kill them, or restart them mid-deploy and nothing is lost, because there is no state in them to lose; it all sits one hop further along.

  4. The Channel Server sends the message to machines, not to people. It does not walk a list of 10,000 members; it has never heard of any of them. It does not know Priya is in #general, and it does not know who is online.

    What it keeps instead is a much shorter list: which Gateway Servers currently have somebody listening to this channel. Those 10,000 people are spread across the fleet, so that list might be 200 machines long. The CS sends one copy to each of those 200 machines, and it is done.

  5. Each Gateway Server multiplies its one copy locally. A GS takes that single event, looks at the clients it personally holds sockets for, and writes the message down each relevant one — maybe 50. The expansion happens inside one machine's memory, with no further network calls. Across all 200 Gateway Servers 10,000 people get the message, but no single machine ever did 10,000 units of work, and the sender's request finished long before any of it completed.

What “Owning a Channel” Actually Means

That verb is doing a lot of work in the step above, so pin it down. A Channel Server is nothing exotic — it is a machine. Slack runs a fleet of them — the count is not published; the arithmetic in this part assumes a few hundred — all running the identical Java process. Host 47 and host 48 are the same software; the only thing telling them apart is which channels each has been made responsible for.

And somebody has to be responsible, because every channel has a small pile of live state that must sit in some machine's RAM:

The subscriber listWhich Gateway Servers currently hold at least one client listening to this channel — “GS-3, GS-17, GS-88…”. This is the list the fan-out walks.
Recent history“Some amount of history of channels,” in Slack's words — the last stretch of events, in memory, so that a Gateway Server re-registering after a blip can be brought up to date from the buffer rather than from MySQL. How far back it reaches is not published; anything older goes over HTTP, as the “past versus future” subsection below explains. “How the recent-history buffer actually works,” further down, finishes the mechanism.
OrderingThe sequence events go out in for this channel, so every recipient sees the same order.

So “CS-47 owns #general” means precisely this: that pile of state lives in CS-47's memory and nowhere else. Want to publish to #general? CS-47 is the machine you have to reach. Not a copy of it, not a replica — the one.

Why exactly one owner, and not three

Because the subscriber list is the thing you route by, and duplicating it immediately creates a question with no good answer. If CS-47 and CS-48 both held #general's list, does a new message go to both — in which case every member receives it twice — or to one, in which case the other machine's list is quietly wrong the moment anyone joins or leaves? You would be forced into keeping two copies synchronised in real time, which is a harder problem than the one you started with. A single owner makes “who is subscribed here?” a question with exactly one correct answer, in exactly one place, one hop away.

How the owner is chosen: arithmetic, not a directory

The obvious design is a lookup table — some registry service that knows channel → server, which everyone queries before sending. That buys you an extra network round trip on every message in Slack, a thing that can be stale, and a thing that can go down and take the product with it.

So there is no registry. The owner is computed:

hash(“C456”)  →  a number  →  the machine responsible for that number

Deterministic, and identical everywhere. Any Admin Server anywhere in the fleet does this locally in microseconds and lands on the same answer as every other Admin Server, with no coordination and nothing to look up. That is what lets the AS be stateless: it does not need to know anything, it just does the maths.

The consistent in “consistent hashing” is what makes this survive a changing fleet. With a plain hash % 300, adding one host changes the divisor — and nearly every channel in Slack is suddenly assigned somewhere new, meaning the entire fleet's memory is wrong at once. Consistent hashing instead arranges the hosts around a ring and gives each one an arc of it, so adding or removing a machine disturbs only that machine's arc. Everything else stays exactly where it was. (In practice each host holds many small arcs rather than one big one, so a removed host's channels are shared out across all the survivors instead of dumped on a single neighbour, and load stays even. That is standard consistent hashing, not a Slack-specific detail.)

Two things follow, and both matter later. Ownership is memory, not truth — the messages are already durable in MySQL, so losing a CS loses no data, only liveness — which is what CHARM, at the end of this part, exists to handle. And a channel cannot be split: ownership is per-channel, so a 50,000-member #general is one channel on one machine, full stop. You cannot throw hardware at it. That is the ceiling the channel fan-out part runs into.

The Subscribe Path — How That List Gets Built

The send path above takes the subscriber list as given: the CS “knows” which 200 Gateway Servers to copy the event to. But where did that list come from? The answer runs in the opposite direction to everything else in this part, which is why it is easy to miss.

The Channel Server never goes looking for Gateway Servers. The Gateway Servers come to it and register themselves. The CS is entirely passive — its subscriber list is something it was told, one registration at a time, long before your message showed up.

Priya and her one WebSocket sit at the bottom of the diagram; Gateway Server GS-17 sits above her; and above that, side by side, two identical Channel Servers: CS-47, which owns the channel topic C456 for #general, and CS-12, which owns Priya's own user topic U123. Each Channel Server box holds a green chip showing the single line of memory it keeps, C456 or U123 mapped to a list containing GS-17. Between every pair of tiers there is one corridor drawn as a capsule, and inside each corridor two lanes run in opposite directions: a blue lane pointing upward, numbered one, which is the subscription sent once when she connects, and a teal lane pointing downward, numbered two, which is every event afterwards travelling back down that same corridor. The channel column and the user column are drawn exactly the same way, with the same capsule, the same two lanes and the same green memory chip; only the example payloads differ, a message posted in #general on one side and a you-were-mentioned event on the other, and a note above each column says where the topic ID came from: Webapp's membership list for the channel, and a hash of her own user ID, needing no lookup, for the user topic.
Subscription flows up; events flow down the same path afterwards — identically for a channel topic and for her own user topic
  1. You connect, and one Gateway Server takes you on. Your client opens its WebSocket to a GS near you — call it GS-17. Slack describes what happens next in one sentence: the GS “fetches the user information, including all the user's channels, from Webapp and sends the first message to the client,” then “subscribes to all the channel servers that hold those channels … asynchronously.” So GS-17 now knows who you are and the full list of channels you belong to — all 400 of them — and starts registering for every one, in the background, without making you wait for the last registration before you can use the first channel. Note the Webapp round trip: connecting is already a database-backed request before a single event flows, which is the thread the boot payload part pulls on.

  2. GS-17 works out the owner by itself. For channel C456 it runs the same hash → ring position → machine arithmetic the Admin Server uses on the send path. This is the quiet payoff of having no directory: a machine publishing and a machine subscribing both compute the same owner independently, in microseconds, with nothing to look up and nobody to ask. The one input it needs is the current ring membership — which hosts are on the ring right now — and that is shared configuration read from Consul, as the CHARM subsection at the end of this part explains.

  3. GS-17 registers with CS-47, and CS-47 writes one line in memory. The registration says, in effect, “send me everything for C456 from now on”; the far side records C456 → […, GS-17, …]. That is the whole transaction — and that line is literally the subscriber list from the previous subsection. Repeat it a couple of hundred times, as members of #general all over the world connect to whichever Gateway Server is nearest them, and the list of ~200 machines assembles itself. (Whether the registration rides a fresh connection or an existing one is not published — but with each user's 400 channels spread over the whole ring, every GS ends up talking to every CS anyway, so read it as a message over a persistent connection.)

  4. And one more registration, which is not a channel at all. Everything above is about the 400 channels. But GS-17 also registers Priya's socket against her own topic: hash(“U123”) → whichever CS owns it → “send me everything for U123.” Same arithmetic, same registration message, same single line of RAM on the far side — because as far as a Channel Server is concerned there is no such thing as a “user topic.” There is a topic ID and a list of Gateway Servers that want it, and U123 is simply one more ID. This is the What Slack is part’s “everything is a channel” ceasing to be a slogan.

    What differs is where the two come from. The 400 are read out of the membership list the Webapp just returned — GS-17 could not have guessed them, and fetching them is the one part of connect the user actually waits on (the boot payload part’s thread). This one is computed from her user ID alone, needs no lookup to know it exists, and is the only subscription guaranteed to be there for exactly as long as the socket is. Slack publishes the channel registrations and not this one; that the user topic is subscribed at connect is inference from the events Slack does deliver over it, described below.

Membership is not subscription — even though every membership gets one

Two facts are in play here, kept in two completely different places, and conflating them is the fastest way to get this design wrong:

MembershipSubscription
The fact“Priya is a member of #general”“GS-17 wants C456's events right now”
Lives inMySQL, as a durable rowOne Channel Server's RAM
LastsYearsUntil her socket closes
Survives logoutYesNo — it is torn down
Costs anything?A few bytes of storageYes — she is now an n in somebody's fan-out

Slack does hold a live subscription for every channel a connected user belongs to — that is what the asynchronous registration at connect is for. What keeps that from being the n × k bill from the What Slack is part is that a subscription is not traffic: it is one line in a map, and it costs nothing until somebody posts. The bill is paid per event, per connected recipient, and most of your 400 channels are silent most of the day. So the n in n × k is “members currently online,” never “members.” Disconnect, and every one of those lines is removed; you are still a member, you have simply stopped costing anything.

Why the list has 200 entries and not 10,000

Here is the detail that makes the two-level tree pay off. GS-17 might be holding 50 different clients who all want C456. It does not subscribe fifty times. It subscribes once, and keeps its own private count of how many of its clients care. Another member of #general connects to GS-17: the count goes up, nothing is sent to the CS. One of them disconnects: the count goes down. When it reaches zero, GS-17 tells CS-47 to take it off the list and stops receiving that channel entirely.

So the collapsing from 10,000 people to 200 machines does not happen at send time — it already happened, gradually, at the Gateway layer. And this is exactly why the channel fan-out part can claim that absent members cost nothing: someone who is not connected has no Gateway Server registering on their behalf, so they do not appear anywhere in the CS's view of the world. They are not skipped during fan-out; they were never in the list to begin with.

Now notice what kind of thing that list is: a few hundred lines of RAM on one machine, built entirely from registrations that arrived over the network. It is not in MySQL. It is not replicated. If the machine holding it dies, the list does not fail over — it simply ceases to exist, and has to be built again from scratch by every Gateway Server re-registering with whoever takes over. Holding onto that is what makes CHARM, at the end of this part, make sense.

What the Gateway Server Is Actually Holding

First, the correction people almost always need: you have one socket, not one per conversation. One WebSocket to one Gateway Server, for your entire session. Ten channels open, still one socket, and the same subscriptions as before.

If one socket carries many topics, then the GS must know which of its sockets care about which topic — otherwise an arriving event has nowhere to go. It keeps that as an index, and it needs it in both directions:

topic → socketsThe hot path. An event for C456 arrives; look up C456, get the local sockets to write to, write. This lookup happens on every single event, so it is the one that has to be fast.
socket → topicsFor teardown. Priya shuts her laptop and the connection dies; now she must be removed from every topic she was in — C456, C789, her own per-user stream, any file she had open. Without this direction, that means scanning every topic list on the machine hunting for her socket. With it, one lookup and a few removals.

Concretely, that is two maps in one process:

GS-17, in RAM:

  conns[socket-a] = { user: U123,
                      topics: { C456, C789, ... , U123 } }   <-- ~401 entries
  conns[socket-b] = { user: U456, topics: { ... } }
  ...

  subs[C456]      = { socket-a, socket-b, ... }              <-- local sockets only
  subs[U123]      = { socket-a }                             <-- her laptop; + phone, desktop
  subs[C789]      = { socket-a, socket-q }

It is one relation stored twice, transposed. Two things fall straight out of it. Priya's own topic sits in subs next to the channels, distinguished only by having a subscriber set of one to three sockets instead of fifty — the GS has no notion of a “user topic,” and the What Slack is part’s everything is a channel shows up here as an absence of special-casing. And the reference count from the previous subsection is free: “how many of my clients still want C456?” is simply the size of that topic's socket set, so when a removal takes it to zero the GS unsubscribes from CS-47. There is no separate counter to maintain and get out of step.

Now put the two tiers side by side, because this is the part worth carrying out of this part:

CS-47:   C456 → { GS-3, GS-17, GS-88, … }   — about 200 entries

GS-17:   C456 → { socket-a, socket-b, … }   — about 50 entries

It is the same data structure at two scales — the Channel Server maps a topic to machines, the Gateway Server maps that same topic to sockets. That is not an analogy for the two-level tree; it is the two-level tree. Fan-out is one map lookup, then another map lookup, and the only reason no machine ever does 10,000 units of work is that neither map is ever 10,000 entries long.

One more thing about the Gateway side of that pair: the entries are not counted per connection, they are counted per membership. Every socket contributes ~401 pairs, once in each direction. Take a hypothetical box holding 16,000 clients — the per-host figure is not published, so treat the number as illustrative and the shape as not:

16,000 sockets × 401 topics ≈ 6.4M (topic, socket) pairs — held twice, once per direction

At a few tens of bytes an entry that is hundreds of megabytes of pure routing table per host, storing nothing but who wants what. So the boot payload part’s 400-channel figure is not colour: it is a multiplier on the Gateway tier's footprint, and the same breadth is what forces the connect-time Webapp round trip to ship all 401 channel IDs before a single event can flow. One cause, two bills.

Two consequences the rest of the guide leans on. First, this is the per-connection memory: “the GS is stateful, sharded by user and region” means precisely this pile of maps, plus each socket's own buffers and identity — multiplied by tens of millions of connections, which is the RAM ceiling named as Axis A's limiting resource. Those per-socket buffers are also where a slow client shows up: a phone on a bad link in a busy channel cannot drain events as fast as the GS writes them, so its buffer grows. Slack does not publish its policy here; the only sane one is a cap, beyond which the GS drops events or the connection and lets the client heal over HTTP — one more reason the socket is best-effort by design. Second, this is why a deploy is worse than a traffic spike: restart a Gateway Server and every one of these maps vanishes with the process, because they were never anywhere but RAM. Every client it held reconnects, re-authenticates, re-fetches and re-subscribes — and each re-subscription may land on a Channel Server that has to rebuild its list too. “The expensive moment is connect” is really a statement about how much in-memory index has to be reconstructed, and by whom.

Two Streams: the Channel Topic and the Per-User Stream

If GS-17 is subscribed to all 400 of Priya's channels, a message in #random already reaches her socket while she is looking at #general — her client could bump the unread count itself. So why does Slack also publish private per-user events such as channel_marked? Because there are two paths carrying two different kinds of thing, and the channel topic can only carry one of them.

The channel topic (C456)Carries the message itself — the same bytes to everyone connected and subscribed. This is the fan-out tree above: the CS, the ~200 Gateway Servers, the local socket writes. It tells Priya's laptop what was said.
Her own private per-user streamCarries “what this means for you” — you were mentioned, your read marker moved on another device, your DND window changed, your badge should light up. Her GS keeps her attached to this for as long as she is connected at all; if she has no live socket, the same decision comes out as an APNs or FCM push instead.

The structural reason is one sentence: a topic delivers the same bytes to everyone on it. Compare what the two things actually are:

“hello world” in #general“you have an unread, and you were mentioned”
How many distinct events?One event, 10,000 identical copies10,000 different events, one copy each
Depends on the recipient?No — the same bytes for everybodyYes — their last-read marker, mute setting, DND window, device list
ShapeBroadcastUnicast

The fan-out tree works only because the payload is identical. A Channel Server can hand one copy to a Gateway Server and let it blindly duplicate to fifty sockets precisely because nobody has to think about who those fifty people are. The moment the content differs per person, that mechanism is useless — you cannot “copy” something that is not the same thing twice. The per-user stream is the unicast escape hatch inside an otherwise broadcast system.

Three consequences make that more than a technicality. Authority: your laptop could count #random unreads from the messages it receives, but your sleeping phone, and your laptop after a reconnect, cannot — they missed the events. The server keeps the authoritative marker, so any device can be told the answer instead of replaying history to derive it. Stability: the set of channel topics your GS holds changes as you join, leave and reconnect, while your per-user stream is fixed for the whole session — it is the one address that always works. The offline case: content delivery assumes a live socket, but notifications must work when there is none; because the decision is already computed centrally and per person, it can be routed to a socket or to APNs/FCM from the same place.

Who writes to a per-user stream, and when

The writer is always the Webapp — never the real-time tier, which only ever moves things it was handed. And the route is the one you already know: hash(“U123”) → the Channel Server that owns that topic → the Gateway Servers holding a subscriber → sockets. Nothing about a user topic is special; the Admin Server does not know or care that U123 is not a chat room.

What happenedWhen it publishesWho receives it
You change your avatar or display nameAfter the profile row commitsOther people — anyone whose screen renders you
Someone posts in a channel you belong toSeconds later, off the send pathYou only — your connected client already has the message itself from the channel topic; this is the authoritative unread and mention state, and it is what reaches the devices that did not
You read a channel (your marker moves)After the marker write commitsYour other devices only
You toggle DND or change notification prefsAfter the write commitsYour other devices only
You are added to or removed from a channelAfter the write commitsYou only

The discipline never changes: persist, then publish — the same rule as the message send path, for the same reason. Nobody is told about a state change that is not yet durable.

The other traversal: the membership flow

Row two of that table is the expensive one, and it deserves a name. Everything up to here has traced one way of answering “who is in #general” — the subscriber list, built by Gateway Servers registering on behalf of clients they hold. One message triggers a second traversal that answers the same question from completely different data. Almost every confusing thing about Slack's delivery model comes from mixing the two up:

The subscription traversalThe membership traversal
Answers“Which machines are holding someone who is listening right now?”“Whose state changes because this was posted?”
ReadsOne Channel Server's RAM — the ~200-entry listMySQL — the durable membership rows, all 10,000
CoversConnected members only. Absent members are not skipped; they were never in the listEvery member, connected or not — that is the whole point of it
RunsSynchronously on the send path, in millisecondsAsynchronously on the job queue (see async work), seconds later
ProducesOne event, copied down a treeUp to 10,000 distinct events, one recipient each
Publishes toThe channel topic C456Each member's own private user topic — or their phone
Cost shapeO(g), g = Gateway Servers holding a listenerO(n), n = members. This is the O(n) the channel fan-out part is about

Both start at the same instant — the moment the Webapp's write to MySQL commits — and then diverge completely:

A single purple MySQL cylinder at the top, the moment the message row commits, forks into two labelled tracks. The left track, headed FAST and FOLLOWS CONNECTIONS, is reached by a solid blue arrow marked on the send path, now: Admin Server to CS-47, then a green box that is the thing it walks, CS-47 memory holding about 200 entries shown as chips named GS-3, GS-17 and GS-88, then the sockets of members who are online. It finishes high up the diagram in a green result strip reading already done, one event copied down a tree, order g where g is Gateway Servers. The right track, headed SLOW and FOLLOWS MEMBERSHIP, is reached by a dashed teal arrow marked enqueue one job then return: the job queue, then a long dashed arrow with a break mark labelled seconds pass, then a purple MySQL cylinder that is the thing it walks, every member of C456 shown as chips named U123, U456, U789 and 9,997 more, then a per-member decision box, which splits into a blue box for members online, published to each member own user topic, and a grey box for members not online, pushed through APNs or FCM. It finishes far lower down in a purple result strip reading 10,000 distinct events, one recipient each, order n where n is members. A panel in the space the fast track leaves empty warns that a Gateway Server never asks who is in a channel.
One commit, two traversals: the fast one follows connections, the slow one follows membership

Read the right-hand branch carefully, because it is where the expensive part of Slack lives. The worker cannot shortcut it. Each of those 10,000 decisions needs that member's own mute setting for this channel, their DND window in their own timezone, their last-read marker, and their registered devices — per-user rows, nothing cacheable across users, and the answer is different for every one of them. So the notification work for a busy channel is not one publish with 10,000 recipients; it is 10,000 separate publishes with one recipient each, to 10,000 different topics. That is the unicast row made concrete, and it is the real texture of the channel fan-out part’s O(n): not a big fan-out, but an enormous number of tiny ones. It is also why this runs on a job queue rather than the send path — the sender's HTTP request returned long before the last badge lands. And the two outcomes at the bottom are not two features; they are the same decision resolving differently depending on whether the member has a live socket. The channel fan-out part picks up that second path, including why a laptop and a phone receiving the same thing twice is solved by ts rather than by coordination.

One reading of the fan-out is worth killing on sight, because almost everybody reaches for it: “the GS receives the event for C456, looks up who is in that channel, picks out the ones it is responsible for, and delivers to them.” No step of that happens. A Gateway Server does not know, and never asks, who is in a channel. Its index is the whole of what it has — topic → my sockets and its inverse, built entirely from its own clients' registrations. There is no roster in it, and GS-17 could not name a single member of #general who is not currently attached to GS-17. It does not have the membership data (that is MySQL, sharded by workspace, the workspace sharding part); doing the per-person lookups would turn the cheapest tier into one doing thousands of database reads per message; and, fatally, it structurally cannot reach the people who matter — the membership traversal exists largely for members who are not connected, and a GS holds no socket for those people, so no amount of filtering there could ever produce them.

So the two traversals never meet at the Gateway Server. What they share is the machinery, not the decision: the bottom-left branch of the diagram — topic → owning CS → subscribed GSes → sockets — is character for character the same as the message path. The only differences are that the topic ID is a user instead of a channel, and that there are 10,000 of them instead of one.

Opening a Channel: the Past over HTTP, the Future over the Socket

Click #general and two things matter — one of which already happened when you connected. An HTTP request fetches history: “give me the last 50 messages in C456,” an ordinary request to the Webapp, answered out of MySQL; everything you see when the channel first paints came from there. The live subscription is already in place: your GS registered with CS-47 for C456 when you connected, so nothing is set up now — what changes is that your client starts rendering those events instead of just counting them.

So the split is past versus future — but be exact about where the seam sits, because it is not the moment you opened the channel. The seam is the ts the history response ends at. Everything up to that timestamp: database, over HTTP. Everything after it: the socket stream that was already flowing. Scrolling up is more HTTP — the socket is never involved in history you navigate to, no matter how far back you go. The Channel Server's small in-memory buffer exists for the real-time tier's own catch-up after a blip, not for browsing.

The client stitches the two together with ts. History came back ending at …100; a live event arrives stamped …205, which is larger, so it appends to the bottom. And because that stream predates the fetch rather than starting after it, the two can only overlap, never gap: a message posted between the database query and the first paint arrives on both paths, and the same ts comparison drops the duplicate. Under subscribe-on-open the same window would be a hole, with nothing to heal it.

If the events already arrived, why fetch anything?

Eager subscription raises the obvious objection from the other direction. While you sat in #general, events for the other 399 channels were landing on your socket, and your client did not throw them away — that is where the sidebar's unread count and mention badge come from. So when you finally click #random, why does it go to the database for messages it was handed minutes ago?

Because what the socket gave you is a suffix, not a window. It delivered what was posted since you connected. It has nothing to say about what came before that, and “before that” is most of what a channel looks like when it paints.

You are holding a fragment with a hole above itThree messages arrived in #random while you were connected. The channel had five hundred before that. Rendering the channel means the last ~50 ending at now — so 47 you never received, and no amount of socket buffering produces them. The stream can only ever extend the bottom of a window somebody else has to hand you.
The gaps are silentThe socket is best-effort by design: a slow client past its buffer cap has events dropped, and a reconnect loses whatever happened during the gap. The fatal part is not the loss but the unknowability — the client cannot tell which events it missed. A buffer of unknown completeness is fine for “there is something new here,” and can never be rendered as history.
Events mutate, they do not only appendEdits, deletes, reactions and the link-preview unfurl (see async work) all arrive as events against a message. Apply an edit to a message you never received and it is a silent no-op — the fragment does not just have holes, it drifts wrong.

So whatever the client had buffered for #random is merged into the fetched window by ts, duplicates dropping out as above — the buffer is an optimisation layered on the fetch, never a replacement for it. One sentence carries the whole subsection: the client treats the socket as a hint and the database as truth. If opening a channel rendered from socket history, correctness would depend on how good your wifi had been for the last twenty minutes.

Scope: what a Slack client caches locally is implementation detail this guide's sources do not cover. The load-bearing claim is the architectural one — the history fetch happens on open, and the socket is never authoritative for history.

Reading it again: the round trip that clears the badge

The loop closes in a way worth seeing, because it explains where unread state actually lives. When you open #random, your client tells the server “I have read up to ts…205” over HTTP. The server moves your last-read marker and then publishes your new state on your private per-user stream — a channel_marked event. Your phone, which was showing a badge, is attached to that stream too, and clears it a moment later.

So your unread state is not in your client. It is on the server, and every device you own is just a subscriber to it — which is why the badge clears on your phone when you read something on your laptop, and why that works without your two devices ever knowing about each other.

What Comes Down the Socket: Thin Events

The blob that arrives for a new message is small, roughly:

channel: C456  ·  user: U123  ·  ts: 1694612345.001200  ·  text: “hello world”

Enough to render instantly. But two kinds of thing are deliberately left out:

Who U123 isNo name, no avatar, no job title — just the ID. Your client already has that cached, which is Flannel's entire job (see Flannel). Shipping “Priya Sharma + avatar URL + title” to 10,000 recipients would mean sending the same profile bytes ten thousand times, per message. Send the ID; let each client look it up once and reuse it forever.
Anything slowA link preview does not exist yet when the message is sent — a background job fetches it seconds later (see async work) and then edits the message, which fans out a second event. So a message with a preview reaches you as two separate events: text now, preview shortly after. The socket never waits for slow work.

The channel fan-out part has a name for this: thin events, fat objects. Push the smallest thing that identifies what happened, and let each client hydrate the details from a cache. The expensive bytes get sent once to Flannel rather than n times over sockets.

Keeping the Ring Healthy: CHARM

Channel Servers are stateful and consistent-hashed, which raises two questions: how does everyone agree on the ring, and what happens when a host on it dies? Slack's answer to both is CHARM — Consistent Hash Ring Managers — plus Consul, its service-discovery store. In Slack's words, “each consistent hash is defined and managed by CHARMs, and then Admin Servers and CS discover them by querying Consul for the up-to-date config.” So the ring is not something every host computes privately from a hard-coded host list; it is shared configuration with one writer (CHARM) and many readers. Slack names Admin Servers and Channel Servers as the ones querying Consul; a Gateway Server must read the same ring too, since it computes owners on the subscribe path — that is inference from the published connect sequence, not a quotation. “Just do the maths” earlier in this part works because all of them are doing the maths over the same published ring.

When a CS becomes unhealthy, CHARM replaces it: Slack reports that “a new CS is ready to serve traffic in under 20 seconds,” during which users of the affected channels “experience elevated latency in message delivery.” Because each team's channels are spread across all CSs, one host's failure touches a thin slice of many teams rather than everything belonging to a few.

The reason 20 seconds is the target rather than 20 minutes: a CS holds channels in memory. While its slice of the ring is unowned, events for those channels have nowhere to go. Durability is not at risk — the message is already in MySQL — but liveness is: users in those channels stop seeing messages arrive until someone else picks up the range. Slack's answer is not "make CS durable," it is "make the gap short."

What the replacement entails follows from the subscribe path, and Slack does not narrate it, so treat this as reasoning. The new CS starts with an empty map. Every Gateway Server that held a subscription on the dead host sees the ring change in Consul, recomputes the owner for each affected channel, and re-registers — the “rebuilt from scratch by every GS re-registering” step foreshadowed earlier. The recent-history buffer went with the old host, so a client that missed events during the gap heals over HTTP. The same logic runs the other way: a GS's registration is a live connection to the CS, so when a GS dies its entries drop out of every CS's map as that connection closes — no garbage collector needed.

  • Guarantees: A message that the Webapp acknowledged is durable and will be visible on the next history fetch, regardless of what the real-time tier does. Connections are held close to the user, so the socket leg is short even when the data is far.
  • Does not guarantee: That every published event reaches every online client. A CS handover, a GS restart, or a flaky socket can drop events; the client is responsible for detecting the gap and healing it by re-fetching — which is exactly the expensive operation the boot payload part is about.