What it is
An LLM application is ordinary software with one unusual dependency: a model API that turns a prompt into generated text. Around it sit familiar layers. An API owns users, authentication and sessions. Orchestration builds the prompt from instructions, conversation history, retrieved documents and tool definitions, calls the model and post-processes the answer. A gateway (optional at first, standard at scale) routes calls to models, enforces quotas and handles failover. The model itself is usually a hosted API, sometimes a self-hosted inference server.
Why it exists
You can call a model API from a controller in ten lines. That works until the call takes seconds instead of milliseconds, the provider answers 429, a model version is retired, or a region goes down. The architecture exists because a model call is slow, metered, rate limited, non-deterministic and owned by someone else. Each layer isolates one of those problems so features do not each solve them differently.
How it works
Prefill and decode. The model first processes the whole prompt (prefill), then generates output tokens one at a time (decode). Time to first token grows with prompt length; total time grows mostly with the number of output tokens. A few hundred output tokens take seconds on typical hosted models. Your own work (database lookups, prompt assembly) is usually tens of milliseconds.
Streaming. Most model APIs can stream the answer as server-sent events. The application forwards chunks to the browser as they arrive (in ASP.NET Core, an IAsyncEnumerable or SSE response; with Microsoft.Extensions.AI, GetStreamingResponseAsync). The user starts reading after the prefill. The request still lasts as long and holds its connection, its slot on the model side and its share of quota just as long.
Concurrency. Little’s law: open calls = arrival rate × duration. 20 requests/s at 4 s each is 80 concurrent calls. If latency doubles because the provider is slow, so does concurrency, and any fixed-size pool, semaphore or connection limit on that path fills up. Use asynchronous I/O so waiting costs no threads, and size limits from the formula.
Timeouts. A non-streaming call needs a total timeout derived from the real latency distribution of that model and output length. A streaming call is better served by two limits: time to first token and maximum gap between chunks. Check library defaults: the .NET standard resilience handler (AddStandardResilienceHandler) ships with per-attempt and total timeouts that suit ordinary HTTP calls and can be shorter than a long generation.
Quotas and 429. Providers limit requests per minute and tokens per minute per account, model and region; some count input and output tokens separately. Above the limit they answer 429, usually with a Retry-After header. Capacity planning is in tokens: requests per minute × (prompt + output tokens).
Retries. Official SDKs retry 429 and 5xx a couple of times by default, with backoff. Retries help with short bursts and transient errors. Under steady overload they add attempts without adding successes. Cap attempts, use exponential backoff with jitter, honour Retry-After, and never retry a stream the user has already partly seen without telling them.
Gateway and fallback. A gateway presents one endpoint and routes to several deployments: different models, providers or regions, each with its own quota. It can split by weight, route by request type (cheap model for simple tasks), detect failures through health checks or error rates, and fail over. Fallback models answer differently, so prompts and evaluations must cover every model you might route to.
When to use it
- Any feature that calls a hosted model in a request path users wait on.
- When more than one team or feature shares model quota: a gateway gives you per-feature limits and cost attribution.
- When availability matters more than the exact model: fallback across providers or regions.
When not to
- Offline batch jobs (summarise a million documents overnight) do not need streaming or tight timeouts; use the provider’s batch API or a queue with workers and a rate limiter.
- A prototype with one feature and low traffic: a gateway and multi-model routing are overhead until quotas or outages actually hurt.
- Tasks a deterministic rule or a small classifier solves reliably: a model call adds seconds, cost and variance.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Streaming | Fast perceived response, early cancel | More complex error handling; partial answers cannot be retried invisibly |
| Short timeouts | Bounded waits, fewer piled-up calls | More failures during slow periods; abandoned work may still be billed |
| Retries | Survive bursts and transient errors | Extra load and latency; useless against steady overload |
| Fallback model | Availability across provider outages | Different answer quality; prompts and evals for every model |
| Central gateway | One place for routing, quotas, logging | Another hop and component to run redundantly |
Alternatives
- Provisioned or reserved capacity with the provider instead of shared pay-as-you-go quota: predictable throughput, paid whether used or not.
- Self-hosted inference (open-weight models on your GPUs with an inference server): full control over capacity and data, and all the operational work that comes with it.
- Asynchronous UX: accept the request, process it through a queue, notify when done. Avoids holding connections for long generations.
- Smaller or specialised models for narrow tasks (classification, extraction): faster and cheaper, and often good enough.
Failure modes
- Slow provider: nothing fails, everything takes longer, open calls and memory pile up until something else breaks.
- Quota exhaustion: one feature’s spike (or a retry storm) uses the shared quota and every other feature gets 429.
- Timeout mismatch: a generic HTTP timeout shorter than real generations fails long answers every time.
- Mid-stream failure: the connection dies after half an answer; a silent retry produces a different second half.
- Model retirement or silent update: provider model versions change behaviour; pin versions and re-run evaluations before switching.
- Unbounded output: a prompt that invites long answers raises latency and cost; set a maximum output length.
In production
Log every model call with model, prompt and output token counts, latency (time to first token and total) and outcome; attribute cost per feature. Alert on 429 rate and on latency percentiles per model. Pin model versions. Keep prompts versioned alongside code. In .NET, Microsoft.Extensions.AI provides a provider-neutral IChatClient with middleware for logging, caching and telemetry (OpenTelemetry has semantic conventions for generative AI spans); Semantic Kernel builds on it for agent and plugin scenarios. Put resilience (timeouts, retries, circuit breaking) in one shared pipeline rather than in each feature.
Common misconceptions
- "Streaming makes it faster." It makes the first words appear sooner. Total time and capacity are unchanged.
- "More retries mean fewer errors." Only for transient failures. Against a quota they produce more 429s.
- "Our servers are the bottleneck." For most LLM features the first limit is the provider quota in tokens per minute.
- "A timeout stops the work." The provider may finish generating, and you may still pay for it.
- "Any model can be the fallback." Only one whose answers your evaluations have accepted.
Interview angle
Expect questions like “design a chat assistant” or “add an AI summary feature”. Strong answers separate API, orchestration and model access; estimate tokens per request and translate traffic into tokens per minute against the quota; say how streaming works end to end; set timeouts from the latency distribution; explain retry limits and backoff; and describe a gateway with fallback, per-feature quotas and logging. Mention cost per request and that model calls are non-deterministic, so testing needs evaluation sets, not only unit tests.
Model assumptions
The simulation is a simplified model, not a benchmark. The Chat API is the traffic source (Poisson arrivals) and owns timeouts and retries. Orchestration takes ~40 ms. Model A has 32 concurrent slots and ~3 s per answer, Model B ~1.5 s (lognormal, cv 0.4); “degraded” multiplies service time. Provider quotas are a token bucket in requests per second, assuming a fixed ~1,500 tokens per request; real quotas count tokens. A rate-limited call fails immediately (as a 429 would). The gateway probes every second and ejects a model after two failed probes. The streaming step is a scripted illustration: the engine treats each response as one message, so token chunks are drawn as scripted packets. Numbers are illustrative orders of magnitude, not provider measurements.