Building a Production-Grade LLM Inference Platform: Practices and Architecture

    This article explains what it takes to move large language model inference from a lab demo to a production platform. It covers a five-layer architecture, cache-aware routing, SLO-based autoscaling, observability signals specific to inference, stream resumption for long sessions, continuous tuning against real traffic, a phased rollout plan, and common anti-patterns. Engineers will find concrete logic, configuration examples, and evaluation practices they can adapt to their own infrastructure.

    1. Why “It Runs” Is Not “Production-Ready”

    In a lab environment, an inference service is considered working as soon as it loads weights and responds to a single request. Production changes the evaluation criteria entirely: Does a request return within the agreed latency? Does throughput hold when traffic spikes? Can a session recover if an instance exits unexpectedly? Does a long-tail request drag down GPU utilization? Can model or parameter changes be evaluated quantitatively?

    These concerns share one trait: none of them belong to the model itself. They belong to the scheduling and operations system around the model.

    The core goal of a production-grade inference platform is therefore to consolidate scattered capabilities into reusable infrastructure: deployment orchestration, traffic scheduling, elastic scaling, observability, fault-tolerant resume, and continuous tuning. Each is covered below.

    2. Layered Architecture

    A production-ready inference platform is typically divided into five layers, top to bottom:

    • Access layer: unified entry point, authentication, rate limiting, protocol adaptation (sync/streaming).
    • Scheduling layer: routing policy, cache affinity, queues and priorities, overload protection.
    • Execution layer: model instance orchestration, batching and GPU memory management, warmup and readiness checks.
    • Elasticity layer: SLO-based scaling, resource profiling, cold-start optimization.
    • Operations layer: metrics, logs and tracing, evaluation regression, continuous parameter and configuration tuning.

    The value of layering is fault-domain isolation: overload at the access layer should not crush the execution layer, elasticity jitter should not cause routing oscillation, and tuning actions in the operations layer must pass an evaluation gate before taking effect.

    3. Cache-Aware Routing: Sending Requests to the Most Compute-Efficient Instance

    The cost structure of LLM inference differs sharply from traditional stateless services. Prefix computation (prompt encoding) and context caching significantly affect per-request latency. If routing is simple round-robin, requests sharing the same system prompt or the same long document get scattered across instances, cache hit rates drop, and redundant computation rises.

    The idea behind cache-aware routing: maintain a “fingerprint set” of cached prefixes for each instance, compute how well an incoming request’s prefix matches an instance’s cache, then make a weighted decision that also accounts for instance load. Illustrative logic:

    1. def pick_instance(req, instances):
    2. # 1) Compute prefix fingerprint (e.g., stable hash of the first N tokens)
    3. fp = prefix_fingerprint(req.prompt)
    4. # 2) Filter unavailable instances; compute affinity score and load penalty
    5. best, best_score = None, float("-inf")
    6. for ins in instances:
    7. if not ins.ready or ins.draining:
    8. continue
    9. affinity = ins.cache_hit_ratio(fp) # 0~1
    10. load = ins.inflight / ins.max_inflight # 0~1
    11. score = 0.7 * affinity - 0.5 * load
    12. if score > best_score:
    13. best, best_score = ins, score
    14. # 3) Fall back to least load when affinity is generally low, avoiding hotspots
    15. return best or min(instances, key=lambda i: i.inflight)

    Three engineering caveats: first, the affinity weight must not be too high, or load will skew; second, scaling instances invalidates cache, so affinity weight should be reduced during a “rebalancing window”; third, once a streaming request establishes a connection, keep session stickiness to avoid switching instances mid-stream.

    4. SLO-Based Autoscaling: From “Watching CPU” to “Watching Service Objectives”

    CPU-utilization-based scaling largely fails for inference: GPU utilization may be low while requests are already queuing badly, or utilization may be high while latency is still within SLO. A better approach uses service objectives as the feedback signal, such as P95 time-to-first-token, P99 end-to-end latency, queue time, and rejection rate.

    A practical control loop:

    1. Define the SLO and observation window, e.g., “P95 TTFT ≤ 800ms sustained for 1 minute.”
    2. Collect a composite metric: pressure = w1*queue_time_norm + w2*latency_norm + w3*reject_rate.
    3. Add damping to scaling decisions: scale up only after N consecutive breaching windows, scale down only after M consecutive surplus windows, to avoid oscillation.
    4. Cold-start governance: weight loading and warmup are the main latency sources. Keep a minimum “warm standby” replica count, use image and weight prefetching, and load shards in parallel.
    1. scaling:
    2. target:
    3. slo: {ttft_p95_ms: 800, e2e_p99_ms: 4000}
    4. cooldown: {up_seconds: 60, down_seconds: 300}
    5. bounds: {min_replicas: 2, max_replicas: 40}
    6. warm_pool: 1 # Warm standby replicas to shorten scale-out effect time

    Note that elasticity must work with scheduling: at the moment of scale-out, new instances have empty caches, so cache affinity weight should be temporarily reduced to let traffic transition smoothly, rather than flooding the new instances at once as “idle and optimal.”

    5. Observability: Four Signal Categories for Inference

    Observability for inference services cannot stop at QPS and error rate. At minimum, cover:

    • Request quality: input/output token length distribution, truncation rate, over-limit rejection rate.
    • Latency breakdown: queue time, prefix encoding time, per-token decode time, network and serialization overhead.
    • Resource efficiency: GPU memory usage and fragmentation, actual batch size, cache hit rate, cost per token.
    • Stability: instance ready/drain events, scaling counts, session interruption and recovery success rate.

    Latency breakdown is especially critical: only by separating “queuing” from “computation” can you tell whether the problem is insufficient capacity or an overly heavy single request. Emit a structured record per request with per-stage timings, and link access and execution layers with a trace ID for long-tail diagnosis.

    6. Stream Resumption: Fault Tolerance for Long Sessions and Long Outputs

    Long-form generation, multi-turn conversations, and streaming output are most vulnerable to an instance failure or connection drop forcing a full restart. The general approach to stream resumption introduces a “generation position”: the server persists generated content and context state (session ID, generated token sequence, sampling parameter summary) at fixed intervals; the client reconnects with the position and continues from the breakpoint instead of re-inferring.

    Key points: persist positions to low-latency key-value or message-oriented storage to avoid blocking the decode loop; validate parameter consistency on resume requests to prevent context drift; design for idempotency so resubmitting the same position produces no duplicate content; and set maximum resume counts and total duration limits to prevent abnormal loops.

    1. POST /v1/chat/completions {session_id, prompt, stream:true}
    2. -> event stream: delta / checkpoint(seq=128) / done
    3. After disconnect:
    4. POST /v1/chat/resume {session_id, seq:128}
    5. -> continue emitting delta from seq=128

    7. Tuning Agent: Continuous Optimization Against Real Workloads

    “Optimal parameters” from offline benchmarks often do not hold under real traffic, because real workloads vary enormously in input length distribution, concurrency patterns, and business time-of-day. The idea of continuous tuning is to sample real online requests into a replay set, run controlled experiments around batch size, parallelism/sharding strategy, cache capacity, sampling and decoding parameters, and replica specs, and evaluate with dual objectives of SLO and cost.

    Three disciplines in practice: first, all changes go through canary release and automatic rollback, restoring the previous configuration immediately when metrics breach; second, the optimization objective must include a cost term, avoiding “latency met but cost doubled”; third, bind configuration and model versions for management, forming a traceable “workload–configuration–result” ledger so tuning conclusions are reproducible.

    1. def evaluate(config, replay_set):
    2. m = run_replay(config, replay_set)
    3. feasible = m.ttft_p95 <= SLO.ttft_p95 and m.e2e_p99 <= SLO.e2e_p99
    4. return (feasible, m.cost_per_1k_tokens, m.throughput)
    5. # Compare cost only when feasible is true; otherwise treat as an unusable candidate
    • Phase 1: unify access and standardize protocols; fill in latency breakdown and error classification to make problems “measurable” first.
    • Phase 2: launch cache-aware routing and overload protection, usually the fastest payoff.
    • Phase 3: adopt SLO-based elasticity and warm standby; load-test cold-start and jitter boundaries.
    • Phase 4: implement stream resumption and idempotent semantics for long-session workloads.
    • Phase 5: establish a replay and canary evaluation loop so tuning becomes a standing capability rather than a one-off action.

    9. Common Anti-Patterns

    • Scaling only on GPU utilization, ignoring queue and rejection signals.
    • Cache affinity weight set too high, causing hotspots on a few instances and lower overall throughput.
    • Elasticity and routing operating independently, causing violent traffic redistribution after scale-out.
    • Observability with only aggregate metrics and no breakdown, making long-tail issues impossible to attribute.
    • Promoting tuning conclusions from a single load test directly to full rollout, with no canary or rollback.

    10. Conclusion

    The competitiveness of a production-grade inference platform lies not in single-point model performance but in organizing routing, elasticity, observability, fault tolerance, and tuning into a closed loop: observability provides signals, scheduling and elasticity consume them, resumption preserves experience continuity, and tuning turns online feedback into configuration improvements. When this loop runs stably, the inference service truly moves from demo to operable infrastructure. To shorten the build cycle, teams can build the foundation on general cloud capabilities such as container platforms, log services, monitoring and alerting, and object storage, focusing effort on scheduling policies and the evaluation system where real differentiation lies.