The golden rule

Use the simplest pattern that solves the problem. Patterns stack in layers of increasing complexity and cost. Each step up adds capability, and also latency, cost and new ways to fail.

  1. 1Prompting
  2. 2RAG
  3. 3Workflows
  4. 4Agents
  5. 5Multi-agent
SituationReach for
The model already knows itPrompting
The model lacks the knowledgeRAG
You know the stepsWorkflow
You don't know the stepsAgent
One agent's context or focus breaks downMulti-agent
It touches money, email or productionHuman in the loop and guardrails

1. Prompting patterns

The cheapest layer. Exhaust these before you add infrastructure.

PatternWhen to use
Zero-shotThe task is common and well defined ("summarize this")
Few-shotOutput format or style matters: show 2 to 5 examples
Chain of thoughtReasoning tasks: math, logic, multi-step analysis
Structured outputCode consumes the result: force JSON with tool use or JSON mode
Role or system promptA consistent persona, tone or set of constraints across a session

2. RAG patterns

Use RAG when the model needs knowledge it doesn't have: private documents, fresh data, large corpora.

PatternWhen to use
Naive RAGEmbed → retrieve top k → put into the prompt. Fine for small, clean corpora
Hybrid searchVector and keyword (BM25) together. When exact terms matter: IDs, names, code
RerankingRetrieve 50, rerank to 5 with a cross-encoder. Fixes poor precision
Query rewriting, HyDERewrite the question before retrieval. For vague or conversational queries
Semantic chunkingStructural or semantic chunks beat fixed-size chunks almost always
Agentic RAGThe model decides whether and what to retrieve, possibly in rounds. For complex questions across sources

RAG in two halves

Use it when: the model needs knowledge it does not have: your documents, fresh data, a large corpus.

index time, oncedocschunksembedvectorsquery time, every questionquestionembednearestrerankto 5top 50LLMthe question goes in the prompt tooanswer +sourceshybrid search adds keywords (BM25)
  1. Once: split the documents into chunks, embed each chunk, store the vectors.
  2. Per question: embed it, fetch the nearest chunks, rerank and keep the best few.
  3. Put those chunks and the question in the prompt, and ask for sources.

The catch: retrieval decides the answer. If the right chunk is not in the top few, the model cannot use it, so measure retrieval before tuning prompts.

3. Workflow patterns

Fixed control flow with an LLM inside each step. Predictable and debuggable, so prefer these over agents whenever the steps are known.

PatternShapeWhen to use
Prompt chainingStep 1 output feeds step 2A known sequence: outline → draft → edit
RoutingA classifier sends input to a specialized prompt or modelSupport triage; cheap versus expensive model routing
Parallelization (fan-out)Split → N parallel calls → aggregateIndependent subtasks, voting, per-document processing
Evaluator-optimizerGenerator and critic loop until acceptedQuality-critical output: code review, translation
Orchestrator-workersA lead LLM decomposes and delegatesSubtasks you can't predict upfront, with one point of control

4. Agentic patterns

The LLM controls the loop. Use them only when the path can't be decided in advance.

PatternWhen to use
Tool use, function callingThe foundation: the model picks tools and arguments
ReAct loopReason → act → observe → repeat. The default agent loop
ReflectionThe agent reviews its own output and retries. Better quality at a latency cost
PlanningWrite a plan first, then execute. For long multi-step tasks
MemoryShort term (the conversation) and long term (facts, preferences). When sessions must build on each other
Human in the loopApproval gates before irreversible actions such as payments, emails and deletes. Required for high-stakes tools

Workflow or agent

Use it when: you have to choose who decides the next step: your code or the model.

workflow: you draw the arrowsLLM: outlineLLM: draftLLM: editagent: the model picksreasonact: toolobservedonepredictable, easy to debugflexible, but costlyand it can wanderknow the steps? workflow. don't? agent.
  1. Workflow: write the steps in code, with one LLM call inside each.
  2. Agent: give the model tools and let it loop: reason, act, observe.
  3. Stop the loop on "done", a step limit or a budget.

The catch: every step the model chooses is a step you cannot predict or test in advance. Prefer the workflow whenever you can write the steps down.

5. Agent collaboration patterns

"Multi-agent" is the umbrella term; the patterns below are specific shapes under it. Start with orchestrator-workers, the sensible default.

PatternStructureWhen to useMain cost
Orchestrator-workers (supervisor)A lead agent delegates; workers never talk to each otherUnpredictable subtasks, one point of controlThe supervisor's context grows with every result
Sequential pipelineA → B → C, each owns a stageKnown ordered stages, each with its own tools or contextErrors compound downstream
Evaluator-optimizerGenerator and critic loopQuality over latency, when "good" can be written down2 to 5× cost; the critic needs a rubric, not "is this good?"
Debate, ensemble votingN independent answers, then a judge or consensusHigh stakes with no ground truthMost expensive per answer; returns fall off after 3 to 5 agents
HierarchicalSupervisors managing supervisorsGenuinely large scopes, which are rareFailure modes multiply; hard to trace
SwarmPeers; any agent hands off to any other, no bossConversations that shift domain (sales ↔ billing ↔ tech)Lowest determinism and debuggability
Fan-out (map-reduce)Parallel independent calls → aggregateIndependent chunks where latency mattersAlmost none; use it freely, even inside other patterns

