11B.1 Cost and Latency Optimization

ProductionLesson 1 of 811,843 words9 parts
Module 11B · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

Every LLM feature ships with two bills: the one your provider sends you, and the one your users experience as seconds of waiting. Both are engineering problems, not pricing-page problems — the same model at the same list price can cost you 10× more or less depending on how you call it, and feel 5× faster or slower depending on how you sequence the work around it. This lesson is the complete engineering reference for optimising both: the cost model (what actually goes into a request's price, including the costs that aren't tokens), the latency model (where the seconds go, from network to decode), a prioritised playbook of ten levers in the order they usually pay off, quality-aware optimisation so savings don't silently become regressions, latency engineering including hedged requests, token-denominated quotas and FinOps, the vendor pricing mechanics worth exploiting, and the build-vs-buy break-even for self-hosting. It builds on 03.7 (per-call accounting and the price table), 07.1 (the RAG request anatomy), 08A.2 (the agent loop) and 11A.1 (the traces this lesson analyses).

What you'll learn

  • The full cost model for an LLM feature: variable costs (tokens by type, media, tools), fixed costs (embeddings index, vector DB, observability, hosting, people) and the hidden multipliers that make bills surprise you (retries, truncation, fallbacks, reasoning tokens, compounding history)
  • The latency model: network, queueing, retrieval, guardrails, prefill, tool calls, decode and retries — and why TTFT and total time are different problems
  • How to measure before you optimise: baseline distributions from traces, and a waste-report script that reads the JSONL trace schema from 11A.1 and ranks what to fix first
  • The prioritised optimisation playbook: remove waste, caching, model tiering, reasoning budgets, batch/flex/async tiers, parallelism and streaming, speculative and early-exit patterns, retrieval sizing, regional endpoints and connection reuse, self-hosting at scale
  • Quality-aware optimisation: cost-quality frontiers, acceptable-regression budgets, eval gates and A/B tests — and the false savings that look like wins on a dashboard
  • Latency engineering: streaming UX, parallel tool calls, avoiding waterfalls, hedged requests with full code, timeouts and deadlines, and when a premium service tier is worth its price
  • Token budgets and quotas: per-request caps, per-tenant token quotas with reserve-then-settle, agent budgets, a short view of chargeback/showback (the full treatment is 11B.6), forecasting, and FinOps for AI
  • The vendor pricing mechanics to exploit — caching discounts, batch discounts, long-context tiers, regional and priority surcharges, free tiers, committed-use and enterprise agreements, and price-change monitoring — verified as of November 2026
  • Build-vs-buy: the API-vs-self-hosted break-even calculator, and the hidden costs both sides forget

What you don't need

  • API keys. Every sample runs on pure Python and standard library only — calculators, quota logic, a hedged-request demo with fake calls, and a waste report over trace files you generate yourself. Provider-facing facts are cited to official pages.
  • A running LLM service. llm_service/ files in this lesson are reference code for the module's running project; the pure-local parts run standalone.
  • Per-call cost accounting. 03.7 owns token counting, cost_calc.py, prices.yaml and the cost tracker — this lesson consumes its numbers and links to it constantly. Caching strategy is 11B.3; model selection and routing is 11B.5; eval methodology is Module 10A; security and privacy are Module 12.

Setup

The samples in this lesson are pure Python 3.11+ with the standard library — no packages, no keys, no services:

bash
uv init llm-service --bare --python 3.13 && cd llm-service

Save the three modules as llm_service/economics.py, llm_service/budget.py and llm_service/waste_report.py. economics.py is printed in three parts (1.5, 2.4, 7.5 and Part 9); budget.py is printed complete in 6.2 — its quota half is exercised in 7.2. Four tiny driver scripts (economics_demo.py in 1.5, hedge_demo.py in 6.2, quota_demo.py in 7.2, buildvsbuy_demo.py in 9.1) print every Output: block below; they sit next to the modules. The waste report reads the JSONL trace records defined in 11A.1, 2.6; 3.2 includes a fixture generator you can run to produce traces_fixture.jsonl.


What you must be able to do after this lesson#

  • Break the cost of an LLM feature into variable and fixed costs and spot the hidden multipliers
  • Break latency into its stages and tell which levers fix TTFT and which fix total time
  • Measure baseline cost and latency distributions and run the waste-report script before optimising
  • Apply the optimisation playbook in order and put every cost lever behind an eval gate
  • Implement a per-tenant token quota with reserve-then-settle
  • Decide when hedged requests are worth their cost
  • Compute the API versus self-hosted break-even

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Our bill tripled but request count only grew 20%." 1.3 The hidden multipliers
"Why does the agent cost ~15× the chatbot?" 1.6 Worked example: an agent run
"Users say it's slow but p50 latency looks fine." 2.4 Worked example: the latency budget and Part 6
"Can't we just use a cheaper model?" 4.3 Model tiering and Part 5
"Batch is half price — why not everything?" 4.5 Lever 5: batch, flex and async tiers
"Send a second request if the first is slow." 6.2 Hedged requests
"Give each tenant 1M tokens a day." 7.2 Token-denominated tenant quotas
"Should we self-host to save money?" Part 9: Build vs buy
"The eval score dropped but cost halved." Part 5: Quality-aware optimisation

Part 1: The cost model — where every dollar goes#

1.1 Two kinds of cost: variable and fixed#

An LLM feature's bill has two structurally different halves, and optimising them takes different skills:

Variable cost Fixed cost
What it is Everything priced per unit of usage: tokens, cache writes, media, tool calls, storage Everything priced per time or per unit of capacity: vector DB instance, observability platform seat, app servers, GPU rental, index builds, people's time
Scales with Requests × tokens per request Nothing — it arrives whether or not a user calls
Optimised by Prompt design, caching, model choice, batching, quotas Architecture choices, right-sizing, commit discounts, build-vs-buy
Where it surprises you Multipliers nobody modelled (retries, reasoning, history) The bill that stays after you "optimise" traffic to zero

The variable side is what 03.7 computes exactly per call: Usage normalised across providers, priced through prices.yaml, recorded by cost_tracker.py. This lesson does not redo that arithmetic — it asks the questions above it: what does one user request cost end to end, what does one feature cost per month, and which levers move which line.

1.2 The variable cost equation#

For one model call, the bill is a sum over token types — the full per-provider detail (cache read vs write rates, long-context tiers, regional uplifts, media and tool fees) is owned by 03.7, Part 3 and 02.9, Part 6. The structure:

text
cost(call) = uncached_input × p_in
           + cached_input   × p_cached        # usually a fraction of p_in
           + cache_writes   × p_write         # can exceed p_in
           + output         × p_out           # includes reasoning/thinking
           + media/tool fees                  # per image, per search, per GB-day

Three facts about this equation drive everything in the lesson:

  • Output is the expensive token. Output prices run 2–8× input prices across current frontier models (02.9, 6.2), and reasoning tokens bill as output even when invisible (02.8, 5.1). A feature that generates long answers on a reasoning model is output-dominated; a RAG feature that reads 20K tokens and answers in 200 is input-dominated. Your optimisation order depends on which side dominates your workload.
  • Cached input is a different price, not a discount coupon. Reads are cheap, writes can cost more than plain input, and on Gemini explicit caches you also pay storage per hour (02.9, 6.3). Whether caching pays is a break-even calculation, not a reflex — 03.7, Part 11 and 11B.3 own it.
  • The price you pay isn't always the price on the page. Service tiers (batch/flex/priority/fast), long-context surcharges, regional uplifts, gateway fees and introductory-price expiries all move the effective rate (Part 8).

1.3 The hidden multipliers#

The per-call equation above is what one successful call costs. Your monthly bill multiplies it by factors the formula doesn't show:

Multiplier Mechanism Where it's covered
Retries A retried call is billed again in full — input and output generated before the failure 03.8 owns retry policy; here it enters the cost model as an attempts factor
Truncation A reply cut off at max_tokens/max_output_tokens is paid for and usually re-asked: two bills for zero usable output 02.5, 4.6, 03.7, 12.1
Fallbacks A fallback to a bigger or different provider model bills at that model's rates; silent quality regressions are free but failures aren't 11C.3 owns the mechanism; the cost side is here
History compounding In chat, turn n re-sends turns 1…n−1: input grows ~quadratically with turns 02.7, Part 6, 04.7
Tool results Every tool result is re-billed as input on this call and every later call in the conversation 08A.2, 08A.8
Agent loops A 10-step agent run is ~10 model calls, each re-sending the accumulated history 08A.2, worked in 1.6
Reasoning effort Higher effort can multiply output tokens 5–25× on the same visible answer 02.8, 5.1
Hedged requests A hedge that wins still bills the loser 6.2
Server-side tools Web-search results fetched mid-call are billed as input on this turn and every later turn that carries them 08A.8, 3.3

1.4 Fixed costs: the bill that arrives anyway#

Token spend is the visible half. The invisible half is what you pay whether or not anyone calls:

Fixed cost Typical driver Optimisation lever
Embedding + vector DB Index size × storage/compute; reranker hosting Index only what retrieval needs; quantise vectors; right-size the instance (06, 07.2)
Observability platform Per-trace or per-seat pricing at high volume Sampling, tail-based retention, self-hosted Phoenix (11A.1)
App servers / workers Always-on processes holding async streams and queues Right-size concurrency, not CPU (11C.1)
Index builds and re-embedding Re-crawl + re-embed on schema/model change Versioned blue/green indexes (05.9, 07.11)
People On-call, prompt iteration, eval maintenance, incident response The most expensive line and the one nobody puts in the model — see Part 9

At low traffic, fixed costs dominate and per-request optimisation is premature. The crossover is roughly where variable spend exceeds fixed spend — compute it, don't guess (1.5).

1.5 Worked example: a RAG request, itemised#

