Self-Hosted LLM Inference: Costs, Benefits, and Engineering Practices
Self-hosting large language model inference can reduce per-token costs, improve data control, and provide greater flexibility over model versions, latency, and throughput—but only when utilization is high enough to justify the operational overhead. This guide explains how to estimate unit costs, select hardware, configure inference frameworks, adapt services to heterogeneous accelerators, manage quotas, and evaluate whether self-hosting is the right deployment strategy.
1. Why Self-Host Inference?
When a team relies on a third-party API, costs are determined by the provider’s pricing and quota policies. As open-source models continue to approach the capabilities of commercial models, more organizations are considering self-hosted inference.
There are usually three main reasons:
- High-frequency usage can make usage-based API bills grow quickly.
- Business data may need to remain inside a private network.
- Teams may want direct control over model versions, latency, and throughput instead of being affected by changes to an external service.
Self-hosting is not automatically cheaper. It shifts the cost model from paying per token to paying for machine time. Whether it is financially worthwhile depends largely on whether the infrastructure can maintain a high utilization rate. When machines sit idle, the effective cost per token rises quickly.
The first step in deciding whether to self-host is therefore to calculate the unit cost accurately.
2. Start with the Unit Cost per Token
The unit cost of an inference service can be estimated with the following formula:
Unit cost = Hourly cost per machine ÷ (Effective throughput in tokens/second × 3,600)
“Effective throughput” means the actual number of tokens produced per second while meeting the target latency. It is usually much lower than the theoretical peak.
For example, assume that one node costs 40 yuan per hour and provides an effective output throughput of 2,000 tokens per second. The cost per one million output tokens is approximately:
40 ÷ (2,000 × 3,600) × 1,000,000 ≈ 5.6 yuan
This is only an example. In practice, you should substitute your own hardware pricing and benchmark results.
Two variables require particular attention:
- Effective throughput: This is affected by batch size, input and output length distributions, and concurrency. Long-context requests consume substantially more GPU memory and reduce the number of requests that can be processed simultaneously.
- Utilization: Idle periods during nights or off-peak hours are still included in the hourly infrastructure cost. If average utilization is only 20%, the unit cost is roughly five times higher than it would be at full utilization.
Before deployment, benchmark the service with traffic replay based on realistic workloads rather than estimating costs from theoretical peak performance.
3. Three Dimensions of Hardware Selection
When selecting an accelerator, teams typically focus on three factors.
GPU memory capacity determines how large a model can fit on a device. With common weight precisions, larger models require more memory. In addition to model weights, you must reserve memory for the KV cache, whose requirements grow linearly with concurrency and context length.
Memory bandwidth directly affects decoding speed. During autoregressive generation, the system must read a large amount of model weight data to generate each token, making memory bandwidth a frequent bottleneck.
Interconnect between devices determines the efficiency of multi-device parallelism. When a model cannot fit on a single device, tensor parallelism is required. At that point, communication latency between devices can become the performance limit.
Quantization is another common way to reduce costs. Compressing weights from higher precision to lower-bit formats can reduce memory usage and improve throughput, but it may also introduce some accuracy loss. Before production deployment, compare quantized and non-quantized versions on your own evaluation set rather than judging only by speed.
4. Inference Frameworks and Key Parameters
Mature inference frameworks generally provide several capabilities. Understanding them makes it easier to tune the service:
- Continuous batching: New requests are added dynamically at each decoding step instead of waiting for an entire batch to finish. This can significantly improve hardware utilization.
- KV-cache management: Paged memory management reduces fragmentation and supports higher concurrency.
- Prefix caching: Requests with the same system prompt or document prefix can reuse previously computed results. This is useful for applications with fixed templates.
- Tensor parallelism and pipeline parallelism: The model can be split across multiple devices to balance capacity and performance.
The following is a generic service configuration example. The parameter names are illustrative placeholders; consult the documentation for the selected framework for the actual field names:
serving:model_path: /models/base-model-int8tensor_parallel_size: 4max_num_seqs: 128 # Maximum number of requests processed concurrentlymax_model_len: 8192 # Maximum context length per requestgpu_memory_utilization: 0.90enable_prefix_caching: trueapi_format: chat-completions
A useful tuning principle is to define latency targets first—for example, time to first token and the interval between generated tokens—and then increase concurrency within those constraints.
Pursuing throughput without considering latency can severely worsen tail latency and ultimately degrade the user experience.
5. Adapting to Heterogeneous Accelerators
When a team uses a less common accelerator, hardware adaptation is often more complicated than expected. The main tasks include:
- Checking operator coverage: Verify that the core operators used by the inference framework are implemented on the target hardware. Missing operators may need to be replaced or implemented manually.
- Graph compilation and dynamic shapes: Some hardware platforms have limited support for dynamic input lengths. Bucketing or padding strategies may be necessary to reduce the number of compilation runs.
- Validating numerical consistency: The same model may produce numerically different outputs on different hardware platforms. Compare generated results and key metrics on a fixed evaluation set.
- Profiling performance: Use the hardware vendor’s profiling tools to identify bottlenecks and distinguish between compute, memory-access, and communication overhead.
After the adaptation is complete, maintain a regression test suite. Run it again whenever the driver, framework, or model version is updated.
6. Service Management and Quota Control
Once inference is available as a shared service, the next challenge is managing resources across users. A common approach is to implement rate limiting and usage accounting at the gateway layer, with quotas assigned by user or project.
The following is a simplified token-bucket example:
import timeclass TokenBucket:def __init__(self, rate_per_sec: float, capacity: int):self.rate = rate_per_sec # Tokens added per secondself.capacity = capacity # Maximum bucket capacityself.tokens = capacityself.last = time.monotonic()def allow(self, cost: int) -> bool:now = time.monotonic()self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)self.last = nowif self.tokens >= cost:self.tokens -= costreturn Truereturn False# Example: approximately 60,000 tokens per minute for each userbucket = TokenBucket(rate_per_sec=1000, capacity=60000)if not bucket.allow(cost=512):raise RuntimeError("Quota exceeded. Please try again later.")
In addition, the service should provide:
- Persistent usage records: Store the input and output token counts, request duration, and user identity for billing and cost analysis.
- Tiered quotas: Separate free, standard, and high-quota users to prevent a single user from consuming all available resources.
- Monitoring and alerting: Track queue time, error rate, memory usage, and throughput per device, and configure threshold-based alerts.
- Degradation strategies: During peak periods, prioritize critical workloads and queue non-critical requests or return clear rate-limit messages.
7. Objectively Evaluating Benefits and Risks
Self-hosting offers three primary benefits:
- At high utilization, the unit cost can be significantly lower than usage-based pricing.
- Keeping data inside the organization provides greater control over compliance risks.
- Teams can adjust model versions and inference parameters as needed.
The risks also need to be considered carefully.
First, infrastructure costs continue even when machines are idle. Teams with highly variable demand may lose money. Second, self-hosting requires personnel to manage deployment, monitoring, incident recovery, and model upgrades, creating significant hidden labor costs. Third, open-source models have different license terms, which must be reviewed individually before commercial use. Fourth, hardware procurement or rental involves supply and lead-time risks.
A practical strategy is hybrid deployment: use self-hosted infrastructure for baseline traffic and external APIs for peak demand or specialized capabilities. This approach controls fixed costs while preserving flexibility.
8. Pre-Deployment Decision Checklist
Before committing to a full production deployment, confirm the following:
- Are daily token volumes and peak concurrency supported by reliable historical data?
- What effective throughput was measured under the target latency requirements?
- Based on the expected utilization rate, is the unit cost lower than the current solution?
- Is there enough operations staff to provide 24/7 incident response?
- Have model licensing, data compliance, and audit requirements been evaluated?
- Is there a rollback plan that can restore the previous service if problems occur?
Self-hosting is worth pursuing only when these questions have reasonably clear answers. Otherwise, start with a small-scale pilot and use real traffic data to validate the assumptions. In many cases, this is the more practical approach.
