Production LLM Architecture
A Systems Handbook for Engineers Shipping AI

About This Book

Most LLM applications shipping to production today run 10–50x more expensively than they need to. Latency is higher than users will tolerate, infrastructure costs are higher than the business can sustain, and the gap between a promising demo and a reliable product remains stubbornly wide.

The problem is not the model. The problem is everything around the model: context that is too large, prompts that are reprocessed on every call, tasks routed to expensive models that cheaper ones handle just as well, agent loops with no bounds.

This book is the engineering layer above model selection. It defines six governing laws of production LLM systems and applies them across fourteen chapters covering inference mechanics, context architecture, execution strategy, and deployment operations. Every technique is grounded in production results — what actually breaks at scale, not what looks good in benchmarks.

Target reader: Senior engineers, platform engineers, and technical leads responsible for the latency, cost, and reliability of LLM-powered systems. You already know what LLMs are. This book shows you how to ship them.


Contents

Part I — Inference Mechanics
  • Chapter 1: The Life of a Prompt — The four stages of inference and why input length is the primary cost and latency lever. (This chapter)
  • Chapter 2: The KV Cache — How the transformer memory system works, and why cache misses silently double your costs.
Part II — Context Architecture
  • Chapter 3: Data Engineering for LLMs — Restructure data at the source: JSON compaction, table aggregation, and format choices that cut token counts by 40–60%.
  • Chapter 4: Query-Aware Filtering — Send only what this specific query needs. Classifier-based filtering that reduces retrieved context by 70–90% without quality loss.
  • Chapter 5: Prompt Caching Architecture — Eliminate the cost of reprocessing static content. Cache breakpoints, TTL management, and the multi-tenant pitfalls that silently break hit rates.
  • Chapter 6: Instruction Minimalism and Output Control — Shrink system prompts and constrain output format. Every redundant instruction token is a tax on every request.
  • Chapter 7: Tiered Model Architecture — Route each task to the cheapest model that meets quality thresholds. The cost gap between tiers is several-fold; most tasks belong in the fast tier.
Part III — Execution Architecture
  • Chapter 8: Pipeline Orchestration — Parallelize independent calls, set latency budgets per stage, and implement circuit breakers that prevent one slow model from stalling the pipeline.
  • Chapter 9: Tool Use and Agent Architecture — Bounded agent loops, tool definition efficiency, and the failure modes that cause agents to run forever or hallucinate tool calls.
  • Chapter 10: Evaluation Frameworks — Build evaluation pipelines that catch regressions before they reach users. Shadow evaluation, quality gates, and the metrics that matter in production.
  • Chapter 11: Retrieval Architecture — Retrieval recall vs. precision tradeoffs, chunking strategies, and the reranking layer that separates useful RAG from expensive noise.
  • Chapter 12: Guardrails and Safety — Input classification, output validation, and the classify-then-route pattern that keeps costs low while maintaining safety coverage.
Part IV — Deployment & Operations
  • Chapter 13: From Prototype to Production — The migration checklist: evaluation infrastructure, provider fallback, version pinning, and the operational gaps that cause production incidents.
  • Chapter 14: Production Failure Modes — Twenty-four documented failure modes, each with symptom, root cause, and fix. The complete field guide for debugging LLM systems in production.
Appendices
  • Provider Differences · Token Accounting · Production Checklist · Glossary · Acronyms · Batch vs. Real-Time Decision Framework · Self-Hosted vs. API Breakeven Analysis · GPU Capacity Planning · Production LLM Reference Architecture · Domain Translation Table

The Six Laws of Production LLM Systems

Every chapter in this book applies one or more of these laws. They are the governing constraints of every LLM system in production.

Law 1 — Prefill: All input tokens are processed before the first output token appears. Input length governs time-to-first-token.
Law 2 — Sequential Output: Decode generates tokens one at a time. Output length governs total response time.
Law 3 — Prefix Stability: Cached prefix content must be byte-identical across requests for cache reuse.
Law 4 — Information Density: Every token should carry information the model can use. Redundancy is paid in compute.
Law 5 — Routing: Assign each task to the cheapest model capable of handling it.
Law 6 — Bounded State: Explicitly cap every resource — tokens, iterations, retries, memory.
Part I — Inference Mechanics

How LLM inference works at the hardware level

Chapter 1: The Life of a Prompt

Laws addressed: Prefill (Law 1), Sequential Output (Law 2)

Context Engineering Defined

Context engineering is the discipline of designing and optimizing everything sent to a language model — system prompts, retrieved data, conversation history, tool definitions — to minimize cost and latency while preserving response quality.

It is not prompt engineering. Context engineering is the engineering layer above: deciding what data to include, how to structure it, what to cache, what to filter, and when to route to a different model.

If prompt engineering is writing a good email, context engineering is designing the mail system.

What Happens When You Call the API

A typical API call:

response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system="You are a helpful math tutor for grade 5...",
    messages=[
        {"role": "user", "content": "How do I add fractions?"}
    ]
)

