How Developers Can Plan LLM API Costs When Free Quotas Are Limited
This guide explains why free quotas for large language model services get restricted and which limits cause common errors. It covers the main billing models, practical ways to reduce token usage, a basic design for a local chat client that keeps API keys on the server side, exponential backoff for rate limits, and usage monitoring with budget alerts.
1. Why Free Quotas Get Tightened
Free quotas are resources that providers use for trials and user acquisition. Model inference consumes compute, and when resources are limited, providers must apply rate limits to keep the service stable overall. As a result, common problems such as sudden slowdowns, “usage limit reached” messages, and failed requests during peak hours usually come from one of the following limits:
- Request rate limit: The number of requests allowed per unit of time, commonly called RPM (Requests Per Minute).
- Token usage limit: The total number of tokens that can be consumed per day or per month.
- Concurrency limit: The number of requests that one account can run at the same time.
- Context length limit: The maximum input and output length that a single request can carry.
Understanding these dimensions helps you identify the source of a problem. If errors occur frequently over a short period, a rate or concurrency limit is usually the trigger. Waiting or slowing down requests typically resolves it. If the service cannot be used for the entire billing cycle, the quota is exhausted, and you need to adjust your usage or choose a paid option.
2. Understanding Common Billing Models
LLM services generally use one of four billing models. Each suits different use cases.
| Billing model | How it works | Best suited for |
|---|---|---|
| Pay-as-you-go | Charged based on the input and output tokens actually consumed | Developers and businesses with fluctuating usage that need flexible scaling |
| Prepaid balance | Top up in advance, and each call deducts from the balance | Teams that call the API continuously and want to control per-request spending |
| Resource pack | Buy a fixed amount of quota in advance and use it within its validity period | Projects with relatively stable usage whose total volume can be estimated |
| Subscription | Pay monthly or yearly and use the service within the plan’s scope | Individual users or high-frequency interactive scenarios |
Before choosing a billing model, collect real usage data. Unit prices and plan rules change often, so check the official pricing pages and documentation of the provider. This article does not list specific prices.
Cost estimation depends on token count. Different tokenizers split Chinese text differently, so you cannot calculate costs directly from character counts. A more reliable method is to read the usage fields returned by the API and calculate costs from the unit prices. The example below shows the estimation logic. The prices are placeholders and should be replaced with actual prices.
def estimate_cost(input_tokens: int, output_tokens: int,price_in_per_million: float, price_out_per_million: float) -> float:"""Estimate the cost of a single call from input and output token counts and the price per million tokens."""cost_in = input_tokens / 1_000_000 * price_in_per_millioncost_out = output_tokens / 1_000_000 * price_out_per_millionreturn cost_in + cost_out# Placeholder prices, for demonstration onlyprint(estimate_cost(input_tokens=1200, output_tokens=800,price_in_per_million=1.0, price_out_per_million=2.0))
3. Reducing Costs Through Usage
The first step is to reduce wasted tokens. Many chat applications send the entire message history to the model with every request, so the longer the history, the larger each input. Common optimizations include the following.
1. Truncate Conversation History
Keep only the most recent turns, and always keep the system instructions. This controls input length while the model can still understand the current context.
def trim_history(messages: list[dict], max_turns: int = 10) -> list[dict]:"""Keep system messages and only the most recent max_turns rounds of user and assistant messages."""system_msgs = [m for m in messages if m["role"] == "system"]dialog_msgs = [m for m in messages if m["role"] != "system"]return system_msgs + dialog_msgs[-max_turns * 2:]
2. Summarize Earlier Conversation
When a long conversation needs to retain key information, have the model compress the earlier content into a summary, and place that summary in a system message. A summary is usually much shorter than the original conversation, which significantly reduces input tokens.
3. Limit Output Length
Use the max_tokens parameter to cap the length of each reply. For tasks such as classification, extraction, and short Q&A, this setting directly lowers output costs.
4. Cache Repeated Requests
When the same question appears repeatedly within a short time, cache the result. The cache key should be determined by the model name, the parameters, and the complete input together. This prevents requests with different parameters from returning incorrect results.
5. Choose Model Size by Task
Simple tasks do not need the most capable model. Assign tasks such as classification and format conversion to smaller models, and reserve larger models for complex reasoning. This tiered approach usually reduces total cost significantly while keeping quality acceptable.
4. Designing a Local Chat Client
Some users want to save conversation records locally or use the same interface across devices. A lightweight client can meet this need. It usually has three parts: a frontend page, local storage, and a backend proxy.
Browser page -> Local backend proxy -> Model service API| |Local history Reads the key fromstorage environment variables
API Key Management Comes First
Accessing a model service requires an API key. If the key is written into frontend code or shipped with the page, anyone who can access the page files may read and misuse it, which can cause unexpected charges. Follow these practices:
- Store keys in environment variables or a secrets management service, not in source code or logs.
- Let the frontend communicate only with your own backend. The backend attaches the key before forwarding requests.
- Set usage limits on keys and rotate them regularly.
The following example reads the key from an environment variable and calls the API. The endpoint is a placeholder. Replace it with the address in the relevant API documentation.
import osimport requestsAPI_URL = "https://api.example.com/v1/chat/completions"API_KEY = os.environ["LLM_API_KEY"] # Read from an environment variable, never hardcode itdef chat(messages: list[dict], model: str) -> dict:headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}payload = {"model": model, "messages": messages, "max_tokens": 512}resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)resp.raise_for_status()return resp.json()
Storing, Importing, and Exporting Local History
Conversation history can be saved as a structured file, such as JSON. Each record contains a session ID, a timestamp, a role, and content, which makes retrieval and migration easier. When exporting, filter out keys and other sensitive fields so that credentials are not saved along with the conversation.
import jsonfrom datetime import datetime, timezonedef save_session(path: str, session_id: str, messages: list[dict]) -> None:record = {"session_id": session_id,"saved_at": datetime.now(timezone.utc).isoformat(),"messages": messages, # Store only conversation content, no keys}with open(path, "w", encoding="utf-8") as f:json.dump(record, f, ensure_ascii=False, indent=2)
5. Handling Rate Limits and Retries
For rate-limit responses such as 429, the most common strategy is exponential backoff. After each failure, the wait time doubles up to a set cap. This prevents piled-up requests from adding to the congestion.
import timefrom typing import Callableimport requestsdef call_with_backoff(send: Callable[[], requests.Response],max_retries: int = 5) -> requests.Response:for attempt in range(max_retries):resp = send()if resp.status_code != 429:return respwait_seconds = min(2 ** attempt, 30)time.sleep(wait_seconds)raise RuntimeError("Requests are still being rate limited. Maximum retry attempts reached.")
Retry logic needs attention to two points. First, retry only on rate limits, timeouts, and temporary server errors. Report parameter errors, authentication failures, and similar problems immediately instead of sending the request again. Second, if the provider includes a suggested wait time in the response headers, use that value first.
6. Usage Monitoring and Budget Alerts
Usage that is not monitored often goes unnoticed until the end of the month. Record the following information for every call:
| Metric | Purpose |
|---|---|
| Input and output token counts | Calculate costs and analyze the share of long-context requests |
| Request latency | Detect abnormal delays |
| Error code distribution | Identify rate limits, authentication failures, and other issues |
| Model name | Compare the cost and performance of different models |
| User or feature module | Locate high-consumption business processes |
Log only statistical data, not full sensitive conversation content. Budget alerts should use multiple thresholds. For example, send notifications at 50%, 80%, and 100% of the monthly budget so there is time to make adjustments.
from collections import defaultdictdaily_usage = defaultdict(int) # Cumulative token count per datedef record_usage(date_key: str, total_tokens: int, daily_limit: int) -> None:daily_usage[date_key] += total_tokensratio = daily_usage[date_key] / daily_limitif ratio >= 0.8:print(f"[Alert] Usage on {date_key} has reached {ratio:.0%} of the daily limit. Check the request sources.")
7. Deciding Whether to Change the Billing Model
Decide whether to switch to a paid option based on actual data, not on frustration or a single experience. Consider these questions:
- Over the past month, have weekly call volumes and token consumption been stable?
- Which features account for most of the high-frequency usage? Can history truncation or caching reduce their consumption?
- Which is lower: your current costs, or the estimated cost under a paid plan?
- Have your requirements for response speed and availability exceeded what the free plan can support?
If most answers point to stable, high-frequency usage, a fixed-period pl
