Calling an LLM from Spring Boot Safely: 6 Production Rules

Calling an LLM from Spring Boot Safely: 6 Production Rules

11 min read

Spring AI turns an LLM call into one line of Java. Keeping that line from taking the rest of your service down with it is the real work. If you call an LLM from Spring Boot in production, these are the six rules I would put around it, with config checked against Spring AI 1.1 and Resilience4j 2.4.

TL;DR

  • Put connect and read timeouts on the HTTP client. A blocking call without one holds a thread as long as the provider likes.

  • Spring AI already retries: 10 attempts by default, backoff up to 3 minutes. Tune it down and keep one retry layer.

  • Wrap the call in a Resilience4j circuit breaker with an honest fallback.

  • Cap tokens per request and per user, and record what each call used.

  • Never call an LLM inside a database transaction.

Why one slow LLM call can take down the whole service

Example numbers: your endpoint calls a model that usually answers in 3 seconds. During a provider incident it takes 20. Traffic is 10 requests a second. Requests in flight equal arrival rate times time per request (Little's law), so 10 x 20 = 200 requests waiting at once. Tomcat's default server.tomcat.threads.max is 200. Every thread is now waiting on the model, and your login page queues behind them.

If the call also sits inside a transaction, the same maths runs against HikariCP's default pool of 10 connections, and you hit the wall at one request every two seconds.

Virtual threads (spring.threads.virtual.enabled=true on Java 21) remove the thread ceiling. They don't remove the connection pool, the provider's rate limits or the bill.

Ten requests a second, each waiting 20 seconds on an LLM, fill all 200 Tomcat threads
Little's law in one picture: 10 requests a second times 20 seconds each is 200 requests in flight, the whole default thread pool.

The setup: a plain ChatClient

The code targets Spring AI 1.1.8 on Spring Boot 3.5, with the OpenAI starter. The ChatClient code is the same for other providers; the starter and some options change.

Groovy
dependencies {    implementation platform("org.springframework.ai:spring-ai-bom:1.1.8")    implementation "org.springframework.ai:spring-ai-starter-model-openai"    implementation "io.github.resilience4j:resilience4j-spring-boot3:2.4.0"    implementation "org.springframework.boot:spring-boot-starter-aop"    implementation "org.springframework.boot:spring-boot-starter-actuator"}

The naive version, which works fine on a laptop:

Java
public String review(String answer) {    return chatClient.prompt().user(answer).call().content();}
Chat Client API :: Spring AI Reference
docs.spring.io

Rule 1: put timeouts on the HTTP client

Spring AI's OpenAI auto-configuration builds its client from the RestClient.Builder that Spring Boot auto-configures, so Boot's global HTTP client properties (3.4+) apply:

YAML
spring:  http:    client:      connect-timeout: 2s      read-timeout: 15s

Connect should be short, because a healthy provider accepts connections fast. Read timeout comes from your measured p99 for the largest answer you allow, plus headroom. 15 seconds is an example, not a recommendation.

Two things to know:

  • These are global. Every auto-configured RestClient and RestTemplate in the app gets them, so configure other clients separately if they need different values.

  • Resilience4j's @TimeLimiter is not the tool here. Its Spring Boot docs say Retry, CircuitBreaker, RateLimiter and Bulkhead support synchronous return types; TimeLimiter is not on that list. A blocking ChatClient call needs its timeout on the HTTP client.

Rule 2: should you retry a failed LLM call?

Yes, but only errors that can succeed on a second try: 5xx responses and network failures such as timeouts, with exponential backoff and a cap of two or three attempts. Don't retry 400s, auth errors or quota errors. And keep exactly one retry layer, because Spring AI already retries by default.

The defaults surprise people. From the Spring AI 1.1 OpenAI docs:

Property

Default

What I set

spring.ai.retry.max-attempts

10

2

spring.ai.retry.backoff.initial-interval

2 sec

1s

spring.ai.retry.backoff.multiplier

5

2

spring.ai.retry.backoff.max-interval

3 min

2s

spring.ai.retry.on-client-errors

false

false

What gets retried, per the 1.1 source: a 4xx becomes a NonTransientAiException and is not retried, unless you list the code in on-http-codes or turn on on-client-errors. A 5xx becomes a TransientAiException and is retried. I/O failures, timeouts included, surface as ResourceAccessException and are retried too.

With the defaults, the backoff sleeps alone are 2 s, 10 s, 50 s, then 3 minutes for each remaining attempt: about 19 minutes for one request, before counting the calls themselves. With my settings, the worst case is a call, a 1-second pause and one more call: 15 + 1 + 15 = 31 seconds. Do this sum for your own config (attempts x read timeout + backoff). It must be shorter than what your caller will wait.

YAML
spring:  ai:    retry:      max-attempts: 2      backoff:        initial-interval: 1s        multiplier: 2        max-interval: 2s
Retry maths: Spring AI default backoff of 2, 10, 50 and 180 seconds against a tuned config of one 1-second pause
Worst case = attempts x read timeout + backoff. With the defaults, the backoff alone is about 19 minutes.

One retry layer. If you also put Resilience4j's @Retry with maxAttempts: 3 around the call, each attempt runs Spring AI's whole retry loop. With Spring AI's defaults, that is up to 30 HTTP calls, and 30 bills, for one click. I keep Spring AI's retry, since it already separates transient from non-transient errors, and use Resilience4j only for the circuit breaker.

What about 429? It's a 4xx, so it isn't retried by default, and I leave it that way. A quota 429 won't fix itself in two seconds, and a rate-limit 429 is the provider asking you to slow down.

Rule 3: add a circuit breaker with Resilience4j

Retries handle a blip. A circuit breaker handles an outage. When the failure rate or the slow-call rate in a sliding window crosses a threshold, the breaker opens and rejects calls immediately with CallNotPermittedException. After a wait it lets a few trial calls through (half-open), and closes again if they succeed.

YAML
resilience4j:  circuitbreaker:    instances:      llm:        slidingWindowType: COUNT_BASED        slidingWindowSize: 20        minimumNumberOfCalls: 10        failureRateThreshold: 50        slowCallDurationThreshold: 10s        slowCallRateThreshold: 50        waitDurationInOpenState: 30s        permittedNumberOfCallsInHalfOpenState: 3

slowCallDurationThreshold is the line most people skip, and it covers the nastiest case: the provider isn't down, just slow, which is exactly what drains your threads. The library defaults are general-purpose (a window of 100 calls, a 60-second slow-call threshold), so set your own.

  • By default every exception counts as a failure.

  • The annotation works through a Spring proxy. Call the method from another bean; a call from the same class skips the breaker, the same trap as @Transactional.

  • On Spring Boot 3 you need spring-boot-starter-aop on the classpath.

  • If you add Resilience4j's @Retry anyway, the default aspect order puts Retry outside CircuitBreaker.

Circuit breaker states: CLOSED, OPEN and HALF_OPEN with the transitions between them
Closed while calls succeed, open when failures or slow calls cross the threshold, half-open to test recovery.

IMAGE 3: Circuit breaker states (upload the generated image here)

Getting Started
Getting started with resilience4j-spring-boot2 or resilience4j-spring-boot3
resilience4j

Rule 4: a fallback that tells the truth

The fallback runs when the call fails or the breaker is open. It lives in the same class, takes the same parameters plus one exception parameter, and returns a compatible type. What it returns is a product decision. In order of preference:

  1. A cached answer for the same input, if it is still valid.

  2. The non-AI path: the full text instead of the summary, plain search results instead of a generated answer.

  3. A clear message: "The reviewer is busy. Your answer is saved, try again in a minute."

Never return a canned answer dressed up as model output. Mark fallback responses with a degraded flag so the UI can say so and your dashboards can count them.

Rule 5: a token and cost budget for every request

Three limits, all cheap:

  1. Output cap per request: ChatOptions.builder().maxTokens(400) passed to .options(...). For OpenAI reasoning models, Spring AI's docs say to use maxCompletionTokens instead; the two are mutually exclusive.

  2. Input cap: reject inputs over a size limit before calling. Characters are a rough but free proxy for tokens.

  3. Daily budget per user: read usage from chatResponse.getMetadata().getUsage() and add it to a counter per user per day.

Java
@Componentpublic class TokenBudget {    private static final long DAILY_TOKENS_PER_USER = 50_000;    private static final ZoneId IST = ZoneId.of("Asia/Kolkata");    private final StringRedisTemplate redis;    public TokenBudget(StringRedisTemplate redis) {        this.redis = redis;    }    public boolean hasRoom(String userId) {        String used = redis.opsForValue().get(key(userId));        return used == null || Long.parseLong(used) < DAILY_TOKENS_PER_USER;    }    public void record(String userId, int tokens) {        String key = key(userId);        redis.opsForValue().increment(key, tokens);        redis.expire(key, Duration.ofDays(2));    }    private static String key(String userId) {        return "llm:tokens:" + userId + ":" + LocalDate.now(IST);    }}

This is a soft cap. Two parallel calls can both pass hasRoom and overshoot by one call. For a token budget that is fine.

Rule 6: never call an LLM inside a database transaction

@Transactional keeps a database connection checked out until the method returns. Put a 20-second model call inside, and that connection sits idle for 20 seconds. Ten such requests and, with HikariCP's default pool, every query in the app waits.

Java
@Transactionalpublic void draftReply(long ticketId) {    Ticket ticket = tickets.findById(ticketId).orElseThrow();    String draft = chatClient.prompt().user(ticket.getMessage()).call().content(); // connection held    ticket.setDraftReply(draft);}
Java
public void draftReply(long ticketId) {    String message = tickets.findById(ticketId).orElseThrow().getMessage();    String draft = chatClient.prompt().user(message).call().content(); // no connection held    tx.executeWithoutResult(status ->            tickets.findById(ticketId).orElseThrow().setDraftReply(draft));}

tx is a TransactionTemplate, which Spring Boot auto-configures. One more trap: spring.jpa.open-in-view is on by default in Spring Boot web apps. With it on, the persistence context lives for the whole request, and Spring configures Hibernate to keep a connection, once acquired, until that context closes. The split only frees the connection if open-in-view is off, so I turn it off.

Two timelines comparing a DB connection held for the whole LLM call against a short read, the call, and a short write
Hold the connection for milliseconds, not for the whole model call.

How to call an LLM from Spring Boot: the full service

Everything together. The input cap and budget live in the service, outside the breaker, so a rejected input never counts as a provider failure.

Java
@Componentpublic class CoachClient {    private static final Logger log = LoggerFactory.getLogger(CoachClient.class);    private static final int MAX_OUTPUT_TOKENS = 400;    private final ChatClient chatClient;    public CoachClient(ChatClient.Builder builder) {        this.chatClient = builder                .defaultSystem("You are a strict Java interviewer. Reply in at most 5 sentences.")                .build();    }    @CircuitBreaker(name = "llm", fallbackMethod = "fallback")    public CoachReply review(String answer) {        ChatResponse response = chatClient.prompt()                .user(answer)                .options(ChatOptions.builder().maxTokens(MAX_OUTPUT_TOKENS).build())                .call()                .chatResponse();        if (response == null || response.getResult() == null) {            throw new IllegalStateException("Empty response from the model");        }        Usage usage = response.getMetadata().getUsage();        Integer total = usage.getTotalTokens();        log.info("llm call: prompt={} completion={}", usage.getPromptTokens(), usage.getCompletionTokens());        return new CoachReply(response.getResult().getOutput().getText(), total == null ? 0 : total, false);    }    private CoachReply fallback(String answer, Throwable cause) {        log.warn("llm call failed, serving fallback: {}", cause.toString());        return new CoachReply("The reviewer is busy. Your answer is saved, try again in a minute.", 0, true);    }}
Java
@Servicepublic class ReviewService {    private static final int MAX_INPUT_CHARS = 4_000;    private final CoachClient coach;    private final TokenBudget budget;    public ReviewService(CoachClient coach, TokenBudget budget) {        this.coach = coach;        this.budget = budget;    }    public CoachReply review(String userId, String answer) {        if (answer.length() > MAX_INPUT_CHARS) {            throw new IllegalArgumentException("Keep the answer under " + MAX_INPUT_CHARS + " characters");        }        if (!budget.hasRoom(userId)) {            return new CoachReply("You have used today's review budget. It resets at midnight.", 0, true);        }        CoachReply reply = coach.review(answer);        budget.record(userId, reply.tokensUsed());        return reply;    }}
Java
public record CoachReply(String text, int tokensUsed, boolean degraded) {}

Production checklist

  • Connect and read timeouts set, read timeout from measured p99

  • spring.ai.retry tuned, and the worst case computed

  • Exactly one retry layer

  • Circuit breaker with a slow-call threshold

  • Fallback is honest and marked degraded

  • maxTokens per request and an input size cap

  • A per-user daily token budget, with usage logged per call

  • No LLM call inside @Transactional, and open-in-view off

  • API key from an environment variable or secret store, never committed

The 60-second interview answer

I treat the LLM like any slow, flaky dependency. Timeouts on the HTTP client, set from measured p99. Retries only for 5xx and network errors, with backoff and a small cap, and only one retry layer: Spring AI retries by default with 10 attempts, so I tune that down instead of stacking another. A Resilience4j circuit breaker with failure and slow-call thresholds, plus an honest fallback: a cached answer, the non-AI path, or a clear try-again. A token budget: maxTokens per request, an input cap, and a per-user daily limit from reported usage. And the call never runs inside a database transaction, because it would hold a connection for the whole call.

Try it yourself

1. With Spring AI's default retry settings, the provider returns 503 for ten minutes. What does one request go through?

Answer 1

It keeps retrying through the outage: attempts after sleeps of 2 s, 10 s, 50 s, then every 3 minutes. It finally succeeds around the ten-minute mark, long after the user gave up, holding a thread the whole time. Lower max-attempts and let a circuit breaker fail fast.

2. You add Resilience4j @Retry with maxAttempts: 3 and keep Spring AI's defaults. Worst case, how many HTTP calls per click?

Answer 2

30. Each of the 3 outer attempts runs up to 10 inner attempts.

3. Your @CircuitBreaker never opens, even though every call fails. Give two likely reasons.

Answer 3

The method is called from the same class, so the proxy is skipped. Or spring-boot-starter-aop is missing. Also check that minimumNumberOfCalls has been reached, and that the method doesn't catch the exception itself.

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?