Handling LLM Service Failures and Processing Long Texts: A Practical Guide
When working with large language model APIs, failures such as timeouts, truncated outputs, and rate-limit errors are common. This guide explains how to classify failures into server-side, input-related, and client-side causes, walk through a structured troubleshooting process, handle extremely long unsegmented text through normalization and chunked processing, manage multi-turn conversation context with sliding windows, summarization, and pinned instructions, and apply retry, degradation, validation, and monitoring practices to keep critical workloads running during service instability. Working code examples in Python are included throughout.
1. Background: What Failures Usually Look Like
When consuming an LLM service, failures typically manifest in a few recognizable ways:
- Requests hang for a long time and eventually time out.
- Output is cut off mid-sentence and left incomplete.
- Responses suddenly become very short or drift far from the question.
- Error codes or rate-limit notices are returned.
- Pages load indefinitely.
These symptoms generally trace back to three categories of causes.
Server-side issues: overall load spikes, failures in specific nodes, or queueing in model inference.
Input issues: a single request that is too long, messy formatting, missing punctuation that makes semantic segmentation hard for the model, or accumulated multi-turn context that exceeds the limit.
Client-side issues: unstable networks, misconfigured proxies, or overly short local timeout settings.
If you do not distinguish these three categories first, troubleshooting tends to devolve into ineffective trial and error. The reliable approach is to locate the problem first, then decide whether to wait, modify the input, or switch to a fallback plan.
2. Start with Failure Diagnosis
Troubleshooting should proceed from the simplest checks to the more complex ones.
Step 1: Reproduce the problem. Send the same input again and observe whether the failure occurs consistently. Intermittent failures are usually related to network or service fluctuations; stable reproduction points more toward the input itself.
Step 2: Run a controlled experiment. Shorten the input to a few hundred characters, or replace it with a piece of text known to work. If short text processes normally, the problem is most likely input length or formatting.
Step 3: Check service status. Most providers publish a status page or announcements; use these to determine whether a widespread outage is in progress.
Step 4: Inspect client logs. Confirm the timeout values, retry counts, request body sizes, and returned error codes.
The following example is a health check with timeout control, used to distinguish “service unreachable” from “business request failure.” The endpoint and key are read from environment variables rather than hardcoded:
import osimport timeimport requestsAPI_URL = os.environ["LLM_API_URL"]API_KEY = os.environ["LLM_API_KEY"]def health_check(timeout_s: float = 10.0) -> dict:"""Send a minimal request to check reachability and approximate latency."""headers = {"Authorization": f"Bearer {API_KEY}"}payload = {"messages": [{"role": "user", "content": "ping"}]}start = time.monotonic()try:resp = requests.post(API_URL, json=payload, headers=headers, timeout=timeout_s)latency = time.monotonic() - startreturn {"ok": resp.status_code == 200, "status": resp.status_code,"latency_s": round(latency, 3)}except requests.Timeout:return {"ok": False, "status": "timeout", "latency_s": None}except requests.RequestException as exc:return {"ok": False, "status": f"network_error: {type(exc).__name__}","latency_s": None}
A health check only confirms whether the service responds; it does not replace business-level validation. Business requests still need their own result logging.
3. Handling Extremely Long Text Without Punctuation
When the input is several thousand characters long with almost no punctuation, problems typically appear at three levels simultaneously.
First, the token count approaches or exceeds the per-request limit, so the service may reject the request outright or truncate processing midway.
Second, missing punctuation blurs sentence boundaries. The model must infer where paragraphs and topics shift, which increases comprehension difficulty and degrades output quality.
Third, long inputs diffuse attention. Key information is easily overlooked, and analysis tends to favor content near the beginning or the end.
The recommended approach is: normalize first, then split into segments, then aggregate.
Normalization means performing minimal cleanup without changing the original meaning — for example, adding sentence breaks at natural pauses or semantic transitions, and removing duplicated whitespace and garbled characters. This step must be conservative; do not rewrite the author’s content.
For segmentation, estimate tokens roughly by character count and include overlapping regions so that key information does not fall exactly on a cut point. The following code demonstrates chunking with overlap:
def split_text(text: str, max_chars: int = 1500, overlap: int = 200) -> list[str]:"""Split text by character count with overlap between adjacent chunks,reducing the risk of losing information at cut points."""if max_chars <= overlap:raise ValueError("max_chars must be greater than overlap")chunks = []start = 0while start < len(text):end = min(start + max_chars, len(text))chunks.append(text[start:end])if end == len(text):breakstart = end - overlapreturn chunks
After splitting, send each chunk in a separate request and ask the model for structured output — for example, the paragraph’s topic, key facts, and points that need verification. Finally, make one aggregation request to combine the per-chunk results. For aggregation, feed the chunk-level results as input rather than resubmitting the entire original text.
4. Context Management in Multi-Turn Conversations
In multi-turn conversations, message history accumulates continuously. Once the total length exceeds the limit, the service either returns an error or silently drops the earliest content, causing the model to “forget” previously agreed requirements.
Three common strategies address this:
- Sliding window: keep only the most recent turns. Simple to implement, but early important constraints get lost.
- Summary compression: condense older conversation into a summary that preserves facts and conclusions.
- Pinned context: store the user’s core requirements, terminology definitions, and output format separately, and include them in every request so they are not discarded as the window slides.
Real-world projects typically combine all three:
def build_messages(system_prompt: str, pinned: str,summary: str, recent: list[dict], max_recent: int = 6) -> list[dict]:"""Assemble request messages: system instruction, pinned requirements,conversation summary, and the most recent turns."""msgs = [{"role": "system", "content": system_prompt}]if pinned:msgs.append({"role": "system", "content": f"Pinned requirements:\n{pinned}"})if summary:msgs.append({"role": "system", "content": f"Summary of earlier conversation:\n{summary}"})msgs.extend(recent[-max_recent:])return msgs
5. Retries, Degradation, and Fault Tolerance
Retries are the most common response to transient failures, but a poorly designed retry strategy can worsen congestion.
Retries should use exponential backoff with random jitter, preventing large numbers of clients from retrying at the same instant. Only retry recoverable errors — timeouts, connection drops, and rate limiting. Requests that fail due to invalid parameters or content policy violations should not be retried.
Degradation means the system keeps working at reduced quality when the service is unavailable. Examples include moving long tasks to an asynchronous queue for later processing, switching to a backup model or backup service, or temporarily returning cached results with a clear label.
The following is a retry decorator based on exponential backoff:
import randomimport functoolsimport timeRETRYABLE = (TimeoutError, ConnectionError)def with_retry(max_attempts: int = 4, base_delay: float = 1.0, max_delay: float = 20.0):def decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):for attempt in range(1, max_attempts + 1):try:return func(*args, **kwargs)except RETRYABLE:if attempt == max_attempts:raisedelay = min(max_delay, base_delay * (2 ** (attempt - 1)))time.sleep(delay * random.uniform(0.5, 1.0))return wrapperreturn decorator
All parameter values here are examples; adjust them based on the actual service’s rate-limit policy and your business’s tolerance for latency.
6. Validating Output
A successful response does not mean the result is ready to use. Analytical tasks in particular require validation.
Structural validation checks whether the output matches the expected format — for example, whether JSON parses correctly and required fields are present.
Length validation checks whether the output is suspiciously short or long. Output that ends abruptly usually indicates truncation.
Content validation checks whether key facts match the source — for instance, whether names, dates, and numbers have been altered. For content that informs important decisions, arrange manual spot checks.
7. Monitoring and Alerting
Reliable service consumption depends on continuous observation. At a minimum, collect these metrics: request success rate, latency percentiles, input and output lengths per request, error code distribution, and retry counts.
Alert thresholds should be set against historical baselines rather than fixed, arbitrary numbers. A sudden drop in success rate, a noticeable rise in latency, and steadily growing retry counts are generally more meaningful signals than any single failure.
Each request should carry a unique request identifier, with a summary of request parameters, elapsed time, and error information written to a logging service. When problems occur, you can trace the full chain by identifier and cross-reference it against the provider’s status announcements.
Cost also belongs in monitoring. Both chunking and retries increase the number of API calls, so estimate expenses based on actual input scale before going live and set usage caps.
8. Practical Checklist
- When a failure occurs, first classify it as server-side, input-related, or client-side.
- Run a controlled experiment with short text to confirm whether the problem relates to input size.
- For extremely long text, apply conservative normalization first, then process in chunks with overlap between segments.
- In multi-turn conversations, combine sliding windows, summary compression, and pinned context.
- Retry only recoverable errors, using exponential backoff with jitter.
- Prepare asynchronous queues or fallback plans for long tasks so critical flows are not interrupted.
- Validate output across three dimensions: structure, length, and content.
- Continuously monitor success rate, latency, and usage, with sensible alert thresholds.
Following this workflow, most failures can be located quickly, and critical tasks can remain available even during periods of service instability.
