Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Multi-Agent in Production: Java Engineering Patterns for State, Idempotency & Safety

This article details production-grade multi-agent architectures for Java backends, covering when to split agents, six high-ROI scenarios, topology patterns (Supervisor, Pipeline, Map-Reduce, Debate), communication protocols, framework selection (Spring AI, LangChain4j, LangGraph4j), and core code for orchestration, checkpointing, idempotency, and observability.

When to Split Agents — and When Not To

Multi-agent systems split cognitive responsibilities — context, permissions, concurrency — not just model roles. Each node should have narrow input, structured output, and independent retry. A practical "three-cross" rule: split when tasks cross roles (planning vs execution vs review), cross tools (>8–15 tools degrade stability), or cross state (long flows need memory, checkpointing, human-in-the-loop, compensation). Four additional checks: knowledge-domain contamination, permission isolation for mutating ops, natural parallelism, and need for independent critics/verifiers.

Selection order: single agent first; fixed DAG for deterministic flows; Supervisor when intent space is large but enumerable; free negotiation last. Multi-agent amplifies latency, token cost, and failure surface ~N×; debugging complexity ~N². Decomposability and division-of-labour payoff are both required.

Six High-ROI Scenarios

Intelligent Customer Service — Roles: Reception, Retrieval, Order Query, Refund, QA. Topology: Supervisor + Handoff. Why split: tools, scripts, permissions naturally domain-separated. Java focus: Dubbo, RBAC, approval flows, RocketMQ.

AI Dev Pipeline — Roles: Requirements, Arch, Coding, Test, Review, Deploy. Topology: Pipeline + limited rollback. Why split: write and review must be separated. Java focus: Git, Maven, JUnit, Jenkins, Sonar.

DeepResearch / Financial Research — Roles: Planner, Parallel Searchers, Writer, Critic. Topology: Map-Reduce + Critic. Why split: retrieval parallelizable; single context too small. Java focus: virtual threads, citation tracing, Top-K merge.

ChatBI / Data Governance — Roles: Planner, SQL Agent, Executor, Chart, Analyst, Writer. Topology: Planner-Executor-Replanner. Why split: generation and validation must be separate. Java focus: JDBC, SQL sandbox, slow-query intercept.

AIOps / SRE — Roles: Logs, Metrics, Traces, Changes, Runbooks, Execution. Topology: Parallel forensics + state machine. Why split: heterogeneous data sources; write ops high risk. Java focus: Prometheus, K8s, HITL, state persistence.

Enterprise Digital Employees — Roles: Parsing, Extraction, Rule Check, Multi-role Review, Human Approval. Topology: Pipeline + Debate + HITL. Why split: involves financial loss, compliance, audit. Java focus: idempotency, Saga, Flowable, audit logs.

1. Intelligent Customer Service

Query agents use read-only tools; refund agents use write tools; QA agents do rule+LLM dual validation. Putting all in one agent loses control over permissions, prompts, and audit. JD's Jing XiaoZhi and Dewu's decomposed roles (controller, utterance, evaluator, polisher) show measurable resolution-rate gains. Huawei Cloud AgentArts uses a central controller routing to pre-sales, after-sales, tech-support sub-agents. Core goal: controllable answers, not just fast ones — with SLA, human fallback, quantifiable resolution and transfer rates.

2. AI Dev Pipeline

Roles: Requirements, Architecture, Coding, Test, Review, Deploy Verification. Coder cannot self-review; Reviewer gets read-only tools; Ops alone touches Jenkins/K8s/release. Intermediate artifacts should be structured (PRD, task list, diff, test report) not free chat. Key insight: Git permissions, test gates, limited rollback, and release approval matter more than "auto code generation." Giving Reviewer write access is like letting the grader change the student's answers.

3. DeepResearch & Financial Research

Typical chain: Planner → Searcher × N → Fan-in → Writer → Critic. Single agent cannot hold dozens of pages, filings, announcements. Parallel retrieval needs citation tracing, evidence deduplication, Top-K merge — otherwise just faster hallucination. Must store: conclusion summary, raw evidence IDs + citation locations, source/time/confidence, each agent's supporting/opposing views, final adjudication rationale. Blackboard passes only {summary + evidenceIDs}; avoid shipping full text between agents.

4. ChatBI & Data Governance

