← Back to blog

LLM Wiki: What Really Happens in an API Call

Discover what happens inside an LLM API call—from tokenization to output streaming. Learn the latency and cost mechanics that shape AI products.

LLM Wiki: What Really Happens in an API Call

You have felt it. You type a prompt, hit send, and the response starts streaming in under a second. It feels instant, almost casual — like the model already knew what you wanted. But that one second hides a chain of events involving tokenization, billions of matrix multiplications, and a caching trick that most engineering teams never actually see. Think of this as the practical LLM wiki entry we wish existed when we first started shipping AI features: not the academic version, but the one that explains where your latency and your bill actually come from.

Understanding this chain is not trivia. It directly changes how you architect features, how much you pay per user, and whether your product feels fast or sluggish. So here is what happens between "send" and the first word of the answer.

Step One: Your Text Becomes Numbers (Tokenization)

The model does not read words. It reads tokens — chunks of text mapped to integers. The word "unbelievable" might split into un, believe, able. A common word like "the" is a single token. Emoji, code, and non-English text often cost more tokens per character.

This matters for one blunt reason: you pay per token, and you are limited per token. When a provider advertises a 200,000-token context window, that is roughly 150,000 English words — but far fewer if you are sending JSON, code, or Cyrillic text. You can watch this happen yourself with the OpenAI tokenizer tool, which shows exactly how a string breaks apart.

Real numbers: in our experience with production RAG systems, teams routinely underestimate token counts by 20–40% because they count words, not tokens. A prompt that looks like 500 words can bill as 900 tokens once you add formatting, retrieved documents, and system instructions. Multiply that across a million requests a month and the gap becomes a real line item.

Put simply: tokenization is the meter on the taxi. It starts running before the model thinks anything.

Step Two: The Prompt Enters the Model (The Prefill Phase)

Once your text is tokens, the model processes all of them at once. This is called prefill. Every token is compared against every other token through the attention mechanism — the core idea from the 2017 paper Attention Is All You Need that made modern LLMs possible.

Here is the part that surprises people: prefill is fast per token because it happens in parallel. Feeding 2,000 tokens of context is not 2,000 times slower than feeding 10 tokens — the GPU chews through them in one heavy batch. This is why a long document summary and a short question can have similar "time to first token."

But prefill is compute-heavy. A larger prompt means more matrix math, more GPU seconds, and more cost. This is the hidden tax on stuffing everything into context "just in case." Every extra paragraph of instructions you never trim gets reprocessed on every single call.

Honest take: most teams treat the prompt as free real estate. It is not. A bloated system prompt is a fixed cost paid on every request, forever, at scale.

Step Three: The Model Writes One Token at a Time (Decoding)

Now the interesting shift. After prefill, the model generates the answer — but it cannot do this in parallel. It produces one token, then feeds that token back in to produce the next, then the next. This is called autoregressive decoding, and it is why responses stream to you word by word instead of appearing all at once.

This is also the slow part. Each new token requires a full pass through the model's billions of parameters. A 500-token answer means 500 sequential passes. This is why:

  • Time to first token depends mostly on prefill (your input length).
  • Total response time depends mostly on output length (how much the model writes).

The business consequence is direct: if you want faster, cheaper responses, the biggest lever is often telling the model to write less. Asking for a JSON object instead of a chatty paragraph can cut output tokens — and therefore latency and cost — by half or more.

Key takeaway for business: you control input cost by trimming the prompt, and output cost by constraining the response format. Both are engineering decisions, not model limitations.

Step Four: The KV Cache — Why the Second Message Is Cheaper

Here is the trick most people never see. During decoding, the model would normally have to re-read the entire conversation for every new token. That would be brutally slow. Instead, it stores the intermediate results of attention — the "keys and values" — in what is called the KV cache.

Think of it like a warehouse close to the store instead of an overseas supplier. Once the context is processed, the model keeps those computed results nearby so it does not have to recompute them from scratch for each new token. This is what makes decoding feasible at all.

Providers have extended this idea into prompt caching: if you send the same long system prompt or document on repeated calls, they cache the prefill work and charge you a fraction of the price for the reused portion. Anthropic and OpenAI both document meaningful discounts on cached input tokens. For any product with a large, stable system prompt — a customer support bot, a coding assistant — this is one of the highest-leverage cost optimizations available. The Hugging Face guide to LLM inference covers the mechanics in more depth for teams that want the engineering detail.

