Pattern: parallelization

In one sentence

Run several LLM calls at once and merge them in code: sectioning splits a task into independent parts, voting runs the same task N times. You trade extra tokens for lower latency or higher confidence.

Analogy: Sectioning is a kitchen where the grill, salad and dessert stations cook one order at the same time; voting is asking three doctors for a diagnosis and acting on their agreement.

Sectioning runs different jobs at once; voting repeats one job and aggregates. Latency is the slowest branch, cost is the sum.

How it works

  • Sectioning: one focused call per aspect usually beats one call juggling every aspect.
  • Vary prompts, temperatures or models across voters; 3–5 is a common starting point.
  • Wall-clock time is the slowest branch, not the sum; tokens and cost multiply by the fan-out.
  • The real design work is the aggregator: any-of maximizes recall, majority favors precision.
  • If a step needs another's output, use Pattern: prompt chaining; if subtasks depend on the input, Pattern: orchestrator–workers.

Check yourself

Answer to mark it learned; your answers aren't scored.

A contract-review service runs one LLM call per section, ~12 in parallel. p50 latency is fine, but p99 is several times higher, and ~1% of requests fail outright when a single branch errors. Traces show no rate-limit errors. What do you add?

Go deeper

Full explanation

Parallelization runs several LLM calls concurrently and merges their outputs in code. It has two variants:

  • Sectioning: split the work into independent subtasks that you define in advance and run them side by side. One call answers the user while another screens the input for policy violations; one call per contract section; separate graders for tone, accuracy and safety. Each focused call usually beats one call juggling every aspect.
  • Voting: run the same task N times (different prompts, temperatures or models) and aggregate: majority, flag if any reviewer flags, or a threshold. This buys confidence, as in Self-consistency & best-of-N.

Wall-clock latency becomes the slowest branch instead of the sum, while tokens and cost multiply by the fan-out. The real design work is the aggregator: how to merge sections, which vote rule to use (any-of maximizes recall, majority favors precision), and what to do when a branch fails or times out.

The constraint: subtasks must be fixed and independent. If a step needs another's output, it's Pattern: prompt chaining; if the subtasks depend on the input, it's Pattern: orchestrator–workers.

Code Sectioning and voting with asyncio.gather
pythonSectioning and voting with asyncio.gather
import asyncio
from anthropic import AsyncAnthropic

client = AsyncAnthropic()
MODEL = "claude-haiku-4-5"  # focused calls rarely need the biggest model

async def llm(system: str, user: str) -> str:
    msg = await client.messages.create(model=MODEL, max_tokens=1024, system=system,
                                       messages=[{"role": "user", "content": user}])
    return msg.content[0].text

# Sectioning: different jobs on the same input, run concurrently
async def answer_with_guardrail(question: str) -> str:
    answer, verdict = await asyncio.gather(
        llm("You are a helpful support agent.", question),
        llm("Does this request violate our usage policy? Reply SAFE or UNSAFE.", question),
    )  # latency = slower of the two, not the sum
    if verdict.strip().upper().startswith("SAFE"):
        return answer
    return "Sorry, I can't help with that."  # we still paid for the answer tokens

# Voting: same job (find vulnerabilities), N diverse prompts, aggregate with a rule
LENSES = ["injection (SQL, shell, templates)", "authn/authz bypass", "secrets and crypto misuse"]

async def flag_diff(diff: str, min_votes: int = 1) -> bool:
    votes = await asyncio.gather(*[
        llm(f"Review this diff for {lens}. Reply VULNERABLE or OK.", diff) for lens in LENSES])
    flags = sum(v.strip().upper().startswith("VULNERABLE") for v in votes)
    return flags >= min_votes  # 1 = any-of: max recall, more false positives to triage
Real example

A code-review bot scans every pull request for security issues. One generic prompt caught ~60% of the seeded vulnerabilities in the team's test set. They switched to three parallel reviewers, each prompted for one class (injection, authz, secrets), flagging the PR if any reviewer flags. Recall rose to ~85% at the cost of more false positives, which a human triages. Because the calls run concurrently, review time stayed ~6 s instead of ~18 s sequentially, while token cost roughly tripled.

Trade-offs +4 · −4

+ You gain

  • Latency of the slowest branch instead of the sum of all steps.
  • Focused prompts per aspect usually beat one prompt checking everything.
  • Voting gives a confidence signal: disagreement flags the cases worth a human look.
  • Branches are fixed, so cost and behaviour stay predictable and testable.

− You pay

  • Cost multiplies by the fan-out: voting with 5 samples is ~5× the tokens.
  • Fan-out multiplies requests per minute, so rate limits bite under load.
  • Aggregating free-form text is hard: there's no majority between two essays.
  • Correlated voters (same model, same prompt) add cost, not confidence.

Use it when

Subtasks are independent and known in advance (sectioning), or a single call is too noisy for a decision you can aggregate, like a label or a flag (voting).

Avoid it when

Steps depend on each other (chain them), the subtasks depend on the input (orchestrator–workers), or outputs are free-form text with no sensible way to merge or vote.

Numbers to know 4
  • Rule of thumb: wall-clock ≈ max(branch latencies); cost ≈ sum of all branches.
  • Self-consistency (Wang et al., 2022): majority vote over ~40 sampled reasoning paths added +17.9 points on GSM8K over single-path chain-of-thought.
  • Independence math: 3 voters each catching 70% of bugs → any-of ~97%, majority ~78%. Only if their errors were independent, which they rarely are.
  • Rule of thumb: 3–5 voters is a common starting point; add more only if the eval curve still rises.
Common pitfalls 4
  • Voting with the same prompt at temperature 0: N near-identical answers, N× the cost, no new information.
  • Assuming voters are independent: same model, same blind spots. Diversify prompts, models or inputs.
  • No timeout or partial-failure policy: one slow branch sets your p99, one failed branch crashes the request.
  • Streaming the answer before the parallel guardrail returns: you show content you may have to retract.
Interview questions 2

Answer out loud first, then reveal.

You need a safety check on every chat response without adding latency. How?Show answer

I run the guardrail as a parallel section: the screening call on the input starts at the same moment as the main answer, so its latency hides behind generation. A separate, small, focused prompt also screens better than asking the main call to answer and police itself. The trade-offs: I pay for answer tokens even on requests I end up blocking, and I hold the stream until the screen returns, which often happens before the first sentence. Output-side checks run on streamed chunks.

When does voting actually help, and how do you pick the aggregation rule?Show answer

Voting helps when one call is noisy and the output is discrete or checkable (a label, a yes/no flag, a number), so outputs can be compared. It doesn't help free-form prose without a judge. The rule follows the cost of errors: in a vulnerability scan a miss is expensive, so I flag if any reviewer flags and accept more false positives; to auto-approve content I'd require a majority or unanimity. And I make voters diverse, because correlated voters just repeat the same mistake N times.