AI EngineeringZero to ProductionHome·About·What’s new·Contact
Enterprise & Leadership · Part 3

FinOps for AI at scale

An AI feature with a great demo and unknown unit economics is a liability, not a product. This lesson is FinOps for LLM features: the discipline of knowing the cost per successful request, attributing spend to teams and features, enforcing token budgets and quotas, capturing the ROI of caching and batching, running showback / chargeback, and forecasting spend before finance is surprised. The methods are durable; every price is illustrative and must be verified against current vendor pricing.

⏱️ ~90 min🏢 Org / decision layer🎯 Lead / staff

Learning objectives

  • Compute the unit economics of an LLM feature: cost per request and cost per successful request.
  • Attribute spend with tagging so you know which team, feature, and customer drives cost.
  • Set and enforce token budgets and quotas that protect margin without breaking the product.
  • Quantify the ROI of caching and batching instead of assuming they help.
  • Run showback / chargeback to change behavior, and forecast spend to avoid surprises.
Honesty note on pricesFinOps methods are stable. Every per-token rate, discount, and dollar figure below is illustrative and moves constantly — verify against the current vendor pricing page before you put a number in a budget. Anthropic and other providers publicly document features like prompt caching and batch processing; confirm current mechanics and discounts in their docs.

1 · Unit economics — the only number that matters

Start with a scene you've watched play out. A team ships an AI feature. The demo is dazzling, adoption climbs, everyone celebrates — and then, two months later, the cloud invoice arrives and nobody can say whether the feature makes money or loses it. They know the total bill. They cannot tell you what a single answer costs, or whether that cost is smaller than the value it creates. That gap is not a rounding error; it is the difference between a product and a very expensive science project.

Here is the mental model that fixes it. Think of your LLM feature like a factory that makes one thing: a successful answer. A factory owner doesn't brag about the price of raw steel or the number of times a machine cycled — they care about the all-in cost of one finished, sellable part, including the scrap. FinOps for AI is the same discipline pointed at tokens: the only number that lets you reason about margin is the fully-loaded cost of one answer a user actually kept.

That's why the foundational metric is cost per successful request — and why the two obvious alternatives quietly lie to you. Cost per token is an input, like the price of steel: it tells you nothing about how many tokens a real answer burns or how often you throw the part away. Cost per API call is closer but still deceptive, because it counts every retry and every failed attempt as if it delivered value. The most common mistake in AI FinOps is exactly this: a dashboard proudly reports a low cost-per-call, leadership relaxes, and nobody notices that a fifth of those calls were retries or answers the user immediately rephrased. You were measuring the machine cycling, not the parts you sold.

So the formula deliberately divides by the fraction of calls that succeeded — because the wasted calls don't vanish from the bill, they get absorbed into the cost of the answers that worked. Pair that unit cost with the value (revenue, deflected support ticket, hour saved) each successful answer creates, and you finally have the one figure an executive can act on: the feature's margin. Everything else in this lesson — tagging, budgets, caching, forecasting — exists to move or protect this single number.

The foundational FinOps metric for an AI feature is cost per successful request. Not cost per token (an input), not cost per API call (ignores retries and failures) — cost per request that actually delivered value. The formula is deliberately blunt:

Cost per successful requestcost_per_success = (input_tokens·in_rate + output_tokens·out_rate + retries + tool_calls) / success_rate. The ÷ success_rate is the part teams forget: if 20% of requests fail or get retried, your true cost per useful answer is ~25% higher than the naive per-call price. A feature can be profitable per call and unprofitable per success.

Output tokens usually dominate because output rates are typically higher than input rates and generation is where length balloons. This single fact drives most cost wins: cap and shape output, and you move the biggest lever. Tie the unit cost to the revenue or value per request and you have the feature's margin — the number an exec actually needs.

what you paid for (raw calls) success retry rephrased only green delivered value — you paid for all three cost_per_call total spend ÷ all calls (lies) cost_per_success = cost_per_call ÷ success_rate ÷ 0.80 success ⇒ ~25% higher than the naive figure The wasted calls don't leave the bill — they get absorbed. Dividing the raw per-call cost by the success rate reveals the true cost of one answer a user actually kept.
🗺️ How to read this diagram

