Cost & Token Management
You pay per token, in and out. Watch usage, cap output, and pick the right model.
Claude bills by tokens — small chunks of text (about 4 characters each). You pay for both the tokens you send (input) and the tokens Claude generates (output).
Levers on cost
- Model choice — Haiku is far cheaper than Opus for simple tasks.
- max_tokens — cap output so long answers do not surprise you.
- Prompt size — trim unnecessary context; do not resend more than needed.
Measure it
Every response includes a usage object with input and output token counts. Log these to understand and control your spend.
Example
const res = await client.messages.create({
model: "claude-opus-4-8", max_tokens: 500,
messages: [{ role: "user", content: "Summarize the news." }],
});
const u = res.usage;
console.log(`Input tokens: ${u.input_tokens}`);
console.log(`Output tokens: ${u.output_tokens}`);
// Multiply by the model's per-token price to estimate cost,
// and switch simple tasks to claude-haiku-4-5-20251001 to save.When to use it
- Log input and output tokens per request to a database so you can generate per-user billing reports.
- Set max_tokens to 150 for a product-description feature to prevent Claude from generating overly long, expensive responses.
- Switch from claude-sonnet-4-5 to claude-haiku-4-5 for classification tasks to cut token costs by an order of magnitude.
More examples
Log token usage after every request
Persists per-request token counts to a database for cost tracking and per-user billing.
const msg = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 256,
messages: [{ role: "user", content: userQuestion }],
});
const { input_tokens, output_tokens } = msg.usage;
await db.query(
"INSERT INTO usage_log (user_id, input, output, ts) VALUES ($1,$2,$3,NOW())",
[userId, input_tokens, output_tokens]
);Cap output with max_tokens
A tight max_tokens cap prevents Claude from generating explanatory prose for simple classification tasks.
// Force short answers for a classification task
const msg = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 8, // single-word or very short reply
system: "Reply with one word: positive, negative, or neutral.",
messages: [{ role: "user", content: review }],
});Estimate cost before sending
Approximates token count from character length to estimate cost before the request is made.
// Rough token estimation (~4 chars per token)
function estimateTokens(text) {
return Math.ceil(text.length / 4);
}
const prompt = buildPrompt(userInput);
const estimatedInputTokens = estimateTokens(prompt);
// Haiku pricing as of 2025: $0.00025 per 1k input tokens
const estimatedCost = (estimatedInputTokens / 1000) * 0.00025;
console.log(`Estimated cost: $${estimatedCost.toFixed(6)}`);
Discussion