Local LLM Slow First Token? 7 Fixes to Reduce TTFT

Local LLM slow first token? Discover why Ollama, LM Studio, and llama.cpp pause before replying, plus 7 practical ways to measure and reduce TTFT.

Local LLM Slow First Token? 7 Fixes to Reduce TTFT

Your local LLM may generate text smoothly once it starts, yet leave you staring at an empty response for several seconds. If your local LLM is slow to produce the first token, the problem is not necessarily generation speed. It may be model loading, prompt processing, insufficient GPU memory, repeated context evaluation, or an application that delays displaying the output.

The fastest way to fix it is to identify which stage causes the wait. Start by comparing a cold request with a warm request, then measure prompt-processing time and inspect CPU/GPU placement. Only change inference settings after identifying the bottleneck.

This guide covers Ollama, LM Studio, and llama.cpp, with a reproducible diagnostic test, practical configuration changes, and an explanation of why apparently powerful hardware can still feel unresponsive. No particular GPU, model, or optimization is assumed to deliver a universal speed improvement.

What Is Time to First Token (TTFT)?

Time to first token (TTFT) measures the interval between sending an inference request and receiving the first generated token. It differs from tokens per second (TPS), which describes how quickly the model continues producing tokens.

For a locally running model, the first response can involve several distinct stages:

The Local LLM First-Token Pipeline

Conceptual process diagram — not a measured timing chart. Model loading occurs only when the model is not already resident.

STAGE 01
Model Loading
Weights are loaded into system memory and/or GPU memory when needed.
Cold requests only
STAGE 02
Prompt Prefill
Input tokens are processed and attention states are prepared, including the KV cache.
Strongly influenced by input length
STAGE 03
First Token
The first output token is generated and delivered to the client.
The endpoint of TTFT
STAGE 04
Token Generation
Subsequent tokens are decoded until the model finishes or reaches a limit.
Usually evaluated with TPS

Reading the diagram: TTFT ends at the first token, not when the complete response finishes. Request queuing, client communication, and interface rendering can introduce additional delays. The boxes have equal dimensions because their actual durations vary by workload and hardware.

Why does the distinction matter? Imagine a model that starts writing quickly but generates slowly afterward. Increasing its prompt-processing performance may barely improve the experience. Conversely, a model with excellent generation throughput can still have a frustrating startup delay if it must repeatedly load its weights or evaluate a lengthy conversation.

The official 🔗 Ollama Generate API documentation exposes separate loading, prompt-evaluation, and generation metrics, making it possible to investigate this distinction instead of guessing.

Why Your Local LLM Takes So Long to Start Responding

1. The model is repeatedly loading from storage

When an inference runtime unloads an inactive model, the next request may need to read its weights from storage and prepare the required memory allocations again. This is a cold start.

The delay can be especially noticeable with larger models, slower storage, or a machine experiencing memory pressure. However, an SSD upgrade is not automatically the solution: if loading takes little time compared with prefill, faster storage will not resolve the main problem.

How to identify it: Run the same model twice with short prompts. Keep the model loaded between requests. If the first request is considerably slower and the loading metric accounts for the difference, focus on model residency.

2. Prompt processing is consuming most of the time

Before a transformer-based LLM generates an answer, it must process the input it receives. That includes more than the latest question: system instructions, previous conversation turns, retrieved documents, tool definitions, and other content may contribute to the effective prompt.

A simple question inside a lengthy conversation can therefore take substantially longer to begin answering than the same question in a fresh chat.

Prompt processing is often called prefill. The runtime computes attention-related states for the input tokens and creates or updates the key-value cache. The amount of uncached work matters directly to the first-token delay.

How to identify it: Compare a short prompt in a new conversation with a long prompt using the same resident model. If the shorter request starts much faster and the prompt-evaluation metric changes accordingly, prefill is a likely bottleneck.

3. The model does not fit entirely in GPU memory

A local model uses memory for more than its weight file. Inference also requires attention-cache storage, compute buffers, and other runtime resources. Applications already using VRAM reduce the available headroom.

If the required allocations cannot fit on the GPU, a runtime may place some model layers in system RAM and execute them on the CPU. The resulting transfers and slower computations can hurt both prompt processing and generation.

This is why choosing a quantized model solely because its download size is smaller than the GPU’s advertised VRAM can be misleading.