Read top-to-bottom: the calls you paid for, then the two ways to count them.

  • The top row is every call you were billed for: one green success plus a red retry and a rephrased (soft-failed) call that delivered nothing.
  • The left blue box is cost_per_call — total spend spread over all calls, which flatters you because it treats the red boxes as if they worked.
  • The amber box on the right is the honest number: dividing by success_rate (the arrow) pushes the figure up — at 80% success, about 25% higher.

In short: per-call cost hides failures; per-success cost charges them to the answers that actually worked.

2 · Cost attribution — tag everything

Picture the meeting nobody enjoys. The AI bill jumped 40% this month and the VP wants to know why. You open the provider console and find… one number. A single line item: "model usage." No breakdown by team, feature, or customer. You can see that spend happened; you have no idea where. So the honest answer is a shrug, and the next hour is spent guessing. That shrug is the single most common failure in AI cost management — not a rate that's too high, but spend you cannot explain.

The analogy that makes it click: imagine running a shared office and getting one combined electricity bill for the whole building with no sub-meters. You know the total went up. Was it the server room? The new team on the third floor? Someone leaving the AC on all weekend? Without meters on each circuit, you can only argue, never fix. Tagging is installing the sub-meters. Every request carries a little label — which team, which feature, which environment, which customer, which model — so that when the bill arrives, a mystery becomes a query.

Why these particular tags, and not a hundred others? Because each one answers a question that leads directly to an action, and that's the test a tag must pass — a label you'll never slice by is just noise. Team and feature tell you who owns the spend and which product line drives it, so you can bill it back or kill a low-ROI feature. Environment catches the classic leak of burning production-priced money in dev and staging. Tenant (hashed, so you keep the cost signal without storing raw customer identifiers) reveals which customers are expensive enough to need a price tier or a quota. Model shows where you're paying frontier rates for work a cheaper model could do.

The mistake to avoid is treating tagging as a nice-to-have you'll add "once things settle." Attribution is not an optimization — it is the precondition for every optimization. If your first tagging pass comes back and 60% of spend has no label, that untagged blob is your finding: you fix attribution before you touch anything else, because tuning a system you can only see 40% of is guessing with extra steps.

You cannot manage what you cannot attribute. Every request should carry metadata that lets you slice spend after the fact: team, feature, environment (prod/dev), customer/tenant (or a hashed id), and model. Without tagging, a spend spike is a mystery; with it, it's a query.

no tags model usage $1 line item — why? 🤷 tag every request team feature env tenant_hash model cost_usd now: GROUP BY any dimension → a query, not a shrug Tagging installs the sub-meters. The same spend, labelled at the source, turns an unexplainable invoice into something you can slice by team, feature, environment, tenant, or model.
🗺️ How to read this diagram

Read left-to-right: the invoice you fear, then the request that fixes it.

  • The red block on the left is the default failure — one opaque "model usage" line with no way to answer "where did it go?"
  • The arrow is the fix: attaching metadata to every request so the cost record carries who/what/where.
  • The grid on the right is the tag set — team, feature, env, tenant_hash, model — plus the computed cost_usd (green) that each label can now be grouped by.

In short: attribution is the precondition for every optimization — tag first, tune second.

TagAnswers the questionFinOps action it enables
teamWho owns this spend?Showback / chargeback
featureWhich product line drives cost?Kill or optimize low-ROI features
environmentAre we burning prod money in dev?Cap non-prod aggressively
tenantWhich customers are expensive?Price tiers, quota per plan
modelIs a cheaper model viable here?Route by task difficulty
Untagged spend is the default failureThe most common enterprise AI-cost problem isn't a high rate — it's a single line item on the invoice with no breakdown. If your first tagging pass reveals that 60% of spend is untagged, that is the finding: fix attribution before you optimize anything, or you'll optimize blind.

3 · Budgets, quotas, and model routing

Here's the failure this section prevents. A dependency starts timing out at 2 a.m. Your agent, dutifully, retries. The retry also fails, so it retries again — a tight loop, each pass paying full price for tokens, thousands of times an hour, while everyone sleeps. By morning a single misbehaving code path has spent a month's budget. Nobody chose to spend that money; there was simply nothing standing between the code and the credit card. Attribution would tell you afterward where the money went. Budgets, quotas, and routing are what stop it going there in the first place.

