跪拜 Guibai
← All articles
Backend · Java · AI Programming

Spring AI vs LangChain4j: The 2026 Java LLM Architecture Bet, Priced Out

By Rain的Java大神之路 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

The wrong framework choice can silently drag an entire platform from Boot 3 to Boot 4, a decision nobody formally makes. An anti-corruption layer turns the bet into an option: swapping frameworks costs two dev-days, gray releases and ArchUnit boundaries let a loss be rolled back in a week.

Summary

Both frameworks now treat model abstraction as a commodity, so the difference is positioning, not feature count. Spring AI is the Spring-native AI abstraction, an AI-era JDBC that manages unified calls, keys, retries, streaming, and observability. LangChain4j is a framework-agnostic JVM toolbox with more granular RAG pipelines, more model vendors and vector stores, and an explicit agentic module. The decision tree starts with your runtime: Boot 4 projects should look at Spring AI 2.0; Boot 3 holdouts either stay on the 1.1.x line or use LangChain4j; non-Spring stacks go straight to LangChain4j.

The production sections carry the real substance. Under 500 concurrent 5-second requests, a Tomcat 200-thread pool delivers about 40 req/s; switching to Java 21 virtual threads yields roughly 480 req/s and cuts P95 from 24 seconds to 1.5. RAG tuning is broken into seven independently replaceable stages, with hard filters and chunking doing most of the work before you pay for rewriting and reranking. Tool count explosion is handled via progressive disclosure, saving 34–64% of tokens. Structured output uses JSON Schema plus validation retry, and a budget guard short-circuits overspending. Streaming requires care with backpressure, tool-call aggregation, and usage accounting.

The core recommendation is an anti-corruption layer: a LlmPort that never exposes framework types to the business layer. With that port, switching frameworks is a one-line config change plus one adapter, measured at about 2 person-days on a 120k-line codebase instead of 18. Gray release with sticky conversation IDs makes the bet reversible, and ArchUnit rules enforce the boundary in CI.

Takeaways
— Both frameworks' model abstraction layer is roughly 90% identical; the real difference is positioning: Spring AI is the Spring-native PSA pattern, LangChain4j is a framework-agnostic JVM toolbox.
— Spring AI 2.0 forces Boot 4 + Framework 7 + Jackson 3; Boot 3.x stays on the 1.1.x maintenance line, and Boot 3.5's open-source support ended 2026-06-30.
— LangChain4j starters cover Boot 3.5+ and Boot 4, require only JDK 17+ for the core, and don't depend on Spring.
— APIs are drifting: LangChain4j renamed ChatLanguageModel to ChatModel; Spring AI 2.x plans to replace ChatMemory with the Session API.
— In a 500-concurrency load test, Tomcat 200 threads with 5s responses delivered ~40 req/s; with Java 21 virtual threads, ~480 req/s (12x throughput) and P95 dropped from 24.14s to 1.52s.
— Virtual thread pinning in synchronized blocks or native calls (e.g., OkHttp) can negate gains; fall back to a dedicated AI thread pool with semaphore throttling if pinning is uncontrollable.
— Progressive tool disclosure via 'tool-search-advisor' saves 34–64% tokens, rising to 60–70% in enterprise agent scenarios.
— Anti-corruption layer: on a 120k-line codebase, switching frameworks without ACL costs ~18 person-days; with ACL, ~2 person-days.
— Gray release with sticky conversationId per engine is mandatory because ChatMemory formats are incompatible between the two frameworks.
— ArchUnit rules can enforce 'no framework imports in business layer' as a CI gate.
— RAG tuning: chunking + hard filters (zero model calls) solve about 70% of retrieval quality problems before spending on rewriting and reranking.
— RabbitMQ-style dead-letter queues and hard retry limits are recommended for structured output validation failures.
— Streaming usage is only available in the final chunk; enable include_usage and estimate with a tokenizer on mid-stream disconnect.
Conclusions

The genuine cost driver is leaking framework types into 200+ business classes, not the framework choice itself; a wrong abstraction forces a rework of the entire AI capability, not just a refactor.

Framework features converge within three months, but runtime binding takes three years to escape; Spring AI's container assumption is a migration tax outside the Spring ecosystem.

RAG improvement is a series of replaceable experiments; the granularity of the minimum replaceable unit (an interface vs a whole pipeline) determines whether a team keeps iterating into the fifth round.

The anti-corruption layer works best when it abstracts only the stable minimum (chat, tools, retrieval), letting advanced orchestration features leak through; otherwise you lose Advisor semantics.

Virtual threads are the pragmatic concurrency solution for AI workloads on Tomcat, not WebFlux, because they reuse existing filters, interceptors, and ThreadLocal chains, but pinning must be verified for the HTTP client stack.

Two frameworks can coexist in one service only when they split by layer (Spring AI for access/engineering, LangChain4j for retrieval/orchestration) and only one auto-config set owns the ChatModel.

A gray-release A/B experiment with sticky conversation IDs turns framework selection into an option, making a wrong bet reversible and thus far less costly.

