Calling an LLM from the backend: timeouts, retries, streaming and fallbacks
An LLM call is a slow, flaky third party that bills per token. How to set a deadline, retry the right status codes, stream over SSE, stop the LLM from taking the whole service down, and review AI-written integration code.
On this page
1. The problem
An order page calls an LLM to summarise orders. One afternoon the provider slows to 40 seconds and returns 429 for 30% of requests. Default retries hold each request for minutes; after 90 seconds all 200 Tomcat threads are stuck and the checkout API in the same service returns 503.
2. Key idea
LLM APIs differ from ordinary REST APIs in timing, error types and the price of each attempt. The wrapping is familiar: deadlines, bounded retries, bulkheads, fallbacks.
| Ordinary REST API | LLM API | |
|---|---|---|
| Latency | 50–300 ms | 1–60 s, growing with output tokens |
| Transient errors | rare | 429 per tokens/minute, 5xx, overload |
| Price of one attempt | near zero | per token; a retry pays again |
| Mid-response errors | rare | a stream that returned 200 can still get an error event |
Stacked retries multiply: your 3 × the framework's 10 × the HTTP client's 3 is 90 calls for one button click.
2.1 Which calling style?
| Approach | Use when | Don't use when |
|---|---|---|
| Synchronous, no stream | short output: classification, JSON extraction, under ~5 s | long answers for people to read |
| Stream over SSE | chat, the user reads as it arrives | you need complete JSON before using it |
Async job (202, poll) |
over ~30 s, long documents, batches | the user needs the answer now |
Three rules: one overall deadline, every inner timeout below it; one retry layer, attempts × timeout < deadline; a dedicated bulkhead for the LLM so a slow LLM can't drag the whole service down.
3. In Java
Your job is the bulkhead and the fallback.
@Service
class OrderSummaryService {
private final ChatClient chat;
private final Semaphore llmSlots = new Semaphore(20); // at most 20 concurrent LLM calls
OrderSummaryService(ChatClient.Builder builder) {
this.chat = builder.defaultSystem("Summarise the order in 3 sentences.").build();
}
String summarize(String orderText) {
if (!llmSlots.tryAcquire()) return FALLBACK; // no slot: return now, don't queue
try {
return chat.prompt().user(orderText).call().content();
} catch (RuntimeException e) { // timeout or error after retries
return FALLBACK;
} finally { llmSlots.release(); }
}
static final String FALLBACK = "No summary yet. See the order details below.";
}Other languages: Go context.WithTimeout, Node.js AbortSignal.timeout(). Official SDKs usually retry by default.
Spring AI retries, truncated output and streaming
- Spring AI has its own retry (
spring.ai.retry.*), by default many attempts with backoff up to minutes: fine for background jobs, wrong for a user waiting on a request. Lower it to 2 attempts with short backoff, and keep the HTTP client timeout below the deadline. - An answer cut off at the token limit still returns HTTP 200: Anthropic reports
stop_reason: "max_tokens", OpenAIfinish_reason: "length". Truncated is not success, especially when you expect JSON. - An SSE stream needs a timeout between chunks (e.g.
Flux.timeout(Duration.ofSeconds(10))) and a total cap; an error after HTTP 200 must reach the client as an error event. - A circuit breaker (Resilience4j) opens when the error or slow-call rate crosses a threshold, so you stop burning threads and money on a provider that's down.
4. Working with AI
Hand to AI: an adapter around ChatClient, WireMock tests simulating 429 with retry-after, 500, a 30 s slow response, a stream cut mid-way.
Check in AI-written code:
- There's an overall deadline; the client timeout is below it.
- Only one retry layer (not SDK plus Spring AI plus
@Retryable). - No retries on 400, 401, 403; 429 honours
retry-after. - The LLM has its own bulkhead, not a pool shared with critical APIs.
- Truncated output isn't treated as success; each call logs model, tokens, time and fallback branch.
5. Exercises
Exercise 1: Review "retry to be safe"
The AI added the code below, saying "handles transient provider errors". application.properties keeps Spring AI's defaults. Find the bugs, show how to prove them, fix it.
@Retryable(retryFor = Exception.class, maxAttempts = 3)
public String classify(String ticket) {
return chat.prompt().user(ticket).call().content();
}Solution to Exercise 1
- Two stacked retry layers:
@Retryable3 times × Spring AI's default retries. One ticket can hold a thread for tens of minutes. retryFor = Exception.classretries 400s too: paying for tokens 3 times for an error that will certainly repeat.- No deadline: nothing stops the waiting after the user has left.
- Proof: WireMock returning 429 forever, count requests reaching the stub and measure the time; return 400 and assert exactly 1 request.
- Fix: drop
@Retryable, lowerspring.ai.retryto 2 attempts with short backoff, a 10 s timeout, a bulkhead and a fallback.
Exercise 2: Read an incident
15 minutes after enabling "suggested replies" for 100% of users: LLM call p99 goes from 4 s to 38 s, the 429 rate from 0 to 30%. Tomcat has 200/200 threads busy and the checkout API (same service) fails 25% of the time. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: the provider's rate limit (tokens/minute) is exceeded, retries stretch every request, and the LLM shares the thread pool with checkout, dragging the whole service down.
- 15 minutes: turn the feature off with a flag (or back to 10%); checkout recovers as soon as threads are freed.
- Root fix: a dedicated bulkhead, an overall deadline, one retry layer honouring
retry-after, a circuit breaker, a "no suggestion yet" fallback. Get the rate limit raised first, then roll out gradually by measured tokens/minute.
Summary
- An LLM is a slow, expensive, often overloaded dependency: wrap it like any third party.
- One overall deadline, one retry layer.
- Retry 429 (honouring
retry-after), 5xx, network errors; never 400. - A dedicated bulkhead and a fallback so a slow LLM can't take the service down.
Read more: Part 2: LLM API cost and latency.
Practice interview questions on this topic
- When do you stream an LLM answer over SSE, and when do you make it an async job?
- A service calls an LLM inside a user request: how do you set timeouts and retries?
- The LLM provider slows down and returns 429, and the whole service goes down with it: how do you diagnose and fix it?
- An LLM feature has a 9-second p99: how do you bring latency down?
Comments
Community rules