LLM Inference Architecture and Cost Optimization: Engineering Practices for High-Throughput Serving

    This is a practical, engineering-oriented guide to designing and operating a high-throughput LLM inference platform. Starting from the economics of a fast-growing API business, it shows how to translate revenue growth into a capacity plan, work through the throughput–latency–cost trade-off, and apply inference-engine optimizations such as continuous batching, paged KV cache management, chunked prefill, prefill/decode disaggregation, and speculative decoding. It then covers a layered system architecture, unit-cost accounting, model routing, autoscaling and overload protection, capacity planning tied to long-term commitments, enterprise governance (SLA, multi-tenant isolation, compliance), a phased rollout roadmap, and common pitfalls. The central argument is that sustainable growth comes down to per-token cost and SLA fulfillment.

    1. Starting From a Steep Revenue Curve

    Publicly disclosed quarterly financials show a leading LLM service provider growing quarterly revenue more than 1100% year over year, with cumulative annual revenue of roughly $33.24 billion (~1200% YoY). Its enterprise-facing business contributed about $17 billion in the quarter, with more than 11,000 enterprise customers at an annualized revenue of $100,000 or more, and total contracted backlog obligations of about $320 billion at quarter-end. At the same time, the company’s total spending commitments under compute procurement and long-term leasing agreements reached about $895.4 billion. The income statement is less flattering: an operating loss of about $567 million and a net loss of about $23.3 billion, directed largely toward compute infrastructure and R&D.

    For engineering teams, this curve carries more information than any architecture diagram.

    First, revenue scales roughly with throughput. LLM API revenue is essentially driven by token consumption, so 1100% revenue growth sits on top of an order-of-magnitude increase in token throughput. The architecture must scale smoothly by design, not by throwing more machines at the problem.

    Second, the loss structure shows that compute is where the cost concentrates. The ~$23.3 billion net loss is more than 40 times the operating loss; the difference comes mainly from fair-value accounting items such as financing-valuation changes, not from day-to-day cash outflows. Even so, the business is still losing money at the operating level, and that loss is almost entirely compute-related. This means GPU utilization, cache hit rate, and per-token cost directly determine gross margin.

    Third, backlog contracts and compute commitments map to each other. The ~$320 billion of contracted backlog needs capacity to be delivered, and the ~$895.4 billion of compute commitments needs demand to be absorbed. Together they form a multi-year “revenue-to-capacity” matching chain, so capacity planning on the technical side must align with the long-horizon commitments on the commercial side.

    Fourth, enterprise customers are the dominant segment. Tens of thousands of enterprise customers make SLAs, multi-tenant isolation, data compliance, and metered billing hard requirements rather than nice-to-haves.

    Fifth, all revenue comes from API calls, enterprise subscriptions, and customized services. A stated policy of no advertising across the product line fixes the revenue sources, which means every percentage point of gross-margin improvement has to come from engineering efficiency, not from monetizing traffic.

    The rest of this article uses “architecture and cost governance for a high-concurrency LLM inference platform” as the main thread.

    2. Demand Modeling: Translating the Revenue Curve Into a Capacity Curve

    Before capacity planning, translate business language into engineering language:

    1. total token throughput = number of requests × average input tokens × (1 + average input/output token ratio) × (1 + retry amplification factor)
    2. required compute ≈ total token throughput ÷ effective per-GPU throughput
    3. effective per-GPU throughput = peak compute × compute utilization × batching efficiency × cache-hit gains

    Three amplification effects deserve particular attention:

    1. Agent-driven output expansion. Tool calls, chain-of-thought, and multi-step planning significantly increase output tokens and round trips. A single user-visible request can turn into dozens of model calls behind the scenes.
    2. Quadratic cost of long context. The complexity of attention computation grows quadratically with context length, while KV-cache memory usage grows linearly with length and concurrency. A handful of very long requests can fill up an entire inference node.
    3. Retry and timeout amplification. Client-side timeout retries and failed rate-limit backoffs push real load above the nominal business volume. If this is not measured separately, the capacity model will be systematically too low.

    In practice, teams usually collect the following as inputs:

    • P50/P95/P99 distributions of input and output tokens;
    • Peak-to-trough ratio, daily cycles, weekly cycles, and holiday effects;
    • Tenant concentration (the traffic share of the largest tenants).

    These distributions drive the downstream batching strategy and pooling design.

    3. The Core Tension: The Impossible Triangle of Throughput, Latency, and Cost

    LLM inference is constrained simultaneously by compute, memory bandwidth, and memory capacity, and it is hard to satisfy all three goals at once:

    • Chasing throughput means larger batches and longer queue waits, so per-request latency rises;
    • Chasing low latency means capping batch size and reserving headroom, so accelerator utilization drops and unit cost rises;
    • Chasing low cost means higher packing density and resource utilization, but under traffic spikes you hit capacity ceilings quickly, and tail latency and availability degrade.

    So the first step is not optimization but tiering. A common tiering scheme:

    Tier Typical scenarios Priority goal Scheduling strategy
    Interactive Chat, coding assistance/autocomplete Time to first token Dedicated pool, reserved capacity, no preemption
    Standard General API calls Balance of latency and throughput Shared pool, priority-based scheduling
    Batch Offline summarization, data processing Unit cost Allow queuing and preemption, off-peak execution
    Long-context Long-document understanding, whole-repo code analysis Memory capacity Dedicated large-memory pool, capped concurrency

    Once tiered, the “impossible triangle” turns into a single-objective optimization problem for each tier.

    4. Inference Engine: A Checklist for Extracting More From Each Unit of Compute

    1. Continuous batching. Traditional static batching must wait for an entire batch to finish generating before releasing resources, so short requests get held back by long ones. Continuous batching dynamically swaps requests in and out at iteration (token) granularity, filling a slot the moment a request completes. It is one of the most direct ways to raise accelerator utilization.

    2. Paged KV cache management. Allocating and managing KV-cache memory by token blocks significantly reduces internal fragmentation. Identical system prompts, few-shot examples, or repository context shared across requests can reuse cached blocks, sharply cutting the compute cost of repeated prefixes.

    3. Chunked prefill and prefill/decode (PD) disaggregation. Prefilling a long prompt is compute-intensive, while decoding is memory-bandwidth-intensive. Splitting long prompts into chunks and interleaving them with decode scheduling avoids a long request blocking the first-token output of others. At very large scale, prefill and decode can also be split into separate resource pools, each scaling independently according to its own bottleneck.

    4. Speculative decoding. A small model or n-gram approach first “guesses” several candidate tokens, which the large model then verifies in a single parallel pass. In scenarios with high acceptance rates, such as code completion, this noticeably reduces decode latency.

    5. Quantization and parallelism. Weight quantization (e.g., FP8, INT4) can reduce memory footprint and improve decode throughput, but its impact on output quality must be evaluated. Tensor parallelism lets you fit larger models but introduces inter-GPU communication overhead; pipeline parallelism can improve overall utilization but lengthens per-request latency. Both need to be tuned per tier.

    6. The “cold start” problem in autoscaling. Large-model instances load anywhere from several GB to hundreds of GB of weights, and cold starts can take tens of seconds to several minutes, so traditional CPU-threshold autoscaling is often “too little, too late.” Practical approaches include:

    • a pre-warmed, always-on instance pool;
    • layered weight loading or in-memory image snapshots to speed up startup;
    • scaling based on predicted queue-wait time;
    • traffic shaping.
    1. # Illustrative code: predictive scaling + overload protection (product-agnostic)
    2. # Scale-up trigger: predicted queue wait exceeds the time to complete a scale-up action
    3. queue_wait = queue_depth / max(current_throughput, 1) # unit: seconds
    4. if queue_wait > scale_up_lead_time * safety_factor: # scale_up_lead_time = time for an instance to become ready
    5. target = ceil(queue_depth / batch_capacity) + warm_pool_size
    6. scale_out(target)
    7. # Overload protection: fail fast rather than let accepted requests avalanche
    8. def admit_request(req, pool):
    9. if pool.queue_wait_estimate() > req.max_queue_seconds:
    10. raise Overloaded(req.retry_after_hint) # tell the client to back off and retry
    11. pool.enqueue(req, priority=req.slo_class)

    5. System Architecture: From Gateway to Elastic Resource Pools

    The overall architecture can be split into five layers:

    1. Access layer: handles authentication, tenant identification, quota checks, and streaming forwarding, and performs the first round of rate limiting.
    2. Scheduling layer: maintains request queues, schedules by SLO tier and tenant priority, and provides fair sharing and overload protection.
    3. Inference layer: made up of stateless inference instances that carry the engine-level optimizations; instances are pooled by tier and support independent scaling.
    4. Cache and state layer: stores prefix caches, session context, and task state, balancing low latency against persistence.
    5. Observability and metering layer: collects full-link metrics and generates token-level billing and cost-allocation data.

    Supporting capabilities include:

    • an asynchronous task queue to absorb batch-tier requests and smooth peaks and troughs;
    • an offline evaluation pipeline (automatically regressing quality, latency, and throughput after each engine or model change) to prevent optimizations from rolling back;
    • object storage for long context and datasets, plus logging and monitoring/alerting for troubleshooting and capacity warnings.

    If the whole system is built on a cloud platform such as Baidu AI Cloud, you can use general-purpose capabilities like container platforms, object storage, message queues, logging, and monitoring/alerting directly, and focus your effort on differentiating the inference engine and scheduling strategy.

    6. Cost Structure: Making Every Token Accountable

    LLM inference cost can be decomposed as:

    1. unit token cost = (accelerator cost + supporting CPU/memory + storage and network + operations amortization) / total effective output tokens
    2. effective output tokens = billed tokens × (1 - invalid request share) × (1 - duplicate-compute share)

    Model routing is one of the highest-leverage cost-reduction measures: route simple tasks to small or distilled models and complex tasks to large models, with routing decisions driven by quality evaluation and confidence signals.

    1. # Illustrative code: tiered model routing (thresholds must be set with an offline eval set)
    2. def route(prompt, context):
    3. if context["task_type"] in SIMPLE_TASKS and prompt.estimate_tokens() < ROUTE_SMALL_TOKEN_LIMIT:
    4. return small_model_endpoint
    5. if prompt.estimate_tokens() > ROUTE_LONG_TOKEN_THRESHOLD:
    6. return long_context_endpoint
    7. return default_model_endpoint

    Other key measures:

    • Off-peak scheduling: shift batch-tier tasks to trough periods to raise overall utilization on the daily cycle;
    • Resource pooling and oversubscription: reserve capacity for the interactive tier, let the batch tier fill the rest, and set preemption priorities;
    • Capacity mix: reserved instances hold the baseline, on-demand instances absorb fluctuations, and preemptible instances carry fault-tolerant workloads;
    • Budget guardrails: set per-tenant token budgets and alert thresholds to prevent abnormal or runaway loops of calls;
    • Cost attribution dashboard: map every inference expense to a tenant, business line, and model tier, so “who consumes, who benefits” is obvious at a glance.

    7. Capacity Planning: Making Capacity Commitments Defensible

    Facing contracted backlog and compute commitments in the hundreds of billions, the goal of capacity planning is no longer “is it enough?” but “how much is committed, when will it be delivered, and how do we avoid idle capacity?”

    1. Layered forecasting: start with tenant-level demand forecasts, roll them up bottom-up, then cross-check against the commercial side’s contract pipeline.
    2. Step-wise scaling: lock in baseline capacity quarterly and reserve a buffer to absorb traffic spikes and token expansion from model iterations.
    3. Pre-launch prerequisites: before a new model goes live, complete capacity load testing, latency baselines, and rate-limit thresholds so a launch does not mean immediate overload.
    4. SLA and contract linkage: map SLA tiers to specific resource pools, priorities, and penalty terms so commitments can actually be met.
    5. Idle-capacity governance: for persistently low-utilization resources, establish mechanisms to reclaim, downgrade, or redirect them to the batch tier, so committed capacity is not left spinning.

    What matters is not absolute forecast accuracy, but that forecast deviations can be detected and corrected quickly.

    8. Enterprise Governance: SLAs, Isolation, and Compliance

    Enterprise customers demand far more in stability, security, and auditability than individual users do, and this governance capability determines whether a product can enter core business systems:

    • Multi-tenant isolation: three-way isolation across quota, rate limiting, and resource pools, so one tenant’s traffic spike cannot cause “noisy neighbor” problems for others;
    • SLA system: define time to first token, generation rate, availability, rate-limit policy, and penalty standards clearly, grounded in load-test data and historical statistics rather than arbitrary promises;
    • Data security: encryption in transit and at rest, key management, tenant-level data isolation, and configurable data-retention policies;
    • Audit and observability: full-link tracing, per-tenant token-level billing, audit logs, and abnormal-call detection;
    • Content safety: bidirectional input/output filtering tied to risk-control policies;
    • Private deployment: for customers whose data cannot leave their environment, offer dedicated instances or a dedicated-environment deployment, adapting the same engine and scheduling system to different delivery models.

    9. Phased Rollout Roadmap

    Phase Timeline Focus Acceptance criteria
    Observability & baseline Months 1–2 Full-link metrics, token distribution, peak/trough profile, cost attribution Core dashboards usable, unit cost measurable
    Engine optimization Months 2–4 Continuous batching, paged cache, chunked prefill Significant gain in effective per-GPU throughput, no P99 latency regression
    Cache & routing Months 4–6 Prefix cache, model routing, off-peak scheduling Cache hit rate and gross margin improve together
    Elasticity & cost Months 6–9 Predictive scaling, resource pooling, budget guardrails Timely peak scaling, steady rise in overall utilization
    Capacity & commitments Ongoing Layered forecasting, step-wise scaling, SLA linkage Capacity commitment fulfillment rate is quantitatively trackable

    10. Common Pitfalls

    • Looking only at average utilization: averages hide the long tail. Base decisions on P95 utilization by tier and by time window.
    • TTFT-only thinking: “fake smoothness,” where the first token arrives fast but generation is slow, also hurts the experience, so generation rate must be monitored too.
    • Ignoring retry amplification: client-side timeout retries can multiply real load, so the capacity model must account for it.
    • Treating context compression as free cost reduction: forcibly truncating context can degrade output quality, trigger more corrective calls, and raise total cost.
    • One-size-fits-all quantization: it pays off clearly in some scenarios but can be counterproductive in precision-sensitive ones like code and math, so it must be evaluated per scenario.
    • Scaling up all at once, after the fact: large-model instances start slowly, so reactive scaling is only firefighting; combine predictive scaling with always-on warm standby.
    • Treating margin optimization as a pure finance problem: in an inference business, cache hit rate, batching efficiency, and model routing strategy are the most direct financial levers.

    Conclusion

    How steep the revenue curve ultimately becomes depends on how efficiently the inference system turns each unit of compute into usable tokens. From demand modeling and engine optimization to elastic scaling, cost governance, and enterprise-grade safeguards, competition among high-growth LLM services comes down to per-token cost and the ability to fulfill SLAs. Get this main thread right, and growth becomes sustainable.