Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 85/ 160
05. AI System Design

Token Budgets

Hard caps on prompt and completion tokens to control cost and latency.

BeginnerMax Tokens · Truncation3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

A token budget puts a limit on how much text goes in and out of the AI for each request so it never gets too slow or too expensive.

Think of it like…

A household budget: you set limits for rent, food and entertainment, decide what to cut first when money is tight (entertainment before rent) and track spending against each line.

Where you’ve seen it

A support assistant uses an input budget of 7,000 tokens split as: system 800, tools 600, memory 700, retrieved documents 3,000, recent history 1,500 and user message 400, with an output cap of 600 tokens. At illustrative prices of $2.50 per million input and $10 per million output tokens, the worst case is 7,000 × 2.5/1M + 600 × 10/1M = $0.0175 + $0.006 = $0.0235 per request. At 100,000 requests a day that's a ceiling of $2,350 a day, compared with about $1,195 a day at the average usage of 3,100 input and 420 output tokens ($0.01195). The worst-case latency is bounded too: 0.6 s time to first token plus 600 ÷ 150 tokens per second = 4.6 s of decoding. When retrieved text exceeds 3,000 tokens, the lowest-ranked chunks are dropped first; when history exceeds 1,500, older turns are summarised; the system prompt and tool definitions are never truncated. Requests that hit the output cap with finish reason "length" are detected and either continued or flagged.

Words you’ll hear

Context window
The maximum number of tokens (input plus output) a model can process in one call.
max_tokens / completion cap
A limit on generated tokens, bounding cost and decode time.
Priority packing
Filling the prompt in order of importance and trimming the least important parts first.
Finish reason "length"
A signal that generation stopped because the cap was reached, so output may be truncated.

Visual diagram

Loading interactive diagram

Theory & deep dive

Setting and enforcing budgets

Start from the requirements: the context window of the model, the maximum acceptable cost per request and the latency target. Subtract the output cap from the window to get the input ceiling, then allocate it across prompt sections based on the value each adds (found by ablation on the eval set: how much does quality drop if retrieved context is cut from 3,000 to 1,500 tokens?). Count tokens with the model's own tokenizer before the call; character-based estimates (such as characters ÷ 4) are off by 20% or more for code, non-English text and numbers, and the same text tokenises differently across models.

Enforce budgets in a central layer rather than scattered in features: a prompt builder that takes prioritised sections, counts tokens and trims in a defined order. Typical rules are: never truncate system instructions, tool schemas or the user's actual question (reject or ask for a shorter input if it exceeds its cap); drop the lowest-ranked retrieved chunks first (after reranking), then summarise or drop the oldest history, then reduce memory to the top facts. Set max_tokens per task type (short for classification, longer for drafts), and for agents set step and total-token budgets plus a stop condition so a loop can't run away.

Worst-case cost and latency

7,000 input tokens × $2.50/M = $0.0175; 600 output tokens × $10/M = $0.006; total $0.0235. Latency: 0.6 s TTFT + 600/150 = 4.0 s decode = 4.6 s. These are ceilings you can promise, rather than hopes.

Key takeaway: Derive budgets from window, cost and latency limits; count with the real tokenizer; trim by priority in one central builder.

Budgets over time: users, agents and truncation handling

Per-request caps need companions: per-user and per-tenant daily or monthly token quotas, per-feature budgets so an experimental feature can't consume the bill, and alerts at fractions of budget (for example 80% of the daily cap). Return clear errors or degrade gracefully when a quota is exhausted (switch to a cheaper model, shorter answers, or queue the request) instead of failing silently. In conversations, history grows each turn and cost per turn grows with it (turn n re-sends everything), so use sliding windows, summarisation or memory retrieval to keep the input roughly constant, and consider provider prompt caching for the stable prefix.

Handle the output cap carefully. When generation stops with finish reason length, the answer may be cut mid-sentence or mid-JSON; detect it, then retry with a higher cap, ask the model to continue, or fail with a clear message. For structured output, set the cap high enough to fit the schema (and use the schema's shortest field names) so truncation doesn't produce invalid JSON. Log actual token usage per request (input, output, cached) to compare with the budget, find prompts that regularly hit the limit and tune allocations from data. Reasoning models consume hidden reasoning tokens that count toward the cap, so budgets must include them.

Growing history

A chat with 300 tokens per exchange re-sends all prior turns: turn 10 sends about 3,000 tokens of history, turn 20 about 6,000. A 1,500-token history budget with summarisation of older turns keeps turn 20 at about 1,500 plus a 200-token summary instead of 6,000.

Key takeaway: Add quotas, alerts and graceful degradation, summarise long histories and handle truncated outputs explicitly.

How it works, step by step

Step 1 of 4
Engineering

1. Derive the limits

Combine the context window, cost ceiling and latency target to set input and output caps.

7,000 in · 600 out · $0.0235 · 4.6 s
Key numbers at this step
Include
reasoning tokens

When to use it & trade-offs

What it is

A token budget is a hard allocation of how many tokens a request may use: a cap on completion tokens (max_tokens), an allocation of the prompt across its parts (system instructions, tool definitions, memory, retrieved documents, conversation history, the user message) and often per-user, per-feature and per-agent-run limits. Budgets bound cost and latency, because both grow with tokens, and keep prompts inside the model's context window. Enforcement needs a real tokenizer count before the call, a priority order for what gets truncated or summarised, and handling for the case where output is cut off at the limit.

Why it matters: Without budgets, one pathological request (a pasted 200-page document, a runaway agent loop, a model that rambles) can dominate cost and latency, and a growing chat history eventually overflows the window and fails. Budgets turn those risks into predictable worst cases: you can state a maximum cost per request, a maximum latency and a maximum daily spend, and design what degrades first when limits are reached.

When to reach for it

  • Any production LLM feature with cost or latency targets
  • Chat with growing history
  • Agents that could loop

When to avoid or be careful

  • Estimating tokens with character counts
  • Truncating system instructions or tool schemas
  • Ignoring finish reason length

Ways to keep prompts within budget

Truncate lowest-priority content
Best for: Retrieved chunks and old history

Strengths: Simple, predictable.

Watch out: May drop useful information.

Summarise older context
Best for: Long conversations and agent runs

Strengths: Keeps key facts in fewer tokens.

Watch out: Extra call; summaries can lose detail.

Retrieve on demand (memory or RAG)
Best for: Large knowledge or history stores

Strengths: Pulls only what's relevant.

Watch out: Retrieval quality limits answers.

Interview signals & numbers to know

When this topic comes up

  • “One request cost us $5”
  • “Context length exceeded”
  • “Outputs get cut off”
  • Per-user token quotas
  • Agent loop budgets

Benchmarks & rules of thumb

$0.0235 -
worst-case cost per request in the example
$2,350 vs $1,195 -
daily ceiling vs typical spend at 100k requests
4.6 s -
worst-case latency: 0.6 s TTFT + 600 ÷ 150 tokens/s

Common mistakes & follow-ups

Common interview mistakes

  • Setting max_tokens so low that JSON outputs are truncated.
  • Forgetting that hidden reasoning tokens count toward the cap.
  • Letting history grow until the request fails with a context error.

Likely interviewer follow-ups

  • How would you design token limits for a chat product?
  • What do you drop first when a prompt is too long?
  • How do you handle responses that hit max_tokens?
Interview tip: State the worst-case cost and latency your budgets guarantee. It shows budgets as an engineering promise, not just a parameter.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Token Budgets with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Prefix Caching
Next topic
Streaming Responses