Between client.messages.create() and the response, four distinct stages execute — each with different performance characteristics and optimization opportunities.

Step 1: Tokenization

Text enters the model as tokens — chunks typically representing 3-4 characters in English. The sentence "How do I add fractions?" becomes roughly seven tokens.

Tokens are the fundamental unit of LLM economics — pricing, latency metrics, and every optimization in this book operate at the token level.

INVARIANT Different models use different tokenizers. The same text produces different token counts on Claude, GPT, and Llama. Token-level optimizations are not portable between providers. Always use the tokenizer for the specific model you target.

Token Counting Rules of Thumb

1 token ≈ 4 characters ≈ 0.75 words in English prose

A 2,000-word document ≈ 2,700 tokens

Code tokenizes at ~2-3 characters per token (less efficient than prose)

Structured data is less efficient: {"name": "Alice"} costs 10 tokens; name: Alice costs 4

Step 2: Prefill — Processing the Input

Once tokenized, the entire input — system prompt, conversation history, user message, tool definitions — enters the model in a single batch. The model processes all tokens simultaneously in the prefill phase.

During prefill, the model transforms each input token into internal Key and Value vectors. This is computationally intensive — heavy matrix multiplications — but because all input tokens are known upfront, the work is parallelized across the GPU's thousands of cores.

INVARIANT Prefill time scales approximately linearly with input length for moderate context sizes (under ~16K tokens). Double the input tokens, roughly double the prefill time. At longer contexts, the quadratic attention computation (each token must attend to every other token, so work grows with the square of input length) becomes significant, and prefill time grows faster than linearly.

Reference latencies for a 70B parameter model on NVIDIA A100 (312 TFLOPS; newer accelerators are faster in absolute terms, but the scaling pattern is identical):

Input SizePrefill TimeRelative to 1KNotes
1,000 tokens~0.45 seconds1xLinear regime
5,000 tokens~2.25 seconds5xLinear regime
10,000 tokens~4.5 seconds10xLinear regime
50,000 tokens~27-30 seconds60-67xAttention overhead visible
100,000 tokens~65-90 seconds145-200xQuadratic attention dominates

At short-to-moderate contexts (<16K), feedforward computation dominates and scaling is effectively linear (~0.45ms per token). At longer contexts, the O(n²) attention computation becomes the bottleneck. FlashAttention and related optimizations reduce memory overhead but do not eliminate the compute scaling. Managed API latencies differ in absolute terms but follow the same scaling pattern.

The difference between a 5,000-token context and a 50,000-token context is roughly twenty-five seconds of waiting before the model generates a single output token. That is not network latency or slow code. It is compute: more input means more computation. This is Law 1 (The Prefill Law) in action.

Step 3: Decode — Generating the Response

Once prefill completes, the model produces output tokens one at a time. This is the decode phase. Decode is inherently sequential — the model must produce token 1 before token 2, because each token's probability depends on every token before it.

Decode has a fundamentally different performance profile. Prefill is compute-bound (GPU busy calculating). Decode is memory-bound (GPU spends most time loading model weights from memory). Each output token takes roughly the same time to generate, regardless of input length.

Model ClassApproximate Decode Speed1,000 Tokens Takes
70B (e.g., Llama 70B on A100)~11 tokens/second~90 seconds
Medium (~30B, API mid-tier)~30-40 tokens/second~25-33 seconds
Small (~8B, API fast tier)~60-80 tokens/second~12-17 seconds

Decode speed is approximately constant with respect to input length. At very long contexts (100K+), KV cache reads add minor overhead.

DESIGN RULE Decode speed does not meaningfully change whether input was 1,000 or 100,000 tokens. The model generates output at roughly the same rate either way. This asymmetry — input cost scales, output cost is fixed per token — is the foundation of every optimization that follows.

Step 4: Streaming

Streaming exposes the two-phase architecture directly to the user:

These map to two critical metrics:

MetricWhat It MeasuresControlled By
Time to First Token (TTFT)Delay before response startsPrefill time (input length)
Tokens per Second (TPS)Speed of streaming outputDecode rate (model + hardware)

TTFT is the metric users feel most acutely. 200ms feels instant. 2 seconds feels slow. 20 seconds feels broken. Since TTFT is driven by prefill, which scales with input length, context engineering directly controls user-perceived responsiveness. This is Law 1 applied to user experience.

DESIGN RULE For any user-facing application, always enable streaming. Without it, the user waits for the entire response (prefill + full decode) before seeing anything.

The Two Phases: A Concrete Comparison

Figure 1.1: Prefill processes all input tokens in parallel; Decode generates output tokens one at a time
Figure 1.1: Prefill processes all input tokens in parallel; Decode generates output tokens one at a time

Baseline: mid-tier model (Sonnet-class), managed API, 500-token response.