"Analyze Q3 South-China GMV drop" splits into Planner, SQL Agent, Executor, Chart, Analyst, Writer. SQL generation and correctness validation must be separate — a plausible full-table scan can kill the DB before the report agent confidently explains wrong results. Java excels here: connection pools, slow-SQL intercept, result trimming, Bean Validation, metric-definition checks all in deterministic code. Industrial data governance follows same pattern: profiling, cleansing rules, quality checks, alerting agents — not ad-hoc model-written SQL for every step.

5. AIOps & SRE

Logs, metrics, traces, changes run parallel forensics; SRE agent aggregates root cause, matches runbook, generates postmortem. Execution phase (restart, scale, rollback) are write ops requiring state machine + human gates with approval suspend/resume/replay. Challenges: multi-source time-window alignment, alert deduplication + evidence chains, single-source timeout not dragging whole diagnosis, role-based tool auth (Prometheus, K8s client, Jenkins), runbook failure compensation + re-confirmation.

6. Enterprise Digital Employees

Expense, reconciliation, contract review, risk control use "parse → extract → rule-check → multi-role review → human approve." Content production splits topic, copy, image, video, compliance, distribution for daily short-video/WeChat needs. Other verticals: industrial/supply-chain (order-material-production-quality), smart manufacturing (station assistant, field ops, R&D assistant), sales/HR digital employees (Aliyun AgentCore, AgentLoop, Wanlian), office collaboration (Tencent Agent Suite), e-commerce ops (selection, copy, listing, ad), education/content (lecturer, TA, grading or topic, writing, review, distribution), risk/anti-fraud (parsing, rules, cross-verification), OTA itinerary (flight, hotel, visa parallel pricing then merge time/budget), game/simulation (NPC, social sim, multi-party), cross-end automation (agent calls agent, not just app).

Production Architecture: Governance, Not Group Chat

1. Supervisor Owns Ingress; Commander & Dispatcher Separated

9 fully-connected agents create 36 potential communication paths — any latency, hallucination, or state pollution spreads. Better: atop Supervisor-Worker, separate "thinking" (Commander, strong reasoning model for planning) from "execution" (Dispatcher, rules engine, state machine, deterministic code). LLM decides what ; code ensures how reliably . Simple routing via LLM adds cost and turns a deterministic scheduling decision into a new uncertainty source.

2. Four Topologies Cover Most Projects

Supervisor — Central router; workers only reply to supervisor. Use case: customer service, tickets, digital employees. Required guards: allow-list, confidence threshold, max hops.

Pipeline — Fixed sequential stages. Use case: R&D, content production, approval. Required guards: conditional rollback, human nodes.

Map-Reduce — Parallel fan-out, then aggregate. Use case: DeepResearch, ChatBI, AIOps. Required guards: timeout fallback, rate limit, Top-K.

Debate / Critic — Multi-perspective adversarial, verifier decides. Use case: risk, contract, compliance. Required guards: confidence threshold, deterministic rules.

Blackboard pattern overlays any topology: agents write structured facts, evidence IDs, sources, versions — not raw text. Keep workers ≤5; prune by "irreplaceability," not headcount.

3. Communication Protocols — Each Handles One Segment

In-process Shared State — Responsible for low-latency task-state sharing; not responsible for cross-service persistence, network retry.

MCP — Responsible for agent tool discovery, description, invocation; not responsible for full inter-agent collaboration semantics.

A2A / AHA — Responsible for task delegation, state, result contracts between agents; not responsible for message persistence, retry, backpressure.

RocketMQ / Kafka — Responsible for cross-service event bus, persistence, retry, decoupling; not responsible for business state machine, final adjudication.

Redis Stream — Responsible for lightweight session event stream, state collaboration; not responsible for complex cross-cluster message governance.

Prefer sync; add MQ only for cross-service or backpressure. MQ adds ~5–50ms latency but buys persistence/retry — worthwhile for non-hard-real-time (customer service, research). Model each collaboration session as a persistable, replayable event stream , not "fire-and-forget."

4. Java Framework Selection

Single agent + tool calling — Better fit: Spring AI. Reason: ChatClient, structured output, Advisor convenient.

Fixed linear flow — Better fit: Spring AI or plain Service. Reason: no need for state graph for a few calls.

LangChain4j stack — Better fit: @AiService + @Tool. Reason: interface-style agents, business tool wiring intuitive.

Dynamic routing, conditional rollback — Better fit: LangGraph4j. Reason: StateGraph and conditional edges suit graph flows.

