Cost Optimization and Migration Guide for LLM APIs After Price Changes

    LLM API pricing changes can significantly affect your budget, especially when cache hit rates, output length, and billing periods are involved. This guide explains how to evaluate a price change using the "cost per successful task" metric, break down per-call billing formulas, schedule deferrable workloads into off-peak windows, and route tasks by complexity tier. It includes a Python cost estimation example, cache key design practices, and practical steps to decide whether to stay with your current provider or migrate.

    1. Do the Math Before Deciding Whether to Switch Providers

    LLM API pricing is typically determined by three dimensions: model tier, token type, and billing period. A price change may raise the unit price of only one token type, or adjust multiple dimensions at once. Treating a price change as “an overall X% increase” often leads to wrong conclusions.

    A price change affects teams in two main ways. First, the cost per request rises, so the same workload requires a larger budget. Second, the cost structure shifts. Businesses that rely heavily on caching, long contexts, or large outputs may be affected far more than others.

    When evaluating options, use a single metric: cost per successful task, defined as:

    Cost per successful task = Total spend in the measurement period ÷ Number of successfully completed tasks

    Total spend includes fees from failed and retried requests, while successful tasks only count those that pass quality acceptance. Looking only at unit price or per-call cost ignores the extra spend caused by failures and retries. For example, a provider with a lower unit price but a noticeably lower success rate may end up with a higher cost per successful task.

    2. Break Down the Billing Structure

    For pay-as-you-go model services, the cost of a single call can be written as:

    Cost per call = uncached input tokens × uncached input price + cache-hit input tokens × cache-hit price + output tokens × output price

    If the provider charges different rates by time period, apply the prices for the corresponding period in the same formula. The following code wraps the formula in an estimation function, with prices configured per period—after a provider price change, you only need to update the configuration.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_miss: float # Uncached input price, unit: currency per million tokens
    5. input_hit: float # Cache-hit input price, unit: currency per million tokens
    6. output: float # Output price, unit: currency per million tokens
    7. # Values are for demonstration only and do not represent actual quotes; replace with the provider's current price list.
    8. PRICING_BY_PERIOD = {
    9. "peak": Pricing(input_miss=2.0, input_hit=0.2, output=8.0),
    10. "valley": Pricing(input_miss=1.2, input_hit=0.12, output=5.0),
    11. }
    12. def estimate_cost(period: str, miss_tokens: int, hit_tokens: int, output_tokens: int) -> float:
    13. """Estimate the cost of a single call."""
    14. p = PRICING_BY_PERIOD[period]
    15. return (
    16. miss_tokens * p.input_miss
    17. + hit_tokens * p.input_hit
    18. + output_tokens * p.output
    19. ) / 1_000_000

    Here is a worked example using the demo prices. Suppose a call has 26,000 input tokens, an uncached input price of 2 per million tokens, and a cache-hit price of 0.2 per million tokens. Input costs at different cache hit rates (rounded to four decimal places):

    Cache hit rate Input cost
    0% 0.0520
    50% 0.0286
    80% 0.0146
    95% 0.0075

    For the 80% case: the uncached portion is 26,000 × 20% = 5,200 tokens, costing 5,200 × 2 ÷ 1,000,000 = 0.0104; the cached portion is 26,000 × 80% = 20,800 tokens, costing 20,800 × 0.2 ÷ 1,000,000 = 0.00416. Together that is 0.01456, or 0.015 rounded to three decimals.

    This example illustrates two points. First, cache hit rate has a large impact on input cost. Second, in most pay-as-you-go services, output tokens are priced higher than input tokens, though the exact ratio depends on your bill. At an output price of 8 per million tokens, 2,000 output tokens cost 0.016—already more than the input cost at an 80% hit rate. Controlling output length is therefore usually the most direct way to cut costs. Approaches include specifying the output format in the prompt, limiting the number of fields and their length, and removing unnecessary explanatory text.

    Note that some providers charge separately for cache writes or cache storage. When calculating savings, include these fees in the formula, or you will overstate the benefit of caching.

    3. Schedule Deferrable Tasks into Off-Peak Periods

    If your provider charges different rates by time period, the first step is to classify tasks as deferrable or non-deferrable.

    Deferrable tasks are those with no user waiting in real time, where results can be delivered later—for example, offline evaluations, batch summarization, data labeling, and report generation. Non-deferrable tasks are those where a user is waiting or that directly affect interactivity—for example, live customer support, real-time chat, and in-page instant generation. The test is simple: if a task is still valuable two hours later, it can be deferred.

    Recommended scheduling practices for deferrable tasks:

    1. Push tasks into a queue, recording the task type, deadline, and idempotency key.
    2. The scheduler releases tasks during low-price periods and caps concurrency per window to avoid rate-limit failures at scale.
    3. Set timeout thresholds and retry limits. Use exponential backoff for retries and reuse idempotency keys to prevent duplicate billing for the same task.
    4. If a task exceeds its deadline without completing, escalate to an alert and let a human decide whether to run it at the current period’s price.

    Here is an example using the demo prices. Assume each call has 26,000 uncached input tokens, an 80% cache hit rate, and 2,000 output tokens:

    Period Cost per call Cost for 1,000 calls
    Peak 0.0306 30.56
    Off-peak 0.0187 18.74

    For the same 1,000 calls, running them all off-peak brings the cost down from 30.56 to 18.74 at demo prices. Actual savings depend on the provider’s price list, period boundaries, and the proportion of deferrable tasks—calculate with your real bills.

    4. Cache Reuse and Tiered Task Routing

    Cache reuse starts with cache key design. A cache key should include the model name and version, a hash of the system prompt, the prompt template version, output-affecting parameters (such as temperature and maximum output length), and a hash of retrieved chunks. Hash user identifiers; never put plaintext personal information into cache keys.

    Cache effectiveness depends on the provider’s caching mechanism. Prefix caching requires the beginning of requests to be identical, so dynamic content in prompts should be placed at the end. Hit rules vary across providers—consult the official documentation and verify through testing.

    Monitor hit rates per business line, calculated as hit tokens ÷ total input tokens. If a business line’s hit rate stays low, check whether the prompt changes frequently or whether dynamic content sits in the prefix position.

    Caches need an invalidation strategy. Proactively clear relevant caches when templates change, model versions are upgraded, knowledge bases are updated, or caches exceed their validity period. For highly time-sensitive content, such as real-time prices or same-day news, do not use caching.

    Tiered task routing aims to run simple tasks on low-cost models and reserve premium models for complex ones. A common tiering scheme:

    • Tier 1: Tasks with clear rules, such as classification, extraction, and format conversion—use a low-cost small model.
    • Tier 2: Routine generation, summarization, and rewriting—use a mid-tier model.
    • Tier 3: Multi-step reasoning, complex code, and high-risk judgments—use a flagship model.

    Tiering criteria can include input length, business risk level, and historical quality scores. Validate tiering rules regularly with an evaluation set to prevent low-cost models from degrading quality on critical tasks.