Bloated AgentOptimized Agent
Input tokens50,0005,000
Output tokens500500
TTFT (prefill)~8 seconds~0.8 seconds
Decode time~14 seconds~14 seconds
Total time~22 seconds~14.8 seconds
Improvement33% faster, 10x less input cost

Input reduced by 90%. Total response time dropped by a third. Decode time unchanged. Response identical in length and quality. The user receives it 7 seconds sooner, with sub-second TTFT instead of eight seconds of blank screen.

At typical API pricing, 45,000 eliminated input tokens save money on every request — across thousands of daily users, the difference between a sustainable product and one that bleeds money.

INVARIANT Reducing input tokens improves the expensive phase (prefill) while leaving the useful phase (decode) untouched. Faster, cheaper, no quality degradation.

What Is in the Context Window

Typical context breakdown by application archetype:

ComponentSimple ChatbotRAG ApplicationTool-Using Agent
System prompt800 tokens2,000 tokens3,500 tokens
Tool definitions8,000 tokens
Retrieved context12,000 tokens6,000 tokens
Conversation history1,500 tokens3,000 tokens2,500 tokens
User message100 tokens200 tokens150 tokens
Total input2,40017,20020,150
User message as % of total4.2%1.2%0.7%
Figure 1.2: Context window composition across three application types
Figure 1.2: Context window composition across three application types

Two observations:

  1. The user's actual question is typically 1-4% of total input (often under 1% for tool-heavy agents). The other 96-99% is context: instructions, data, history, tool definitions.
  2. A large portion of that context is identical across every request. System prompt and tool definitions never change. This static content gets re-processed from scratch on every API call — unless you act on it.

The dynamic content — retrieved context, conversation history — is often larger than necessary for any given query. A user asking "What's my next assignment?" does not need 12,000 tokens of course material. Sending it all is the default behavior of most RAG implementations, and it is where the largest optimization opportunities exist.

The Optimization Stack: Preview

Five optimization layers, each targeting a different point in the pipeline:

LayerStrategyWhat It DoesChapter
1Data EngineeringRestructure data for fewer tokensCh 3
2Query-Aware FilteringSend only what is relevant to this queryCh 4
3Prompt CachingSkip re-processing static portionsCh 5
4Prompt SimplificationReduce instruction and output overheadCh 6
5ArchitectureRoute queries, parallelize calls, right-size modelsCh 7-9

These layers compound. Applying all five to a production agent typically yields 85-95% reduction in token usage and drops latency from tens of seconds to single digits.

A Note on Real-World Latency

The latencies in this chapter represent raw computation. Actual API latency includes network round-trips, request queuing, and provider-side optimizations. Measured numbers differ from theoretical calculations, but proportional relationships hold — a 10x input reduction yields substantial real-world TTFT improvement.

Failure Mode: Unaudited Context

Symptom: High latency and cost with no clear cause. API bills are 5-10x expected.

Root cause: The development team has never measured the actual token composition of their prompts. The system prompt is 5,000 tokens (thought to be "short"), retrieved context is 15,000 tokens (sent in full regardless of query), and conversation history is unbounded. Nobody knows because nobody logged it.

Fix: Instrument your API calls to log token counts by category (system, tools, retrieved, history, query). Calculate static percentage and excess percentage. Most teams find 60-80% of tokens are either static (cacheable) or excess (removable). This audit is the prerequisite for every optimization in the book.

Law violated: Prefill (Law 1), Bounded State (Law 6)

Checklist

  • Measure your application's TTFT under current load
  • Log the full prompt for 10 real requests and categorize every token: static, dynamic-necessary, dynamic-excess, user message
  • Calculate your static percentage and excess percentage
  • Identify the largest single source of token waste (usually retrieved context or tool definitions)

What You Now Know

The core insight: your LLM application spends most of its time and money processing the input, not generating the answer. The prefill phase — processing system prompt, retrieved context, conversation history — is the bottleneck. The decode phase is largely fixed.

Every unnecessary token in your input costs three times over: API fees, user-facing latency, and infrastructure capacity. Context engineering eliminates that waste — not by sending less, but by sending smarter: the right data, in the right format, cached where possible, filtered for relevance, and routed to the right model.

This is a sample chapter from Production LLM Architecture by Debabrata Acharjee. The full book continues with thirteen more chapters covering the KV cache, data engineering, query-aware filtering, prompt caching, instruction minimalism, model routing, pipeline orchestration, evaluation frameworks, retrieval architecture, guardrails, deployment operations, and a complete production failure mode catalog.

Get notified when it's live →

About the Author

Debabrata Acharjee is a software engineer specializing in production AI infrastructure. He has designed and optimized LLM deployment pipelines across multiple organizations — working on the latency, cost, and reliability problems that emerge when prototypes meet real traffic.

Production LLM Architecture is the systematic framework that came out of that work. Not a survey of model capabilities, but an engineering discipline for the layer that surrounds the model: how you structure context, cache state, route tasks, and bound resources. The six laws in this book are the constraints that govern every LLM system in production, whether or not you have named them.