Five Technical Foundations for Enterprise LLM API Platforms
This article covers five technical foundations for building production LLM API platforms: metering and billing, multi-tenant rate limiting, cost optimization, capacity and SLA management, and billing reliability. It explains token-based billing formulas, atomic request and token bucket limiting, model routing and caching strategies, capacity planning, TTFT alerting, graceful degradation, idempotency, reconciliation, and a launch checklist.
Introduction: What an Enterprise LLM API Platform Must Deliver
When an enterprise exposes large model capabilities as APIs, the platform engineering team is not delivering a single model endpoint. It is delivering a production system that must be measurable, isolated, optimizable, scalable, and reconcilable.
Common mistakes include:
- Focusing only on model quality while ignoring token billing semantics.
- Limiting requests per minute without protecting against long-context traffic spikes.
- Optimizing routing only for cost without setting capability and latency safeguards.
- Planning capacity based on experience instead of load testing and watermark management.
- Reviewing billing only at the aggregate level without idempotence and reconciliation.
Teams often search for terms such as “how are LLM API charges calculated,” “how to implement multi-tenant rate limiting,” “how token billing works,” and “how to maintain SLA for LLM API platforms.” In practice, they need to build five technical foundations:
- Metering and billing
- Multi-tenant rate limiting
- Cost optimization
- Capacity and SLA management
- Billing reliability
The sections below provide practical implementations for these five modules.
1. Metering and Billing: Every Invoice Must Be Verifiable
The billing anchor for LLM APIs is the token. Input tokens, cached input tokens, and output tokens are usually priced separately. The unit price can also be affected by model tier, context length, cache hits, batch discounts, and tiered pricing.
Before launch, the platform must define the billing formula and document the formula, price version, currency, pricing unit, and rounding rules in both technical documentation and customer-facing billing explanations.
A recommended approach is to define “display billing tokens” and “amount” separately:
display_billing_tokens = (input_tokens - cached_input_tokens) + output_tokensbilling_amount = (input_tokens - cached_input_tokens) * input_price+ cached_input_tokens * cached_price+ output_tokens * output_price
Where:
input_tokens: total number of original input tokens.cached_input_tokens: number of input tokens that hit the cache; it must satisfy0 <= cached_input_tokens <= input_tokens.output_tokens: actual number of tokens generated by the model.input_price: unit price for input tokens that do not hit the cache.cached_price: unit price for input tokens that hit the cache.output_price: unit price for output tokens.- Pricing units must be consistent, such as “CNY per million tokens” or “USD per thousand tokens,” and the invoice must show the currency, pricing unit, and rounding rule.
It is important to emphasize that display_billing_tokens is only for usage display or trend analysis. It cannot be multiplied by a single unit price to calculate the final amount. The final amount must be calculated according to the billing tiers, with clear rules for the minimum billing unit, rounding strategy, free quota, taxes, and refunds.
For example, if tiered pricing exists, the amount should be calculated as follows:
billing_amount = Σ(usage in each tier × unit price for that tier)
Example: assume the currency is CNY and all unit prices are “CNY per million tokens”:
input_price = 2cached_price = 0.5output_price = 6
For a request where:
input_tokens = 1840cached_input_tokens = 1200output_tokens = 356
First calculate the display billing tokens:
display_billing_tokens = (1840 - 1200) + 356 = 996
Then calculate the amount:
billing_amount = (640 * 2 + 1200 * 0.5 + 356 * 6) / 1000000= (1280 + 600 + 2136) / 1000000= 0.004016 CNY
If the platform defines the minimum billing unit as 0.000001 CNY, keeps six decimal places, and uses round-half-up, the final invoice should show 0.004016 CNY. If the raw amount is 0.0040164 CNY, it should be recorded as 0.004016 CNY. If it is 0.0040165 CNY, it should be recorded as 0.004017 CNY.
From an engineering perspective, each request should generate a verifiable usage record containing fields such as:
request_idtenant_idapp_idmodelinput_tokenscached_input_tokensoutput_tokensdisplay_billing_tokensamountcurrencyprice_versionrounding_rulelatency_mscharged_at
The invoice should show cache-hit usage, non-cache-hit usage, the corresponding unit prices, discount amounts, free quota deductions, taxes, and refund information. This avoids situations where users cannot understand why the displayed usage does not match the charged amount.
2. Multi-Tenant Rate Limiting: Request Buckets and Token Buckets Must Be Deducted Atomically
How should multi-tenant rate limiting be implemented?
Limiting only RPM is not enough, because extremely long context requests can overwhelm the system. Limiting only TPM is also not enough, because it may not stop short-term traffic spikes.
Production-grade rate limiting must maintain both request buckets and token buckets:
- Request buckets control the number of calls.
- Token buckets control text throughput.
The capacity and rate of the two buckets should be configured separately. The “check and deduct” operation must be completed in the same critical section.
A single-process implementation can be written as follows:
import threadingimport timeclass Bucket:def __init__(self, capacity, rate):self.capacity = capacityself.rate = rateself.tokens = capacityself.updated = time.monotonic()def refill(self, now):self.tokens = min(self.capacity,self.tokens + (now - self.updated) * self.rate)self.updated = nowclass TenantLimiter:def __init__(self, rpm, tpm, est_tokens):self.req_buckets = {}self.tok_buckets = {}self.est_tokens = est_tokensself.rpm = rpmself.tpm = tpmself.lock = threading.Lock()def retry_after(self, bucket, amount):lack = max(0, amount - bucket.tokens)if bucket.rate <= 0:return 1return max(1, int(lack / bucket.rate) + 1)def check_and_deduct(self, tenant_id, est_tokens=None, now=None):now = now or time.monotonic()est_tokens = est_tokens or self.est_tokenswith self.lock:req = self.req_buckets.setdefault(tenant_id, Bucket(self.rpm * 2, self.rpm / 60))tok = self.tok_buckets.setdefault(tenant_id, Bucket(self.tpm * 2, self.tpm / 60))req.refill(now)tok.refill(now)if req.tokens < 1:return False, self.retry_after(req, 1)if tok.tokens < est_tokens:return False, self.retry_after(tok, est_tokens)req.tokens -= 1tok.tokens -= est_tokensreturn True, 0def finish(self, tenant_id, actual_tokens):with self.lock:tok = self.tok_buckets.get(tenant_id)if tok is None:returnrefund_tokens = max(0, self.est_tokens - actual_tokens)tok.tokens = min(tok.capacity, tok.tokens + refund_tokens)
Key point: the request bucket and token bucket must perform “check and deduct” within the same critical section. If the request bucket is deducted first and the token bucket deduction fails, the request bucket must be rolled back. Otherwise, request quotas may be incorrectly consumed.
The implementation above places refilling, checking, and deducting for both buckets inside the same lock, satisfying single-process atomicity.
The definitions of est_tokens and actual_tokens also need to be clear:
est_tokens: the estimated amount used for pre-deduction. It can be a conservative value based on “maximum input length + maximum output length,” or it can be estimated from the tenant’s historical P95 usage.actual_tokens: the sum of actual input tokens and actual output tokens after the request completes.- If
actual_tokensis less thanest_tokens, the difference should be refunded to the token bucket. - If
actual_tokensis greater thanest_tokens, the platform should not silently enlarge the token bucket. Instead, it should record the overage usage and route it into billing and risk-control processes.
Recommended overage records should include at least:
request_idtenant_idest_tokensactual_tokensoverage_tokensoverage_amountoverage_reasonrisk_statusreview_owner
Where:
overage_tokens = max(0, actual_tokens - est_tokens)
If the overage amount exceeds the tenant threshold, it should trigger alerts, manual review, or a risk-control queue. It should not be automatically allowed without any record.
In distributed production environments, a single-process lock is not enough. It is recommended to implement atomic rate limiting based on Redis Lua scripts or dedicated rate-limiting components.
Recommended key names:
llm:limit:{tenant_id}:rpmllm:limit:{tenant_id}:tpm
Each key can store the current token count, last refill timestamp, bucket capacity, and refill rate. If fixed-window counting is used, the TTL can be set to the window length. If a token bucket is used, the TTL can be set to twice the window length. For example, for a 60-second window, use a 120-second TTL to avoid abnormal keys remaining for too long.
For the time source, prefer Redis TIME or a unified server clock to avoid clock drift across multiple application instances.
In a Redis Lua script, both buckets should be read, refilled, and checked within the same script. If the request is allowed, both buckets should be deducted at the same time. If not, neither bucket should be deducted, and the script should return a suggested retry time.
When the gateway receives a rate-limiting result, it should return HTTP 429, a structured error code, and a Retry-After value. For example:
{"error": {"code": "RATE_LIMITED","message": "Token bucket exhausted","retry_after": 3}}
If the Redis call fails, the Lua script times out, or a network error occurs, the system must avoid partial deductions. Usually, it should return a retryable error to prevent clients from blindly retrying and amplifying the incident.
It is also recommended to classify tenants into categories:
- Reserved tenants: allocated dedicated capacity.
- Shared tenants: scheduled with weighted fair queuing.
- Trial tenants: configured with lower RPM, TPM, and shorter queues.
3. Cost Optimization: Routing, Caching, Context Management, and Batching
The goal of cost optimization is not simply to use the cheapest model. The goal is to choose the lowest feasible cost while meeting quality, latency, and security requirements.
Model routing should follow the principle of “capability first, latency as a safeguard, and cost optimization second”:
def route(task, latency_headroom=0.3):# latency_headroom: the fraction of the end-to-end SLO allocated to TTFT.ttft_budget = task.latency_slo * latency_headroomfor model in model_registry.order_by_cost():if model.capability.meets(task.required_capability) \and model.p95_ttft <= ttft_budget:return modelfallback = model_registry.fallback()if fallback and fallback.capability.meets(task.min_capability):return fallbackraise NoAvailableModel("no model meets capability and latency budget")
The following fields need to be clearly defined:
model.capability: model capability attributes, which may include reasoning level, tool-calling capability, context window, multimodal capability, and security compliance labels.task.required_capability: the hard capability requirement for the task.task.min_capability: the minimum capability allowed when fallback is triggered.model.p95_ttft: the P95 time-to-first-token latency of the model in the target region and hardware configuration.task.latency_slo: the end-to-end latency target.latency_headroom: the fraction of the latency budget allocated to TTFT. Its unit must match the latency unit, usually seconds.
Fallback should not mean “arbitrary degradation.” Fallback should be triggered when:
- No model meets the required capability.
- All candidate models exceed the latency budget.
- The primary model has a regional outage.
- Real-time capacity is insufficient.
If the task involves high-risk content or mandatory capability requirements, the system should not silently degrade. It should return an explicit error.
Routing rules should be configurable, support canary rollout, and be rollback-friendly. A recommended approach is to start with a 1% traffic canary and monitor:
- Request error rate
- TTFT P95
- Task escalation rate
- Model fallback rate
- Offline evaluation set pass rate
- Cost per request
Automatic rollback should be triggered if:
- The error rate exceeds the baseline by more than 1 percentage point.
- TTFT P95 increases by more than 20%.
- The offline evaluation pass rate falls below the threshold.
Caching is an important cost lever. Exact caching is suitable for identical requests. Semantic caching is suitable for similar questions, but similarity thresholds must be set carefully. Prefix caching is suitable for long system prompts and fixed context.
Whether caching is worthwhile can be estimated as follows:
cache_benefit = hit_rate * cost_per_inferencecache_cost = storage_cost + vector_retrieval_cost + cache_invalidation_cost
To make the formula verifiable, the following measurement definitions are needed:
- Hit rate: calculated over a rolling 24-hour or 7-day window, segmented by tenant, model, and cache type.
- Cost per inference: includes GPU compute cost, token pricing cost, queueing cost, and network transfer cost.
- Vector retrieval cost: based on the number of vector retrievals per query, index storage cost, and latency cost.
- Cache invalidation cost: includes expiration deletion, dirty-data recomputation, and the cost of falling back to the model when hit rate drops sharply.
Cache strategies should be expanded only when the cache benefit is greater than the cache cost.
Context management includes retrieval augmentation, historical summarization, context compression, and tool-call trimming. Many cost problems are not caused by expensive models, but by placing unnecessary history into the context.
Batching should be used for offline tasks, summarization jobs, and batch annotation tasks. These can be scheduled during off-peak periods to improve accelerator utilization while avoiding impact on online real-time SLAs.
4. Capacity and SLA: Turning Compute Commitments into Deliverable Capacity
Capacity planning should not rely on guesswork. A capacity ledger is recommended, maintained by region, model, and hardware type:
required_capacity = peak_qps * average_tokens_per_request * safety_marginavailable_capacity = Σ(accelerator_count * sustainable_throughput_per_accelerator * availability)utilization = required_capacity / available_capacity
Capacity inputs must be verifiable.
Sources for peak QPS should include:
- Historical 7-day P95 peaks
- Business growth forecasts
- Marketing campaign estimates
- Contingency plans for sudden traffic spikes
The average tokens per request should specify the measurement window. For example, it can use the P50 or weighted average from the last 7 days of APM logs, segmented into input tokens, output tokens, and cached input tokens.
The safety margin should be justified based on:
- Single availability-zone failure
- Batch processing efficiency loss
- Queueing delay
- Unexpected traffic spikes
- Model switching and fallback
Common values range from 1.2 to 1.5. If regional failover is required, a minimum of 1.3 is recommended.
Example: assume a region expects a peak of 100 QPS and an average of 3000 tokens per request.
100 QPS = 100 requests/second100 requests/second * 60 seconds = 6000 requests/minute6000 requests/minute * 3000 tokens/request = 18,000,000 tokens/minute
That is 18 million tokens per minute. With a safety margin of 1.3:
required_capacity = 18,000,000 * 1.3 = 23,400,000 tokens/minute
So the required capacity is 23.4 million tokens per minute. The platform should then calculate the required number of accelerators based on sustainable throughput per accelerator, model parallelism strategy, batching efficiency, and failover margin.
The capacity ledger should distinguish three types of resources:
- Locked capacity: resources committed to customers and not available for reallocation.
- Reserved tenant capacity: capacity reserved for major customers.
- Shared elastic pool: capacity used for unexpected traffic and unreserved tenants.
Load testing should cover more than a single model endpoint. It should cover the full path:
- Gateway
- Queueing
- Scheduling
- Inference
- Token streaming
- Billing telemetry
Load test parameters should include at least:
- Concurrent users
- QPS
- Input length P50/P95
- Maximum output length
- Cache hit rate
- Accelerator type
- Batch size
- Whether prefix caching is enabled
During load tests, the platform should record:
- CPU utilization
- GPU memory usage
- Queue length
- TTFT
- End-to-end P95/P99 latency
- Error rate
- Rate-limit rate
TTFT alerts must specify the applicable model, region, measurement method, and time window.
For example:
alert: HighTtftP95SmallFastModelRegionEastexpr: histogram_quantile(0.95, sum by (le, model, region, route) (rate(llm_ttft_seconds_bucket{model=~"small-fast.*", region="region-east", route="standard"}[5m]))) > 2for: 10mlabels:severity: P2model_class: small-fastmetric_unit: secondsannotations:summary: "region-east small-fast standard route P95 TTFT exceeds 2 seconds"measurement: "time from gateway receiving the request to the first SSE token; unit: seconds; aggregated over a 5-minute window; client network time excluded"scope: "applies only to small-parameter low-latency models; thresholds for large-parameter reasoning models can be set to 8 seconds; new regions or new accelerator types require separate calibration"
The 2-second threshold in this example applies only to small-parameter low-latency models in the region-east, using the standard route, measured at the gateway side. Large-parameter reasoning models, cross-region calls, long-context tasks, or new accelerator types need to be recalibrated.
Before launching a new model, it is recommended to replay the last 7 days of real traffic and set the initial threshold to 1.2 times the P95 baseline. The threshold can then be adjusted based on failure drills and capacity load tests.
The priority order for graceful degradation is recommended as follows:
- Reduce the maximum output length.
- Switch from high-cost models to low-cost models that still meet the minimum capability requirement.
- Enable caching or reduce cache refresh frequency.
- Delay non-core tool calls and background tasks.
Recovery conditions should also be defined. Advanced capabilities should be gradually restored only after:
- TTFT P95 falls below the threshold.
- Queue length falls below the safe watermark.
- Error rate returns to normal.
- GPU utilization drops back to a stable level.
5. Billing Reliability: Making Invoices Ready for Reconciliation
Billing reliability is more important than simply being able to bill. Once an invoice becomes unexplainable, it can lead to customer disputes, refund risk, and compliance risk.
The usage record should include at least:
request_id, tenant_id, app_id, model, input_tokens,cached_input_tokens, output_tokens, display_billing_tokens,amount, currency, price_version, rounding_rule,latency_ms, charged_at, status, idempotency_key
Idempotence must handle concurrent duplicate requests. It is recommended to use tenant_id + request_id as the unique key and enforce a unique constraint at the database layer.
If Redis is used for idempotence, use SETNX to write a processing state first:
idempotency:{tenant_id}:{request_id}
The TTL can be set between 10 minutes and 24 hours, depending on the longest request processing time and retry window.
After SETNX succeeds, the system enters the asynchronous billing flow:
- Write the usage event.
- Write the idempotency record.
- Update the billing ledger.
If a concurrent request finds that the idempotency key already exists, it should return the result of the first request or a “processing” status. It should not bill the request again.
Reconciliation should be implemented in two layers:
- Real-time reconciliation: compare gateway usage events with billing service records.
- Offline reconciliation: daily comparison between billing records and data warehouse aggregation results.
If the difference exceeds a threshold, such as 0.1% or a predefined amount threshold, an alert should be triggered.
Reconciliation failures should not only be logged. They should enter a retry queue. If retries still fail, they should enter a dead-letter queue for manual handling or compensation jobs.
Audit logs should be retained for at least 180 days. If customer contracts, financial regulations, or industry compliance require a longer period, the contract or regulation should take precedence.
Audit logs should be as tamper-proof as possible. They should record:
- Billing formula version
- Price version
- Discount policy version
- Invoice generation time
Changes to billing rules should go through an approval process. The process should clearly define:
- Responsible owner
- Approver
- Effective time
- Rollback plan
The invoice dispute process should also be productized:
- Customers can query details by
request_id. - They can view input usage, cached usage, output usage, unit price, and amount.
- Dispute tickets should be responded to within the promised time window.
- If an overcharge is confirmed, there should be a refund or credit process.
6. Launch Checklist
- Is the metering definition documented, including token definitions, cache-hit rules, pricing units, and rounding rules?
- Is it clear that
display_billing_tokenscannot be directly multiplied by a single unit price, and is the amount calculated using the tiered accumulation method? - Are the minimum billing unit, rounding examples, free quota, taxes, and refund rules defined?
- Are request buckets and token buckets separated, and do they support pre-deduction and refund?
- Is rate limiting atomic: locked in a single process, and using Redis Lua or an equivalent atomic mechanism in distributed environments?
- Does distributed rate limiting define key names, TTLs, time sources, HTTP 429,
Retry-After, and rollback behavior? - When
actual_tokensis greater thanest_tokens, are overage fields recorded and sent to billing and risk-control processes? - Does routing define capability fields, latency budgets, fallback trigger conditions, and minimum fallback capability?
- Does routing support canary rollout and rollback, and is there an offline evaluation set?
- Does caching account for the hit-rate measurement window, cost per inference, vector retrieval cost, and cache invalidation cost?
- Does the capacity ledger explain peak QPS sources, the measurement window for average tokens per request, and the basis for the safety margin?
- Does the capacity example complete unit conversion and remain traceable to load test and monitoring data?
- Does load testing cover the full path, and do its parameters include concurrency, input/output length, accelerator type, and cache hit rate?
- Do TTFT alerts clearly define metric units, applicable models, regions, time windows, and measurement methods?
- Is billing idempotent, and can it handle concurrent duplicate requests?
- Does Redis SETNX have a TTL, does the database have a unique constraint, and does the asynchronous billing flow guarantee ordering?
- Are real-time usage records reconciled with offline aggregation results, and do reconciliation failures trigger retries and a dead-letter queue?
- Can invoices be split by tenant, application, and model, and do they support detailed downloads?
- Are audit logs retained for an adequate period, and are billing formula versions, price versions, and discount versions traceable?
- Do billing changes have approval, owners, effective times, and rollback plans?
The core standard for a production-ready enterprise LLM API platform is to turn every API call into a measurable, isolated, governable, optimizable, and reconcilable service unit.