Fan-out, supervisor and swarm compared

Fan-out is a concurrency pattern rather than collaboration: workers never interact and can be plain prompt calls. Swarm is decentralized: routing logic lives inside each agent, and a handoff transfers the whole conversation.

Fan-outSupervisorSwarm
Who decides routingYou, in codeA central agentEach agent, locally
Workers runIn parallelParallel or sequentialOne at a time
Workers talk to each otherNeverNever (only via the supervisor)Directly, via handoff
Control returns to a centerYes (reduce step)Yes (supervisor)No, control wanders
DeterminismHighMediumLow
DebuggabilityEasyMediumHard

Who routes the work

Use it when: one agent is not enough, and you have to decide who sends work where.

fan-outsplitwwwreducesupervisorleadwwwworkers never talkswarmaaahand off the chatwho routesyour codethe leadeach agentdeterminismhighmediumlowdebuggingeasymediumhard
  1. Fan-out: your code splits the work, workers run in parallel, a reduce step joins them.
  2. Supervisor: a lead agent delegates, and every result comes back to it.
  3. Swarm: each agent decides whom to hand the conversation to.

The catch: control moves further from your code at each step to the right, and determinism and debuggability drop with it.

How agents communicate

This is a separate choice from the topology above.

  • Handoff: full control transfer; the receiving agent gets the conversation (OpenAI Agents SDK style).
  • Tool call: a sub-agent is invoked as a function and returns a result, which keeps the parent context clean (Claude and LangGraph subagent style).
  • Shared state: a graph state object or scratchpad that all agents read and write (LangGraph's core model).
  • Message passing: async messages or events between agents (AutoGen style).

The deciding factor is often isolation versus continuity. Supervisor sub-agents keep contexts isolated: the worker returns a conclusion and the parent stays clean. Swarm handoffs share the conversation history.

6. Case study: a ticket to PR coding pipeline

The shape that works is a sequential pipeline with fan-out inside the read-only stages and an evaluator loop at the end. Not a swarm, and not a free-form supervisor.

  1. Ticket
  2. Investigate fan-out, read-only
  3. Plan
  4. Human approves the plan
  5. Implement a single agent
  6. Verify fresh evaluator agents
  7. PR description
  8. Human merges

Investigate with fan-out, read-only sub-agents. This stage is search-heavy and fills context quickly. One agent traces the bug area, one maps the affected tests, one checks conventions and related PRs. Each returns a conclusion instead of file dumps, which keeps the parent context clean. The output is a written investigation doc with the root cause, relevant files, approach options and risks.

Plan behind a human approval gate. This is the highest-leverage place for a human: reviewing a plan is cheap, reviewing a wrong diff is expensive.

Implement with one agent. Code changes are deeply interdependent, and two agents editing related files produce conflicts and inconsistent assumptions. Fan out implementation only when the ticket really splits (backend, frontend, docs), and then with strict file ownership that never overlaps.

Verify with a fresh evaluator, never the implementer. An agent grading its own work is systematically lenient. Spawn fresh agents that get the ticket and the diff: one runs the tests, one reviews against conventions, one checks the acceptance criteria. Findings go back to the implementer for at most 2 or 3 rounds, then escalate to a human.

By ticket size: a small ticket gets a single agent plus a verify step, a medium ticket gets the full pipeline, and only truly parallel workstreams get fan-out implementation with strict file ownership.

The ticket to PR pipeline

Use it when: an agent writes code that people will merge.

ticketinvestigateplanyou approvethe planread-only, in parallelimplementone agentverifyat most 2 or 3 roundsPRyoumergefresh agents, never the implementermany readers, one writer, a fresh judge, two human gates
  1. Investigate with read-only agents in parallel; each returns a conclusion, not file dumps.
  2. A human approves the plan, then one agent implements it.
  3. Fresh agents verify; findings go back for at most 2 or 3 rounds, then a human merges.

The catch: an agent grading its own work is lenient, so the verifier must never be the implementer.

7. Concerns that apply to every pattern

  • Guardrails: input and output validation, prompt injection defense, PII filtering.
  • Caching: prompt caching for repeated context, semantic caching for repeated queries.
  • Evals: automated test sets plus LLM as judge. Without evals, everything else is guesswork.
  • Fallbacks and retries: model or provider fallback chains for reliability.

Hard-won warnings for multi-agent systems

  1. A single agent with good tools beats multi-agent most of the time. Add agents only when one agent's context or focus clearly breaks down.
  2. Context isolation is the real reason for sub-agents. If you're not getting that benefit, skip the pattern.
  3. Every agent boundary loses information, so write explicit contracts for what goes in and what must come back.
  4. Cost scales linearly with agents; reliability doesn't. Two agents that are each right 90% of the time, chained, are right about 81% of the time.

Framework notes

How the patterns map to LangGraph in Python and Spring AI in Java.

ConceptLangGraphSpring AI (Java)
Fan-out, map-reduceSend APIHand-rolled with CompletableFuture or structured concurrency
Orchestrator-workersSubgraphs and SendA hand-rolled supervisor loop, or a call out to a LangGraph service
Evaluator-optimizerA conditional edge looping backAdvisor chain and a custom loop
Swarmlanggraph-swarmNot native
Shared stateThe State objectManaged by the application
RAGRetriever nodesRAG Advisors
Tool callingNativeNative (@Tool, function callbacks)