LLM API Token Procurement: Evaluating Cost and Stability
LLM API costs are driven by token volume, input/output mix, and unit prices, but price alone is a poor procurement criterion. This article explains how to break down per-call token costs, account for hidden expenses, evaluate availability, latency percentiles, rate limits, and error distributions, mitigate peak-hour throttling, and assess access-channel risk. It also provides a selection checklist and engineering practices for abstraction, secret management, failover, monitoring, and regression testing.
1. Background
LLM APIs meter usage in tokens. Procurement cost depends on call volume, input/output structure, and unit price. Many teams focus only on unit price early on and overlook stability and compliance costs. When traffic reaches peak periods, failed requests and rising latency often cost far more to fix than the savings achieved earlier. Token procurement should therefore be evaluated using engineering metrics, not price tables alone.
2. Breaking Down Token Costs
2.1 Billing Units
Common billing models price input tokens and output tokens separately, and output tokens usually cost more. If a task produces verbose output, cost can rise significantly. When designing prompts, controlling output length is a direct way to reduce cost.
2.2 Estimating Per-Call Cost
Per-call cost can be calculated with the following formula:
Per-call cost = input tokens / 1,000,000 × input price + output tokens / 1,000,000 × output price
def estimate_cost(input_tokens: int, output_tokens: int,price_in: float, price_out: float) -> float:"""price_in and price_out are prices per million tokens; the currency is agreed by the buyer."""return (input_tokens / 1_000_000 * price_in+ output_tokens / 1_000_000 * price_out)
Multiplying average daily calls by per-call cost gives a baseline budget. Before launch, estimate using real business samples rather than idealized averages.
2.3 Hidden Costs
Beyond the visible bill, several cost categories are easy to overlook:
- Duplicate billing risk: Whether failed requests are billed depends on the specific service terms and should be confirmed against the contract or official documentation.
- Repeated long-context input: If multi-turn conversations include the full history every time, input tokens grow linearly with the number of turns.
- Engineering labor cost: Rate-limit handling, failover, and cost monitoring all require ongoing investment.
3. Stability: A More Important Metric Than Unit Price
In procurement evaluation, the following four metrics reveal service quality better than unit price:
- Availability: The monthly ratio of successful requests to total requests, with timeouts and explicit errors tracked separately.
- Latency percentiles: Focus on P95 and P99; averages hide the experience impact of long-tail requests.
- Rate-limit thresholds: Include requests per minute and tokens per minute; confirm both.
- Error-code distribution: The shares of 429 (too many requests), 5xx (server errors), and timeouts determine where response strategies should focus.
These four metrics often change most sharply during peak periods. Evaluation should cover different windows such as weekday peaks and weekends, rather than relying on a single test result.
4. Causes of Peak-Hour Rate Limiting and How to Respond
4.1 Common Causes
Rate limiting usually has three causes: shared quota on a channel is consumed by multiple users at once; concurrent connections reach a cap; or the application produces bursty traffic without smoothing.
4.2 Response Strategies
- Client-side rate limiting: Use token bucket or leaky bucket algorithms to control send rate and avoid instantaneous bursts.
- Exponential backoff with jitter: After a failure, increase wait time exponentially and add randomness so many requests do not retry at the same moment.
- Request queuing: Place non-real-time tasks in a queue and process them at the consumption rate.
- Model downgrade: For tasks with lower quality requirements, switch to a smaller, cheaper model.
Below is an example of retry with jitter:
import randomimport timeRETRYABLE_STATUS = {429, 500, 502, 503, 504}def call_with_backoff(send, max_retries: int = 5,base: float = 0.5, cap: float = 20.0):"""send is a function that issues the request and returns a response object with a status_code attribute."""for attempt in range(max_retries + 1):resp = send()if resp.status_code not in RETRYABLE_STATUS:return respif attempt == max_retries:breakdelay = min(cap, base * (2 ** attempt))time.sleep(random.uniform(0, delay)) # Full jitter to spread out retriesraise RuntimeError("Retries exhausted; check channel status or reduce concurrency")
Note that retries are only appropriate for idempotent or safely replayable requests. For operations with side effects, confirm the consequences of duplicate calls first.
5. Risk Layering for Access Channels
By access path, common options fall into four categories:
- Direct integration with the model provider’s official API: The path is shortest and the data boundary is clear, but pricing and quota terms may be less favorable for small teams.
- Cloud-hosted model services: These can reuse existing account systems, networking, and security policies, making them suitable for teams already deployed on that platform.
- Enterprise agreements or volume purchasing: Contracts define usage, price, and service levels, making this suitable for stable, large-volume scenarios.
- Third-party aggregation and forwarding services: Onboarding is simple and pricing is flexible, but they add an extra hop; the nodes data passes through and logging policies require close review.
When choosing a channel, verify the following questions:
- How many nodes does request data pass through? Do any nodes retain logs, and for how long?
- Can the model version behind responses be verified, for example, whether the response includes a model identifier that can be checked?
- Does the service-level agreement commit to availability in writing, and are outage compensation terms explicit?
- Are refund rules, billing definitions, and invoice information transparent?
For non-official channels, also run a consistency test: use a fixed test set to compare output quality and style across channels. If a channel’s price is far below market level, verify its cost source further, because a low price can mean risk is being shifted to the user.
6. Selection Checklist
| Dimension | Check question | Pass criteria |
|---|---|---|
| Availability | What was the monthly availability over the past three months? | Written data is available and meets business requirements |
| Rate limits | What are the requests-per-minute and tokens-per-minute limits? | Limits exceed business peak with headroom |
| Latency | Are P95 and P99 latency acceptable during peak hours? | Meets product experience targets |
| Data compliance | Is data retained, and if so, for how long and for what purpose? | Meets internal and industry compliance requirements |
| Model consistency | Can the returned model version be verified? | Test-set outputs match expectations |
| Billing transparency | Are failed requests billed, and are there price-change terms? | Terms are clear and traceable |
| Incident response | What are the notification timeline and handling process for incidents? | Clear response time commitments |
| Migration cost | How much code must change to switch to another channel? | Low-cost switching is possible through a unified call layer |
7. Engineering Implementation Recommendations
7.1 Abstract a Unified Call Layer
Business code should not depend directly on a specific channel’s endpoint and protocol. A unified call layer that encapsulates request formats, retries, and logging enables fast switching when a channel has issues.
7.2 Inject Secrets and Endpoints Through Environment Variables
import osLLM_ENDPOINT = os.environ["LLM_ENDPOINT"]LLM_API_KEY = os.environ["LLM_API_KEY"]
Secrets should not be written into code or logs. Inject them through environment variables or a secrets management service, and rotate them regularly.
7.3 Configure Primary and Backup Channels
For critical workloads, configure a primary channel and a backup channel, and switch automatically based on health check results. The switching policy should include a cooldown to prevent frequent flapping between channels.
7.4 Monitoring and Alerting
Continuously monitor the following metrics:
- Daily token usage and cost, split by business line
- Request success rate and the share of each error code
- P95 latency and queue length
Set alert thresholds for each metric and review cost and quality trends regularly.
7.5 Periodic Regression Evaluation
After a channel or model changes, output quality may drift. Build a fixed evaluation set, run it regularly, and record results to detect problems early.
Procurement decisions should be based on measurable metrics; unit price is only one input.