Checkpoint resume, human-in-the-loop — Better fit: LangGraph4j / Spring AI Alibaba Graph. Reason: checkpoint, suspend/resume easier.

Existing Spring Boot codebase — Better fit: Spring AI Alibaba. Reason: closer to Spring dev habits.

High-control production system — Better fit: custom lightweight orchestration + MCP/A2A. Reason: full control over state, audit, protocol, observability.

Python: LangGraph leans graph state machine, CrewAI role-driven, MetaGPT software-team process. AutoGen in maintenance; Microsoft's next is Agent Framework. Frameworks handle flow; you still must add state persistence, idempotency, approval gates, token budgets, business audit — the real gap between demo and production.

Core Code: Wrapping Models in Deterministic Engineering

1. Narrow Worker Contracts; Tools Stay in Their Lanes

LangChain4j style: declare dedicated agents via interfaces.

@AiService
public interface OrderAgent {
    @SystemMessage("You are after-sales order specialist, only answer based on tool-returned order data, forbidden to fabricate order IDs and amounts.")
    String handle(String userQuery);
}

@AiService
public interface TechAgent {
    @SystemMessage("You are tech support engineer, first check monitoring logs and knowledge base, explicitly escalate to human if unable to locate.")
    String debug(String problemDesc);
}

Key: each agent sees only its own system prompt, knowledge domain, tool list. Review nodes must output structured data — no free-text "I think it should pass."

ReviewResult result = ChatClient.builder(chatModel)
    .defaultSystem("You are code review agent: only judge pass/issues, forbidden to modify code, forbidden to call write tools")
    .build()
    .prompt()
    .user(codeDiff)
    .call()
    .entity(ReviewResult.class);

2. Supervisor Routing: Registry, Structured Result, Confidence, Budget

public enum Action { ROUTE, FINISH }

public record RouteDecision(Action action, String agentName, double confidence, String reason) {}
@Service
@RequiredArgsConstructor
public class SupervisorOrchestrator {
    private final Map<String, Agent> agentRegistry;
    private final ChatClient routerClient;
    private static final int MAX_ROUNDS = 8;
    private static final int MAX_TOKEN_BUDGET = 50_000;
    private static final Set<String> ALLOWED = Set.of("ORDER", "REFUND", "TECH", "HUMAN");

    public OrchResult run(String goal, String traceId) {
        AgentContext ctx = new AgentContext(traceId, goal);
        for (int round = 0; round < MAX_ROUNDS; round++) {
            if (ctx.tokenUsed() > MAX_TOKEN_BUDGET) return OrchResult.budgetExceeded(ctx);
            RouteDecision decision = routerClient.prompt()
                .system("""
                You are customer service dispatcher, output structured result only.
                Available experts: ORDER / REFUND / TECH.
                Choose HUMAN for financial disputes, emotional users, insufficient info.
                Return FINISH when task completed.
                """)
                .user(u -> u.text("Session summary: {s}
Latest task: {q}")
                    .param("s", ctx.compactState())
                    .param("q", ctx.currentTask()))
                .options(ChatOptions.builder()
                    .model("qwen-turbo")
                    .temperature(0.0)
                    .build())
                .call()
                .entity(RouteDecision.class);

            if (decision != null && decision.action() == Action.FINISH) return ctx.finish();
            if (decision == null || !ALLOWED.contains(decision.agentName()) || decision.confidence() < 0.75) {
                return OrchResult.escalateToHuman(ctx, "route_gate_rejected");
            }
            Agent agent = agentRegistry.get(decision.agentName());
            AgentResult result = agent.invoke(ctx.taskFor(decision), ctx.viewFor(decision.agentName()));
            ctx.merge(result); // Reducer merge, must support idempotency and version check
        }
        return OrchResult.maxRoundsReached(ctx);
    }
}

Four guards: (1) agentRegistry auto-collects workers via Spring — new agents need no supervisor change; (2) .entity() constrains model output to DTO, avoiding "ORDER"/"order"/"订单" mixing; (3) allow-list + 0.75 confidence dual gate — escalate to human rather than misroute; (4) MAX_ROUNDS and MAX_TOKEN_BUDGET bound rounds and cost.

Quality gate before finalization (LangChain4j pseudo-code):

String answer;
int step = 0;
do {
    answer = worker.handle(userInput);
    step++;
    if (reviewModel.check(answer).pass()) break;
} while (step < MAX_STEPS);
if (step >= MAX_STEPS) return Reply.escalate(answer);
memory.add(userInput, answer); // only persist finalized result
return Reply.ok(answer, step);

Do not write rework intermediate states into long-term memory — one wrong assumption then contaminates every subsequent round.

Routing can be further rule-based via chain-of-responsibility instead of if-else:

public interface AgentRouter {
    String route(AgentContext ctx);
    int order();
}

@Component
public class IntentBasedRouter implements AgentRouter {
    @Override public String route(AgentContext ctx) {
        Intent intent = ctx.getIntent();
        if (intent == null) return null;
        // Routing table can live in Nacos/Diamond for hot reload
        return ROUTE_TABLE.getOrDefault(intent.getCode(), null);
    }
    @Override public int order() { return 10; }
}

@Component
public class FallbackRouter implements AgentRouter {
    @Override public String route(AgentContext ctx) {
        return ctx.getConfidence() < 0.75 ? "human_agent" : "general_qa_agent";
    }
    @Override public int order() { return 99; }
}

@Service
public class RoutingSupervisor {
    private final List<AgentRouter> routers;
    public RoutingSupervisor(List<AgentRouter> routers) {
        this.routers = routers.stream()
            .sorted(Comparator.comparingInt(AgentRouter::order))
            .toList();
    }
    public String dispatch(AgentContext ctx) {
        for (AgentRouter router : routers) {
            String target = router.route(ctx);
            if (target != null) {
                ctx.addTrace("routed by " + router.getClass().getSimpleName());
                return target;
            }
        }
        return "human_agent";
    }
}

Fallback router must exist; routing reason must enter trace — so when wrong, you can distinguish routing error, retrieval error, or generation error.

3. Minimal Orchestrator: Serial with Dependencies, Parallel without

public class MultiAgentOrchestrator {
    private final ExecutorService agentPool = Executors.newFixedThreadPool(8);

