Leer en español · Lire en français · Auf Deutsch lesen
Section 12.2 of 12.8 · Advanced · 30 min read
Where models fit in an architecture
Video lesson
5 min · narrated, with captionsListen only (audio)
Read the transcript
Choosing the best model of the month matters less than you might think. In systems built on artificial intelligence, or AI, the lasting decisions are where a model runs, what sits in front of it, and what happens when it fails.
Think of a model as a specialist contractor. You can hire one from an agency for an hourly fee. That's a hosted API: the most capable models and no hardware, but you pay per token, and your data leaves your boundary. You can employ your own specialist, with all the equipment that needs. That's self-hosting an open-weight model: you control the data and the version, but you plan capacity for scarce, expensive accelerators. Or you can give every customer a small toolkit to use at home. That's an on-device model: private, offline and with no cost per call, but much less capable.
Next, ask whether a user is waiting. Online inference sits in the request path, so answers are streamed, and calls need timeouts and capacity for the evening peak. Batch work has no one waiting, such as tagging two million menu items with allergens overnight. It can use the cheapest adequate model, and retry calmly. Asynchronous inference queues the request and tells the user the result will follow. Moving work out of the online path is one of the most effective cost and reliability decisions available.
Once more than one feature calls models, an AI gateway pays for itself. Here, a support assistant, a nightly batch job and a staff search tool all call it, each with its own internal identity. The gateway offers one API for all models. It holds the provider keys, routes calls and handles fallbacks, enforces quotas and rate limits, logs every call with redaction, and offers hooks for guardrails. Behind it sit two hosted providers and a self-hosted model. Changing provider becomes a configuration decision, not a code change in every service. The price is a new critical dependency that must be highly available, and a concentrated store of prompts that may contain personal data.
Not every request needs the most capable model. Routing decides up front. A question such as where is my order can go to a small, cheap model, while a complaint about three problems goes to a larger one. A cascade tries a cheap model first, and escalates only when a check fails. The best checks are deterministic, such as failed schema validation. A model's own statement of confidence is the least reliable signal. When a model is rate limited or down, a fallback ladder tries the next rung: the same model elsewhere, another provider, a smaller model, and finally a response with no AI at all, such as a handoff to a person. Give each rung its own timeout and the whole ladder a total deadline, so no one waits through several slow failures. And record which rung answered.
Here's how it comes together for the food delivery platform's support assistant. It handles about forty thousand conversations a day. About two thirds concern late orders, missing items or refunds. The first streamed words must arrive within two seconds, and the full answer within eight, both at the ninety fifth percentile. Chat must be available ninety nine point nine per cent of the time. Two hosted providers sit behind an AI gateway. A small model routes each turn and answers simple status questions. A larger model handles complaints. Refunds over fifteen pounds need a human, and the refund service applies the policy in ordinary code, not in the model. The ladder runs from the primary model to the second provider, then a small model, and finally a canned message with the option to queue for a person. On escalation, agents see the transcript, the sources used and the proposed action, so the customer doesn't repeat themselves.
Human in the loop covers several designs: approval before an action, review afterwards, escalation, or feedback. Name which one you mean. Approval creates a queue that must be sized for peak volume, like the fraud review queue in Section twelve point one. People who approve hundreds of good suggestions start approving without reading. That's automation bias. So show the evidence and the exact action, and track how often reviewers change the proposal. And choose models with your own evaluation set of real examples, not public leaderboards. Expect a combination, not one winner.
The full section compares the hosting options and lists the criteria for choosing a model. Next, in Section twelve point three, we look at retrieval augmented generation. See you there.
What you need to know
- A model is one dependency in a larger system; the lasting architectural decisions are where it runs, how it is called, what sits in front of it and what happens when it fails.
- Hosted APIs give the best capability with no infrastructure but per-token cost, rate limits and data leaving your boundary; self-hosted open-weight models give control at the cost of operating accelerators; on-device models give privacy and offline use with limited capability.
- Online inference serves users who are waiting and needs latency targets and streaming; batch and asynchronous inference move work out of the request path and are cheaper and more robust.
- An AI gateway centralises provider keys, routing, fallbacks, quotas, logging and guardrails, at the cost of a new critical dependency and a concentrated store of prompts.
- Routing sends each request to a suitable model up front; a cascade escalates from a cheap model only when a reliable check fails; a fallback ladder tries other regions, providers, models and finally a non-AI response, within a total deadline.
- Human-in-the-loop designs (approval, review, escalation, feedback) need capacity planning and interfaces that resist automation bias.
- Choose models with your own evaluation set against agreed criteria: capability, cost, latency, context length, data residency, licence, features and operational terms.
The model is a dependency, not the architecture
Section 12.1 described a model as a probabilistic function reached through an API. In an architecture it is one container among many, and usually a small part of the code. A customer-support assistant has a chat front end, a conversation store, integrations with order and refund services, a search index, identity, logging, a handoff to human agents and a deployment pipeline; the model call is one line in the middle. The architectural questions are therefore familiar ones asked of a new kind of dependency: where does it run, how is it called, what sits between it and the callers, what happens when it is slow, wrong or unavailable, and who is accountable for its output?
Getting these questions right matters more than choosing the best model of the month. Models are replaced every few months; the gateway, the fallback design, the evaluation set and the human review process last for years. The decisions in this section are the significant, hard-to-reverse ones in the sense of Chapter 1, so they deserve decision records; the choice of a particular model version should be easy to change.
Three places a model can run
Hosted model APIs. The provider runs the model and you pay per token. This covers the frontier providers' own APIs (OpenAI, Anthropic and Google among others) and cloud platforms that resell several vendors' models inside your existing cloud account. It is the fastest way to start and gives access to the most capable models, with no accelerators to buy or operate. The costs are per-token pricing that grows with use, rate limits set by someone else, a dependency on the provider's availability, models that are deprecated on the provider's timetable, and data that leaves your boundary. Contracts, data processing terms, zero- or limited-retention options and regional processing reduce the last concern but do not remove it.
Self-hosted open-weight models. An open-weight model publishes its trained weights, so you can run it on your own or rented accelerators with an inference server such as vLLM. Examples include models from Meta (Llama), Mistral, Alibaba (Qwen), DeepSeek, Google (Gemma) and OpenAI (gpt-oss). You control the data path, the exact version and fine-tuning, and at high, steady volume the cost per token can fall well below API prices. In exchange you take on capacity planning for scarce, expensive hardware, utilisation (idle accelerators cost the same as busy ones), upgrades, security patching and on-call. Licences matter: some open-weight models use permissive licences such as Apache 2.0, while others use custom licences with conditions on use or scale, and most do not publish their training data. The Open Source Initiative's Open Source AI Definition (version 1.0, October 2024) sets a higher bar than open weights alone. A middle path, used by this course's own chatbot, is to call open-weight models through a third-party inference provider: per-token pricing, no hardware, and the freedom to move the same model elsewhere.
On-device models. Small models, often a few billion parameters or fewer and quantised to lower precision, run on phones, laptops or in the browser. They give privacy (data never leaves the device), offline operation, no per-call cost and very low latency, at the price of much lower capability, a wide spread of device performance, larger app downloads and the difficulty of updating models already shipped to millions of devices. Many products combine them: a small on-device model handles quick, private tasks and escalates harder ones to the cloud.
Comparing the options
| Option | Strengths | Costs and risks | Typical fit |
|---|---|---|---|
| Hosted proprietary API | Best capability, no infrastructure, fast start, provider handles scaling | Per-token cost at scale, rate limits, provider outages and deprecations, data leaves your boundary, lock-in through provider-specific features | Most new features; low or spiky volume; tasks needing frontier capability |
| Open-weight model through an inference provider | Per-token pricing with no hardware; same weights can move to another host or in-house | Still an external dependency; capability below the frontier on some tasks; provider quality and limits vary | Cost-sensitive features; portability; a step towards self-hosting |
| Self-hosted open-weight | Full control of data, version and tuning; low marginal cost at high steady load | Accelerator cost and scarcity, idle capacity, operations skills, upgrades, licence conditions | Strict data constraints; very high steady volume; heavy fine-tuning |
| On-device | Privacy, offline use, no per-call cost, minimal latency | Small models only; device fragmentation; update distribution; battery and memory | Private quick tasks, autocomplete, offline features, first step of a cascade |
Online inference and batch scoring
The second question is whether a user is waiting. Online inference calls the model in the request path, so latency targets apply: users notice the time to the first visible words, which is why chat answers are streamed, and they abandon a request that takes many seconds. Online calls need timeouts, concurrency limits and capacity for the evening peak, exactly as any synchronous dependency in Chapter 6.
Batch scoring processes many items without anyone waiting: tagging two million menu items with allergens overnight, summarising yesterday's support conversations, re-embedding a document collection. Batch work can use the cheapest adequate model, run when capacity is free and retry calmly. Several providers offer asynchronous batch interfaces that accept a file of requests and return results within hours at a substantial discount. Between the two sits asynchronous inference: a request is queued, the user is told the result will follow (a refund decision by e-mail, a document summary in a few minutes), and workers drain the queue at a controlled rate, using the queues and back pressure of Chapter 9 to absorb peaks and provider rate limits. Moving work out of the online path is one of the most effective cost and reliability decisions available.
An AI gateway between applications and models
Once more than one team or feature calls models, a dedicated AI gateway pays for itself. It plays the role an API gateway plays for microservices, specialised for model traffic. Applications call one internal endpoint with one request format and their own identity; the gateway holds the provider keys, translates to each provider's API, applies routing and fallbacks, enforces per-team quotas and spending budgets, applies rate limits, records every call (model, version, token counts, latency, cost, outcome) for tracing and cost allocation, can cache responses, and offers a place to attach input and output guardrails centrally.
The benefits are architectural: provider choice becomes a configuration decision instead of a code change in every service, keys are no longer scattered across applications, spending is visible per feature, and a provider outage is handled once. The costs are those of any shared intermediary. It is a new critical dependency that must be highly available, it adds a small amount of latency, and its logs become a concentrated store of prompts that may contain personal data, so redaction and retention rules (see privacy by design) apply to it. Open-source and managed gateway products exist, and cloud platforms include gateway features; building a thin one is reasonable for a small system, but quotas, streaming, retries and accounting are more work than they look.
An AI gateway
Routing and cascades
Not every request needs the most capable model. Routing decides up front which model should handle a request, using rules (the feature, the customer tier, the language) or a small, fast classifier. In the support assistant, where is my order?
can go to a small, cheap model that calls one tool, while a complaint about three separate problems goes to a larger model. A model cascade instead tries a cheaper model first and escalates only when a check says its answer is not good enough. Chen, Zaharia and Zou's FrugalGPT (2023) showed that well-tuned cascades can approach the quality of the strongest model at a fraction of the cost.
A cascade is only as good as its escalation check. Reliable checks are deterministic: the output fails schema validation, a cited source does not exist, a required field is missing, a business rule rejects the proposal. A verifier model scoring the answer is weaker but often useful. A model's own statement of confidence is the least reliable signal and should not be used alone. Cascades also have costs: escalated requests pay for two calls and wait for both, there are now two models to evaluate and keep in step, and the quality ceiling is set by the check, not by the strong model. Measure the escalation rate; if most requests escalate, route instead.
Fallback ladders across models and providers
Model APIs fail in all the ways remote dependencies fail, plus a few of their own: rate-limit responses (HTTP 429) when a quota is exhausted, overload errors at busy times, slow responses that exceed a timeout, regional outages, and models withdrawn on a deprecation date. The patterns of Chapter 9 apply directly, arranged as a fallback ladder: an ordered list of rungs, each tried when the one above fails. A typical ladder is the primary model; the same model in another region or from another host; a different model of similar capability from a second provider; a smaller, faster model; and finally a non-AI response, such as a helpful canned message, the help-centre search results or a handoff to a person.
Design rules for a ladder: give each rung its own timeout and the whole ladder a total deadline, so that the user never waits for four slow failures in a row; respect Retry-After and put a rate-limited model into a cooldown (a simple circuit breaker) instead of hammering it; do not retry errors that will fail again, such as a request that is too large or rejected by a content filter; validate output on every rung, because a lower rung may produce answers in a slightly different shape; evaluate each rung against the same evaluation set, since prompts often need per-model adjustment; and record which rung answered, so that quality dashboards can tell a degraded answer from a normal one.
This course's own AI features are a small, real example. ArchitectBot's answers and the marking of written test answers are generated through a ladder of several open-weight models served by one inference provider, tried in a fixed order of preference. A model that returns a rate-limit response is cooled down for the period the provider asks (within set bounds), a request that fails, times out or returns an unusable answer moves to the next rung, those rungs share an overall time budget, and a second provider serves as the last rung. The design trades some answer quality on the lower rungs for availability: a slightly weaker answer is preferred to none.
Humans in the loop
Human in the loop describes several different designs, and it helps to name which one is meant. Approval before effect: the model drafts, a person approves (a refund above a limit, a reply to a regulator, a change to production). Review after effect: outputs take effect immediately and people review a sample or the flagged cases. Escalation: the model handles what it can and hands the rest to a person, with the conversation and the evidence. Feedback: people label or correct outputs to build evaluation sets and improve prompts.
Each design has architectural consequences. Approval creates a queue that must be sized for peak volume, like the fraud review queue in section 12.1, and adds latency measured in minutes or hours. People who approve hundreds of good suggestions start approving without reading (automation bias), so the interface should show the evidence and the exact action, highlight what is unusual, and track how often reviewers change the proposal; an override rate near zero is a warning, not a success. Handoffs need the full context so the customer does not repeat themselves. The human oversight required by regulation for some uses is more demanding still: the person must understand the system's limits and be able to override it.
Build or buy, and how to choose a model
The build-or-buy question has more than two answers. You can buy a complete AI feature inside a product you already use (a helpdesk vendor's assistant); build on hosted APIs; fine-tune a model for your task; self-host open weights; or, rarely, train your own. Use the strategic lens of domain-driven design: buy for generic capabilities such as meeting transcription, and build where AI touches your core domain and your own data gives you an advantage. Whatever you build, keep provider-specific code behind a port with an adapter per provider, and avoid depending on features only one provider offers unless their value justifies the lock-in.
Choose models with your own evaluation set, not with public leaderboards. Leaderboards measure general tasks that may not resemble yours, and some have been tuned against. Define the criteria and their weights before testing, as with any weighted decision, then shortlist two or three candidates and measure them on a few hundred real examples. Expect the answer to be a combination, such as a small model for routing and a larger one for hard cases, rather than one winner.
Criteria for choosing a model
| Criterion | Questions to ask | How to check |
|---|---|---|
| Capability | Does it do our task well enough, in our languages and formats? | Score it on your own evaluation set; compare error types, not only averages |
| Cost | What do input, output and reasoning tokens cost at our volumes? | Multiply measured tokens per request by expected traffic; include retries and escalations |
| Latency | How long until the first token, and how many tokens per second, at peak? | Measure p50 and p95 from your region, under load, with realistic prompt sizes |
| Context length | Does our longest realistic input fit with room for the answer? | Test quality at that length; long-context quality varies |
| Data residency and retention | Where is data processed and stored, for how long, and is it used for training? | Read the data processing terms; confirm regional endpoints and retention settings in writing |
| Licence and terms | May we use it for this purpose, at this scale, and fine-tune it? | Read the licence or terms of service with legal advice where needed |
| Features | Does it support tool calling, structured outputs, streaming, images or audio? | Prototype the exact features the design depends on |
| Operations | What are the rate limits, availability record, version pinning and deprecation policy? | Check published limits, status history and how long pinned versions are supported |
Decision guide
Decision guide: where should this model run?
Ask the questions in order for each AI feature; different features of one product often land in different places.
- Must the feature work offline, or must the data never leave the user's device?YesUse an on-device model, accept a smaller model's limits, and plan how model updates reach devices. Consider escalating hard cases to the cloud with the user's consent.NoContinue.
- May this data be processed by an external provider under contract (purpose, retention, region)?YesContinue.NoSelf-host an open-weight model in your own environment, or use a provider deployment inside your own cloud tenancy that satisfies the same restrictions.
- Does the task need capability that open-weight models you could run do not reach on your evaluation set?YesUse a hosted frontier API behind an AI gateway, with a fallback to a second provider and a non-AI last rung.NoContinue.
- Is the volume high and steady enough to keep dedicated accelerators busy, and do you have people to operate them?YesSelf-hosting open weights may be cheaper. Prove it with a cost model that includes staff, idle capacity, redundancy and upgrades.NoUse a hosted API, either proprietary or an open-weight model through an inference provider, and revisit when volume grows.
Worked example
Worked example: a support assistant for the food-delivery platform
The platform receives about 40,000 support conversations a day, peaking in the evening rush. About two-thirds concern late orders, missing items or refunds. The goal is to resolve routine cases automatically, hand the rest to people with context, and never pay a refund the policy does not allow.
| Quality targets | First streamed words within 2 seconds at p95; complete answer within 8 seconds at p95; chat available 99.9% of the time, with a human or canned fallback when models are unavailable. |
|---|---|
| Constraints | Customers in the UK and EU, so personal data is processed under GDPR with regional processing and limited retention; refunds over £15 need a human; existing order and refund services must remain the systems of record. |
| Where models run | Hosted APIs from two providers behind an AI gateway. A small model routes each turn by intent and answers simple status questions; a larger model handles complaints and multi-issue conversations. Overnight, a batch job summarises and tags conversations for analytics through a provider's batch interface. |
| Knowledge | Policies and help-centre articles are retrieved at query time from a hybrid search index (section 12.3), never fine-tuned into a model. |
| Actions | The orchestrator exposes read-only tools (order status, order items) and one write tool that proposes a refund; the refund service applies the policy and limits in ordinary code (section 12.4; secured in section 12.6). |
| Humans | Escalation to the agent console when the customer asks, after two failed attempts, for refunds over the limit, or when the conversation suggests a vulnerable customer; agents see the transcript, the retrieved sources and the proposed action. |
| Failure behaviour | Ladder: primary model, second provider, small model, then a canned message with a link to the help centre and the option to queue for a person. |
| Observability | Every model call is traced through the gateway with model version, tokens, latency, cost, retrieved sources and outcome, feeding evaluation (section 12.5) and cost monitoring (section 12.7). |
The model calls are a small part of the design; most containers are ordinary services with ordinary responsibilities.
The decisions most worth an ADR are the gateway, the two-provider ladder, keeping policy in the refund service and the escalation rules, because they are expensive to reverse; the choice of model versions is deliberately easy to change.
Container diagram: support assistant
Check your understanding
Why can an AI gateway's logs become a privacy concern?
They collect the prompts and responses of every feature in one place, and prompts often contain personal data, so redaction, access control and retention limits are needed.
When is routing a better choice than a cascade?
When the kind of request can be recognised up front, or when most requests would escalate anyway, so that trying the cheap model first only adds cost and latency.
Why does each rung of a fallback ladder need its own timeout and the whole ladder a total deadline?
So that a user never waits through several slow failures in a row; the ladder must give some answer within the response time users will tolerate.
Give one benefit and one cost of running a model on the user's device.
Benefit: privacy, offline use, no per-call cost or very low latency. Cost: much lower capability, varied device performance, larger downloads or difficult model updates.
Sources and further reading
- Chen, Zaharia and Zou: FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance (2023)
- Open Source Initiative: The Open Source AI Definition 1.0
- Bharani Subramaniam and Martin Fowler: Emerging Patterns in Building GenAI Products (2025)
- Simon Brown: The C4 model for visualising software architecture
Have a question about this section? ArchitectBot, the course’s AI study assistant, answers from the course first.
Ask: “When does it make sense to self-host an open-weight model instead of paying for a hosted API?”