What changes in production#
A demo calls a model and prints the answer. A production service must be observable (what did it do, how long, at what cost), tested (evaluated on a dataset), resilient (timeouts, retries, fallbacks), secure and governed. Spring AI plugs into the Spring Boot production toolkit you already use for this.
Observability#
Spring AI instruments ChatClient, ChatModel, EmbeddingModel, VectorStore, advisors and tool calls with Micrometer observations. With Spring Boot Actuator and an OpenTelemetry or Prometheus exporter you get metrics and traces without extra code.
flowchart LR
APP["Spring AI service<br/>Micrometer observations"] --> OTLP["OpenTelemetry exporter<br/>OTLP"]
APP --> PROM["Prometheus endpoint<br/>/actuator/prometheus"]
OTLP --> COL["OTel Collector"]
COL --> TR["Tracing backend<br/>Tempo, Jaeger, vendor APM,<br/>or LLM tools like Langfuse"]
PROM --> GRAF["Grafana dashboards<br/>tokens, latency, errors, cost"]
What you get (names follow the OpenTelemetry GenAI conventions where they exist):
- Spans for ChatClient calls, each advisor, model calls, tool calls and vector store queries.
- Attributes such as operation, provider, request model, response model, temperature, max tokens, finish reason.
- Token usage metrics (
gen_ai.client.token.usagewith input/output type) — the basis for cost dashboards. - Latency histograms per operation and model.
management.tracing.sampling.probability=1.0
management.otlp.tracing.endpoint=http://otel-collector:4318/v1/traces
# Content logging is OFF by default — prompts and completions may contain personal data.
spring.ai.chat.client.observations.log-prompt=false
spring.ai.chat.client.observations.log-completion=false
spring.ai.tools.observations.include-content=false
Cost per request: multiply token metrics by your price table in the dashboard, tagged by application, feature and tenant (add custom observation tags or an advisor that records them).
Evaluation in tests#
Spring AI includes LLM-as-judge evaluators you can use in JUnit tests:
RelevancyEvaluator— is the answer relevant to the question given the retrieved context?FactCheckingEvaluator— is the claim supported by the provided documents (faithfulness)?
@SpringBootTest
class PolicyAssistantEvaluationTest {
@Autowired PolicyAssistant assistant;
@Autowired ChatClient.Builder judgeBuilder; // ideally a different, strong model
@ParameterizedTest
@CsvFileSource(resources = "/golden/policy-questions.csv", numLinesToSkip = 1)
void answersAreRelevantAndGrounded(String question) {
AssistantAnswer answer = assistant.answerWithSources(question);
var relevancy = new RelevancyEvaluator(judgeBuilder);
var request = new EvaluationRequest(question, answer.documents(), answer.text());
assertThat(relevancy.evaluate(request).isPass()).isTrue();
var factCheck = FactCheckingEvaluator.builder(judgeBuilder).build();
assertThat(factCheck.evaluate(request).isPass()).isTrue();
}
}
Practical tips:
- Keep evaluation suites in a separate test task (they cost money and take minutes); run them in CI on prompt, model and retrieval changes and nightly.
- Report aggregate scores vs baseline rather than failing on a single case — non-determinism makes single-case assertions flaky. A common approach: fail the build if the pass rate drops more than a few points.
- Use Testcontainers for pgvector, Redis and even local models (Ollama) in integration tests.
- Use a mock
ChatModelfor fast unit tests of your orchestration logic.
Resilience#
flowchart LR
C["ChatClient call"] --> TO["HTTP client timeouts<br/>connect + read"]
TO --> RT["Spring AI retry<br/>backoff on 429/5xx"]
RT --> CB["Resilience4j circuit breaker<br/>+ bulkhead"]
CB --> GW["AI gateway<br/>fallback provider"]
CB -->|"open"| DEG["Degraded response<br/>sources only / cached / handoff"]
- Retries: Spring AI’s retry support (
spring.ai.retry.*properties) retries transient errors with exponential backoff. Do not retry non-idempotent tool side effects blindly. - Timeouts: configure the underlying HTTP client (
RestClient/WebClient) — long generations need generous read timeouts, interactive endpoints should stream. - Circuit breakers and bulkheads: wrap calls with Resilience4j (via Spring Cloud Circuit Breaker or annotations) so a slow provider does not exhaust threads.
- Virtual threads (Java 21):
spring.threads.virtual.enabled=truelets thousands of concurrent blocking model calls run cheaply. - Fallback models: prefer doing provider failover in the AI gateway; otherwise catch errors and call a second
ChatClient.
Configuration and secrets#
- API keys from a secrets manager (Vault, cloud secret stores) via Spring Cloud integrations — never in Git.
- Point model base URLs at the AI gateway, so routing, quotas and audit are central.
- Externalise model names, temperatures and prompt template locations into configuration; change them per environment and feature flag.
Deployment reference#
flowchart TB
ING["Ingress / API gateway<br/>OIDC, rate limits"] --> SVC["Spring AI service<br/>N replicas, virtual threads,<br/>HPA on concurrency"]
SVC --> AIGW["AI gateway"]
SVC --> PG[("PostgreSQL + pgvector<br/>chat memory, vectors")]
SVC --> REDIS[("Redis<br/>cache, sessions")]
SVC --> MCPG["MCP gateway"]
ING2["Ingestion job<br/>CronJob / queue consumer"] --> PG
ING2 --> AIGW
SVC -.-> OTEL["OTel collector"]
VAULT["Secrets manager"] -.-> SVC
- Stateless service replicas; state in PostgreSQL/Redis.
- Separate deployment for ingestion so re-indexing never affects chat latency.
- Scale on concurrent requests rather than CPU — the service mostly waits on I/O.
- Readiness checks should not call the LLM (cost, flakiness); check configuration and dependencies instead.
Production checklist#
| Area | Check |
|---|---|
| Observability | Traces across advisors, tools and vector store; token and cost dashboards; alerts |
| Evaluation | Golden dataset; CI evaluation gate; online sampling |
| Resilience | Timeouts, retries, circuit breaker, fallback, degraded mode |
| Security | Input/output guardrails, tool authorisation, ToolContext identity, secrets in vault |
| Data | PII masking in logs, retention, no-training terms with providers |
| Cost | Quotas at gateway, prompt caching, model routing, max tokens |
| Governance | Registered in AI inventory, risk assessment, model and prompt versions recorded |
Review questions#
How do you monitor a Spring AI application? Spring AI emits Micrometer observations for chat clients, advisors, models, tools and vector stores. Export traces via OpenTelemetry and metrics via Prometheus; build dashboards for latency, errors and token usage (cost); keep prompt content logging off unless masked and governed.
How do you test LLM features in Spring?
Unit-test orchestration with a mocked ChatModel; integration-test with Testcontainers; evaluate quality with RelevancyEvaluator and FactCheckingEvaluator over a golden dataset in a separate CI stage, gating on aggregate scores against a baseline.
How do you make Spring AI calls resilient? HTTP timeouts, Spring AI retry with backoff for transient errors, Resilience4j circuit breakers and bulkheads, virtual threads for concurrency, gateway-level provider fallback, and a designed degraded mode.
Summary#
- Micrometer observations + OpenTelemetry give traces, token metrics and cost dashboards; keep content logging governed.
- Evaluate with Spring AI evaluators on golden datasets in CI, gating on aggregate scores.
- Timeouts, retries, circuit breakers, virtual threads and gateway fallbacks for resilience.
- Separate ingestion from serving; route models through the AI gateway; keep secrets in a vault.
References#
- Spring AI, Observability.
- Spring AI, Evaluation Testing.
- OpenTelemetry, GenAI semantic conventions.