For Ollama, check actual model placement with:

ollama ps

Read the PROCESSOR column. A fully GPU-resident model is reported differently from one split between CPU and GPU. This interpretation is documented in the 🔗 Ollama FAQ.

On a supported NVIDIA setup, you can also inspect VRAM use with:

nvidia-smi

High GPU memory usage alone is not proof of inefficient inference. Combine it with the model-placement information and performance measurements.

4. The context window is larger than the hardware can comfortably support

The context window determines how much input and conversation history the model can handle. Larger settings can increase KV-cache memory requirements, sometimes forcing a runtime to reduce GPU offloading or reject a request.

There is an important distinction: lowering the configured maximum context does not necessarily make an unchanged short prompt faster. The benefit depends on how the runtime allocates memory, how much context is actually processed, and whether the smaller allocation improves device placement.

For typical chat sessions, avoid configuring an enormous context window merely because the model advertises support for it. Reserve large contexts for workloads that genuinely require them.

5. Prompt caching is ineffective or repeatedly invalidated

Many inference runtimes can reuse previously computed attention states when an incoming prompt shares an eligible prefix with earlier requests.

For example, a coding assistant may send the same system instructions on every turn. If those instructions remain unchanged and the runtime retains the relevant cache, it may avoid processing them from scratch.

However, changing the beginning of the prompt can prevent reuse. Dynamically generated timestamps, reordered tool descriptions, or frequently modified system messages are possible causes.

The 🔗 llama.cpp server documentation describes prompt-cache reuse and how its server reports cached tokens.

A cache miss is not necessarily a software defect. It may simply mean the new request does not contain a reusable prefix, or the runtime has reclaimed the previous cache.

6. Background workloads, reasoning, or the interface are adding delays

A busy GPU, competing inference requests, antivirus scanning, power-saving limits, thermal throttling, or incompatible runtime settings may also affect performance.

Reasoning-capable models introduce another distinction: the first generated token may belong to an internal reasoning stream that a chat interface does not display. The visible answer can therefore appear substantially later than the actual first generated token.

Some applications also buffer responses or perform retrieval, prompt construction, or additional processing before displaying any content. A slow graphical interface does not automatically mean slow model inference.

Compare the model through a direct local API request with the same model through the application. If the API streams output promptly but the application does not, investigate the client-side workflow rather than changing GPU settings immediately.

📊 Diagnose the Delay Before Changing Settings

The following table connects common symptoms to the most useful first test. These are diagnostic possibilities, not proof that every symptom has a single cause.

First-Token Troubleshooting Matrix

Observed symptom Possible cause First diagnostic action
First request slow, second request fast Cold loading or reusable prompt cache Compare loading duration and cached-token count
Short prompts fast, long prompts slow Expensive prefill Compare input tokens and prompt-evaluation duration
First token and later tokens both slow CPU execution, partial GPU offload, or resource constraints Inspect model placement, memory, and generation TPS
Performance worsens during long chats Growing history, context pressure, or cache behavior Repeat the question in a fresh conversation
API responds quickly, chat UI appears stuck Buffering, hidden reasoning, or application overhead Compare direct streaming output with application output
Multiple users experience intermittent pauses Request queuing or concurrency pressure Inspect active requests, queueing, and runtime capacity

This matrix is a qualitative troubleshooting guide. It does not represent benchmark results or measured probabilities.

How to Measure Local LLM Time to First Token in Ollama

Ollama provides a particularly useful starting point because its API reports the phases of a completed generation. You can obtain the metrics without installing a separate benchmarking framework.

Step 1: Inspect the model and keep the workload simple

Open your terminal and list the locally installed models:

ollama list

Choose one installed model. Use a short, repeatable prompt, and avoid changing the model or inference settings while comparing the initial results.

Step 2: Read the timing fields

For an ordinary non-streaming request, Ollama’s /api/generate endpoint returns several useful fields:

  • load_duration: time spent loading the model.
  • prompt_eval_count: number of input tokens reported for prompt evaluation.
  • prompt_eval_cached_count: input tokens reused from the cache, when reported.
  • prompt_eval_duration: time spent evaluating uncached prompt tokens.
  • eval_count: generated output token count.
  • eval_duration: time spent generating output tokens.
  • total_duration: duration reported for the completed generation request.