Think of it like the controls on household spending. A token budget is your monthly spending limit — a soft alert when you're getting close, a hard cap when you've hit it — scoped per tenant or per feature so one heavy user can't drain the shared pool. A rate quota (requests per minute) is the circuit breaker: it doesn't care about the monthly total, it just refuses to let any single source fire absurdly fast, which is exactly what kills a runaway retry loop before it does real damage. And model routing is buying the right tool for each job instead of the most expensive tool for every job.

Routing deserves a moment because it's the most leverage for the least pain. Most requests are easy — a short classification, a lookup, a reformat — and a cheaper, faster model handles them perfectly well. A minority are genuinely hard and need the frontier model's reasoning. If you send everything to the frontier model "to be safe," you're paying premium rates on traffic that never needed them. A cheap classifier or a simple heuristic (length, whether a tool is required, task type) labels each request easy or hard and routes accordingly, falling back to the frontier model only when the cheap one's quality check fails. The quiet bonus: because routing lowers the average cost per request, it also slows how fast tenants burn their budget — the two controls reinforce each other.

The mistake to avoid is imagining the hard cap as a simple on/off switch an engineer flips. What happens when a paying customer hits their cap? Silence and errors look exactly like an outage, and the support cost of that surprise can dwarf whatever you saved. The cap is a product decision — degrade to a cheaper model, queue the work, or refuse with a clear message — made with product and honoring the contract, not a value quietly hard-coded in a config file.

Attribution tells you where money goes; budgets and quotas stop it going somewhere bad. Three complementary controls: a per-tenant/per-feature token budget (soft alert, hard cap), a rate quota (requests per minute) to stop runaway loops, and model routing that sends easy requests to a cheaper model and reserves the frontier model for hard ones. The flow below shows a request passing these gates.

Request arrives Budget check under budget? Route request cheap vs frontier Cache lookup hit? Model call if needed Meter + tag for showback
🗺️ How to read this diagram

Follow it strictly left→right: one request enters on the far left and moves through a row of six gates before any money is spent, ending at the meter on the right.

  • The leftmost box, Request arrives, is the incoming call; the brand-coloured arrow carries it into the first control rather than straight to the model.
  • The middle boxes are the cost gates in order — Budget check (under budget?), Route by difficulty (cheap vs frontier), and Cache lookup (hit?) — each arrow only passes the request on if that gate lets it through, and a cache hit can short-circuit the call entirely.
  • The payoff is the last pair: Model call runs only "if needed," and every request finally lands on Meter + tag "for showback" — so usage is attributed no matter which path it took.

In short: a request passes the budget, routing, and cache gates before the model runs, and is metered and tagged on the way out.

A hard cap is a product decision, not a switchWhen a tenant hits a hard budget cap, what happens? Degrade to a cheaper model, queue, or refuse with a clear message — but decide this with product, because it's a UX and contract question, not just an engineering one. A silent failure at the cap is the worst option: it looks like an outage and generates support cost that dwarfs the savings.

4 · Caching & batching — ROI, not folklore

You've probably heard the confident advice. Someone in a review says "just add caching, it'll cut costs," and everyone nods because it sounds obviously true. Three weeks later the cache is live, the bill hasn't moved, and there's a new layer of infrastructure to maintain. The advice wasn't wrong in general — it was applied without checking whether this workload had the property that makes caching pay. Caching and batching are two of the largest cost levers in AI, and both are widely available, but neither delivers savings by being switched on. They deliver savings only when the workload's numbers cooperate — which is why this section is called ROI, not folklore.

Start with the intuition behind each. Caching is "don't pay twice for the same work." There are two flavors. An exact-response cache is a photocopier: the identical question comes in, you hand back the answer you already generated, and you skip the model entirely. That only helps to the degree that questions actually repeat — great for a popular FAQ, useless for a stream of unique long-tail prompts. Prompt caching is subtler and often more powerful: when many different requests all begin with the same large stable prefix — a big system prompt, a shared set of documents — you can have the provider bill that reused prefix at a reduced rate instead of full price on every call. It's like a restaurant prepping a base sauce once each morning rather than from scratch per plate: the shared part gets cheaper, the per-order part stays custom.

