Building LLM Applications Under Compute Constraints: From Rate Limiting to Graceful Degradation
A practical guide to designing LLM applications that keep working when platform quotas and request rates tighten. It covers why inference capacity is limited, how context length drives GPU memory use, and how to apply RAG with token budgets, externalized conversation storage with privacy safeguards, rate limiting, semantic caching, fallback strategies, monitoring, and autoscaling.
When a platform tightens quotas, the cause is usually an imbalance between inference compute supply and demand. As a developer, the right assumption is that upstream quotas and request limits can change at any time. Application layers should plan for context control, rate limiting, caching, degradation, and data management instead of assuming unlimited compute.
1. Why Platforms Tighten Quotas
Large model inference depends on three resources: GPU compute, GPU memory capacity, and GPU memory bandwidth. As concurrent requests increase, GPU work queues up, response latency rises, and the memory used by individual requests can exceed what the cluster can hold. To protect overall service, platforms commonly limit input length per request, cap the number of requests per time window, reduce concurrency quotas, and queue or reject requests during peak periods. These measures protect the availability of the whole cluster. They are not aimed at any single application.
Applications should plan for this. When the platform returns a rate-limit error (HTTP 429) or a “service busy” response, the application should keep running, or at least tell users what is happening in a clear way.
2. Why Long Contexts Consume GPU Memory, and What Frequency Limits Control
In the Transformer architecture, each time the model generates a new token, it reads the Key and Value vectors of all previous tokens. This data is called the KV Cache. The size of the KV Cache can be roughly estimated as:
KV Cache bytes ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × batch size × bytes per element
The factor of 2 accounts for the Key and Value caches. As the formula shows, longer contexts and larger concurrent batches increase memory use quickly.
A common misunderstanding needs clarifying here. Deleting a user’s chat history usually frees session storage and state records on the platform side. The KV Cache is a resource used during a single request, and it is released when that request ends. Clearing chat history therefore does not directly reclaim GPU memory. Platforms limit input length to control the peak memory of each request and to keep a few oversized requests from overloading an entire inference node.
Frequency limits are a scheduling tool for multi-tenant environments. GPU compute time is a shared resource. Without quotas, a small number of high-frequency users can crowd out everyone else. Quotas and token bucket mechanisms help keep access fair and prevent abuse.
3. Replacing Unlimited Long Prompts with RAG
Pasting large reference documents into a prompt is expensive, and it can easily exceed the model’s context limit. A safer approach is Retrieval-Augmented Generation (RAG).
The basic workflow is as follows:
- Chunk documents. Split documents at semantic boundaries into segments of 300 to 800 tokens. Keep an overlap of 50 to 100 tokens between adjacent segments so key information is not cut off.
- Embed and store. Generate vectors with an embedding model, write them to a vector database, and record the source document, page number, and update time.
- Retrieve. For each query, fetch the Top-K segments (start with 3 to 5 and tune from there). Filter out results below a similarity threshold. The threshold should be determined with your own evaluation set. A starting value of 0.3 to 0.4 is reasonable.
- Set a context budget. Cap the total tokens of the retrieved material, for example at 4,000 tokens. Segments that exceed the cap are dropped entirely rather than cut partway through.
- Limit output. Use
max_tokensto cap response length. A common range is 512 to 1,024.
The example code below uses starting values. Adjust them for your application.
import timeimport randomTOP_K = 4SIM_THRESHOLD = 0.35MAX_CONTEXT_TOKENS = 4000MAX_OUTPUT_TOKENS = 1024MAX_RETRIES = 3def build_context(query, retriever, tokenizer):hits = retriever.search(query, top_k=TOP_K)hits = [h for h in hits if h.score >= SIM_THRESHOLD]chunks, used = [], 0for h in hits:n = len(tokenizer.encode(h.text))if used + n > MAX_CONTEXT_TOKENS:breakchunks.append(h.text)used += nreturn chunksdef call_llm_with_backoff(client, prompt):for attempt in range(MAX_RETRIES):try:return client.chat(prompt=prompt, max_tokens=MAX_OUTPUT_TOKENS, timeout=30)except RateLimitError:# Exponential backoff with random jitter to prevent retries from arriving at the same timetime.sleep(2 ** attempt + random.uniform(0, 0.5))return None # Hand off to the caller's degradation logicdef answer(query, retriever, tokenizer, client):chunks = build_context(query, retriever, tokenizer)if not chunks:return "No relevant information was found in the current materials. Please try rephrasing the question or adding more details."prompt = "Answer the question based on the following materials. Clearly state if the materials do not contain the answer:\n" \+ "\n".join(chunks) + f"\n\nQuestion: {query}"result = call_llm_with_backoff(client, prompt)return result if result is not None else "The service is temporarily busy. Please try again later."
Before deployment, confirm that the vector database and embedding model versions match, set timeouts for the retrieval service, and make sure there is a fallback path when retrieval fails.
4. Externalizing Session History and Meeting Privacy Requirements
Do not tie business logic to a platform’s built-in chat history feature. Platforms may change their retention policies, and history may not be exportable. Persist conversation records in your own database, such as PostgreSQL. The table can include session_id, user_id, role, content, token_count, created_at, and a per-session summary field.
Assemble context for each turn as follows:
- Keep the most recent 6 to 10 turns verbatim.
- Summarize earlier content with a small model. Keep each summary within 300 to 500 words, and update it regularly.
- Combine the summary with the recent turns and the RAG results. The total must still stay within the context budget.
Conversation records often contain personal information, so compliance requirements need to be implemented in the engineering design:
- Notice and consent: When a user first uses the service, explain what data is stored, why, and how long it is kept. Provide a way to delete it.
- Data minimization: Store only the fields the business needs. Do not store full device information or unrelated data.
- Encryption in transit: Use TLS 1.2 or later across the entire path.
- Encryption at rest: Encrypt stored data with strong encryption such as AES-256. Consider field-level encryption for sensitive
