Calling a language model from a prototype takes ten lines of code. Calling one from a product that thousands of people use every day, with latency targets, error budgets and a finance team watching the bill, is a different job. The model is a remote dependency that is slow, non-deterministic, occasionally wrong, rate limited and priced per token. Treating it like any other API leads to timeouts, broken JSON and surprise invoices.
This article covers the integration patterns that hold up in production: when to call the model synchronously and when not to, how to stream, how to get reliable structured output, how to fail gracefully, and where caching actually helps. The examples are provider-neutral. The trade-offs apply whether you use a hosted API or a self-hosted model.
Start with the shape of the request
Before choosing a pattern, classify the feature by how a user experiences it. Three questions do most of the work.
- Is the user waiting on the answer, staring at a spinner or a chat box?
- Does the output feed another system, or is it displayed to a person?
- What does a wrong answer cost, and can it be caught before it matters?
A chat assistant, a document summary that appears after upload, and a nightly classification of support tickets look similar from the model’s side, but they need three different integration designs. The mistake we see most often is building the chat design for everything: a synchronous call inside a web request, with a 60 second timeout and no retry policy.
The model call is rarely the hard part. The hard part is deciding what the product does when that call is slow, malformed or wrong.
Synchronous versus asynchronous calls
Synchronous request and response
The simplest pattern is to call the model inside the request handler and return the result. It works when the expected latency is under a few seconds and the volume is modest. Short classification, intent detection and small rewrites fit here, especially with a small, fast model.
The risks are well known. Model latency has a long tail: a call that normally takes 1.5 seconds can take 20 under load. Your web workers sit blocked while they wait, so a provider slowdown becomes your outage. Set explicit timeouts on every call, cap concurrency with a semaphore or queue, and decide in advance what the user sees when the timeout fires.
Asynchronous jobs
For anything that takes more than a few seconds, or that does not need an immediate answer, use a job queue. The request handler stores a task, returns an identifier, and a worker calls the model. The client either polls, subscribes to a server-sent event stream or receives a webhook or push notification.
Asynchronous design gives you things synchronous cannot:
- Retries with exponential backoff and jitter, without holding a user connection open.
- Rate limit control: the worker pool size is your concurrency knob.
- Batch endpoints, which many providers price at roughly half the interactive rate in exchange for a delay of up to 24 hours.
- Idempotency: a job key means a retry never produces two charges or two emails.
The price is complexity in the UI. You need states such as queued, running, failed and done, and a clear way to show them. For back-office workflows such as extracting fields from invoices or tagging a backlog, that complexity is worth it.
A rule of thumb
If the user is waiting and the work fits in about three seconds, call synchronously with a timeout. If the user is waiting and the work is longer, stream. If nobody is waiting, queue it and batch it.

