Latency Optimization
Make AI features feel fast: time to first token, output length, parallelism, smaller models, caching and speculative work.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Deploying LLM-Powered Services, Tracing and LLM Observability
Users judge AI features by how quickly something useful appears. Two numbers matter most: time to first token (TTFT) and total generation time, which is driven mostly by how many output tokens you generate.
Biggest levers
- Stream everything user-facing. It does not reduce total time but transforms perceived speed.
- Generate fewer tokens: ask for concise answers, cap max tokens, and avoid making the model repeat input back. Output tokens are much slower than input tokens.
- Use a smaller or faster model for steps that do not need the largest one: classification, routing, extraction, query rewriting.
- Parallelize independent calls (retrieval plus guardrail plus classification) instead of running them one after another.
- Prompt caching reduces TTFT for long, repeated prefixes like big system prompts or documents.
- Reasoning budgets: extended thinking improves hard tasks but adds seconds; set budgets per task.
Pipeline hygiene
- Measure each stage with tracing and optimize the slowest one first.
- Keep connections warm and reuse HTTP clients.
- Choose provider regions close to your servers and users.
- Precompute what you can: embeddings, summaries and common answers.
Speculative and optimistic UX
Start retrieval while the user is still typing, show partial results, or run a quick draft answer while a slower model verifies it.
Good enough to move on
You can profile a slow RAG endpoint, show a per-stage latency breakdown, and cut its p95 latency substantially with at least three techniques from this list.
Key concepts
- Time to first token
- Output length control
- Smaller models for sub-tasks
- Parallel calls
- Prompt caching for TTFT
- Per-stage latency profiling
- Speculative UX patterns
Mini project
Take a RAG endpoint with p95 above 8 seconds, trace each stage, apply streaming, parallel retrieval and guardrails, a smaller rewrite model and output caps, and document the new latency breakdown.
Check yourself
Why does halving the output length usually speed up a response more than halving the input length?
Free resources
- OpenAI docs: latency optimization (OpenAI)
- Anthropic docs: reducing latency (Anthropic)