System Design
Intermediate 13 min read AI-era system design

LLM cost engineering

In one line

LLM cost is calls x tokens x price, so you control it by making fewer calls, sending fewer and cheaper tokens, using the smallest model that passes your evals, using discounts (prompt caching, batch APIs), and measuring cost per tenant, feature and successful outcome so you know where the money goes.

What it is

With classic backends, cost is mostly fixed infrastructure that grows slowly with traffic. With LLMs, every call has a direct, variable price: input tokens x input price + output tokens x output price, where output tokens typically cost 3 to 5 times more than input tokens. One customer, one feature or one runaway agent loop can cost 100 times another, so cost becomes a design property like latency.

Cost engineering has two halves. Reduction: shrink calls, tokens and price per token without losing quality. Visibility and control: attribute every call's cost to a tenant, feature and outcome, set budgets and alerts, and use unit economics (cost per resolved ticket, per generated report) to make product decisions.

In India the pressure is sharper: prices are in dollars while revenue per user is often in rupees and low, and Indian-language text can need several times more tokens than the same message in English on common tokenizers. A feature that is cheap for a US SaaS seat can be unaffordable for a free consumer app with millions of users.

Why interviewers ask

Interviewers increasingly ask 'how much will this cost and how would you bring it down?' for AI designs. A strong answer estimates cost with real formulas, names the biggest lever for that workload instead of listing every trick, protects against runaway spend, and keeps quality fixed with evals while cutting cost. It also shows product sense: knowing that the cheapest call is the one you do not make.

How it works

  1. 1Model the cost per unit of value: per request, per conversation (number of calls x tokens per call) and per successful outcome. Use the provider's reported usage fields, including cached tokens, not your own estimates.
  2. 2Avoid calls: answer common, structured requests with rules, search or templates; generate on user action rather than on page load; precompute and store results that many users share (product summaries) instead of generating per view.
  3. 3Shrink input tokens: trim conversation history (keep the last few turns plus a running summary), send 5 relevant chunks instead of 30, remove verbose instructions and unused tool definitions, and compress JSON context to only needed fields.
  4. 4Order prompts for provider prompt caching (static first, dynamic last); cached input tokens are billed at a large discount, often 50 to 90% depending on the provider.
  5. 5Shrink output tokens: set max_tokens per feature, ask for concise formats (bullets, JSON fields) and stop sequences, and let users stop generation. Output is the expensive side.
  6. 6Right-size the model: route simple tasks (classification, extraction, short rewrites) to small models and keep large models for hard reasoning; use a cascade (try small, escalate on low confidence or failed validation). Prove each routing rule with eval scores per slice.
  7. 7Use batch pricing for non-urgent work: OpenAI and Anthropic batch APIs process requests asynchronously within 24 hours at about half the price, ideal for nightly summaries, re-embedding and evaluations.
  8. 8Consider fine-tuned small models or self-hosting (for example open-weight models on vLLM) only at high, steady volume: you pay for GPUs per hour whether busy or idle, so the break-even depends on utilisation, and you take on serving, scaling and upgrades.
  9. 9Control spend: per-tenant and per-feature token budgets in the AI gateway, step and cost caps for agents, and anomaly alerts (for example spend above 3x the same hour last week).
  10. 10Attribute cost: the gateway emits a usage event per call (tenant, feature, model, input, cached and output tokens, price version); store it in an analytics database and join with a versioned price table, because prices change and history must not be recomputed with today's price.

Worked example · Cutting the cost of an AI support conversation by about 70%

  1. Starting point: 1M conversations a month, 4 large-model calls per conversation, each with 5,000 input tokens (3,500 of them a static system prompt and tool list) and 300 output tokens. Illustrative price: $3 per million input, $15 per million output.
  2. Per call: 5,000 x $3/M = $0.0150 input + 300 x $15/M = $0.0045 output = $0.0195. Per conversation: 4 x $0.0195 = $0.078 (about Rs 6.6 at Rs 85 per dollar). Monthly: $78,000.
  3. Lever 1, prompt caching: put the 3,500 static tokens first so they are cache reads at 10% of price. Input per call = (1,500 x $3 + 3,500 x $0.30) / 1M = $0.00555. Per call total $0.01005.
  4. Lever 2, routing: two of the four calls are intent classification and slot extraction. Moving them to a small model at $0.25/M input and $1.25/M output costs $0.00125 + $0.000375 = $0.0016 per call. Evals show the same accuracy on these tasks.
  5. New cost per conversation: 2 x $0.01005 + 2 x $0.0016 = $0.0233, about Rs 2. Monthly: about $23,300, a 70% reduction with no measured quality loss.
  6. Unit economics: if 60% of conversations resolve without a human, cost per resolved conversation is $0.0233 / 0.6 = about $0.039. Compare with the cost of a human-handled chat to decide where the AI should be used and whether a more expensive model that resolves 70% would be worth it.
  7. Guardrail: a per-tenant monthly budget and an alert at 3x normal hourly spend stop one integration bug from wiping out these savings.

Picture it

LLM cost is like a taxi meter rather than a monthly bus pass. You save by not taking unnecessary trips, taking the shortest route (fewer tokens), using an auto-rickshaw instead of an SUV when you are alone with no luggage (smaller model), sharing rides that go the same way (caching and batching), and checking each department's taxi bill every week.

Key patterns

Model cascade

When: Mixed easy and hard requests

