Sub topic 12
Parallel fan-out and merging results
Some orchestrator tasks split into subtasks that do not depend on each other. Running them one after another wastes time. This chapter shows how to run them concurrently (fan-out) and how to combine their outputs (merging). It assumes you have read the chapters on agents as tools and the orchestrator pattern. It also assumes you know basic Python and have seen asyncio.
When fan-out applies
Fan-out means the orchestrator starts several worker calls at once and waits for them. It fits when the subtasks meet three conditions:
- Each subtask can be described without the output of another one.
- The workers do not write to the same resource.
- The orchestrator can combine the results afterwards.
Examples are researching three competitors, reviewing five files, or checking one document against several policies. If subtask B needs the answer from subtask A, run them in sequence. Starting B early only makes it guess.
The latency gain is concrete. Three workers that take 8, 10, and 6 seconds cost 24 seconds in sequence. In parallel they cost about 10 seconds, the slowest worker, plus the orchestrator's own calls. Token cost does not fall. You pay for every worker either way.
Two ways to fan out
There are two common designs.
- Model-driven. The model emits several tool calls in one reply. Most tool-calling APIs allow this. Your runtime executes all of them concurrently and appends one tool result per call.
- Code-driven. Your code decides the split, for example one worker per input file. It runs the workers and passes the results to a model for merging.
Model-driven fan-out is flexible, but the model can issue calls that depend on each other. Code-driven fan-out is predictable and easier to test. Prefer it when the shape of the work is known in advance.
A concurrent runner
The loop from earlier chapters calls the model synchronously. For fan-out you need concurrency. Model calls spend almost all their time waiting on the network, so threads work well and keep the earlier run function unchanged. The code below uses concurrent.futures and a stand-in worker so you can run it as shown.
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fake_worker(task: str) -> str:
"""Stand-in for as_tool(worker, call_model)."""
if "bad" in task:
raise ValueError(f"worker could not handle: {task}")
time.sleep(1) # simulates a model call
return f"result for {task}"
def fan_out(tasks: list[str], worker, max_workers: int = 4, timeout: float = 30.0):
"""Run worker(task) for every task concurrently.
Returns a list of dicts, one per task, in the original task order.
A failure in one worker does not cancel the others.
"""
results = [None] * len(tasks)
with ThreadPoolExecutor(max_workers=max_workers) as pool:
futures = {pool.submit(worker, t): i for i, t in enumerate(tasks)}
try:
for fut in as_completed(futures, timeout=timeout):
i = futures[fut]
try:
results[i] = {"task": tasks[i], "ok": True, "output": fut.result()}
except Exception as exc:
results[i] = {"task": tasks[i], "ok": False, "error": str(exc)}
except TimeoutError:
pass # unfinished tasks are filled in below
for i, r in enumerate(results):
if r is None:
results[i] = {"task": tasks[i], "ok": False, "error": "timeout"}
return results
if __name__ == "__main__":
start = time.time()
out = fan_out(["vendor A", "vendor B", "bad vendor", "vendor D"], fake_worker)
print(f"{time.time() - start:.1f}s")
for r in out:
print(r)Four tasks finish in about one second, not four. The bad task is reported as a failed result and the other three still return.
Note that the with block waits for running threads on exit, so a timed-out worker can still delay the function. Real model clients should have their own request timeout as well. The timeout here limits how long you wait for collecting results, not how long a thread runs.
Keep results in order and labeled
Results arrive in completion order, not the order you launched them. If you append them to the message history as they arrive, the history differs from run to run, which makes tests and traces hard to compare. The runner above writes each result into the slot of its task index. This gives a stable order.
Label every result with the task that produced it. A merging model that sees five unlabeled paragraphs cannot tell which vendor each one describes.
Merging results
Merging is where most fan-out designs go wrong. There are three strategies.
| Strategy | How it works | Use when | Risk |
|---|---|---|---|
| Concatenate | Join outputs in order with labels | Sections of a report, one per item | No reconciliation of overlap |
| Reduce in code | Compute from structured outputs, such as a sum, a vote, or a union | Workers return numbers, labels, or lists | Needs a fixed output schema |
| Model merge | A model reads all outputs and writes one answer | Outputs overlap, conflict, or need rewriting | Cost, and it can drop or invent details |
Reducing in code is the most reliable, so use it whenever the outputs can be structured. Ask each worker for JSON with fixed fields, validate it, and then combine it in code.
import json
from collections import Counter
def merge_votes(results: list[dict]) -> dict:
"""Each worker returned JSON like {"label": "approve", "confidence": 0.8}."""
labels, skipped = [], []
for r in results:
if not r["ok"]:
skipped.append({"task": r["task"], "reason": r["error"]})
continue
try:
data = json.loads(r["output"])
labels.append(data["label"])
except (json.JSONDecodeError, KeyError, TypeError):
skipped.append({"task": r["task"], "reason": "malformed output"})
if not labels:
return {"decision": None, "skipped": skipped}
winner, count = Counter(labels).most_common(1)[0]
return {
"decision": winner,
"agreement": count / len(labels),
"skipped": skipped,
}The function never discards a failure silently. It reports each skipped worker in the merged output, so the caller can decide whether the result is trustworthy.
Merging with a model
When you need prose, give the merging model the labeled results and tell it how to handle gaps. A prompt like the following works:
You are given results from independent workers. Each is labeled with its task.
Combine them into one answer. Keep claims attributed to their task.
If two results disagree, report both and say they disagree.
If a result is marked FAILED, say that part is missing. Do not guess it.The last two lines matter. Without them, a merging model tends to smooth over conflicts and fill gaps with plausible text.
Partial failure
With several workers, some will fail. Decide the policy before you write the code.
- All required. Any failure fails the whole request. Use this when the answer is meaningless with a piece missing.
- Quorum. Proceed if at least N of M workers succeed, such as 2 of 3 reviewers.
- Best effort. Proceed with whatever returned and state what is missing.
Retries belong at the single-worker level, as described in the failure-handling chapter. Retrying the whole fan-out repeats the work that already succeeded and its cost.
Limits and guards
Fan-out multiplies every earlier risk by the width of the fan-out.
- Cap the width. Do not let the model choose an unbounded number of tasks. A request like "check every row" could create thousands of workers. Enforce a maximum in code and use
max_workersto limit concurrent calls. - Respect rate limits. Parallel calls hit provider limits sooner. A burst of 429 errors turns a latency optimization into a failure source. Use a bounded pool and retry with backoff.
- Budget the tokens. Total cost is roughly the sum over all workers. Set a token or call budget for the whole run, not only per worker.
- Keep depth bounded. A worker that fans out again produces width times width. Do not give workers the ability to spawn more workers unless you cap total calls.
- Avoid shared writes. If two workers edit the same file or record, the final state depends on timing. Give workers read-only tools, and apply changes in the merge step.
Workers are also a trust boundary. A worker that reads web pages can return text with injected instructions, and the merge step then reads that text. Treat worker output as data, and keep it in a clearly separated, labeled section of the merge prompt.
Common errors
- Fanning out dependent tasks, so workers invent inputs they should have received.
- Appending results in completion order, which makes runs non-reproducible.
- Dropping failed workers without telling the merge step.
- Letting a model merge numeric results instead of computing them in code.
- Using no timeout, so one stalled worker blocks the entire answer.
Exercise
An orchestrator fans out three reviewers in parallel. Their JSON verdicts are "approve", "approve", and a timeout. Using the merge_votes function, what does it return for "decision" and "agreement", and what should the orchestrator do next under a 2-of-3 quorum policy?
Show answer
merge_votes counts only the two successful labels, so decision is "approve" and agreement is 1.0 (2 of 2). The timed-out worker appears in "skipped" with reason "timeout". Under a 2-of-3 quorum, two successes meet the threshold, so the orchestrator may proceed, but it should report that one reviewer did not respond. Note that agreement 1.0 is computed over successes only, so the caller should also check the number skipped.
Exercise
Why does the fan_out function store each result at its task's index instead of appending results as futures complete?
Show answer
Futures complete in a timing-dependent order. Writing to the task's index gives the same result order on every run, which keeps traces comparable, tests stable, and lets the merge step match each result to the task that produced it.