What this means for your project: structure your prompts so the stable, reusable part comes first and the variable part comes last. Cache hits can drop input costs dramatically on high-volume workloads. We have seen this turn an unaffordable feature into a profitable one without changing a single line of the model's behavior.

Where This All Runs: API vs Local LLM

So far this describes a call to a hosted API. But the same steps happen if you run a local LLM on your own hardware — the difference is who owns the GPU and the bill.

  • Hosted API: you pay per token, scale instantly, and get the newest models. You give up control over data residency and are exposed to rate limits and price changes.
  • Local LLM: you run an open-weight model (like Llama or Mistral) on your own machines. Data never leaves your infrastructure, and marginal cost per call drops toward the cost of electricity. In exchange, you buy or rent GPUs, manage the serving stack, and usually accept a capability gap versus frontier models.

Here is what we recommend: start on a hosted API to validate the product, then evaluate a local LLM only when volume is high enough that token costs exceed the fully-loaded cost of running your own hardware — including the engineers who keep it alive. For most teams under a few million calls a month, that crossover has not yet arrived. For regulated industries where data cannot leave the building, the calculation flips regardless of volume.

Honest take: "we'll just run it locally to save money" is one of the most common miscalculations we see. The token bill is visible; the DevOps burden of serving models reliably is not — until it lands on your team.

Why This Is a Pipeline Problem, Not a Prompt Problem

There is a useful question hiding here that connects directly to reliability: what is a DevOps pipeline for an LLM feature, and why does it matter? A traditional pipeline builds, tests, and deploys code. An LLM pipeline adds new failure points that classic monitoring never watched: token limits exceeded mid-conversation, cache misses spiking your bill overnight, latency creeping up as context grows, and silent quality drift when a provider updates a model.

Each of the four steps above is a place where things break in production. Tokenization can blow past context limits. Prefill cost can balloon from an unbounded prompt. Decoding can stall on a runaway generation. Cache logic can silently stop working after a refactor and quietly double your costs. Treating an LLM call as a single opaque box is exactly how teams end up debugging for days. When an AI feature misbehaves, the discipline of root cause analysis in LLM apps is what separates a two-hour fix from a two-week mystery — because you know which of the four stages to inspect.

The same logic applies to cost and speed observability. Instrumenting each stage — input tokens, output tokens, cache hit rate, time to first token — is what turns a vague "it feels slow and expensive" into a specific, fixable number. Our write-up on cost and latency observability at scale walks through how to capture these metrics per request without slowing anything down. For teams running conversational or voice products where every call multiplies, testing agents across thousands of scenarios is what keeps a small tokenization or latency regression from reaching every user at once.

The Numbers That Actually Matter

If you take four metrics from this piece into your next planning meeting, make them these:

  1. Input tokens per call — the tax you pay before the model thinks. Trim the prompt to lower it.
  2. Output tokens per call — the biggest driver of latency. Constrain the format to lower it.
  3. Cache hit rate — free money if your prompts are structured for reuse.
  4. Time to first token — the number your users actually feel.

Improving these is rarely about switching models. It is about understanding the four-step journey every request takes and removing waste at each stop. This field moves fast, and keeping an eye on LLM research news and provider changelogs pays off — a single pricing update on cached tokens or a new streaming feature can shift the economics of your feature overnight.

Key Takeaways for Business

Key takeaway for business: the second between "send" and "answer" is not magic — it is tokenization, prefill, decoding, and caching, and each one is a cost lever you control.

  • Trim before you scale. Input length is a fixed tax on every call. A leaner prompt pays dividends across every request forever.
  • Constrain the output. Asking for less text is the single fastest way to cut both latency and cost, with no model change required.
  • Cache deliberately. Structure prompts so the stable part is reusable, and prompt caching can turn an expensive feature into an affordable one.

Put simply: teams that understand what happens inside an LLM API call ship faster, cheaper products than teams that treat it as a black box. The mechanics are learnable, the levers are real, and the savings show up on the first invoice after you pull them.

This article is based on publicly available sources and may contain inaccuracies.

Related articles

✦SqueezeAI
  1. Команды систематически занижают количество токенов на 20–40%, считая слова вместо токенов: 500 слов с форматированием, документами и системными инструкциями легко превращаются в 900 токенов — на миллионе запросов это ощутимая статья расходов.
  2. Фаза prefill обрабатывает все токены промпта параллельно, поэтому длинный документ и короткий вопрос могут иметь одинаковое «время до первого токена» — но каждый лишний абзац инструкций, который вы не обрезаете, пересчитывается на каждом вызове и бьёт по вычислительным затратам.

Powered by B1KEY