Architecture
LLM Production Architecture: The Six Layers You Need
The six layers of an LLM production architecture: serving, orchestration, retrieval, caching, observability and guardrails, with decision criteria and a one-week audit.
Key takeaways
- An LLM production architecture has six layers: serving, orchestration, retrieval, caching, observability, and guardrails, and most demos fail because only the first two were designed.
- Start API-first and cut token spend with model routing and prompt caching before ever considering self-hosted inference.
- Retrieval fails quietly through stale or truncated chunks, so index on write for fast-changing data and track recall and precision on a real-question eval set.
- Trace every request end to end with per-span token counts so you can attribute cost and quality regressions to a specific layer.
- Run a one-week audit: replay real traffic, trace failed agent runs, sample retrieval results, measure cache hit rate, and fix the single costliest layer first.
An LLM production architecture is six layers stacked between your prompt and your users: serving, orchestration, retrieval, caching, observability, and guardrails. Most demos fail in production because one or two of those layers were never designed, and the token bill and reliability problems show up only under real traffic. This guide maps all six in one diagram, with decision criteria for each.
What does an LLM production architecture actually consist of?
Six layers, in the order a request hits them: serving (the model API or self-hosted inference), orchestration (the code that routes prompts, tools, and agent steps), retrieval (the RAG pipeline feeding context), caching (reusing responses and embeddings so you stop paying full price for repeat traffic), observability (tracing and evals that show you what actually happened), and guardrails (input and output checks at each boundary). Most teams have layer one and a sketch of layer two. The other four are where production reliability gets won or lost.
The one diagram: request path from user to response
Follow one request end to end. A user message arrives and passes an input guardrail. Orchestration decides whether this is a single completion or an agent loop with tool calls. Retrieval pulls relevant context from your vector store.
A cache check runs first, because a hit costs roughly nothing instead of full inference price. The serving layer generates a response, an output guardrail screens it, and observability records a trace of every hop with token counts attached. That trace is what tells you whether a quality regression came from retrieval, the model, or your prompt. Token costs compound along this path: hosted model APIs bill per input and output token, and pricing is published on vendor pricing pages like OpenAI's (pricing), so a 10x jump in real traffic multiplies every layer's bill, not just the model's.
Why demos skip most of these layers
A demo runs one request at a time with a friendly prompt, so caching, guardrails, and tracing look like overhead. Real users send hostile inputs, repeat the same questions, and hit rate limits in bursts. The layers you skipped become the incident. More on each layer in the rest of the blog.
Which serving layer should you pick, and when does the token bill force a change?
API-first vs self-hosted inference
At 2-20 people, start with an API-first serving layer. Your bottleneck is shipping reliability under real traffic, not squeezing cents per token, and APIs let you swap models without touching GPU fleets. Self-hosting earns its keep when volume is high and predictable enough that reserved GPU capacity beats per-token pricing, or when latency SLOs or data-residency rules rule out third-party APIs.
| Criterion | API-first | Self-hosted |
|---|---|---|
| Fixed cost | Zero upfront | GPU fleet + ops hire |
| Cost per token | Highest at scale | Drops with volume |
| Latency control | Provider-dependent | You own p99 |
| Model swaps | Minutes | Weeks of porting |
| Break-even | Always cheaper early | Only at steady, high volume |
The honest trade-off: self-hosting converts variable token spend into fixed engineering cost. If nobody on your team owns inference ops today, that fixed cost is a salary, not a line item. I see this trade-off weekly in my consulting work.
When to route between models
Route before you self-host. Sending cheap requests to a small model and reserving the frontier model for hard inputs typically cuts the token bill without touching quality, and it keeps your serving layer API-first. Add routing when one model's per-token cost dominates your bill and your evals show a smaller model passes on a measurable share of traffic.
How should the orchestration layer be structured for agents?
Agent loops, state, and retries
An agent loop is three things: a call to the model, a tool call, and a check on whether to stop. Keep that loop explicit in your own code so you can log every iteration and cap every run. State belongs in a durable store keyed by run ID, not in a growing prompt, so a crashed run resumes instead of restarting. Retries need two tiers: fast retries on transient API errors with exponential backoff, and a replay path that reloads state rather than re-running the whole loop. Without that split, one flaky provider call quietly doubles your token bill.
Frameworks vs plain code
A framework earns its place when you need multi-agent handoffs, human-in-the-loop approval, or graph-based control flow you would otherwise hand-roll. If your agent is a single loop with a handful of tools, plain code with a tracing hook is easier to debug and cheaper to reason about. One concrete saving either way: most providers offer prompt caching, which cuts the cost of re-sending long system prompts and tool schemas on every turn (see Anthropic's prompt caching documentation). If the architecture decisions above are the gap between your demo and production, this is the work I handle day to day — more on my background at federicomolina.com/about.
Where does retrieval (RAG) break first in production?
Retrieval rarely fails loudly. It fails quietly: the right document exists, but the chunk returned is stale, truncated, or never indexed.
Chunking and freshness
Fixed-size chunks split mid-table or mid-function, so the model gets half a fact. Match chunk size to your content: sections for docs, function boundaries for code. Freshness is the bigger production gap. If your index rebuilds nightly but your product data changes hourly, users get confident answers from yesterday's truth. Index on write for anything that changes fast, and store a timestamp per chunk so you can detect staleness.
Measuring retrieval quality, not vibes
Before real traffic, build a small eval set of real user questions with the documents that should be retrieved. Track recall (did the right chunk appear in the top-k?) and precision (how much of the context window is filler you paid tokens for?). Re-run it after every chunking or embedding change. Retrieval regressions are invisible in demos and expensive under load, which is exactly the gap I work on; see selected work.
What should you cache to cut inference cost without hurting quality?
Three cache layers do different jobs. Response caching stores exact outputs for identical requests and is free of quality risk, but real traffic rarely repeats. Prompt caching lets providers reuse the static prefix of your prompt (system message, few-shot examples, retrieved context) at reduced rates, and OpenAI documents this as automatic for eligible requests on its API (OpenAI pricing docs). Semantic caching matches new queries to past ones by embedding similarity, which is where quality risk enters: a near-match can return a stale or wrong answer.
Prompt caching vs semantic caching
Prompt caching is a no-brainer first move: it changes nothing about your output, only what you pay for repeated prefixes. Semantic caching needs a similarity threshold, an eval set to tune it, and tracing to catch bad hits before users do.
Hit-rate math: an illustrative worked example
Say 20% of queries semantically hit, cached answers cost a tenth of a full call, and your monthly bill is $10,000. Savings are 20% × 90% = $1,800, minus eval and monitoring overhead. If bad hits force a rollback, the threshold was too loose. If you're auditing where caching fits in your stack, my services page covers that review.
What observability do you need before real users hit the system?
Uptime monitoring tells you the API responded. It says nothing about whether the response was correct, whether retrieval returned the right chunks, or whether a token bill is quietly doubling week over week. You need three things wired before launch: tracing on every call, evals running in CI, and alerts that fire on quality regressions, not just 5xx errors.
Tracing every call end to end
Each request should produce one trace covering the full path: incoming prompt, retrieval results, orchestration steps, model calls, token counts, and latency per span. When an agent misbehaves under real traffic, you debug by reading the trace, not by guessing which step failed. Without per-span token counts, you cannot attribute cost to a feature, a prompt version, or a user segment, which means you cannot cut the bill surgically.
Evals as a release gate
Build a small eval set from real production failures, even if it starts at 20 to 50 cases. Run it in CI against every prompt change, retrieval config change, or model swap, and block deploys that regress. Then alert on the same metrics in production: a drop in retrieval hit rate or a spike in refusals should page you the same way latency does.
Which guardrails belong at which layer?
Input vs output guardrails
Input guardrails run before the prompt reaches the model: prompt-injection detection, PII scrubbing, topic filters, and schema validation on structured fields. They are cheap to enforce at the API gateway or orchestration entry point, and they protect your token bill by rejecting junk before inference runs. Output guardrails run after generation: refusal detection, factuality checks against retrieved sources, and format validation before the response reaches the user or a downstream tool. Output checks cost more because they often need a second model call, so scope them to high-risk paths like tool invocation and external messaging rather than every response.
Graceful degradation paths
Every guardrail needs a defined failure behavior, decided before real users hit it. Block and return a safe fallback message, retry with a stricter prompt, or route to a cheaper model with tighter instructions. The failure mode that kills production reliability is a guardrail that silently drops the request: the user sees nothing, your tracing shows a gap, and you find out from a support ticket. Log every guardrail intervention as a traced event with the reason and the rule that fired, the same way you trace latency and token spend. OpenTelemetry's generative AI observability conventions give you a standard span structure for attaching those events to the rest of your trace.
How do you audit your own architecture in a week?
The six-layer audit checklist
Day one, replay last week's real traffic against your serving layer and record p95 latency and cost per request. Day two, trace three failed agent runs end to end and find where orchestration lost state or looped. Day three, sample retrieval results for your ten most common queries and grade relevance manually.
Day four, measure your cache hit rate; under 20% on repeated traffic means money on the table. Day five, confirm every production request emits traces and that evals run on a sample of them. Day six, log every guardrail trigger and check whether blocks are false positives. Day seven, write down the single layer that costs you the most and fix that one first.
Fractional architect vs hiring vs marketplaces
A senior AI-architecture hire takes months and costs a full salary before you know if the demo-to-production gap is a two-week fix or a rebuild. Marketplaces like Toptal, A.Team, and Upwork give you individuals who execute tasks but don't own the architecture decision across all six layers. Specialist shops like The Fractional CTO cover general startup technical leadership, not LLM-specific production work.
A fractional AI architect runs this audit, fixes the highest-cost layer, and hands your team the decision criteria, on a fraction of a full-time hire. That fits a 2-20 person team with buying authority and no senior AI hire: you pay for the diagnosis and the first fix, then decide whether the gap justifies a permanent role.
FAQ
Can a fractional CTO design my LLM production architecture without joining full-time?
Yes. The audit format maps all six layers in about a week, identifies the single layer costing you the most, and fixes that first. You get the diagram, the decision criteria, and the first repair delivered, then decide whether the gap justifies a permanent senior hire. That fits a 2-20 person team with no AI specialist on staff.
How much of my token bill comes from layers other than the model?
More than most teams expect. Uncached repeated traffic pays full inference price, agent loops that retry without durable state can double spend, and retrieval that stuffs filler into the context window bills you for tokens that add nothing. Tracing with per-span token counts is how you attribute cost to a feature, prompt version, or user segment.
Should I self-host models before adding caching and routing?
No. Routing cheap requests to smaller models and enabling provider prompt caching both cut spend while keeping your serving layer API-first, and neither requires owning GPUs. Self-hosting only breaks even at steady, high volume, and it converts variable token spend into a fixed engineering cost that includes someone owning inference ops.
What is the fastest way to find where my architecture will fail?
Replay last week's real traffic and record p95 latency and cost per request, then trace three failed agent runs end to end. Sample retrieval results for your ten most common queries, measure cache hit rate, and confirm every request emits a trace. Real users send hostile inputs and repeat questions, so demo behavior tells you little.
Do I need all six layers before launch?
Not fully built, but each needs a designed minimum. A small eval set of 20 to 50 real cases, tracing on every call, basic guardrails at the API boundary, and prompt caching are cheap to add early and expensive to retrofit. The layers you skip become the incident once traffic arrives, because demos run one friendly request at a time.