Complete Guide to LLM Application Architecture
Build production LLM applications end to end: API layers, prompt management, streaming, caching, guardrails, observability, evaluation and deployment patterns.
Introduction
The first version of an LLM feature is twenty lines: take a user message, call chat.completions.create, return the text. It survives the demo and then starts failing in ways that have nothing to do with the model: a prompt change ships untested and tanks answer quality, a duplicated question costs the same tokens as the first hundred, a prompt injection attempt sails straight into the context window, and nobody can say why p95 latency tripled last Tuesday.
An LLM application architecture is the set of layers sitting between the user’s request and the model’s response — API handling, prompt construction, retrieval, the model call itself, output parsing, guardrails, caching, and observability. Each layer answers one question: how the request gets in, what context goes to the model, what the response means, what it must never say, what you don’t pay for twice, and how you know when it breaks.
This guide walks through each layer with production code: SSE and WebSocket endpoints, prompt registries, semantic caching, input/output guardrails, structured logging and metrics, retries with fallback, and model routing. It assumes Python and a working FastAPI or similar backend.
Architecture Overview
A production LLM request flows through eight layers before the answer goes back:
The layers, in order of what they own:
| Layer | Owns | Typical failures |
|---|---|---|
| API layer | Endpoints, auth, rate limiting, streaming transport | Timeouts, blocked event loops |
| Input guardrails | Length limits, injection detection, PII screening | Prompt injection, cost abuse |
| Prompt builder | Templates, few-shot, context injection | Prompt drift, versionless edits |
| Cache | Exact and semantic reuse | Redis KEYS scans, stale answers |
| LLM provider | The model call, retries, fallbacks | Rate limits, provider outages |
| Response parser | Structured output, schema validation | Malformed JSON, hallucinated fields |
| Output guardrails | PII redaction, harmful content, format checks | Leaked data, unsafe answers |
| Observability | Logs, metrics, traces, evaluation | Invisible quality regressions |
You don’t need all eight on day one — a read-only summarization endpoint can skip guardrails and cache — but you need to know which ones you’re skipping and why. The rest of the guide builds each layer.
API Layer
Streaming Responses with Server-Sent Events
Users judge an LLM app on time-to-first-token. Server-Sent Events stream tokens over plain HTTP — no socket management, automatic reconnection, works through most proxies:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel
import json
app = FastAPI()
client = AsyncOpenAI()
class ChatRequest(BaseModel):
message: str
system: str = "You are a helpful assistant."
@app.post("/chat")
async def chat(request: ChatRequest):
async def stream_response():
stream = await client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": request.system},
{"role": "user", "content": request.message}
],
stream=True,
temperature=0.7
)
async for chunk in stream:
if chunk.choices[0].delta.content:
data = json.dumps({
"type": "token",
"content": chunk.choices[0].delta.content
})
yield f"data: {data}\n\n"
yield f"data: {json.dumps({'type': 'done'})}\n\n"
return StreamingResponse(
stream_response(),
media_type="text/event-stream"
)
Two details matter here. The request body is a BaseModel, not a dict — you get validation and OpenAPI docs for free. And everything is async end to end: a sync LLM call inside an async endpoint blocks the event loop and serializes every request.
WebSocket for Bidirectional Chat
SSE is one-directional — server to client. When the client also pushes mid-generation (stop buttons, live edits, voice input), use WebSockets:
from fastapi import FastAPI, WebSocket
from openai import AsyncOpenAI
app = FastAPI()
client = AsyncOpenAI()
@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
await websocket.accept()
conversation_history = []
while True:
message = await websocket.receive_text()
conversation_history.append({"role": "user", "content": message})
stream = await client.chat.completions.create(
model="gpt-4o",
messages=conversation_history,
stream=True
)
full_response = ""
async for chunk in stream:
token = chunk.choices[0].delta.content or ""
full_response += token
await websocket.send_json({"type": "token", "content": token})
conversation_history.append({"role": "assistant", "content": full_response})
await websocket.send_json({"type": "done"})
The trade-off: WebSockets need connection lifecycle handling — reconnects, heartbeats, per-connection state, and they don’t play well with simple HTTP middleware. Rule of thumb: SSE for “show me the answer as it generates,” WebSocket for “the client and model talk back and forth.” The in-memory conversation_history here also dies with the connection — durable sessions need the store covered in the LangChain production guide.
Prompt Management
Prompts are code: they change behavior, they regress, and they deserve version control. Hardcoding them in source means every tweak is a deploy.
Prompt Templates with Jinja2
A template class separates the static structure from the per-request variables:
from jinja2 import Template
from dataclasses import dataclass
from typing import Any
@dataclass
class PromptTemplate:
template_str: str
system_prompt: str
def render(self, **kwargs: Any) -> list[dict]:
template = Template(self.template_str)
user_content = template.render(**kwargs)
return [
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": user_content}
]
# Define templates
code_review_prompt = PromptTemplate(
system_prompt="You are a senior code reviewer. Analyze code for bugs, security issues, and improvements.",
template_str="""Review the following {{ language }} code:
```{{ language }}
{{ code }}
```
Focus on:
1. Bugs and potential errors
2. Security vulnerabilities
3. Performance issues
4. Code style and readability
Provide specific, actionable feedback."""
)
messages = code_review_prompt.render(
language="python",
code="def add(a, b): return a + b"
)
Prompt Registry
Scale that pattern into a registry that loads versioned templates from files at startup — prompts become data you can diff, review, and roll back:
import yaml
from pathlib import Path
class PromptRegistry:
def __init__(self, prompts_dir: str):
self.prompts_dir = Path(prompts_dir)
self.templates: dict[str, PromptTemplate] = {}
self._load_prompts()
def _load_prompts(self):
for file in self.prompts_dir.glob("*.yaml"):
with open(file) as f:
data = yaml.safe_load(f)
self.templates[data["name"]] = PromptTemplate(
template_str=data["template"],
system_prompt=data["system"]
)
def get(self, name: str) -> PromptTemplate:
if name not in self.templates:
raise KeyError(f"Prompt template '{name}' not found")
return self.templates[name]
# prompts/code_review.yaml
# name: code_review
# system: "You are a senior code reviewer."
# template: |
# Review the following {{ language }} code:
# {{ code }}
registry = PromptRegistry("prompts")
messages = registry.get("code_review").render(language="python", code="print('hello')")
In production, extend this with a version field per template and log which version served each request — that’s the difference between “the model got worse” and “prompt v14 changed the system message.” The prompt version control template has a ready-made file format and release checklist.
Caching
LLM calls are slow and metered; cache hits are neither. There are two flavors, and the right one depends on how much variation your queries have.
Exact Match Cache
Identical inputs get identical outputs — hash the full request and short-circuit:
import hashlib
import json
def exact_cache_key(messages: list[dict], model: str) -> str:
# Hash the full message list and model
content = json.dumps({"messages": messages, "model": model})
return f"llm_exact:{hashlib.sha256(content.encode()).hexdigest()}"
async def exact_cached_completion(messages, model="gpt-4o"):
key = exact_cache_key(messages, model)
cached = r.get(key)
if cached:
return json.loads(cached)
response = await client.chat.completions.create(model=model, messages=messages)
result = response.choices[0].message.content
r.setex(key, 3600, json.dumps(result))
return result
Exact cache costs nothing to maintain but only helps repeated queries — great for docs lookups and FAQ bots, useless for free-form chat.
Semantic Cache
Similar questions should hit the same answer. The naive implementation below embeds the query and compares against cached entries — but notice the flaw in how it searches:
import redis
import json
import hashlib
import numpy as np
from openai import AsyncOpenAI
r = redis.Redis(host="localhost", port=6379)
client = AsyncOpenAI()
async def get_embedding(text: str) -> list[float]:
response = await client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return response.data[0].embedding
def cosine_similarity(a: list[float], b: list[float]) -> float:
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
async def semantic_cached_completion(messages: list[dict], threshold: float = 0.95) -> str:
user_query = messages[-1]["content"]
query_embedding = await get_embedding(user_query)
# PRODUCTION WARNING: r.keys() + per-key GET is O(n) and blocks Redis.
# At scale, store vectors in Redis Stack (FT.SEARCH KNN) or pgvector
# and query the index instead of scanning every cached entry.
for key in r.scan_iter("llm_cache:*", count=100):
cached = json.loads(r.get(key))
similarity = cosine_similarity(query_embedding, cached["embedding"])
if similarity > threshold:
return cached["response"]
response = await client.chat.completions.create(model="gpt-4o", messages=messages)
result = response.choices[0].message.content
cache_key = f"llm_cache:{hashlib.md5(user_query.encode()).hexdigest()}"
r.setex(cache_key, 3600, json.dumps({
"query": user_query,
"embedding": query_embedding,
"response": result
}))
return result
scan_iter instead of keys() avoids blocking Redis, but you’re still downloading and comparing every embedding per request — fine at hundreds of entries, broken at tens of thousands. Past that point, put the vectors in an index that does approximate nearest neighbor for you (Redis Stack FT.SEARCH, pgvector, or a dedicated store). The embedding cache pattern covers threshold tuning; set it too low and users get answers to questions they didn’t ask.
Guardrails
Guardrails run twice — on the way in and on the way out. Input checks stop abuse and injection attempts; output checks stop the model from leaking data or producing things you’ll regret.
Input Validation
import re
from dataclasses import dataclass
@dataclass
class GuardrailResult:
passed: bool
reason: str = ""
class InputGuardrail:
def __init__(self, max_length: int = 10000, blocked_patterns: list[str] = None):
self.max_length = max_length
self.blocked_patterns = [re.compile(p, re.IGNORECASE) for p in (blocked_patterns or [])]
def check(self, text: str) -> GuardrailResult:
if len(text) > self.max_length:
return GuardrailResult(False, f"Input exceeds max length of {self.max_length}")
for pattern in self.blocked_patterns:
if pattern.search(text):
return GuardrailResult(False, f"Input matches blocked pattern: {pattern.pattern}")
return GuardrailResult(True)
guardrail = InputGuardrail(
max_length=5000,
blocked_patterns=[
r"ignore (previous|above) instructions",
r"disregard (your|the) system prompt",
r"reveal (your|the) (system|initial) prompt"
]
)
Regex catches the obvious attacks — and only the obvious ones. Determined prompt injection survives keyword lists, which is why serious deployments layer a second model-based check or an external scanner. Treat the regex layer as cheap filtering for the bulk of junk, not a security boundary: the OWASP LLM Top 10 is the reference for what actually gets through, and the LLM security guide covers the full defense stack.
Output Filtering
class OutputGuardrail:
def __init__(self):
self.pii_patterns = [
(re.compile(r'\b\d{3}-\d{2}-\d{4}\b'), '[SSN REDACTED]'),
(re.compile(r'\b\d{16}\b'), '[CARD REDACTED]'),
(re.compile(r'\b[\w.]+@[\w]+\.\w+\b'), '[EMAIL REDACTED]'),
]
def redact_pii(self, text: str) -> str:
for pattern, replacement in self.pii_patterns:
text = pattern.sub(replacement, text)
return text
def check(self, response: str) -> GuardrailResult:
harmful_indicators = ["how to hack", "how to steal", "how to harm"]
lower = response.lower()
for indicator in harmful_indicators:
if indicator in lower:
return GuardrailResult(False, f"Output contains harmful content: {indicator}")
return GuardrailResult(True)
One design decision: redact PII before storing the response anywhere (cache, logs, analytics) — if you cache the raw output, you’ve built a PII database you never wanted.
Observability
When an LLM feature degrades, the first question is “what did the model actually see and return?” Without structured logs that answer is gone.
Structured Logging
import logging
import json
from datetime import datetime, timezone
from uuid import uuid4
class LLMLogger:
def __init__(self, name: str = "llm"):
self.logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(message)s'))
self.logger.addHandler(handler)
self.logger.setLevel(logging.INFO)
def log_request(self, request_id: str, model: str, messages: list, **kwargs):
self.logger.info(json.dumps({
"event": "llm_request",
"request_id": request_id,
"model": model,
"message_count": len(messages),
"total_tokens_estimate": sum(len(m["content"]) // 4 for m in messages),
"timestamp": datetime.now(timezone.utc).isoformat(),
**kwargs
}))
def log_response(self, request_id: str, model: str, response: str,
latency_ms: float, tokens_used: int, **kwargs):
self.logger.info(json.dumps({
"event": "llm_response",
"request_id": request_id,
"model": model,
"latency_ms": latency_ms,
"tokens_used": tokens_used,
"response_length": len(response),
"timestamp": datetime.now(timezone.utc).isoformat(),
**kwargs
}))
def log_error(self, request_id: str, error: str, **kwargs):
self.logger.error(json.dumps({
"event": "llm_error",
"request_id": request_id,
"error": error,
"timestamp": datetime.now(timezone.utc).isoformat(),
**kwargs
}))
llm_logger = LLMLogger()
Every entry carries a request_id so you can join request, response, and error events for one call. Note datetime.now(timezone.utc) — utcnow() is deprecated since Python 3.12. For deeper tracing across services, the same events map onto OpenTelemetry spans with token counts as attributes.
Metrics Collection
import time
from collections import defaultdict
class LLMMetrics:
def __init__(self):
self.request_count = 0
self.token_count = 0
self.error_count = 0
self.latencies: list[float] = []
self.model_usage: dict[str, int] = defaultdict(int)
self.cache_hits = 0
self.cache_misses = 0
def record_request(self, model: str, latency_ms: float, tokens: int,
cached: bool = False, error: bool = False):
self.request_count += 1
if error:
self.error_count += 1
else:
self.latencies.append(latency_ms)
self.token_count += tokens
self.model_usage[model] += 1
if cached:
self.cache_hits += 1
else:
self.cache_misses += 1
def summary(self) -> dict:
latencies = self.latencies[-1000:] # Last 1000 requests
return {
"total_requests": self.request_count,
"total_tokens": self.token_count,
"error_rate": self.error_count / max(self.request_count, 1),
"avg_latency_ms": sum(latencies) / max(len(latencies), 1),
"p95_latency_ms": sorted(latencies)[int(len(latencies) * 0.95)] if latencies else 0,
"cache_hit_rate": self.cache_hits / max(self.cache_hits + self.cache_misses, 1),
"model_usage": dict(self.model_usage)
}
metrics = LLMMetrics()
The numbers worth alarming on: error_rate (provider trouble), p95_latency_ms (user experience), cache_hit_rate (whether the cache is earning its complexity), and total_tokens (the bill). The LLM cost tracking template turns the token metrics into per-model and per-feature cost attribution.
Structured Output
Free text is for humans. Anything downstream code consumes should come back as validated JSON.
Function Calling for Structured Data
import json
from openai import AsyncOpenAI
from pydantic import BaseModel
client = AsyncOpenAI()
class CodeReview(BaseModel):
bugs: list[str]
security_issues: list[str]
improvements: list[str]
overall_score: int # 1-10
async def structured_code_review(code: str, language: str) -> CodeReview:
response = await client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a code reviewer. Analyze the code and return structured feedback."},
{"role": "user", "content": f"Review this {language} code:\n```\n{code}\n```"}
],
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
return CodeReview(**data)
review = await structured_code_review("def add(a, b): return a + b", "python")
JSON Schema Validation with Retry
Models occasionally return malformed JSON or missing fields — validate against a schema and feed the error back once before giving up:
from pydantic import BaseModel, ValidationError
from typing import Optional
class LLMResponse(BaseModel):
answer: str
confidence: float
sources: list[str] = []
follow_up_questions: list[str] = []
async def validated_llm_call(messages: list[dict]) -> Optional[LLMResponse]:
response = await client.chat.completions.create(
model="gpt-4o",
messages=messages,
response_format={"type": "json_object"}
)
try:
data = json.loads(response.choices[0].message.content)
return LLMResponse(**data)
except (json.JSONDecodeError, ValidationError) as e:
# One retry with the error echoed back — models fix this reliably
retry_messages = messages + [
{"role": "assistant", "content": response.choices[0].message.content},
{"role": "user", "content": f"Your response was invalid: {e}. Please fix and return valid JSON."}
]
retry = await client.chat.completions.create(
model="gpt-4o",
messages=retry_messages,
response_format={"type": "json_object"}
)
data = json.loads(retry.choices[0].message.content)
return LLMResponse(**data)
Cap this at one retry — a model that fails twice usually fails forever on that input, and each retry doubles the cost of the call. If your provider supports structured outputs with JSON Schema, prefer the strict mode over json_object: it guarantees schema conformance instead of hoping for it.
Error Handling and Retries
Rate limits and provider hiccups are facts of life. Retry transient errors with backoff; fall back to other models when the primary is down.
import asyncio
from openai import AsyncOpenAI, RateLimitError, APIError
client = AsyncOpenAI()
async def llm_with_retry(messages, model="gpt-4o", max_retries=3, timeout=30):
for attempt in range(max_retries):
try:
response = await client.chat.completions.create(
model=model,
messages=messages,
timeout=timeout
)
return response.choices[0].message.content
except RateLimitError:
# Exponential backoff + jitter would be ideal in multi-worker setups
await asyncio.sleep(2 ** attempt)
continue
except APIError as e:
if attempt < max_retries - 1:
await asyncio.sleep(1)
continue
raise
raise RuntimeError(f"LLM call failed after {max_retries} retries")
# Fallback across models/providers on persistent failure
async def llm_with_fallback(messages):
models = ["gpt-4o", "gpt-4o-mini", "claude-sonnet-4-5"]
for model in models:
try:
return await llm_with_retry(messages, model=model)
except Exception as e:
print(f"Model {model} failed: {e}")
continue
raise RuntimeError("All model fallbacks exhausted")
gpt-4o → gpt-4o-mini is a quality downgrade; gpt-4o → claude-sonnet is a provider failover. Which you pick depends on whether you’d rather degrade answers or stay up — usually the second wins, and cross-provider fallback also survives a full OpenAI outage. The retry pattern covers backoff math and the circuit breaker pattern stops hammering a provider that’s already down — hammering just extends the outage for everyone.
Deployment Patterns
Model Router
Not every request deserves your best model. A router sends trivial queries to cheap models and reserves the expensive one for work that needs it:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
class ModelRouter:
def __init__(self):
self.routes = {
"simple_qa": "gpt-4o-mini",
"complex_reasoning": "gpt-4o",
"code_generation": "gpt-4o",
"summarization": "gpt-4o-mini",
"creative_writing": "gpt-4o"
}
def classify(self, user_input: str) -> str:
input_lower = user_input.lower()
if any(w in input_lower for w in ["write code", "implement", "debug", "refactor"]):
return "code_generation"
elif any(w in input_lower for w in ["summarize", "summary", "tldr"]):
return "summarization"
elif any(w in input_lower for w in ["write a story", "poem", "creative"]):
return "creative_writing"
elif len(user_input) < 100:
return "simple_qa"
else:
return "complex_reasoning"
async def route(self, messages: list[dict]) -> str:
user_input = messages[-1]["content"]
category = self.classify(user_input)
model = self.routes[category]
response = await client.chat.completions.create(
model=model,
messages=messages
)
return response.choices[0].message.content
router = ModelRouter()
Keyword classification is a starting point, not the destination — production routers graduate to a small classifier model or embeddings once traffic justifies it. Whatever you do, log which model served each request: the LLM cost optimization guide has the math for when routing actually pays (hint: when your traffic mix is mostly simple queries).
Async Batch Processing
For background jobs — nightly summarization, bulk classification — fan out with a semaphore cap so you stay under the rate limit instead of bouncing off it:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def process_batch(prompts: list[str], concurrency: int = 5) -> list[str]:
semaphore = asyncio.Semaphore(concurrency)
async def process_one(prompt: str) -> str:
async with semaphore:
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
timeout=60
)
return response.choices[0].message.content
tasks = [process_one(p) for p in prompts]
return await asyncio.gather(*tasks)
# Process 100 prompts with max 5 concurrent
prompts = [f"Summarize topic {i}" for i in range(100)]
results = await process_batch(prompts, concurrency=5)
If your volume qualifies, the provider batch APIs (50% discount on OpenAI’s Batch API, 24h turnaround) beat anything you can build with concurrency — use semaphore throttling for interactive workloads, real batch APIs for bulk.
Production Checklist
- Rate limiting on API endpoints
- Input/output guardrails configured
- Prompt templates versioned and stored externally
- Semantic cache for repeated queries
- Structured logging with request IDs
- Latency and token metrics collected
- Model router for cost optimization
- Fallback models configured
- Streaming responses for long outputs
- Structured output validation with retry
- PII redaction on outputs
- Cost monitoring and alerts
- Evaluation pipeline for quality checks
- Circuit breaker for LLM provider failures
See Also
- Companion project — runnable FastAPI app with every layer from this guide
- Official docs: OpenAI API, Structured Outputs, FastAPI, OWASP LLM Top 10, OpenTelemetry
- Complete Guide to LangChain in Production
- Complete Guide to RAG in Production
- Complete Guide to LLM Cost Optimization
- Complete Guide to LLM Evaluation
- Complete Guide to LLM Security
Frequently Asked Questions
How do I reduce LLM costs in production?
Route simple queries to cheaper models and reserve expensive ones for complex work. Add semantic caching for repeated questions, use batch APIs for offline jobs, and monitor tokens per feature — the cost optimization guide has the full playbook.
What is the best way to manage prompts?
Treat prompts as versioned assets: store them in external files (YAML, JSON), load them through a registry at startup, and log which version served each request. Never hardcode prompts in application code — every change becomes a deploy and nobody can diff regressions.
How do I handle LLM API failures?
Retry rate limits with exponential backoff, configure cross-model or cross-provider fallbacks for outages, add a circuit breaker so you stop hammering a provider that's down, and set explicit timeouts on every call — the SDK defaults wait far longer than users will.
Should I use streaming or batch responses?
Streaming (SSE or WebSocket) for anything a user watches — time-to-first-token is what they perceive as speed. Batch responses for background jobs and non-interactive workflows where simplicity matters more than perceived latency.
How do I evaluate LLM output quality?
Build an evaluation pipeline: golden datasets of inputs and expected criteria, LLM-as-judge grading for subjective quality, and automated checks for format and faithfulness. Track quality metrics over time and correlate with prompt or model changes — the LLM evaluation guide covers dataset design and rubrics.
What guardrails do I need?
Input guardrails: length limits, injection detection, PII screening. Output guardrails: PII redaction, harmful content filtering, format validation. Use both rule-based (cheap, catches bulk junk) and model-based (slower, catches what rules miss) layers, and log every rejection for auditing.
When should I use a framework like LangChain?
When you need composition beyond a single call — chains, agents, retrieval, memory — the abstractions pay for themselves. For a single endpoint doing prompt-in-text-out, direct SDK calls like the ones in this guide have less overhead and fewer moving parts. The LangChain production guide covers that path.
Related Resources
Complete Guide to LangChain in Production
Run LangChain in production: LCEL chains, agents, memory, streaming, RAG, retries, observability and FastAPI deployment patterns that survive real traffic.
GuideComplete Guide to RAG in Production
Take RAG to production: chunking strategies, vector store selection, hybrid retrieval, reranking, RAGAS evaluation, and deployment patterns.
GuideComplete Guide to LLM Evaluation
Evaluate LLM apps in production: RAGAS, LLM-as-judge, hallucination detection, human eval, A/B testing and CI/CD regression pipelines.
GuideComplete Guide to LLM Cost Optimization
Cut LLM costs in production: model routing, prompt compression, caching, Batch API, token budgets and cost monitoring with real numbers.
PatternCircuit Breaker Pattern in Python, JavaScript, and Java
Prevent cascading failures by stopping requests to failing services. An architectural pattern for resilient distributed systems.
DocAI LLM Incident Response Runbook
Operational runbook for LLM production incidents: hallucination events, model outages, cost spikes, safety failures, and degraded quality. Includes severity levels, escalation paths, diagnostic steps, and recovery procedures.