Course contents

16. AI System Design Lesson 1 of 10

LLM Application Architecture

See where the time goes in an LLM request, what streaming changes, and how timeouts, quotas, retries and model fallbacks shape the architecture.

18 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An LLM request spends almost all its time generating tokens; your own code barely shows.
  • Streaming improves time to first token but not total time or the capacity a request holds.
  • Slow model calls pile up: concurrency = rate × latency. Timeouts bound the damage.
  • Quotas in requests and tokens per minute are usually the first limit; retries cannot exceed them.
  • A gateway routes across models and quotas and fails over when a provider is down.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. An app, an orchestrator, a model API

    A chat feature is three layers. The Chat API owns the HTTP endpoint, authentication and the user’s session. Orchestration builds the prompt: system instructions, conversation history, retrieved context and tool definitions. Then it calls the model API over HTTPS.

    The Chat API sends about 3 requests per second. Orchestration takes ~40 ms; the model needs about 3 seconds to generate an answer. Look at P50: almost all of it is generation. Making the orchestration code twice as fast would not be visible.

    Scene: The Chat API sends 3 requests per second through Orchestration to Model A. Each request takes about 3 seconds, almost all of it inside the model.

    Key idea: In an LLM request, generation time dominates: your own code is a rounding error next to the model call.

  2. 2. Stream the tokens

    A model writes its answer one token at a time. First it reads the whole prompt (prefill), then it generates tokens one after another (decode). With streaming (server-sent events in most model APIs), each chunk is passed on as soon as it exists.

    This scripted walk-through follows one answer: the first chunk reaches the user after about 0.6 s (time to first token), the last after about 3 s. The total time is the same, and the model slot is busy just as long. Streaming changes what the user *feels*, not the capacity you need.

    Scene: A scripted request travels from Users to Model A. After about half a second the first token chunk flows back through Orchestration and the Chat API to the user, followed by a chunk every 250 ms until the answer is complete after about 3 seconds.

    Key idea: Streaming cuts time to first token, not total generation time or the capacity a request occupies.

  3. 3. The provider slows down

    One second in, the provider has a bad day and generation becomes twice as slow. Nothing fails. Requests just take ~6 s instead of ~3 s, and the Chat API has a 30-second timeout, so it waits.

    Watch in flight: by Little’s law, concurrency = rate × latency. At 3 requests/s and 6 s each, about 18 calls are open at once instead of 9. Every one of them holds a connection, memory and, in many apps, a slot in a limited pool. Slow is often worse than down.

    Scene: Model A becomes twice as slow. Requests take about 6 seconds and the number of requests in flight roughly doubles.

    Key idea: When a dependency slows down, open calls pile up: concurrency = rate × latency.

  4. 4. Bound the wait

    The Chat API now gives up after 8 seconds. The slowest requests, roughly one in six here, fail with a timeout instead of hanging. No user waits more than 8 s, and the tail of open calls is cut off.

    Two things a timeout does not do: it does not make the model faster, and it does not stop the work. The model keeps generating answers nobody will read, and you may still pay for those tokens. With streaming, use two limits: one for the first token and one for the gap between chunks, rather than one tight total.

    Scene: With an 8-second timeout, the slowest requests fail as timeouts. No successful request takes longer than 8 seconds, but Model A keeps working on requests the Chat API abandoned.

    Key idea: A timeout turns slow into a fast, visible failure. Size it from the model’s real latency distribution.

  5. 5. 429 Too Many Requests

    The provider recovers and the feature launches: traffic grows to 8 requests per second. Model APIs enforce quotas per account and model, in requests per minute and tokens per minute. This account’s quota works out to about 5 requests per second at ~1,500 tokens each.

    Everything above the quota is refused at once with HTTP 429. Roughly a quarter to a third of the requests now fail, while the model itself has plenty of free slots. The limit is the contract, not the hardware.

    Scene: Traffic rises to 8 requests per second. Model A accepts about 5 per second and answers the rest immediately with 429, so roughly a quarter to a third of requests fail.

    Key idea: Quotas, not servers, are usually the first capacity limit of an LLM feature. Plan in tokens per minute.

  6. 6. Retries cannot buy quota

    The Chat API now retries failures: up to 3 attempts, exponential backoff starting at 1 s, with full jitter. Official model SDKs do this by default for 429 and 5xx; in .NET, Microsoft.Extensions.Http.Resilience gives you the same pipeline.

    Watch offered load: attempts per second climb well above 8, but throughput stays near 5 and the error rate barely moves. Retries rescue requests hit by a short burst. Against a steady overload they only add more 429s. Honour the provider’s Retry-After header and cap the attempts.

    Scene: The Chat API retries failed requests up to three times. Attempts per second rise above 8, but Model A still accepts only about 5 per second and the share of failed requests stays about the same.

    Key idea: Retries smooth out bursts; they cannot create capacity. Under steady overload they make it worse.

  7. 7. A gateway and a second model

    An LLM gateway now sits between orchestration and the models. It sends requests alternately to Model A and Model B, a smaller, faster model (~1.5 s) on a separate quota of ~10 requests/s, for example another provider, region or deployment.

    Each model gets about 4 requests/s, under both quotas: the 429s disappear and P50 drops, because half the answers come from the faster model. The catch: two models do not answer the same way. Every prompt now has to be tested against both.

    Scene: An LLM gateway forwards requests alternately to Model A and Model B. Each gets about 4 requests per second, nothing is rate limited and median latency drops.

    Key idea: A gateway turns several models and quotas into one endpoint you can route, split and fail over.

  8. 8. Model A goes down

    At 1.5 s Model A has an outage. Answers it was generating are lost, and requests the gateway still sends there are refused. The gateway probes each model every second; after two failed probes it stops routing to A and everything goes to Model B, which has quota to spare.

    In the gap, the Chat API’s retries land on Model B and rescue most of the failed calls, so users see few errors. One caveat the model cannot show: a stream that dies halfway cannot be retried invisibly; the user has already seen half an answer.

    Scene: Model A goes offline. Requests sent to it fail until the gateway’s health checks remove it, about two seconds later; retries move most of those requests to Model B, which then serves all traffic.

    Key idea: Fallback = detect the failure, route to another model, retry the requests caught in between.

  9. 9. The shape of an LLM application

    Keep the layers apart: an API that owns users and sessions, orchestration that owns prompts and tools, a gateway that owns routing, quotas, retries and fallbacks, and models behind it. In .NET, Microsoft.Extensions.AI gives orchestration code one IChatClient abstraction over providers, which makes the gateway’s job of swapping models easier.

    What the simulation leaves out: cost per token, prompt caching, content filters and evaluation. Every model call is slow, metered and non-deterministic. Treat it like a remote dependency that will be slow, throttled and down, because it will be.

    Scene: The full architecture: Chat API, Orchestration, LLM Gateway and two models. Model B serves all traffic while Model A is offline.

    Key idea: Design an LLM call like any slow, metered, unreliable dependency: timeouts, bounded retries, quotas and a fallback.