How to measure latency, errors, token usage and spend for model calls in a Spring Boot application using Micrometer, tracing and safe logging.
Adding a language model call to a Spring Boot service is easy. Knowing how it behaves in production is not. Model calls are slow compared with database queries, their latency varies widely, providers have outages and rate limits, and every request costs money based on tokens. A feature that looks fine in testing can quietly become the slowest and most expensive part of your system.
Traditional application monitoring covers some of this, but AI features need a few extra signals: token usage, cost, model and prompt versions, and a safe way to see what was actually sent. This article shows how to instrument AI calls in Spring Boot with Micrometer metrics, distributed tracing and careful logging, and how to alert on both latency and spend.
What to measure for every model call
Start with a small, consistent set of signals for each call to a model provider:
- Latency: total duration, with percentiles, because averages hide the slow requests users notice.
- Outcome: success, error, timeout or rate-limited, so you can tell provider problems from your own bugs.
- Token usage: input and output tokens separately, since providers usually price them differently.
- Dimensions: model name, feature (for example "invoice-summary" or "support-chat") and prompt version.
Keep tag values low in cardinality. Model name, feature and outcome are fine; user IDs, request IDs or prompt text must never become metric tags, because each unique value creates a new time series and can overwhelm your metrics backend.
Timers and counters with Micrometer
Spring Boot Actuator auto-configures a Micrometer MeterRegistry, so you can inject it and record metrics around your model client. The example below wraps any model call, times it with a Timer, and records token usage with Counters:
@Component
public class InstrumentedModelClient {
private final MeterRegistry registry;
public InstrumentedModelClient(MeterRegistry registry) { this.registry = registry; }
public String call(String feature, String model, Supplier<ModelResult> request) {
Timer.Sample sample = Timer.start(registry);
String outcome = "success";
try {
ModelResult result = request.get();
countTokens(feature, model, "input", result.inputTokens());
countTokens(feature, model, "output", result.outputTokens());
return result.text();
} catch (RuntimeException e) {
outcome = "error";
throw e;
} finally {
sample.stop(Timer.builder("ai.request.duration").tag("feature", feature).tag("model", model)
.tag("outcome", outcome).publishPercentileHistogram().register(registry));
}
}
private void countTokens(String feature, String model, String type, long tokens) {
Counter.builder("ai.tokens").tag("feature", feature).tag("model", model).tag("type", type)
.register(registry).increment(tokens);
}
}
Here ModelResult is a simple record such as record ModelResult(String text, long inputTokens, long outputTokens) {}, populated from the usage fields that most model APIs return. Micrometer caches meters by name and tags, so calling register repeatedly returns the existing meter. With the Prometheus registry, these appear as ai_request_duration_seconds (with histogram buckets) and ai_tokens_total.
If you use Spring AI, check its observability support, which can emit metrics and traces for model calls without hand-written wrappers. The principles in this article still apply to the tags and alerts you build on top.
Turning tokens into cost
Token counters are the foundation for cost tracking. There are two common approaches:
- Compute cost in the dashboard: multiply token rates by the provider's price per token in your Prometheus or Grafana queries. Prices stay in one place and history is preserved.
- Record cost in the application: keep a price table in configuration and increment an
ai.costcounter in rupees or dollars per call. This is convenient when different features use different models.
Either way, treat the result as an estimate and reconcile it periodically against the provider's invoice. Break cost down by feature: knowing that one report generator uses most of your budget is far more actionable than a single monthly total.
Tracing model calls end to end
Metrics tell you that something is slow; traces tell you where. Spring Boot uses Micrometer Tracing, which can bridge to OpenTelemetry (via micrometer-tracing-bridge-otel) and export spans to a backend such as Jaeger, Zipkin, Grafana Tempo or a commercial tool through an OTLP exporter.
For AI features, a useful trace for a single request might show the incoming HTTP request, the database lookup, the vector search for retrieval, the model call itself and any post-processing. Add span attributes such as model name, prompt version and token counts, but not the prompt text. Outgoing calls made with an auto-configured RestClient or WebClient built from Spring's builders are instrumented automatically, and the Micrometer Observation API lets you wrap your own steps, such as retrieval, in named spans.
Traces are particularly valuable for retrieval-augmented features, where slowness may come from the embedding call or the vector database rather than the language model.
Logging prompts safely
When an AI answer is wrong, developers want to see the exact prompt and response. Those texts often contain customer names, phone numbers, addresses or financial details, which brings obligations under India's DPDP Act, 2023 and your own contracts. A safe approach:
- Log metadata by default: trace ID, feature, model, prompt version, token counts, latency and outcome.
- Redact identifiers such as phone numbers, email addresses and PAN before any text is logged.
- Store full prompt and response text, if needed, in a separate store with restricted access and a short retention period, linked by trace ID.
- Allow sampling or a per-feature switch so full-text capture can be turned on only while investigating.
- Never log API keys or authorisation headers; check that HTTP client debug logging is off in production.
Alerting on latency, errors and spend
Good alerts are few and actionable. A starting set for AI features:
- Latency: 95th percentile of
ai_request_duration_secondsabove a threshold for several minutes, for example usinghistogram_quantile(0.95, sum by (le, feature) (rate(ai_request_duration_seconds_bucket[5m]))). - Error rate: the share of calls with
outcome="error"above a set level, which often signals a provider incident or exhausted quota. - Spend rate: hourly token or cost rate well above its normal level, which can indicate a bug, a retry loop or abuse.
- Daily budget: a warning when estimated daily spend crosses a threshold, plus the provider's own billing alerts as a backstop.
Pair alerts with protections in code: timeouts on every model call, limited retries with backoff, circuit breakers (for example with Resilience4j) and per-user or per-tenant rate limits.
How NextWebGen can help
NextWebGen builds and runs Java and Spring Boot applications, and we can add AI features with metrics, tracing, safe logging and cost alerts in place from the first release. If you need help instrumenting existing services or setting up monitoring on your servers, see our server management services.



