Fan-out and fan-in
medium 30 minFan-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
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
- 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
criticalThousands of calls use up connections and memory.
Wrongawait gather(*(call(i) for i in items))Rightgate = Semaphore(20)await gather(*(limited(gate, i) for i in items))Counting messages
criticalDuplicates finish the job with a hole in it.
Wrongreceived += 1if received == expected: finish()Rightopen_ids.discard(piece_id)if not open_ids: finish()Sending before saving the job
majorA fast result arrives and finds no job.
Wrongsend_all(pieces)save_expected(pieces)Rightsave_expected(pieces)send_all(pieces)Averaging averages
majorPieces of different size count the same.
Wrongmean(p.avg for p in parts)Rightsum(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.