Anatomy of an LLM Serving Engine A technical post walks through the anatomy of an LLM serving engine, tracing a single request through the API parser, tokenizer, waiting queue, scheduler, model executor, sampler, streamer, and cache manager, and argues that these components must stay separate so cancellation and measurement remain tractable. The post includes a minimal asynchronous engine built on the `sshleifer/tiny-gpt2` checkpoint with PyTorch and `transformers`, which runs one request at a time to expose the boundaries that production engines extend with batching and a paged KV cache. It warns that releasing a request object without releasing its cache blocks would eventually exhaust device memory, and recommends vLLM for real services rather than implementing the teaching engine for an application. 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. 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: 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. python Run a minimal asynchronous inference engine. import asyncio import threading import time from dataclasses import dataclass, field import torch from transformers import AutoModelForCausalLM, AutoTokenizer Keep the state and timing information for one request together. @dataclass class Request: prompt: str max new tokens: int arrived: float = field default factory=time.perf counter output: asyncio.Queue = field default factory=asyncio.Queue cancelled: threading.Event = field default factory=threading.Event started: float | None = None first token: float | None = None last token: float | None = None output tokens: int = 0 class MiniEngine: def init self, model id="sshleifer/tiny-gpt2", max waiting=4 : Load the model once, then create a bounded admission queue and worker. self.tokenizer = AutoTokenizer.from pretrained model id self.model = AutoModelForCausalLM.from pretrained model id .eval self.waiting = asyncio.Queue maxsize=max waiting self.loop = asyncio.get running loop self.stats = self.worker = asyncio.create task self. worker def emit self, request, value : Safely send worker-thread results back to the asyncio event loop. self.loop.call soon threadsafe request.output.put nowait, value def generate self, request : Run blocking model execution in the worker thread. try: inputs = self.tokenizer request.prompt, return tensors="pt" token ids = with torch.inference mode : Prefill the prompt once and retain its KV cache for decoding. result = self.model inputs, use cache=True cache = result.past key values next id = int result.logits 0, -1 .argmax Decode one token at a time, emitting cumulative token IDs. for in range request.max new tokens : if request.cancelled.is set : break token ids.append next id self. emit request, token ids.copy , time.perf counter if next id == self.tokenizer.eos token id: break if len token ids == request.max new tokens: break result = self.model torch.tensor next id , past key values=cache, use cache=True, cache = result.past key values next id = int result.logits 0, -1 .argmax except Exception as exc: Deliver model failures to the request's async consumer. self. emit request, exc finally: A None sentinel marks the end of this output stream. self. emit request, None async def worker self : Process admitted requests serially while leaving the event loop free. while True: request = await self.waiting.get if request is None: self.waiting.task done return request.started = time.perf counter if not request.cancelled.is set : await asyncio.to thread self. generate, request else: request.output.put nowait None self.waiting.task done async def stream self, prompt, max new tokens=24 : Validate and admit the request without waiting on a full queue. if not prompt or max new tokens < 1: raise ValueError "prompt must be nonempty and max new tokens positive" request = Request prompt, max new tokens try: self.waiting.put nowait request except asyncio.QueueFull as exc: raise RuntimeError "waiting queue is full" from exc try: Convert cumulative token IDs into text as worker updates arrive. while True: item = await request.output.get if item is None: break if isinstance item, Exception : raise item token ids, timestamp = item request.first token = request.first token or timestamp request.last token = timestamp request.output tokens = len token ids yield self.tokenizer.decode token ids, skip special tokens=True finally: Cancel abandoned work and record metrics for requests that started. request.cancelled.set if request.started is not None: self.stats.append { "queue s": request.started - request.arrived, "ttft s": None if request.first token is None else request.first token - request.arrived , "decode s": None if request.first token is None else request.last token - request.first token , "output tokens": request.output tokens, } async def close self : Stop the worker through the same queue and wait for clean shutdown. await self.waiting.put None await self.worker async def main : Submit one request, consume its stream, and display the final metrics. engine = MiniEngine try: async for text in engine.stream "The capital of France is" : latest text = text print "output:", latest text print "metrics:", engine.stats -1 finally: await engine.close if name == " main ": asyncio.run main 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 import asyncioimport threadingimport timefrom dataclasses import dataclass, field import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer Keep the state and timing information for one request together.@dataclassclass Request: prompt: str max new tokens: int arrived: float = field default factory=time.perf counter output: asyncio.Queue = field default factory=asyncio.Queue cancelled: threading.Event = field default factory=threading.Event started: float | None = None first token: float | None = None last token: float | None = None output tokens: int = 0 class MiniEngine: def init self, model id="sshleifer/tiny-gpt2", max waiting=4 : Load the model once, then create a bounded admission queue and worker. self.tokenizer = AutoTokenizer.from pretrained model id self.model = AutoModelForCausalLM.from pretrained model id .eval self.waiting = asyncio.Queue maxsize=max waiting self.loop = asyncio.get running loop self.stats = self.worker = asyncio.create task self. worker def emit self, request, value : Safely send worker-thread results back to the asyncio event loop. self.loop.call soon threadsafe request.output.put nowait, value def generate self, request : Run blocking model execution in the worker thread. try: inputs = self.tokenizer request.prompt, return tensors="pt" token ids = with torch.inference mode : Prefill the prompt once and retain its KV cache for decoding. result = self.model inputs, use cache=True cache = result.past key values next id = int result.logits 0, -1 .argmax Decode one token at a time, emitting cumulative token IDs. for in range request.max new tokens : if request.cancelled.is set : break token ids.append next id self. emit request, token ids.copy , time.perf counter if next id == self.tokenizer.eos token id: break if len token ids == request.max new tokens: break result = self.model torch.tensor next id , past key values=cache, use cache=True, cache = result.past key values next id = int result.logits 0, -1 .argmax except Exception as exc: Deliver model failures to the request's async consumer. self. emit request, exc finally: A None sentinel marks the end of this output stream. self. emit request, None async def worker self : Process admitted requests serially while leaving the event loop free. while True: request = await self.waiting.get if request is None: self.waiting.task done return request.started = time.perf counter if not request.cancelled.is set : await asyncio.to thread self. generate, request else: request.output.put nowait None self.waiting.task done async def stream self, prompt, max new tokens=24 : Validate and admit the request without waiting on a full queue. if not prompt or max new tokens < 1: raise ValueError "prompt must be nonempty and max new tokens positive" request = Request prompt, max new tokens try: self.waiting.put nowait request except asyncio.QueueFull as exc: raise RuntimeError "waiting queue is full" from exc try: Convert cumulative token IDs into text as worker updates arrive. while True: item = await request.output.get if item is None: break if isinstance item, Exception : raise item token ids, timestamp = item request.first token = request.first token or timestamp request.last token = timestamp request.output tokens = len token ids yield self.tokenizer.decode token ids, skip special tokens=True finally: Cancel abandoned work and record metrics for requests that started. request.cancelled.set if request.started is not None: self.stats.append { "queue s": request.started - request.arrived, "ttft s": None if request.first token is None else request.first token - request.arrived , "decode s": None if request.first token is None else request.last token - request.first token , "output tokens": request.output tokens, } async def close self : Stop the worker through the same queue and wait for clean shutdown. await self.waiting.put None await self.worker async def main : Submit one request, consume its stream, and display the final metrics. engine = MiniEngine try: async for text in engine.stream "The capital of France is" : latest text = text print "output:", latest text print "metrics:", engine.stats -1 finally: await engine.close if name == " main ": asyncio.run main 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: Start a vLLM server and inspect its Prometheus metrics. vllm serve facebook/opt-125m --max-model-len 512 In another terminal: curl -s http://127.0.0.1:8000/metrics | grep '^vllm:' | head 123 vllm serve facebook/opt-125m --max-model-len 512 In another terminal:curl -s http://127.0.0.1:8000/metrics | grep '^vllm:' | head 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 https://docs.vllm.ai/en/latest/cli/serve/ . Documents the API server and configuration flags. - vLLM documentation. Metrics https://docs.vllm.ai/en/latest/usage/metrics/ . Documents the metrics endpoint and request, cache, and latency measurements. - Hugging Face Transformers documentation. Caching https://huggingface.co/docs/transformers/en/cache explanation . 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.