    public String serialExecute(List<BaseAgent> agents, String inputContext) {
        String current = inputContext;
        for (BaseAgent agent : agents) current = agent.execute(current);
        return current;
    }

    public Map<String, String> parallelExecute(List<BaseAgent> agents, String inputContext) {
        List<CompletableFuture<Map.Entry<String, String>>> futures = agents.stream()
            .map(agent -> CompletableFuture.supplyAsync(() -> Map.entry(agent.getAgentName(), agent.execute(inputContext)), agentPool))
            .toList();
        return futures.stream().map(CompletableFuture::join)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public abstract static class BaseAgent {
        protected String agentName;
        protected abstract String execute(String context);
        public String getAgentName() { return agentName; }
    }
}

Fixed pool suits teaching/low concurrency. With Java 21 virtual threads, use Semaphore, Sentinel to limit downstream concurrency. Virtual threads solve expensive waiting threads, not infinite downstream capacity.

4. DAG Scheduling: Intra-layer Parallel, Inter-layer Sequential

public final class MultiAgentScheduler {
    private final Commander commander;
    private final Dispatcher dispatcher;
    private final ExecutorService pool;

    public TaskResult execute(Task task) {
        DAG dag = commander.plan(task);
        for (List<Node> layer : dag.topologicalLayers()) {
            List<CompletableFuture<NodeResult>> futures = layer.stream()
                .map(node -> CompletableFuture.supplyAsync(() -> dispatcher.dispatch(node), pool))
                .toList();
            List<NodeResult> results = futures.stream().map(CompletableFuture::join).toList();
            // Keep completed results; failed nodes enter compensation or fallback
            dag.merge(layer, results);
        }
        return dag.finalizeResult();
    }
}
topologicalLayers()

guarantees same-layer no-dependency tasks run parallel; layers run sequential per dependencies. E.g., market monitor and announcement retrieval run together; investment reasoning waits for both. Run topological sort at startup — fail-fast on illegal cycles before production.

5. Java 21 Orchestration Kernel: Private Snapshots, Timeouts, Unified Fallback

Agents exchange only structured artifacts, not full chat history.

public sealed interface AgentResult permits Ok, Escalate {}

public record Ok(String stepId, JsonNode payload, int tokens) implements AgentResult {}

public record Escalate(String reason, String traceId) implements AgentResult {}

public record AgentStep(String id, Agent agent, Set<String> deps, Duration timeout) {}
public final class AgentGraph {
    private final List<AgentStep> steps;
    private final ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor();
    private final int maxHops = 2;

