PATTERN · ORIGINAL
Fan-out and real-time delivery
Fan-out on write vs read vs hybrid, celebrity skew, choosing WebSocket, SSE or mobile push, connection gateways and subscription registries, coalescing updates, and backfill on reconnect.
Fan-out is what happens when one event has many audiences. A post reaches followers, a message reaches group members, a price tick reaches watchers, a like count reaches everyone looking at the post. The design questions are always the same two: when do you do the per-recipient work (at write time or at read time), and how does the result reach a recipient who is online right now?
The first question is about storage and compute. The second is about connections. They are often tangled in interviews, so this article treats them separately and then joins them up.
When to fan out
Fan-out on write (push)
When someone posts, a background job copies a reference to the post into every follower's pre-built timeline. Reading a timeline becomes one cheap lookup. This is the right default when reads vastly outnumber writes, which is true of most feeds: people scroll far more than they post.
The cost is write amplification. As estimates that drive decisions shows, 5,000 posts per second with 200 followers each is a million timeline inserts per second, and much of that work is for people who will not open the app today.
Fan-out on read (pull)
Store each post once under its author. When a user opens their timeline, fetch recent posts from everyone they follow and merge them. Writes are trivial and nothing is wasted on inactive users. Reads are expensive: following 500 accounts means up to 500 lookups and a merge on every refresh, which is hard to keep under a couple of hundred milliseconds.
Hybrid, because of celebrity skew
Follower counts are extremely skewed. Most accounts have a few hundred followers; a handful have tens of millions. Pushing a post from a 50-million-follower account means 50 million inserts for one event, which delays every other post in the queue. Pulling for everyone makes every read slow.
The usual answer: push for ordinary accounts, pull for very large ones. Pick a threshold (say 100,000 followers). Posts from accounts below it are fanned out on write. Posts from accounts above it are stored once, and at read time the timeline service merges the user's pre-built timeline with recent posts from the few large accounts they follow. A user follows at most a handful of such accounts, so the read-time merge stays small. Twitter described a design along these lines in the talk in further reading.
Two refinements worth mentioning: skip fan-out to users who have not been active in weeks (build their timeline on demand when they return), and cap each stored timeline at a few hundred entries, since almost nobody scrolls further.
| Option | Wins when | Costs |
|---|---|---|
| Fan-out on write | Reads far outnumber writes and follower counts are bounded | Write amplification, wasted work for inactive users, slow delivery for huge audiences |
| Fan-out on read | Audiences are huge or writes are frequent relative to reads | Expensive, slower reads; merge cost grows with follow count |
| Hybrid | Audience sizes are heavily skewed, as in most social graphs | Two code paths, a threshold to tune, and a merge step on read |
Note that a microblog timeline and a ranked news feed differ here. A timeline is mostly about this delivery problem. A ranked feed adds candidate generation and scoring, so the “fan-out” there often produces candidates rather than a final ordered list.
How to reach someone who is online
Everything above produces data in a store. For live features (chat, live comments, live like counts, price tickers) the update also has to be pushed to a device in a second or two. Three channel types cover nearly every case.
| Channel | Use it when | Watch out for |
|---|---|---|
| WebSocket | Both directions matter on the same connection: chat, typing indicators, collaborative editing | Stateful connections to manage; proxies and load balancers must support upgrades and long idle times |
| Server-sent events (SSE) | Updates flow one way to a browser: live comments, scores, counts, dashboards | One direction only (send actions over normal HTTP); browsers limit connections per domain over HTTP/1.1 |
| Mobile push (APNs, FCM) | The app is in the background or closed and the user should be told something | Best effort, rate limited, delayed by the OS; a nudge to open the app, not a data pipe |
Long polling is still a reasonable fallback where persistent connections are blocked. For an interview, say which you chose and why in one sentence, and note that the app usually uses a socket when open and mobile push when closed, as in a notification service.
Gateways and subscription registries
Persistent connections change the shape of the system. A single server can hold tens of thousands to a few hundred thousand idle connections, so 10 million online users means a fleet of a hundred or more connection servers. Put them in their own tier:
- Connection gateways terminate WebSockets or SSE, authenticate, and keep a map of local connection to user and to topics. They hold no business logic, so they can be deployed and scaled independently and restarted without losing data.
- A subscription registry records which gateway holds which subscriber:
topic or user → set of gateway ids. Gateways register on connect and unregister on disconnect, with a TTL heartbeat so crashed gateways age out. - A publish path: when an event happens, a fan-out worker looks up the registry and sends one message per gateway, not per user. Each gateway then delivers locally to all its connections for that topic.
The per-gateway trick is the key multiplier for live events. A stream with 2 million viewers spread across 200 gateways becomes 200 internal messages per update, not 2 million. Each gateway then does a cheap local loop. The registry entry for that topic is itself a hot key; it changes slowly, so gateways and fan-out workers can cache it for a few seconds (see caching and hot keys).
For one-to-one or small-group delivery like chat, the registry maps users to gateways instead of topics to gateways, and the shape is otherwise identical. Slack's post in further reading describes gateway servers and channel servers in this role.
Coalescing and throttling
Not every event deserves its own push. A popular post receiving 5,000 likes per second does not need 5,000 count updates per second sent to every viewer; nobody can read that fast, and it multiplies load by the audience size. Instead:
- Coalesce: per topic, keep only the latest value and flush every 1 to 2 seconds. For counts, send the new total, not each increment. Clients just render the latest.
- Throttle per connection: cap how many messages a single client receives per second. Slow clients get the latest state rather than a backlog.
- Sample for huge audiences: for live comments on a stream with millions of viewers, show each viewer a sampled subset at a readable rate (say 10 comments per second) rather than every comment.
- Drop, do not queue, for slow consumers: if a gateway's send buffer for one connection fills, drop intermediate updates or disconnect. Unbounded buffers on a gateway are how one slow phone network turns into an out-of-memory crash for 50,000 users.
Coalescing is a product decision as much as a technical one. Chat messages must not be coalesced or dropped. Like counts and viewer counts should be. Say which category each live update falls into.
Backfill on reconnect
Connections drop constantly: phones switch networks, laptops sleep, gateways get deployed. The push channel is therefore a fast path, not the source of truth. Design for gaps:
- Give every event a sequence number per topic or conversation (or a timestamp plus id) when it is stored.
- The client remembers the last sequence it rendered.
- On reconnect, the client sends that number, and the server returns everything after it from the store, then resumes live pushes. SSE has this built in through the last event id header.
- If the gap is huge (the client was away for a day), skip the replay and just reload the current state.
Sequence numbers also let clients drop duplicates and reorder, since a fan-out pipeline that retries will occasionally deliver an event twice (see consistency and idempotency). One subtle race: subscribe first, then fetch the backfill, then discard any live event with a sequence already seen. Doing it the other way round leaves a window where events are missed.
Putting it together on the board
For any live or feed question, draw two lanes. The top lane is durable: write API, store with sequence numbers, event bus, fan-out workers, and (for feeds) per-user timelines with the hybrid threshold written beside them. The bottom lane is ephemeral: gateways, registry, client connections, with “coalesce 1 s” or “never drop” written on the push arrow. Then mark the reconnect path from client back to the store. With that picture, most follow-ups (a celebrity posts, a gateway dies, a client is slow, a user was offline for an hour) have an obvious place to point. Queue mechanics for the fan-out workers are in queues, retries and dead letters, and per-topic ordering in partitioning and ordering.
TAKE THIS TO YOUR NEXT SKETCH
- Decide when per-recipient work happens: on write for read-heavy feeds, on read for huge audiences, hybrid for skewed graphs.
- Set a follower threshold for the hybrid and merge large accounts at read time; skip fan-out for inactive users.
- Pick WebSocket for two-way, SSE for one-way browser streams, and mobile push only to nudge a backgrounded app.
- Put connections in a gateway tier and send one internal message per gateway using a subscription registry.
- Coalesce and throttle counts and other replaceable state; never coalesce or drop messages users must see.
- Store before you push, number events per topic, and backfill from the last seen sequence on reconnect.
PRACTICE WITH THIS
Now sketch one.
OFF-SITE READING · NOT WRITTEN BY US
Further reading
- Timelines at Scale
A Twitter engineer describes pushing tweets into cached follower timelines on write and the special handling large accounts needed.
- Real-time Messaging
How Slack routes messages to online users through gateway servers that hold WebSocket connections and channel servers that own subscriptions.
- Using server-sent events
The browser API for one-way streams, including automatic reconnection and the last event id that makes resuming a stream simple.
- The WebSocket API
Reference for full-duplex browser connections, useful when deciding whether you need client-to-server messages on the same channel.