Monitoring Spring AI with Micrometer and RelevancyEvaluator
Track Spring AI 2.0.1 token usage and latency in Prometheus and Grafana via Micrometer, and automate quality checks with RelevancyEvaluator.
Shipping a generative AI feature to production leaves you with two blind spots standard HTTP metrics can’t answer: how fast you’re burning token budget, and whether a prompt tweak silently introduced hallucinations. Spring AI 2.0.1 instruments
ChatModelandChatClientthrough Micrometer Observation out of the box, and pairs that telemetry withRelevancyEvaluatorandFactCheckingEvaluatorfor automated LLM-as-a-Judge checks.
Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, Prometheus, Grafana, and Zipkin. Full source is in spring-ai-examples (
observability-evaluation).
Observability and evaluation architecture
Telemetry and quality checks run on two complementary tracks: Micrometer records real-time token counts, inference latency, and distributed spans on every live request, while EvaluationService scores sampled or CI test cases and exports pass/fail counters back into the same registry.
flowchart TD
User["Client (POST /api/ask)"] --> Service["AssistantService (RAG + ChatClient)"]
Service --> Gemini["Google Gemini (gemini-3.5-flash-lite)"]
Service -.->|"Micrometer Observation"| Meter["Micrometer Core"]
Meter -->|"/actuator/prometheus"| Prom["Prometheus (9090) -> Grafana (3000)"]
Meter -->|"Brave Spans"| Zipkin["Zipkin Tracing (9411)"]
Eval["EvaluationService (Relevancy / FactCheck)"] -.->|"Pass / Fail Counters"| Meter
Choosing an evaluation strategy and when not to use LLM-as-a-Judge
| Evaluation method | Speed & cost | Best for | Main weakness |
|---|---|---|---|
| Deterministic assertions | Instant, free | JSON schema validity, tool arguments, regex/format checks | Cannot judge semantic grounding or paraphrased answers |
LLM-as-a-Judge (RelevancyEvaluator) | 1 extra LLM call per check | RAG grounding, hallucination regression in CI, sampled prod audits | Non-deterministic; judge model can share biases with generator |
| Human review | Slow, expensive | High-stakes legal/medical sign-off and golden dataset creation | Doesn’t scale to every pull request |
When not to run RelevancyEvaluator: Never invoke an LLM evaluator synchronously on the hot path of every production user request. Doing so doubles both your latency and your token bill. Run deterministic checks inline, run LLM evaluators asynchronously on a 1–5% traffic sample, and gate prompt or model upgrades with them in CI.
Project setup and configuration
Dependencies in build.gradle.kts
Add Spring Boot Actuator, the Prometheus Micrometer registry, and Brave/Zipkin tracing (if you already run an OpenTelemetry Collector, you can bridge Micrometer tracing to OTel as covered in my Spring Boot OpenTelemetry guide):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.1"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
implementation("tools.jackson.module:jackson-module-kotlin")
// Metrics and distributed tracing
implementation("io.micrometer:micrometer-registry-prometheus")
implementation("io.micrometer:micrometer-tracing-bridge-brave")
implementation("io.zipkin.reporter2:zipkin-reporter-brave")
developmentOnly("org.springframework.boot:spring-boot-docker-compose")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
Exposing metrics and tracing in application.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
server:
port: 8096
spring:
application:
name: observability-evaluation
ai:
google:
genai:
api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY:demo-key}
chat:
model: gemini-3.5-flash-lite
options:
include-extended-usage-metadata: true
management:
endpoints:
web:
exposure:
include: health, info, prometheus
tracing:
sampling:
probability: 1.0 # 100% sampling for dev/staging; lower to 0.05-0.1 in production
zipkin:
tracing:
endpoint: http://localhost:9411/api/v2/spans
Auto-instrumented Spring AI metrics in Prometheus
With Actuator and micrometer-registry-prometheus on the classpath, Spring AI automatically wraps every ChatModel and ChatClient call in a Micrometer Observation following OpenTelemetry GenAI semantic conventions. Three metrics matter most in day-to-day operations:
gen_ai.client.token.usage(Counter): Tagged withgen_ai.system="google_genai",gen_ai.request.model="gemini-3.5-flash-lite", andgen_ai.token.type(input,output, ortotal). This drives real-time cost dashboards and runaway-spend alerts.gen_ai.client.operation(Timer): Measures raw model network round-trip and inference duration.spring.ai.chat.client(Timer): Measures end-to-endChatClientduration including advisor overhead (RAG retrieval, chat memory lookups, and tool calls). Comparingspring.ai.chat.clientagainstgen_ai.client.operationimmediately shows whether a slowdown came from your vector database or from Gemini itself.
Figure 1. /actuator/prometheus output exposing auto-instrumented token counters and operation timers.
Ready-to-use Grafana PromQL queries
- Tokens consumed per minute by type:
sum by (gen_ai_token_type) (rate(gen_ai_client_token_usage_total[1m])) * 60 - Model inference p95 latency:
histogram_quantile(0.95, sum by (le) (rate(gen_ai_client_operation_seconds_bucket[5m])))
Automating quality checks with RelevancyEvaluator
To catch hallucinations and ungrounded answers automatically, I wire Spring AI’s RelevancyEvaluator (does the answer address the question using the retrieved context?) and FactCheckingEvaluator (is a specific claim supported by the reference documents?) into EvaluationService, and export custom Micrometer counters for pass/fail rates:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@Service
class EvaluationService(
private val assistantService: AssistantService,
private val chatClientBuilder: ChatClient.Builder,
meterRegistry: MeterRegistry
) {
// 1. Relevancy evaluator (is the answer grounded in the retrieved context?)
private val relevancyEvaluator = RelevancyEvaluator.builder()
.chatClientBuilder(chatClientBuilder)
.build()
// 2. Fact-checking evaluator (is the claim supported by reference documents?)
private val factCheckingEvaluator = FactCheckingEvaluator.builder()
.chatClientBuilder(chatClientBuilder)
.build()
// Custom evaluation pass/fail counters
private val passCounter = meterRegistry.counter("ai.evaluation.result", "evaluator", "relevancy", "pass", "true")
private val failCounter = meterRegistry.counter("ai.evaluation.result", "evaluator", "relevancy", "pass", "false")
fun evaluateRelevancy(question: String): EvaluationView {
val (answer, docs) = assistantService.askWithContext(question)
val request = EvaluationRequest(question, docs, answer)
val response = relevancyEvaluator.evaluate(request)
if (response.isPass) passCounter.increment() else failCounter.increment()
return EvaluationView(
evaluator = "relevancy",
target = question,
answer = answer,
pass = response.isPass,
score = response.score,
sourceDocumentIds = docs.map { it.id }
)
}
fun evaluateFactCheck(claim: String): FactCheckView {
val docs = assistantService.allReferenceDocuments()
val request = EvaluationRequest(claim, docs, "")
val response = factCheckingEvaluator.evaluate(request)
return FactCheckView(
evaluator = "fact_check",
claim = claim,
pass = response.isPass,
score = response.score
)
}
}
Figure 2. Evaluator JSON responses marking a grounded answer as pass: true (1.0) and a fabricated claim as pass: false (0.0).
CI/CD quality regression workflow
Running evaluation integration tests on pull requests that touch prompts, advisors, or model versions catches quality regressions before they merge. Here is a minimal GitHub Actions workflow scoped to the observability-evaluation module:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
name: AI Quality Regression
on:
pull_request:
paths:
- 'observability-evaluation/**'
workflow_dispatch:
jobs:
evaluate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '25'
- uses: gradle/actions/setup-gradle@v4
- name: Run evaluation tests
env:
SPRING_AI_GOOGLE_GENAI_API_KEY: ${{ secrets.SPRING_AI_GOOGLE_GENAI_API_KEY }}
run: ./gradlew :observability-evaluation:test --tests "*IntegrationTests"
- name: Upload test report
if: always()
uses: actions/upload-artifact@v4
with:
name: evaluation-report
path: observability-evaluation/build/reports/tests/test
Verification
Run the unit and integration tests to verify that gen_ai.client.token.usage increments, ai.evaluation.result records pass/fail counts, and both evaluators flag fabricated claims reliably:
1
./gradlew :observability-evaluation:test
Figure 3. Passing unit and integration tests for Micrometer token counters, RelevancyEvaluator, and FactCheckingEvaluator.
Production caveats and checklist
Watch out for prompt logging and PII in traces: Spring AI’s observation config lets you enable
spring.ai.chat.client.observations.log-prompt=trueandlog-completion=truefor debugging. Leave both disabled in production unless your tracing backend is scrubbed for PII—otherwise raw user prompts and internal handbook excerpts end up in Zipkin or Grafana Tempo in plaintext. Also avoid using the exact same lightweight model to both generate and judge complex answers; pairing a fast generator with a stronger judge model in CI reduces self-confirmation bias.
Before rolling out observability and evaluation in production, verify these four items:
- Cost alerts configured: Alert on sudden spikes in
rate(gen_ai_client_token_usage_total[5m])per model so a buggy retry loop can’t drain your API budget overnight. - Sampling tuned: Drop
management.tracing.sampling.probabilityfrom1.0to0.05–0.1in production and keep prompt/completion logging off by default. - Evaluators off the critical path: Run
RelevancyEvaluatorasynchronously on sampled traffic or inside CI pull-request gates, never blocking user responses. - Stable golden dataset: Keep a small, version-controlled set of 20–50 representative Q&A pairs (including known unanswerable questions) so CI regression scores stay comparable across model upgrades.