Concepts & terms
Anti-corruption layer (ACL)
A boundary that isolates business domain from external frameworks using ports and adapters, so framework imports never appear in business logic. Swapping frameworks becomes a config change plus one adapter instead of a mass refactor.
Portable Service Abstraction (PSA)
A Spring pattern that treats an LLM like a DataSource, providing a uniform interface for model calls, key management, timeouts, retries, streaming, and observability, aiming for integration efficiency.
Virtual thread pinning
On JDK 21, virtual threads can pin the underlying carrier thread when entering synchronized blocks or certain native calls, temporarily undoing concurrency benefits. Mitigations include ReentrantLock or a dedicated thread pool.
Progressive tool disclosure
Grouping and routing tool definitions to the model by scenario or role, so only relevant tools are exposed at each step. This reduces token overhead and improves tool-selection accuracy, with Spring AI 2.0's tool-search-advisor saving 34–64% tokens.
From the discussion

The discussion centers on where to place the anti-corruption layer and how to enforce it. A dedicated adapter module with a port interface, backed by ArchUnit, gets broad agreement, but annotation-level leakage (like @Tool on business methods) remains a real hole. The thread also converges on defining a stable capability contract first and explicitly disabling retries for write operations, since idempotency keys alone don't prevent duplicate records. No major disagreement surfaces, though contract testing scope (happy path versus timeouts and rate limiting) is left as an open question.

— The true cost of framework selection is platform upgrade overhead; rollback costs often exceed model invocation fees.
— The anti-corruption layer should be a dedicated adapter module, not the business Service; business code depends on its own port (e.g., LlmPort) and avoids framework imports.
— ArchUnit enforces the boundary reliably, but it cannot catch annotation-level leakage (e.g., @Tool on business methods) because annotations bring framework semantics into the business layer.
— A stable capability contract (name, schema, result codes, retryability) must be defined before writing an adapter; switching frameworks then only rewrites the adapter.
— Framework default timeout/retry is unsafe for write operations; idempotency keys are only a fallback, so retry should be explicitly disabled per capability and delegated to business logic.
— Contract tests should cover not just happy paths but also timeouts and rate limiting; current practice remains unclear.
Featured comments
badhope 1 likes

This piece really explains that 'framework selection is actually the cost of platform upgrade.' We've encountered similar problems when building Agent applications: to integrate one model, we ended up upgrading the whole Spring Boot, and the rollback cost later was much higher than the model invocation fee. I want to ask: where did you put the anti-corruption layer? Is it at the Service interface, or a standalone adapter module?

Rain的Java大神之路

666, I feel this pain lol. We didn't put it on the business Service; we split out a dedicated adapter module. The business layer only depends on its own defined LlmPort and doesn't directly import AI framework packages; ArchUnit enforces the boundary. Framework-specific logic like RAG and Agent orchestration stays inside the adapter and doesn't leak out; we only abstract the minimal stable capabilities. Later, when changing or rolling back frameworks, only the adapter is touched; business code doesn't need changes.

badhope  → Rain的Java大神之路

This adapter approach is clean; ArchUnit enforcing the boundary is more reliable than verbal agreement. We later also kept the tool-calling schema outside the port, so when switching models we only change the serialization adapter. One question: does your contract testing only cover happy path, or does it also include timeout and rate limiting?

去吧波波鸟 1 likes

This article is brutally honest. The cost of choosing the wrong framework is a refactor; the cost of choosing the wrong abstraction is a rewrite of the entire AI capability. That line hits home. I'm taking note of the ArchUnit trick to weld the boundary shut.

Rain的Java大神之路

Haha, 6, thanks for the recognition! Indeed, abstracting wrong is more fatal than switching frameworks. ArchUnit's move is to define the red line in advance, so boundaries aren't slowly crossed and things don't become coupled without notice 😁

星云PLUS团队 1 likes

Let me add a point that's easy to miss about the anti-corruption layer: if you directly annotate business methods with the framework's @Tool or ToolCallback, the framework type leaks back into the business class through the annotation, so you haven't actually prevented leakage. A more robust approach is to define your own capability description first (name, parameter schema, result code, whether it's retryable), then write a layer that adapts to the specific framework. Switching frameworks only requires changing the adapter layer. Also, the framework's built-in timeout/retry is dangerous for write operations by default: without an idempotency key, retrying a document creation leads to duplicate records. It's best to explicitly mark retryable=false per capability and hand the retry decision back to the business.

Rain的Java大神之路

Great point, 666, you're right. I didn't cover these two points thoroughly in the article. The first one: I only prevented import in my original code; the example directly annotated the business class with @Tool, which brings the framework semantics back through the annotation, and ArchUnit can't stop that. Following your advice, defining the capability description first and then writing the adapter layer is cleaner; switching frameworks only touches the adapter layer. Second: an idempotency key is just a fallback; write operations should also explicitly retryable=false, leaving retry decision to the business, otherwise a document creation retries and creates duplicates. I'll add these two points to the tool section later. Thank you for the reminder.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