Cost and Latency: Making AI Features Cheap Enough to Ship

Learn the practical strategies — caching, batching, model tiers, and effort levels — that make AI features affordable and fast enough to actually ship to users.

The Bill That Killed My Demo

I built a little AI-powered writing assistant last year. It worked great in testing. I was proud of it. Then I showed it to about 40 people over a weekend and got a bill that made me physically wince.

The problem wasn't that AI was expensive. The problem was that I was measuring cost completely wrong. I was thinking in terms of requests — each button click, each API call. But the real question is always: how much does it cost to complete one useful task for one user? That reframe changed everything about how I design AI features now.

This article is everything I wish I'd known before that weekend. We're going to talk about caching, batching, model selection, effort levels, and how to think about all of it together.

Measure Per Task, Not Per Request

Before we touch any technique, the mindset shift: a single user task might involve three, five, or ten API calls under the hood. If you optimize one call but leave four wasteful ones running, you haven't really solved anything.

So whenever I'm evaluating cost or latency, I track it like this:

python
# Track cost at the task level, not request level
class TaskCostTracker:
def __init__(self):
self.total_input_tokens = 0
self.total_output_tokens = 0
self.requests_made = 0

def log_request(self, response):
self.total_input_tokens += response.usage.input_tokens
self.total_output_tokens += response.usage.output_tokens
self.requests_made += 1

def cost_usd(self, input_rate, output_rate):
# rates are per million tokens
return (
(self.total_input_tokens / 1_000_000) * input_rate +
(self.total_output_tokens / 1_000_000) * output_rate
)

Once you're tracking this way, you'll often find one or two requests are responsible for 80% of your bill. That's where to focus.

Model Choice: The Biggest Lever You Have

People agonize over prompt optimization when the biggest cost reduction is just picking a smaller model. The price difference between model tiers is genuinely enormous — we're often talking 10x to 50x per token between flagship and mini models.

Here's how I think about routing:

python
def pick_model(task_type: str, complexity: str) -> str:
# Cheap, fast models for simple tasks
simple_tasks = ["classify", "extract", "summarize_short", "route"]
if task_type in simple_tasks or complexity == "low":
return "gpt-4o-mini" # or claude-haiku, gemini-flash

# Mid-tier for most real work
medium_tasks = ["draft", "explain", "refactor"]
if task_type in medium_tasks:
return "gpt-4o" # or claude-sonnet

# Flagship only when it truly matters
return "o1" # or claude-opus — multi-step reasoning, high stakes

The rule I follow: start with the cheapest model that could plausibly do the job. If your evals show it's failing, step up. Don't start at the top and work down — you'll never bother to optimize.

The 90/10 rule of model routing

In most apps, 90% of requests are simple classification, extraction, or short generation tasks. If you route those to a mini model, you can afford the full flagship for the 10% that actually need it — often for the same total monthly cost.

Effort Levels: Telling the Model How Hard to Think

Newer models — especially OpenAI's o-series and Claude's extended thinking — have configurable reasoning effort. This is distinct from model choice. You're telling the same model to spend more or fewer internal reasoning steps before responding.

High effort is expensive. Low effort is fast and cheap. Use it deliberately:

python
# OpenAI reasoning effort example
response = client.chat.completions.create(
model="o3-mini",
messages=messages,
reasoning_effort="low" # "low", "medium", or "high"
)

# Claude extended thinking — set a token budget
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 1024 # Keep thinking short for simple tasks
},
messages=messages
)

When I first tried extended thinking, I had the budget set at 10,000 tokens for every request. It was doing doctoral-thesis-level reasoning to answer "what's a good headline for this paragraph?" Dropping that budget to 1,024 for simple tasks cut my costs dramatically with zero quality loss.

Caching: Pay Once, Use Many Times

Both OpenAI and Anthropic now offer prompt caching — if the same prompt prefix shows up repeatedly, the provider caches the computed tokens and charges you significantly less for repeat hits. Anthropic charges about 10% of normal input pricing for cache reads.

The key insight: your system prompt is the same on every request. If it's 2,000 tokens and you're making 10,000 requests a day, caching that prefix alone saves a lot of money.

python
# Claude: mark cache breakpoints with cache_control
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": long_system_context, # e.g., your 5000-token knowledge base
"cache_control": {"type": "ephemeral"} # Cache this prefix
},
{
"type": "text",
"text": user_query # This part changes each request
}
]
}
]

Beyond API-level caching, you can also cache your own results. If multiple users are likely to ask similar questions, semantic caching — storing past responses and fuzzy-matching new queries against them — can be very effective. Libraries like GPTCache or a simple Redis layer with embedding similarity can get you there.

Cache TTL matters

Anthropic's prompt cache lasts 5 minutes by default, with longer TTLs available. Structure your requests so the cacheable prefix comes first and stays stable. Injecting timestamps or dynamic content early in the prompt will bust the cache every time.

Batching: When You Don't Need the Answer Right Now

Both OpenAI and Anthropic offer batch APIs that process requests asynchronously — typically within a few hours — at roughly half the normal per-token price. If your feature doesn't need a real-time response, batching is free money.

Good candidates for batching: nightly report generation, background enrichment of user data, bulk document classification, pre-generating summaries that get cached before users request them.

python
# OpenAI Batch API — submit a file of requests
import json

requests = [
{
"custom_id": f"task-{i}",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": doc}]
}
}
for i, doc in enumerate(documents_to_process)
]

# Write to JSONL and upload
with open("batch_input.jsonl", "w") as f:
for req in requests:
f.write(json.dumps(req) + "\n")

# Submit and poll for results
batch_file = client.files.create(open("batch_input.jsonl", "rb"), purpose="batch")
batch = client.batches.create(input_file_id=batch_file.id, endpoint="/v1/chat/completions", completion_window="24h")

Output Length: The Hidden Cost Driver

Output tokens are more expensive than input tokens on most APIs — and they're the ones you have the most control over. I've seen prompts that say "please provide a comprehensive, detailed explanation" when what was actually needed was a one-paragraph summary. That's burning money on tokens nobody wanted.

Be explicit about the output you need:

prompt
# Instead of this:
"Explain what this function does."

# Be specific about format and length:
"Explain what this function does in 1-2 sentences. No code examples needed."

# For structured data, use JSON mode — it eliminates preamble tokens:
"Return JSON with keys: summary (string, max 50 words), sentiment (positive/negative/neutral)"

Setting max_tokens as a hard ceiling is also worth doing for user-facing features where you know the expected response length. It won't hurt quality if set reasonably, and it protects you from occasional runaway responses.

Putting It Together: A Decision Framework

When I'm designing a new AI feature, I now run through this checklist before writing a single line of code:

Pre-build cost checklist

1. What's the minimum model tier that could do this job? Start there. 2. Does any part of the prompt stay the same across requests? Mark it for caching. 3. Does this need to be real-time, or can it be batched? 4. What's the maximum output length I actually need? Set that explicitly. 5. How many API calls happen per user task? Track all of them together.

The goal isn't to be cheap for its own sake — it's to build features that are economically sustainable at scale. An AI feature that costs $0.50 per user per day isn't a product, it's a liability. The same feature, properly optimized, might cost $0.02 and suddenly becomes something you can actually ship and grow.

The weekend that burned me taught me that AI costs aren't a fixed property of the technology — they're a design choice. And once you start thinking per task instead of per request, you'll find the expensive parts surprisingly quickly.

Keep going

More tutorials in this category, or explore the full field guide.

More ChatGPT Tutorials Official Docs ↗