Self-Hosted LLM Inference: A Practical Cost-Benefit Analysis
This article explains how to evaluate whether self-hosting LLM inference makes sense by building a cost model around device cost, effective throughput, and utilization. It covers unit-token cost, quota and pricing design, hardware selection, deployment architecture, batching, rate limiting, usage metering, billing, risks, and a pre-launch checklist.
1. Why More Teams Consider Self-Hosted Inference
Online discussions often describe deploying a model and earning a certain amount from it. Such experience reports are appealing, but most describe only the result. They rarely explain the cost structure, traffic sources, and risk boundaries. Treating isolated cases as general rules can easily lead to poor decisions.
Teams usually have three motivations for self-hosting inference:
- Cost control: When call volume is stable and large enough, amortizing cost by device time may be lower than per-call pricing.
- Data and compliance requirements: Business data cannot leave the internal network, or the service must meet specific audit requirements.
- Customizable capabilities: The team needs to adjust context length, output format, sampling strategy, or connect a private knowledge base.
Each motivation has preconditions. Self-hosting may be more economical than using an external service only when call volume is large enough, device utilization is high enough, and operations capability is strong enough. Therefore, the first step is not to look at someone else’s revenue number, but to build a cost model.
2. Start with the Numbers: Building a Revenue Model
The economics of any inference service can be broken down into three variables: device cost, effective throughput, and pricing strategy.
2.1 Unit Token Cost
Let the total hourly cost of a device be $C_h$, peak output throughput per card or per machine be $T$ (tokens/second), and average utilization be $U$ (between 0 and 1). The amortized cost per million output tokens is:
Device cost should include hardware depreciation, electricity, data center or cloud resource rent, bandwidth, and allocated labor for operations. Many calculations include only GPU rent and ignore operations and idle-time waste, which makes the result overly optimistic.
2.2 Utilization Is the Most Sensitive Variable
Utilization $U$ has the largest impact on the result. For the same device, raising utilization from 30% to 70% can more than halve the unit cost. Common ways to improve utilization include:
- Merging requests and using dynamic batching so multiple requests share one forward pass;
- Designing time-of-day pricing or reserved capacity to direct low-peak resources to asynchronous tasks;
- Co-deploying long-tail models so that one model does not monopolize an entire device.
2.3 Quota and Pricing Design
When providing a service externally, quotas and tiers are common operational tools. Typical approaches include:
- Free or low-quota trials: Lower the barrier for new users, but limit the maximum usage per user to prevent resources from being exhausted by a few accounts;
- Tiered quotas: Divide users by usage or payment amount, with higher tiers receiving higher rate limits or better unit prices;
- Prepaid and recharge: Lock in cash flow in advance while ensuring a clear relationship between quota and actual resources.
The core of tier design is to make revenue cover marginal cost and leave enough room for high-volume users to grow. If quota limits exceed actual available compute, the service will queue and time out, and user experience will deteriorate quickly.
3. Hardware and Runtime Environment Selection
Hardware selection should focus on three metrics: memory capacity, memory bandwidth, and multi-card interconnect capability.
- Memory capacity determines whether model weights and KV cache fit. Larger models require more memory and further limit concurrent requests.
- Memory bandwidth affects decoding speed. Most generation tasks are bottlenecked by repeatedly reading weights; higher bandwidth means faster generation per request.
- Interconnect capability determines the efficiency of multi-card partitioning. Cross-card communication latency and bandwidth directly affect the benefits of tensor parallelism.
For the hardware ecosystem, evaluate migration cost rather than simply comparing peak compute. Accelerator cards differ significantly in operator libraries, inference framework support, and compiler toolchain maturity. Choosing an unfamiliar software and hardware combination often consumes substantial engineering time during debugging before launch. It is advisable to validate model accuracy, latency, and throughput with a small-scale workload before deciding whether to scale up.
4. Key Parts of the Deployment Architecture
A usable inference service usually includes the following layers:
Client requests│▼Gateway layer (authentication, rate limiting, billing statistics)│▼Scheduling layer (queuing, batching, priority)│▼Inference engine (model loading, KV cache management, decoding)│▼Device layer (accelerators, memory, communication)
4.1 Model Optimization
Common optimization methods include quantization, KV cache reuse, and operator fusion. Quantization reduces precision but can significantly lower memory usage and bandwidth pressure. Before launch, run regression evaluations on target tasks to confirm that quality degradation is acceptable. Do not rely only on general benchmark scores; use business samples as the standard.
4.2 Batching and Continuous Scheduling
Continuous batching can dynamically adjust the batch as requests arrive and finish, preventing short requests from waiting behind long ones. This is one of the main ways to improve throughput. When implementing it, pay attention to the maximum batch size, maximum waiting time, and per-request token limit; these three need to be tuned together.
4.3 Rate Limiting and Fairness
A service without rate limiting can easily be overwhelmed by burst requests from a single user. A common approach is the token bucket algorithm, which allocates rates by user or key. A simplified implementation is shown below:
import timeclass TokenBucket:"""Token bucket: rate is tokens added per second, capacity is bucket capacity."""def __init__(self, rate: float, capacity: float):self.rate = rateself.capacity = capacityself.tokens = capacityself.updated_at = time.monotonic()def allow(self, cost: float) -> bool:now = time.monotonic()self.tokens = min(self.capacity, self.tokens + (now - self.updated_at) * self.rate)self.updated_at = nowif self.tokens >= cost:self.tokens -= costreturn Truereturn False
In actual deployment, cost should be estimated from the request’s input and output token counts rather than fixed at 1. Rate-limit values should be set based on load-test results, not by rule of thumb.
5. Billing and Usage Metering
The accuracy of the billing system directly affects cost accounting. At minimum, record the following fields: request time, user identifier, model version, input token count, output token count, time to first token, and total duration.
With this data, you can calculate the actual cost and revenue per user and identify the user groups that consume the most resources. If a small number of accounts consume most of the compute, the quota strategy needs to be re-evaluated.
The following is an example function for calculating unit gross margin. All parameters are passed in by the caller and do not depend on any specific price:
def gross_margin(price_per_1m: float, cost_per_1m: float) -> float:"""Gross margin = (price - cost) / price."""if price_per_1m <= 0:raise ValueError("Price must be greater than 0")return (price_per_1m - cost_per_1m) / price_per_1m
When gross margin is negative, scaling up only amplifies losses. Therefore, before any promotion, confirm that gross margin is positive and remains positive at the target utilization.
6. Risks and Boundaries
Self-hosted inference services mainly carry four types of risk.
Economic risk: Insufficient utilization, price competition, and sudden device failures can all compress profit. Use conservative utilization assumptions in calculations and keep a cost buffer.
Stability risk: Single-machine failures, incompatible driver versions, and memory fragmentation can all cause service interruptions. Health checks, automatic restarts, and multi-replica deployment are needed.
Compliance risk: If the service is provided externally, it must comply with data and content regulations, record necessary logs, and clearly define the boundaries for using user data.
Measurement risk: Revenue numbers circulating online often lack assumptions. For example, whether device depreciation is included, whether labor is counted, and whether long-term prepaid prices are used can significantly affect the conclusion. When reading such numbers, first map them back to the formula above, then judge whether they can be reproduced.
7. Launch Checklist
Before deciding to launch officially, confirm the following items in order:
- Define the target users and core scenarios, and estimate average daily requests and peak concurrency;
- Validate model quality with real samples and determine the quantization plan;
- Run load tests on the target hardware to obtain throughput, time to first token, and memory usage curves;
- Calculate unit token cost with the formula and perform sensitivity analysis under different utilization levels;
- Design rate limiting, tiers, and billing rules, and ensure revenue covers marginal cost;
- Set up monitoring and alerting covering device temperature, memory, queue length, and error rate;
- Complete compliance review and define data storage and log retention policies;
- Run a small-traffic canary for two to four weeks and calibrate the cost model with actual data.
8. Conclusion
Self-hosted inference is as much an operations effort as an engineering effort. Its return depends on utilization, cost structure, and service quality, not on a single number. As long as the cost model is clear, rate limiting and billing are solid, and risks are treated prudently, a team can determine whether self-hosting fits its business.
