How Async Fan-out Actually Works: Queues, Workers, and the Write Path
The tweet is durably stored in under a millisecond; the poster gets
OKimmediately. Everything after that — writing into followers' timeline caches — happens in the background via a queue-and-worker pipeline. Understanding this pipeline is what makes "asynchronous fan-out" a concrete mechanism, not a hand-wave.
The intuition first
Think of a post office with a drop box and a sorting floor. When you mail a letter, the act of dropping it in the box is instant — you're done, the letter is safe. The sorting, routing, and delivery to individual mailboxes happens separately, in the back, by postal workers. You don't wait at the drop box while they do all that.
Twitter's write path is that drop box. Posting a tweet = dropping the letter. The fan-out workers = the postal sorting floor. The two are deliberately decoupled via a durable queue, so the poster's experience is always instant regardless of how many mailboxes (followers) need to be updated.
The three-phase write path
Every tweet goes through three distinct phases. The poster's OK arrives after Phase 1; Phases 2 and 3 are invisible to them.
PHASE 1 — SYNCHRONOUS (poster waits for this)
─────────────────────────────────────────────
User submits tweet
│
▼
1a. Assign Snowflake ID (distributed, in-process, ~microseconds)
│
▼
1b. Write tweet to tweet store (T-bird / durable storage)
│ (sharded write; acknowledged once on disk)
▼
1c. Enqueue a fan-out job onto the Fan-out Queue
│ (a single small message: { tweet_id, author_id, timestamp })
▼
Return HTTP 200 / OK to the poster ◄── poster is done; sees their tweet immediately
on their own profile timeline
PHASE 2 — ASYNC (background; poster doesn't see this)
──────────────────────────────────────────────────────
Fan-out Queue (durable, replicated message queue — e.g. Kafka or an internal equivalent)
│
▼
Fan-out Worker picks up the job
│
├─ 2a. "Who follows this author?" → graph service (Flock / FlockDB)
│ returns a list of follower IDs
│ (for large accounts: paginated; the list may be millions of entries)
│
▼
For each follower ID f:
ZADD home_timeline:{f} score=tweet_id member=tweet_id (Redis timeline shard)
ZREMRANGEBYRANK home_timeline:{f} 0 -(cap+1) (trim to ~800)
PHASE 3 — REAL-TIME PUSH (optional; modern clients)
─────────────────────────────────────────────────────
After ZADD completes for a follower:
│
▼
Push notification / SSE / WebSocket wake-up sent to that follower's active clients
(so the feed updates live without a manual refresh)
Why Phase 1 must be fast and Phase 2 can be slow
The reason for the split is the read:write ratio:
- The poster is one person waiting for one response. Phase 1 does the minimum durable work (store the tweet, enqueue a tiny message). It takes on the order of single-digit milliseconds.
- Fan-out affects potentially millions of people, but none of them are waiting synchronously for this write to complete. They'll see the tweet next time they load their feed (or via a push notification when Phase 3 fires). A few seconds of delivery lag is invisible to them.
This asymmetry justifies doing the expensive work (Phase 2) completely outside the poster's request lifecycle.
The fan-out queue: why it exists
The queue between Phase 1 and Phase 2 is not optional — it is the contract that makes async fan-out safe:
| Without a durable queue | With a durable queue |
|---|---|
| Phase 2 must run inside the poster's request — adds seconds of latency | Phase 2 runs whenever workers have capacity — poster's latency unaffected |
| If the fan-out service is down or slow, the tweet post fails | Tweet is durably stored; workers catch up when the service recovers |
| A spike of celebrity tweets overwhelms fan-out in real time | The queue absorbs the spike; workers drain it at their own pace |
| No retries: a failed ZADD is lost | Failed jobs can be retried from the queue without re-accepting the tweet |
The queue is essentially a shock absorber between unpredictable write bursts (a celebrity tweets → sudden spike of fan-out jobs) and a steady fleet of workers that drains the queue at a bounded rate. During a spike the queue grows; when the spike passes, workers catch up.
Fan-out workers: partitioned by author, not follower
A critical detail: fan-out jobs are partitioned (on the queue) by author ID, not by follower ID. Why?
- All tweets from author X are processed in order by the same worker partition. This preserves tweet ordering within a given author's fan-out — followers always see that author's tweets in Snowflake-ID order, never two tweets from the same author arriving swapped.
- Partitioning by follower would scatter one celebrity's fan-out across all partitions randomly, making ordering guarantees across that author's tweets much harder to enforce.
Tweet queue (partitioned by author_id):
partition A: author_1 tweets → [ T₃, T₇, T₁₂ ] → Worker A processes in order
partition B: author_2 tweets → [ T₅, T₉ ] → Worker B processes in order
partition C: author_3 tweets → [ T₂ ] → Worker C processes in order
"The fan-out queue" is really one topic, many partitions
"A single queue" is the right mental model, but the physical implementation (Kafka or an internal equivalent) isn't one ordered log — it's a topic split into P partitions, each of which is an independent ordered log with its own consumer:
Topic: fanout-jobs (1 logical queue)
├─ partition 0 → ordered log → consumed by exactly one worker in the group
├─ partition 1 → ordered log → consumed by exactly one worker in the group
├─ partition 2 → ordered log → consumed by exactly one worker in the group
└─ ...
At any instant it's a strict one worker per partition within a consumer group — never two workers pulling from the same partition concurrently, since that would let them interleave a single author's jobs and break the ordering guarantee this whole scheme exists to provide. (The reverse isn't restricted: one worker can own several partitions if P exceeds the worker count. And which worker owns a partition can change over time — crash, rebalance, autoscaling — just never more than one at once.)
A job doesn't map to a partition number directly — it's hashed:
partition = hash(author_id) % P
This is deterministic: the same author always lands in the same partition (as long as P doesn't change). That's the entire mechanism behind "processed in order by the same worker partition" above — the ordering guarantee a partitioned log gives you is only within a partition, never across the whole topic, so the partition key is what turns "global ordering is impossible at this scale" into "per-author ordering is easy for free."
How many partitions?
There's no fixed number — like the celebrity cutoff (see hybrid model), it's a capacity-planning decision, not a formula. But it's not sized the way a typical queue is sized, and the reason is specific to fan-out:
-
Partition count is a hard ceiling on parallelism. In a consumer group, at most one active consumer works a given partition at a time. Want 50 workers churning concurrently? You need ≥50 partitions, or the extra workers sit idle.
-
Size for aggregate work, not message count. A normal queue is sized off message rate — here, ~12,000 tweets/sec at peak (see why timelines are hard). But a fan-out job's cost isn't one unit of work; it's proportional to follower count. A 200-follower author's job is ~200 ZADDs; a 15,000-follower author's job (just under the hybrid model part cutoff) is ~15,000 ZADDs. So what you're really provisioning for is aggregate ZADD throughput, not job throughput:
required partitions ≈ (peak jobs/sec × avg followers/job) / (ZADDs/sec one worker can sustain)
This is also why the ~20K cutoff (see hybrid model) matters here too, not just at the push/pull decision point: it caps the worst-case single job at ~cutoff followers, so no one partition can be pinned processing one enormous job for seconds. Because ordering is per-partition, a slow job creates head-of-line blocking for every other author sharing that partition — the cutoff bounds how bad that blocking can get.
-
Overprovision for hash skew. Hashing spreads typical authors evenly, but you don't control which authors collide into the same partition. If two 15K-follower accounts land in the same partition and both spike in the same hour, that partition runs hot while others idle — the same hot-shard problem the write amplification part and the Tweet Store appendix describe, one layer up. The standard mitigation is simply more partitions than the steady-state math requires, so real load is less likely to concentrate on any one of them.
-
Repartitioning is expensive, so you round up front. Changing
Pchangeshash(author_id) % Pfor nearly every author — it breaks the "same author, same partition" invariant that ordering depends on. SoPisn't tuned casually in production; it's chosen with headroom for growth, because scaling it later means a coordinated migration (drain, remap, replay), not a config flip.
If it's one worker per partition, how does this scale at all?
If ordering forces exactly one worker per partition at any instant, it looks like the worker count is capped — but that's confusing a hard ceiling with the thing that actually flexes. Two different levers are at play, and only one of them is fixed:
P(partition count) is the ceiling — the maximum number of workers that could ever be simultaneously useful. It's fixed (expensive to change, per point 4 above).- Worker count is the elastic lever — it moves freely anywhere from 1 up to
P, and this is what actually scales minute-to-minute.
With P = 100, you could run 1 worker consuming all 100 partitions round-robin (slow, but correct), or 100 workers each owning exactly one partition (max parallelism this topic supports), or anywhere in between. This is exactly what a consumer group rebalance does: when a worker joins or leaves the group, its partitions get redistributed among whoever remains. Add workers under load → rebalance hands each worker fewer partitions → higher aggregate throughput. Remove workers as load drops → rebalance consolidates. No data moves; only the worker↔partition assignment changes, so it's cheap and fast — unlike changing P itself.
P = 100 partitions (fixed ceiling)
Low load: 10 workers → each owns ~10 partitions → lower parallelism, queue still drains
High load: 100 workers → each owns 1 partition → max parallelism this topic supports
Beyond that: 101st worker joins → no partition left to give it → sits idle
This is also the deeper reason the earlier line about Twitter "provisioning worker capacity to keep queue depth near zero" works at all: it's describing autoscaling the worker count toward P as load rises, and back down as it falls — the elastic half of the system. The wall only appears once worker count equals P and the queue is still growing — at that point there's no more parallelism left to hand out, only P independent ordered logs exist, and the only remaining options are making each worker faster per-partition (batch the ZADDs, more concurrent Redis calls per job) or increasing P itself, which is the expensive, planned-ahead operation from point 4 — not something you reach for mid-incident.
How large fan-outs (celebrities) are handled here
Recall the hybrid model part: accounts above the follower cutoff (~20K) skip fan-out entirely — their tweets are pulled at read time. But for accounts below the cutoff with still-large followings (say, 15K followers), the fan-out is a single job that does 15K ZADDs. The worker handles this sequentially: read the follower list page by page from the graph service, ZADD to each follower's timeline shard.
For accounts just under the cutoff, this single job can take hundreds of milliseconds. That's why the cutoff exists and why it matters: you don't want fan-out jobs taking seconds, because that means a tweet is "in flight" (visible to some followers but not others) for longer, widening the eventual-consistency window (see eventual consistency).
Backpressure and what happens when workers fall behind
The queue provides backpressure protection:
- If workers are processing slower than tweets arrive, the queue grows. This is visible and monitorable (queue depth is a key on-call metric).
- Workers do not block the poster's write path — the queue absorbs load silently.
- But: the deeper the queue, the longer the eventual-consistency window. A tweet from 10 minutes ago that hasn't been fanned out yet is a real inconsistency (though the tweet is still readable via the user's profile timeline, since Phase 1 stored it durably).
- Operationally, Twitter provisions worker capacity to keep queue depth near zero under normal load, with headroom for spikes. If queue depth exceeds a threshold, it's an on-call alert.
The full write path in one picture
POST /tweet (poster's HTTP request)
│
├─── 1a. mint Snowflake ID (~microseconds, no I/O)
│
├─── 1b. write to tweet store (T-bird) (~single-digit ms, durable)
│ also: send to Earlybird (~parallel, for search indexing — Section 8)
│
├─── 1c. ENQUEUE { tweet_id, author_id } (tiny message, durable queue)
│
└─── HTTP 200 to poster ◄────── poster is done
│ (queue, absorbs spikes)
▼
Fan-out Worker (async, background)
│
├─── fetch follower list from graph service
│ (paginated for large lists)
│
├─── for each follower:
│ ZADD home_timeline:{follower_id} score=tweet_id member=tweet_id
│ ZREMRANGEBYRANK ... (trim to cap)
│
└─── (optionally) fire push notification to active follower clients
Pros and cons of this queue-worker design
| ✅ Pros | ❌ Cons |
|---|---|
| Poster's latency is always fast — decoupled from fan-out cost | Eventual consistency window (see eventual consistency): followers see tweet after a lag, not instantly |
| Queue absorbs traffic spikes — celebrity tweets don't cause synchronous overload | Queue depth is an on-call concern — deep queues mean delayed delivery |
| Retryable — a failed ZADD can be retried from the queue; no data loss | Ordering requires partitioning by author — adds queue design complexity |
| Independent scaling — worker fleet scales on fan-out throughput, independent of poster request rate | Two storage writes per tweet (tweet store + queue) adds a little Phase 1 cost |
| Graceful degradation — if workers fall behind, tweets still exist in the tweet store; they're just late to timelines | Wasted work — you fan out to followers who may never read their feed |