LLM API Architecture: Requests, Tokens & Tools Explained

LLM API Architecture: Requests, Tokens & Tools Explained

What actually happens between the moment a user presses Enter and the moment a language model’s answer starts appearing on screen? Most teams building on large language models treat that gap as a black box, and that is exactly where production problems hide. A slow response, a surprise bill, a broken retry loop, or a prompt injection that leaks data almost always traces back to a misunderstanding of the architecture underneath. This article walks through that architecture layer by layer: the request format, the transport, the security and rate-limit machinery, the token economics, and the orchestration patterns that turn a raw model endpoint into a reliable system.

The Request Model: Messages, Roles and Statelessness

Nearly every hosted LLM API follows the same basic shape. A client sends a list of role-tagged messages, and the server returns a model-generated reply. The roles are usually system (instructions that set behavior), user (the human or upstream system’s input), and assistant (prior model turns). This chat-completions style became the default pattern after March 2023, replacing the older approach of sending a single raw prompt string.

The most important architectural property is statelessness. In most hosted APIs, the server does not remember previous calls. Every request must resend the full conversation history, plus any retrieved documents and system instructions. That has three practical consequences:

  • Request payloads grow as conversations get longer, so latency and cost creep upward turn by turn.

  • The client is responsible for context management, including trimming, summarizing, or discarding old turns.

  • Any server-side “memory” feature is an add-on that stores state on the provider’s side, not a property of the core protocol.

A common beginner mistake is assuming the model “remembers” the last request. It does not. If the history is not in the payload, the model has never seen it. Some providers now offer server-side conversation state, so the stateless rule is no longer universal, but the safe default for architecture design is to treat every call as a fresh, self-contained request.

Streaming: Why Tokens Arrive One at a Time

Streaming: Why Tokens Arrive One at a Time

Users judge latency by time-to-first-token, not total generation time. That is why streaming matters. Instead of waiting for a complete response, most LLM APIs stream output incrementally using Server-Sent Events (SSE) over plain HTTP, delivering each chunk as a `data:` event. The normative definition lives in the WHATWG HTML Living Standard’s server-sent events section, which is worth reading if you are building your own client or debugging a proxy that buffers the stream.

Streaming changes the shape of the stack. A load balancer or API entry service that buffers full responses will break streaming, so verify that every hop supports chunked, unbuffered delivery. On the client side, handle partial JSON, reconnects, and the final `[DONE]` signal. In practice, the most common streaming bug is a reverse proxy with response buffering enabled by default; the fix is usually one configuration flag, but finding it can take hours.

Authentication and Authorization

API access is almost always gated by a bearer token sent in the HTTP `Authorization` header, a pattern standardized in RFC 6750, OAuth 2.0 Bearer Token Usage. The token is typically a long-lived API key, though enterprise deployments increasingly use short-lived tokens from an identity provider.

From an architecture standpoint, the key rule is that API keys must never reach the browser or mobile client. Put a backend-for-frontend in between: the client authenticates to your service, your service holds the provider key, and your service enforces per-user quotas, logging, and content policy. This single decision solves key rotation, abuse prevention, and cost attribution at once. Teams that embed keys in client code eventually discover them in public repositories; rotating a leaked key is painful, and the bill from a scraped key can be brutal.

Rate Limits, Retries and Backpressure

Providers meter usage, usually by requests per minute and tokens per minute, and signal exhaustion with HTTP status 429, “Too Many Requests,” defined in RFC 6585’s additional HTTP status codes. Responses often include a `Retry-After` header telling the client how long to wait.

A naive retry loop makes things worse: when every worker retries immediately, the system hammers an already-throttled endpoint. What works in practice is exponential backoff with jitter, a circuit breaker that fails fast when error rates spike, and a queue in front of the model call so bursts are smoothed rather than amplified. Token-per-minute limits are especially easy to underestimate, because a single request with a large retrieved context can consume a huge share of the budget in one shot.

Failure mode Typical cause Practical fix
429 storms Synchronous retries across many workers Exponential backoff with jitter, request queue
Timeouts on long answers No streaming, aggressive client timeout Stream tokens, raise read timeout
Truncated output Context window exhausted by input Trim history, summarize, cap retrieval
Duplicate side effects Retry after a successful tool call Idempotency keys on tool execution

Tokens: The Unit of Billing and Limits

Models do not read characters; they read tokens, produced by subword tokenizers. Most modern models use byte-pair encoding (BPE) variants, a technique popularized by Sennrich et al.’s 2016 paper on neural machine translation with subword units, and OpenAI’s tiktoken library implements its own tokenizers. The practical upshot: English text averages roughly four characters per token, but code, JSON, and non-Latin scripts tokenize far less efficiently.

The context window is the maximum combined input plus output tokens per request. It has grown enormously across model generations, but the exact number differs by model and changes often, so hard-coding a figure into your architecture is a mistake. Instead, treat the limit as configuration, measure token counts before sending, and reserve headroom for the output. A request that fills the window completely may return a truncated answer or an error, and neither outcome is obvious to the end user.

Tool Calling and Structured Output

In June 2023, function calling arrived: the model could return structured JSON arguments for developer-defined functions, which the application then executes. This turned LLM APIs from text generators into orchestration hubs. The architectural pattern is a loop:

  • Send the user request plus a list of available tool definitions.

  • The model returns either a final answer or a tool call with JSON arguments.

  • Your application validates the arguments and executes the function.

  • The result is appended as a new message, and the loop repeats until the model produces a final answer.