The documented duration fields use nanoseconds. Divide them by one billion to convert them into seconds.

These numbers are useful, but a non-streaming request does not directly measure client-observed TTFT. It returns the completed response, so the time until the first output token reaches your client is not separately observable in that request.

Step 3: Measure the actual streaming delay

The following optional Python example uses only the standard library. It sends a request to a local Ollama server and measures the interval until the first generated response or thinking content arrives. Replace the model placeholder with the exact name shown by ollama list.

import json
import time
import urllib.request

MODEL = "YOUR_INSTALLED_MODEL"

payload = {
    "model": MODEL,
    "prompt": "Explain a KV cache in one sentence.",
    "stream": True
}

request = urllib.request.Request(
    "http://localhost:11434/api/generate",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Content-Type": "application/json"}
)

start = time.perf_counter()
first_token = None
final = None

with urllib.request.urlopen(request, timeout=180) as response:
    for raw_line in response:
        event = json.loads(raw_line)

        if first_token is None:
            if event.get("response") or event.get("thinking"):
                first_token = time.perf_counter() - start

        if event.get("done"):
            final = event

if final is None:
    raise RuntimeError("No completed response received.")

load_s = final.get("load_duration", 0) / 1e9
prefill_s = final.get("prompt_eval_duration", 0) / 1e9
decode_s = final.get("eval_duration", 0) / 1e9

print("First streamed token (s):", first_token)
print("Model loading (s):", load_s)
print("Prompt processing (s):", prefill_s)
print("Generated tokens:", final.get("eval_count"))
print("Prompt tokens:", final.get("prompt_eval_count"))
print("Cached tokens:", final.get("prompt_eval_cached_count"))
print("Generation time (s):", decode_s)

Save the example as a Python file and execute it while Ollama is running. The reported first-token time includes the client-side request and delivery path, while the individual duration fields describe work measured by Ollama. They are related, but they are not interchangeable.

For reasoning models, this script counts the first streamed thinking content if it arrives before answer text. To measure the first visible answer instead, count only the response field. Keep the definition consistent throughout your comparisons.

Step 4: Run three controlled comparisons

  1. Cold start: ensure the model is unloaded, then send the short test prompt and record loading time and TTFT.
  2. Warm request: keep the same model loaded, use a comparable short prompt, and record the same metrics. Check cache reuse before attributing a speed change solely to loading.
  3. Long input: keep the model loaded and submit a representative longer prompt. Compare prompt tokens, cached tokens, prefill duration, and TTFT with the warm short-request measurements.

Repeat each condition several times. For performance tuning, compare the median of repeated measurements rather than trusting a single run. Record the runtime version, model identifier, quantization, context setting, and hardware alongside the results.

How to Fix Slow First-Token Latency: A Practical Workflow

Fix 1: Keep the model loaded when you use it frequently

If loading dominates the delay, keeping the model resident can reduce repeated cold starts. Ollama documents a default five-minute residency period, although your application or API request can override its behavior.

For a model already installed locally, this request asks Ollama to preload it and keep it resident for 30 minutes:

curl http://localhost:11434/api/generate \
  -d '{"model":"YOUR_INSTALLED_MODEL","keep_alive":"30m"}'

This example uses POSIX-style shell syntax. On Windows, use the equivalent request syntax for your terminal. You must replace the placeholder with an installed model name.

The tradeoff is memory residency: a model kept loaded continues occupying resources that other applications may need. Extending residency is useful when repeated loading is the problem, but it does not inherently accelerate prefill or token decoding.

Fix 2: Shorten the actual prompt, not merely the context limit

If prefill dominates, reduce unnecessary input tokens. A fresh conversation is often a useful diagnostic control, but in real applications you may need to manage context more carefully.

Practical improvements include removing outdated chat history, passing only the relevant passages from retrieved documents, simplifying repeated instructions, and limiting tool definitions to those actually required for a task.

Do not remove essential evidence or instructions simply to reduce token count. For document analysis and retrieval-augmented generation (RAG), aggressive trimming may reduce answer quality or eliminate necessary context.

Fix 3: Right-size the context window

In Ollama’s interactive CLI, you can set a smaller context limit using the documented parameter interface:

/set parameter num_ctx 4096

Run this inside an Ollama interactive session. An application that calls Ollama through its API may instead supply num_ctx in the request options.

