15 LLM Latencies: Where Your AI App Is Slow and How to Fix It
Most slow AI features are not slow because of the model. Latency hides in 15 places across four layers. Measure each one, find the slow stage, and fix that, instead of swapping models.
By Shafin ZamanLast updated 28 min readEvery number sourced
All 15 latencies, fixes and code as one Markdown file.
TL;DR
When an AI feature feels slow, the reflex is to swap the model. Sometimes that is the answer. Usually it is not, because the model call is one stage of many: a retrieval that crosses a region, an embedding call in a Python loop, a reasoning model thinking hard about a yes-or-no question, four tool calls made one after another, a container that had to boot first.
This guide splits latency into 15 types across the four layers where it hides. For each one: what it is in plain English, how to measure it, what causes it, the fixes (split into hosted APIs like Claude, OpenAI and Gemini, and self-hosting with vLLM, SGLang or TensorRT-LLM), and one honest caveat. Every number, flag and parameter was checked against the official docs or the original paper on 20 October 2026, and each section lists its sources.
The biggest latency fix of all: skip the LLM call. Extracting an order number, ranking documents or tagging a ticket takes microseconds to milliseconds with regex, BM25 or a small classifier, against hundreds of milliseconds to seconds for a model call. The classic NLP toolkit covers when you do not need an LLM at all.
Measure first
You cannot fix a stage you have not timed. Three numbers describe almost every request, and all three should be measured where the user is, on the client.
- TTFT
- Time to first token: how long until the first word appears. It decides whether the app feels responsive.
- Tokens/s
- How fast text flows after that, the inverse of time per output token. It decides how long a long answer takes.
- End-to-end
- Send to last token. The number that counts whenever code, not a person, consumes the answer.
This script records all three from a streaming call, separating the thinking tokens a reasoning model spends before it answers from the tokens the user actually sees:
import statistics
import time
import anthropic
client = anthropic.Anthropic()
def timed_call(prompt: str, model: str = "claude-opus-5-5") -> dict:
start = time.perf_counter()
first_text = None
with client.messages.stream(
model=model,
max_tokens=2048,
messages=[{"role": "user", "content": prompt}],
) as stream:
for event in stream:
if (
first_text is None
and event.type == "content_block_delta"
and event.delta.type == "text_delta"
):
first_text = time.perf_counter() # first word the user can see
final = stream.get_final_message()
end = time.perf_counter()
first_text = first_text or end
# Reasoning models think before they answer. Count only the visible tokens.
details = final.usage.output_tokens_details
thinking = (details.thinking_tokens or 0) if details else 0
visible = final.usage.output_tokens - thinking
writing_time = end - first_text
return {
"ttft": first_text - start, # includes network, queue, prefill, thinking
"e2e": end - start,
"tok_per_s": (visible - 1) / writing_time if visible > 1 and writing_time else None,
}
runs = [timed_call("Summarise our refund policy in three bullets.") for _ in range(50)]
for metric in ("ttft", "e2e", "tok_per_s"):
xs = [r[metric] for r in runs if r[metric] is not None]
cuts = statistics.quantiles(xs, n=100, method="inclusive") # 99 cut points
print(f"{metric:>9} p50={cuts[49]:.2f} p99={cuts[98]:.2f} mean={statistics.mean(xs):.2f}")Why P50 and P99 beat averages
Latency is never a single number; it is a distribution with a long tail. Most requests are quick and a few are very slow, so the average lands somewhere in between and describes nobody. Google's SRE book puts it plainly: a simple average can obscure tail latencies, and percentiles are preferred over the mean.
Report P50 (the typical user) and P99 (the slowest one in a hundred) for every route. The tail matters more than it looks, because requests that depend on several calls inherit the slowest one. In The Tail at Scale, Dean and Barroso show a server that is slow on just 1% of requests makes 63% of requests slow once each one fans out to 100 such servers. An agent that makes ten model calls per task is a small version of the same problem.
For targets, the classic thresholds from Nielsen Norman Group still hold: 0.1 seconds feels instantaneous, 1 second keeps the user's flow of thought uninterrupted, and 10 seconds is about the limit of their attention. Streaming is how an LLM answer that takes ten seconds still starts inside the second.
Latencies 1–4
What users feel
The four numbers a person actually experiences. Measure them at the client, where the user is, not on the server.
1.Time-to-first-token (TTFT)
The wait between sending a request and seeing the first word of the answer. It covers the network, any queue, reading the prompt (prefill) and, on reasoning models, the thinking that happens before the first visible word. This is the number that makes an app feel fast or broken.
How to measure it
Stream the response and timestamp the first text chunk on the client. Measure where the user is: a server-side number leaves out the network. On reasoning models, track time to first visible token separately from time to first token of any kind, because thinking can sit between them.
Main causes
- Long prompts, so prefill takes a while
- Retrieval, reranking or tool calls that run before the model call
- Reasoning before the first visible word
- Queueing at the provider or on your own server
- No streaming at all, so the user's TTFT is the whole end-to-end time
Using a hosted API
- Stream every response a person reads. OpenAI calls it the single most effective approach, because it cuts the waiting time to a second or less.
- Cache the stable prefix. Anthropic's docs say you will generally see improved time-to-first-token for long documents. A request with max_tokens set to 0 pre-warms the cache before the first real user arrives.
- Lower reasoning effort on routes that do not need it. Gemini's docs warn that a high thinking level may take significantly longer to reach a first (non-thinking) output token.
- OpenAI suggests asking reasoning models for a short preamble, so something visible arrives before the long thinking ends.
Self-hosting
- Prefix caching (on by default in vLLM and SGLang) so repeated system prompts are not recomputed.
- Keep the queue short: a request that waits for a slot pays that wait as TTFT.
- Chunked prefill trades a little TTFT for smoother tokens. vLLM's docs say higher --max-num-batched-tokens values achieve better TTFT, smaller ones better inter-token latency.
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=2048,
messages=[{"role": "user", "content": "Where is order #4417?"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True) # the user starts reading hereCaveat
Streaming changes how long the wait feels, not how long the answer takes. If your code must have the whole output before it can act, for example to parse JSON, run a guardrail or call a tool, streaming to the user helps much less, and end-to-end latency is the number to work on.
SourcesNVIDIA NIM: LLM benchmarking metricsOpenAI: latency optimizationAnthropic: prompt cachingGemini: thinkingOpenAI: reasoning modelsvLLM v0.32: optimization and tuning
2.Time-per-output-token (TPOT)
How long each token takes after the first one, so how fast the text flows once it starts. Its inverse is tokens per second for one user. Nearly the same thing is called inter-token latency (ITL); NVIDIA defines it as (end-to-end − TTFT) ÷ (output tokens − 1).
How to measure it
Divide the time after the first token by the number of tokens after it. Count tokens from the API's usage numbers, not from stream chunks, because one chunk can carry several tokens. On reasoning models, subtract the thinking tokens or the speed looks better than what the user sees.
Main causes
- Model size: a bigger model does more work for every token
- Load on the server: more users in the same batch means a slower share for each
- Very long contexts, which make every decode step read more memory
- The service tier you are on
Using a hosted API
- Use a smaller, faster model for steps that do not need the big one. Anthropic's latency guide points at Claude Haiku 5.5 for speed-critical work.
- Anthropic's fast mode delivers up to 2.5x higher output tokens per second at premium pricing on Claude Opus 5.5. The docs are explicit that the gain is output speed, not time-to-first-token.
- OpenAI's fast mode (service_tier "fast", formerly priority processing) is described as up to 2.5× faster with more consistent latency, also at a higher price.
Self-hosting
- Quantize weights and the KV cache. vLLM's FP8 page cites a 2x reduction in model memory and up to 1.6x throughput, and notes that latency gains are limited in its online dynamic mode.
- Speculative decoding (see decode latency) to cut inter-token latency at low to medium load.
- Lower --max-num-seqs to give each user a bigger share of the GPU, at the cost of total throughput.
Caveat
Once text streams faster than people read, a faster TPOT stops being felt in a chat window. It still matters for long outputs and for machines reading the answer, such as agents and JSON pipelines, so decide which one you are optimizing for before paying for a faster tier.
SourcesNVIDIA NIM: LLM benchmarking metricsDatabricks: LLM inference performance engineeringAnthropic: reducing latencyAnthropic: fast modeOpenAI: fast modevLLM: FP8 quantization
3.End-to-end latency
The whole request, from send to the last token. Roughly TTFT plus TPOT times the number of output tokens. For anything that needs the complete answer before it can act, such as structured output, a tool call or a batch job, this is the only latency that counts.
How to measure it
Wall-clock time around the full call, on the client. Then break it into spans (retrieval, model call, each tool) with whatever tracing you already have, so you can see which stage owns the time.
Main causes
- Long outputs: every extra token costs one more TPOT
- Reasoning tokens generated before the answer
- Several model calls run one after another
- Retries after timeouts and rate limits
Fixes
- Generate fewer tokens first. OpenAI's latency guide: cutting 50% of your output tokens may cut ~50% of your latency, while cutting 50% of your prompt may only result in a 1–5% improvement.
- Ask for the format you need and nothing else: the fields you will parse, not a paragraph around them.
- Combine sequential calls where one prompt can do the work of two, and run independent calls in parallel.
- Skip the call when you can: an exact-match or semantic response cache, or no LLM at all for steps a classifier or a regex can do.
Using a hosted API
- Lower reasoning effort where quality holds (Anthropic output_config effort, OpenAI reasoning effort, Gemini thinking_level).
- Use a smaller model for simple steps.
Caveat
max_tokens is a hard cut, not a word count the model aims for. A response that hits the limit is truncated mid-thought, which is worse than a slow one. Ask for brevity in the prompt and keep max_tokens as a safety net.
SourcesOpenAI: latency optimizationDatabricks: LLM inference performance engineeringAnthropic: reducing latencyRedis: semantic caching
4.P99 latency
The latency 99% of requests beat. In other words, the slowest one in a hundred. Averages hide it: Google's SRE book says a simple average can obscure tail latencies, and recommends percentiles over the mean. At any real volume, one in a hundred is a lot of people.
How to measure it
Log every request's latency with its route and model, then compute percentiles over a window. You need enough samples: P99 over 50 requests is basically the maximum. Watch P50 and P99 together, because a change can improve one and wreck the other.
import statistics
# request_log: your own records, e.g. [{"route": "/chat", "e2e": 1.84}, ...]
latencies = [r["e2e"] for r in request_log if r["route"] == "/chat"] # seconds
cuts = statistics.quantiles(latencies, n=100, method="inclusive")
p50, p95, p99 = cuts[49], cuts[94], cuts[98]
print(f"n={len(latencies)} p50={p50:.2f}s p95={p95:.2f}s p99={p99:.2f}s")Main causes
- Queueing spikes at peak traffic
- Cold starts and expired caches
- Retries after a timeout or a 429
- Outlier inputs: the one user who pastes a 40-page document
- Fan-out: the more calls a request depends on, the more likely one of them is slow
Fixes
- Set timeouts on every call, then retry with backoff and jitter, so one stuck request does not hold the user forever.
- Hedge only cheap calls: send a duplicate after a delay and take whichever returns first. The Tail at Scale reports that hedging after 10 ms cut a Google service's 99.9th-percentile from 1,800 ms to 74 ms for 2% more requests.
- Cap input size, and send giant documents down a separate, slower path.
- Keep interactive traffic away from batch jobs, and keep something warm.
Using a hosted API
- OpenAI's fast mode promises more consistent latency. OpenAI's flex tier is the opposite: cheaper, slower, sometimes unavailable, so keep it off interactive routes.
- A fallback provider or model for when your primary is overloaded.
Caveat
Hedging an LLM call doubles the cost of every request you hedge, because you pay for both. Only hedge short, cheap calls, and only after a delay near your P95, which is how The Tail at Scale keeps the extra load to about 5%.
SourcesGoogle SRE book: Service Level ObjectivesDean & Barroso: The Tail at Scale (CACM, 2013)OpenAI: fast mode
Latencies 5–8
Inside the model
Where the time goes once a request reaches the model: waiting for a slot, reading the prompt, writing the answer, and booting the thing in the first place.
Prefill: one pass, all prompt tokens
Decode: one pass per output token
5.Prefill latency
The time the model spends reading your prompt before it writes anything. All prompt tokens are processed in one parallel pass, which is limited by raw compute, so it grows with input length. On long prompts it is most of TTFT.
How to measure it
Hosted APIs do not report it, so compare TTFT across prompt sizes, or between a cache hit and a miss (Anthropic reports cache_read_input_tokens, OpenAI reports cached_tokens in usage). On vLLM, read vllm:request_prefill_time_seconds.
Main causes
- Long system prompts and tool definitions sent on every call
- Too many retrieved chunks stuffed into the context
- The full chat history resent every turn
- Large documents and images
Using a hosted API
- Prompt caching. Anthropic: mark the end of the stable prefix with cache_control (minimum 512 tokens on Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5; 5-minute default TTL, 1-hour option). OpenAI caches automatically from 1,024 tokens on GPT-5.6 and later. Gemini caches implicitly on 2.5 and newer models, though Google frames it as a cost feature and publishes no latency claim.
- Put stable content first and volatile content last, because caching is a prefix match.
- Send fewer, better chunks. Reranking (see #11) earns its keep partly by shrinking the prompt.
Self-hosting
- Prefix caching: vLLM's is on by default, SGLang's RadixAttention is on by default, and TensorRT-LLM reuses KV cache blocks across requests by default.
- Attention kernels such as FlashAttention, which reduce memory reads and writes.
- Disaggregated prefill in vLLM is experimental. Its docs say it does not improve throughput but is a much more reliable way to control tail inter-token latency.
import anthropic
client = anthropic.Anthropic()
POLICY_DOCS = open("policies.md").read() # large, and identical on every request
def ask(question: str):
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system=[
{"type": "text", "text": "You are Acme's support assistant."},
{
"type": "text",
"text": POLICY_DOCS,
"cache_control": {"type": "ephemeral"}, # cache everything up to here
},
],
messages=[{"role": "user", "content": question}], # only this part changes
)
u = response.usage
print(f"written={u.cache_creation_input_tokens} read={u.cache_read_input_tokens} uncached={u.input_tokens}")
return response
ask("What is the refund window?") # first call: computes the docs and writes the cache
ask("Do you ship to Canada?") # within 5 minutes: reads them, prefill skips the docsCaveat
Caching only matches an exact prefix within its TTL. A timestamp at the top of your system prompt silently gives you a 0% hit rate. And trimming a short prompt barely helps: by OpenAI's own numbers, halving a prompt may improve latency by only 1–5%. Fix output length first.
SourcesAnthropic: prompt cachingOpenAI: prompt cachingGemini: context cachingOpenAI: latency optimizationvLLM v0.32: metricsSGLang: server argumentsTensorRT-LLM: KV cache reuseDao et al.: FlashAttention (2022)vLLM v0.32: disaggregated prefill
6.Decode latency
The time spent generating the answer, one token per pass. Each pass reads the model's weights and the growing KV cache from GPU memory, so decode is limited by memory bandwidth rather than compute. For long answers it is most of end-to-end time.
How to measure it
End-to-end minus TTFT. On vLLM: vllm:request_decode_time_seconds, plus vllm:inter_token_latency_seconds and vllm:request_time_per_output_token_seconds.
Main causes
- Long outputs and reasoning tokens
- A large model for a simple step
- Big batches sharing the GPU
- Running without CUDA graphs (vLLM's --enforce-eager)
Using a hosted API
- Generate fewer tokens: tighter prompts, structured output, lower effort.
- Smaller models for simple steps, and fast mode where you can justify the price.
Self-hosting
- Speculative decoding: a draft guesses several tokens and the big model verifies them in one pass, with identical output. The original paper reports 2X–3X on T5-XXL and EAGLE-3 reports up to 6.5x, but vLLM's docs are blunt that real gains depend on your model, traffic, hardware and sampling.
- Quantization (FP8, AWQ, GPTQ, FP4) moves fewer bytes per token.
- Keep CUDA graphs and torch.compile on in production: --enforce-eager skips both for faster startup, at the cost of steady-state decode performance.
- Tensor parallelism splits each step across GPUs.
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--enable-prefix-caching \
--gpu-memory-utilization 0.90 \
--max-num-seqs 256 \
--max-model-len 16384 \
--kv-cache-dtype fp8 \
--speculative-config '{"method": "ngram", "num_speculative_tokens": 4, "prompt_lookup_min": 2, "prompt_lookup_max": 5}'
# Then measure it. Reports mean, median and the percentiles you ask for.
vllm bench serve \
--backend vllm \
--model meta-llama/Llama-3.1-8B-Instruct \
--dataset-name random --random-input-len 1024 --random-output-len 128 \
--num-prompts 200 --max-concurrency 16 \
--percentile-metrics ttft,tpot,itl,e2el \
--metric-percentiles 50,90,99Caveat
Speculative decoding helps most at low to medium load and on predictable text. vLLM targets medium-to-low QPS workloads with it, and TensorRT-LLM notes speed-ups are only observable at low batch sizes. A badly matched draft model can make things slower. Benchmark at your real concurrency.
SourcesvLLM v0.32: optimization and tuningNVIDIA: Mastering LLM inference optimizationvLLM v0.32: metricsvLLM v0.32: speculative decodingLeviathan et al.: speculative decoding (2023)Li et al.: EAGLE-3 (2025)TensorRT-LLM: speculative decodingvLLM: FP8 quantization
7.Queue time
The time a request waits before any GPU work starts, because every slot is busy. It happens at your provider and on your own server alike, and it never shows up as a line item. It shows up as TTFT that is fine at 10am and terrible at 2pm.
Static batching
Continuous batching
How to measure it
Self-hosted: vllm:request_queue_time_seconds and vllm:num_requests_waiting. Hosted: compare TTFT at quiet and peak hours, and count 429s, because every retry after a rate limit is queue time you added yourself.
Main causes
- Traffic bursts above capacity
- Rate limits, and retries that pile onto them
- Long requests hogging slots that short ones are waiting for
- Static batching, where everyone waits for the longest sequence
Using a hosted API
- Smooth bursts with a client-side queue that respects retry-after, instead of hammering on 429s.
- Move non-interactive work to batch APIs, so it stops competing with users.
- Paid speed tiers: OpenAI fast mode. Anthropic's Priority Tier capacity commitments are no longer available for purchase.
Self-hosting
- Continuous batching, so a waiting request takes a slot the moment one frees. vLLM, SGLang and TensorRT-LLM ("in-flight batching") all do it. Orca introduced the idea as iteration-level scheduling.
- Autoscale on queue depth (requests waiting), not GPU utilization.
- Separate deployments for long and short requests, so a 100k-token prompt cannot block a chat reply.
Caveat
Bigger batches raise total throughput but slow each user's tokens. PagedAttention's headline gain, 2–4× throughput, is measured at the same level of latency, not lower. Tuning for queue time and for TPOT pull in opposite directions, so pick per workload.
SourcesvLLM v0.32: metricsAnthropic: service tiersOpenAI: fast modeTensorRT-LLM: paged attention and in-flight batchingYu et al.: Orca (OSDI 2022)Kwon et al.: PagedAttention (SOSP 2023)
8.Cold start latency
The extra time when a request lands on something that is not ready: a fresh container, weights not yet in GPU memory, an empty cache. Scale-to-zero, serverless and every new deploy pay it. It also hides in your own app, in models and clients loaded on the first request.
How to measure it
Tag each request with whether it hit a fresh instance, and compare the first request after idle with steady state. For self-hosted servers, time each startup phase separately: image pull, weight load, compile, warm-up.
Main causes
- Scaling to zero
- Downloading and loading weights
- Graph capture and torch.compile on first boot
- Loading models or creating API clients inside the request handler
- Prompt caches that expired during a quiet spell
Using a hosted API
- Create your API client once and reuse it, so connections stay open.
- Pre-warm the prompt cache before traffic arrives: Anthropic documents a max_tokens 0 request for exactly this.
Self-hosting
- Keep at least one replica warm, and send a warm-up request before marking an instance ready.
- Persist the compile cache: vLLM stores torch.compile artifacts under VLLM_CACHE_ROOT, which can be copied between machines or baked into a container image.
- Faster weight loading: --load-format runai_streamer or fastsafetensors.
- vLLM's sleep mode (--enable-sleep-mode) releases most GPU memory while idle and resumes without a full restart.
Caveat
Warm capacity costs money every hour it sits idle. For low-traffic internal tools, a cold start once an hour can be cheaper than a GPU that never sleeps. And no official source gives a typical cold-start time, because it depends entirely on your model size and storage, so measure your own.
SourcesAnthropic: prompt cachingvLLM v0.32: optimization and tuningvLLM: Run:ai Model StreamervLLM: sleep mode
Latencies 9–11
In the RAG pipeline
Everything that runs before the model sees a single token. These stages add straight onto time-to-first-token, and they are invisible in the model provider's dashboard.
9.Retrieval latency
The time to find the relevant chunks: the vector search, any keyword search, filters, and the network round trip to wherever the index lives. It runs before the model call, so every millisecond lands on TTFT.
How to measure it
Time the search call on its own and log what you asked for: k, candidates, filters, and which index. A retrieval that is fast in a notebook and slow in production is usually a network hop or a filter.
Main causes
- Exact (brute-force) search over a large collection
- Search parameters turned up for recall: HNSW ef_search, Atlas numCandidates
- Filters on fields with no index
- The database in a different region from the app
- Several searches run one after another
Fixes
- Use an approximate index (HNSW) and tune it. hnswlib: higher ef leads to more accurate but slower search. pgvector's hnsw.ef_search defaults to 40. MongoDB recommends numCandidates at least 20 times your limit.
- Index the fields you filter on. Qdrant: for performant filtering, create payload indexes. MongoDB warns filtered queries are typically slower than unfiltered ones.
- Put the vector store in the same region as your app, and reuse connections.
- Run keyword and vector search in parallel, not in sequence.
Caveat
Turning ef_search or numCandidates down buys speed with recall. A fast retriever that misses the right chunk makes the model slower and wrong. MongoDB puts good recall at roughly 90–95% overlap with exact search, so measure recall before and after any change.
Sourceshnswlib: algorithm parameterspgvector READMEMongoDB Atlas: $vectorSearchQdrant: filtering
10.Embedding latency
The time to turn text into a vector. At query time it is on the critical path of every RAG request. At ingest it decides how long a re-index takes.
How to measure it
Time the embed call on its own, and keep query-time and ingest-time numbers apart. They have different fixes.
Main causes
- One API round trip per text
- Embedding in a Python loop instead of a batch
- Loading the model inside the request handler
- A large model where a small one would do
Fixes
- Batch. Sentence Transformers' encode() batches internally (batch_size defaults to 32). OpenAI's embeddings endpoint takes up to 2,048 inputs per request.
- Cache query embeddings: popular questions repeat.
- Run a small model locally to remove the network. all-MiniLM-L6-v2 has 22.7M parameters and outputs 384 dimensions.
- Use an optimized backend: Sentence Transformers supports ONNX and OpenVINO (backend="onnx").
Using a hosted API
- On Gemini, check the model before batching: gemini-embedding-2 produces a single aggregated embedding for a list of inputs, unlike gemini-embedding-001. Wrap each input separately or use the Batch API.
- OpenAI's dimensions parameter (text-embedding-3 models) shortens vectors, which mostly speeds up search and storage rather than the embed call itself.
from functools import lru_cache
from openai import OpenAI
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") # once, at startup
chunks = ["Refunds are issued within 14 days.", "We ship to 30 countries.", "..."]
# Slow: one forward pass and one Python round trip per text
# vectors = [model.encode(c) for c in chunks]
# Fast: one call; the library batches internally (batch_size defaults to 32)
vectors = model.encode(chunks, batch_size=64, normalize_embeddings=True)
# Hosted API: send a list, not a loop. OpenAI accepts up to 2,048 inputs per request
# (300,000 tokens in total across them).
resp = OpenAI().embeddings.create(model="text-embedding-3-small", input=chunks)
api_vectors = [d.embedding for d in resp.data]
# Query time: identical questions are common, so never embed the same string twice.
@lru_cache(maxsize=10_000)
def embed_query(q: str) -> tuple[float, ...]:
return tuple(model.encode(q, normalize_embeddings=True))Caveat
Switching embedding models means re-embedding your whole corpus: vectors from two different models are not comparable. Pick the model with that cost in mind, not just its speed.
SourcesSentence Transformers: encode()Sentence Transformers: speeding up inferenceOpenAI: embeddings API referenceGemini: embeddings
11.Reranking latency
The time for a second, more careful pass that scores each (question, candidate) pair and keeps the best few. A cross-encoder reads both texts together, which is why it is accurate and why its cost grows with every candidate.
How to measure it
Time the rerank call, and log the number of candidates and their average length. Those two numbers predict its latency better than anything else.
Main causes
- Too many candidates sent to the reranker
- Long documents per candidate
- A remote rerank API on the critical path
- A cross-encoder running on CPU
Fixes
- Retrieve wide, rerank narrow. The Sentence Transformers docs: scoring thousands or millions of pairs would be rather slow, so retrieve e.g. 100 candidates and rerank those.
- Rerank the chunk, not the whole document. Cohere truncates long documents at max_tokens_per_doc (4,096 by default) and recommends against sending more than 1,000 documents in a single request.
- Run the reranker on a GPU, or use a smaller one.
Caveat
Deleting the reranker is the easiest latency fix and often the wrong one. It is frequently the cheapest quality gain in the pipeline, and it shrinks the prompt you send to the model, which wins some of the time back. Measure answer quality with and without it before you cut it.
SourcesSentence Transformers: retrieve & re-rankCohere: Rerank API reference
Latencies 12–15
In the agent loop
Agents multiply every other latency on this page, because each lap of the loop pays for a model call, a tool call and the glue between them again.
12.Tool-call latency
The time spent running the tools a model asks for (your APIs, database queries, web searches), plus the extra model round trip to read their results.
Sequential: sum of all three
Parallel: only the slowest
How to measure it
Put a span around each tool execution, and count model calls per task. A task that makes eight sequential tool calls has eight chances to be slow.
Main causes
- Independent tools run one after another
- Slow downstream APIs with no timeout
- Huge tool outputs that make the next prefill longer
- A model round trip for every single tool
Fixes
- Execute tool calls with asyncio.gather or a TaskGroup, and give each one a timeout with asyncio.timeout.
- Cache tool results that do not change between turns.
Using a hosted API
- Let the model request tools in parallel and execute them concurrently. On Claude it is on by default (disable_parallel_tool_use inside tool_choice turns it off). Return every tool_result together in the next user message. OpenAI exposes the same switch as parallel_tool_calls.
- Return only the fields the model needs from each tool.
import asyncio
import anthropic
client = anthropic.AsyncAnthropic()
async def get_order(order_id: str) -> str:
await asyncio.sleep(0.8) # stands in for a real API call
return f"Order {order_id}: shipped Tuesday via DHL"
async def get_customer(email: str) -> str:
await asyncio.sleep(0.6)
return f"{email}: premium plan, 2 open tickets"
TOOLS = {"get_order": get_order, "get_customer": get_customer}
TOOL_SPECS = [
{
"name": "get_order",
"description": "Look up an order by its ID.",
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
},
{
"name": "get_customer",
"description": "Look up a customer by email.",
"input_schema": {"type": "object", "properties": {"email": {"type": "string"}}, "required": ["email"]},
},
]
async def run_tool(call) -> dict:
try:
async with asyncio.timeout(5): # one slow API must not stall the whole turn
result = await TOOLS[call.name](**call.input)
return {"type": "tool_result", "tool_use_id": call.id, "content": result}
except Exception as exc: # includes TimeoutError
return {"type": "tool_result", "tool_use_id": call.id, "content": str(exc), "is_error": True}
async def answer(question: str) -> str:
messages = [{"role": "user", "content": question}]
while True:
response = await client.messages.create(
model="claude-opus-5-5", max_tokens=4096, tools=TOOL_SPECS, messages=messages
)
calls = [b for b in response.content if b.type == "tool_use"]
if not calls:
return "".join(b.text for b in response.content if b.type == "text")
# Claude can request several tools in one turn. Run them together, not in a loop:
# the wait is the slowest tool, not the sum of all of them.
results = await asyncio.gather(*(run_tool(c) for c in calls))
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": list(results)}) # all results, ONE message
print(asyncio.run(answer("Where is order 4417, and what plan is jane@example.com on?")))Caveat
Only run independent, read-only tools in parallel, which is also Anthropic's guidance. Two writes that depend on each other must stay in order, however much faster parallel would be.
SourcesAnthropic: parallel tool useOpenAI: function callingPython docs: asyncio tasks
13.Planning latency
The time the model spends deciding what to do: reasoning tokens before its first action, and planning turns that produce no output a user sees. It is the thinking spinner before anything happens.
How to measure it
Track reasoning tokens per request (Anthropic reports them as output_tokens_details.thinking_tokens) and the time to the first tool call or visible word. Run the same sample of real tasks at two effort levels and compare.
Main causes
- High reasoning effort on routes that do not need it
- A frontier model doing a job a small model could do
- Vague tasks, so the model has to work out what you want
- Too many tools to choose from
Using a hosted API
- Cap reasoning per route. Anthropic: output_config effort (low, medium, high, xhigh, max); Claude Opus 5.5 and Haiku 5.5 default to medium, most other models to high. OpenAI: reasoning effort, where the supported values depend on the model. Gemini: thinking_level, where low minimizes latency and cost.
- Route simple steps (classify, extract, pick a tool) to a small, fast model, and keep the big model for the step that needs it.
- Give the full task up front and offer fewer tools, so there is less to deliberate over.
import anthropic
client = anthropic.Anthropic()
def route(ticket: str) -> str:
r = client.messages.create(
model="claude-haiku-5-5", # small and fast: this step only picks a label
max_tokens=10,
thinking={"type": "disabled"}, # no reasoning needed to choose a category
output_config={"effort": "low"},
messages=[{
"role": "user",
"content": f"Label this ticket as billing, shipping or other. Reply with the label only.\n\n{ticket}",
}],
)
return r.content[0].text.strip()Caveat
Lower effort trades away capability. Anthropic describes it as optimizing for speed and cost while accepting some reduction in capability. Test on real tasks, because a cheaper step that fails and needs a retry is not faster.
SourcesAnthropic: effortOpenAI: reasoning modelsGemini: thinkingAnthropic: reducing latency
14.Multi-hop latency
When answering needs a chain of dependent lookups (find the supplier, then their location, then the lead time there), each hop is a model call plus a retrieval, and the next hop cannot start until this one finishes. IRCoT and Self-Ask are the research versions of this pattern.
- Hop 1LLMretrieveWho supplies part X?
- Hop 2LLMretrieveWhere is that supplier?
- Hop 3LLMretrieveWhat is the lead time there?
How to measure it
Log the number of hops per question and the latency per hop. The distribution matters: a few questions taking eight hops can own your P99.
Main causes
- Questions that genuinely chain facts together
- A weak first retrieval that forces the agent to search again
- No cap on the number of hops
- Relational questions answered by document search instead of a query
Fixes
- Improve the first retrieval (hybrid search, reranking) so fewer hops are needed.
- Decompose the question up front, then run the sub-questions that do not depend on each other in parallel.
- Cap hops, and use a small model for the intermediate ones.
- Answer relational questions with a database query rather than a chain of document searches.
Caveat
A hop cap means some hard questions get a worse answer instead of a slower one. Pick the cap by measuring accuracy against hops on real questions, not by guessing.
SourcesTrivedi et al.: IRCoT (2022)Press et al.: Self-Ask (2022)Anthropic: Building effective agents
15.Orchestration overhead
Time spent in the glue rather than in models or tools: framework layers, serialization, sequential awaits, prompts rebuilt every step, and extra model calls a framework adds for you (routers, summarizers, validators). It is whatever is left after you subtract model and tool time from the wall clock.
How to measure it
Trace a task end to end. Add up every model and tool span, subtract from total wall time, and look at what is left and where the gaps sit.
Main causes
- Hidden model calls inserted by a framework
- Steps that wait for each other when they did not need to
- Clients and connections created per step
- Agents used where a fixed workflow would do
Fixes
- Start with the API directly. Anthropic's advice: many patterns can be implemented in a few lines of code, and frameworks often add layers of abstraction that obscure the underlying prompts and responses.
- Use a workflow, a predefined code path, when you already know the steps. Save open-ended agents for open-ended problems.
- Run independent steps concurrently. Anthropic's research system cut research time by up to 90% for complex queries largely by running subagents and tools in parallel.
Caveat
There is no trustworthy public benchmark of framework overhead. The ones that exist come from vendors and are not independently replicated. Measure your own stack, and remember that a framework that saves you a week of work may be worth a few milliseconds.
SourcesAnthropic: Building effective agentsAnthropic: How we built our multi-agent research system
Diagnosis: symptom to fix
Start from what you are seeing. The middle column is where to look first, and the last one is the first thing to try. Confirm with stage timings before you change anything.
| Symptom | Probably | First fix to try |
|---|---|---|
| Long blank wait, then the whole answer appears at once | #1 Time-to-first-token (TTFT) | Stream the response |
| Blank wait is long even with streaming, and worse with long prompts | #5 Prefill latency#1 Time-to-first-token (TTFT) | Cache the stable prefix and check cache hits in usage |
| Text starts quickly but crawls | #2 Time-per-output-token (TPOT)#6 Decode latency | Smaller model or lower effort for this step |
| Your code waits for the full answer (JSON, tool calls) and it takes ages | #3 End-to-end latency#6 Decode latency | Ask for fewer output tokens |
| Usually fast, occasionally terrible | #4 P99 latency#7 Queue time | Plot P50 and P99 per route, then add timeouts and retries |
| Only slow at peak hours | #7 Queue time | Watch queue depth; move batch work off the interactive path |
| The first request after a quiet spell is slow | #8 Cold start latency | Warm-up request and a pre-warmed cache before traffic |
| RAG answers are slow before the model even starts | #9 Retrieval latency#10 Embedding latency#11 Reranking latency | Time each RAG stage separately |
| Long thinking spinner before the agent does anything | #13 Planning latency | Cap reasoning effort; route simple steps to a small model |
| Agent tasks take minutes, tools run one at a time | #12 Tool-call latency | Run independent tool calls in parallel |
| Questions that need several facts are far slower | #14 Multi-hop latency | Decompose up front and run sub-questions in parallel |
| Model time plus tool time does not add up to wall time | #15 Orchestration overhead | Trace the gaps; remove hidden model calls |
Where to start: the checklist
In order. Most apps get most of their speed back before the halfway mark.
- 1.Measure TTFT, tokens per second and end-to-end time at the client, as P50 and P99, per route.
- 2.Ask whether the step needs an LLM at all. A regex, a classifier or BM25 answers in milliseconds. See the classic NLP toolkit.
- 3.Stream every response a person reads.
- 4.Cut output tokens before input tokens: they cost far more time.
- 5.Cache the stable prefix of your prompts, and confirm cache hits in the usage numbers.
- 6.Use the smallest model and the lowest reasoning effort that passes your evals, step by step.
- 7.Run independent tool calls, retrievals and sub-questions in parallel.
- 8.Time every RAG stage separately. Batch and cache embeddings, and rerank fewer candidates.
- 9.Cap agent loops and hops, and replace known paths with fixed workflows.
- 10.Only then reach for serving-level work (quantization, speculative decoding, batching), or a new model.
The takeaway
A slow AI feature is a pipeline with one slow stage, not a slow model. Time every stage, fix the slowest one, and measure again. Swap the model last, and only if the numbers say the model is where the time goes.
Frequently asked questions
Why is my LLM app slow?+
Usually not because of the model. Latency hides in fifteen places across four layers: what users feel (time-to-first-token, time-per-output-token, end-to-end and P99 latency), inside the model (prefill, decode, queue time and cold starts), the RAG pipeline (embedding, retrieval and reranking) and the agent loop (tool calls, planning, multi-hop chains and orchestration overhead). Measure each stage at the client, find the slowest one, and fix that. The most common culprits are no streaming, long outputs, high reasoning effort on simple steps, sequential tool calls, and RAG stages that run before the model starts.
What is TTFT vs TPOT?+
Time-to-first-token (TTFT) is how long the user waits before the first word appears. It includes network time, queueing, reading the prompt (prefill) and, on reasoning models, thinking. Time-per-output-token (TPOT) is the average time between tokens after that, so it decides how fast text flows. End-to-end latency is roughly TTFT plus TPOT times the number of output tokens. TTFT decides whether an app feels responsive; TPOT and output length decide how long the full answer takes.
What is P99 latency?+
P99 latency is the response time that 99% of requests beat, so it describes the slowest one request in a hundred. It matters because averages hide slow requests, and at any real traffic volume one in a hundred is many users. It compounds when one task depends on several calls: in The Tail at Scale, Dean and Barroso show that if each server is slow on 1% of requests, a request that fans out to 100 such servers is slow 63% of the time. Track P50 and P99 together, per route.
How do I reduce RAG latency?+
Time each stage separately first: query embedding, vector search, reranking and the model call. Then batch and cache embeddings, run a small embedding model locally if the network round trip dominates, tune the vector index's search parameters (HNSW ef_search, or numCandidates on MongoDB Atlas) against measured recall, index the fields you filter on, keep the vector store in the same region as the app, rerank around 100 candidates rather than thousands, and send fewer, better chunks to the model so prefill is shorter. Cache the stable part of the prompt as well.
Why are AI agents slow?+
Because an agent is a loop, and every lap pays for a model call, one or more tool calls and the orchestration between them. Anthropic's own guidance is that agentic systems often trade latency and cost for better task performance. The fixes are to run independent tool calls in parallel, cap reasoning effort and route simple steps to a small model, cap the number of hops, remove hidden model calls added by frameworks, and use a fixed workflow instead of an agent whenever you already know the steps.
I post these on LinkedIn, one practical breakdown a week. Follow along for the next one.