High-Throughput LLM Inference Framework Design and Engineering Practice

    This article explains how production LLM inference has moved from “it can run” to “it can operate”: predictable throughput and latency under hardware, SLA, and security constraints. It lays out a seven-layer architecture, then covers operator–engine co-design, async continuous batching, distributed and expert parallelism, speculative decoding, bounded replay for sliding-window attention, constrained structured output, and tokenizer consistency. It also discusses private vs. cloud deployment, multi-accelerator adaptation, production gaps such as distributed KV cache and cache-aware routing, and a practical path for evaluation, tuning, and a full request lifecycle.

    1. Background: Inference Has Moved from “Runnable” to “Operable”

    Once large language models enter production, the goal of an inference system is no longer “a single request returns a result.” It is to deliver predictable throughput and latency, continuously and stably, under a given hardware budget, SLAs, and security constraints. Compared with traditional online services, LLM inference has several distinctive traits:

    • Compute and memory access are unbalanced. Prefill is more compute-heavy; token-by-token decode is more memory- and scheduling-heavy. The same system must serve long prompts, short outputs, long outputs, and high-concurrency short requests.
    • GPU memory and cache become first-class resources. Weights, KV cache, temporary activations, and communication buffers compete. Cache policy directly sets concurrency limits and tail latency.
    • Model structure is more complex. Mixture-of-experts, long context, multimodal input, and structured output mean the framework cannot only wrap a forward pass; it must own scheduling, parallelism, operator optimization, and protocol adaptation.
    • Deployment shapes vary. Enterprises need private deployments for data isolation and compliance, and elastic scale-out on public cloud. Hardware generations, network topologies, and precision strategies also differ.

    From public descriptions of this class of open-source inference frameworks, the value is not only open model-execution code. It is a relatively complete base of operators, engine, distributed execution, scheduling, and multi-platform adaptation: offline inference, token encode/decode, production-grade implementations across accelerator types, and core techniques around MoE, async batch scheduling, and custom kernels. Online KV-cache storage and cross-replica load balancing are often not fully open, which highlights the engineering gap between an “open inference framework” and an “operable inference platform.”

    This article treats that class of systems without naming a specific product. It abstracts a reusable architecture and engineering practice.

    2. Overall Architecture: Layered Design from Protocol to Kernel

    A production LLM inference framework typically splits into seven layers:

    1. Protocol and ingress: request protocols, auth, quotas, rate limits, timeouts, cancellation, streaming, and structured-output declarations.
    2. Encode/decode: text ↔ token sequences, special tokens, normalization, streaming boundaries, and version consistency.
    3. Admission and scheduling: multi-priority queues, continuous batching, token-budget control, chunked prefill, and backpressure.
    4. Distributed execution: execution plans from topology, parallelism, cache location, and expert load.
    5. Model execution and cache: attention, FFN, expert routing, KV-cache management, speculative-decoding verification.
    6. Operators and runtime: fused ops, custom kernels, memory allocation, communication primitives, and heterogeneous device abstraction.
    7. Observability and governance: metrics, logs, traces, incidents, and audit data for capacity planning and recovery.

    A simplified request path:

    1. request -> auth/quota -> tokenization -> structured-constraint compile
    2. -> admission queue -> batch scheduler -> distributed execution plan
    3. -> model executor (attention / expert routing / KV cache / speculative verify)
    4. -> streaming decode -> metrics and logs -> response

    The point of the layers is not count; it is clear resource bounds and failure policy. Scheduling must not pile requests unbounded: apply backpressure from run-queue length, KV-cache watermarks, and expected wait. Execution must not assume every operator exists on every accelerator: need fallbacks and numerical checks. Ingress should push structured output, max context, and streaming constraints forward so invalid work never reaches expensive model steps.

    3. Core Techniques

    3.1 Operator and Engine Co-Design

    High-performance inference is not wrapping a model script as a service. Throughput and latency are driven by fusion, data layout, dynamic shapes, quantization, memory reuse, and communication overlap.

    Co-design typically shows up in three ways:

    • Fusion and fewer memory round-trips. Fuse adjacent ops such as normalization, residual, activation, and positional encoding. Attention needs different implementations by sequence length, batch size, and cache layout.
    • Dynamic shapes and batching. Online input and output lengths are irregular. Operators must support dynamic shapes, variable-length sequences, and chunked compute. Fixed-shape-only optimization can look strong offline and still worsen tail latency in production.
    • Multi-accelerator abstraction. Devices differ in ISA, precision, memory hierarchy, and interconnect. Device-specific capability belongs in the operator layer so upper scheduling stays stable. Porting is more than “it compiles”: verify numerics, long-sequence stability, failure recovery, and performance regressions.

    Custom kernels are not better in volume. Each one raises maintenance and regression cost. A reasonable path: a verifiable baseline with generic ops, measurable fusion and layout work on hot paths, then shadow traffic and a benchmark suite to confirm gains.

    3.2 Async Batch Scheduling: Balancing Throughput and Tail Latency

    LLM scheduling usually uses continuous batching: while one request is still generating tokens, new requests can join the same step, raising utilization. High throughput is not unbounded batch size. Larger batches increase step time and hurt interactive tail latency; smaller batches waste the device and raise cost per token.

    A practical async scheduler must handle at least:

    • Token budget, not request count. Prompt and output lengths vary widely; batching by request count loses budget control. Decide the batch from tokens this step, cache occupancy, and attention complexity.
    • Chunked prefill. One-shot prefill of a long prompt blocks decode. Split prefill into small steps interleaved with decode to reduce interference with short requests.
    • Multi-priority and anti-starvation. Interactive, offline batch, and internal eval need different priorities. High-priority queues must not starve low-priority work under sustained load; use aging or time quotas.
    • Backpressure and cancel. When KV-cache watermarks are high or wait exceeds SLO, admit fewer new requests, or let clients cancel and free cache immediately.
    • Explainable metrics. Expose queue length, tokens per batch, prefill vs. decode mix, wait-time percentiles, cache hits and evictions—so you can tell “not enough compute” from “scheduling imbalance.”

    Illustrative scheduling loop (structure only, not a real API):

    1. while serving:
    2. ready = admission.poll()
    3. batch = scheduler.select(
    4. ready,
    5. policy="slo_aware",
    6. token_budget=B,
    7. max_wait_ms=W,
    8. priority=["interactive", "batch"]
    9. )
    10. plan = runtime.plan(batch, topology, cache_state)
    11. outputs = engine.step(plan)
    12. scheduler.complete(batch, outputs)
    13. metrics.observe(batch, outputs)

    Policy must match the deployment goal. Chat should prioritize time-to-first-token and inter-token latency. Offline data production can tolerate worse tails for more tokens per unit time. Isolate the two loads physically or logically so offline floods do not take down online serving.

    3.3 Distributed Inference and Expert Parallelism

    Parallelism typically includes tensor, pipeline, and expert parallel. Tensor parallel splits a layer across devices, cutting per-card memory and compute but adding intra-layer communication. Pipeline parallel splits by layer, which fits multi-node setups but needs micro-batch scheduling and bubble control. Expert parallel places different MoE experts on different devices and routes tokens accordingly.

    For MoE, the hard part is not only expert count, but routing imbalance and communication:

    • Token dispatch and gather. The router sends tokens to experts from gating, then merges results. All-to-all frequency, batch size, and topology awareness drive tail latency.
    • Expert load balance. Hot experts overload some devices while others idle. Capacity limits, expert replication, routing noise, auxiliary losses, or runtime migration can help, but inference-time room is limited; co-design with the model is required.
    • Communication overlap. Overlapping expert compute, dispatch, gather, and the next schedule step raises throughput, but complexity grows: partial failure and timeouts must be handled.
    • Tail amplification. A few tokens on a slow node can stall the whole step. Schedulers should see device load and topology and not blindly grow batches.

    Distributed plans should be fallback-first. If a parallel path fails, degrade to a more conservative strategy instead of taking the whole service down.

    3.4 Speculative Decoding: Extra Compute for Lower Latency

    The idea: a smaller draft model or draft head proposes candidate tokens; the target model verifies them in one pass and accepts those that match the target distribution. High accept rates cut serial decode steps and inter-token latency; low accept rates make draft work pure overhead.

    Engineering focus:

    • Adaptive draft length. Fixed length varies widely by task. Adjust from recent accept rate, request type, and load.
    • Batched verification. Verification can compute several positions in parallel, but sampling, temperature, and constrained decoding must stay consistent.
    • Structured output. Under grammar or schema constraints, draft tokens must also be legal, or accept rate drops and invalid results appear.
    • Cost accounting. Speculation is not always faster. Gains are clear when target decode is the bottleneck, accept rate is high enough, and extra memory is affordable.

    3.5 Sliding-Window Attention with Bounded Replay

    In long-context inference, KV cache grows linearly with sequence length. Sliding-window attention keeps only a recent window, bounding attention compute and storage. If the task needs earlier information, the window alone can lose accuracy.

    “Bounded replay” means checkpointing and replaying history under finite memory and time: keep key states or compressed summaries near window boundaries, and replay a short history on demand instead of growing cache without bound. Engineering points:

    • Bounded resources. Cap replay length, checkpoint count, and replay frequency so long requests do not exhaust cache budget.
    • Consistency. Replayed state must be numerically close enough to a normal forward pass, or style can drift within one request.
    • Layered policy. Interactive traffic can keep the recent window; offline long documents can get more checkpoints; approximate settings can use summaries or retrieval instead of full replay.
    • Observability. Record replay triggers, extra compute time, and cache hit rate to see whether the long-context policy actually improves quality.

    3.6 Structured Output: Constrained Decoding and Protocol Consistency

    Structured output requires a schema: fixed fields, enums, nested arrays, parseable formats. Prompts alone are unreliable. Production systems typically use constrained decoding: at each step, mask illegal tokens given grammar state so only tokens that advance a legal state remain.

    Illustrative logic:

    1. state = grammar.initial()
    2. while not state.finished():
    3. logits = model.step(context, cache)
    4. legal = state.allowed_tokens()
    5. next_token = sample(mask_illegal(logits, legal))
    6. state = state.advance(next_token)
    7. emit(next_token)

    Hard parts are performance and correctness:

    • Cost of the legal set. Recomputing legal tokens every step can be expensive. Precompile grammar states, cache transition tables, and limit complex schemas.
    • Streaming plus final validation. Stream with local checks, but still deserialize and apply business validation on the full response.
    • Tokenizer alignment. Special tokens, whitespace, and escaping affect structure; encode/decode must match the constrained decoder.
    • Failure recovery. If the model cannot satisfy the constraint, return a clear error or fall back to plain text—not output that looks structured but will not parse.

    3.7 Token Encode/Decode: Small Module, Global Consistency

    Tokenization looks like text ↔ integers, but it affects cache keys, audit logs, streaming, structured constraints, and client/server protocols. A reliable component should guarantee:

    • Encode/decode invertibility, or explainable differences. Normalization, case, whitespace folding, and special tokens need explicit rules.
    • Correct streaming boundaries. A character may span multiple tokens; do not emit half a character on every token.
    • Version consistency. Model upgrades can change the vocabulary and special-token semantics. Serving, clients, and offline eval must match versions.
    • Sensitive data. Prompts, tokens, and generations may be sensitive; logs need redaction, sampling, and access audit.

    4. Deployment Shape and Multi-Accelerator Adaptation

    Private deployment emphasizes data staying in-domain, dedicated resources, and auditability. Public cloud emphasizes elasticity, on-demand scale, and multi-tenant isolation. Switching location is not enough: scheduling, storage, network, and operations all change.

    On the cloud, an inference cluster can sit on general infrastructure such as Baidu AI Cloud container platforms, object storage, logging, and monitoring: containers for stateless replicas, object storage for weights and offline eval data, logs and metrics for observability. That only solves the resource and ops base. Throughput and latency still depend on parallelism, batching, cache design, and kernel quality.

    Multi-accelerator adaptation needs three layers:

    1. Device abstraction: a unified description of memory, compute, communication, and supported precision so scheduling stays decoupled.
    2. Operator implementations: multiple backends for core ops, generic fallbacks, and numerical plus performance baselines for fused ops.
    3. Release validation: a matrix of device × model covering short requests, long context, high concurrency, structured output, failure recovery, and soak tests.

    5. Open Boundaries vs. Production Gaps

    Public materials typically open offline inference, operator and engine code, and some platform adapters first. Online KV-cache storage and cross-replica load balancing are often incomplete. That split is understandable: offline inference is easier to reproduce; online cache and global scheduling couple tightly to infrastructure, topology, and business policy.

    To run an open framework in production, enterprises usually still need:

    • Distributed KV cache: sharding, tiered storage, eviction, consistency, and recovery. Lost or mismatched cache causes extra compute, wrong results, or tail spikes.
    • Cache-aware cross-replica routing: same session or similar prefixes hitting the same cache cut cost, but the router must also consider queues, expert hotspots, tenant quotas, and failure domains—not hash alone.
    • Multi-tenant governance: auth, quotas, rate limits, audit, key management, network isolation, and redaction.
    • Model lifecycle: version registry, canaries, shadow traffic, rollback, A/B tests, and capacity rehearsals.
    • Observability and incident handling: TTFT, inter-token latency, throughput, error rate, cache hits, device utilization, and communication wait.

    A conservative path: validate correctness, operator coverage, and baseline performance offline; then a single-cluster online service with scheduling, monitoring, and rate limits; then cache-aware routing and multi-cluster DR; then a platform with hosting, elastic scale, and cost control.

    6. Evaluation, Tuning, and Practice

    Do not judge only “tokens per second.” Track at least:

    • TTFT percentiles (interactive experience);
    • inter-token interval percentiles (generation smoothness);
    • end-to-end success and timeout rates;
    • device utilization and communication-wait share;
    • KV-cache hits, evictions, and memory watermarks;
    • expert load skew and hot-expert share;
    • speculative-decoding accept rate;
    • structured-output constraint failure rate.

    Benchmarks should replay real traffic across input/output lengths, concurrency, and priorities. Warm up first, record percentiles not means, and check quality and constraint satisfaction after. Comparing throughput only on fixed short prompts is misleading.

    Start tuning from this list:

    1. Scheduling: token budget, max concurrency, chunked-prefill grain, priority queues; watch whether throughput gains cost tail latency.
    2. Parallelism: mix of tensor, pipeline, and expert parallel from model size, topology, and interconnect; avoid high-frequency traffic over slow links.
    3. Cache: block size, suffix reuse, eviction, tiered storage; bigger is not always better—balance hit rate vs. memory pressure.
    4. Operators: fusion and layout on hot paths; every custom kernel in regression tests.
    5. Speculative decoding: enable or disable drafts by task, adapt draft length, avoid low accept rates slowing the fleet.
    6. Structured output: precompile schemas, cache transitions, limit deep nesting so constraint checks are not a new bottleneck.
    7. Release: canaries, shadow traffic, capacity rehearsals, degradation and fast rollback.

    7. Full Path of One Online Request

    1. Ingress: auth, quota, size limits, timeouts.
    2. Encode: tokens plus redacted audit as needed.
    3. If structured output is declared, precompile constraints and an initial grammar state.
    4. Admission by priority and watermarks; if the queue is too long, return backpressure.
    5. Scheduler picks by token budget; chunked prefill or interleave with decode.
    6. Distributed layer builds a parallel plan, trading cache hits, device load, and expert placement.
    7. Executor runs attention, expert routing, cache updates, and speculative verification.
    8. Output returns after constraint checks and streaming decode; metrics and logs fire.
    9. On node failure or cache invalidation, retry, degrade, or stop per policy to avoid cascading failure.

    8. Conclusion

    A high-throughput LLM inference framework is a continuous trade among compute, memory, network, and latency. Operator–engine co-design sets single-node efficiency; async batching sets cluster throughput and tails; distributed and expert parallel set model-scale limits; speculative decoding, bounded sliding-window replay, and structured output extend specific scenarios. Open frameworks lower the starting cost, but online KV cache, cross-replica balancing, multi-tenant governance, canary release, and observability still need to be completed against each enterprise’s infrastructure.

    A realistic strategy: establish correctness and performance baselines with offline inference, then add online scheduling and cache governance. Ground every optimization in measurable SLO, cost, and quality—do not confuse a fast microbenchmark with an operable production system. When scheduling, cache, kernels, and operations close the loop, the framework becomes lasting LLM infrastructure rather than a set of open components.