The value shown is an example configuration, not a benchmark-derived universal recommendation. Select a setting that accommodates the actual prompt and expected output, while leaving appropriate memory headroom.

A smaller context allocation can sometimes allow more of the model to stay on the GPU. Conversely, reducing the limit below the size of a required conversation may cause truncation or other application-specific problems.

Fix 4: Use a smaller or more suitable model quantization

If the model is partially CPU-resident because of memory pressure, switching to a smaller model or lower-bit weight quantization can improve effective throughput by allowing greater GPU residency.

However, smaller weights do not guarantee lower TTFT. Backend kernels, model architecture, quantization format, cache settings, and the available device can all affect performance.

For example, a quantized model that fits entirely on a GPU may outperform a larger model that must move work between CPU and GPU. But a lower-precision format may also reduce accuracy in certain reasoning, coding, or factual tasks.

For a detailed examination of those quality and memory tradeoffs, see the related Noxoric article: 🔗 4-Bit vs 8-Bit AI Quantization: Which Should You Use?

Fix 5: Investigate KV-cache memory and Flash Attention

The KV cache stores attention-related information used during inference. Its memory footprint depends on the model architecture, context, precision, and runtime configuration.

For compatible backends and devices, Flash Attention can reduce memory requirements during attention processing. Ollama’s documentation states that it automatically uses Flash Attention when supported, so manually enabling it should not be treated as a required first step.

Ollama also documents optional KV-cache quantization, including q8_0 and q4_0, when Flash Attention is enabled. Its documented approximate memory reductions relative to f16 are about one-half for q8_0 and one-quarter for q4_0.

Those are KV-cache memory comparisons, not claims about model-weight sizes or measured TTFT gains. The quality impact depends on the model and task. Consult the 🔗 official Ollama configuration guidance before modifying server-wide cache settings.

Fix 6: Improve cache reuse where appropriate

If the same long system prompt or retrieved context is repeatedly supplied, look for opportunities to preserve a stable reusable prefix. Avoid changing its beginning unnecessarily.

For llama.cpp server users, examine the server’s prompt-cache settings and timing fields. Do not assume that every cache is persistent across restarts or that identical-looking conversations necessarily produce matching token sequences.

Caching is most useful when substantial input is reused. A completely new document or unrelated conversation may provide little or no opportunity to reuse earlier computations.

Fix 7: Verify the GPU backend, power state, and competing workloads

If basic configuration changes do not resolve the issue, inspect the actual execution environment. A GPU can be present yet underused because of unsupported drivers, an incompatible backend, insufficient VRAM, or explicit CPU-only configuration.

On laptops, check whether the system is operating under a restrictive power profile. On systems that slow progressively during sustained inference, inspect temperatures and clock behavior for thermal throttling.

Close unnecessary GPU-heavy applications temporarily, repeat the same test, and compare the measurements. Update inference runtimes and drivers where appropriate, but preserve a record of the previous working configuration so you can identify regressions.

Ollama vs LM Studio vs llama.cpp: Where to Investigate TTFT

All three can run models locally, but their diagnostics and configuration interfaces differ. Apply settings only to the runtime that actually hosts your model.

Runtime Diagnostic Comparison

Runtime Useful diagnostics Best starting point
Ollama Load duration, prompt duration, cache counts, output duration, model placement ollama ps and /api/generate
LM Studio First-token time, token throughput, input count, and model loading metrics through its REST API /api/v1/chat response statistics
llama.cpp Prompt-processing throughput, generation throughput, GPU-offload configuration, server cache and timing information llama-bench and llama-server timings

1. LM Studio: Check first-token and loading statistics

LM Studio’s documented REST chat endpoint can report time_to_first_token_seconds, tokens_per_second, and, when relevant, model_load_time_seconds.

That separation helps distinguish the initial delay from the speed of subsequent generation. It is especially useful when comparing a newly loaded model with an already resident model.

See 🔗 LM Studio’s Chat API documentation for the current response structure and available statistics. Avoid mixing metrics from different API versions without checking their definitions.

2. llama.cpp: Benchmark prefill separately from generation

llama.cpp provides a benchmarking utility that separates prompt-processing tests from token-generation tests. This is useful for isolating computation performance from the end-to-end experience of a chat application.

For example, a model-specific benchmark can be run with the following command where the utility is available:

