SALE! Use code blackfriday for 40% off everything!
Hurry, sale ends soon! Click to see the full catalog.

Anatomy of an LLM Serving Engine

Calling model.generate() is enough for one local prompt. A service also has to accept requests, decide when they may run, retain state while they run, stream results, and release resources when they finish. Those tasks continue even when the model and decoding algorithm stay the same.

This post follows one request through a serving engine. The small engine below runs one request at a time so that the boundaries are visible. Production engines add batching and a paged KV cache.

In this post, you will learn about:

  • How a request moves through a serving engine
  • How to build a small asynchronous generation worker and streamer
  • How cancellation, backpressure, and metrics shape the service

Let’s get started.

Anatomy of an LLM Serving Engine.
Photo by Taylor Floyd Mews. Some rights reserved.

Overview

This post is divided into four parts; they are:

  • The Request Path
  • A Minimal Asynchronous Engine
  • Cancellation, Backpressure, and Failure
  • Metrics and Production Interfaces

The Request Path

A text-generation workflow from request to response has several components:

Anatomy of an LLM Serving Engine diagram

The API parser validates the prompt, token limit, and decoding settings before work reaches the GPU. The tokenizer turns text into token IDs. The waiting queue holds requests that cannot run yet. The scheduler chooses work for the next model iteration, subject to limits on active sequences, tokens, and KV cache space. The model executor produces logits. Keeping it supplied with eligible work can improve utilization. The sampler selects token IDs, and the streamer turns them into client-visible text.

The cache manager owns the per-layer keys and values created during prefill and decode. It allocates storage in the layout expected by the attention kernel and maps each sequence’s logical token positions to their physical cache locations. In a paged cache, individual blocks are contiguous, but the complete cache for a sequence need not be. The manager must retain these blocks while a sequence can continue and reclaim them when the sequence ends. Releasing a request object without releasing its cache blocks would eventually exhaust device memory.

The interfaces between these components matter. A scheduler needs token counts and a cache-capacity estimate before admission. An executor needs the selected token positions and cache locations, but does not need to know the client’s HTTP connection. A streamer needs output tokens and a request ID, but does not need direct access to model weights. Keeping these responsibilities separate makes cancellation and measurement easier to reason about.

Offline inference can process a known list of prompts without a waiting queue or network server. An interactive single-user runtime has a queue of at most one request. A multi-user service needs admission control because arrivals and output lengths vary independently.

A Minimal Asynchronous Engine

The following example uses a small public checkpoint and requires PyTorch and transformers (python -m pip install torch transformers). Run the block in a Python environment with those packages installed. It downloads sshleifer/tiny-gpt2 on the first run. The model is intentionally small; it is used to test the request path, not to provide a reliable answer. This is a teaching example that exposes the jobs an engine coordinates. You can use vLLM for a real service rather than implementing this engine for an application.

The worker executes blocking PyTorch calls in a thread so the event loop can accept requests and deliver output. The thread sends cumulative token IDs back to the event loop, where the streamer decodes them. Cumulative decoding avoids treating each token’s bytes as a complete piece of text.

This engine still executes only one request at a time. Using asyncio keeps the interface responsive; it does not make the model run requests concurrently. It also uses the model’s ordinary cache object rather than a paged cache manager.

The _worker() method is a minimal scheduler. It takes requests from the bounded waiting queue in FIFO order and runs one request to completion before starting the next. The queue provides basic admission control, while the worker determines execution order. This scheduler does not batch requests, preempt a running request, or choose work one token at a time.

The example also simplifies KV cache management. The cache variable in _generate() holds the transformers past_key_values object returned after prefill and passes it back to the model during each decode step. When _generate() returns, the engine drops that reference. There is no shared cache pool, block table, reference counting, capacity tracking, or explicit block reclamation.

Cancellation, Backpressure, and Failure

The waiting queue has a fixed capacity. The put_nowait() call rejects a request when it is full instead of allowing unbounded memory growth. A real HTTP server should turn that condition into a documented retryable response and should also bound the number of active requests.

If a consumer stops reading the async generator, its finally block sets a cancellation flag. The worker checks the flag between generated tokens. Cancellation is therefore cooperative: it cannot interrupt an already-running GPU kernel. The final event still releases the stream, and the worker drops its model cache reference when _generate() returns.

The example’s per-request output queue is unbounded to keep the thread-to-event-loop handoff simple. A production streamer needs a bounded output buffer and a slow-client policy. Otherwise, a client that reads slowly can retain a growing number of tokens in host memory. The engine must also handle tokenizer errors, model errors, timeouts, and worker death without leaving requests waiting forever.

When a service uses an explicit paged KV cache, cancellation has one more step: remove the request from future schedules and decrement its block references. The same cleanup is required after EOS, a length limit, and an error.

Metrics and Production Interfaces

The example records queue time, time to first token (TTFT), decode interval, and output token count. Queue time ends when the worker starts. TTFT begins when the request enters the engine and ends at the first produced token. Decode interval spans the first to the last output token; divide it by output_tokens - 1 for average time per later token when at least two tokens were produced. These timestamps do not separately expose tokenization, prefill, or network transit.

Production services should attach one request ID to parsing, admission, execution, streaming, and failure events. They should also record active and waiting requests, per-request prompt length, generated length, and KV cache occupancy. A device-wide memory reading is not the same as live KV occupancy: weights, workspaces, and reserved cache blocks also consume device memory.

Run this command on a supported GPU to see a full API server. It downloads the public facebook/opt-125m checkpoint. Keep the server running in one terminal and use a second terminal to query its metrics endpoint:

vLLM supplies the API parser, scheduler, model executor, KV cache manager, and streamer. The command does not expose all of those as separate Python objects, but their responsibilities are the same as in the request path above. Other engines such as TensorRT-LLM, Hugging Face TGI, SGLang, and llama.cpp make different implementation choices while solving the same request-lifecycle problem.

Further Reading

  • vLLM documentation. Serve CLI. Documents the API server and configuration flags.
  • vLLM documentation. Metrics. Documents the metrics endpoint and request, cache, and latency measurements.
  • Hugging Face Transformers documentation. Caching. Explains the key-value state used during incremental generation.

Summary

An inference engine connects request admission, tokenization, scheduling, model execution, cache ownership, sampling, streaming, and measurement. Each component changes the resources a request occupies and the latency the user sees. The minimal engine makes those boundaries visible, while later posts add iteration-level scheduling and explicit cache management.

No comments yet.

Leave a Reply

Machine Learning Mastery is part of Guiding Tech Media, a leading digital media publisher focused on helping people figure out technology. Visit our corporate website to learn more about our mission and team.