Batching is a different trade entirely — you give up latency to get a lower rate. Submit many requests together as an offline job and the provider can schedule them efficiently and charge less. That's a bargain for latency-tolerant work like nightly evals, backfills, or bulk enrichment, and a non-starter for anything a user is waiting on in real time. Anthropic, for instance, publicly documents both prompt caching and a Message Batches path; the mechanics and the exact discounts move, so confirm the current numbers in the provider's docs before you put them in a model.

The discipline — and the mistake to avoid — is celebrating before you measure. A cache with a 5% hit rate saves about 5% and adds complexity you'll maintain forever; that's often a net loss. Prompt caching pays off only when the reused prefix is genuinely large and genuinely reused before it expires — if the "stable" prefix actually changes every request, the saving evaporates. So you compute it honestly: saving = hit_rate × cost_of_avoided_work − overhead, compared against doing nothing. "Cache everywhere" is folklore; "cache the big reused prefix, because the hit rate says so" is FinOps.

Two of the biggest cost levers are caching (don't pay twice for the same work) and batching (trade latency for a lower rate). Both are widely available — Anthropic publicly documents prompt caching and a batch/Message Batches path — but neither is free ROI; you must measure.

Exact-response cache repeat? → skip model saves only the repeats real if hit_rate high ~0 on long-tail Prompt caching prefix tail reused prefix billed cheap every call, if reused ~0 if prefix varies Batching latency → lower rate offline jobs only evals, backfills not for interactive saving = affected_fraction × avoided_cost − overhead — measure before you ship Three levers, three preconditions. Each saves money only when the workload has the matching property — repeats, a stable reused prefix, or latency tolerance.
🗺️ How to read this diagram

Scan the three panels left-to-right; each shows what a lever saves (green) and when it doesn't (red).

  • Exact-response cache skips the model entirely for identical repeats — great at a high hit rate, near-zero on unique long-tail prompts.
  • Prompt caching splits each request into a reused prefix (green, billed cheap) and a custom tail — it pays on every call, but only if the prefix is genuinely large and stable.
  • Batching is the amber trade: give up latency to get a lower rate, which fits offline jobs but never interactive traffic.

In short: "cache everywhere" is folklore; compute saving = affected_fraction × avoided_cost − overhead per lever before shipping.

LeverHow it savesWhen ROI is realWhen it isn't
Exact-response cacheSkip the call for repeated identical requests.High repeat rate (FAQs, popular queries).Long-tail unique requests — near-zero hit rate.
Prompt cachingReuse a large stable prefix (system prompt, docs) across calls at a reduced rate.Big shared context reused often.Tiny or constantly-changing prompts.
BatchingSubmit many requests together for a lower rate.Latency-tolerant offline jobs (evals, backfills, enrichment).Interactive, latency-sensitive requests.
Measure hit rate before you celebrateA cache with a 5% hit rate on a long-tail workload saves ~5% and adds complexity — often not worth it. Prompt caching pays off only when the reused prefix is large and reused frequently before it expires. Compute the actual saving: saving = hit_rate × cost_of_avoided_work − cache_overhead, and verify current caching/batch discounts in the provider's docs before modeling them.

5 · Showback, chargeback, and forecasting

Consider two ways to change how a team spends. In the first, at the end of each month you send every team a report: "here's what your AI usage cost." They can read it or ignore it; nothing lands on their budget. In the second, that same cost is actually deducted from the team's budget — real money, out of a pool they had other plans for. The first is showback; the second is chargeback. The distinction sounds like accounting trivia, but it's the whole psychology of cost control: visibility makes people aware; a bill on their own budget makes them act. A team that merely sees a number tends to keep doing what it was doing; a team whose budget shrinks when it's wasteful suddenly cares about that bloated prompt.

There's a sequencing trap here, though. Chargeback is more powerful precisely because it's real money — which means the moment the numbers look wrong, the conversation stops being about saving money and becomes an argument about your accounting. If your attribution is shaky (remember the untagged-spend problem from §2), turning on chargeback too early buys you months of disputes instead of savings. So the rule is: showback first to build trust in the numbers, chargeback only once the attribution is solid enough that nobody can credibly contest their line.

Forecasting is the third piece, and it exists to kill the surprise. Finance can absorb a rising AI bill; what it cannot forgive is a rising bill nobody warned them about. The naive forecast — "last month times some growth factor" — is a shrug dressed up as a projection, and it falls apart the moment someone asks why. The credible forecast is built bottom-up from the unit economics you established in §1: for each feature, projected_requests × cost_per_success, summed across the portfolio, plus an explicit line for each planned launch. Now every dollar in the projection traces back to a product number.

That traceability is the entire payoff, and it's why forecasting closes the loop this lesson opened. When an exec asks "why is next quarter's AI bill up 40%?", the bottom-up forecast lets you answer "the new sales-drafter feature at its projected 150k requests a month" — a specific, defensible, product-linked cause — instead of the shrug you started with in §2. Unit economics, attribution, budgets, and caching all feed this final number; getting it right is what turns FinOps from a cleanup exercise into a planning tool.

Showback shows each team what its AI usage costs (visibility, no bill). Chargeback actually bills it to their budget (accountability, real incentive). Showback changes awareness; chargeback changes behavior — but chargeback needs trustworthy attribution first, or you'll spend more time arguing about the numbers than saving money. Forecasting projects spend from usage trends and launch plans so finance sees the curve before it bends.

Tagged usage from §2 attribution Showback sees its cost → awareness Chargeback billed to budget → behavior Forecast Σ req × $/success needs solid tags first Visibility makes people aware; a bill makes them act. All three outputs draw on the same tagged usage — but chargeback and a credible forecast both depend on the attribution being trustworthy first.
🗺️ How to read this diagram

Follow the arrows left-to-right from the shared source into the three things you do with it.

  • The left box is the tagged usage from §2 — the single source all three outputs feed on.
  • Showback (top) just shows a team its number → awareness; Chargeback (middle, amber) deducts it from the team's budget → behavior change.
  • The amber "needs solid tags first" note points back at chargeback: turn it on before attribution is trustworthy and you buy disputes, not savings. Forecast (bottom) sums projected_requests × cost_per_success from §1.

In short: same tagged data, three uses — showback to build trust, chargeback to change behavior, forecast to kill the surprise.

Forecast bottom-up from unit economicsThe credible forecast isn't "last month × growth." It's Σ(feature: projected_requests × cost_per_success), plus a line for each planned launch. That ties the finance number directly to product plans, so when someone asks "why is next quarter's AI bill up 40%?" the answer is "the new feature X at its projected volume," not a shrug.

✓ Checkpoint — you can move on when you can…

  • Compute cost per successful request and explain why dividing by success_rate matters.
  • List the five tags every request should carry and one action each enables.
  • Choose between soft alert, hard cap, degrade, and queue for a tenant that exceeds budget.
  • Decide whether caching or batching is worth it for a given workload, using hit rate / latency tolerance.
  • Explain the difference between showback and chargeback and what must be true before chargeback works.
✓ Knowledge check

A feature's dashboard shows $0.006 per API call and leadership is happy. You look closer and find a 15% retry rate and a 30% of answers that users immediately rephrase (a soft failure). What's the real unit cost story, and what do you report?

Show answer
The $0.006 per call hides the true cost per successful request. Retries inflate the call count, and the 30% rephrase rate means those calls didn't deliver value — they're failures that also generated a second paid call. Roughly, if only ~70% of calls succeed and 15% are retried, the cost per useful answer is materially higher than $0.006 (you paid for the retries and the failed first attempts). Report cost per successful request, not per call, and flag the rephrase rate as both a quality and a cost problem — fixing the failure mode cuts spend and improves UX at once. Verify the exact rates against current pricing and your logs.
✓ Knowledge check

An engineer proposes adding prompt caching everywhere to cut costs. Under what conditions will this actually save money, and when could it add cost or complexity for little gain?

Show answer
Prompt caching saves money when a large, stable prefix (a big system prompt or a shared document set) is reused frequently within the cache's lifetime, because you pay a reduced rate on the cached portion instead of full price every call. It helps little — or adds complexity/overhead — when prompts are small, when the 'stable' part actually changes every request, or when the same prefix is rarely reused before it expires. The discipline: measure the reuse rate and prefix size, compute saving = reuse × cached_prefix_cost_delta − overhead, and confirm the current caching mechanics and discount in the provider's docs. "Cache everywhere" is folklore; "cache the big reused prefix" is FinOps.

🪜 Practice ladder beginner → industry

Six graded exercises, easy to real-world. Try each before opening its solution.

Exercise 1 · Compute cost per successful requestBeginner

Context: Unit economics is the first FinOps reflex; everything else builds on it.

Your task: Given usage numbers for a feature, compute cost per call and cost per successful request.

Requirements:

  • Input: 800 input tokens, 400 output tokens per call (verify rates against current pricing)
  • Assume in-rate $3 / M tokens, out-rate $15 / M tokens (illustrative)
  • Success rate is 80% (20% fail or are retried)
  • Report both cost-per-call and cost-per-success and explain the gap

💡 Hint: cost_per_call = in·in_rate + out·out_rate; then ÷ success_rate.

Show solution

Per call (illustrative rates — verify current pricing): input = 800/1e6 × $3 = $0.0024; output = 400/1e6 × $15 = $0.0060; per call = $0.0084.

Per successful request: $0.0084 / 0.80 = $0.0105 — about 25% higher than the per-call figure.

The gap explained: one in five calls doesn't deliver a useful answer but still costs money (a failure or a retry), so the cost of each useful answer absorbs those wasted calls. Notice output is 71% of per-call cost — capping/shaping output is the biggest single lever here.

Exercise 2 · Design the request tagging schemaIntermediate

Context: You can't manage what you can't attribute; tagging is the enabling infrastructure.

Your task: Design the metadata schema attached to every request and show one spend query it unlocks.

Requirements:

  • List the required tags and their types
  • Show how a hashed tenant id preserves privacy while enabling per-customer cost
  • Write one aggregation (pseudo-SQL) that finds the most expensive feature
  • State what you'd do first if 60% of spend came back untagged

💡 Hint: Tags travel with the usage record so cost can be grouped by any dimension later.

Show solution

Schema (per request usage record):

  • team (string), feature (string), env (prod|staging|dev), tenant_hash (sha256 of tenant id, truncated), model (string)
  • input_tokens, output_tokens, retries, success (bool), cost_usd (computed)

Privacy: hashing the tenant id lets you compute per-customer cost and spot expensive tenants without storing raw customer identifiers in the FinOps store.

Query — most expensive feature: SELECT feature, SUM(cost_usd) c FROM usage WHERE env='prod' GROUP BY feature ORDER BY c DESC LIMIT 5;

If 60% is untagged: stop optimizing and fix attribution first — instrument the untagged call sites, because any optimization on 40% visibility is guesswork.

Exercise 3 · Build a budget + quota + routing controlAdvanced

Context: Attribution finds the spend; budgets and routing keep it in bounds.

Your task: Design the enforcement for a per-tenant token budget with a soft alert and hard cap, plus difficulty-based model routing.

Requirements:

  • Define soft-alert (e.g. 80%) and hard-cap (100%) behavior
  • Decide what happens at the hard cap and justify it with product
  • Define the routing rule that sends easy vs hard requests to different models
  • Note how routing interacts with the budget

💡 Hint: Cheap model for easy requests both saves money and slows budget burn.

Show solution

Budget states. Track cumulative tokens per tenant per billing period. At 80%: soft alert to the tenant + account owner (no behavior change). At 100%: hard cap.

Hard-cap behavior (decided with product): degrade, don't fail — route remaining requests to the cheaper model and add a clear notice, rather than returning errors. Refusing outright looks like an outage; degrading preserves the product and margin. Enterprise plans may instead queue or allow overage-billing per contract.

Routing rule. A cheap classifier (or heuristic: length, presence of tool need, task type) labels each request easy|hard. Easy → cheap model; hard → frontier model. Fallback to frontier only if the cheap model's confidence/quality check fails.

Interaction: routing reduces average cost per request, which slows budget burn, so tenants hit the cap later — routing and budgeting reinforce each other rather than competing.

Exercise 4 · Model the ROI of a caching strategyExpert

Context: Caching is assumed to help; a lead proves it with a number before shipping complexity.

Your task: Model the ROI of two caching strategies for a workload and recommend one.

Requirements:

  • Workload: 1M req/month, of which 12% are exact repeats and 100% share a large system prompt
  • Strategy A: exact-response cache. Strategy B: prompt caching on the shared prefix
  • Estimate savings for each and net out cache overhead
  • Recommend, and state what measurement would change the call

💡 Hint: saving = affected_fraction × avoided_cost − overhead; compare against doing nothing.

Show solution

Strategy A — exact-response cache. Only the 12% exact repeats benefit; they skip the call entirely. Saving ≈ 12% of inference spend, minus modest cache infra. Real and worth it at this hit rate.

Strategy B — prompt caching on the shared prefix. All 100% of requests share the large system prompt, so the cached prefix is billed at a reduced rate on nearly every call. If the prefix is, say, 60% of input tokens and caching cuts that portion's rate substantially, the saving applies broadly — typically a larger absolute win than A here, because it touches every request, not 12%. (Verify the current prompt-caching discount and minimums in the provider docs.)

Recommendation: do both — they stack (A avoids repeated work; B cheapens the rest). If forced to pick one, B, because it affects 100% of traffic. What would change it: if the system prompt actually varies per request (prefix not stable), B's saving evaporates and A becomes the only real lever — so measure prefix stability and exact-repeat rate first.

Exercise 5 · Build a bottom-up spend forecastProfessional

Context: Finance hates surprises; a bottom-up forecast ties the AI bill to product plans.

Your task: Build a next-quarter LLM spend forecast for a representative product with three features plus a planned launch.

Requirements:

  • Forecast per feature = projected_requests × cost_per_success
  • Add a line for a new feature launching mid-quarter
  • Show the total and the month-over-month curve
  • State the top assumption and how you'd track it against actuals

💡 Hint: Forecast = Σ over features; make each line traceable to a product number.

Show solution

Bottom-up forecast (illustrative).

FeatureReq/mo$/successMonthly
Support assistant200k$0.011$2,200
Doc search500k$0.004$2,000
Summaries (batch)300k$0.002$600
New: sales-email drafter (launches month 2)0 → 150k$0.009$0 / $1,350 / $1,350

Curve: Month 1 ≈ $4,800; Month 2 ≈ $6,150; Month 3 ≈ $6,150 — the step is the launch, not mystery growth. Quarter total ≈ $17,100.

Top assumption: the drafter's 150k projected volume and $0.009/success. Track actuals weekly against this line; if adoption runs hot, the forecast flexes on a known variable, not a surprise. All rates verified against current pricing at forecast time.

Exercise 6 · Diagnose and fix a runaway AI billIndustry scenario

Context: Representative scenario: the monthly LLM invoice tripled with no obvious feature launch. The CFO wants an explanation and a plan by Friday.

Your task: Run the FinOps investigation and deliver a diagnosis plus a remediation plan.

Requirements:

  • State the first thing you check and why
  • List the likely culprits a tripled bill usually hides
  • Give the immediate stop-the-bleeding actions and the durable fixes
  • Propose the controls that prevent a recurrence
  • Frame the CFO-facing summary

💡 Hint: Attribution first — you can't fix what you can't see; then triage by biggest line item.

Show solution

First check: attribution. Slice the spend by feature/team/env/model/tenant. A 3× jump almost always shows up as one or two lines, not uniform growth. If spend is largely untagged, that's finding #1 and the first fix.

Likely culprits: (1) a retry storm — a failing dependency causing loops that each pay for tokens; (2) a prompt/context bloat change that ballooned input tokens on every call; (3) traffic hitting the frontier model where routing should have sent it to a cheaper one; (4) dev/staging pointed at prod-priced endpoints; (5) a single abusive or runaway tenant.

Stop the bleeding (this week): add rate quotas to cap runaway loops, cap non-prod spend, and put a hard budget on the top offending tenant/feature (degrade, don't fail). Durable fixes: fix the retry logic with backoff + a circuit breaker; trim the bloated prompt; turn on difficulty routing; add caching if reuse is real.

Prevent recurrence: spend anomaly alerts on the tagged data, budgets/quotas per tenant, a cost gate in CI that flags prompt changes that raise average tokens, and a monthly showback so teams see their own line.

CFO summary: "The increase is X% from [specific cause], not broad growth. We've capped it this week and the durable fix lands in N weeks; going forward, budgets, routing, and anomaly alerts make a silent 3× impossible."

© 2026 studybydoing.in · AI Engineering: Zero to Production · All rights reserved. · About · Privacy Policy · Terms · Contact
Educational content, provided as-is and without warranty. Code samples are examples — review, test, and adapt them before using in production. See the Terms of Use & Disclaimer. Use at your own risk.
© studybydoing.in