./llama-bench -m /path/to/model.gguf -p 512 -n 128

The command requests prompt-processing and token-generation tests. The prompt and generation lengths shown are benchmark parameters, not claimed measurements.

Keep in mind that llama-bench does not include every component of real application latency. Its documentation specifically notes that tokenization and sampling times are not included in its measurements.

Use the 🔗 official llama-bench README to interpret its results correctly.

Why a Faster Tokens-Per-Second Result May Not Fix TTFT

Inference performance cannot be reduced to a single number. A local model can have excellent generation throughput while remaining slow to start a response, particularly when requests involve large uncached prompts or cold loading.

Similarly, an optimization that increases generation speed may have a limited effect on prefill, and a configuration designed to improve memory efficiency may introduce its own computational overhead.

Consider the following distinctions:

  • Changing the model: may reduce computation and memory requirements, but it also changes output capabilities and quality.
  • Changing quantization: may improve GPU fit, but the resulting performance depends on kernels and architecture.
  • Shortening a prompt: directly reduces input work, provided the removed tokens would otherwise have required processing.
  • Keeping the model loaded: avoids repeated cold starts but does not eliminate the cost of new uncached prompts.
  • Improving caching: benefits repeated eligible prefixes, not arbitrary new inputs.
  • Increasing GPU offload: can help if the hardware and available memory support it, but excessive allocations may cause failures or fallback behavior.

The most useful optimization is the one that targets the stage consuming the time. That is why TTFT, prefill throughput, generation throughput, and memory placement should be considered together rather than ranked by a single headline number.

Pros and Cons of the Main TTFT Fixes

Optimization Tradeoff Cards

Keep the Model Loaded

✅ Avoids repeated model loading.

❌ Keeps system or GPU memory occupied.

Use when: Cold starts dominate and requests arrive frequently.

Reduce Prompt Length

✅ Reduces uncached input-processing work.

❌ May remove necessary information.

Use when: Prefill time rises with prompt size.

Lower Memory Requirements

✅ May enable fuller GPU residency.

❌ May affect output quality or context capacity.

Use when: VRAM pressure causes partial offload.

Reuse Prompt Cache

✅ Avoids repeating eligible prefill computations.

❌ Offers limited benefit for unrelated prompts.

Use when: Requests share substantial stable prefixes.

These cards compare documented mechanisms and practical tradeoffs. They do not imply that one optimization is numerically superior on every system.

Common Mistakes That Make TTFT Troubleshooting Harder

Some seemingly logical fixes can create misleading results or make the system less stable.

  1. Changing several settings simultaneously: If you switch model size, quantization, context length, and GPU offloading at the same time, you cannot determine which change caused the observed difference. Change one variable at a time and repeat the measurements.
  2. Comparing a cold run against a cached run: A cold request and a cached request do not perform the same amount of work. Report whether the model was resident and whether input tokens were reused before drawing conclusions about hardware or runtime speed.
  3. Assuming low GPU utilization means a GPU problem: GPU utilization can vary throughout the inference pipeline. During loading, CPU preparation, client-side processing, or request queuing, the GPU may show little activity even if it will later execute the model correctly.
  4. Assuming smaller quantization always means faster inference: Lower-bit weights reduce storage requirements, but their execution characteristics vary. Some formats may require additional conversion or use less efficient kernels on a particular backend. Always compare actual performance and answer quality.
  5. Buying more hardware before checking the workload: A new GPU may be valuable when existing hardware is the confirmed bottleneck. It is a poor substitute for investigating an application that repeatedly reloads a model, resends unnecessary context, or waits before displaying generated output.

Final Verdict: Fix the Delay You Can Actually Measure

When a local LLM is slow to deliver its first token, the right solution depends on where the time is spent. If loading dominates, investigate model residency. If prompt evaluation dominates, reduce unnecessary input and improve cache reuse. If both prompt processing and generation are slow, inspect GPU offloading, memory pressure, and runtime configuration.

Start with three measurements: a cold request, a warm request, and a longer uncached input. They provide a clearer diagnostic foundation than randomly modifying settings or switching models.

Above all, treat latency improvements as workload-specific results. A useful configuration should improve responsiveness without silently sacrificing essential context, answer reliability, or system stability.

🚀 Explore more practical AI and technology guides on Noxoric to make better-informed decisions about local models, hardware, and software performance.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button