Take the docs_qa request from 07.1, 5.1: ~3,000 prompt tokens in total (system + retrieved chunks + question — 07.1 budgets ~2,800 for the same shape; the extra ~200 here is the citation footer this lesson's prompt adds), ~350 output tokens, plus a query embedding and optional rerank. Using the module's economics.py (cost half below, prices as parameters — the numbers use Claude Sonnet 5.5's November 2026 list prices from 03.7's prices.yaml):

python
# economics.py — the cost and latency model for an LLM feature.
# Pure Python, standard library only. Prices are PARAMETERS...
from __future__ import annotations

from dataclasses import dataclass, field


@dataclass(frozen=True)
class Prices:
    """USD per 1M tokens for one model."""
    input: float
    output: float                 # includes reasoning/thinking tokens
    cached_input: float = 0.0
    cache_write: float = 0.0


@dataclass(frozen=True)
class TokenUsage:
    """One call's billed tokens, per the 03.7 token convention."""
    input: int = 0
    cached: int = 0
    written: int = 0
    output: int = 0


def call_cost_usd(u: TokenUsage, p: Prices) -> float:
    return (u.input * p.input + u.cached * p.cached_input
            + u.written * p.cache_write + u.output * p.output) / 1_000_000


@dataclass
class RequestProfile:
    """The average shape of one user-facing request to a feature."""
    name: str
    calls: int = 1               # model calls per request (agents: many)
    usage: TokenUsage = field(default_factory=TokenUsage)
    other_usd: float = 0.0       # embeddings, rerank, web search, storage
    retries: float = 1.0         # expected attempts per call


def request_cost(profile: RequestProfile, prices: list[Prices]) -> float:
    per_call = [call_cost_usd(profile.usage, prices[min(i, len(prices) - 1)])
                for i in range(profile.calls)]
    return sum(per_call) * profile.retries + profile.other_usd


@dataclass
class FixedCosts:
    vector_db_usd: float = 0.0
    observability_usd: float = 0.0
    hosting_usd: float = 0.0
    index_build_usd: float = 0.0


def monthly_cost(requests_per_day: int, profile: RequestProfile,
                 prices: list[Prices], fixed: FixedCosts,
                 days: int = 30,
                 users_per_day: int | None = None) -> dict[str, float]:
    """Monthly cost breakdown. `requests_per_day` is SERVICE-WIDE traffic,
    so `cost_per_day_usd` is the whole feature's daily variable spend —
    pass `users_per_day` (daily active users) for a true per-user figure."""
    per_request = request_cost(profile, prices)
    variable = per_request * requests_per_day * days
    fixed_total = (fixed.vector_db_usd + fixed.observability_usd
                   + fixed.hosting_usd + fixed.index_build_usd)
    total = variable + fixed_total
    out = {
        "variable_usd": round(variable, 2),
        "fixed_usd": round(fixed_total, 2),
        "total_usd": round(total, 2),
        "cost_per_request_usd": round(per_request, 6),
        "cost_per_day_usd": round(per_request * requests_per_day, 4),
        "variable_share": round(variable / total, 3) if total else 0.0,
    }
    if users_per_day:
        out["cost_per_user_day_usd"] = round(
            per_request * requests_per_day / users_per_day, 4)
    return out

The rest of economics.py is printed where each piece is used: the latency model in 2.4, the forecast function in 7.5, and the self-host side in Part 9.

Run the worked examples with this small driver (economics_demo.py, next to economics.py). The profiles are the RAG request above and the 9-step agent of 1.6; the monthly fixed costs are assumed round numbers for a small RAG service (vector DB, observability, hosting, index builds), not quotes:

python
# economics_demo.py — reproduces the numbers in 1.5 and 1.6. Stdlib only.
import json

from economics import (FixedCosts, Prices, RequestProfile, TokenUsage,
                       monthly_cost, request_cost)

sonnet = Prices(input=2.00, output=10.00, cached_input=0.10)   # Sonnet 5.5 list, Nov 2026
rag = RequestProfile("docs_qa", calls=1, other_usd=0.0004, retries=1.02,
                     usage=TokenUsage(input=2400, cached=600, output=350))
agent = RequestProfile("support_agent", calls=9, other_usd=0.002, retries=1.05,
                       usage=TokenUsage(input=2200, cached=3000, output=900))
fixed = FixedCosts(vector_db_usd=300, observability_usd=150,
                   hosting_usd=100, index_build_usd=5)          # assumed, per month

print("=== 1. RAG request vs agent run (Sonnet 5.5 prices, Nov 2026) ===")
print(f"rag request : {request_cost(rag, [sonnet]):.6f} USD")
print(f"agent run   : {request_cost(agent, [sonnet]):.6f} USD")
print("\n=== 2. Monthly service economics, 20k req/day ===")
print(json.dumps(monthly_cost(20_000, rag, [sonnet], fixed,
                              users_per_day=4_000), indent=2))
Output14 lines
=== 1. RAG request vs agent run (Sonnet 5.5 prices, Nov 2026) ===
rag request : 0.008927 USD
agent run   : 0.131465 USD

=== 2. Monthly service economics, 20k req/day ===
{
  "variable_usd": 5356.32,
  "fixed_usd": 555,
  "total_usd": 5911.32,
  "cost_per_request_usd": 0.008927,
  "cost_per_day_usd": 178.544,
  "variable_share": 0.906,
  "cost_per_user_day_usd": 0.0446
}

Where each dollar of the RAG request goes — the itemisation call_cost_usd computes line by line (Sonnet 5.5 prices: $2.00/MTok input, $0.10 cached reads, $10.00 output):

Line Tokens Rate USD
Uncached input (system + chunks + question) 2,400 $2.00/MTok $0.004800
Cached prefix reads 600 $0.10/MTok $0.000060
Output (answer + citations) 350 $10.00/MTok $0.003500
Model subtotal $0.008360
× expected retries (1.02) $0.008527
Embedding + rerank (other_usd) $0.000400
Per request $0.008927

Read it three ways:

  • One RAG answer costs ~$0.009 on Sonnet 5.5 at these parameters — call it a cent. Output is 42% of the model bill despite being 11% of the tokens; input dominates the token count but output dominates the dollar count after the cache discount. At 20,000 requests/day that's $5,356/month variable against $555 fixed: the variable side is 91% of the bill, so per-request optimisation is where the money is at this scale.
  • The same request on Haiku 5.5 (Prices(input=0.10, output=0.50, cached_input=0.01)) costs $0.000829 — an order of magnitude cheaper, which is why 4.3 exists.
  • Cost per day ($178.54) is the whole service's daily variable spend — the number finance asks for at feature level. For per-user economics pass users_per_day: at 4,000 daily active users the same model gives $0.0446 per user per day — the unit-economics chain of 7.4 starts here.

1.6 Worked example: an agent run#

An agent isn't one request — it's a loop of model calls, each re-sending the accumulated history plus new tool results (02.7, 6.2, 08A.2). Model it as calls=N with the average per-call usage, and remember the per-call input grows each step:

python
# A 9-step support-agent run on Sonnet 5.5: each call carries ~5,200 input
# tokens (growing history, 3,000 of it cacheable prefix) and ~900 output.
agent = RequestProfile(
    "support_agent", calls=9,
    usage=TokenUsage(input=2200, cached=3000, written=0, output=900),
    other_usd=0.002, retries=1.05)
# request_cost(...) -> $0.131 per run
Output · the same value economics_demo.py prints in 1.51 line
agent run   : 0.131465 USD

Where the agent's dollars go, per call: 2,200 uncached × $2.00 = $0.0044, 3,000 cached × $0.10 = $0.0003, 900 output × $10.00 = $0.0090 → $0.0137 per call; × 9 calls = $0.1233, × 1.05 expected retries = $0.1295, + $0.002 tool/embedding overhead = $0.1315 per run. That's ~15× the RAG request for the same model — and it's an underestimate, because real agent input grows per step (step 9's prompt is much bigger than step 1's), tool results compound, and a budget_exhausted run still bills every call it made (08A.2, 3.3). The agent's cost levers are different too: fewer steps (better tools, 08A.6), cheaper models for easy steps (11B.5), context compaction (04.7), and hard budgets before the loop runs away (08A.2, 7.3).

The algebra behind that growth (why input tokens grow with the square of the number of steps, and what caching and compaction each change) is in 11B.2, Part 4. 11B.8, Part 1 has the agent-cost calculator and the p95 tail.


Part 2: The latency model — where every second goes#

2.1 Cost and latency are the same pipeline, priced differently#

Every request travels the same stages whether you count dollars or milliseconds. Draw the pipeline once and both models fall out of it:

flowchart LR
    subgraph req ["One user request"]
        A["Network<br/>DNS/TLS/transit"] --> B["Your queue<br/>(concurrency cap)"]
        B --> C["Retrieval<br/>embed+search+rerank"]
        C --> D["Guardrails<br/>input checks"]
        D --> E["LLM call 1<br/>prefill → TTFT"]
        E --> F["Tool calls<br/>(parallel?)"]
        F --> G["LLM call 2..N<br/>(agent loop)"]
        G --> H["Decode/stream<br/>output tokens"]
        H --> I["Output guardrails"]
    end
    A -. "~40–300ms" .-> B
    C -. "10–500ms" .-> D
    E -. "TTFT: prefill ∝ input" .-> F
    H -. "decode ∝ output × ITL" .-> I

Cost attaches to the model calls (tokens) and the retrieval/embedding calls (their own token or per-query prices); latency attaches to every stage, including the ones that cost nothing (your queue, your guardrails). That's why a "cheap" feature can be slow (many small calls in sequence) and an "expensive" one can feel instant (one big cached call, streamed).

2.2 TTFT vs total time: two different problems#

  • TTFT (time to first token) is dominated by prefill — the model reading your whole prompt in one parallel pass — plus everything before it (network, retrieval, queue). It grows with input size, faster than linearly at long contexts (02.7, 6.3). Streaming doesn't help TTFT; it only hides the decode tail.
  • Total time adds decode: output tokens generated one forward pass each, at the model's inter-token latency. Long outputs dominate total time even when TTFT is instant.
  • TTFVT (time to first visible token) on reasoning models can be seconds after TTFT, because thinking tokens stream (or don't) before the answer (glossary, 02.8, 5.2).

The engineering consequence: measure TTFT and total separately (the trace schema has ttft_ms and latency_ms for exactly this), because they have different levers — TTFT yields to smaller prompts, warmer caches and fewer pre-model stages; total yields to shorter outputs, faster decode tiers and parallelism.

2.3 Queueing: the stage everyone forgets#

Between "user hits send" and "provider sees the request" sits your queue: the concurrency cap, the per-tenant limiter, the worker pool. An LLM call is mostly waiting (03.9, 1.1), so unbounded concurrency doesn't speed anything up — it converts latency into 429s and retry storms. The queue is where tail latency is born: p50 can look fine while p99 waits behind a neighbour's 4-second reasoning call. Little's law applies: queue_depth ≈ arrival_rate × service_time; if arrivals exceed the service rate, the queue grows without bound and every request's latency grows. Cap concurrency, shed load early, and alert on queue depth (11A.2 owns the metrics).

2.4 Worked example: the latency budget#

economics.py's LatencyBudget makes the additive model concrete — every stage in milliseconds, TTFT and total derived:

python
@dataclass(frozen=True)
class LatencyBudget:
    """Where the seconds go for one request. All values in milliseconds."""
    network_ms: float = 40.0
    queue_ms: float = 0.0
    retrieval_ms: float = 0.0       # embed + search + rerank + assemble
    guardrails_ms: float = 0.0
    prefill_ms: float = 0.0         # TTFT of first model call
    tool_ms: float = 0.0            # all tool executions (parallel max)
    decode_ms: float = 0.0
    retries_ms: float = 0.0

    @property
    def ttft_ms(self) -> float:
        return self.network_ms + self.queue_ms + self.retrieval_ms \
            + self.guardrails_ms + self.prefill_ms

    @property
    def total_ms(self) -> float:
        return self.ttft_ms + self.tool_ms + self.decode_ms + self.retries_ms


def agent_latency(budget: LatencyBudget, steps: int) -> dict[str, float]:
    """An agent run repeats model call + tool execution `steps` times.
    Retrieval happens once; guardrails may run per step. Queueing is counted
    once via `ttft_first_ms` (the first call's wait) — per-step queue wait is
    a 11A.2/03.9 concern this simplified model doesn't price."""
    per_step = (budget.network_ms + budget.prefill_ms
                + budget.tool_ms + budget.decode_ms + budget.retries_ms)
    return {
        "ttft_first_ms": budget.ttft_ms,
        "total_ms": budget.retrieval_ms + budget.guardrails_ms
                    + per_step * steps,
        "model_calls": float(steps),
    }

Two budgets from the docs_qa numbers in 07.1, 5.1: the RAG request is a single model call, so it gets tool_ms=0/retries_ms=0; the agent run repeats network + prefill + tool + decode + retries per step:

python
rag_lat = LatencyBudget(network_ms=40, retrieval_ms=360,
                        guardrails_ms=25, prefill_ms=800, decode_ms=900)
agent_lat = LatencyBudget(network_ms=40, retrieval_ms=360,
                          guardrails_ms=25, prefill_ms=800, tool_ms=1400,
                          decode_ms=900, retries_ms=120)

print("=== 3. Latency model: RAG vs 9-step agent ===")
print(f"RAG request: TTFT {rag_lat.ttft_ms:.0f}ms, total {rag_lat.total_ms:.0f}ms")
run = agent_latency(agent_lat, steps=9)
print(f"agent run  : TTFT {run['ttft_first_ms']:.0f}ms, "
      f"total {run['total_ms']:.0f}ms over {run['model_calls']:.0f} calls")
Output3 lines
=== 3. Latency model: RAG vs 9-step agent ===
RAG request: TTFT 1225ms, total 2125ms
agent run  : TTFT 1225ms, total 29725ms over 9 calls

Where the RAG request's 2,125 ms goes — every LatencyBudget field, as a share of TTFT and of total:

Stage ms Share of TTFT (1,225) Share of total (2,125)
Network (amortised TLS + transit) 40 3% 2%
Queue (your concurrency cap) 0 0% 0%
Retrieval (embed + search + rerank + assemble) 360 29% 17%
Guardrails 25 2% 1%
Prefill (~3,000 prompt tokens) 800 65% 38%
TTFT subtotal 1,225
Decode (~350 output tokens, streamed) 900 — 42%
Total 2,125

And one agent step — the unit that repeats nine times:

Stage per step ms Share of step (3,260)
Network 40 1%
Prefill (growing history) 800 25%
Tool execution (parallel max) 1,400 43%
Decode 900 28%
Retries (expected extra) 120 4%
Retrieval + guardrails (once per run) 385 —

Read it:

  • The RAG request's TTFT is 1.2s — of which retrieval+rerank is ~360ms and prefill ~800ms. Retrieval is ~30% of TTFT: worth optimising but not the whole story; the prompt size is.
  • Reconciling with 07.1: its stage table lands at ~1.16s TTFT / ~2.1s total for the same request; this budget adds the 40ms network and 25ms guardrails that 07.1 leaves to "your infrastructure", giving 1,225ms / 2,125ms — same request, same stages, two accounting boundaries. The agent row keeps the full budget because agent steps genuinely pay tools and retries.
  • The agent run's TTFT is the same 1.2s (first call only) but total is ~30s: nine sequential model+tool rounds at ~3.3s each. The user's perceived wait is dominated by steps × per-step latency — tool execution alone is 43% of a step — which is why agent latency engineering is about fewer round trips (parallel tool calls, 4.6) and earlier partial results, not a faster model.
  • agent_latency() in the file computes this generally: total ≈ retrieval_once + steps × (network + prefill + tool + decode + retries).

2.5 Perceived latency: the gap between measured and felt#

Users don't experience milliseconds; they experience silence. Three techniques shrink the felt wait without changing the physics:

  • Streaming moves the first visible token from total to ttft (03.3).
  • Progress and partial results — retrieval counts, "checking 3 sources", tool-call labels — fill the pre-TTFT gap (13 owns AI UX; the principle is yours to apply).
  • Speculative prefetch and precomputation — start retrieval or a cheap first pass before the user finishes typing, or warm the prompt cache on likely next inputs (4.7).

Part 3: Measure first — the optimisation loop#

3.1 Baseline before you touch anything#

Every optimisation in this lesson is a hypothesis until you have a baseline. The baseline is three distributions from your traces (11A.1), per feature:

  1. Cost per request — p50, p95, p99, and the share of cost_source: unknown.
  2. Latency — TTFT and total, p50/p95/p99.
  3. Composition — input vs output vs cached vs reasoning tokens; attempts distribution; finish_reason mix.

If you don't have traces yet, 11A.1 builds them; if you have logs but no token fields, 03.7, Part 5 adds them. Optimising without this is guessing which of the ten levers matters — and the wrong lever wastes a sprint.

3.2 The waste report#

waste_report.py reads the JSONL trace records from 11A.1, 2.6 and ranks mechanical waste — the things that are wrong regardless of model quality:

python
# waste_report.py — read trace JSONL, report optimisation targets.
# Input: one JSON object per span (11A.1 §2.6 schema). Pure stdlib.
from __future__ import annotations

import json
import sys
from collections import defaultdict


def percentile(values: list[float], p: float) -> float:
    if not values:
        return 0.0
    xs = sorted(values)
    k = max(0, min(len(xs) - 1, int(round((p / 100) * (len(xs) - 1)))))
    return xs[k]


def load_llm_spans(path: str) -> list[dict]:
    """Read 11A.1 §2.6 JSONL records and flatten each into one dict.

    The canonical record is an envelope (trace_id, kind, status, timing)
    plus an `attrs` object holding the LLM fields — this merges them so the
    report can read `feature`, `uncached_input_tokens`, `cost_usd` etc.
    directly. Non-LLM spans (kind != "llm" with no model_resolved) are
    skipped."""
    spans = []
    with open(path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            rec = json.loads(line)
            attrs = rec.get("attrs") or {}
            if rec.get("kind") != "llm" and "model_resolved" not in attrs:
                continue
            flat = dict(attrs)
            flat.update({k: v for k, v in rec.items() if k != "attrs"})
            spans.append(flat)
    return spans


def report(spans: list[dict]) -> str:
    n = len(spans)
    if not n:
        return "no llm spans found"
    out = [f"{n} LLM spans\n"]

    def total(field: str) -> int:
        return sum(int(s.get(field) or 0) for s in spans)

    inp = total("uncached_input_tokens") + total("cached_input_tokens")
    outp = total("output_tokens")
    reas = total("reasoning_tokens")
    cached = total("cached_input_tokens")
    priced = [s for s in spans
              if s.get("cost_source") != "unknown"
              and s.get("cost_usd") is not None]
    cost = sum(float(s.get("cost_usd") or 0) for s in priced)
    lat = [float(s["latency_ms"]) for s in spans if s.get("latency_ms")]
    ttft = [float(s["ttft_ms"]) for s in spans if s.get("ttft_ms")]
    retries = sum(1 for s in spans if (s.get("attempts") or 1) > 1)
    trunc = sum(1 for s in spans
                if s.get("finish_reason") in ("length", "max_tokens",
                                              "max_output_tokens", "incomplete"))
    errs = sum(1 for s in spans if s.get("status") not in (None, "ok"))

    out.append(f"tokens: {inp:,} in ({cached:,} cached, "
               f"{cached / max(1, inp):.0%} hit share) + {outp:,} out "
               f"({reas:,} reasoning = {reas / max(1, outp):.0%} of output)")
    if cost:
        out.append(f"cost:   ${cost:,.2f} total over {len(priced)} priced "
                   f"calls, ${cost / max(1, len(priced)):.5f}/call avg"
                   + (f" ({n - len(priced)} unknown-cost spans excluded)"
                      if len(priced) < n else ""))
    if lat:
        out.append(f"latency: p50 {percentile(lat, 50):.0f}ms "
                   f"p95 {percentile(lat, 95):.0f}ms "
                   f"p99 {percentile(lat, 99):.0f}ms")
    if ttft:
        out.append(f"ttft:    p50 {percentile(ttft, 50):.0f}ms "
                   f"p95 {percentile(ttft, 95):.0f}ms")

    waste = []
    if retries:
        waste.append(f"{retries} calls retried "
                     f"({retries / n:.0%}) — retry amplification; check 03.8 "
                     f"handling before blaming the model")
    if trunc:
        waste.append(f"{trunc} calls hit the output cap "
                     f"({trunc / n:.0%}) — paid-for answers you can't use; "
                     f"raise the cap or shorten the ask")
    if errs:
        waste.append(f"{errs} calls ended non-ok — you may have paid for "
                     f"partial output; check cost_source=unknown too")
    big = [s for s in spans if int(s.get("uncached_input_tokens") or 0)
           > 100_000]
    if big:
        waste.append(f"{len(big)} calls over 100K input tokens — check "
                     f"long-context pricing tiers (02.9 §6.6) and whether "
                     f"the context should have been compacted (04.7)")
    low_cache = [s for s in spans if int(s.get("cached_input_tokens") or 0) == 0
                 and int(s.get("uncached_input_tokens") or 0) > 2_000]
    if low_cache:
        waste.append(f"{len(low_cache)} calls >2K input with zero cache "
                     f"reads — stable prefixes aren't being cached (11B.3)")

    by_feat: dict[str, dict[str, float]] = defaultdict(
        lambda: {"n": 0, "cost": 0.0, "inp": 0, "out": 0})
    for s in spans:
        f = by_feat[s.get("feature") or "?"]
        f["n"] += 1
        f["cost"] += float(s.get("cost_usd") or 0)
        f["inp"] += int(s.get("uncached_input_tokens") or 0) \
            + int(s.get("cached_input_tokens") or 0)
        f["out"] += int(s.get("output_tokens") or 0)
    out.append("\nby feature:")
    for name, f in sorted(by_feat.items(), key=lambda kv: -kv[1]["cost"]):
        out.append(f"  {name:20s} {int(f['n']):>5} calls  "
                   f"{int(f['inp']):>10,} in  {int(f['out']):>8,} out  "
                   f"${f['cost']:>9.2f}")

    by_ver: dict[tuple, list[float]] = defaultdict(list)
    for s in spans:
        key = (s.get("feature"), s.get("prompt_version"))
        if s.get("cost_usd") is not None and s.get("cost_source") != "unknown":
            by_ver[key].append(float(s["cost_usd"]))
    drift = []
    for (feat, ver), costs in by_ver.items():
        if len(costs) >= 5 and percentile(costs, 95) > 2 * percentile(costs, 50):
            drift.append(f"  {feat} v{ver}: p95 ${percentile(costs, 95):.4f} "
                         f"vs p50 ${percentile(costs, 50):.4f} — long tail "
                         f"of expensive requests (big contexts? retries?)")
    if drift:
        out.append("\ncost tail per prompt version:")
        out.extend(drift)

    out.append("\nwaste checklist:")
    out.extend(f"  - {w}" for w in waste) if waste else out.append(
        "  - none of the mechanical waste signals fired")
    out.append("  next: rank features by cost, then check each against the "
               "playbook in Part 4 — measure before you optimise")
    return "\n".join(out)


if __name__ == "__main__":
    print(report(load_llm_spans(sys.argv[1] if len(sys.argv) > 1
                                else "traces.jsonl")))

To reproduce the report, generate a fixture in the exact §2.6 schema — envelope fields at top level, LLM fields inside attrs. This script writes traces_fixture.jsonl: 60 LLM spans across three features (with retries, truncations, missed cache reads, two cost_source: "unknown" spans — one of them an error — for realism), plus two non-LLM spans the loader filters out:

python
# make_fixture.py — writes traces_fixture.jsonl (11A.1 §2.6 schema).
import json

feats = [("docs_qa", 2400, 350, 0.004), ("support_agent", 5200, 900, 0.02),
         ("invoice_extract", 1800, 200, 0.002)]
recs = []
for i in range(60):
    feat, inp, outp, cost = feats[i % 3]
    cached = inp // 2 if i % 4 else 0
    attempts = 2 if i % 17 == 0 else 1
    lat, ttft = 800 + (i * 37) % 3000, 300 + (i * 13) % 900
    recs.append({
        "trace_id": f"tr_{i:03d}", "span_id": f"s_{i:03d}",
        "parent_span_id": "s_000", "name": "generate", "kind": "llm",
        "start_ms": float(i * 60_000), "duration_ms": float(lat),
        "status": "ok", "ts": "2026-11-04T15:00:00.000Z",
        "attrs": {
            "feature": feat, "model_resolved": "claude-sonnet-5-5",
            "provider": "anthropic",
            "uncached_input_tokens": inp - cached,
            "cached_input_tokens": cached,
            "output_tokens": outp,
            "reasoning_tokens": outp // 5 if feat == "support_agent" else 0,
            "cost_usd": cost * attempts, "cost_source": "computed",
            "latency_ms": lat, "ttft_ms": ttft,
            "finish_reason": "length" if i % 23 == 0 else "stop",
            "attempts": attempts,
            "prompt_version": "1.4" if i < 40 else "1.5",
        }})

# Two LLM spans whose cost couldn't be computed (unknown is null, never 0),
# plus two non-LLM spans the loader filters out.
recs += [
    {"trace_id": "tr_x01", "span_id": "s_x01", "kind": "llm",
     "name": "generate", "status": "ok", "duration_ms": 1500.0,
     "attrs": {"feature": "docs_qa", "model_resolved": "claude-sonnet-5-5",
               "uncached_input_tokens": 2600, "cached_input_tokens": 0,
               "output_tokens": 300, "cost_usd": None,
               "cost_source": "unknown", "latency_ms": 1500,
               "ttft_ms": 500, "finish_reason": "stop", "attempts": 1,
               "prompt_version": "1.5"}},
    {"trace_id": "tr_x02", "span_id": "s_x02", "kind": "llm",
     "name": "generate", "status": "error", "duration_ms": 3200.0,
     "attrs": {"feature": "support_agent",
               "model_resolved": "claude-sonnet-5-5",
               "uncached_input_tokens": 5400, "cached_input_tokens": 0,
               "output_tokens": 700, "cost_usd": None,
               "cost_source": "unknown", "latency_ms": 3200,
               "ttft_ms": 900, "finish_reason": "error", "attempts": 3,
               "prompt_version": "1.5"}},
    {"trace_id": "tr_x03", "span_id": "s_x03", "kind": "tool",
     "name": "search_docs", "status": "ok", "duration_ms": 120.0,
     "attrs": {"feature": "docs_qa"}},
    {"trace_id": "tr_x04", "span_id": "s_x04", "kind": "retrieval",
     "name": "retrieve", "status": "ok", "duration_ms": 120.0,
     "attrs": {"feature": "docs_qa"}},
]
with open("traces_fixture.jsonl", "w") as f:
    for r in recs:
        f.write(json.dumps(r) + "\n")
bash
python make_fixture.py
python -m llm_service.waste_report traces_fixture.jsonl   # or: python waste_report.py traces_fixture.jsonl
Output · on that fixture18 lines
62 LLM spans

tokens: 196,000 in (70,500 cached, 36% hit share) + 30,000 out (3,600 reasoning = 12% of output)
cost:   $0.55 total over 60 priced calls, $0.00917/call avg (2 unknown-cost spans excluded)
latency: p50 1873ms p95 2909ms p99 2983ms
ttft:    p50 677ms p95 1028ms

by feature:
  support_agent           21 calls     109,400 in    18,700 out  $     0.42
  docs_qa                 21 calls      50,600 in     7,300 out  $     0.09
  invoice_extract         20 calls      36,000 in     4,000 out  $     0.04

waste checklist:
  - 5 calls retried (8%) — retry amplification; check 03.8 handling before blaming the model
  - 3 calls hit the output cap (5%) — paid-for answers you can't use; raise the cap or shorten the ask
  - 1 calls ended non-ok — you may have paid for partial output; check cost_source=unknown too
  - 12 calls >2K input with zero cache reads — stable prefixes aren't being cached (11B.3)
  next: rank features by cost, then check each against the playbook in Part 4 — measure before you optimise

What just happened: support_agent is ~76% of the bill on a third of the calls — that's where the optimisation effort goes, not the average. The cost line also shows the honest accounting: 60 priced calls averaged (the two cost_source: "unknown" spans are excluded from the average, not silently zeroed), and the error span surfaces in the checklist. The waste checklist then names the mechanical fixes (retries, truncation, missed cache) that are wrong regardless of which model serves the traffic.

3.3 The cost-quality frontier#

The deepest fact in optimisation: cost and quality trade off, but not linearly, and not everywhere. Plot quality (your eval score) against cost per request for each configuration you've tried — model tier, prompt version, caching on/off, reasoning effort — and you get a cost-quality frontier: the set of configurations where you can't get more quality without paying more, or less cost without losing quality.

text
quality
  ^
  |        ● frontier config A (sonnet, full context)
  |       /
  |      /  ← dominated region: same quality, more cost
  |     ● config B (haiku, trimmed prompt) — ON the frontier
  |    /
  |   ● config C (haiku, no eval) — dominated: worse AND not cheaper enough
  +--------------------------> cost/request

Every optimisation in Part 4 is a move along or toward this frontier. The mistake is optimising cost without the quality axis: a config that saves 40% and loses 2 eval points may be a great trade or a disaster depending on whether those 2 points were already marginal. Part 5 makes the frontier measurable.


Part 4: The prioritised playbook#

Ten levers, roughly in the order they pay off for most features. Each says what it is, when it wins, what it costs you, and where the boundary with another lesson falls. The decision table at the end of the part summarises. 11B.2, Part 6 gives a one-line ranking of the same levers by size of effect, with the price figures from that lesson.

4.1 Lever 1: remove waste#

The cheapest savings are the tokens you shouldn't have sent at all:

Waste Fix Boundary
Over-long outputs max_output_tokens ceiling sized from your p99 + headroom; concise-output instructions or the provider's verbosity control where one exists (02.5, Part 6); structured output instead of prose 03.7, 12.1, 03.4
Repeated per-item overhead Thousands of tiny calls that each re-send the same long instructions: cache the shared prefix (11B.3), or pack several items into one call ("classify these 20" — the request-packing meaning of batching, 03.9, 1.4) and evaluate that packing does not lower per-item accuracy 03.9, 04.6
Bloated prompts Trim instructions, dedupe retrieved chunks, drop boilerplate 04.6, 07.2
Unused tool definitions Send only the tools the task needs; tool search / deferred loading for large catalogues 08A.8, Part 8, 02.7, 6.5
Ever-growing history Compaction, selective retention, structured state 04.7, 02.7, Part 4
Re-sent tool results Clear or summarise old tool outputs; handles + just-in-time retrieval 04.7, Part 5

The discipline: measure the composition first (3.2). If 60% of input is retrieved chunks you didn't need, trimming the prompt won't help — retrieval sizing (4.8) will. Waste removal is feature-specific; there's no universal "send less" button.

4.2 Lever 2: caching#

11B.3 owns the whole caching stack — provider prompt caching strategy, exact-match response caching, semantic caching, embedding/retrieval/tool-result caches, cache economics and safety. The cost lesson's contribution is one line: caching is usually the highest-ROI lever because it attacks input tokens, which dominate most workloads — but only when the prefix is actually stable and the hit rate is measured, not assumed. The waste report's "zero cache reads on >2K input" signal is the canary.

4.3 Lever 3: model tiering#

Not "use a cheaper model" — use the cheapest model that passes your evals for each task. A support bot doesn't need the same model for "reset my password" (classification) as for "explain this billing dispute" (reasoning). The patterns:

  • Static tiering by task — route each feature/sub-task to its cheapest adequate model (11B.5 owns the routing mechanics).
  • Cascade — cheap model first, escalate on low confidence or validator failure (11B.5, 07.8 for speculative RAG).
  • Downgrade under load — when queue depth or budget pressure rises, serve the cheaper tier for non-critical traffic (7.2; the downgrade-or-refuse design is 11B.6, 4.3, and what to do when a rate limiter says no is 11B.7, 1.5).

The guardrail: every tier must pass your evals for that task — a cheaper model that fails 5% more is not cheaper (Part 5).

4.4 Lever 4: reasoning effort and budget#

Reasoning tokens bill as output and can multiply a request's cost 5–25× on the same visible answer (02.8, 5.1). The lever is per-request effort, not per-model: easy tasks get low/none, hard ones get high. 02.8, Part 3 owns the per-provider controls (reasoning.effort, thinking budgets, reasoning param); the cost lesson adds: treat effort as a cost knob and evaluate it like one — the eval suite should run at each effort level you ship, because the quality drop from high→low is task-specific and sometimes zero.

4.5 Lever 5: batch, flex and async tiers#

When nobody is waiting, the same model costs half as much. As of November 2026 (verified on the pricing pages — Part 8 has the full table):

Tier Discount Latency When it fits
Batch API ~50% off input+output Hours (typically ≤24h) Nightly jobs, eval suites, dataset labelling, backfills
Flex ~50% (OpenAI, Gemini) Slower, may throttle Bulk work needing results in minutes–hours
Standard list interactive Anything a user is waiting on
Priority/Fast 1.8–6× faster/more reliable Latency-critical paid features only

03.9 owns the mechanics completely — batch lifecycle, custom_id, resumable manifests, flex fallbacks, webhooks. The cost lesson's rule: classify every workload by "can it wait?" before you build it synchronous. A feature that starts synchronous "for simplicity" and never moves to batch is paying 2× forever on work that didn't need to be instant.

4.6 Lever 6: parallelism and streaming for perceived latency#

  • Parallel, not sequential. Independent stages (retrieval branches, multiple tool calls, multiple model calls for different sub-questions) run concurrently — asyncio.gather, TaskGroup, or the provider's parallel tool calls (03.9, Part 4, 03.5). Sequential waterfalls are the #1 avoidable latency.
  • Stream everything a human reads (03.3).
  • Bound the concurrency — parallelism without a semaphore converts latency into 429s (03.9, 4.1).

4.7 Lever 7: speculative and early-exit patterns#

Pay full price only where the cheap answer isn't good enough:

  • Cascade / early exit — cheap model answers; a validator (schema check, self-grade, judge, confidence threshold) decides whether to escalate to the expensive model. Expected cost = p_cheap × cost_cheap + p_escalate × cost_expensive; it wins when the cheap model handles most traffic well (11B.5 owns the router; the cost math is here).
  • Speculative RAG — a small drafter reads the retrieved docs and drafts; a large verifier checks and only rewrites where wrong (07.8).
  • Prefetch and precompute — run retrieval or a cheap first pass before the user's request completes (query autocomplete, likely-next-question prediction), or warm the prompt cache for predictable next inputs (11B.3).
  • Provider speculative features — prompt lookup / predicted outputs where offered (02.5, 11.1); awareness, not a lever you control.

4.8 Lever 8: retrieval and rerank sizing#

Retrieval feeds the prompt; an oversized context is both slower (prefill) and costlier (input tokens). 07.2 owns the mechanics — k selection, score floors, adaptive k, token-budgeted context shaping, MMR diversity, small-to-big expansion. The cost lesson's contribution: retrieval size is a cost-and-latency dial, and it's usually set by feel, not by measurement. The waste report shows input-token share; the eval suite shows whether fewer chunks hurt answers. Tune k on the cost-quality frontier, not on recall alone.

4.9 Lever 9: regional endpoints and connection reuse#

Two small levers that compound:

  • Connection reuse. One long-lived client per process — the SDK's connection pool amortises DNS/TLS handshakes (50–300ms each) across requests (03.1, connection pooling). "One client per request" is a latency bug and a socket-exhaustion bug.
  • Regional endpoints place inference nearer your users — but can cost a premium (02.9, 6.7). The trade: latency vs a percentage surcharge vs data-residency requirements. Choose per feature, not globally.

4.10 Lever 10: self-hosting at scale#

At sufficient volume, running open-weight models yourself can beat API pricing — but only past a break-even that most teams never reach (Part 9). 11C.6 owns the whole topic: hardware sizing, runtimes (vLLM switches prefix caching on by default for models that support it — read from its engine-arguments reference as of November 2026), serving, and the ops burden. The cost lesson's contribution: self-hosting is a fixed-cost play — it converts variable token spend into provisioned GPU-hours, which only wins at high utilisation. Below the break-even it's strictly worse.

4.11 The decision table#

Symptom in your traces First lever to try Why first
High input-token share, stable prefix Caching (11B.3) Biggest input reduction, lowest risk
Long outputs / high output share Output caps + concise prompts (4.1) Output is the expensive token
Reasoning tokens >30% of output Effort budget (4.4) Often a config change, not a model change
Many calls per user request Fewer steps / parallel calls (4.6, 11B.5) Agents multiply everything
Work that can wait Batch/flex tier (4.5) ~50% off, zero quality risk
p95 TTFT high, p50 fine Queue depth + hedging (6.2) Tail latency, not median
Cost creeping up over time Prompt-version drift (3.2) A deploy added tokens silently
Everything already lean Model tiering or self-hosting (4.3, Part 9) The remaining levers are structural

Part 5: Quality-aware optimisation#

5.1 Every change goes through evals#

A cost optimisation is a behavioural change until proven otherwise: a smaller model, a trimmed prompt, a lower effort level, fewer retrieved chunks — each can silently degrade answer quality. The rule: no cost lever ships without an eval gate. 10A.8 owns regression testing and CI gates; 10A.9 owns online evaluation. The cost lesson adds the framing: your eval suite should run per candidate configuration, producing a (cost, quality) point for the frontier — not just a pass/fail.

5.2 Cost-quality frontier and acceptable-regression budgets#

Two artefacts make the trade explicit:

  • The frontier table — one row per configuration tried: cost/request, eval score, p95 latency, sample size. The frontier is the Pareto set; anything dominated (worse quality AND more cost) is discarded regardless of how it got there.
  • The regression budget — "we accept at most −1.5 eval points for ≥30% cost reduction" is a policy decision, not a discovery. Write it down per feature, get product sign-off, and enforce it in the eval gate. Different features have different budgets: an internal copilot can tolerate more regression than a customer-facing extractor.

5.3 A/B tests and canaries#

For changes that pass offline evals but might behave differently on live traffic (new model version, new prompt, new routing split), 10A.9 owns the online methodology. The cost lesson's note: an A/B test on cost levers needs cost AND quality arms — randomise users to config A/B, measure eval score and spend per resolved outcome, not just clicks. A cheaper config that increases support tickets is a false saving (5.4).

5.4 The false savings catalogue#

The optimisations that look like wins on a cost dashboard and lose on the business metrics:

False saving What actually happens The tell
Cheaper model, more retries Retry amplification eats the savings (1.3) attempts > 1 share rises in traces
Aggressive truncation Cut-off answers re-asked or escalated: two bills, zero output finish_reason: length share rises
Shorter prompts, worse answers Quality drops → more follow-ups, escalations, re-asks Eval score drops; support volume rises
Over-aggressive caching Stale or wrong cached answers served at scale Cache-hit rate up, complaint rate up
Hedging everything Every request bills twice hedged=true share × unit cost > latency saved
Batch for user-facing work Users wait hours; workarounds appear Feature usage drops; "it's slow" tickets
Removing guardrails to save latency Incidents and safety events cost more than the ms saved Module 12 metrics; never a real saving

Part 6: Latency engineering#

Deep-dive

6.1 TTFT engineering: the pre-model path#

TTFT = network + queue + retrieval + guardrails + prefill. Levers by stage:

  • Network: connection reuse (4.9), regional endpoints where they help.
  • Queue: concurrency caps sized to provider limits, not to hardware (03.9, 4.7).
  • Retrieval: parallel branches, smaller k, skip rerank when k is already small (07.1, 5.1).
  • Guardrails: run cheap checks first, expensive ones in parallel or post-response (Module 12 owns the checks; sequencing is yours).
  • Prefill: smaller prompts, warmer prompt cache, and — on reasoning models — lower effort (thinking tokens delay first visible token even more than prefill does).

6.2 Hedged requests#

When p95 latency matters more than median cost, hedging sends a second identical request after a delay and keeps whichever finishes first. It's the standard fix for tail latency behind a shared provider queue — at the price of billing both calls.

budget.py implements hedging and the tenant quotas of 7.2 — the complete file, stdlib only:

python
# budget.py — token-denominated quotas and hedged requests.
# Two mechanisms this module adds on top of what Module 03 already owns:
# TenantQuota (per-tenant token budgets, reserve-then-settle) and
# hedged_call (tail-latency hedging). Rate limiting (RPM/TPM token
# buckets) is 03.8's rate_limiter.py — different problem, different tool.
from __future__ import annotations

import asyncio
import time
from dataclasses import dataclass


# ------------------------------------------------------------ tenant quotas

@dataclass
class QuotaWindow:
    """A tenant's token budget for one window (e.g. per UTC day)."""
    limit_tokens: int
    window_seconds: float = 86_400.0


class TenantQuota:
    """Reserve-then-settle token budget for one tenant.

    `reserve()` charges the ESTIMATED worst case before the call;
    `settle()` replaces it with the ACTUAL billed tokens (from usage).
    Failed/unknown calls keep the reservation — over-charging a quota by a
    few tokens beats letting failures spend for free. In production the
    store is Redis/Postgres (atomic increments); this in-memory version is
    the tested logic and the unit-test seam.
    """

    def __init__(self, limit_tokens: int, window_seconds: float = 86_400.0,
                 clock=time.monotonic) -> None:
        self.window = QuotaWindow(limit_tokens, window_seconds)
        self.clock = clock
        self._used = 0
        self._reserved = 0
        self._window_start = clock()

    def _roll(self) -> None:
        now = self.clock()
        if now - self._window_start >= self.window.window_seconds:
            # `_used` resets; `_reserved` deliberately does NOT — a request
            # that reserved late in the old window still holds its estimate
            # until settle() releases it, so the new window can't be
            # oversubscribed by in-flight calls. (A reserve() that never
            # settles leaks its reservation into every later window — in
            # production sweep stale reservations by age; day windows make
            # it rare.)
            self._used = 0
            self._window_start = now

    @property
    def remaining(self) -> int:
        self._roll()
        return self.window.limit_tokens - self._used - self._reserved

    def reserve(self, estimated_tokens: int) -> bool:
        """Try to hold `estimated_tokens` (input estimate + output cap).
        Returns False when the remaining budget can't cover it."""
        self._roll()
        if estimated_tokens > self.remaining:
            return False
        self._reserved += estimated_tokens
        return True

    def settle(self, reserved: int, actual_tokens: int | None) -> None:
        """Release the reservation; charge actual (or the reservation when
        the call failed and the real usage is unknown)."""
        self._roll()
        self._reserved = max(0, self._reserved - reserved)
        self._used += reserved if actual_tokens is None else actual_tokens

    def report(self) -> dict[str, float | int]:
        self._roll()
        return {
            "limit": self.window.limit_tokens,
            "used": self._used,
            "reserved": self._reserved,
            "remaining": self.remaining,
            "utilisation": round((self._used + self._reserved)
                                 / self.window.limit_tokens, 3),
        }


# ------------------------------------------------------------ hedged calls

@dataclass
class HedgeConfig:
    """When and how often to hedge (app-level wiring; hedged_call itself
    takes hedge_after_ms directly)."""
    delay_ms: float = 800.0        # fire request B this long after request A
    max_inflight_per_request: int = 2
    enabled: bool = True


@dataclass
class HedgeResult:
    winner: str                    # "primary" | "hedge"
    value: object
    hedged: bool                   # True when the second call was needed
    wasted_usd_estimate: float = 0.0


async def hedged_call(call, *, hedge_after_ms: float,
                      make_hedge=None) -> HedgeResult:
    """Run `call(label)` for "primary"; if it hasn't finished `hedge_after_ms`
    after starting, also run `make_hedge()` (defaults to another `call("hedge")`).

    `call` is an async callable `label -> awaitable`. The first call to
    COMPLETE WITH A RESULT wins; every other task is cancelled. A call that
    ends in an exception is NOT a winner — if the hedge fails while the
    primary is still running, the primary keeps going and may still deliver;
    the request only fails when EVERY started call has failed (the primary's
    error is preferred when several fail). If the primary itself fails
    before the hedge delay, that exception propagates — hedging buys tail
    latency, not retries; layer 03.8's retry policy outside this. When
    primary and hedge finish in the same event-loop pass, the primary wins
    the tie (it was sent first).

    Cost note: the losing request was still sent and billed (providers bill
    generated tokens). `wasted_usd_estimate` is left for the caller to fill
    from the price table; the mechanism doesn't guess prices.
    """
    primary = asyncio.ensure_future(call("primary"))
    hedge = None
    try:
        done, _ = await asyncio.wait({primary}, timeout=hedge_after_ms / 1000)
        if not done:
            # Primary still running at the hedge delay: launch the hedge.
            hedge = asyncio.ensure_future((make_hedge or call)("hedge"))
        inflight = {primary} | ({hedge} if hedge is not None else set())
        # First SUCCESSFUL completion wins. Failed tasks are skipped while
        # siblings still run, so a dead hedge can't kill a live primary.
        while inflight:
            done, inflight = await asyncio.wait(
                inflight, return_when=asyncio.FIRST_COMPLETED)
            good = [t for t in done
                    if not t.cancelled() and t.exception() is None]
            if good:
                winner = primary if primary in good else good[0]
                for t in inflight | done:
                    if t is not winner:
                        t.cancel()
                label = "primary" if winner is primary else "hedge"
                return HedgeResult(label, winner.result(),
                                   hedged=hedge is not None)
        # Every started call failed — surface the primary's error if it has
        # one, else the hedge's, else a bare RuntimeError.
        for t in (primary, hedge):
            if t is not None and t.done() and not t.cancelled():
                exc = t.exception()
                if exc is not None:
                    raise exc
        raise RuntimeError("hedged_call: every attempt failed")
    finally:
        for t in (primary, hedge):
            if t is not None and not t.done():
                t.cancel()

A demo with fake calls — a slow primary (900 ms) against a fast hedge (200 ms), then the failure edge cases (hedge_demo.py, next to budget.py):

python
# hedge_demo.py — hedged_call against fake providers. Stdlib only.
import asyncio

from budget import hedged_call


def make_call(primary_ms, hedge_ms, primary_fails=False, hedge_fails=False):
    async def call(label: str) -> str:
        ms, fails = ((primary_ms, primary_fails) if label == "primary"
                     else (hedge_ms, hedge_fails))
        await asyncio.sleep(ms / 1000)
        if fails:
            raise RuntimeError(f"{label} exploded")
        return f"answer-from-{label}"
    return call


async def main() -> None:
    print("=== 6. hedged_call: primary slow (900ms), hedge fast (200ms) ===")
    r = await hedged_call(make_call(900, 200), hedge_after_ms=300)
    print(f"winner={r.winner} hedged={r.hedged} value={r.value!r}")
    r = await hedged_call(make_call(50, 200), hedge_after_ms=300)  # fast primary: no hedge
    print(f"winner={r.winner} hedged={r.hedged} value={r.value!r}")

    print("=== 6b. hedged_call edge cases ===")
    r = await hedged_call(make_call(900, 400, hedge_fails=True), hedge_after_ms=300)
    print("hedge fails at ~700ms, primary delivers at ~900ms -> "
          f"winner={r.winner} hedged={r.hedged} value={r.value!r}")
    try:
        await hedged_call(make_call(500, 500, True, True), hedge_after_ms=300)
    except RuntimeError as exc:
        print(f"both calls fail -> RuntimeError: {exc}")


asyncio.run(main())
Output6 lines
=== 6. hedged_call: primary slow (900ms), hedge fast (200ms) ===
winner=hedge hedged=True value='answer-from-hedge'
winner=primary hedged=False value='answer-from-primary'
=== 6b. hedged_call edge cases ===
hedge fails at ~700ms, primary delivers at ~900ms -> winner=primary hedged=True value='answer-from-primary'
both calls fail -> RuntimeError: primary exploded

The second line of 6b is the case the naive version gets wrong: the hedge raised first, but because a failed task is never a winner, the primary kept running and delivered — the request survived a dead hedge. The third line shows the other side: when every started call fails, the primary's exception propagates (a primary that fails before the hedge delay fails the call outright — hedging buys latency, not retries; that's 03.8's job).

When to hedge, and when not to:

Situation Hedge? Why
Interactive feature, p95 latency SLO at risk Yes, tuned delay Tail latency is queue wait, not work
Cheap model call behind an expensive one Prefer escalating only on failure Hedging doubles spend; a cascade doubles only on escalation
Non-idempotent or costly side effects Never without dedup Two calls = two charges, possibly two writes
Provider already rate-limited No — worsens the 429s Hedging adds load exactly when scarce
Bulk/batch work No Latency doesn't matter; cost does

Rules that make hedging safe: idempotent calls only (a read/complete, never a charge or a write), bounded hedge rate (hedge at most X% of requests — track hedged share in metrics, 11A.2), price the waste (each hedge bills a full call — the delay should be set so hedges fire on, say, the slowest 5–10% of requests, tuned from your ttft_ms/latency_ms distributions), and cancel promptly so the loser stops generating (and billing) ASAP — providers bill generated tokens, so an uncancelled loser keeps costing.

6.3 Timeouts, deadlines and cancellation#

Hedging handles slow; timeouts handle stuck. The discipline (03.8 owns retry/timeout mechanics):

  • Per-stage deadlines, not one global timeout: retrieval 500ms, prefill budget by prompt size, decode bounded by output cap ÷ minimum acceptable token rate. A single 60s timeout on a 4-stage pipeline lets one stuck stage eat the whole budget.
  • Deadline propagation: pass the remaining budget downstream; a tool call that starts with 8s left gets 8s, not its own 30s default.
  • Cancellation reaches the provider: closing your HTTP stream tells the provider to stop generating — and billing. The async with + re-raise CancelledError pattern from 03.3, 11.4 is the mechanism; an abandoned stream bills until it ends.

6.4 When a premium tier is the right latency lever#

Before hedging or engineering around latency, check whether the provider sells a faster tier: OpenAI Fast (2×) and Ultrafast (6×, Astra/6.1-Sol only), Anthropic fast mode on Fable 5.2, Opus 5.5, Opus 5 and Opus 4.8 (2× list price on Fable 5.2 and Opus 5.5, research preview on the last two; not available with Batch), Gemini Priority (~1.8×) — all verified on the pricing pages as of November 2026 (Part 8). The math: a 2× tier is worth it when latency_saved × value_of_latency > premium × volume. For a feature where faster answers convert or retain users, it can be the cheapest latency money buys; for internal tools, it's usually waste. Price it per feature.


Part 7: Budgets, quotas and FinOps#

Deep-dive

7.1 Per-request caps#

03.7, Part 12 owns the per-call controls completely: max_output_tokens as the ceiling, the per-request cost guard (worst-case estimate → downgrade or refuse), per-user daily budgets with reserve-then-settle, provider-side spend limits, and the alert catalogue. Don't rebuild them — this lesson adds the tenant and windowed layer on top.

7.2 Token-denominated tenant quotas#

The full treatment of budgets versus quotas, and of reserve-then-settle across a whole organisation, is in 11B.6, Parts 1 to 3; this section is the token-denominated tenant form, with its code.

Per-user USD budgets answer "how much can one user spend?" Tenant quotas answer "how much of the pool can this tenant consume, in tokens, per window?" — the unit that maps to provider rate limits (TPM/TPD) and to showback. budget.py's TenantQuota (in the full file above) is the tested logic — QuotaWindow holds the limit, reserve()/settle()/report() do the accounting; production swaps the store for Redis/Postgres atomic increments. The call pattern:

python
q = TenantQuota(limit_tokens=50_000)          # 50K tokens/day for this tenant

ok = q.reserve(estimated_tokens=12_000)       # input estimate + output cap
if not ok:
    raise QuotaExceeded(q.report())           # deny BEFORE sending — a quota
                                              # checked after the call is a
                                              # report, not a control
# ... run the call, get usage back ...
q.settle(reserved=12_000, actual_tokens=9_800)   # charge ACTUAL, release rest
# on failure/unknown usage: q.settle(12_000, None) keeps the reservation
q.report()   # {"limit": 50000, "used": ..., "reserved": ..., "remaining": ...}

A driver that replays four requests against a 50K-token/day tenant (quota_demo.py, next to budget.py):

python
# quota_demo.py — TenantQuota reserve-then-settle. Stdlib only.
import json

from budget import TenantQuota

q = TenantQuota(limit_tokens=50_000)
print("=== 5. TenantQuota: 50k tokens/day ===")
for estimate, actual in ((12_000, 9_800), (12_000, 11_000),
                         (30_000, None), (12_000, 10_500)):
    if q.reserve(estimate):
        print(f"reserve {estimate:,}: ok (remaining {q.remaining:,})", end="")
        q.settle(estimate, actual)
        print(f" -> settled actual={actual}")
    else:
        print(f"reserve {estimate:,}: DENIED (remaining {q.remaining:,})")
print(json.dumps(q.report(), indent=2))
Output12 lines
=== 5. TenantQuota: 50k tokens/day ===
reserve 12,000: ok (remaining 38,000) -> settled actual=9800
reserve 12,000: ok (remaining 28,200) -> settled actual=11000
reserve 30,000: DENIED (remaining 29,200)
reserve 12,000: ok (remaining 17,200) -> settled actual=10500
{
  "limit": 50000,
  "used": 31300,
  "reserved": 0,
  "remaining": 18700,
  "utilisation": 0.626
}

The third request is denied before sending — that's the point: a quota checked after the call is a report, not a control. The design rules are the ones 03.7, 12.3 and 11B.6 teach in full: reserve the estimate before the call (input estimate + output cap, 11B.6, 2.1), settle the actual from usage, keep the reservation when usage is unknown (11B.6, 3.1), and let in-flight reservations survive a window boundary (here _roll resets _used but not _reserved; 11B.6, 1.4). Window the quota the way you will explain it (per UTC day, per month).

Multi-tenant fairness (one tenant's burst starving the others) is a scheduler concern: 11B.7, 1.3 builds a fair-share limiter and 03.9, Part 5 covers rate-aware throughput. The quota is the accounting.

7.3 Agent budgets#

08A.2, 3.3 owns the in-loop Budget: max_steps, max_output_tokens, max_total_tokens (the honest runaway guard — it counts re-sent input), max_cost_usd, max_seconds, per-tool call caps, loop detection. The cost lesson's note: an agent's quota is consumed per step, not per request — a tenant's daily token budget can be eaten by one runaway 40-step loop. Wire the agent's Budget to the tenant's TenantQuota: reserve the worst-case run (max steps × max tokens) or settle per step; never let an agent draw unboundedly from a shared pool. The organisation-level hierarchy an agent's run budget should draw from is 11B.6, 1.3.

7.4 Chargeback and showback#

"What did engineering spend on LLMs this month?" is a FinOps question, and the trace records already carry the join keys (feature, tenant_hash, prompt_version — 11A.1, 2.6). Those keys are the allocation tags, so set them at span-creation time: you can't allocate spend you didn't tag. In short:

  • Showback (report only): a monthly GROUP BY per feature or tenant. Start here; it's just the waste report grouped by month.
  • Chargeback (bill internal teams): the same numbers plus allocated fixed costs (vector DB, observability) pro-rated by usage share, using the fixed-cost model from 1.4.
  • Unit economics: cost per request, then per user, then per resolved ticket or answer. The last one is the number that matters and the hardest to get: it needs the outcome join from evals and feedback (10A.9, 11A.1 sessions and feedback). The product formula is in 13A.6, 6.2.

The full treatment is in 11B.6, Part 6 (showback, chargeback, which price teams pay, shared-cost allocation, month-end reconciliation) and Part 5 (tags and the providers' attribution units).

7.5 Forecasting and price-change monitoring#

Two forward-looking disciplines:

  • Forecasting: monthly_cost() from 1.5 with your measured RequestProfile and current prices gives the run-rate; forecast_monthly() (the last piece of economics.py) extends it with a compounding growth assumption:
python
# economics.py — forecasting: project monthly cost forward.
def forecast_monthly(requests_per_day: float, monthly_growth: float,
                     profile: RequestProfile, prices: list[Prices],
                     fixed: FixedCosts, months: int = 6,
                     days: int = 30) -> list[dict[str, float | int]]:
    """Project monthly cost forward: requests/day compounds by
    `monthly_growth` (0.05 = +5%/month) while the profile, prices and fixed
    costs stay constant — re-run when any of them change. A forecast is a
    model, not a promise."""
    rows = []
    rpd = float(requests_per_day)
    for m in range(1, months + 1):
        row = dict(monthly_cost(round(rpd), profile, prices, fixed, days))
        row["month"] = m
        row["requests_per_day"] = round(rpd)
        rows.append(row)
        rpd *= 1 + monthly_growth
    return rows

Driver — the §1.5 RAG service (rag, sonnet and fixed from economics_demo.py) at 20k requests/day growing 5% a month:

python
from economics import forecast_monthly   # plus rag, sonnet, fixed as in economics_demo.py

for row in forecast_monthly(20_000, 0.05, rag, [sonnet], fixed, months=6):
    print(f"month {row['month']}: {row['requests_per_day']:,} req/day "
          f"-> ${row['total_usd']:>10,.2f}/mo")
Output6 lines
month 1: 20,000 req/day -> $  5,911.32/mo
month 2: 21,000 req/day -> $  6,179.14/mo
month 3: 22,050 req/day -> $  6,460.34/mo
month 4: 23,152 req/day -> $  6,755.48/mo
month 5: 24,310 req/day -> $  7,065.61/mo
month 6: 25,526 req/day -> $  7,391.27/mo

Six months of +5%/month growth adds ~$1,480/month — compounding is why "it's only 5%" still ends in a budget conversation. Re-run the forecast when traffic or mix changes (a new feature, a model swap, a price change), and pair it with 11A.2's spend alerts (and the burn-rate rule in 11B.7, Part 5) so the forecast meets reality in a dashboard, not a surprise.

  • Price-change monitoring: prices change with effective dates (introductory pricing ends, new tiers appear). 03.7, Part 4 owns the mechanism — prices.yaml with valid_from/valid_to periods and a source URL per row. The operational habit: a scheduled job diffs the providers' pricing pages/catalogue against your table and opens an issue on drift (11C.2 owns the CI shape). A price change you don't notice is a bill shock in 30 days.

The production failures this lesson's machinery exists to catch — symptom first, then cause, then the first check:

Failure Symptom in traces/alerts Likely cause First check → fix
Optimised before measuring Cost lever shipped, bill unchanged Wrong lever for the actual waste Run waste_report.py on real traces first (3.2)
Cheap model + retries costs more attempts > 1 share climbs; cost/request rises Retry amplification on the cheap tier Compare attempts-adjusted cost, not list price (5.4)
Truncation bill shock finish_reason=length share spikes Output cap sized for the old prompt Raise cap or shorten the ask; paid-for unusable output
Hedging doubles spend hedged=true share × unit cost exceeds latency saved Delay tuned to the median, not the p95 tail Retune hedge_after_ms from your ttft_ms/latency_ms distributions; cap hedge rate
Dead hedge kills a live request Requests fail that would have succeeded First-completed task raised; loser cancelled hedged_call skips failed tasks — only propagate when all fail (6.2)
Agent loop eats a tenant's day Quota denials mid-run; budget_exhausted traces Per-step draws from a shared pool Wire agent Budget to TenantQuota; reserve worst-case run (7.3)
Stale price table cost_source=unknown share grows; cost line under-reports New model/tier missing from prices.yaml Unknown is null, never 0 — update the table, then backfill (7.5)
Self-host idle-GPU bill GPU spend flat while request volume fell Fleet provisioned for a peak that moved to the API tier Re-run selfhost_verdict at current demand; utilisation is capacity, not a discount (Part 9)

Part 8: Vendor pricing mechanics to exploit#

Reference

The price map and its modifiers (batch, flex, fast, long context, residency, tokenizer) are owned by 11B.2, Part 2 and 2.5. This part is the exploitation view, and adds the mechanics the price map lacks: gateway fees, free tiers, committed use, introductory-price cliffs and price-change monitoring.

The prices on the pricing page are the list; the mechanics below are where the real bill is set. All verified on the official pages as of November 2026 — the numbers move, the mechanics are durable. 03.7 and 02.9, Part 6 own the per-provider price facts; this table is the exploitation view.

Mechanic What it is How to exploit it Verified as of Nov 2026
Caching discounts Cache reads bill at a fraction of input; writes can cost more Stable-prefix prompt design (04.6, 11B.3); measure hit rate OpenAI cached input $0.01/MTok on luna; Anthropic cache hits 0.05–0.1× input (0.025× on Fable 5.2 and 5.1); Gemini implicit caching on paid tier
Batch discounts ~50% off input+output for async jobs Classify every workload by "can it wait?"; move evals, labelling, backfills to Batch All four providers ~50% (OpenAI, Anthropic, Gemini, OpenRouter :batch)
Flex tier Sync requests at batch-like prices, slower Bulk work needing minutes–hours latency OpenAI, Gemini; OpenRouter :floor
Long-context tiers Whole request repriced above a threshold Trim prompts that sit just over the line; the threshold applies to the whole request OpenAI >272K input; Anthropic Haiku 5.5 >100K prompt (incl. cache tokens)
Regional/data-residency uplifts ~10% premium for in-region inference Use only where residency requires it; don't pay globally for one feature OpenAI +10% (models released on/after 2026-03-05), FedRAMP +10% (OpenAI pricing page, checked 12 November 2026); Anthropic inference_geo multipliers; cloud platforms ~10%
Priority/Fast tiers 1.8–6× price for faster/more reliable serving Per-feature latency SLO math (6.4) OpenAI Fast 2×, Ultrafast 6×; Anthropic fast mode premium (Fable 5.2, Opus 5.5, Opus 5, Opus 4.8; not with Batch); Gemini Priority ~1.8×
Free tiers Free tokens with data-use or rate catches Learning/dev only; never customer data on a training tier Gemini free tier on Flash models (content used to improve our products; the paid tier does not; Gemini pricing page, checked 12 November 2026); OpenRouter :free (20 req/min; 50 req/day, 1,000/day after buying 10 credits; OpenRouter limits page, checked 12 November 2026)
Committed-use / enterprise Volume commitments, provisioned throughput, negotiated rates At scale, negotiate — the list price is the ceiling, not the floor Anthropic Priority Tier commitment (no longer sold per 03.9); Gemini Enterprise provisioned throughput; OpenRouter Enterprise custom
Gateway fees OpenRouter: no inference markup but a fee on credit purchases — 5.5% Standard, 8% Business — plus a separate fee on crypto payments; BYOK 5% of list price above the $25k/mo allowance Factor the fee into cost comparisons; BYOK only beats PAYG above the allowance. Governance: prompts sent through OpenRouter may be routed to third-party providers, so check data policies, retention and ZDR before sending enterprise data Verified on openrouter.ai/pricing + /docs/faq
Introductory pricing Launch prices with end dates Budget at the post-promo price; the cliff is scheduled Gemini 4 Argon $2/$10→$4/$20 on 2026-12-01; 3.8 Flash $0.75/$3.75→$1.50/$7.50 on 2027-01-01; GPT-5.6 Sol promo ends 2026-11-30
Price-change monitoring Prices change; pages are the source of truth prices.yaml periods + a drift-check job (7.5) —

The meta-lesson: the pricing page is an input to your model, not a fact. Every number above has a source URL in prices.yaml; when the page changes, your model should change with it — that's what 03.7, Part 4 built.


Part 9: Build vs buy#

Deep-dive

9.1 The break-even question#

The tokens-per-second break-even formula and a dated utilisation analysis are in 11B.2, Part 8; this section is the requests-per-day calculator in code.

Self-hosting an open-weight model converts variable token spend into fixed GPU-hours. It wins only when your volume is high enough and your utilisation good enough that the fixed cost per request drops below the API's variable cost. economics.py computes it:

python
# The rest of economics.py: the self-host side of the model.
def api_monthly_cost(requests_per_day: int, usage: TokenUsage,
                     prices: list[Prices], days: int = 30) -> float:
    profile = RequestProfile("api", calls=len(prices), usage=usage)
    return request_cost(profile, prices) * requests_per_day * days


def selfhost_monthly_cost(gpu_usd_per_hour: float, gpus: int,
                          days: int = 30,
                          extra_usd: float = 0.0) -> float:
    """GPU-hours billed per month, plus ops extras (monitoring, failover
    capacity, engineering time amortised). You pay for PROVISIONED GPUs —
    utilisation is a capacity constraint, not a cost line (see below)."""
    billed_hours = gpus * 24 * days          # you pay for provisioned GPUs
    return billed_hours * gpu_usd_per_hour + extra_usd


def servable_requests_per_day(gpus: int, gpu_capacity_rpd: float,
                              utilisation: float) -> float:
    """The most requests/day this fleet can sustain at `utilisation`.
    `gpu_capacity_rpd` is requests/day ONE GPU serves at 100% utilisation —
    measure it on your own workload; model size, context length and batch
    size move it by an order of magnitude."""
    return gpus * gpu_capacity_rpd * utilisation


def required_gpus(requests_per_day: int, gpu_capacity_rpd: float,
                  utilisation: float) -> int:
    """Smallest fleet that serves `requests_per_day` at `utilisation`."""
    import math
    return max(1, math.ceil(
        requests_per_day / (gpu_capacity_rpd * utilisation)))


def break_even_requests_per_day(usage: TokenUsage, prices: list[Prices],
                                gpu_usd_per_hour: float, gpus: int,
                                extra_usd: float = 0.0,
                                days: int = 30) -> dict[str, float]:
    """The request volume where self-hosting a FIXED fleet beats the API.

    Utilisation deliberately does NOT appear: it can't move the cost
    crossing (you pay for provisioned GPUs either way) — it decides whether
    the fleet can SERVE the crossing. Check with servable_requests_per_day.
    Returns inf when API cost per request is ~0."""
    api_per_request = request_cost(
        RequestProfile("api", calls=len(prices), usage=usage), prices)
    host_monthly = selfhost_monthly_cost(gpu_usd_per_hour, gpus,
                                         days, extra_usd)
    crossing = (host_monthly / (api_per_request * days)
                if api_per_request > 0 else float("inf"))
    return {
        "break_even_requests_per_day": crossing,
        "api_usd_per_request": api_per_request,
        "selfhost_usd_per_month": host_monthly,
    }


def selfhost_verdict(requests_per_day: int, usage: TokenUsage,
                     prices: list[Prices], gpu_usd_per_hour: float,
                     gpu_capacity_rpd: float, utilisation: float,
                     extra_usd: float = 0.0,
                     days: int = 30) -> dict[str, float | int | bool]:
    """Build-vs-buy at a DEMAND level: the fleet utilisation forces you to
    provision, the monthly cost, and which side wins. This is where
    utilisation actually bites — low utilisation means more GPUs for the
    same demand, which raises the self-host cost per request."""
    gpus = required_gpus(requests_per_day, gpu_capacity_rpd, utilisation)
    host = selfhost_monthly_cost(gpu_usd_per_hour, gpus, days, extra_usd)
    api_per_request = request_cost(
        RequestProfile("api", calls=len(prices), usage=usage), prices)
    api_total = api_per_request * requests_per_day * days
    return {
        "gpus": gpus,
        "servable_rpd": servable_requests_per_day(gpus, gpu_capacity_rpd,
                                                  utilisation),
        "selfhost_usd_per_month": host,
        "api_usd_per_month": api_total,
        "selfhost_usd_per_request": host / (requests_per_day * days),
        "api_usd_per_request": api_per_request,
        "selfhost_cheaper": host < api_total,
    }

A driver for a mid-size feature (3,000 uncached input tokens, 1,500 cached-read tokens and 400 output tokens per request) against Sonnet 5.5 prices, one H100-class GPU at $2.50/hr, $300/mo ops extras, and an illustrative capacity of 30,000 req/day per GPU at 100% utilisation (measure your own — it moves by an order of magnitude with model size, context length and batch) — buildvsbuy_demo.py:

python
# buildvsbuy_demo.py — API vs self-hosted break-even. Stdlib only.
from economics import (Prices, TokenUsage, break_even_requests_per_day,
                       selfhost_verdict, servable_requests_per_day)

sonnet = Prices(input=2.00, output=10.00, cached_input=0.10)
usage = TokenUsage(input=3000, cached=1500, output=400)
GPU_USD_HR, CAPACITY_RPD, EXTRAS = 2.50, 30_000, 300.0

b = break_even_requests_per_day(usage, [sonnet], GPU_USD_HR, 1, extra_usd=EXTRAS)
print("=== 4. Build vs buy: 8B-class model, 1x H100-class GPU ===")
print(f"fixed 1-GPU fleet: break-even at {b['break_even_requests_per_day']:,.0f} req/day "
      f"(${b['selfhost_usd_per_month']:,.0f}/mo vs API ${b['api_usd_per_request']:.5f}/req)")
for util in (0.9, 0.6, 0.2):
    cap = servable_requests_per_day(1, CAPACITY_RPD, util)
    ok = ("break-even reachable" if cap >= b["break_even_requests_per_day"]
          else "1 GPU CANNOT serve it")
    print(f"  util {util:.0%}: servable {cap:>6,.0f}/day -> {ok}")
for util in (0.6, 0.2):
    v = selfhost_verdict(20_000, usage, [sonnet], GPU_USD_HR, CAPACITY_RPD,
                         util, extra_usd=EXTRAS)
    side = "self-host cheaper" if v["selfhost_cheaper"] else "API cheaper"
    print(f"  20k req/day @ {util:.0%} util: {v['gpus']} GPUs, self-host "
          f"${v['selfhost_usd_per_month']:,.0f}/mo vs API ${v['api_usd_per_month']:,.0f}/mo -> {side}")
Output7 lines
=== 4. Build vs buy: 8B-class model, 1x H100-class GPU ===
fixed 1-GPU fleet: break-even at 6,897 req/day ($2,100/mo vs API $0.01015/req)
  util 90%: servable 27,000/day -> break-even reachable
  util 60%: servable 18,000/day -> break-even reachable
  util 20%: servable  6,000/day -> 1 GPU CANNOT serve it
  20k req/day @ 60% util: 2 GPUs, self-host $3,900/mo vs API $6,090/mo -> self-host cheaper
  20k req/day @ 20% util: 4 GPUs, self-host $7,500/mo vs API $6,090/mo -> API cheaper

Read it carefully — the honest version has caveats the calculator can't see:

  • The API price used Sonnet 5.5 as a proxy. A self-hosted 8B-class model is not Sonnet — the quality gap is the real comparison, and it belongs in the eval suite, not the spreadsheet (11C.6, 13A.8).
  • Utilisation is the swing factor — through capacity, not price. The cost crossing for a fixed fleet never moves ($2,100/mo buys you the 6,897 req/day break-even whether the GPU is 20% or 90% busy). What utilisation decides is whether the fleet can serve that crossing — at 20% the one GPU tops out at 6,000/day, below break-even — and, at a fixed demand, how many GPUs you must provision: 20k req/day needs 2 GPUs at 60% utilisation but 4 at 20%, turning a $3,900/mo win into a $7,500/mo loss against the API's $6,090. Self-hosting rewards steady load — bursty traffic needs headroom you'd pay for anyway.
  • $300/mo extras is optimistic. It covers monitoring and failover, not the engineering time to run vLLM, patch it, evaluate each new model release, and keep it secure. 11C.6 prices that honestly.
  • The hidden API costs (eval runs, observability, engineering time) exist on both sides — don't let "self-hosting saves money" mean "self-hosting saves the API bill while adding a platform team."

9.2 The decision frame#

Factor Favours API Favours self-hosting
Volume Below break-even Above break-even, sustained
Utilisation Bursty/uncertain demand Steady, predictable load
Model quality needed Frontier quality required A smaller open model passes your evals
Data residency Provider terms acceptable Must keep data in your VPC
Ops capacity Small team Platform team exists
Model churn Want latest frontier weekly Stable model is fine
Compliance Provider certifications suffice You need your own controls

The hybrid answer is common and usually right: self-host the cheap, high-volume, latency-sensitive slice; API the hard tail. 11B.5 routes between them; 11C.6 runs the local side.

9.3 Energy and carbon: the cost you don't see on the invoice#

Every token costs joules somewhere, and for an applied AI engineer energy is an awareness topic, not a design topic — but three connections to this lesson's material are worth knowing:

  • Self-hosted GPUs spend most of their energy idle. A GPU serving at 15% utilisation burns roughly its full TDP whether it answers one request or a thousand — the same utilisation arithmetic as the break-even calculator in 9.1 is the energy argument. Under-utilised self-hosting is simultaneously a cost and a carbon problem; the fix is the same (batch tighter, consolidate, or go back to the API).
  • API providers' energy claims are mostly unverifiable. Datacentre PUE, renewable mix and per-token energy vary by provider and region, and most providers don't publish auditable per-token figures — treat headline "green" claims as marketing unless a provider publishes methodology you can check. If a regulated-industry disclosure ever needs an energy number (Module 12 owns compliance), that's a procurement question, not something you can derive from your own metrics.
  • The playbook's cost levers are the energy levers. Smaller models, caching, batch tiers, quantisation and routing easy traffic down-tier all reduce joules per answer exactly as they reduce dollars per answer — the frontier model you only call when needed is also the smaller carbon footprint.

If you want order-of-magnitude context, there is exactly one auditable provider figure at the time of writing: Google's paper Measuring the environmental impact of delivering AI at Google Scale (August 2025) reports 0.24 Wh for the median Gemini Apps text prompt, counting the whole serving stack (accelerators, host machines, idle capacity and datacentre overhead; an accelerator-only count gave 0.10 Wh, 2.4× lower). Read it as what it is: a median for one product's short text prompts, measured by the provider on its own hardware, and more than a year old. Long-context, reasoning-heavy and agentic calls are different workloads and no comparable published figure exists for them, so don't multiply 0.24 by your token counts and call it a footprint. The engineering-relevant question is fleet-scale: millions of calls a day makes utilisation and model choice matter again.


Common misconceptions#

Misconception Reality
"Cost per request is tokens × list price." It's tokens × effective price × attempts × calls × multipliers. Retries, reasoning, history compounding and tier uplifts all multiply it (1.3).
"The cheapest model is the cheapest option." Only if it passes your evals and doesn't retry more. A cheap model with 20% retry rate can cost more than a dear one with 1% (Part 5).
"Caching always saves money." Cache writes can cost more than input; explicit caches bill storage; a broken prefix wastes the write. It's a break-even calculation (03.7, Part 11, 11B.3).
"Batch is half price, so use it for everything." Only work that can wait ~24h. User-facing features on batch are a product failure, not a saving (4.5).
"Streaming makes it faster." Streaming hides decode time; it doesn't reduce TTFT. Measure both (2.2).
"Hedging is free latency." Every hedge bills a full call. Hedge the tail, not the median, and only idempotent requests (6.2).
"Self-hosting is cheaper at scale." Only past the break-even and at high utilisation. Below it, you're paying GPU-hours for idle capacity (Part 9).
"Optimise cost first, measure quality later." Every cost lever is a behavioural change. The eval gate comes with the change, not after (Part 5).
"The pricing page is the price." It's the list. Tiers, uplifts, fees, introductory cliffs and gateway margins set the real bill (Part 8).
"p50 latency is the latency." Users feel p95/p99. The queue, not the median call, generates the tail (2.3).

Key takeaways#

  • Two bills: variable (tokens by type × effective price × multipliers) and fixed (infra, observability, people). Optimise them differently; know which dominates at your scale.
  • Measure before you optimise: baseline cost/latency distributions from traces, then the waste report ranks mechanical fixes before you touch models.
  • The playbook is ordered: remove waste → cache → tier models → reasoning budgets → batch/flex → parallelism/streaming → speculative/early-exit → retrieval sizing → regional/connection → self-host. Each has a boundary lesson; this lesson owns the economics.
  • Quality is the constraint: every cost lever ships through an eval gate; the cost-quality frontier and regression budget make the trade explicit.
  • Latency is two problems: TTFT (prefill + pre-model path) and total (decode + steps). Streaming fixes felt latency; hedging fixes tail latency at a priced cost.
  • Quotas are controls, not reports: reserve-then-settle before the call, in the unit that maps to provider limits (tokens).
  • The pricing page is an input: exploit caching, batch, tiers, uplifts and commitments — and monitor for changes, because the bill you budgeted is the bill that was true last month.
  • Self-hosting is a fixed-cost bet: it wins only above break-even at high utilisation; the hybrid (local for cheap/high-volume, API for the tail) is usually the right answer.

Terms introduced in this lesson#

Term One-line definition
Cost model The equation (and its fixed-cost counterpart) that turns a workload shape into a dollar estimate
Latency model The additive per-stage breakdown of where request time goes, split into TTFT and total
Hidden multiplier A factor that multiplies the naive per-call cost: retries, truncation, fallbacks, reasoning, history, agent steps
Cost-quality frontier The Pareto set of configurations trading eval score against cost per request
Acceptable-regression budget The policy on how much quality may be traded for cost, per feature
False saving An optimisation that cuts the cost dashboard but loses on business metrics (retries, re-asks, escalations)
Hedged request A second identical request fired after a delay; first to finish wins, loser is billed anyway
Token-denominated quota A per-tenant token budget per window, reserve-then-settle, in tokens not dollars
Chargeback / showback Allocating LLM spend to internal teams as bills / as reports
Unit economics Cost per request → per user → per resolved outcome
Break-even (API vs self-host) The request volume where self-hosted GPU cost drops below API variable cost
Utilisation The fraction of provisioned GPU-hours actually serving requests; the swing factor in self-hosting economics
FinOps for AI The discipline of forecasting, attributing, budgeting and governing LLM spend
Service tier A provider's price/latency trade for the same model: batch, flex, standard, priority/fast
Long-context surcharge A repricing of the whole request once input crosses a threshold (the mechanic the pricing pages call a long-context tier)

All terms are also collected in the glossary.


Exercises#

  1. Cost model: using economics.py, model your own feature's RequestProfile (calls, tokens, other costs, retries). What dominates — input, output, or fixed costs? At what request volume does the answer change?
  2. Waste report: generate a traces.jsonl fixture (the format is in 11A.1, 2.6) with a deliberately wasteful pattern — high retry rate, truncated outputs, zero cache reads — and run waste_report.py. Which signal fires first, and what lever from Part 4 addresses it?
  3. Hedging: in hedged_call, the loser is cancelled, but the provider may already have billed the input and the output generated so far. Extend HedgeResult to carry tokens_billed for both calls and compute the true cost of a hedge at your prices. At what hedge rate does the latency win stop paying for itself?
  4. Quotas: give TenantQuota a second window (per-minute burst on top of per-day) and a fair_share report across tenants. What's the concurrency-safe production version (Redis INCRBYFLOAT + check)?
  5. Break-even: using break_even_requests_per_day and selfhost_verdict, sweep utilisation from 10% to 90% for your workload (pick a gpu_capacity_rpd and say why). For each utilisation: how many GPUs does your demand need, what's the monthly self-host cost, and does it beat the API? At what utilisation does self-hosting become viable for your traffic?
  6. Frontier: pick three configurations for one feature (e.g. sonnet+full context, haiku+trimmed, sonnet+cascade). Run your eval suite on each (or reason about it), build the cost-quality frontier table, and mark which are dominated.
  7. Tiers: classify every workload in a hypothetical product (chat, nightly summariser, eval suite, data labelling, real-time assistant) by "can it wait?" and assign batch/flex/standard/priority. Which did you get wrong on first instinct?
Hints for the exercises
  1. For the §1.5 RAG profile, variable cost equals the $555 fixed cost at about 555 ÷ (0.008927 × 30) ≈ 2,070 requests a day; below that, fixed costs dominate. Change retries, output or cached one at a time and watch which line moves the total most.
  2. Edit make_fixture.py (raise the attempts and finish_reason="length" shares, set cached to 0). The checklist prints its signals in a fixed order (retries, truncation, errors, long context, missed cache), so "first" means first in the list; the levers are 03.8's retry policy, a larger output cap or shorter ask (4.1), and prefix caching (11B.3).
  3. A hedge that loses has already been sent: assume its whole input plus the output generated before cancellation was billed. Extra spend per request ≈ hedge rate × cost of one call; the latency win pays only while the value of the faster p95 (for example fewer abandoned requests) exceeds that. With a 5% hedge rate you pay about 5% more on the call line, with 30%, about 30% more.
  4. Two windows are two TenantQuota objects: reserve in the minute window first, then the day window, and release the first reservation if the second refuses. For Redis, tokens are integers, so INCRBY suffices (INCRBYFLOAT is for dollars): increment, compare with the limit, DECRBY and deny if over, with EXPIRE set to the window length; a Lua script makes the check-and-increment atomic. fair_share is each tenant's used divided by the sum over all tenants.
  5. With the lesson's illustrative 30,000 requests/day per GPU, $2.50/hour, $300 extras and 20,000 requests/day against Sonnet 5.5 prices, the fleet is 7 GPUs at 10% utilisation ($12,900/month), 4 at 20% ($7,500), 3 at 30% ($5,700), 2 at 40-60% ($3,900) and 1 at 70-90% ($2,100), against an API bill of $6,090; so self-hosting becomes viable at about 30% utilisation, for these made-up numbers. Replace the capacity with a figure you measured before you trust the answer.
  6. A configuration is dominated if another one is at least as good on quality and cheaper (or equal cost and better quality). Keep sample sizes in the table: a 1-point difference on 30 eval cases is noise.
  7. A typical first-instinct mistake is leaving eval suites and labelling on the standard tier; they are classic batch work. Chat and the real-time assistant are standard (priority only if the latency SLO maths of 6.4 pays), the nightly summariser is batch, and bulk work that needs results within the hour is flex.

Check yourself#

  1. What's the difference between variable and fixed cost in an LLM feature, and which dominates at low vs high traffic?
  2. Why is output usually the expensive token, and what makes reasoning tokens surprising?
  3. Name four hidden multipliers that make "tokens × list price" wrong.
  4. Why does an agent run cost ~15× a RAG request on the same model?
  5. What's the difference between TTFT and total latency, and which levers fix each?
  6. Why is queueing the stage everyone forgets, and what does Little's law predict?
  7. What three distributions do you need before optimising, and what does the waste report measure?
  8. List the ten levers of the playbook in order, and name the lesson that owns each boundary.
  9. Why must every cost lever go through an eval gate, and what's an acceptable-regression budget?
  10. When is hedging worth its cost, and when is it never safe?
  11. What's the difference between a per-request cost cap and a token-denominated tenant quota?
  12. Why does self-hosting only win above a break-even, and what two factors dominate that calculation?
  13. Which vendor pricing mechanics can reduce your bill below list price, and which increase it?
  14. What are the hidden costs of self-hosting that the break-even calculator can't see?

Further resources#


← Module 11A: Observability and AgentOps | Module 11B overview | 11B.2 — Tokenomics: The Unit Economics of LLM Applications →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close