Skip to content

    Agentic AI for Java

    Multi-Agent Systems: Orchestrator, Workers and Handoffs

    Split one Java agent into an orchestrator and specialists, compare agent-as-a-tool with handoffs, count the extra model calls, and learn when not to split.

    By Published 24 min read

    Share

    This lesson is part of Agentic AI for Java Developers: Build and Ship Agents. Enroll for free, then sign in, to read it in full.

    What you'll learn: how to build an orchestrator with specialist agents, wire them as tools, as a handoff, through shared state and through an event bus, count what the split costs in model calls, and apply a decision rule for when one agent is the better design.

    When one agent starts to feel crowded

    Your on-call agent from the last lessons has four tools and one prompt, and it solves the Parcelo incident in four model calls. Then someone says: "Let's make it a team. A logs expert, a metrics expert, a runbook expert, and a lead who coordinates them." It sounds wise. Real teams work that way, and the diagrams look impressive.

    This lesson builds that team in plain Java, runs it on the same incident, and counts. The single idea: splitting an agent is an engineering trade, not an upgrade. It buys you narrower permissions, separate contexts and independent deployment, and it costs you model calls, failure modes and test effort. We build the team four ways so you can see each cost, then settle on a rule for when it is worth it.

    NOTE

    Invented example. Parcelo is a made-up delivery company; its services, alerts and incident are invented for this course. Every model in the lab is a script that plays fixed replies, so the output is reproducible. A real orchestrator would phrase its tasks differently, might skip a specialist or ask one twice, and a real specialist might need more steps. The counts in this lesson show the structure of a team, not what a real model would do.

    The idea in one picture

    Figure 1. An orchestrator hands tasks to specialists, and each specialist has only its own tools

    An orchestrator delegates to three specialist agents, each with its own narrow tool setGoal to Orchestrator; Orchestrator to Logs agent (task as text); Orchestrator to Metrics agent; Orchestrator to Runbook agent; Logs agent to search_logs; Metrics agent to Metrics tools; Runbook agent to search_runbookGoal: alert A-1042Goalalert A-1042Orchestrator: splits the taskOrchestratorsplits the taskLogs agent: own promptLogs agentown promptMetrics agent: own promptMetrics agentown promptRunbook agent: own promptRunbook agentown promptsearch_logs: its only toolsearch_logsits only toolMetrics tools: two toolsMetrics toolstwo toolssearch_runbook: its only toolsearch_runbookits only tooltask as text

    How to read this: follow the packets from the goal to the lead and out to the three specialists. The orchestrator itself holds no domain tools; each specialist can reach only the tools on its own right-hand side.

    Anthropic's article "Building effective agents", which I fetched while writing this lesson, names this shape the orchestrator-workers workflow: a central LLM "dynamically breaks down tasks, delegates them to worker LLMs, and synthesizes their results", well suited to "complex tasks where you can't predict the subtasks needed." Notice the condition in the second half of that sentence. If you can predict the subtasks, the previous lesson's patterns do the job with less risk.

    TIP

    Picture it: a newsroom. The editor-in-chief receives a story, sends one reporter to the council, another to the courts and a third to the archive, then writes the final article from what they bring back. Each reporter has a press pass for their own building only. Where the picture stops: reporters are people who can push back or ask a clarifying question. Here a specialist sees only the text of its task, nothing else.

    A specialist is an ordinary agent with a narrow job

    There is no new machinery in a specialist. It is the Agent from the agent-loop lab: a model, a loop, a step budget and a tool set. What makes it a specialist is that all four are small and chosen on purpose.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/Specialist.java

    public record Specialist(String name, String description, Agent agent) {
    
        private static final int MAX_STEPS = 4;
    
        public static Specialist logs(ChatModel model) {
            return new Specialist("logs_agent", "Searches the logs of one service for a text and reports what it finds.",
                    new Agent(model, Tools.of(Parcelo.searchLogs()),
                            new AgentConfig("You are the logs specialist. Search the logs for what you are asked, then report in one sentence.", MAX_STEPS)));
        }

    The logs specialist is given one tool, search_logs. If its model asks for roll_back, the registry has no such tool and the loop returns an error result: the model cannot do what the code never offered. The metrics specialist gets get_alert and query_metric; the runbook specialist gets search_runbook. Each also has a step budget of four, so one confused specialist cannot run forever.

    That narrow tool set is the strongest argument for splitting, and it is a security argument, not an intelligence one. The lab has a test for it: a logs agent whose script asks for roll_back gets back unknown tool 'roll_back'. Available tools: search_logs.

    Agent as a tool: the answer comes back to the caller

    The simplest way to connect an orchestrator to a specialist is to make the specialist look like a tool. The orchestrator calls ask_logs_agent(task=...). Behind that name, plain Java runs a whole second agent loop and returns its final answer as the tool result. To the orchestrator it is just another function that returned text.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/AgentTool.java

    @Override
    public ToolSpec spec() {
        return new ToolSpec("ask_" + specialist.name(), specialist.description(),
                List.of(ToolSpec.required("task", ToolSpec.Type.STRING,
                        "What to find out, in one or two sentences. The specialist sees only this text, not your conversation.")));
    }
    
    @Override
    public String execute(Map<String, Object> arguments) {
        AgentResult result = specialist.agent().run((String) arguments.get("task"));
        runs.add(result);
        if (result.stop() != AgentResult.Stop.FINAL_ANSWER) {
            throw new IllegalStateException(specialist.name() + " stopped without an answer (" + result.stop() + " after " + result.steps() + " model calls)");
        }
        board.post(specialist.name(), result.answer());
        return result.answer();
    }

    Four things to notice. The tool takes one parameter, task, and its description says the specialist sees only that text: a specialist starts with an empty conversation, so the task must carry everything it needs. The call to agent().run is a complete agent run, with its own model calls.

    A specialist that stops without an answer throws, and the loop you already know turns an exception into an error result the orchestrator can read. And on success the answer is also posted to a shared board, which we come to shortly.

    The orchestrator is then an Agent whose tool list is the three AgentTools and nothing else.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/Demo.java

    List<AgentTool> tools = List.of(
            new AgentTool(Specialist.logs(models.get("logs_agent")), board),
            new AgentTool(Specialist.metrics(models.get("metrics_agent")), board),
            new AgentTool(Specialist.runbook(models.get("runbook_agent")), board));
    List<Tool> all = new ArrayList<>(tools);
    all.addAll(extraTools);
    return new Team(orchestratorModel, models, tools, board, new Agent(orchestratorModel, new Tools(all), new AgentConfig(LEAD_PROMPT, 4)));

    Seen from outside, the call is a round trip: the answer comes back to the orchestrator, and the orchestrator decides what the user reads.

    Figure 2. Agent as a tool: the specialist's answer returns to the orchestrator, which writes the reply

    Agent as a tool: the specialist returns its answer to the orchestrator, which replies to the userUser to Orchestrator; Orchestrator to Specialist (task text); Specialist to Orchestrator (answer); Orchestrator to User (its own reply)User: asks onceUserasks onceOrchestrator: stays in chargeOrchestratorstays in chargeSpecialist: returns an answerSpecialistreturns an answertask textanswerits own reply

    How to read this: the answer makes a round trip through the orchestrator, which may combine it with others or reword it before the user sees anything.

    Handoff: control moves, the specialist answers

    Figure 3. Handoff: triage transfers once, and the specialist answers the user

    Handoff: triage transfers once and the specialist answers the user directlyUser to Triage; Triage to Specialist (transfer); Specialist to User (answers user)User: asks onceUserasks onceTriage: one turn, then outTriageone turn, thenoutSpecialist: takes overSpecialisttakes overtransferanswers user

    How to read this: triage is out of the picture after one turn. The specialist's words go straight to the user, unchanged.

    TIP

    Picture it: a hospital. A GP who calls a cardiologist for advice and then tells you the result herself is "agent as a tool". A GP who writes a referral, after which you sit in the cardiologist's room and talk to her directly, is a "handoff". After a referral your GP no longer controls what you are told. Where the picture stops: a hospital hands over records; here the specialist sees only the question and a one-line note.

    The lab's Handoff class gives a triage model one transfer_to_<specialist> tool per specialist and one turn. If it asks for a transfer, the specialist runs and its answer is the answer.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/Handoff.java

    public Result answer(String question) {
        List<String> trace = new ArrayList<>();
        List<ToolSpec> offered = specialists.keySet().stream().map(Handoff::transferSpec).toList();
        ModelReply reply = triage.reply(List.of(new Message.Instruction(TRIAGE_PROMPT), new Message.User(question)), offered);
    
        return switch (reply) {
            case ModelReply.FinalAnswer done -> {
                trace.add("triage answers by itself");
                yield new Result("triage", done.text(), trace);
            }
            case ModelReply.ToolRequest request -> transfer(request.calls().get(0), question, offered, trace);
        };
    }

    Triage is asked once. A plain answer means it handled the question itself. A tool request is a transfer, and transfer checks that the named specialist exists and the reason argument is valid before anything is handed over. A transfer to a specialist that does not exist hands nothing over, and a test covers that too.

    The choice between the two connections is a design question about who owns the final answer. If the answer must combine several specialists, or must follow a house style, the orchestrator must own it, so use agent as a tool. If one specialist should simply take the conversation, a handoff saves the orchestrator's second call and keeps the specialist's exact words.

    Shared state: a blackboard

    Specialists that never see each other's work can still share it. A blackboard is a small shared record where each agent posts its finding under its own name, and any later agent can read the board instead of asking again. The lab's version keeps the latest post of each author.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/Blackboard.java

    public synchronized void post(String author, String text) {
        byAuthor.put(author, text);
    }
    
    public synchronized List<Entry> entries() {
        List<Entry> entries = new ArrayList<>();
        byAuthor.forEach((author, text) -> entries.add(new Entry(author, text)));
        return entries;
    }
    
    /** A tool that lets an agent read the board: one line per author, "author: finding". */
    public Tool readTool() {
        return new FunctionTool(
                new ToolSpec("read_board", "Returns the findings that other agents have already posted, one line per agent.", List.of()),
                args -> {
                    List<Entry> entries = entries();
                    if (entries.isEmpty()) return "the board is empty";
                    return String.join(" | ", entries.stream().map(e -> e.author() + ": " + e.text()).toList());
                });
    }

    The methods are synchronized because specialists may one day run at the same time. A second post by the same author replaces the first, so the board always shows the latest finding per author and who wrote it. That choice has a cost: an old finding can be out of date, and the board does not say how old it is. A real design would add a timestamp, a version or an expiry.

    TIP

    Picture it: the whiteboard in an incident room. Each person writes what they found, with their initials, and anyone who walks in later reads the board instead of interrupting people to ask. If someone rubs out an old line without dating the new one, the board quietly lies. Where the picture stops: this board keeps only the latest line per person, and a real one would also say when it was written.

    Figure 4. A blackboard: specialists post once, and a later question reads the board

    Specialists post findings to a blackboard and a follow-up question reads itLogs agent to Blackboard (post); Metrics agent to Blackboard; Runbook agent to Blackboard; Follow-up to Orchestrator; Blackboard to Orchestrator (read_board)Logs agent: posts findingLogs agentposts findingMetrics agent: posts findingMetrics agentposts findingRunbook agent: posts findingRunbook agentposts findingBlackboard: latest per authorBlackboardlatest per authorFollow-up: which deploy?Follow-upwhich deploy?Orchestrator: reads, answersOrchestratorreads, answerspostread_board

    How to read this: the specialists write on the left; the follow-up question on the right does not ask them again, it reads the board. That is why Run 3 below costs 2 model calls and not 8.

    Messages between agents: an in-memory event bus

    Calling a specialist as a function, as AgentTool does, ties the two together in one process: the orchestrator waits for the specialist, and if either crashes both are gone. When agents are owned by different teams, scale independently or must survive a restart, the usual answer is a message broker with topics, such as Kafka. The site has a long article on exactly that design: I Rebuilt Our AI Agents on Kafka Instead of REST.

    I read it while writing this lesson; it argues that point-to-point HTTP between agents becomes brittle as the number of agents grows and puts every agent decision on a topic instead.

    This lab cannot run Kafka (it needs a broker and a network), so it uses a clearly labelled stand-in: an EventBus with topics, subscribers and an ordered log, nothing else.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/EventBus.java

    public void subscribe(String topic, Consumer<Event> consumer) {
        subscribers.computeIfAbsent(topic, t -> new ArrayList<>()).add(consumer);
    }
    
    public void publish(Event event) {
        log.add(event);
        for (Consumer<Event> consumer : List.copyOf(subscribers.getOrDefault(event.topic(), List.of()))) {
            consumer.accept(event);
        }
    }
    WARNING

    This class is not a broker. It has no persistence (a restart loses every event), no partitions, no consumer groups, no acknowledgements, no retries and no back-pressure. Delivery is synchronous in the publisher's thread and it is not thread-safe. Use it to learn the shape of event-driven agents. When messages must survive a crash, use a real broker.

    A BusWorker puts a specialist behind it: it listens on tasks.<name>, runs its agent on the payload, and publishes the answer on results.<name> with the same correlation id, which ties a result to its task. A task that fails goes to dead-letter. And because real brokers commonly deliver at least once, the same event can arrive twice, so the worker remembers the ids it has handled.

    Verified: examples/backend/labs/agent-multi/src/main/java/buildingai/labs/multi/BusWorker.java

    private void onTask(EventBus.Event task) {
        if (!handled.add(task.id())) return;
        AgentResult result = specialist.agent().run(task.payload());
        if (result.stop() == AgentResult.Stop.FINAL_ANSWER) {
            bus.publish(new EventBus.Event("r-" + task.id(), resultTopic(specialist.name()), task.correlationId(), result.answer()));
        } else {
            bus.publish(new EventBus.Event("d-" + task.id(), "dead-letter", task.correlationId(), specialist.name() + " gave no answer"));
        }
    }

    The first line is the whole idempotency story: handled.add returns false for an id seen before, and the duplicate is ignored. Without it a duplicated delivery runs the agent, and its tools, twice.

    NOTE

    On call, 3 a.m.: Lena, at an invented insurer, had a specialist agent that drafted a customer letter whenever a task event arrived. The broker redelivered one event after a restart, the agent ran twice, and one customer received two letters with slightly different wording. Her team added the id check you see above, plus a store of handled ids that survived restarts, which this lab's in-memory set does not. Invented example.

    Figure 5. The same specialists behind a bus: events in, events out, failures to a dead-letter topic

    Specialists behind an event bus: tasks in, results out, failures to a dead-letter topicOrchestrator to Event bus (tasks.name); Event bus to Specialist workers (task event); Specialist workers to Event bus (results.name); Event bus to Orchestrator (result events); Specialist workers to dead-letter (dead-letter)Orchestrator: publishes tasksOrchestratorpublishes tasksEvent bus: in-memory stand-inEvent busin-memorystand-inSpecialist workers: one per topicSpecialistworkersone per topicdead-letter: gave no answerdead-lettergave no answertasks.nametask eventresults.nameresult eventsdead-letter

    How to read this: the flowing dashes are events travelling between agents. No agent calls another directly; they only know topics. The red dashed arrow is the dead-letter path for a task nobody could answer.

    TIP

    Picture it: an office mail room with a pigeonhole per team. You do not walk to the cardiology team; you put a note in their pigeonhole with your name on it and later find their reply in yours. This lab's bus is a cardboard box on your own desk, which shows the idea and loses everything if the cleaner tips it over. A real broker is the mail room with a lock, a log and a night shift.

    Run it

    From examples/backend:

    ./gradlew :labs:agent-multi:test       # 16 tests
    ./gradlew -q :labs:agent-multi:run     # six runs: single agent, orchestrator, blackboard, handoff, failure, event bus

    The first two runs do the same job. The single agent is the four-call investigation from the agent-loop lab. The team is an orchestrator plus three specialists called as tools.

    Expected output, captured from a real run (runs 1 and 2: the single agent, then the orchestrator's trace):

    Parcelo is an invented company; every model below is a script.
    
    Run 1. One agent with all four read-only tools
      stop: FINAL_ANSWER
      model calls: 4
      messages sent to the model: 22
    
    Run 2. An orchestrator calls three specialists as tools (agent as a tool)
      the orchestrator's trace (it sees only the specialists' answers):
        step 1  model   asks for ask_logs_agent(task=Find the latest deploys of payments-gateway.)
        step 1  tool    ask_logs_agent -> payments-gateway deployed v412 at 02:41:05 (previous version v411) and reported healthy at 02:41:40.
        step 1  model   asks for ask_metrics_agent(task=Read alert A-1042 and the database pool metric of payments-gateway.)
        step 1  tool    ask_metrics_agent -> checkout-api p99 is 4200 ms against an 800 ms SLO since 02:47; payments-gateway has had 50 of 50 database connections in use since 02:44.
        step 1  model   asks for ask_runbook_agent(task=What does the runbook say about pool exhaustion?)
        step 1  tool    ask_runbook_agent -> Check for a deploy in the last hour; if there is one, roll it back (needs on-call approval); if not, restart the service (needs on-call approval).
        step 2  final   Likely cause: the payments-gateway deploy v412 at 02:41 exhausted its database pool (50 of 50 in use). Suggested action: roll back to v411, which needs on-call approval.

    Read the orchestrator's trace first. It makes three requests in step 1, one per specialist, and each result is just the specialist's final sentence: ask_logs_agent -> payments-gateway deployed v412 at 02:41:05 .... In step 2 it writes the final answer, which is word for word the single agent's answer. The team answered the same question the same way. Now look inside one specialist.

    Expected output, captured from a real run (inside the logs specialist):

      inside logs_agent (its own agent, its own tools):
        step 1  model   asks for search_logs(service=payments-gateway, text=deploy)
        step 1  tool    search_logs -> 02:41:05 INFO deploy v412 started (previous version v411) | 02:41:40 INFO deploy v412 reported healthy
        step 2  final   payments-gateway deployed v412 at 02:41:05 (previous version v411) and reported healthy at 02:41:40.

    The logs specialist ran its own loop: one tool call, then a final answer, two model calls. The other two specialists did the same, so the totals are below.

    Expected output, captured from a real run (the cost of the split):

      model calls: orchestrator 2, logs_agent 2, metrics_agent 2, runbook_agent 2; total 8
      messages sent to the models, all agents together: 27
      compared with one agent: 8 model calls instead of 4
      the blackboard now holds: [logs_agent, metrics_agent, runbook_agent]

    Eight model calls instead of four, and 27 messages sent to models instead of 22. The messages figure counts conversation entries, not tokens: every call re-sends its whole conversation, so it is a rough stand-in for input size. It does not say how long the messages are.

    Three runs of the team, step by step (interactive when JavaScript is on)

    Agent as a tool

    1. 1. Three tasks. The orchestrator's first reply asks for ask_logs_agent, ask_metrics_agent and ask_runbook_agent, each with a task as text.
    2. 2. Specialists run. Each specialist runs its own loop with its own tools: two model calls each (one tool call, then a final sentence).
    3. 3. Answers come back. Each specialist's final sentence returns to the orchestrator as a tool result.
    4. 4. Final answer. In step 2 the orchestrator answers: Likely cause: the payments-gateway deploy v412 at 02:41 exhausted its database pool (50 of 50 in use).
    5. 5. The bill. Model calls: orchestrator 2, logs_agent 2, metrics_agent 2, runbook_agent 2; total 8. One agent used 4.

    Handoff

    1. 1. Triage asks. Triage asks for transfer_to_runbook_agent with the reason: the user asks what the runbook says.
    2. 2. Control passes. The log says control passes to runbook_agent. Triage is not called again.
    3. 3. Specialist answers. The runbook specialist answers the user directly: Check for a deploy in the last hour; if there is one, roll it back (needs on-call approval)...
    4. 4. The bill. Model calls: triage 1, specialist 2; total 3. The agent-as-a-tool version of the same question used 4.

    A specialist gives up

    1. 1. Logs agent loops. The logs specialist's script asks for the same search again and again, and its budget of 4 steps runs out.
    2. 2. An error result. The orchestrator receives: the tool failed: logs_agent stopped without an answer (STEP_LIMIT after 4 model calls).
    3. 3. Partial answer. The orchestrator answers: Partial answer: the logs agent failed, so a deploy is unconfirmed.
    4. 4. The bill. Model calls: orchestrator 2, logs_agent 4, metrics_agent 2, runbook_agent 2; total 10, against 8 when nothing fails. Messages sent: 41.

    What splitting costs: how the calls multiply

    Every specialist run is a complete agent loop with at least one model call of its own, and the orchestrator needs calls to delegate and to combine. So the number of calls is the orchestrator's plus the sum of the specialists', not a share of a fixed total.

    Figure 6. Where the eight calls come from, against four for one agent

    The calls of a team: two for the orchestrator and two for each of three specialistsOrchestrator to Logs agent (ask); Orchestrator to Metrics agent; Orchestrator to Runbook agent; Logs agent to Team total; Metrics agent to Team total; Runbook agent to Team totalOrchestrator: 2 model callsOrchestrator2 model callsLogs agent: 2 model callsLogs agent2 model callsMetrics agent: 2 model callsMetrics agent2 model callsRunbook agent: 2 model callsRunbook agent2 model callsTeam total: 8 model callsTeam total8 model callsOne agent: 4 model callsOne agent4 model callsask

    How to read this: the orchestrator's own two calls and each specialist's two add up to eight. The green box is the single agent that answered the same question in four.

    Here is the whole lab side by side. All counts are from the Demo, and the model is a script.

    Design Model calls Who writes the answer New failure modes
    One agent, four tools 4 The agent None beyond the loop's own
    Orchestrator, agent as a tool 8 (27 messages sent) The orchestrator A specialist gives up, or a task is vague
    Handoff (runbook question) 3 The specialist Wrong transfer, or no transfer at all
    Agent as a tool (same runbook question) 4 The orchestrator As above
    Bus, three workers and a summary call 7, plus 7 bus events A summary call Duplicates, lost messages, ordering
    Orchestrator when one specialist fails 10 (41 messages sent) The orchestrator The failed specialist's cost is still paid

    Two quiet costs hide in the middle column. First, the specialists ran one after another in this lab, because the loop from the agent-loop lab runs a reply's tool calls in sequence. They are independent, so they could run at the same time (that is the next lesson, on concurrency).

    In that case the calls in a row would be the orchestrator's two plus the slowest specialist's two, four, not eight. I did not build that variant, so treat it as arithmetic, not a measurement.

    Second, the orchestrator is a model too, and it can be wrong in ways one agent cannot. It writes the task text, and the task text is the only thing a specialist sees.

    TIP

    Picture it: a meeting. Every extra attendee needs a briefing before they can contribute, and every contribution has to be summarised for the chair. Four people can still be quicker than one if the job is big enough, but for a ten-minute job the briefings cost more than the work. Where the picture stops: briefings here are model calls, which also cost money.

    Run 5 of the Demo shows what a failure costs. The logs specialist's script asks for the same search again and again until its budget of four steps runs out.

    Expected output, captured from a real run (a specialist that never answers):

    Run 5. One specialist never answers: the failure cost and what the orchestrator sees
        step 1  error   ask_logs_agent -> the tool failed: logs_agent stopped without an answer (STEP_LIMIT after 4 model calls)
        step 2  final   Partial answer: the logs agent failed, so a deploy is unconfirmed. The database pool of payments-gateway is 50 of 50. Please check recent deploys by hand before any rollback.
      model calls: orchestrator 2, logs_agent 4, metrics_agent 2, runbook_agent 2; total 10
      messages sent to the models, all agents together: 41

    The orchestrator is not left hanging: the specialist's give-up arrives as an error result, the orchestrator's script then writes a partial answer that says what is missing, and the run ends. But the logs agent's four calls are already paid, and the answer says nothing about the deploy.

    Figure 7. Run 5 as a sequence: a specialist gives up and the orchestrator answers with what it has

    sequenceDiagram accTitle: A team run in which the logs specialist gives up accDescr: The orchestrator asks the logs agent for a task. The logs agent makes four model calls and then hits its step limit. The orchestrator receives an error result saying the logs agent stopped without an answer. It still asks the metrics agent and the runbook agent, which each answer after two calls, and then writes a partial answer. In total there are ten model calls. autonumber participant O as Orchestrator participant L as Logs agent participant M as Metrics agent participant R as Runbook agent O->>L: ask_logs_agent(task) Note over L: 4 model calls, same search each time L-->>O: error result, STEP_LIMIT after 4 model calls O->>M: ask_metrics_agent(task) M-->>O: answer after 2 model calls O->>R: ask_runbook_agent(task) R-->>O: answer after 2 model calls Note over O: partial answer, 10 model calls in all

    How to read this: follow the numbers down. The note on the logs agent is the wasted spend; the final note is the total, 10 against 8 when nothing fails.

    NOTE

    On call, 3 a.m.: Karim, at an invented ticketing company, split a three-step summarising job into a lead and three specialists because "that is how the diagrams look". Calls per ticket went from 4 to 9 and the summaries read the same. Two weeks later he moved the job back into one agent with two extra tools and kept the saving. The team version was not wrong; it just was not buying anything he had named. Invented example.

    NOTE

    On call, 3 a.m.: Mira, an engineer at an invented marketplace, split her triage agent into a lead and four specialists to "keep prompts small". For one incident the lead wrote the task "check what changed recently" for the deploy specialist, dropping the service name that the original alert contained. The specialist cheerfully reported on a different service. The final answer was fluent, confident and about the wrong deploy. The fix was not a smarter prompt: it was a rule in code that every task string must contain the alert id and the service, and a test that refuses a task without them. Invented example.

    When multi-agent is worse, and the rule for choosing

    Be honest about the downsides, because the lab shows each one.

    • More calls, more latency, more money. Eight calls against four in Run 2, ten against eight when one specialist fails. Every specialist pays a start-up cost: a fresh conversation, a prompt, at least one model call to decide and one to answer.
    • More failure modes. A specialist can fail, loop, or answer the wrong question because of a vague task. The orchestrator can mis-split the work, call the same specialist twice, or paraphrase an answer and lose a detail. With a bus you add duplicates, lost messages and ordering.
    • Harder tests. One agent needs one scripted conversation. A team needs a script per agent and an orchestrator test that stands in for the specialists. The lab's 16 tests cover narrow tool sets, error results, the blackboard, the handoff paths and the bus, and it still has no way to say whether a real orchestrator would split work well.
    • A paraphrase layer. In agent-as-a-tool the orchestrator re-writes the specialist's answer. Run 4 shows it: the handoff returns the specialist's sentence unchanged, and the orchestrator's version is a reworded copy.
    TIP

    Picture it: the telephone game. The more people the message passes through, the more likely a detail is lost, however clever each person is. An orchestrator that summarises three specialists is three more links in the chain. Where the picture stops: you can shorten the chain by making the hand-over structured, for example a record with the alert id and the service instead of free text.

    So when is splitting worth it? The lab shows four benefits that are real and provable, and they give the rule.

    1. Different permissions. A specialist can only call the tools it is given. If one job must never be able to roll back production and another must, separate agents make that a fact of the code.
    2. Separate context. A specialist's tool output stays in the specialist's conversation. A lab test proves that the orchestrator's conversation contains no search_runbook call at all, only the answer.
    3. Different owners or scale. Teams that deploy and scale separately can sit behind a bus, with the costs a bus brings.
    4. Different model or budget per job. Each specialist has its own model and step budget. (The lab uses scripts for all of them, so it does not test this; it is simply how the code is shaped.)

    Figure 8. A decision rule: from "a job for the model" to one agent, a workflow, or a real split

    flowchart TD accTitle: When to split one agent into several accDescr: The first question is whether the steps can be written as Java, which leads to the workflow patterns. If not, the next question is whether one agent with all the tools already works, which leads to staying with one agent. Otherwise, if the jobs need different permissions, owners or models, or one job's raw output would swamp the main conversation, the answer is to split, using agent as a tool or a handoff. If the teams deploy and scale separately or messages must survive a restart, put a real broker between them, otherwise keep the agents in one process. Start(["A job for the model"]) Q1{"Can you write the steps as Java?"} WF["Use a workflow pattern"] Q2{"Does one agent with all tools already work?"} ONE["Keep one agent"] Q3{"Different permissions, owners or models?"} Q4{"Would one job's raw output swamp the conversation?"} SPLIT["Split: agent as a tool, or a handoff"] Q5{"Separate teams, scaling or restarts?"} BUS["Put a real broker between them"] INP["Keep the agents in one process"] Start --> Q1 Q1 -- "yes" --> WF Q1 -- "no" --> Q2 Q2 -- "yes" --> ONE Q2 -- "no" --> Q3 Q3 -- "yes" --> SPLIT Q3 -- "no" --> Q4 Q4 -- "yes" --> SPLIT Q4 -- "no" --> ONE SPLIT --> Q5 Q5 -- "yes" --> BUS Q5 -- "no" --> INP

    How to read this: most jobs exit at the first, second or fifth box with "one agent" or "a workflow". The rule in words: start with one agent, split only for a named benefit from the list above, and measure the added calls before you ship.

    The decision rule, in one sentence: if you cannot name which of those four benefits you are buying, and the number of extra model calls you are paying for it, do not split. "It feels more organised" is not a benefit.

    Under the hood: what crosses the boundary

    An agent boundary is a text boundary. When the orchestrator calls ask_logs_agent, the only things that cross are the task string going in and the final answer coming out. The specialist builds its own conversation from its own system prompt plus that one task; none of the orchestrator's conversation goes with it. That is the source of both the benefits (isolation, narrow tools) and the costs (no shared understanding, every task must be self-contained).

    In the agent-loop lab's golden file, the single agent's conversation grew as 2, 4, 7 and 9 messages across its four calls. In the team, the orchestrator's two calls carried 8 messages between them (2 and 6), and each specialist's own conversation stayed tiny. The lab sums these (the 27 above) because every call is billed on what it sends. A handoff is cheaper still on this measure for the orchestrator: triage is called once.

    The event bus changes the boundary from a function call to a message. A message needs an id (so a consumer can ignore a duplicate), a topic (where it goes) and a correlation id (which task a result belongs to). Those three fields are all the lab's Event record has, and they are the minimum a real broker will also ask of you.

    What a broker adds beyond that, such as durable storage, partitioning for ordering, consumer groups, retries and acknowledgements, is exactly the list of things the stand-in lacks.

    The Kafka article linked above covers keying messages so related events stay ordered; I did not run its code, and its Maven setup targets older Spring versions than this course pins.

    Break it

    I ran each of these together against the lab's tests and restored the code afterwards; each made exactly one test fail.

    • In Specialist.logs replace Tools.of(Parcelo.searchLogs()) with new Tools(Parcelo.allTools()). The logs agent can now call roll_back, and aSpecialistCannotCallAToolOutsideItsSet fails. Narrow tool sets are the main safety property of splitting.
    • In AgentTool.execute delete the board.post(...) line. The board stays empty and specialistsPostToTheBoardUnderTheirOwnName... fails; Run 3 would have nothing to read.
    • In BusWorker.onTask delete the handled.add(task.id()) check. A duplicate delivery now runs the agent a second time and aWorkerPublishesItsAnswer...IgnoresADuplicateTask fails: the script has no third reply.

    One more you can try by hand: in Scripts.orchestrator() delete the service from a task string, so it reads like Mira's. Nothing in the lab catches it, which is the point of the story above.

    In practice: Parcelo

    TriageDesk, Parcelo's on-call assistant, would use a small team for one reason above all: permissions. The specialists get only read tools. The two tools that change production, restart_service and roll_back, are held by no agent; they sit behind an on-call human's approval, which a later lesson builds.

    Figure 9. A design sketch for TriageDesk: read-only specialists, and a human holds the write tools

    TriageDesk sketch: read-only specialists, and the rollback tool sits behind an on-call humanAlert to Orchestrator; Orchestrator to Specialists (task text); Orchestrator to On-call human (proposal); On-call human to roll_back (if approved)Alert: A-1042AlertA-1042Orchestrator: no write toolsOrchestratorno write toolsSpecialists: read-only toolsSpecialistsread-only toolsOn-call human: approvesOn-call humanapprovesroll_back: needs approvalroll_backneeds approvaltask textproposalif approved

    How to read this: the green box can look but never touch. The only path to the yellow tool runs through a person. This is a sketch of the design, not a lab; the guardrails lesson builds the approval step.

    Would this team be better than the single agent? Not for speed or cost: the lab says eight calls against four. It is better only if the permission split matters more to Parcelo than the extra calls do, and that is a decision you make with the cost in front of you, not a default.

    Architect's notes

    • Default to one agent. Splitting adds calls, failure modes and test work; every split needs a named reason from the benefits list and a measured cost.
    • Make the task string a contract. A specialist sees only the task text. Require the identifiers it needs (alert id, service) and check them in code, rather than hoping the orchestrator remembers.
    • Choose handoff or agent-as-a-tool by who owns the answer. If the answer must be combined or reworded, the orchestrator owns it. If one specialist should simply take over, a handoff saves a call and keeps the exact words.
    • Bound every agent separately. Each specialist needs its own step budget, and the orchestrator needs one that counts all its specialist calls. A budget on only the outer loop hides a runaway inner loop.
    • Treat a specialist's failure as normal. An error result must lead to a defined partial answer. The failed specialist's calls are already paid, so count them.
    • Shared state is shared risk. A blackboard entry can be stale or overwritten by another author. Add versions or timestamps before agents act on what they read.
    • Only add a broker for a reason a broker solves. Durability, independent scaling and different owners are reasons. "It looks more professional" is not, and the in-memory stand-in is no substitute when messages must survive a crash.

    Common mistakes

    • Splitting because it sounds like a team. Fix: write down the benefit you are buying and the calls it costs; if you cannot, keep one agent.
    • A vague task string. The specialist answers a different question fluently. Fix: a task format that must include the alert id and the service, validated in code.
    • Giving every specialist every tool. The permission benefit is gone. Fix: give each specialist the minimum, and test that an out-of-set call is refused.
    • No budget inside the specialist. One looping specialist drains the whole run. Fix: a step limit per specialist and an error result when it is hit.
    • Letting the orchestrator hold the write tools. The most powerful agent then also has the widest tool set. Fix: write tools behind a human or a narrow executor, not in the orchestrator.
    • Ignoring duplicates on a bus. At-least-once delivery runs a task twice. Fix: an id on every event and a processed-ids check, as in BusWorker.
    • Testing only the happy path. Fix: scripts for a specialist that gives up, a handoff to a missing specialist and a duplicate delivery, like the lab's tests.
    IMPORTANT

    Remember this:

    • Splitting an agent is a trade: you gain narrow permissions and separate context, you pay in model calls and failure modes.
    • Agent as a tool returns the answer to the caller; a handoff lets the specialist answer the user.
    • A specialist sees only its task string, so the task must carry everything it needs.
    • The lab's team used 8 model calls where one agent used 4. Count the cost before you split.
    • An in-memory bus is a teaching stand-in, not a broker.

    Key takeaways

    • A specialist is an ordinary agent with its own prompt, tool set and step budget; the narrow tool set is the strongest reason to split.
    • Agent as a tool wraps a whole agent as a function; a handoff transfers control so the specialist answers directly.
    • A blackboard shares findings between agents, so a follow-up can read instead of re-asking (2 calls in Run 3, not 8), at the price of staleness.
    • In the lab the team used 8 calls and 27 messages sent, against 4 and 22 for one agent, and 10 calls when one specialist failed. These come from scripted runs and show structure, not real-model behaviour.
    • The decision rule: split only for a named benefit (permissions, separate context, different owners or scale, different model or budget), and only with the extra calls counted.

    Practice exercises

    1. Starter. In Scripts.java change orchestratorRunbookOnly() so the final answer drops the words "needs approval". Run ./gradlew -q :labs:agent-multi:run and compare Run 4's handoff answer with the agent-as-a-tool answer. Which one now loses information, and why can a handoff not?
    2. Intermediate. Add a fourth specialist, deploys_agent, with a new tool of your own in Specialist.java, wire an AgentTool for it in Demo.java, and predict the new model-call total before you run it.
    3. Advanced. Make the task check from Mira's story real: in AgentTool.execute, throw when the task does not contain A-1042. Add a test in MultiAgentTest.java proving a vague task becomes an error result, then show how the orchestrator's script must change to pass.

    Enroll to keep reading

    Lesson 9 of 15 · Agentic AI for Java Developers: Build and Ship Agents

    Split one Java agent into an orchestrator and specialists, compare agent-as-a-tool with handoffs, count the extra model calls, and learn when not to split.

    In the rest of this lesson

    • Messages between agents: an in-memory event bus
    • Run it
    • What splitting costs: how the calls multiply
    • When multi-agent is worse, and the rule for choosing
    • Under the hood: what crosses the boundary
    • Break it

    Enrolling is free. It unlocks every lesson in Agentic AI for Java Developers: Build and Ship Agents, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments