Keeping Costs Under Control¶
Summary¶
Shows how usage-based pricing adds up, why model prices belong in one table, and how daily caps, spend alerts and breakers stop a runaway bill.
Concepts Covered¶
This chapter covers the following 14 concepts from the learning graph:
| Concept | Concept Impact Score |
|---|---|
| Usage-Based Pricing | 31 |
| Per-Call Cost | 28 |
| Free Tier Limits | 1 |
| Vendor Credit Balance | 1 |
| Model Pricing | 2 |
| Single Source of Truth | 2 |
| Single Price Table | 1 |
| Cost per User Action | 4 |
| Daily Cap | 10 |
| Runaway Agent Cost | 2 |
| Budget Limit for Agents | 1 |
| Cost Dashboard | 3 |
| Spend Alert | 11 |
| Spend Circuit Breaker | 10 |
Prerequisites¶
This chapter builds on concepts from:
- Chapter 2: How a Web App Works
- Chapter 4: How AI Coding Agents Work and Fail
- Chapter 9: Working With Outside Services
- Chapter 12: Errors, Logs and Knowing What Happened
A Free Game and a Three-Hundred-Dollar Bill¶
A father hands his old phone to his ten-year-old. He signs it into the family account, installs a game she has been asking about, and checks the price. It's free. Two weeks later the card statement arrives with forty-one charges from the app store, most of them ninety-nine cents, a few of them nine ninety-nine. The game was free, but the gems inside it were not, and each tap on "Buy" was a small charge nobody saw until the statement came.
Nothing was broken, and the phone did what it was set up to do. The daughter wasn't trying to cheat anyone; she was tapping a bright button in a game. The bill came from three facts lining up: every tap cost a little, nothing counted the taps, and the first anyone heard of the total was a month later.
Why this chapter matters
Every paid call in your app is a tap on that button, and the first sign of trouble is often the bill. This chapter shows you how to work out what one user action costs. It also shows how to set three guards so a bad night stops at a number you picked.
The father's fix took ten minutes. He turned on "ask to buy," so each purchase sent a request to his phone. He set a monthly spending limit on the account. And he started glancing at the purchase history every Sunday.
An app built on outside services works like that phone. Every scan, every AI call, every image search is a tap on "Buy." This chapter is about the same three fixes, built into code.
How a Pay-as-You-Go Bill Adds Up¶
Most of the outside services in an AI-built app charge with usage-based pricing: you pay for what you use, measured in calls, searches, minutes of audio or tokens of text, with no fixed price for the month. A gym membership is a flat fee. A taxi is usage-based, and the meter charges for every mile.
That suits a new app, because you pay almost nothing until people use it. The catch is that your code sets the bill by how often it calls the service, and code can call far more often than you meant. A loop, a retry, a bot or a bug can make a thousand calls in a minute.
Each line of that bill is a per-call cost: the price an outside service charges for one request, the message-and-answer from Chapter 2. Some vendors charge a flat amount per call. Some charge per item inside a call, such as per photo or per minute of audio. AI models charge by the token, covered below. Three things about per-call costs surprise builders.
- Failed calls can cost money. Some vendors bill for a search that found nothing, or for a request that timed out on your side but finished on theirs. When Chapter 9's retry logic tries a call again, each try can be a new charge.
- Prices differ by a factor of a hundred. A web search might cost half a cent. A people-search record might cost fifteen cents. One expensive call can outweigh all the cheap ones put together.
- Prices change. Vendors raise prices, add tiers and retire plans. They send an email, and the email is easy to miss.
Free Tiers and Prepaid Credits¶
Free tier limits are the amount of use a vendor gives away each month before it starts charging or stops answering. A free tier is enough to build and test against, and it runs out on the first busy day after launch. Some free tiers start billing when you pass the limit; others return an error. Find out which kind you have, because the second kind becomes an outage the day the app gets popular.
A vendor credit balance is the prepaid usage left in your account with a vendor that sells credits instead of sending a bill. At zero, the vendor refuses your calls until you top up. Chapter 9 showed how a failed call can be misread as an empty result. A people search that fails for lack of credits can look like a search that found no records, and that would read as "no concerns found" for a person nobody checked.
The dating-safety app handled this well. Its alerts warned when a vendor's credit balance ran low. And because every check has a "not checked" result, a check that fails for lack of credits shows as a gap, never as a pass.
Tell your agent
"List every outside service this app pays for. For each one, tell me how it charges (per call, per item, per token or a flat fee), whether we're on a free tier or prepaid credits, and what the service does when we run out: bill us, return an error, or stop answering. Put it in a table. Don't change any code."
What One Scan Costs¶
Per-call costs are the vendor's view. A builder needs to know what it costs when a member does one thing. Cost per user action is the total of every paid call the app makes when a user does one thing, such as running a scan. It tells you whether what members pay covers your costs, and it is the number a runaway bill multiplies.
In the dating-safety app, the costly action is a scan. One scan runs about eight checks, each calling at least one paid service, some once per scan and some once per photo. So the cost depends on what the member uploads.
Adding Up a Scan¶
Here is one scan, check by check. The prices are made up; your vendors' pricing pages have yours. The method carries over: list each paid call, multiply by how many times one scan makes it, and add.
| # | Check | Price per call | Calls in one scan (3 photos) | Cost |
|---|---|---|---|---|
| 1 | Reverse image search | $0.010 per photo | 3 | $0.030 |
| 2 | AI-generated photo detection | $0.005 per photo | 3 | $0.015 |
| 3 | Message pattern check (AI model) | $0.020 per call | 1 | $0.020 |
| 4 | Voice clip check | $0.012 per clip | 1 | $0.012 |
| 5 | People search | $0.150 per search | 1 | $0.150 |
| 6 | Phone number lookup | $0.008 per lookup | 1 | $0.008 |
| 7 | Web search for the match's profiles | $0.005 per query | 2 | $0.010 |
| 8 | Web search for known scam scripts | $0.005 per query | 1 | $0.005 |
| One scan | $0.250 |
That comes to a quarter per scan, and writing it down shows three things. One check is most of the bill: the people search is $0.15 of the $0.25, or 60 percent, so that is the line to look at if costs must come down. The cost moves with the upload: six photos instead of three doubles checks 1 and 2, and the scan costs $0.295. And small numbers grow: 400 scans a day at $0.25 is $100 a day and $3,000 over a thirty-day month. Try changing the inputs below.
Diagram: Scan Cost Calculator¶
Run the Scan Cost Calculator MicroSim Fullscreen
Scan Cost Calculator
Type: microsim
sim-id: scan-cost-calculator
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: calculate
Learning Objective: The learner will calculate the cost per scan and the monthly bill of the dating-safety app from per-call prices, photos per scan, retries and scans per day, to within half a cent per scan and ten dollars per month.
Prerequisites: usage-based pricing, per-call cost, cost per user action, retry (all defined in the sections "How a Pay-as-You-Go Bill Adds Up" and "What One Scan Costs" above; retry is from Chapter 9).
Evidence of Mastery: For four challenges, the learner types a dollar amount before the sim reveals the answer. A per-scan answer is correct when it is within ±$0.005 of the model value. A monthly answer is correct when it is within ±$10 of the model value. Mastery is 4 of 4 correct. Moving the inputs and watching the totals change is exploration, not evidence.
Misconceptions: (1) Every check costs about the same, so cutting any check saves about an eighth of the bill. (2) A scan has one fixed price no matter what the member uploads. (3) A retry is free because the first call failed. (4) A few cents per scan can't add up to much.
Instructional Rationale: Apply-level calculation needs practice with a check, so the learner commits a number before the sim shows it. The four challenges are chosen so each one breaks one misconception: the photo count, the retries and the monthly total each change the answer in a way the learner has to compute.
Content:
The eight checks and their prices. Every price must be labeled "illustrative prices."
| # | Check | Price per call (USD) | Calls per scan |
|---|---|---|---|
| 1 | Reverse image search | 0.010 | photos per scan |
| 2 | AI-generated photo detection | 0.005 | photos per scan |
| 3 | Message pattern check (AI model) | 0.020 | 1 |
| 4 | Voice clip check | 0.012 | 1 |
| 5 | People search | 0.150 | 1 + retries |
| 6 | Phone number lookup | 0.008 | 1 |
| 7 | Web search for the match's profiles | 0.005 | 2 |
| 8 | Web search for known scam scripts | 0.005 | 1 |
Inputs the learner can change:
| Input | Min | Max | Step | Default | Unit |
|---|---|---|---|---|---|
| Photos per scan | 1 | 6 | 1 | 3 | photos |
| People-search retries per scan | 0 | 10 | 1 | 0 | retries |
| Scans per day | 0 | 2000 | 50 | 400 | scans |
Days in a month: 30, fixed.
The sim shows each check's cost per scan, the cost per scan, the cost per day and the cost per month, and marks which check is the largest share of the scan.
Challenges, in this order:
| # | Inputs | Question | Model answer | Feedback when wrong |
|---|---|---|---|---|
| 1 | Defaults (3 photos, 0 retries) | Cost of one scan? | $0.250 | Add all eight lines: 0.030 + 0.015 + 0.020 + 0.012 + 0.150 + 0.008 + 0.010 + 0.005 = $0.250. |
| 2 | 6 photos, 0 retries | Cost of one scan? | $0.295 | Only checks 1 and 2 are priced per photo. They go from $0.045 to $0.090, so the scan rises by $0.045 to $0.295. |
| 3 | 3 photos, 2 retries | Cost of one scan? | $0.550 | Each retry is billed as a full people search. Two retries add 2 × $0.150 = $0.300 to the $0.250 scan. |
| 4 | Defaults, 400 scans per day | Bill for a 30-day month? | $3,000 | 400 scans × $0.250 = $100 a day, and 30 days × $100 = $3,000. |
Provenance: Prices are illustrative and must be labeled so. The eight checks are the dating-safety app's "about eight checks" from research/seed-notes.md, named for this chapter. Challenge values are computed from the Rules and match the section "A Worked Example: Adding Up a Scan."
Rules: Cost of a check = price per call × calls per scan. Checks 1 and 2 make one call per photo. Check 5 makes 1 + retries calls, and every retry is billed in full. Cost per scan = sum of the eight checks, shown to three decimal places. Cost per day = cost per scan × scans per day. Cost per month = cost per day × 30, shown to the nearest dollar. When two checks tie for largest share, both are marked. At 0 scans per day, the daily and monthly costs are $0.
Learner Activity:
- The learner sees challenge 1 with the inputs set and the totals hidden, and types a cost.
- The learner presses Check. The totals appear next to the learner's answer, with the per-check breakdown.
- The learner repeats for challenges 2 to 4. The inputs are set by each challenge and locked while it is open.
- After challenge 4, free exploration unlocks. The learner changes the three inputs and every total updates at once.
- The learner should notice that the people search stays the largest share at every setting, and that retries move the total faster than photos do.
Feedback: Four challenges, fixed order, two attempts each. Correct: "Correct: " followed by the model answer. Incorrect: the "Feedback when wrong" text for that challenge. After the second wrong attempt the model answer and its working are shown, and the challenge counts as missed. A running count "Challenges correct: n of 4" is shown.
Starting State: Challenge 1 is shown with the defaults set and the totals hidden. The question on screen is "What does one scan cost?"
Chapter Anchors: One scan costs $0.250 at the defaults. The people search is $0.15 of that, 60 percent. Six photos make the scan $0.295. At 400 scans a day the bill is $100 a day and $3,000 over a thirty-day month. All prices are made up for the example.
Tell your agent
"Trace what happens when a member runs one scan, from the moment they press the button to the results page. List every paid call the app makes, how many times it makes each one, and what decides that count (photos uploaded, retries, anything else). Then add it up using the prices in our config and tell me the cost of one typical scan and which call is the biggest share."
Model Prices and the Ten-File Problem¶
Chapter 4 explained the token, the piece of text a model reads and writes, roughly three-quarters of a word. Model pricing is how an AI vendor charges for a model: one price per million tokens sent in, and a separate, usually higher, price per million tokens the model writes back. A vendor's bigger models often cost five to twenty times as much per token as its smaller ones.
So the cost of one call is the input tokens times the input price, plus the output tokens times the output price, with both prices per million. Take the message pattern check. Say it sends 4,000 tokens (the member's pasted messages plus the instructions) and gets back 500. At made-up prices of $3 per million in and $15 per million out, that's $0.012 plus $0.0075, about two cents. That is the $0.020 in the scan table. If a member pastes a long conversation and the input grows to 40,000 tokens, the same check costs about thirteen cents. The price per token didn't change; the size of the call did.
The Same Price in Ten Places¶
Code needs these prices to log what a scan cost, show a dashboard, or stop spending at a limit. In the dating-safety app, model prices had been copied into ten different files. Each time an agent wrote code that needed a price, it typed the number in right there. That's normal: an agent working on one file sees one file, and typing the number is the shortest path to working code.
The trouble comes when a price changes. Someone updates the file in front of them, and the other nine keep the old price. The cost report, the logs and any limit built on the price now disagree, and nobody gets an error.
The fix is a single source of truth: each fact lives in exactly one place, and everything that needs it reads it from there. For costs, that is a single price table, one file or database table holding the price of every paid service and model, with the date each price was last checked. When a vendor changes a price, one line changes.
Gate or wall?
A price typed into one file looks like a gate, easy to swing later. But the logs, the dashboard and the spend guards all stand on it, so the price table is a wall. Build it before the guards that read it.
Here is the idea as a TypeScript file. Each entry holds the unit the vendor charges by, the price in US dollars, and the date someone last checked it against the vendor's pricing page. The prices are made up.
// prices.ts: the only place prices live. Check against vendor pages monthly.
export const PRICES = {
"people-search": { unit: "search", usd: 0.150, checked: "2026-11-01" },
"image-search": { unit: "photo", usd: 0.010, checked: "2026-11-01" },
"message-model-in": { unit: "1M input tokens", usd: 3.00, checked: "2026-11-01" },
"message-model-out": { unit: "1M output tokens", usd: 15.00, checked: "2026-11-01" },
// ...one line for every paid service
};
Prices from memory go stale
An agent asked to fill in a price table may type prices from what it learned in training, and those can be a year old. Have it copy each price from the vendor's pricing page, give you the link, and write today's date in checked.
The checked date tells you which prices are oldest, since a price nobody has looked at in six months is a guess. Once the table exists, an automated check can stop a build that has a dollar amount anywhere else in the code, so the ten copies can't grow back. Chapter 17 shows how.
Tell your agent
"Search the whole codebase for every place a price, a cost per token or a cost per call is written as a number. List each file and line. Then create one price table that holds every price, with the date it was last checked, and change every one of those places to read from the table. Show me the list before you change anything."
Three Guards Against a Runaway Bill¶
The father set up a limit, a notice for each purchase, and a weekly look at the history. An app needs a limit, a notice and a stop, and each catches something the others miss. The dating-safety app had the first; the third is the one it lacked.
The Daily Cap¶
A daily cap is a limit on how many times a user action can happen in a day. Past the limit, the app refuses the action until the next day. It counts actions, not money. A cap can apply to each member ("ten scans a day") or to the whole app ("a thousand scans a day"), and most apps want both.
The dating-safety app had a daily scan cap. Say a bot gets into a member's account at midnight and submits about three thousand scans overnight. At $0.25 a scan, that's $750 by morning. With a per-member cap of ten, the bot gets ten scans, $2.50. With only an app-wide cap of a thousand, it gets a thousand scans, $250, and other members are locked out for the rest of the day. That is why the per-member cap comes first.
The refusal must happen before any paid call starts, with a plain message such as "You've reached today's scan limit. It resets at midnight." The wrong way is to start the scan and skip the expensive checks. That breaks the no-false-all-clear rule from Chapter 1: a check that didn't run must show as "not checked," never as passed.
A daily cap has one blind spot. It counts scans and trusts that each scan costs what it used to. If the price of a scan goes up, the cap counts the same scans while the money climbs. The next two guards watch the money.
Tell your agent
"Show me where the daily scan cap is enforced and what its limits are, per member and for the whole app. Confirm that the cap is checked before any paid call is made, and that a member who hits it sees a plain message. If a scan can start and then skip checks because of a limit, show me that code."
Spend Alerts¶
A spend alert is a message sent to a person when spending crosses a set amount. It doesn't stop anything; it makes sure someone knows. It is Chapter 12's alert pointed at money.
There are two places to set one. Most vendors offer a billing alert in their own dashboard that emails you when the month's bill passes an amount. It takes five minutes and no code, so set one for every paid service. The second place is inside the app, where the code knows what each scan cost from the price table. An in-app alert can say "today's spend is twice yesterday's" or "the average cost per scan rose from $0.25 to $0.70 this morning."
The in-app kind catches what the cap misses. Say the people-search vendor raises its price from $0.15 to $0.60 a search, and the builder's monthly price check updates the price table. Every scan now costs $0.70, while the cap sees the usual four hundred scans. A spend alert at $150 a day fires at scan 215, before lunch, and the builder can act the same day.
The in-app alert is only as right as the price table. If the table still said $0.15, the app would count $0.25 a scan and stay quiet. Only the vendor's own billing alert sees what the vendor charges, so set both kinds.
A few settings keep spend alerts useful rather than noisy:
- Set thresholds from what a normal day costs. If a normal day is $100, an alert at $150 means something. An alert at $20 fires every day and gets ignored, the alert fatigue Chapter 12 warned about.
- Alert on cost per scan as well as on totals. A total can rise because the app is popular. A cost per scan that jumps means something changed.
- Send the alert somewhere a person looks within hours: a phone, not a shared inbox.
Tell your agent
"Plan a spend alert and show me the plan before writing code. Every hour, it should add up today's spend from the logged cost of each paid call, using the price table, and text me if today's total passes $150 or the average cost per scan is more than 50 percent above last week's average. Both numbers should be settings, not values in the code. Also list every vendor dashboard where I should set a billing alert myself."
The Spend Circuit Breaker¶
An alert depends on a person reading it, and at three in the morning nobody does. The third guard acts on its own.
A spend circuit breaker is code that keeps a running total of money spent in a period. When the total reaches a limit, it stops every paid call until a person resets it or the period ends. Chapter 9's circuit breaker stops calling a vendor after enough failures; this one trips on dollars instead of errors.
The dating-safety app had no spend circuit breaker. Nothing stopped spending when the money itself got too high. The worked example below shows the gap.
The Retry Storm¶
Say the people-search vendor has a bad night. Its servers accept each request, bill for it, and then time out before answering. The app's retry logic, doing what Chapter 9 taught it, tries again, and again, up to ten times per scan. Every try is billed. A scan that used to cost $0.25 now costs $0.10 for the seven other checks plus eleven people searches at $0.15, which is $1.75.
Here is how the night goes with each guard.
| Guard in place | What happens over 400 scans | Spend by morning |
|---|---|---|
| Daily cap of 1,000 scans only | The cap never trips, since 400 is under 1,000 | $700 |
| Cap plus a spend alert at $150 | The alert fires at scan 86. Nobody reads it until 7 a.m. | $700 |
| Cap, alert, and a spend breaker at $300 | The alert fires at scan 86. The breaker trips after scan 172 and refuses new scans | $301 |
Without the breaker, the night costs seven times a normal day, and nothing in the app looks wrong except the bill. With it, the damage stops at a number the builder chose ahead of time. (It ends a dollar over because it checks the total before each scan, and the last scan it let in finished just above the line.)
Every part did its job
Notice that nothing broke that night. Retrying a stumbling vendor is the right habit, and it turns costly only when each try is billed and nothing counts the money. Any good habit wrapped around a paid call needs a ceiling.
A few design choices make a spend breaker work:
- Put it where every paid call passes: in the shared code all of Chapter 9's adapters call, so no paid call can go around it.
- Read prices from the single price table. A breaker reading a stale price counts the wrong money. This is the strongest reason to fix the ten-file problem.
- Refuse cleanly. New scans get a plain message such as "Scans are paused for a short time. Please try again later." Checks already running are marked "not checked" if they can't finish, never passed.
- Make a person close it. A breaker that resets itself after an hour will trip again an hour later. Have it alert you when it trips and stay open until someone looks.
- Set the limit from a bad day. Put it above the busiest normal day you expect, so popularity doesn't trip it, and below the amount that would hurt.
A spend breaker fails closed on purpose, in Chapter 9's terms: for a few hours the app does less. For a small app, a short pause is usually cheaper than an open-ended bill.
Here is what each guard counts, what it does, and what it can't see.
| Guard | Counts | Does | Misses |
|---|---|---|---|
| Daily cap | Actions (scans) | Refuses actions past the limit | A scan that got more expensive |
| Spend alert | Dollars, and cost per action | Tells a person | Anything nobody reads in time |
| Spend circuit breaker | Dollars | Stops all paid calls until a person resets it | Slow overspending that stays under the limit |
You can run these scenarios yourself in the diagram below and predict which guard acts in each one.
Diagram: Spend Guard Simulator¶
Run the Spend Guard Simulator MicroSim Fullscreen
Spend Guard Simulator
Type: microsim
sim-id: spend-guard-simulator
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: attribute
Learning Objective: The learner will attribute each of three runaway-spend scenarios to the guard that acts first and the guard that stops the spending, choosing among the daily cap, the spend alert, the spend circuit breaker and none.
Prerequisites: cost per user action, daily cap, spend alert, spend circuit breaker, retry (all defined in the section "Three Guards Against a Runaway Bill" above; retry is from Chapter 9).
Evidence of Mastery: For scenarios B, C and D, the learner answers two questions before running the day: "Which guard acts first?" and "Which guard stops the spending?" Each answer is one of: daily cap, spend alert, spend circuit breaker, none. An answer is correct when it matches the answer table in Content. Mastery is 5 of 6 answers correct on the first attempt. Running the day, changing settings and watching the spend line are exploration, not evidence.
Misconceptions: (1) A daily scan cap also caps spending. (2) A spend alert stops the spending. (3) If the scan count looks normal, the bill is normal. (4) A spend breaker should reset itself.
Instructional Rationale: Analyze-level attribution needs the learner to separate what each guard counts from what it does. Predicting before the day runs forces the learner to reason from the guard's rule, and the scenarios are built so the cap, the alert and the breaker each fail to help in at least one of them.
Content:
Guard settings, with the defaults used for the answer table:
| Setting | Min | Max | Step | Default | Unit |
|---|---|---|---|---|---|
| Daily scan cap (whole app) | 100 | 3000 | 100 | 1000 | scans |
| Spend alert threshold | 50 | 500 | 50 | 150 | USD per day |
| Spend breaker limit | 100 | 1000 | 50 | 300 | USD per day |
Each guard can also be switched off. The defaults have all three on.
Scenarios. Every scenario must be labeled "illustrative."
| ID | Scenario shown to the learner | Scans attempted | Cost per scan |
|---|---|---|---|
| A | A normal day | 400 | $0.25 |
| B | A bot uses one account to submit scans all night | 3000 | $0.25 |
| C | The people-search vendor times out and every scan retries it 10 times, each try billed | 400 | $1.75 |
| D | The people-search vendor raised its price from $0.15 to $0.60; the price table has the new price, and nobody changed the guards | 400 | $0.70 |
Scenario A is a practice run with no questions.
Answer table (default settings):
| ID | Acts first | Stops the spending | What happens | Why (feedback) |
|---|---|---|---|---|
| B | Spend alert | Daily cap | Alert fires at scan 600 ($150.00). Cap refuses scan 1001. Day ends at $250.00. | The alert only tells a person. The cap counts scans, and here the scan count is what ran away. |
| C | Spend alert | Spend circuit breaker | Alert fires at scan 86 ($150.50). Breaker trips after scan 172 ($301.00) and refuses scans 173 to 400. | Only 400 scans ran, so the cap never noticed. The money ran away, and only the breaker counts money and acts. |
| D | Spend alert | None | Alert fires at scan 215 ($150.50). Day ends at $280.00, under the breaker limit. | The alert is the only guard that notices. A person has to read it and decide what to do about the new price. |
Scenario A at defaults: no guard acts; the day ends at $100.00.
Provenance: The $0.25 scan and its $0.15 people search come from the section "A Worked Example: Adding Up a Scan" and are illustrative. Scenario C comes from "A Worked Example: The Retry Storm." Scenario D comes from the section "Spend Alerts." That the dating-safety app had a daily scan cap and no spend breaker is from research/seed-notes.md. All guard thresholds are illustrative.
Rules: Scans arrive one at a time, spread evenly over 24 hours. Before each scan starts: if the cap is on and scans already run >= cap, refuse the scan; if the breaker is on and spend so far >= breaker limit, refuse the scan. A scan that starts runs to the end and adds its full cost. After each scan: if the alert is on, has not fired today, and spend >= alert threshold, the alert fires once. A tripped breaker stays tripped for the rest of the day. Spend is shown to the cent. With a guard switched off, it never acts. Worked values at defaults: B alert at scan 600, cap at scan 1001, total $250.00; C alert at scan 86, breaker after scan 172, total $301.00, and $700.00 with the breaker off; D alert at scan 215, total $280.00.
Learner Activity:
- The learner runs scenario A to see a normal day: a spend line that rises to $100 and no guard events.
- The learner opens scenario B, answers the two questions, and presses Run. The day plays out with the spend line, a scan counter and a marker at each guard event.
- The learner repeats for C and D.
- After all three, the learner can change settings, switch guards off, and rerun any scenario. The learner should notice that switching the breaker off in C raises the day to $700, and that lowering the cap does nothing for C or D.
Feedback: Three scenarios, fixed order B, C, D, one attempt per question. On Run, each answer shows correct or incorrect and the Why text. Correct: "Right. " followed by the Why text. Incorrect: "Not this time. " followed by the Why text. If the learner picked the daily cap as the stopper in C or D, add: "The cap counts scans. In this scenario the scan count was normal." A running count "Answers correct: n of 6" is shown. Answers after free exploration begins are not scored.
Starting State: Scenario A is loaded with the default guards and an empty spend line. The prompt reads "A normal day costs $100. What stops a bad one?"
Chapter Anchors: A normal day is 400 scans at $0.25, $100. In the retry storm a scan costs $1.75; the alert fires at scan 86; the breaker at $300 trips after scan 172 and the day ends at $301; without the breaker it reaches $700. In the price-change case a scan costs $0.70 and the alert at $150 fires at scan 215. The bot scenario is three thousand scans overnight. The default cap is 1,000 scans.
Tell your agent
"Plan a spend circuit breaker and show me the plan, including which files change, before writing code. It goes in the shared code that every paid outside call goes through. It should add each call's cost from the price table to a running total for the day, and refuse new paid calls once the total reaches a limit I set in config. When it trips, send me an alert, show members a plain 'scans are paused' message, mark any unfinished checks 'not checked', and keep paid calls stopped until I reset it. Write a test that drives the total past the limit and proves no further paid call is made."
A Cost Dashboard¶
The father's third fix was a look at the purchase history every Sunday. Alerts and breakers handle the bad days. A dashboard shows what a normal day looks like, so you can set those limits sensibly and see slow drift that never trips anything.
A cost dashboard is one page that shows what the app is spending and where the money goes. For the dating-safety app it would show:
- Spend today and for each of the last thirty days
- Spend by vendor, so the people search's share is plain
- Average cost per scan, day by day
- Credit balance left with each prepaid vendor
- Scans today against the daily cap, and the breaker's state: closed, or tripped and when
It doesn't need to be pretty. A page checked once a week, built from the same logged costs and price table the alert and breaker use, is enough.
Check the day after a change
Open the dashboard the day after you change anything that calls a paid service. If the average cost per scan moved, you know which change did it while it is still fresh.
Tell your agent
"Build a simple admin-only page that shows spend per day for the last 30 days, spend by vendor, average cost per scan per day, each vendor's remaining credit balance, today's scans against the cap, and whether the spend breaker is tripped. Use the costs we already log and the price table. Make sure only an admin can open it, and show me the plan before you build it."
When the Agent Is the One Spending¶
There is a second bill: the one for the AI coding agent that builds the app. Agents read and write tokens too, and an agent working on a large codebase reads a lot of it.
Runaway agent cost is spending by an AI agent that keeps going far past what the task needed, because nothing tells it to stop. It happens when an agent loops on a failing test, rereads large files on every step, starts helpers that start helpers, or runs tests that call live paid vendors. The agent is doing what it was asked; nobody set an end. Chapter 4 tells the author's story of a four-hour build that burned 27 million tokens.
The fix is a budget limit for agents: a ceiling on money, tokens, steps or time, set before the agent starts. Some you set in a vendor's dashboard, some in the agent's own settings or code.
- Set a monthly spending limit on each AI vendor account, so a key used by a runaway agent stops at a known number.
- Give each project its own API key (the secret that lets code use a vendor account), so one project's runaway can't drain another's budget and the bill shows who spent what.
- For an agent your app runs, set a maximum number of steps or tool calls and a time limit, and make it stop and report when it reaches either.
- Keep live paid vendors out of the test suite. Tests should call fakes that return saved answers. Chapter 10 covers how.
Tell your agent
"Before you start this task, tell me roughly how many steps it should take. If you reach twice that number, or you've tried the same fix three times without the tests passing, stop and report what you've tried. Also check whether any test in this project calls a paid outside service with a live key, and list those tests."
Back to the Phone¶
The father didn't take the phone away. The game stayed, and so did the gems. Every purchase now asked first, the month had a ceiling, and someone looked at the history once a week. His daughter barely noticed, and the next statement was eleven dollars.
The dating-safety app already had a daily scan cap, credit alerts, and a "not checked" result whenever a cap or empty credits stopped a check. It lacked a guard that watched the money, and one price table for that guard to read. An agent can build both in an afternoon.
Chapter 14 turns to where the app runs: the environments, deploys and rollbacks that decide whether a change reaches members safely.
Key Takeaways¶
- Add up the cost per user action. In the made-up prices, one scan cost $0.25 and the people search was 60 percent of it. Failed calls and retries can be billed too.
- Keep every price in a single price table that all cost code reads.
- A daily cap counts actions, a spend alert tells a person about money, and a spend circuit breaker stops paid calls when money crosses a limit. Each catches what the others miss.
- Set a budget limit for agents before a long task, so runaway agent cost stops at a known number.
Bill under control
You can now add up what one scan costs, keep every price in one table, and say which guard stops which bad night. Good enough for now, and you know why.