AlgoViz

Fan-out and fan-in

medium 30 min

Fan-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

0:00 / 3:15

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

  1. 2003

    The book "Enterprise Integration Patterns" by Hohpe and Woolf names messaging patterns such as Splitter, Aggregator and Scatter-Gather.

  2. 2004

    Google's MapReduce paper appears at OSDI: map tasks in parallel, grouping by key, then reduce tasks.

  3. 2013

    Dean and Barroso publish "The Tail at Scale" in Communications of the ACM, about slow responses in large fan-outs.

  4. 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.

Step 1 of 3

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.

Four quarters, four teams, one flag
1234One map, four quarters

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

A client submits a job to an orchestrator. It puts pieces on a task queue. Four workers, each its own box, take pieces from the queue and put results on a result queue. An aggregator reads the result queue and combines the answer.
The queues separate the speed of the splitter from the speed of the workers.
  • 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

WayHowWatch out
RangesItems 1-25, 26-50, 51-75, 76-100 for four workersPieces may differ in effort
By keyA hash of the user id picks the workerA busy key overloads one worker
Round robinItem N goes to worker N modulo the number of workersIgnores how busy a worker is
Shared queueWorkers pull when they are freeOrder is lost; one more part
Plain modulo moves most keys when the number of workers changes. Consistent hashing moves few. With a queue, fast workers simply take more; see queues.

Good habits

  1. 1

    Idempotent pieces

    A piece may run twice. See idempotency.

  2. 2

    Bounded concurrency

    Use a semaphore or a worker pool, so that memory and connections survive.

  3. 3

    Timeouts

    Each piece has one, and the whole job has a deadline.

  4. 4

    Progress

    Count what is done, failed and open.

Fan-in

Four ways to combine

WayExamples
AggregateSum, count, minimum, maximum, average, other statistics
ConcatenateJoin lists, merge streams, restore the order
SelectThe first answer, the best answer, a vote
TransformGroup by key, pivot, build a graph

Four partial sums

325+950+1575+2200=5050505025+25+25+25=50.5325 + 950 + 1575 + 2200 = 5050 \qquad \frac{5050}{25+25+25+25} = 50.5
The numbers 1 to 100 split into four ranges of 25. The combined average is 50.5.

Success

Results arrive in any order. The ids tell the aggregator which is which.

Incomplete

When some results are missing

ChoiceWhat you returnGood for
Wait for allComplete result, or failurePayroll, billing, backups
DeadlineWhat has arrived by then, marked as partialSearch, price lists
QuorumA result once a majority agreesVotes, replicated reads
FallbackA default for each missing partProduct pages
Always tell the caller that a result is partial.

A piece fails

Every piece must end as done or as failed. Otherwise the aggregator waits for ever.

Retry on another worker

The late answer is a duplicate. Counting by id, not by message, keeps the total right.

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

There are two fan-outs here: one over lines, one over words.

Numbers

How much faster?

Time with workers

T≈tsplit+max⁡i(ti)+tcombine1+25+1=27 s against 100 sT \approx t_{split} + \max_i(t_i) + t_{combine} \qquad 1 + 25 + 1 = 27\ \text{s against } 100\ \text{s}
100 items of one second on 4 workers, with one second to split and one to combine. The speed-up is 100 / 27, about 3.7, and not 4.

The slow tail

1−0.99100≈63%1 - 0.99^{100} \approx 63\%
If each call is slow 1% of the time, independently, then 63% of requests that make 100 calls meet at least one slow call.

Will it all work?

0.999100≈90.5%0.999^{100} \approx 90.5\%
If each of 100 pieces succeeds 99.9% of the time and nothing is retried, almost one job in ten fails.

Choosing the size of a piece

PiecesGoodBad
Many smallEven load, cheap retriesOverhead for each piece, many messages
Few largeLittle overheadStragglers, expensive retries
Make the work of one piece much longer than the cost of handing it out, and have several pieces per worker.

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. 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. 2

    Mark each id once

    Store the result under its piece id. A duplicate changes nothing.

  3. 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. 4

    Watch the deadline

    A timer looks for jobs that are too old and retries or ends them.

When to use it

Use cases

WhereFan-outFan-in
Search engineAsk every index shardMerge and rank
Image processingTiles of a large imageStitch them
Log analyticsFiles to workersAdd up the metrics
NotificationsOne message per recipientDelivery status
PricesAsk several suppliersBest price in stock
TestsSuites on several machinesOne 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.

Sources