Cost Logic of LLM Inference Pricing and Self-Deployment Practices
This article explores the cost structure behind large language model (LLM) inference pricing, how to estimate the cost baseline for usage quotas, and why self-deployment can reduce unit costs. It also covers evaluating usage data, designing for stability with multi-backend routing, and engineering best practices for deployment.
I. Understanding LLM Pricing from Inference Costs
The price of LLM services is not determined solely by market demand. Each inference request consumes GPU memory, compute, memory bandwidth, and power. The costs of these resources vary with model size, context length, and concurrency. Therefore, to understand pricing strategies, one must first understand the cost structure per token.
Unit cost can be approximated by the following formula:
Unit token cost = Cost per card per hour ÷ Effective number of output tokens per card per hour
The effective number of output tokens depends on batching efficiency, request length distribution, memory usage, and model architecture. If a single card handles requests with vastly varying lengths, batching efficiency drops, and the unit cost rises.
There are typically three relationships between pricing and cost:
- Pricing is higher than cost: The service provider earns a gross margin to cover R&D and operations.
- Pricing is close to cost: The provider trades volume or user retention for long-term revenue.
- Pricing is lower than cost: Usually a phased subsidy, aimed at acquiring early users, testing market response, or driving new feature adoption.
Determining which category a pricing strategy falls into requires a comprehensive analysis of public quota limits, limited-time policies, and resource utilization rates.
II. Estimating the Cost Baseline for Quotas
For monthly subscriptions or usage based on issued quotas, a break-even estimation can be performed. The logic is straightforward: the quota limit multiplied by the unit cost equals the maximum cost the provider might bear under that quota. If users rarely max out their quotas, the actual cost remains below this ceiling. If a large number of users max out simultaneously, the cost approaches the ceiling.
Example code:
def max_cost_per_user(quota_tokens_m, unit_cost_per_m_tokens, utilization):"""quota_tokens_m: The number of tokens corresponding to the user quota (in millions)unit_cost_per_m_tokens: Unit cost per million tokensutilization: Average user quota utilization rate, ranging from 0 to 1"""expected_tokens_m = quota_tokens_m * utilizationreturn expected_tokens_m * unit_cost_per_m_tokens
This type of estimation only provides an order of magnitude. The actual cost must also account for retries after failed requests, cache hit rates, cold start latency, and idle resources. Estimation results should be calibrated against actual monitoring data.
III. Why Self-Deployed Inference Can Lower Unit Costs
Self-deployment means running the model on owned or rented compute resources rather than forwarding requests to the model provider’s API. The primary sources of cost reduction include:
- Batching and Continuous Batching
Inference services can merge multiple requests for computation, keeping the GPU at a high load. Continuous batching allows requests to enter or leave a batch at different times, reducing queue wait times.
- KV Cache Reuse
For requests sharing a common prefix, such as identical system prompts, the pre-computed Key-Value (KV) cache can be reused, reducing redundant computation.
- Quantization and Operator Optimization
Reducing the numerical precision of weights or activations decreases memory usage and increases throughput. Operator fusion and kernel optimizations tailored to specific hardware also reduce memory access overhead.
- Parallelism Strategies
Depending on the model size, tensor parallelism, pipeline parallelism, or data parallelism can be selected to enable multiple cards to work collaboratively. Improper parallelism strategies can incur communication overheads that offset the gains.
Self-deployment is not inherently cheaper. It requires the team to bear the personnel costs of operations, autoscaling, version upgrades, and troubleshooting. When traffic is low or highly volatile, on-demand API calls are usually more economical.
When using a model via a forwarding API, requests pass through an additional gateway or proxy layer, slightly increasing latency, but the service provider gains more flexible billing and routing control. The choice between the two approaches should be based on traffic volume, latency requirements, and team capabilities.
IV. Usage Data: Looking Beyond a Single Metric
Public leaderboards or usage dashboards can be easily misinterpreted. A model’s usage ranking is influenced by the following factors:
- User base size and promotional efforts
- Support for input modalities (e.g., image or audio)
- Pricing barriers and quota distribution methods
- Degree of toolchain integration
- Service stability and response speed
Therefore, to evaluate the performance of a model or service, it is recommended to monitor at least the following metrics:
- Request success rate and error type distribution
- Time to first token and overall generation speed
- Weekly retention and daily active users (DAU)
- Average tokens consumed per user
- Evaluation scores on specific internal tasks
When a metric fluctuates significantly in the short term, first rule out the impact of changes in statistical methodology, traffic volatility, and promotional events before judging the trend.
V. Stability Design: From Single-Point Dependency to Multi-Backend Routing
Relying on a single inference backend is a common cause of service outages. This is especially true for self-deployed services, where common failures include:
- Out of Memory (OOM) errors, often seen with extremely long contexts or sudden large batches
- Changes in output behavior after a model version upgrade
- Excessive cold start latency
- Upstream rate limiting or quota exhaustion
- Request timeouts due to network jitter
To address these issues, the following mechanisms can be adopted:
Health Checks: Periodically send probe requests to confirm the model returns results normally and log the latency.
Circuit Breaking: Temporarily stop routing requests to a backend when its error rate exceeds a threshold, waiting for it to recover.
Degradation: Switch to a slightly less capable but more stable backup model when the primary model is unavailable, and label the actual model used in the response.
Multi-Model Routing: Distribute requests to appropriate models based on task type and capability requirements.
Example code:
import timeclass Backend:def __init__(self, name, call_fn, failure_threshold=5, cooldown=60):self.name = nameself.call_fn = call_fnself.failure_threshold = failure_thresholdself.cooldown = cooldownself.failures = 0self.open_until = 0.0def available(self):return time.time() >= self.open_untildef record_success(self):self.failures = 0def record_failure(self):self.failures += 1if self.failures >= self.failure_threshold:self.open_until = time.time() + self.cooldownself.failures = 0def route_request(prompt, backends):"""Backends are sorted by priority, trying available backends in order."""for backend in backends:if not backend.available():continuetry:result = backend.call_fn(prompt)backend.record_success()return backend.name, resultexcept Exception:backend.record_failure()raise RuntimeError("All backends are unavailable")
Once the primary backend’s consecutive failures reach the threshold, it enters a cooldown period, and requests automatically redirect to the next backend. In actual deployment, timeout control, request logging, and alerting should also be included.
VI. Engineering Implementation Recommendations
- Establish a Cost Dashboard
Track and analyze costs by model, project, and user group.
