AlgoViz

Fan-out and fan-in

medium 30 min

Fan-out splits work into pieces and gives them to several workers at once.

See it run

Sum the numbers 1 to 100 with four workers, then break things.

Operations

Success

Four pieces of 25 numbers.

Step 1 of 6

Request received

Orchestrator100 itemsWorker 1idleWorker 2idleWorker 3idleWorker 4idleAggregatoridle

One big task

The orchestrator has 100 items to process.

Step 1: Request received

def job(items):    pieces = split(items, 4)    save_expected(pieces)    for p in pieces:        send(p)    results = wait_for_all(pieces)    return combine(results)
Parallel part
Slowest piece
Result
Complete
One worker
four times the work in a row

Return the sum and the count, so that the average can be combined.

In the real world

The same fan-out and fan-in doing real jobs. Pick one and step through it.

More workers, the same database behind them.

Step 1 of 4

Two workers

OrchestratorwaitingWorker 1runningWorker 2runningAggregatoridle
Database
40%

Good

The database is at 40%.

Step 1: Two workers

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • No limit

    critical

    Thousands of calls use up connections and memory.

    Wrong
    await gather(*(call(i) for i in items))
    Right
    gate = Semaphore(20)await gather(*(limited(gate, i) for i in items))
  • Counting messages

    critical

    Duplicates finish the job with a hole in it.

    Wrong
    received += 1if received == expected: finish()
    Right
    open_ids.discard(piece_id)if not open_ids: finish()
  • Sending before saving the job

    major

    A fast result arrives and finds no job.

    Wrong
    send_all(pieces)save_expected(pieces)
    Right
    save_expected(pieces)send_all(pieces)
  • Averaging averages

    major

    Pieces of different size count the same.

    Wrong
    mean(p.avg for p in parts)
    Right
    sum(p.sum for p in parts) / sum(p.count for p in parts)

Interview tips

  • How to explain it

    • One task becomes many.
    • They run at once.
    • Many results become one.
  • Memory trick: FOFI

    • Fan work Out to workers.
    • Fan results In and aggregate.
  • Always mention

    • The slowest piece.
    • A limit and a deadline.
    • Completion by id.
  • Avoid it when

    • Steps depend on each other.
    • The work is tiny.
    • The backend is full.