    public GraphRun run(AgentContext ctx) {
        List<AgentStep> topo = topoSort(steps);
        Map<String, CompletableFuture<AgentResult>> done = new ConcurrentHashMap<>();
        for (AgentStep step : topo) {
            CompletableFuture<?>[] deps = step.deps().stream()
                .map(done::get)
                .toArray(CompletableFuture[]::new);
            done.put(step.id(),
                CompletableFuture.allOf(deps)
                    .thenApplyAsync(ignored -> step.agent().call(ctx.snapshot(step.id())), vt)
                    .orTimeout(step.timeout().toMillis(), TimeUnit.MILLISECONDS)
                    .exceptionally(e -> new Escalate(step.id() + " timeout/fail", ctx.traceId())));
        }
        return new GraphRun(done, ctx);
    }
}
ctx.snapshot(step.id())

gives each node a private view — prevents one agent mutating another's context. Conditional rollback must be bounded:

graph.addConditionalEdge("review", (result, ctx) -> {
    boolean pass = result instanceof Ok ok && ok.payload().path("pass").asBoolean();
    if (pass) return "deploy_gate";
    if (ctx.incAndGetHops() <= maxHops) return "coder";
    return "human_gate";
});

Every step failure returns Escalate uniformly — not exceptions blowing up the whole graph. Production can layer Resilience4j CircuitBreaker for fast-fail on repeatedly failing agents, with fallback models. If virtual threads unavailable, bounded thread pool transition:

private final ExecutorService agentPool = new ThreadPoolExecutor(
    16, 32, 60L, TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(500),
    new CustomThreadFactory("agent-exec"),
    new ThreadPoolExecutor.CallerRunsPolicy());
CallerRunsPolicy

provides backpressure under overload — not a silver bullet; queue length, timeout, circuit breaker, fallback must be designed together.

6. Parallel Forensics: Rate Limit, Token Budget, Top-K, Evidence Coverage

DeepResearch, AIOps fan-out well but risk overwhelming model gateway or DB.

public EvidenceBundle fanOut(String task, List<SearchAgent> agents, int tokenBudget) {
    AtomicInteger budget = new AtomicInteger(tokenBudget);
    Semaphore limiter = new Semaphore(8);
    Executor vt = Executors.newVirtualThreadPerTaskExecutor();
    List<CompletableFuture<Evidence>> futures = agents.stream()
        .map(agent -> CompletableFuture.supplyAsync(() -> {
            limiter.acquireUninterruptibly();
            try { return agent.search(task, budget); }
            finally { limiter.release(); }
        }, vt).orTimeout(6, TimeUnit.SECONDS).exceptionally(e -> Evidence.degraded(agent.id(), e)))
        .toList();
    List<Evidence> usable = futures.stream()
        .map(CompletableFuture::join)
        .filter(Evidence::usable)
        .sorted(Comparator.comparingDouble(Evidence::score).reversed())
        .limit(12)
        .toList();
    if (usable.size() < Math.ceil(agents.size() * 0.5)) {
        throw new NeedRetryException("Evidence coverage insufficient, trigger re-retrieval");
    }
    return EvidenceBundle.of(usable);
}
Parallelism ≠ stuffing all results back into prompt. Four things happen simultaneously: Semaphore(8) protects downstream, AtomicInteger enforces task-level budget, per-agent 6s timeout with partial degradation, fan-in keeps only Top-12. If evidence coverage <50%, retry retrieval rather than let Writer freely hallucinate.

Wall-clock time drops from sum-of-branches to max-branch-plus-overhead — not algorithmic complexity magically becoming O(1). JDK 25 StructuredTaskScope further simplifies cancellation propagation, timeout, partial failure — evaluate in new modules.

7. State Graph & Checkpoint: Machine Restart Without Re-burning Tokens

LangGraph4j-style review rollback and checkpoint resume:

StateGraph<AgentState> graph = new StateGraph<>(AgentState::new, AgentState.reducer())
    .addNode("planner", this::plan)
    .addNode("executor", this::execute)
    .addNode("reviewer", this::review)
    .addEdge(START, "planner")
    .addEdge("planner", "executor")
    .addConditionalEdges("reviewer", this::routeAfterReview,
        Map.of("pass", END, "reject", "executor"))
    .addCheckpointSaver(new SqliteSaver(dataSource));
var app = graph.compile();
app.invoke(initState, config.withThreadId(traceId));
traceId

serves as session ID, replay ID, and recovery ID. Production storage can swap to Redis, MySQL, Postgres. DeepResearch can add "state hash duplicate" convergence condition:

StateGraph graph = new StateGraph("deep-research", stateFactory)
    .addNode("planner", node_async(plannerAgent))
    .addNode("research", node_async(researchTeam))
    .addNode("writer", node_async(writerAgent))
    .addNode("critic", node_async(criticAgent))
    .addEdge(START, "planner")
    .addEdge("planner", "research")
    .addEdge("research", "writer")
    .addEdge("writer", "critic")
    .addConditionalEdges("critic", edge_async(state -> {
        int loop = state.value("loop", 0);
        int score = state.value("score", 0);
        String hash = state.value("draftHash", "");
        String last = state.value("lastHash", "");
        return loop >= 3 || score >= 85 || hash.equals(last) ? "end" : "revise";
    }), Map.of("revise", "writer", "end", END));

CompiledGraph app = graph.compile(
    CompileConfig.builder()
        .checkpointSaver(new RedisSaver(redisTemplate))
        .build());

Three convergence guards: (1) loop >= 3 caps max rework rounds; (2) score >= 85 stops early on quality; (3) hash.equals(last) detects "edited then reverted" loops. Step limit prevents infinite loops; state hash prevents apparent work but actual spinning .

8. Shared State ≠ Global Map: Partition, Provenance, Version

public class SharedContext {
    private final Map<String, PartitionedMemory> partitions;
    private final long version;
    public synchronized void put(String agentId, String key, Object value) {
        partitions.computeIfAbsent(agentId, id -> new PartitionedMemory())
            .write(key, value, version);
    }
    public Object get(String requesterId, String key) {
        return partitions.values().stream()
            .filter(partition -> partition.has(key))
            .findFirst()
            .map(partition -> partition.read(key, requesterId))
            .orElse(null);
    }
}

Partitions for fault isolation; agentId + version for provenance and rollback; cross-partition reads record lineage. Parallel writes to same Redis state need CAS to avoid last-write-wins:

@Service
public class BlackboardService {
    private final RedisTemplate<String, Object> redis;
    public boolean updateFact(String sessionId, String key, Object value, long expectVersion) {
        String redisKey = "bb:" + sessionId + ":" + key;
        String lua = """
            local cur = redis.call('HGET', KEYS[1], 'version')
            if cur == ARGV[1] then
                redis.call('HSET', KEYS[1], 'value', ARGV[2], 'version', ARGV[1] + 1)
                redis.call('EXPIRE', KEYS[1], ARGV[3])
                return 1
            end
            return 0
        """;
        Long ok = redis.execute(new DefaultRedisScript<>(lua, Long.class),
            List.of(redisKey),
            String.valueOf(expectVersion), JSON.toJSONString(value), "1800");
        return ok != null && ok == 1L;
    }
}

Lua guarantees atomic "check version, write, increment version"; TTL prevents session-state leakage. On conflict, agent re-reads latest version and re-decides — no global lock killing parallelism.

9. Context Compression: Sliding Window, Summarization, Per-Agent Trimming

@Component
public class ContextCompressor {
    private static final int MAX_MESSAGES = 20;
    private static final int KEEP_RECENT = 6;
    public List<Message> compress(List<Message> history, ChatModel summaryModel) {
        if (history.size() <= MAX_MESSAGES) return history;
        List<Message> old = history.subList(0, history.size() - KEEP_RECENT);
        List<Message> recent = history.subList(history.size() - KEEP_RECENT, history.size());
        String summary;
        try { summary = summaryModel.call(buildSummaryPrompt(old)); }
        catch (Exception e) { summary = "Summary failed, truncated " + old.size() + " messages"; }
        List<Message> result = new ArrayList<>();
        result.add(Message.system("Historical dialogue summary:
" + summary));
        result.addAll(recent);
        return result;
    }
}

Summary model can be cheap small model; failure falls back to truncation without blocking main flow. Memory in three layers:

Short-term context — Stores recent messages, current task state. Method: sliding window + last 6 raw messages.

Long-term memory — Stores finalized conclusions, user preferences, project knowledge. Method: historical summaries + vector retrieval.

Failure-pattern memory — Stores error types, root causes, typical contexts. Method: structured failure cases + vector re-injection.

Research shows large-scale multi-agent deployments without shared memory coordination suffer high task failure rates — "hallucination cascade" is common: one agent fabricates, downstream agents treat it as fact. Further, encode failure patterns as retrievable subgraphs injected at planning stage — shifting from "post-hoc correction" to "pre-emptive prevention." Start with source-tagged partitioned memory + vectorized failure-case re-injection ; graph DB not required initially.

10. Tool Integration: Model Proposes, Business Layer Enforces Safety

@Component
@RequiredArgsConstructor
public class OrderTools {
    private final OrderService orderService;
    private final RefundService refundService;

    @Tool(description = "Query order status, amount, after-sales record by phone and order number")
    public OrderDTO queryOrder(@Param("phone") String phone, @Param("orderNo") String orderNo) {
        // Internal auth, param validation, sensitive field masking
        return orderService.detail(phone, orderNo);
    }

    @Tool(description = "Create refund ticket, requires order ID and refund reason")
    public RefundTicket createRefund(@Param("orderId") String orderId,
                                     @Param("reason") String reason,
                                     @Param("idempotencyKey") String key) {
        return refundService.create(orderId, reason, key);
    }
}

Spring AI composes agent with model, tools, memory:

@Bean
public ChatClient agentClient(ChatClient.Builder builder, OrderTools orderTools, ChatMemory memory) {
    return builder
        .defaultSystem("You are e-commerce customer service expert, process user requests per flow")
        .defaultTools(orderTools)
        .defaultAdvisors(new MessageChatMemoryAdvisor(memory))
        .build();
}

@Bean
public ChatMemory sharedMemory(RedisTemplate<String, String> redis) {
    return new RedisChatMemory(redis, "agent:session:");
}

All write tools pass through unified gate:

public JsonNode invoke(String traceId, String stepId, ToolCall call) {
    String key = "%s:%s:%s:%s".formatted(traceId, stepId, call.name(), call.argsDigest());
    if (!idem.tryAcquire(key, Duration.ofHours(24))) return idem.resultOf(key);
    if (call.isWrite() && !approval.approved(traceId, call)) {
        return JsonNodeFactory.instance.objectNode().put("status", "PENDING_HUMAN");
    }
    JsonNode out = call.execute();
    idem.saveResult(key, out);
    auditLog.record(key, call.name(), call.args(), out, traceId);
    return out;
}

Real key design: agent:act:{taskId}:{toolCallId}, Redis SETNX for pre-check, DB unique index as final guard. Idempotency cannot rely on agent self-judging "did I just refund?" — LLM retry, network retry, graph replay all can re-trigger tools; business layer must own idempotency key. For multi-write operations, use Saga for backward compensation (e.g., refund → cancelRefund); implement via Seata or local message table — don't try to roll back entire agent graph on error.

11. LangGraph's Send: Parallel Semantics Reference

Though Java stack, LangGraph's Send API is worth mirroring: Supervisor dynamically creates multiple worker branches, Reducer merges results.

from langgraph.types import Send
from langgraph.graph import StateGraph, END
from typing import Annotated, TypedDict
import operator

class AgentState(TypedDict):
    results: Annotated[list, operator.add]
    task: str

def supervisor(state: AgentState):
    subtasks = decompose_task(state["task"])
    return [Send(f"worker_{i}", {"task": task}) for i, task in enumerate(subtasks)]

def worker(state: dict):
    result = llm.invoke(build_prompt(state["task"]))
    return {"results": [result]}

graph = StateGraph(AgentState)
graph.add_node("supervisor", supervisor)
for i in range(5):
    graph.add_node(f"worker_{i}", worker)
graph.set_entry_point("supervisor")
for i in range(5):
    graph.add_edge("supervisor", f"worker_{i}")
    graph.add_edge(f"worker_{i}", END)

Java can implement same semantics with DAG, virtual threads, Reducer. The API name doesn't matter; independent branch execution, deterministic result merge, per-branch graceful degradation does.

Production Issues That Separate Toys from Systems

Context explosion — Window full after few rounds; early constraints evicted. Fix: private snapshots, summarization, evidence offload, Top-K, per-agent view trimming.

State inconsistency — Agent A says refunded, Agent B sees unrefunded. Fix: shared blackboard + state machine + version; business DB is single source of truth.

Hallucination cascade — Upstream fabrication cited repeatedly downstream. Fix: mandatory citations, independent verifier, critical data only via tools.

Infinite loops & semantic drift — Keeps editing despite answer; coder/tester kick each other. Fix: DAG cycle detection, maxHops, token budget, state hash, forced human exit.

Unstable task decomposition — Same request decomposed differently each time. Fix: constrained JSON Schema, low temperature, enumerated task types, high-freq task templates.

Routing errors — Refund issue sent to tech support. Fix: small model + rule pre-filter + allow-list + confidence threshold + offline eval set.

Tool duplication & dirty writes — Retry causes duplicate refund, duplicate order creation. Fix: idempotency key, DB unique index, Saga, write approval, audit.

Result conflicts — Multi-role conclusions contradict. Fix: deterministic reducer merge, weighted voting, supervisor final say, human review.

Fan-out overloads downstream — One request expands to dozens of LLM/SQL calls. Fix: Semaphore, Sentinel, bounded queue, per-call timeout, circuit breaker.

Latency & cost runaway — Five serial agents, P99 > 30s. Fix: parallelize independent, SSE streaming, semantic cache, model tiering, partial result fallback.

Single-point avalanche — One model rate-limited, whole chain stalls. Fix: timeout, retry, circuit breaker, fallback models, stateless workers, checkpoint recovery.

Permission & prompt injection — External text tricks agent into calling dangerous tool. Fix: mark external content Untrusted, tool RBAC, separate credentials, param validation, bidirectional content filtering.

Black-box debugging — Can't tell if error in routing, retrieval, or generation. Fix: OpenTelemetry, agent/tool spans, I/O, tokens, latency, replay.

No regression — Prompt changes validated by eyeballing. Fix: three-layer eval (routing, single-agent, end-to-end), online bad-case replay.

Key engineering details:

Deterministic checks (amount, state, inventory) in Java code — Bean Validation, rule engine, result-set validation; LLM only advises, never final adjudication.

Each agent uses minimal dedicated credentials — not "prompt says don't drop tables," but the account literally lacks drop-table permission.

Don't rely on plain ThreadLocal for trace propagation in virtual threads — use explicit TraceContext or adapted context propagation; every hop logs traceId/spanId/agentName/token/cost.

Observability into Prometheus, OpenTelemetry, or Langfuse — real value is replayability, not just more dashboards.

Evaluation & Cost: Build from Day One

Multi-agent can't just judge final answer "looks good."

Routing layer — Core metrics: intent accuracy, target-agent accuracy, human-escalation rationality. Example: 94%.

Single Agent layer — Core metrics: tool call success rate, structured output pass rate, agent golden-set score. Example: 86%.

End-to-End layer — Core metrics: task success rate, business resolution rate, avg rounds, human takeover rate. Example: 78%.

Cost layer — Core metrics: tokens per task, cost per session, cache hit rate, budget exceed rate. Example: per-business budget.

Performance layer — Core metrics: TTFT, P95/P99, per-node latency, parallel fan-out latency. Example: per-SLA thresholds.

Routing eval set starts at 500 cases; each agent maintains own golden Q&A set. On end-to-end failure, drill down layer by layer — don't rewrite everyone's prompts at once. Production traffic samples flow back into regression sets, combined with JUnit 5, LLM-as-Judge, human spot-check. Core changes A/B split; watch resolution rate, human-transfer rate, avg rounds, session cost. Cost attribution per span, aggregated by taskId. Routing/classification use small models; planning/final-review use large models; high-frequency Q&A gets semantic cache (Caffeine local, Redis cross-instance).

Recommended Rollout Sequence

Don't start with "fully automated dev loop" — demo dazzles, audit kills.

Pick one process with human fallback , clear SLA, resolution rate, transfer rate.

Workers ≤5 , each keeps only necessary prompt, tools, permissions.

Main trunk DAG, local agent autonomy — no fully-connected group chat.

Day one: provenance, version, checkpoint, trace — don't wait for state loss to add.

All writes through idempotency + approval gates ; timeout, fallback, compensation in deterministic code.

Pre-launch: three-layer eval + task-level budget — effectiveness and cost together.

Multi-agent value isn't making models act more human — it's folding probabilistic model outputs into an engineering system where routing is configurable, calls are timeout-bound, state is replayable, failures are degradable, costs are accountable, and effects are measurable. LLMs bring cleverness; Java engineers bring safety.
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

JavaObservabilityidempotencySpring AImulti-agentlangchain4jlanggraph4jproduction-architecture

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion