Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design how a Spring Boot service calls an external LLM API reliably in production: timeouts, retries, rate limits, streaming, and protecting the service when the provider is slow.

I would give every LLM call a connect timeout of a few seconds and a read timeout sized for long generations, stream user-facing answers so the first tokens arrive quickly, and retry only retryable errors such as 429 and 5xx with backoff that honours Retry-After, using spring.ai.retry.* or Resilience4j. A bulkhead limits concurrent calls so a slow provider cannot exhaust threads or connections, a circuit breaker switches to a fallback such as a smaller model, a cached answer or a clear error, Micrometer observations track tokens, latency and errors per model, and secrets and sensitive user data never reach logs or an unapproved provider.

Why this question is asked

An external LLM is the slowest and least predictable dependency most services have ever had. A normal API answers in 50 milliseconds; a model may take 30 seconds, slow down for everyone during a provider incident, and reject requests when we exceed a rate limit that is shared across the whole company. Interviewers ask this design question to see whether we apply the usual resilience patterns with numbers that fit this unusual dependency. In this answer, we will set timeouts and decide when to stream, design retries, protect the service with a bulkhead and a circuit breaker, add observability, and finish with secrets and data handling.

1Why an LLM Is an Unusual Dependency

Three properties make model calls different. Latency is large and varies with output length: at around 50 output tokens per second, a 1,000-token answer takes 20 seconds. Capacity is limited by provider quotas in requests and tokens per minute, so a traffic spike turns into 429 Too Many Requests responses. And failures cluster: when the provider is overloaded, every call slows down at once.

The danger is what a slow dependency does to us. If our service runs on 200 Tomcat threads and each model call holds a thread for 30 seconds, only 200 calls in flight fill the pool, and then requests that have nothing to do with the model, such as health checks, also queue. So most of this design is about keeping the slowness contained.

2Timeouts and Streaming

We set two timeouts on the HTTP client the provider integration uses. The connect timeout, the time to open a connection, should be short, two to five seconds, because a provider that cannot accept a connection will not get better by waiting. The read timeout must cover the longest answer we allow; if we cap output at 1,000 tokens, 60 seconds is reasonable. We also cap output with a maximum tokens option, which bounds both latency and cost.

For anything a person waits for, we stream. With streaming, the first tokens typically arrive in under a second, and the user reads while the rest is generated. In Spring AI that is stream().content(), returning a Flux<String>. Streaming changes the timeout question: we care about the time to the first token, maybe 10 seconds, and the time between chunks, rather than one long timeout for the whole answer. Background jobs such as summarising tickets do not need streaming and can use the blocking call.

3Retrying Only What Can Succeed Later

Retries help only when the next attempt can succeed. A 429 or a 503 usually will after a pause; a 400 Bad Request or a 401 with an invalid key never will, so retrying those only wastes time and quota. When the provider sends a Retry-After header with a 429, it is telling us exactly how long to wait, and our backoff should wait at least that long.

Spring AI wraps provider calls in a retry template configured through spring.ai.retry.* properties, such as the maximum number of attempts, the initial backoff interval, the multiplier and which HTTP status codes count as retryable; check the exact names for your version. Alternatively, we disable it and use Resilience4j around our own service method, which lets us combine retry with the circuit breaker and bulkhead below. Whichever we choose, it should be one layer of retries, not two nested ones that multiply into nine attempts.

There is a catch for user-facing calls: three retries with exponential backoff can add 15 seconds before the user sees anything. So user-facing requests get one retry at most, and background jobs get more patience.

Java
spring:
ai:
retry:
max-attempts: 3 # names as in Spring AI 1.0; check your version
backoff:
initial-interval: 2s
multiplier: 2
max-interval: 20s
on-client-errors: false # do not retry 4xx in general...
on-http-codes: 429 # ...except rate limits

4Bulkhead and Circuit Breaker

A bulkhead limits how many calls to the provider can be in flight at once, so slowness stays inside one compartment of the service. With a semaphore of 40 permits, at most 40 threads wait on the model; request number 41 waits briefly for a permit or is rejected at once, while the other 160 threads keep serving everything else. The number 40 comes from the provider quota: if we may send 600 requests a minute and calls take about 4 seconds, about 40 are in flight at full quota.

A circuit breaker watches the outcome of recent calls. When, say, 50 percent of the last 50 calls failed or took longer than 20 seconds, it opens and fails calls immediately for 30 seconds instead of sending them. Then it lets a few test calls through, and closes again if they succeed. While it is open, we serve a fallback: a smaller or second-provider model, a cached answer for a common question, or an honest message that the assistant is unavailable.

Java
@Bulkhead(name = "llm") // maxConcurrentCalls: 40
@CircuitBreaker(name = "llm", fallbackMethod = "fallback") // opens at 50% failures or slow calls
public String summarise(String ticket) {
return chatClient.prompt().user(ticket).call().content();
}
private String fallback(String ticket, Throwable t) {
return cache.lookup(ticket) // cached summary, if any
.orElse("Summary unavailable right now."); // honest message, never a guess
}
Step throughPath of one model call
  1. Bulkhead permit free?40 permits
    YesContinueNoReject fast, fallback
  2. Circuit breaker closed?
    YesCall the providerNoFallback immediately
  3. Answer within timeout?
    YesReturn the answerNoCount a failure
  4. Retryable (429, 5xx) and attempts left?
    YesBack off, honour Retry-AfterNoFallback
  5. Fallbacksmaller model, cached answer or clear error

5 steps in order. Play them, or step through them one at a time.

5Observability Per Model

We cannot tune what we cannot see. Spring AI integrates with Micrometer observations, the Spring way of producing metrics and traces from one instrumentation point, and records the latency of chat calls and token usage per model, which we export to Prometheus or our tracing system. We add our own tags such as feature name, and we watch latency percentiles, time to first token for streams, error rate by status code, input and output tokens, retries and circuit breaker state. Alerting on the 429 rate warns us before the quota becomes an outage, and token counts per feature are the basis of the cost report.

6Secrets and Data Handling

The API key comes from a secret store, never from source code, and must never appear in logs; HTTP client debug logging can print headers, so it stays off in production. Prompts and responses may contain personal data, so we decide deliberately whether to log them, and if we do, we redact identifiers and apply the same retention as the source data.

Before sending user data at all, we check its classification. Some data, such as health records or payment details, may not go to an external provider, or only to one with a contract that rules out training on our data and limits retention. That decision belongs in the design, not in each developer's head.

7Follow-up questions

How do we stop one feature from using up the whole provider quota?

Give each feature its own bulkhead size and, ideally, its own rate limiter, so a batch job cannot take every permit from the user-facing chat. A company-wide gateway in front of the providers can enforce per-team quotas as well.

Is falling back to a smaller model always safe?

Only if the feature still produces acceptable results with it, which we check in evaluation beforehand. For tasks where a weaker answer could mislead, an honest unavailable message is better than a worse answer that looks the same.

8Conclusion

In this answer, we treated the LLM as a slow, quota-limited dependency. We set a short connect timeout and a read timeout for long generations, streamed user-facing answers, and retried only 429 and 5xx errors with backoff that respects Retry-After. A bulkhead sized from the quota contained slowness, a circuit breaker switched to a fallback during provider trouble, Micrometer observations tracked tokens, latency and errors per model, and we kept keys and sensitive data out of logs and away from unapproved providers.

What to say in the interviewAbout 80 seconds aloud

Open with

I would treat the model as the slowest, most quota-limited dependency in the service. First, timeouts: a connect timeout of a few seconds, and a read timeout that covers the longest output I allow, which I also cap with max tokens.

Then, if they want more

For anything a person waits on, I stream, so the first tokens arrive in under a second, and I watch time to first token. Second, retries only for errors that can succeed later, mainly 429 and 5xx, with exponential backoff that honours Retry-After, and only one retry for user-facing calls.

Spring AI has spring.ai.retry properties for that, or I use Resilience4j, but only one retry layer. Third, a bulkhead: a semaphore sized from the quota, say forty concurrent calls, so a slow provider cannot take every thread or connection and the rest of the service keeps working.

Fourth, a circuit breaker that opens on failure or slow-call rate and serves a fallback, a smaller model, a cached answer or a clear error. Fifth, Micrometer observations for latency, tokens and errors per model and per feature, with alerts on the 429 rate.

And finally, keys come from a secret store and never appear in logs, and I check data classification before any user data goes to a provider.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring AI reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design how a Spring Boot service calls an external LLM API reliably in production...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/60c3abdfdd/