Fan-out and fan-in
medium 30 minFan-out splits work into pieces and gives them to several workers at once.
Video lesson · Chapter 1 of 5
Four survey crews count a hundred trees
Theory
Read or listen first. About 2 min.
What it is
Fan-out means that one task becomes many. A request is sent to several workers or services at the same time. Fan-in means that many results become one. Somebody collects them, checks that they are complete, and combines them.
The pair appears in many sizes: a few parallel calls inside one web request, a thousand messages on a queue, or a data job over many machines. The parts are always the same: a splitter, workers, and an aggregator that knows how many results to expect.
Why it exists
Work that can be split should not wait in line. If 100 items take one second each, one worker needs 100 seconds and four workers need about 25. The same is true when a page needs data from five services: ask all five at once, and wait only for the slowest.
There is a catch. The whole is as slow as its slowest part and as reliable as all parts together. So the pattern is less about starting many tasks than about limits, timeouts, retries and knowing when you are done.
A short history
2003
The book "Enterprise Integration Patterns" by Hohpe and Woolf names messaging patterns such as Splitter, Aggregator and Scatter-Gather.
2004
Google's MapReduce paper appears at OSDI: map tasks in parallel, grouping by key, then reduce tasks.
2013
Dean and Barroso publish "The Tail at Scale" in Communications of the ACM, about slow responses in large fan-outs.
13 March 2014
The Go blog explains fan-out and fan-in with channels, under exactly those names.
Words to know
- Fan-out
- Splitting or copying work to many workers.
- Fan-in
- Collecting and combining their results.
- Orchestrator
- The part that splits, waits and combines.
- Straggler
- A piece that takes much longer than the others.
- Bounded concurrency
- A limit on how many pieces run at once.
- Scatter-gather
- Ask several services the same thing and merge the answers.
- Dead letter queue
- Where a piece goes after its last failed try.
How it works
Step through the idea, or press Play.
Split. Cut the work into independent pieces with ids
Understand it
Start here
The treasure hunt
A field hides one coin in each of its four quarters. One child would search all day. So Noor cuts the map into four pieces, gives one to each team, and waits for them at the flag.
The prize can be shared only when the last quarter is done.
The idea
Split, work, combine
Fan-out through one queue, fan-in through another
Fan-out
Cut the work by data, by task type, or in turn.
Fan-in
Merge, sum or reduce the results.
Parallelism
Time falls from all pieces in a row towards the slowest share.
Fault tolerance
A failed piece is tried again elsewhere. The other pieces go on.
Fan-out
Four ways to split
| Way | How | Watch out |
|---|---|---|
| Ranges | Items 1-25, 26-50, 51-75, 76-100 for four workers | Pieces may differ in effort |
| By key | A hash of the user id picks the worker | A busy key overloads one worker |
| Round robin | Item N goes to worker N modulo the number of workers | Ignores how busy a worker is |
| Shared queue | Workers pull when they are free | Order is lost; one more part |
Good habits
- 1
Idempotent pieces
A piece may run twice. See idempotency.
- 2
Bounded concurrency
Use a semaphore or a worker pool, so that memory and connections survive.
- 3
Timeouts
Each piece has one, and the whole job has a deadline.
- 4
Progress
Count what is done, failed and open.
Fan-in
Four ways to combine
| Way | Examples |
|---|---|
| Aggregate | Sum, count, minimum, maximum, average, other statistics |
| Concatenate | Join lists, merge streams, restore the order |
| Select | The first answer, the best answer, a vote |
| Transform | Group by key, pivot, build a graph |
Four partial sums
Success
Incomplete
When some results are missing
| Choice | What you return | Good for |
|---|---|---|
| Wait for all | Complete result, or failure | Payroll, billing, backups |
| Deadline | What has arrived by then, marked as partial | Search, price lists |
| Quorum | A result once a majority agrees | Votes, replicated reads |
| Fallback | A default for each missing part | Product pages |
A piece fails
Retry on another worker
Shapes
Four common patterns
MapReduce
Map pieces in parallel, shuffle by key, reduce each key. See MapReduce.
Scatter-gather
Send one question to several services and merge the answers, or pick the best.
Fork-join
Split a task inside one program, run the parts, wait for all.
Work queue
A producer adds pieces, many consumers take them, results are combined.
Word count as fan-out and fan-in
Numbers
How much faster?
Time with workers
The slow tail
Will it all work?
Choosing the size of a piece
| Pieces | Good | Bad |
|---|---|---|
| Many small | Even load, cheap retries | Overhead for each piece, many messages |
| Few large | Little overhead | Stragglers, expensive retries |
Limits
Protect what is behind
A fan-out of 1,000 sends 1,000 calls to the same database. A semaphore lets only so many run at once. Workers that are waiting hold nothing. Running batches one after the other is simpler, but every batch waits for its slowest item.
Batches or a sliding limit?
Completion
How do you know that you are done?
- 1
Save the expected set first
Write the job with all piece ids before the first piece is sent. Otherwise an early result finds no job.
- 2
Mark each id once
Store the result under its piece id. A duplicate changes nothing.
- 3
Finish when no id is open
Check in the same transaction as the last mark, so that two workers do not both finish the job.
- 4
Watch the deadline
A timer looks for jobs that are too old and retries or ends them.
When to use it
Use cases
| Where | Fan-out | Fan-in |
|---|---|---|
| Search engine | Ask every index shard | Merge and rank |
| Image processing | Tiles of a large image | Stitch them |
| Log analytics | Files to workers | Add up the metrics |
| Notifications | One message per recipient | Delivery status |
| Prices | Ask several suppliers | Best price in stock |
| Tests | Suites on several machines | One report |
Use it for
- Large data that can be cut
- Several independent sources
- Processor-heavy work with free cores
- Batches of independent items
Avoid it for
- Steps that depend on one another
- Small work, where the overhead is larger than the gain
- A backend that is already full
- Changes that must be atomic: see saga
Performance
- N workers give at most N times the speed
- Limit concurrency
- Keep coordination small
- Balance the pieces
Reliability
- Idempotent pieces
- Retry with backoff
- A dead letter queue
- A timeout everywhere
Between services, the calls of a scatter-gather follow the rules of microservice communication.
Summary
The whole topic in one minute.
Fan-out turns one task into many that run in parallel. Fan-in turns many results into one. Split by ranges, by key, in turn, or through a shared queue. Combine by adding, joining, choosing or regrouping.
Speed is limited by the slowest piece and by the part that cannot be split. Put a limit on concurrency, a timeout on each piece and a deadline on the whole. Make pieces idempotent, retry them, count results by id, and decide in advance what to do when some never come.
- Fan-out splits, workers run in parallel, fan-in combines.
- The slowest piece sets the time, and all pieces together set the reliability.
- Bound concurrency, set timeouts and a deadline.
- Collect by piece id, so retries and duplicates are harmless.
- Decide what a partial result means before you need it.