Two cautions matter here. First, the model’s arguments are untrusted input: validate them against a schema and enforce authorization at execution time, not in the prompt. Second, tool loops can run away, so cap iterations and total token spend per conversation. The Model Context Protocol (MCP), an open standard announced in November 2024, generalizes this idea by standardizing how LLM applications connect to external tools and data sources, with a published Model Context Protocol specification that defines the client-server contract. MCP reduces bespoke integration work, but it also widens the trust boundary: every connected server is a potential data path, so review what each one can reach.

Retrieval-Augmented Generation in the API Layer

Retrieval-augmented generation (RAG) injects retrieved documents into the prompt so the model can answer from fresh or private knowledge. The term comes from Lewis et al.’s 2020 retrieval-augmented generation paper, and the architecture has become standard for enterprise assistants.

In the API layer, RAG means an extra pipeline before the model call: embed the query, search a vector store, rerank results, assemble a context block, and track the token cost of every chunk. The frequent failure is stuffing too many documents into the prompt. Precision beats volume; a handful of well-ranked passages usually outperforms dozens of marginal ones, and the token savings are real. For a deeper look at how these retrieval and inference layers fit into a broader platform, see this guide to AI inference architecture.

Putting It Together: A Reference Request Path

A well-built LLM application usually has the same skeleton regardless of provider:

  • Client sends input to your backend, never directly to the model provider.

  • Entry service authenticates the user, applies quotas, and logs the request.

  • Orchestrator builds the message array: system prompt, trimmed history, retrieved context, tool definitions.

  • Token counter checks the payload against the model’s context window and estimated cost.

  • Model call streams SSE tokens back through every hop without buffering.

  • Tool executor runs any requested functions with schema validation and idempotency keys.

  • Observability layer records latency, token usage, error codes, and trace IDs.

Each stage is a place where things break, and each is a place where a small guardrail pays for itself. Teams that instrument token usage per user and per feature tend to catch cost anomalies early; teams that do not usually discover them on the invoice. If you are designing the wider platform around these calls, the patterns in this overview of cloud infrastructure and architecture cover the networking, scaling, and reliability layer that the model endpoint sits on.

Common Mistakes That Bite in Production

A few errors show up again and again. Sending full conversation history without trimming eventually hits the context window and inflates cost. Ignoring streaming makes long answers feel broken. Trusting model output as if it were validated data invites injection and malformed tool calls. Retrying non-idempotent operations creates duplicate side effects. And hard-coding model names, token limits, or prices into application code turns a routine provider update into an outage. (Cybersecurity)

The pattern behind all of these is the same: treating the LLM API as a simple function call rather than a distributed system with its own failure modes, cost model, and security surface. The teams that internalize the architecture early spend far less time firefighting later. For a broader view of how these components combine into production systems, this resource on enterprise AI systems and architecture is a useful next step, and this piece on AI cloud architecture covers what changes when the infrastructure itself starts making decisions.

Conclusion

LLM API architecture is less mysterious than it looks once you separate the layers: a stateless message-based request format, SSE streaming for perceived speed, bearer-token auth with a backend in between, rate limits that demand backoff and queues, token accounting that governs both cost and context, and tool-calling loops that need validation and iteration caps. None of these pieces is exotic on its own. The difficulty is that they interact, and a weak link in any one of them shows up as a symptom somewhere else. Design the request path deliberately, instrument it honestly, and treat the model endpoint like the distributed system it is. That is what separates a demo from a product.

Frequently Asked Questions

What is an LLM API architecture?

It covers the components and protocols between a user’s input and a model’s output: the client, your backend entry point, the orchestrator that assembles prompts and context, the model endpoint itself, and the observability and security layers around them. The architecture defines how requests are formatted, authenticated, rate-limited, streamed, and billed.

Are LLM APIs stateless?

Most hosted LLM APIs are stateless by default: the server does not retain conversation history between calls, so the client must resend context each time. Some providers now offer server-side conversation state as an add-on, so the rule is no longer absolute, but designing for statelessness remains the safer default.

Why do LLM APIs stream responses with server-sent events?

Streaming improves perceived latency. Users see the first tokens within a fraction of a second instead of waiting for the whole answer, which matters for long outputs. SSE works over ordinary HTTP, which makes it easy to adopt, but it requires every proxy and entry service in the path to avoid buffering responses.

What happens when an LLM API returns a 429 error?

A 429 means the request exceeded a rate limit, usually measured in requests or tokens per minute. The correct response is to wait, ideally using the `Retry-After` header, and retry with exponential backoff plus jitter. Immediate retries from many workers amplify the problem rather than solving it.

How does tool calling work in an LLM API?

The application sends tool definitions alongside the user request. The model may reply with a structured JSON call instead of text; the application validates the arguments, executes the function, and appends the result as a new message. The loop repeats until the model returns a final answer, so iteration and spend caps are essential.

What is the difference between a context window and a token limit?

They are closely related. The context window is the maximum combined input and output tokens a model can handle in one request. Separate rate limits may cap tokens per minute across all requests. Both are measured in tokens, not words or characters, and both vary by model.

Latest articles

Scroll to Top