Serverless Inference for Large Language Models: A Production Deployment Guide

    This guide explains how to move large language model (LLM) inference to a serverless model, why standard function platforms are not a direct fit, and how to address the main technical challenges. It covers cold-start optimization, scaling signals, GPU memory and batching constraints, streaming connections, a reference architecture with sample code, stability and cost governance, observability metrics, and a phased rollout plan. Readers will get a practical blueprint for evolving from single-instance validation to production-scale operation.

    1. Why LLM Inference Needs to Be Serverless

    Traditional inference services reserve capacity for peak load, so resources sit idle most of the time. LLM weights often reach tens of gigabytes, and a single instance is expensive, which amplifies the waste from static provisioning. The core value of serverless inference is decoupling resource consumption from request volume: scale to zero when there is no traffic, scale out automatically when traffic arrives, and pay only for actual invocations.

    However, LLM workloads differ fundamentally from general-purpose serverless functions: a single request takes a long time, GPU memory usage is high, and model loading is slow. You cannot simply apply the assumptions of a general function platform. The loading, caching, and scheduling strategy needs to be redesigned at the architecture level.

    2. Key Challenges and How to Address Them

    2.1 Cold Start

    Cold start consists of three parts: scheduling latency, image/runtime pulling, and weight loading. Common optimization techniques include:

    • Separate weights from the container image, store weights in object storage, and download shards in parallel after a node starts;
    • Keep a minimum-capacity “warm pool” to absorb traffic spikes;
    • Cache hot weights on a local cache disk or in an in-memory file system;
    • Quantize the model and fuse operators to shorten loading and first-forward time.

    2.2 Choosing Scaling Metrics

    Scaling on request count often lags in LLM scenarios. A more reasonable approach is to use “in-flight concurrent requests” and “queue wait time” as scaling signals, and set an upper bound on the scaling step to avoid oscillation.

    2.3 GPU Memory and Batching

    GPU memory is a hard constraint. You need to cap the maximum batch size and maximum sequence length, use continuous batching to improve throughput, and give long-text requests a separate queue to prevent head-of-line blocking.

    2.4 Long Connections and Streaming Output

    Streaming responses significantly extend connection occupancy. Scaling signals must be decoupled from connection count, and token generation rate should be used as the capacity reference.

    3. Reference Architecture and Sample Code

    A typical layering is: access layer (authentication, rate limiting) → scheduling layer (queues, priorities) → inference layer (serverless worker pool) → supporting layer (object storage, logging, monitoring and alerting).

    1. # Sample: inference call wrapper with a concurrency gate and timeout
    2. import asyncio
    3. sem = asyncio.Semaphore(64) # Per-instance concurrency limit, determined by GPU memory
    4. async def infer(client, prompt, timeout=30):
    5. async with sem:
    6. return await asyncio.wait_for(
    7. client.generate(prompt, stream=True), timeout=timeout
    8. )

    4. Stability and Cost Governance

    For stability, implement three levels of degradation: model degradation (switch from a large model to a smaller one), result degradation (serve a cached approximate answer), and experience degradation (show a queuing notice). For cost, establish two metrics: “cost per thousand tokens” and “throughput per unit of compute.” Regularly review batch size and instance specifications. For offline tasks that tolerate latency, use a low-priority queue and run them off-peak.

    5. Observability

    At a minimum, you need four categories of metrics: latency (time to first token, overall latency), throughput (tokens/s), resources (GPU memory usage, batch utilization), and quality (truncation rate, timeout rate, failed-retry rate). Logs should record a request identifier for full-link tracing, and extra-long inputs should be instrumented separately.

    6. Capability Support on Baidu AI Cloud

    When deploying this architecture on Baidu AI Cloud, you can use general-purpose capabilities directly: object storage for weights and datasets, a container platform for the inference worker pool, a message queue for request buffering and peak shaving, and logging plus monitoring and alerting to close the observability loop. Model services and elastic resources can be combined on demand, enabling a smooth evolution from validation to production scale.

    Phase 1: validate accuracy and latency baselines on a single instance. Phase 2: add queues and concurrency gates, and load-test to find the inflection point. Phase 3: introduce a warm pool and canary release, ramping traffic by percentage. Phase 4: complete degradation and cost dashboards, and establish a routine operations mechanism.