Streaming
Streaming changes perceived latency more than any other technique. A response that takes eight seconds to complete feels fast if the first words appear in 400 milliseconds. Most providers expose token streaming over server-sent events, and the pattern is straightforward: your backend opens a stream to the model and relays chunks to the browser.
Practical details that bite teams:
- Proxy buffering. Reverse proxies and CDNs often buffer responses and destroy the effect. Disable buffering on the streaming route and send periodic heartbeat comments to keep idle connections open.
- Cancellation. When the user closes the tab or presses stop, abort the upstream request. Otherwise you pay for tokens nobody reads.
- Partial output handling. A stream can fail halfway. Decide whether you keep the partial text, show an error, or retry transparently. For anything the user might act on, show that the answer is incomplete.
- Post-processing. Moderation, redaction and citation checks are harder on a stream. Either run them on sentence boundaries or accept a short buffer, for example hold back the last 50 characters until the next chunk arrives.
- Token accounting. Record usage from the final event, and write it to your logs even when the client disconnects early.
Streaming does not reduce total cost or total time. It improves how the wait feels. It also conflicts with structured output, which is the next topic: a half-finished JSON document is not useful to a parser.
Structured output
Any time a model’s output feeds code, free text is a liability. Three techniques exist, in rising order of reliability.
- Prompt and parse. You ask for JSON in the prompt and parse the reply. It works most of the time and fails in embarrassing ways: markdown fences around the JSON, trailing commentary, a missing comma.
- JSON mode or tool calling. The provider constrains the output to valid JSON, or to the arguments of a declared function. Syntax errors mostly disappear, but the content can still violate your schema.
- Schema-constrained decoding. The provider or inference engine enforces a JSON Schema during generation, so the output conforms by construction. Self-hosted engines support grammar-based constraints for the same purpose.
Whichever you use, validate on your side. A schema validator such as Zod, Pydantic or Ajv is cheap, and it catches semantic problems the model cannot: a date in the future, an amount that is negative, an enum value that does not exist. When validation fails, retry once with the error message appended, then fall back.
from pydantic import BaseModel, ValidationError
class Ticket(BaseModel):
category: str # one of: billing, bug, feature, other
urgency: int # 1 to 5
summary: str
def classify(text: str) -> Ticket:
for attempt in range(2):
raw = call_model(prompt(text), schema=Ticket.model_json_schema())
try:
return Ticket.model_validate_json(raw)
except ValidationError as err:
text = f"{text}\n\nPrevious output was invalid: {err}"
return Ticket(category="other", urgency=3, summary=text[:200])
Keep schemas small and flat. Deeply nested structures with many optional fields raise error rates. Prefer enums over free strings, and put the reasoning field before the answer field if you want the model to think before it commits.
Fallbacks and failure handling
Every model dependency will fail. Plan for four kinds of failure, each with its own response.
| Failure | Typical signal | Response |
|---|---|---|
| Rate limit | HTTP 429 | Retry with backoff, honor the retry-after header, shed low-priority load |
| Provider outage | 5xx, timeouts | Circuit breaker, switch to a secondary provider or model |
| Malformed output | Validation error | One repair retry, then a deterministic default |
| Low-quality output | Failed check or low confidence | Escalate to a larger model or a human queue |
Model and provider fallbacks
A secondary model is the most effective resilience measure, and also the easiest to get wrong. Prompts tuned for one model often behave differently on another, so test the fallback path with the same evaluation set you use for the primary. If you fail over without testing, you will find the regressions during the outage.
Use a circuit breaker so you do not keep hammering a failing endpoint. After a threshold of consecutive failures, route traffic to the fallback for a cooling-off period, then probe the primary with a small share of requests.
Graceful degradation
Decide what the feature does with no model at all. A search box can fall back to keyword search. A smart reply feature can hide itself. A summary can show the first paragraph. The user should see a working product with reduced intelligence, not an error page. This is a product decision, so make it with design and not after the first incident.
Retries need discipline
Retry only on errors that can succeed on a second attempt, cap total attempts, and add jitter. Two retries with a 30 second timeout each can turn into a minute of waiting. Set an overall deadline for the whole operation and pass it down.
Caching
Language model calls are expensive and slow compared with a cache lookup, but caching generated text is subtle. There are three layers worth knowing.
Exact-match caching
Hash the full prompt together with the model name and parameters, and store the response. This is safe and trivial, and it pays off for deterministic jobs: classifying the same product description, summarizing the same document version, translating a fixed string. Set temperature low for these calls so that a cached answer is representative.
Prompt caching at the provider
Many providers discount repeated prompt prefixes, often by 50 to 90 percent on the cached portion, and reduce latency too. To benefit, structure prompts so the stable part comes first: system instructions, tool definitions, reference documents. Put the variable user input at the end. A single dynamic value such as a timestamp near the top of the prompt can destroy the cache hit rate, so audit for that.
Semantic caching
A semantic cache embeds the incoming question and returns a stored answer when a previous question was close enough. It can cut cost sharply for repetitive support traffic, but it carries real risk: two questions that are close in embedding space can have different correct answers, such as a question about a policy for one country versus another. If you use it, set a conservative similarity threshold, scope the cache by tenant and by data version, and log hits so you can audit them. Do not use it for personalized or time-sensitive answers.
Observability and control
You cannot operate what you cannot see. Log every call with a request identifier, prompt template version, model, token counts, latency, and outcome of validation. Store full prompts and responses with the same access controls as your production database, because they often contain personal data, and apply a retention limit.
Track a few numbers on a dashboard:
- p50 and p95 latency, time to first token for streaming routes.
- Error rate by type, from the table above.
- Fallback rate. A rising fallback rate is an early warning.
- Cost per request and cost per active user.
- A quality signal, such as thumbs down rate or edit distance between model draft and final text.
Put a kill switch behind a feature flag so that you can turn off a feature or switch models without a deploy. Version your prompts as you version code, and roll changes out gradually.
Putting it together
A typical production design for a customer-facing assistant looks like this: the browser opens a streaming connection; the backend assembles a prompt with a cache-friendly prefix; a gateway layer enforces timeouts, concurrency limits and budgets; the primary model streams tokens, with a circuit breaker routing to a secondary model on failure; output passes through lightweight checks; usage is logged to a metrics pipeline. Background work such as indexing, tagging and report generation runs through a queue with batch pricing and idempotent jobs.
None of this is exotic. It is the same discipline teams apply to payments or email delivery, applied to a component whose behavior is probabilistic. At Datainter we usually put the model behind a thin internal gateway from the first sprint, because retrofitting timeouts, logging and fallbacks into scattered call sites is far more expensive than building the seam early.
Key takeaways
- Choose sync, streaming or queued execution based on who is waiting and for how long, not on what is easiest to code.
- Stream for perceived speed, but cancel upstream calls when the client leaves, and plan for partial failures.
- Use schema-constrained output where available and always validate on your side, with one repair retry and a deterministic default.
- Test the fallback model against the same evaluation set as the primary, and define a no-model experience for every feature.
- Order prompts so stable content comes first to benefit from provider prompt caching, and treat semantic caching as a risky optimization to scope tightly.
- Log prompts, versions, tokens, latency and outcomes from day one, and keep a kill switch.