How: Send to a small model first; escalate to a large model when validation fails or confidence is low. Measure escalation rate and quality per slice.

Generate once, serve many

When: The same output serves many users

How: Precompute summaries, descriptions or translations asynchronously (ideally with batch pricing) and serve them from a database or CDN.

Cost per successful outcome

When: Comparing models or deciding where to use AI

How: Divide total cost by resolved tickets, accepted suggestions or completed tasks; a pricier model can be cheaper per outcome if it succeeds more often.

Versioned price table

When: Cost reporting and billing

How: Store token counts per call and join with prices effective at call time; never recompute history with today's price.

Real-world use

Batch APIs at half price

OpenAI's Batch API and Anthropic's Message Batches API accept large sets of requests and return results within 24 hours at about a 50% discount, a direct saving for any work that is not interactive.

Provider prompt caching discounts

OpenAI applies automatic caching to long repeated prefixes and Anthropic bills explicit cache reads at about a tenth of the input price, which makes long system prompts and agent tool lists far cheaper when prompts are ordered correctly.

Flat-price AI subscriptions

Many AI products charge a flat monthly price while each user's token use varies by 10-100x. A small group of heavy users can cost more than they pay, so teams add per-user token budgets, route routine requests to cheaper models and watch cost per active user, not just total spend.

OpenCost and per-tenant attribution

OpenCost (a CNCF project) allocates Kubernetes infrastructure cost to namespaces and workloads; combined with per-call LLM usage events from a gateway, teams get a full cost per tenant and feature.

In a project

A Jaipur-based social app with 20M monthly users launched AI captions and replies in Hindi and English. The free feature costs about Rs 1.8 crore a month, more than the app's ad revenue from those users.

  1. Instrument cost per feature and per user segment from gateway usage events; find that 8% of users generate 55% of tokens and that Hindi requests average 2.7x the tokens of English ones.
  2. Stop generating three caption suggestions automatically on every photo upload; generate only when the user taps 'Suggest caption', cutting calls by about 60%.
  3. Move caption generation to a smaller model after evals with 500 Hindi and English photos show equal ratings from human raters; keep the larger model for longer replies.
  4. Evaluate a model with a more efficient tokenizer for Indic scripts and compare total cost per Hindi request, not price per token.
  5. Cap max_tokens at 60 for captions and shorten the system prompt from 1,200 to 450 tokens, placing it first for prefix caching.
  6. Add a daily free quota per user (for example 20 AI actions) with a clear message, and a per-feature budget alert at 120% of the daily plan.
  7. Precompute nothing personal, but cache trending sticker-text suggestions per language with an exact cache.

Impact: Monthly AI cost drops by about 80% while usage of the feature by active users stays flat, and the team can now show cost per AI action per language to decide where to expand.

Trade-offs

Use it when

  • AI features at scale where token spend is a visible share of revenue or infrastructure cost
  • Free or low-priced consumer features with millions of users
  • Multi-tenant products that need per-customer limits, pricing or billing
  • Before choosing between hosted APIs and self-hosting

Avoid it when

  • Early prototypes where usage is tiny: optimise for learning speed and quality first, but still log usage
  • Cutting cost in ways that silently lower quality without running evals
  • Self-hosting GPUs for spiky, low-volume traffic where idle hours dominate the bill
  • Micro-optimising prompts when one product change (fewer calls) would save far more

Common mistakes

  • Estimating only requests, not tokens per request, and discovering the bill after launch.
  • Using the largest model for every call, including classification and extraction that small models do equally well.
  • Sending the entire conversation history and 30 retrieved chunks on every turn.
  • Ignoring output length, the expensive side, by not setting max_tokens or a concise format.
  • Breaking provider prompt caching with dynamic content at the start of the prompt.
  • No per-tenant budget or anomaly alert, so one runaway loop or abusive user spends a month's budget in a day.
  • Computing past cost with current prices, or forgetting cached-token and batch discounts.
  • Comparing models by price per token instead of cost per successful outcome at equal quality.

Interview questions

Quick revision

  • Cost = calls x (input tokens x input price + output tokens x output price).
  • Output tokens usually cost 3-5x input tokens; cap them.
  • Cheapest call is the one you skip: rules, templates, generate on action, precompute shared results.
  • Trim context: recent turns + summary, 5-10 chunks, only needed fields and tools.
  • Static-first prompts for cached-input discounts.
  • Small model for classification and extraction; cascade to large on low confidence.
  • Batch APIs: about 50% off for work that can wait up to 24 h.
  • Self-host only with high steady utilisation; idle GPUs still cost money.
  • Budgets per tenant and feature, cost caps per agent run, anomaly alerts.
  • Attribute cost per tenant, feature and outcome with a versioned price table.
  • Indic text can need several times more tokens; compare cost per request, not per token.

Check yourself

1. A call uses 2,000 input tokens and 500 output tokens at $1 per million input and $5 per million output. What does it cost?

2. Nightly you summarise 3 million documents; results are needed by the next morning. What is the most direct saving?

3. Model A costs $0.01 per ticket and resolves 50% of tickets; model B costs $0.015 per ticket and resolves 80%. Which is cheaper per resolved ticket?

4. Why should historical LLM cost be computed from a versioned price table?

Saved on this device. Create a free account to keep it on every device.

Practise this with Sam

A real mock interview, out loud, with an honest scorecard. Free to start.

Start free