Skip to content

Menu

Guide

LLM API Best Practices for Production Apps

AIDToolStack Editorial2026-10-256 min read

Treat the model as an unreliable network service

An LLM API is a remote service that is sometimes slow, sometimes overloaded, and occasionally returns something you didn't expect. Most production problems come from forgetting one of those three. This guide covers the habits that prevent them, with examples against the documented behavior of the OpenAI and Anthropic APIs. For the money side specifically, see our AI cost optimization guide.

Keep keys on the server

Never call an LLM provider directly from browser or mobile code with your secret key. Proxy through your backend, where you can authenticate the user, rate-limit them, and log usage. Store keys in your secret manager, give each environment its own key, and rotate them. Spend limits in the provider console are a useful backstop.

Retry the right errors, with backoff

Anthropic's error docs list the status codes you'll see. The ones worth retrying are 429 (rate_limit_error), 500 (api_error), 504 (timeout_error) and 529 (overloaded_error). A 400 (invalid_request_error) or 401 (authentication_error) will fail the same way every time, so retrying only wastes time.

Two details from those docs matter:

  • If the response has a retry-after header, wait that long.
  • Anthropic sends an x-should-retry header; if it says false, don't retry.

The official SDKs already do this. Anthropic's docs say the SDK honors retry-after and otherwise backs off exponentially between 0.5 and 8 seconds. If you're writing raw HTTP calls, here is a tested version of the same idea:

import random, time

RETRYABLE = {408, 409, 429, 500, 502, 503, 504, 529}

class APIError(Exception):
    def __init__(self, status, retry_after=None, should_retry=None):
        super().__init__(f"HTTP {status}")
        self.status, self.retry_after, self.should_retry = status, retry_after, should_retry

def call_with_retries(fn, max_attempts=5, base=0.5, cap=8.0):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except APIError as e:
            if e.should_retry is False or e.status not in RETRYABLE:
                raise
            if attempt == max_attempts:
                raise
            if e.retry_after is not None:
                delay = float(e.retry_after)
            else:
                # full jitter: random wait up to the exponential ceiling
                delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
            time.sleep(delay)

The jitter matters. If a thousand clients all retry after exactly one second, they hit the API together again. Also note a case from Anthropic's docs: a 429 caused by reaching a spend cap has no retry-after header and keeps failing, so alert on it instead of retrying forever. Our API rate limiting guide covers the server side of the same problem.

Set timeouts and stream long responses

Long generations take a while. Set an explicit client timeout rather than inheriting a default you haven't read. For long responses, use streaming: Anthropic's docs recommend the streaming API for long-running Messages requests, and it lets your UI show text as it arrives instead of a spinner.

When streaming, remember that an error can arrive mid-stream after you've already returned a 200 to your own client. Decide in advance what the UI shows in that case, and log the partial output.

Always cap output

Set max_tokens on every call. It bounds latency and cost, and it protects you from a prompt that accidentally triggers a very long answer. Then check the stop reason in the response: if the model stopped because it hit the limit, the output may be cut off mid-sentence or mid-JSON.

Get structured output the reliable way

If your code parses the response, don't rely on "please reply in JSON". Use the provider's structured output feature. On Anthropic's API you pass a JSON schema in output_config.format:

"output_config": {
  "format": {
    "type": "json_schema",
    "schema": {
      "type": "object",
      "properties": {
        "label": {"type": "string", "enum": ["bug", "feature_request", "billing", "other"]},
        "confidence": {"type": "number"}
      },
      "required": ["label", "confidence"],
      "additionalProperties": false
    }
  }
}

Per Anthropic's docs, the output is constrained to match the schema. Not every JSON Schema feature is supported (for example minimum/maximum and recursive schemas aren't), so still validate business rules in your own code. Tools like our JSON to Zod converter help you write that validation layer.

Cache what repeats

Two kinds of caching help:

  • Prompt caching at the provider. Put stable content (system prompt, tool definitions, reference docs) first and anything that changes per request last. OpenAI caches long prefixes automatically on supported models; Anthropic uses cache_control markers. Keep timestamps and request IDs out of the prefix or you'll never get a hit.
  • Response caching in your app for identical requests, keyed on a hash of the model, prompt version and normalized input.

Version your prompts

A prompt change is a behavior change. Keep prompts in version control, give each a version name, and log that name with every request. When quality drops, you can tell whether it was the prompt, the model, or the input that changed. Pin model versions rather than using aliases that silently move, and test before you upgrade.

Evaluate before you ship changes

Keep a fixed set of test inputs with expected outputs and run it on every prompt or model change. Anthropic's evaluation docs suggest code-based checks for structured answers and an LLM grader for fuzzy qualities like tone, checked against human judgment. Even a small set catches regressions you'd otherwise hear about from users.

Log enough to debug

For each call, log:

  • the request ID (Anthropic returns it in a request-id header and in error bodies; include it in support tickets)
  • model name and prompt version
  • input and output token counts from the usage object
  • latency, stop reason and any retry count

Be careful with logging full prompts and responses. They may contain user data, so apply the same retention and redaction rules as the rest of your logs.

Plan for the provider being down

Decide what happens when the API is unavailable for ten minutes. Options include a queue that retries later, a degraded feature (search without the AI summary), or a fallback to a second provider. If you use a fallback model, run your evaluation set against it too; a different model with the same prompt can behave quite differently.

A short checklist

  • Keys on the server, per environment, with spend limits
  • Retries only on retryable errors, with jitter and a cap
  • Timeouts set, streaming for long outputs
  • max_tokens on every call, stop reason checked
  • Structured outputs for anything parsed by code
  • Stable prompt prefix for caching
  • Prompts versioned, evaluated, and logged
  • A plan for outages

Sources

How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.

Reviews and commentsShow

Reviews

Sign in to leave a review.

Loading reviews…

Comments

Sign in to leave a comment.

Loading comments…