Cost-Aware Architecture for AI Products
· 20 min read
AI features that delight ten users but break the budget at ten thousand are unfinished designs. Staff engineers model tokens per request, cache hit rates, routing tiers, and cost per successful outcome before launch—then gate releases when spend stops buying retention or deflection.
Unit economics belong in the design doc
An AI feature that delights ten users and bankrupts the company at ten thousand users is not a finished design. Estimate tokens per request, expected concurrency, cache hit rate, evaluation overhead, and the willingness of customers to pay for the outcome. These numbers should influence model choice and interaction design before launch.
Cost awareness is not the same as cheapness. Some workflows deserve an expensive model because the alternative is human labor or lost revenue. The engineering task is to spend deliberately where quality creates leverage and refuse spend where it does not.
Document assumptions in the same doc as latency SLOs: p50 and p95 tokens, regeneration rate, and eval job frequency. Finance and product should recognize the same variables engineering uses in load tests, not a separate spreadsheet invented after the first invoice.
Include a sensitivity table: if daily active users double and regeneration rate stays flat, what happens to monthly tokens? If regeneration doubles because context pollution grows, what happens even at flat DAU? Sensitivity analysis prevents surprise inflection points when marketing succeeds.
Staff reviews should ask for a break-even story: at what monthly active usage does gross margin on the AI tier turn negative if model prices hold flat? If the answer is unknowable, the feature is not ready for general availability—only for a capped beta with telemetry that fills the spreadsheet.
Record baseline non-AI support cost per ticket where AI deflection is the goal. Without that baseline, leadership cannot tell whether model spend replaced humans or simply added a parallel channel users ignore.
Route work by difficulty and risk
Not every request needs the strongest available model. Classify tasks by risk and ambiguity. Deterministic extraction, classification, and formatting can often use smaller models or classical software. Open-ended synthesis, planning, and high-stakes advice may justify a stronger model with tighter guardrails.
Routing should be explicit and measurable. Track quality, latency, and cost by route. A cascade that escalates only when confidence is low preserves experience while keeping the average request affordable.
| Route | Typical use | Cost control | | --- | --- | --- | | Classical / rules | Validation, formatting | No model call | | Small model | Classification, short summaries | Low token cap | | Large model | Planning, nuanced drafts | Strict context budget | | Human | Account takeover, money movement | Escalation metric |
Cache stable retrieval and repeated prompts where answers are identical for many users—policy snippets, pricing tiers, public docs. Invalidate caches when source documents change, with version keys tied to your CMS or git commit.
Log cache hit ratio per route weekly. A sudden drop often precedes a cost spike caused by a deployment that busted cache keys or changed embedding models without re-warming hot entries.
When you escalate from small to large models, log the reason code—low confidence, user override, policy block—so product can see whether escalation is a quality feature or a routing bug. Escalation rates above a few percent on high-volume routes usually mean the classifier needs retraining, not that users love premium answers.
Product shape changes the bill
Streaming long essays is expensive. Asking for concise structured recommendations is cheaper and often more useful. Interface decisions—when to call a model, how much history to send, whether to regenerate—are cost controls as much as UX choices.
Batch offline work, precompute frequent answers, and avoid sending the entire account history when a small relevant slice will do. The cheapest token is the one the system never sends.
Mobile apps should default to shorter context windows and progressive disclosure: fetch more history only when the user expands a thread. Expo clients that attach full chat logs on every keystroke burn budget before product analytics can explain why.
Charge product managers for regenerate buttons: each extra click is a priced API call. UX that encourages infinite retries without new information is a hidden subsidy from engineering budget to user frustration.
Voice and multimodal inputs multiply cost: transcription, vision tokens, and longer contexts arrive before the main model call. Price those paths separately in design docs so mobile teams do not ship camera-first flows on the same per-message cap as text chat.
Make spend a health signal
Track cost per successful outcome, not only cost per request. A cheap endpoint that users retry five times is not cheap. Connect finance metrics to product analytics so teams see whether spend is buying retention, conversion, or support deflection.
Sustainable AI products treat model spend as an architectural parameter. When the budget is visible, teams invent better systems instead of hoping traffic stays small.
Alert on cost velocity, not only monthly totals. A deploy that doubles output tokens per success should page the same way a latency regression would, with rollback tied to feature flags rather than waiting for accounting close.
Finance dashboards should slice spend by feature flag and cohort, not only by environment. Staging leaks into production spend when teams forget to disable verbose logging routes that call models with full prompts for debugging.
Define a “cost incident” severity ladder mirroring uptime: Sev-1 when daily burn exceeds forecast by 50% with no matching traffic, Sev-2 when a single tenant crosses fair-use thresholds. Runbooks should include disable flags and model downgrade steps, not only vendor support tickets.
Budget evaluation like production traffic
Evaluation suites that run only before launch still consume tokens daily once wired into CI. Count eval neurons in the same ledger as production routes. Sample production traffic for human review instead of re-running full suites on every typo fix.
Observability stacks that store raw completions inflate storage cost. Align eval artifacts with logging tiers: structured scores and identifiers, not verbatim prompts, unless break-glass policy allows samples.
When eval gates block a merge, record estimated token cost of the run in the PR comment so product understands quality tax as a real line item, not free automation.
Separate eval infrastructure accounts or API keys where possible so production budget alerts do not desensitize teams to eval spikes during heavy release weeks.
Golden-set evals that replay production transcripts need redaction before storage; otherwise you pay twice—once for inference at capture and again every time CI replays the full thread. Store minimal fixtures with synthetic placeholders where PII once lived.
Multi-tenant fairness and throttles
One tenant running agentic loops can consume the shared daily budget. Per-tenant token buckets, concurrency limits, and polite degradation messages protect other customers without taking the whole service offline.
Attribute spend by tenant, feature flag, and prompt version. Sales promises of unlimited AI assistant usage need engineering counters before contract signature, not after the first enterprise onboarded with aggressive automation.
Free tiers deserve explicit caps surfaced in UI—remaining messages, slower routes, or smaller context—so support does not explain opaque slowdowns as model mood.
Enterprise contracts that promise dedicated capacity still share embedding indexes and retrieval clusters in many MVPs—document shared components in SLOs so legal language cannot outrun physical isolation you have not built yet.
Agentic workflows that loop until success need hard iteration caps and cumulative token budgets per user session. Without caps, a single curious power user can exhaust the daily free tier for everyone else on shared infrastructure.
Architecture patterns: cache, route, compress
```yaml request_path: cache_lookup: semantic + exact key on retrieval bundle router: confidence_threshold 0.82 → escalate context: max_tokens 6000 hard cap response: structured_json_when_possible billing_tags: [tenant_id, feature, model_tier, eval_run_id] ```
Compress tool outputs before they enter the prompt. JSON pretty-printing and stack traces belong in logs, not in model context unless an on-call engineer is actively debugging.
Prefer structured outputs that reduce regeneration loops. Schema-validated responses fail fast in code instead of asking the model to apologize and retry in natural language three times.
Instrument dollars or token estimates per successful user session in product analytics, not only in vendor billing portals delayed by a day. Product decisions happen in real time; invoices arrive too late to steer.
Treat prompt templates as versioned assets: each change should note expected token delta and rollback owner. Prompt drift without measurement is how teams accidentally double input size while fixing a typo in the system message.
Operational checklist for AI cost architecture
Publish cost ceilings beside feature flags: max daily spend, max tokens per user per day, and escalation contacts. Pull requests that add new model routes must include projected token math or fail CI.
Review cost per success weekly with product and support. If spend rises while outcomes flatline, fix routing and context before upgrading models.
During incident response, disable expensive routes first—not the entire product—so you preserve core value while stopping bleed. A feature flag per model tier beats a global kill switch that triggers churn.
Link to sibling posts on context engineering and rollout failure modes: polluted context and missing fallbacks both show up as cost spikes before they show up as quality wins.
Reserve headroom in annual model budgets for price list changes—vendors adjust per-token rates more often than teams replatform. A ten percent list increase with flat traffic should not require an emergency rearchitecture or a rushed downgrade that harms quality. Plan those tradeoffs before finance asks.
Finally, rehearse turning AI off: measure revenue and support load when the model path is disabled. If the business stops when AI stops, you built a dependency—not an enhancement—and your unit economics were never real.
Publish a quarterly cost architecture review alongside security review: new routes, new caches, new eval jobs, and any waiver granted during launch week with expiry dates enforced automatically.
Partner with finance on vendor commit discounts only after steady-state usage is measured for two billing cycles. Prepaying for tokens while routing and context budgets are still moving targets locks in waste alongside savings.
Frequently asked questions
Should we always pick the cheapest model?
When is caching LLM responses safe?
What metric should leadership track weekly?
How do we control eval cost in CI?
Sources
- OpenAI — Production best practices — openai.com
- Google Cloud — Cost optimization for ML — cloud.google.com
- AWS — Optimizing ML cost — aws.amazon.com
- OWASP — LLM Top 10 — owasp.org
Related on this site
Related service
AI-powered product development
Ship AI features to production: tooling, retrieval, evaluation, safety boundaries, and operable backends.
Published on May 21, 2026 by Berktug Berke Ates.