Anthropic's IPO and the Real Challenge of LLM Inference: Capacity, Performance, Stability, and Cost Governance at Scale

    Capital activity around AI—large funding rounds and IPO news—keeps making one point: large language models are no longer research topics but infrastructure that must be served continuously. This article takes a neutral, engineering-focused view of what it actually takes to deliver LLMs at scale. It walks through the full request pipeline and breaks it into five areas—capacity planning, inference performance, elasticity and stability, observability, and cost governance—and adds a regression-safety layer plus a phased rollout roadmap. You'll learn to budget capacity in tokens rather than QPS, separate prefill from decode workloads, tune batching windows, apply prefix and result caching, design timeout budgets and tiered degradation, unify metric definitions, and route requests across model tiers to control cost without silently regressing quality. The code samples illustrate scheduling and governance ideas; the specific performance and cost numbers must come from your own measurements.

    Introduction: The Real Bottleneck of Scaling Delivery Is Inference Engineering

    The capitalization of the AI industry is accelerating, with frequent news of large funding rounds and IPOs. These events repeatedly prove one thing: large language models have gone from research topics to infrastructure that must be delivered as a continuous service. For developers and technical leads, the more valuable question is not valuation but how to support large-scale commercial delivery.

    The typical pipeline of an LLM service is: user input goes through preprocessing, retrieval augmentation, and prompt assembly, then enters inference serving, and finally undergoes post-processing, content-safety checks, and result return. The inference stage determines most of the cost, latency, and stability:

    • Cost: Inference compute typically grows linearly with call volume; services without budget management easily see their bills spin out of control;
    • Latency: Time to first token (TTFT) determines the interaction experience; for long-output scenarios, you also need to watch per-token output latency (TPOT);
    • Stability: Inference time fluctuates widely and output length is unpredictable, so the requirements for rate limiting, queuing, and graceful degradation are far higher than for ordinary web services.

    This article breaks this pipeline into five parts—capacity planning, inference performance, elasticity and stability, observability, and cost governance—and gives engineering practices for each.

    Part 1: Capacity Planning—Translate Business Traffic into a “Compute Ledger” First

    1.1 Don’t Just Watch QPS; Budget in Tokens

    Traditional web services often measure capacity with queries per second (QPS). LLM services, however, must consider both input tokens and output tokens at the same time. Within the same service, summarization requests might take a few thousand input tokens and produce a few hundred output tokens, while conversational requests may span multiple turns with a steadily growing context. The compute structure the two consume is completely different.

    Estimations should cover the following parameters:

    1. Average and P95 input length (including system prompts, retrieved snippets, and conversation history);
    2. Average and P95 output length, plus the share of streaming output;
    3. Peak-to-trough ratio and peak concentration, such as the share of traffic during evening peak hours;
    4. Context-window limits and the proportion of requests that exceed them.
    1. # Capacity budget: translate business traffic into daily and peak token demand (sample parameters; replace with values measured on your business)
    2. AVG_INPUT_TOKENS = 1800 # Average input length, including system prompt and retrieval context
    3. AVG_OUTPUT_TOKENS = 350 # Average output length
    4. P95_INPUT_TOKENS = 4000 # Capacity watermark reference for long-context requests
    5. PEAK_QPS = 40 # Peak queries per second
    6. PEAK_HOUR_RATIO = 0.12 # Share of daily traffic that lands in the peak hour
    7. def capacity_budget(avg_qps: float, seconds_per_day: int = 86400) -> dict:
    8. daily_requests = avg_qps * seconds_per_day
    9. daily_input = daily_requests * AVG_INPUT_TOKENS
    10. daily_output = daily_requests * AVG_OUTPUT_TOKENS
    11. # Peak-hour throughput: input plus output, divided by the number of seconds in that hour
    12. peak_hour_tps = (daily_input + daily_output) * PEAK_HOUR_RATIO / 3600
    13. return {
    14. "daily_input_tokens": int(daily_input),
    15. "daily_output_tokens": int(daily_output),
    16. "peak_hour_tokens_per_sec": int(peak_hour_tps),
    17. "instance_hint": round(peak_hour_tps / TARGET_TOKENS_PER_SEC, 1),
    18. }

    1.2 Distinguish Two Load Types: “Prefill” and “Decode”

    Modern LLM inference usually has two phases:

    • Prefill: processes all input tokens in parallel at once; compute-intensive, and it directly determines TTFT;
    • Decode: generates token by token autoregressively; memory-access-intensive, and per-step time determines output speed.

    This means the two load types cannot be scaled with the same yardstick: long-input, short-output scenarios (such as document QA) should prioritize prefill throughput; long-output, low-latency scenarios (such as code completion and real-time chat) need to guarantee decode parallelism. During capacity planning, first profile request lengths for the business, then set targets for each separately.

    1.3 Introduce SLOs to Turn Capacity into a Promisable Service Level

    Capacity numbers only matter when bound to SLOs. At minimum, define three metrics:

    • TTFT: P95 of time to first token;
    • TPOT: average time to output each token, used to measure generation fluency;
    • Queueing latency: the time between a request entering the inference queue and starting to execute.

    Queueing latency is the most easily overlooked signal in capacity planning. When it keeps rising, it usually means concurrent requests have already exceeded the safe watermark of the inference service, and loading more requests will only drag down the experience of all of them.

    Part 2: Inference Performance Optimization—Make Every Unit of Compute Count

    2.1 Dynamic Batching: Let Discrete Requests “Carpool”

    The bottleneck in generative inference is often not peak compute but batching efficiency. When requests are executed serially one by one, accelerators spend much of their time waiting, and memory bandwidth cannot be fully utilized. Dynamic batching merges multiple requests that arrive within a short time window into a single batch, which can significantly boost overall throughput.

    1. import asyncio, time, uuid
    2. class InferenceGateway:
    3. """Dynamic batching gateway: merges requests within a short time window to reduce serial waiting.
    4. In production, the inference serving layer usually has continuous batching and paged-cache management built in;
    5. this class is here to illustrate the scheduling idea."""
    6. def __init__(self, batch_window_ms: int = 20, max_batch: int = 16):
    7. self.batch_window_ms = batch_window_ms
    8. self.max_batch = max_batch
    9. self._queue: asyncio.Queue = asyncio.Queue()
    10. asyncio.create_task(self._batch_loop())
    11. async def chat(self, messages, deadline_budget: float = 3.0):
    12. fut = asyncio.get_running_loop().create_future()
    13. await self._queue.put({"rid": uuid.uuid4().hex,
    14. "messages": messages, "fut": fut})
    15. return await asyncio.wait_for(fut, timeout=deadline_budget)
    16. async def _batch_loop(self):
    17. while True:
    18. batch = [await self._queue.get()]
    19. deadline = time.monotonic() + self.batch_window_ms / 1000
    20. # Keep collecting more requests before the window fills; dispatch immediately once it is full
    21. while len(batch) < self.max_batch and time.monotonic() < deadline:
    22. try:
    23. batch.append(await asyncio.wait_for(
    24. self._queue.get(), deadline - time.monotonic()))
    25. except asyncio.TimeoutError:
    26. break
    27. asyncio.create_task(self._dispatch(batch))
    28. async def _dispatch(self, batch):
    29. try:
    30. outputs = await self._forward([b["messages"] for b in batch])
    31. for item, out in zip(batch, outputs):
    32. if not item["fut"].done():
    33. item["fut"].set_result(out)
    34. except Exception as exc:
    35. for item in batch:
    36. if not item["fut"].done():
    37. item["fut"].set_exception(exc)

    Two practical lessons are worth emphasizing. First, the batch window is a tuning knob that trades throughput against latency: a larger window raises throughput but worsens TTFT; for real-time conversational traffic, the window should stay at the millisecond level. Second, the greater the difference in input and output lengths among requests in a batch, the worse the waste—when one request is still generating at 800 tokens, other requests in the same batch may have finished long ago, and their memory is held for nothing. So production practice often uses continuous batching: a request exits the batch as soon as it finishes generating, and new requests can join at any time, rather than waiting for all requests in a batch to complete.

    2.2 Prefix Reuse and Result Caching

    Many requests share the same prefix, such as the same system prompt, the same retrieval template, or the same product documentation. The compute results of such prefixes can be reused:

    • Prefix caching: reuse the key-value cache of common prefixes to avoid repeated prefill;
    • Result caching: return historical results directly for identical requests, but the key must be designed carefully (normalize whitespace and case, strip non-semantic fields like timestamps) with a reasonable TTL;
    • Semantic caching: map similar questions to existing answers; high reward but also high risk of false hits, so it is only suitable for scenarios with high fault tolerance.

    2.3 Trade-offs Among Quantization, Distillation, and Speculative Decoding

    Common inference-side acceleration techniques include weight quantization (reducing memory footprint and memory-access overhead), distilling smaller models (trading for lower latency), and speculative decoding (using a small draft model to guess multiple tokens, then verifying them all at once with the large model). These techniques share one trait: trading controllable quality loss for throughput:

    • For precision-sensitive tasks involving numbers, code, and compliance judgments, run offline evaluation before going live;
    • Quantization-induced precision loss often concentrates on long-tail inputs, so the evaluation set must cover boundary samples, not just average scores;
    • Speculative decoding shows clear gains in scenarios with highly predictable output and limited gains in scenarios that require long chains of reasoning.

    Part 3: Elasticity and Stability—Make Uncontrollable Load Controllable

    3.1 Peak Shaving, Rate Limiting, and Asynchronization

    The latency tail of generative requests is extremely long; synchronously absorbing peaks is a main source of stability incidents. A more robust approach is to bear load in layers:

    • Ingress rate limiting: set quotas separately by tenant, API key, and scenario, to prevent a single caller from monopolizing all capacity;
    • Queue-based peak shaving: turn non-real-time tasks (batch summarization, offline report generation, document parsing) into asynchronous jobs, buffered by a queue and consumed at a steady rate;
    • Object storage for artifacts: large text and file inputs/outputs should not go directly through the request/response body but be landed as object references first, with the request carrying only the path, reducing transfer and retry costs;
    • Container-platform elastic scaling: use queueing latency and GPU utilization as scaling signals, which is closer to the characteristics of inference load than CPU metrics alone.
    1. import asyncio, random, time
    2. class TokenBucket:
    3. """Token-bucket rate limiter: allows short bursts, with the long-term rate constrained by rate."""
    4. def __init__(self, rate: float, capacity: float):
    5. self.rate, self.capacity = rate, capacity
    6. self.tokens, self.last = capacity, time.monotonic()
    7. self._lock = asyncio.Lock()
    8. async def acquire(self, need: float = 1.0):
    9. async with self._lock:
    10. now = time.monotonic()
    11. self.tokens = min(self.capacity,
    12. self.tokens + (now - self.last) * self.rate)
    13. self.last = now
    14. if self.tokens < need:
    15. await asyncio.sleep((need - self.tokens) / self.rate)
    16. self.tokens = 0.0
    17. RETRYABLE = {429, 502, 503, 504}
    18. async def call_with_retry(fn, *, attempts: int = 3, base: float = 0.2, cap: float = 2.0):
    19. for i in range(attempts):
    20. try:
    21. return await fn()
    22. except Exception as exc:
    23. status = getattr(exc, "status", None)
    24. if status not in RETRYABLE or i == attempts - 1:
    25. raise
    26. # Exponential backoff plus random jitter, to avoid a retry storm hitting the backend all at once
    27. await asyncio.sleep(min(cap, base * 2 ** i) * (0.5 + random.random() / 2))

    3.2 Timeout Budgets and Cascading Degradation

    LLM call chains usually have multiple hops (gateway → orchestration layer → retrieval → inference), and each hop needs an explicit timeout budget; otherwise a single slow point can cause the whole chain to avalanche. The basic principle is that the upstream budget should be larger than the sum of downstream budgets, with room left over for retries.

    Degradation should be designed as predictable multi-level strategies:

    1. When the primary model times out, switch to a lower-latency small model;
    2. If the small model also fails, degrade to a templated answer built from concatenated retrieval snippets;
    3. If everything is unavailable, return a clear failure message and a retry entry point, rather than an empty response.

    At the same time, idempotency design is needed: generative requests are naturally non-idempotent, so requests should carry a request ID before retry, and the server should deduplicate, to avoid duplicate billing and duplicate side effects.

    Part 4: Observability—From “It Runs” to “It’s Measurable”

    4.1 Unify Metric Definitions First

    Many teams hit the same problem in the early days of launching an LLM service: different parties disagree on the definition of “slow.” It is advisable to fix the definitions at the integration stage:

    • Does TTFT count from when the server receives the request, or from when the client sends it? The two can differ by hundreds of milliseconds for cross-region calls;
    • Is queueing latency included in TTFT? This must be stated explicitly;
    • How are failures categorized? Timeouts, content-safety blocks, and parameter-validation failures should be counted separately; lumping them together makes the error rate lose its guiding value.

    Beyond metrics, there must also be token-level metering: record input tokens, output tokens, model version, routing strategy, and time for each request. This data is simultaneously the basis for observability and cost accounting.

    1. def log_completion(req_id: str, *, ttft_ms: float, tpot_ms: float,
    2. in_tok: int, out_tok: int, tenant: str, route: str):
    3. log.info(json.dumps({
    4. "req_id": req_id, "tenant": tenant, "route": route,
    5. "ttft_ms": round(ttft_ms, 1), "tpot_ms": round(tpot_ms, 2),
    6. "in_tokens": in_tok, "out_tokens": out_tok,
    7. "cost_units": in_tok * PRICE_IN + out_tok * PRICE_OUT,
    8. }, ensure_ascii=False))

    Once these structured logs flow into a logging service, two things can be done: first, aggregate and analyze by tenant, scenario, and model dimensions; second, combine with monitoring and alerting to set threshold alerts for phenomena such as sudden TTFT P95 spikes, rising error rates, and abnormal period-over-period token consumption.

    4.2 The Troubleshooting Path from Trace to Profile

    Troubleshooting generative services relies more on distributed tracing than traditional services do. It is advisable to assign a global trace ID to each request, spanning the gateway, retrieval, inference, and post-processing, and record the time of key phases within the trace. When the P95 latency of a scenario rises, first look at the trace’s segmented timing to determine whether retrieval is slow, queuing is long, or generation is slow, then decide whether to dig deeper into phase-level data at the inference layer. This order avoids diving straight into low-level tuning while ignoring the real bottleneck.

    Part 5: Cost Governance—Give Every Token an Owner

    5.1 Build an Explainable Cost Accounting Model

    The cost structure of LLM services is relatively clear—mainly inference compute, storage, and network egress—but attribution is hard. A workable approach:

    • Aggregate costs along three dimensions—tenant + business scenario + model version—to form a drill-down cost report;
    • Set a token budget and an alert line for each scenario, notifying the business side in advance when approaching the threshold, rather than looking at the bill at month’s end;
    • Distinguish interactive traffic from offline batch traffic: the latter can use lower-priority, more idle compute resources at a significantly lower unit price, provided the business can accept longer latency.

    5.2 Use a Routing Strategy Instead of a “One-Size-Fits-All” Approach

    Requests differ greatly in difficulty. Routing simple requests to small models and complex requests to large models is the most direct cost-optimization lever:

    1. Rule-first: format conversion, classification, and extraction tasks should preferentially use lightweight models or a rule engine;
    2. Confidence routing: answer with a small model first, then escalate to a large model when confidence is below a threshold or a refusal is triggered;
    3. Length routing: extremely long-context requests go to model tiers with stronger long-context capability and different unit prices;
    4. Degradation fallback: during peak hours, automatically degrade non-critical scenarios to preserve the SLO of the core chain.
    1. async def route_and_call(request, router):
    2. # Rule layer first: structured tasks don't need an LLM
    3. if request.task_type in {"classify", "extract"}:
    4. return await router.call_light(request)
    5. # Long context goes to a long-window tier
    6. route = "long_ctx" if request.est_tokens > LONG_CTX_THRESHOLD else "standard"
    7. resp = await router.call(route, request)
    8. # Escalate to a stronger model when confidence is insufficient
    9. if resp.confidence < ESCALATE_THRESHOLD and request.allow_escalate:
    10. resp = await router.call("strong", request)
    11. return resp

    The benefit of a routing strategy depends on an accurate profile of requests, so the routing decisions themselves must be logged. Which route has a high hit rate, which escalates frequently, and how much quality improves after escalation should all be part of routine reviews; otherwise the strategy will drift and quietly fail over time.

    Part 6: The Regression Defense Line Between Quality and Cost

    The most common side effect of cost optimization is quality regression, often discovered only after launch. It is advisable to build a three-layer defense:

    • Offline evaluation set: built in layers by business scenario, covering typical samples, boundary samples, and adversarial samples; it must pass every time the model or parameters change;
    • Shadow traffic: run the new strategy in a side path first, compare it against production results, without affecting real users;
    • Canary and automatic rollback: ramp up gradually by traffic percentage, and automatically roll back once core metrics (error rate, TTFT P95, user adoption rate) cross a threshold.

    The choice of evaluation metrics is also critical. Generative outputs have no single correct answer, and a single similarity metric can easily distort; it usually needs to be combined with manual sampling reviews and business-side behavioral metrics (such as adoption rate, secondary-edit rate, and handoff-to-human rate) for a joint judgment.

    Part 7: Suggested Implementation Roadmap

    Phase Key Actions Deliverables
    Phase 1: Observability Unify metric definitions; integrate structured logging and distributed tracing Token-level metering report, core SLO dashboard
    Phase 2: Performance Dynamic batching, prefix and result caching, quantization evaluation Throughput and TTFT baseline comparison report
    Phase 3: Elasticity Layered rate limiting, queue-based peak shaving, multi-level degradation, idempotent retry Load-test report, failure-drill records
    Phase 4: Cost Tenant cost aggregation, budget alerts, model routing, offline batch processing Unit-token cost curve, routing-benefit review

    The phases need not proceed strictly serially. A more common path in practice is: build observability first, then talk about optimization. Without token-level metering and segmented-timing data, any performance or cost optimization can only be judged by experience; its gains are hard to verify and hard to sustain.

    Conclusion

    Scaling LLM services is essentially turning a one-off model capability into a service product that can be operated sustainably. On this path there is no single silver bullet; real competitiveness comes from the accumulation of engineering details: whether capacity planning thinks in tokens rather than QPS, whether the batching window matches the business’s latency requirements, whether the degradation chain has actually been drilled, and whether cost can be attributed to each tenant and scenario.

    It is worth emphasizing that the code in this article illustrates scheduling and governance ideas; production still needs to fill in concurrency control, exception handling, and load-test validation against the specific tech stack. Likewise, specific performance and cost gains must be derived from measured data on your own business; any “universal optimization conclusion” divorced from the scenario is not to be trusted.

    At the resource level, general-purpose cloud product categories are enough to cover most of the above needs: container platforms carry elastic scaling of inference services, message queues handle peak shaving for offline tasks, object storage and cache services carry large artifacts and hot prefixes, and logging services with monitoring and alerting support token metering and SLO dashboards. Baidu AI Cloud offers exactly this kind of general-purpose cloud capability; teams can select on demand against their existing tech stack and focus their energy on business logic and service quality itself, rather than rebuilding infrastructure.

    The heat of funding and IPO news will eventually recede. Whether you can stably deliver low-cost, low-latency, explainable intelligent services is the variable that determines long-run results.