Common mistakes when building with the Anthropic API and how to avoid them.
Use when working with known-pitfalls patterns.
Trigger with "anthropic mistakes", "claude pitfalls", "anthropic gotchas",
"common claude errors", "anthropic anti-patterns".
Common mistakes when building with the Anthropic API and how to avoid them.
Use when working with known-pitfalls patterns.
Trigger with "anthropic mistakes", "claude pitfalls", "anthropic gotchas",
"common claude errors", "anthropic anti-patterns".
Ten common mistakes when building with the Anthropic API and how to avoid them: forgetting max_tokens (required), system prompt in messages array (wrong), non-alternating messages, unchecked stop_reason, creating client per request, no 529 handling, hardcoded model IDs, expensive output tokens, no streaming, and unnecessary PII.
1. Forgetting max_tokens
Unlike OpenAI, max_tokens is required. Omitting it returns a 400 error.
Claude uses a top-level system parameter, not a system message in the array.
// BAD — this sends "system" as a user message role, which will errormessages: [{ role: 'system', content: '...' }, { role: 'user', content: '...' }]
// GOODsystem: 'You are helpful.',
messages: [{ role: 'user', content: '...' }]
3. Non-Alternating Messages
Messages must strictly alternate between user and assistant.
// BAD — two user messages in a rowmessages: [
{ role: 'user', content: 'Hello' },
{ role: 'user', content: 'How are you?' }, // ERROR
]
// GOOD — combine into one or add assistant betweenmessages: [
{ role: 'user', content: 'Hello. How are you?' },
]
4. Not Checking stop_reason
If stop_reason === 'max_tokens', the response was truncated.
if (message.stop_reason === 'max_tokens') {
// Response is incomplete — increase max_tokens or handle truncation
}
5. Creating Client Per Request
Each new Anthropic() creates a new connection pool. In serverless, this adds latency.
// BAD — new client every request
app.post('/chat', async (req, res) => {
const client = newAnthropic(); // Cold connection every time
});
// GOOD — reuse across requestsconst client = newAnthropic();
app.post('/chat', async (req, res) => {
await client.messages.create({ ... });
});
6. No Error Handling for 529
529 (overloaded) is common during peak hours. The SDK retries automatically, but you should handle it for critical paths.
7. Hardcoding Model IDs
Model IDs change with new versions. Use environment variables.