HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 19“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Model Selection, Routing, Latency and Cost Optimization
Every TechLearningPro "Explain" click used the largest model profile on the account.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 19 · AI and LLM Application Fundamentals
Lesson Overview
Every TechLearningPro "Explain" click used the largest model profile on the account. A glossary question — "what is a tenant?" — waited as long as a section explanation and drew the same relative cost. During an enrollment spike the player budget slipped, and finance could see a single pooled token number with no task attached. A prototype also let the browser pass model: "largest" and the API honored it. One script, running in a learner's session, could point the bill at the most expensive profile all afternoon.
Routing is the server decision that picks a profile for a task class, under a latency budget and a relative cost budget, after an evaluation report says the profile is allowed to try that task. The profile id is yours. A config file binds it to whatever provider model id is current. This lesson does not name a vendor model as the answer, and it does not freeze a price. Prices and model lists move. Model comparison and AI cost optimization are the primers. The numbers below are relative units for design review. Replace them with the price card you read on the day you bind the adapter.
You will classify tasks with rules, select the cheapest profile that fits the latency budget and the remaining tenant allowance, fall back once on timeout, and send course-length work to a job instead of the lesson player's stream from lesson 16. A profile with no accepted report from lesson 18 stays ineligible.
Planning assumptions:
Three logical profiles: draft-small, draft-standard, draft-long.
Relative costs 1, 4, and 15. These are not currency and not a quote.
The player path from lesson 1 still targets a short section explanation. Course synthesis is a job.
The lab does not call a provider. A scripted gateway returns text or a timeout.
Learning Objectives
By the end of this lesson you will be able to:
Define a task class, a profile, and a binding as three different records.
Classify glossary, section explanation, and course synthesis with rules you can test, without a model call.
Select the cheapest eligible profile whose expected first-token time fits the latency budget and whose relative cost fits the remaining allowance.
Reject a client-supplied profile id that is not on the server allowlist for that task.
Fall back once on timeout, charge the attempt against the allowance, and stop.
Refuse to run course synthesis on the player request path.
Require an accepted eval report before a profile serves a task.
Record a route decision: task, profile, fallback, relative cost, and outcome. Omit the prompt.
Explain time-to-first-token versus total time, and which one the streaming UI feels.
Keep provider model ids in config, not in the router and not in Git as a recommendation.
Test selection, budget exhaustion, client override, and a single fallback without a network call.
Tell finance which meter maps to which task, in relative units, until a real price card is attached.
Prerequisites
Lesson 1's split between a draft and a completion fact, and the idea of a server-side model port.
Lesson 16's stream: first token, done, and abort. Routing chooses who produces those events.
Lesson 18's gate: accept_candidate is required evidence before traffic moves.
TypeScript strict unions. /learn/typescript if you want the language primer beside lesson 3.
No API key. Relative costs are data in the profile table.
Read context windows if "the largest model" has been your default because it holds more text. A larger window is not a substitute for sending only the authorized excerpt.
Detailed Core Concepts
Task class before model name
The router does not start from a catalog of vendor brands. It starts from the work:
Task class
Learner signal
Where it runs
Quality bar
glossary
Scope term, short question
Player stream
Define the term from the excerpt
section_explain
Scope section
Player stream
Explain the authorized section
course_synthesis
Scope course
Background job
Out of the player budget
Classification in this lab is deterministic:
scope === "course" → course_synthesis
scope === "term" and the trimmed question length is at most 80 → glossary
otherwise, when scope is section or a long term-scoped question → section_explain
The client may send scope because it reflects which button they pressed. The client may not send the profile. A long question on the term button is treated as a section explanation so a pasted page cannot ride the cheap cap while asking for a long answer. That rule is a product choice. The test locks it.
Using a model to classify the route spends the resource you are trying to save and adds a failure mode in front of every click. Rules first. A classifier model is a later optimization when the rules are demonstrably wrong on a labeled sample.
Profiles, bindings, and evidence
A profile is your contract: id, allowed tasks, timeout, max output tokens, relative cost, expected first-token milliseconds.
A binding is a deploy-time map from profile id to a provider model id string loaded from configuration. The router never sees it. Tests fail if a provider model id appears in the router module. When you change vendors, you change the binding, rerun lesson 18's suite for that profile, and leave the call sites on profile ids.
Evidence is the set of pairs (profileId, task) for which you have stored an accept_candidate report. No pair, no traffic. A brand-new profile serves nothing until the harness accepts it. This is how cost work stays attached to quality work.
Illustrative table, not a price card:
Profile
Allowed tasks
Relative cost
Expected first token
Max output tokens
Timeout
draft-small
glossary
1
400 ms
120
4 s
draft-standard
glossary, section_explain
4
900 ms
400
8 s
draft-long
course_synthesis
15
2000 ms
1200
job limit
draft-standard is allowed to serve glossary as a fallback when draft-small times out, because the allowed-task list includes glossary. draft-long is not a fallback for the player. It is too slow and it is the wrong task.
Selection rule
Among profiles that:
list the task in allowedTasks,
have an accepted eval pair for that task,
have expectedFirstTokenMs less than or equal to the request's latency budget, and
have relativeCost less than or equal to the tenant's remaining allowance,
pick the lowest relativeCost, then the lowest expectedFirstTokenMs, then the lexicographically smallest id.
If no profile remains, return no_profile or over_budget and do not call a gateway. The player shows the lesson without a draft, the same fallback as a timeout in lesson 1.
Course synthesis returns async_required even if draft-long would win. The HTTP handler responds with a job accept (202 and a status URL) only on the job route. The player route returns a typed error the UI renders as "That summary runs in the background," and it does not start draft-long inline. API design covers 202 as the status for accepted work. This lesson's router only returns the signal.
Fallback and what you charge
On timeout, try the next profile under the same rule, excluding the one that just failed, once. On invalid_output or refused, do not walk the catalog. A larger model is not a repair for a schema failure; lesson 15's validator is. On aborted, stop. The learner left.
Decrement the tenant allowance by the profile's relativeCost when the attempt starts, not only when it succeeds. A timeout may still have billed input tokens at the provider. The lab ledger uses relative units so you can test the debit without a currency library. Swap in real minor units at the edge when a price card exists, and keep the debit rule.
Allowance is per tenant per UTC day in the lab, held in memory. A production ledger is a counter in your database with a row lock or an atomic increment, keyed by tenant and date. Two API processes must not each think they have the full budget. The in-memory map is for the unit test.
Latency the learner feels
Lesson 16 split time to first token from time to done. The router constrains expected first-token time because that is what the streaming panel needs. Total time is still capped by the profile timeout. A cheap profile that streams immediately and then stalls fails the timeout and may fall back once. Record both durations on the decision log.
Do not put expected latency in the client bundle as a promise. It is an input to selection. Your measured p95 replaces it when you have a week of traffic. Until then, label it illustrative in the config comment.
Caching and duplicate spend
A second identical glossary request can reuse a finished draft when the cache key includes tenant, lesson version, prompt version, profile id, and a hash of the question, and the excerpt is not personalized. A cache hit debits zero relative cost and does not call the gateway. Cache misses follow normal routing. Do not cache course_synthesis in the player. Do not cache an incomplete stream. Lesson 16 already forbade caching a partial SSE body; the router must not reintroduce it.
What optimization is not
Optimization is not "always the smallest model." draft-small is ineligible for section_explain in the table because you have not accepted it for that task. Turning it on without lesson 18's critical cases is how you save money and ship the warm false completion from that lesson.
Optimization is not a client toggle for "quality." Learners do not choose your unit economics, and an attacker using a learner session must not either.
Architecture and Request Flow
flowchart TB
subgraph browser [Browser]
Player[Lesson player]
end
subgraph server [TechLearningPro API]
Auth[Session and ACL]
Class[Task rules]
Router[Profile router]
Ledger[Tenant allowance]
Eval[Accepted report pairs]
end
subgraph model [Gateway]
Bind[Config binding]
Port[Model port]
end
Player -->|scope and question| Auth
Auth --> Class
Class --> Router
Eval --> Router
Ledger --> Router
Router -->|profile id| Bind
Bind --> Port
Port -->|draft or timeout| Player
The browser never receives the provider model id. A timeout on the player path can select one alternate profile. course_synthesis leaves this picture and enters a job worker that uses the same router with a different latency budget.
flowchart LR
Scope[Button scope plus question] --> Task[Task class]
Task --> Eligible[Allowlist and eval pair]
Eligible --> Fit[Latency and remaining cost]
Fit --> Pick[Cheapest profile]
Pick --> Attempt[Gateway attempt]
Attempt -->|timeout once| Next[Next profile]
Attempt -->|ok or second failure| Stop[Draft or fallback UI]
Step-by-step Implementation
Package: packages/model-route/. "strict": true. No network. No process.env reads in the unit tests.
If every evaluated profile is only excluded by budget or latency, the error is over_budget. If none are evaluated, the error is not_evaluated. That distinction tells an on-call engineer whether to wait for the harness or to raise a cap. over_budget also covers "fits the money but misses the latency budget" in this lab, because both mean "a legal profile exists and this request may not use it." Split the reason in production metrics if your dashboards need the split. Do it with a test per reason.
invalid_output returns immediately because reason !== "timeout". The second select excludes the profile that timed out. If the allowance cannot pay for draft-standard, the learner keeps the timeout outcome and the UI uses the incomplete-or-empty tutor state from lesson 16. You do not start a third profile.
packages/model-route/src/ledger.ts
typescript
importtype{ Ledger }from"./execute.js";
/** Test double. A second process with its own map will not see these debits. */
const next =this.remaining(tenantId, day)- relativeCost;
balances.set(key(tenantId, day), next);
},
};
}
Debit can go negative in this helper so a bug that double-debits is visible. selectProfile prevents a start when relativeCost > remaining. It does not look at a negative number and keep going, because remaining is read before the next select.
Step 5: Profiles fixture and client override
packages/model-route/src/profiles.ts
typescript
importtype{ Profile, TaskClass }from"./types.js";
/** Illustrative contracts. Bind provider model ids in deployment config, not here. */
The HTTP layer ignores profileId on the JSON body. A test posts a body that includes profileId: "draft-long" with scope: "term" and asserts the choice is still draft-small. Parse the body with an allowlist of scope and question only. Unknown fields are dropped. Lesson 3's parse style is the pattern: do not copy attacker-controlled fields onto RouteRequest.
When you later fill Gateway.run, read the provider's current API and price card, map choice.profileId through config, pass signal and maxOutputTokens, and translate their timeout into { ok: false, reason: "timeout" }. Delete any sample model name from the pull request if it was only a reminder.
Security
Authentication before classify. No session, no debit, no gateway call.
Authorization is still the lesson ACL from lesson 1. Routing does not widen which excerpt can be sent. A cheap profile is not a reason to attach a larger excerpt.
Least privilege: each provider credential can call inference for the bound models and cannot read the ledger's database role beyond the debit function you expose.
Input validation: question length, scope enum, and a hard ignore of client profileId.
Secrets: bindings can contain model ids, which are not secrets, and endpoints. The credential stays in the secret store. Do not commit a .env with a key "so the router test can hit staging."
Tenant isolation: the ledger key includes tenantId. Tenant A cannot spend tenant B's remaining units. Log the profile id and the relative debit, not the question.
A route decision is configuration disclosure if you return the provider model id to the browser. Return the draft and a generic requestId. Operators see profile ids in server logs.
Prompt injection might say "use the expensive model." The classifier does not read instructions out of the question to pick a profile. Scope comes from the button, length from the string, evidence from your store.
Error Handling
Result
Learner
Ledger
Gateway calls
bad_request
Validation message
Untouched
0
async_required
"Runs in the background" on the player route
Untouched until the job route selects
0 on the player
not_evaluated
Lesson without a draft
Untouched
0
over_budget
Lesson without a draft
Untouched
0
Primary success
Stream or draft
Debited once
1
Primary timeout, fallback success
Draft, maybe later first token
Debited twice
2
Primary timeout, fallback missing
Tutor fallback
Debited once
1
invalid_output
Tutor fallback
Debited once
1
Abort
Incomplete panel
Debited if the attempt started
Stopped via signal
Do not retry unavailable in a loop. One fallback is only for timeout. A provider outage that fails fast as unavailable should trip a circuit in the adapter so you stop debiting the allowance for calls you already know will fail. The circuit is a counter of recent failures and a cool-down. Document the cool-down as a policy number you measured, not as a default copied from a framework.
selectProfile for section uses choice.ok && choice.choice.profileId, and assert.equal compares to the string "draft-standard". When ok is true the && expression is the profile id. When it is false the expression is false and the assertion fails. That is a compact form; expand it if a failure message is unclear.
Add a test that remaining 0 on a glossary request returns over_budget and does not call the gateway. Add a test that removes the glossary pair for draft-small and expects draft-standard only when its pair remains. Add a test that a question longer than 80 characters with scope: "term" classifies as section_explain.
Performance and Cost
First token is the player metric. The illustrative budgets are 1500 ms for selection's expected first token and the profile timeouts in the table. Replace both with p95 from your edge before you argue they are tight or loose.
Output caps stay small on glossary. Streaming a glossary answer through draft-long wastes the window and the allowance.
One fallback caps the outage multiplier at about two attempts, not an unbounded retry. In the fixture, a glossary timeout costs 1 + 4 relative units when both run.
Debit on start so dashboards match bills that include failed attempts. If your provider does not bill timeouts, you can credit on a documented reason. Measure before you credit.
Cache finished public glossary drafts with the key from the concepts section. A hit is the biggest cost win in this lesson and the easiest one to get wrong across tenants.
Jobs for draft-long keep the player process free. Concurrency for the job worker is a separate limit so a synthesis backlog cannot consume the interactive gateway quota.
Eval cost is part of model cost. Re-running lesson 18's paid cassette on every commit is a routing problem too: run it when the prompt or the binding changes.
Illustrative mix: if most clicks are glossary and you route them to relative cost 1 instead of 4, spend on those clicks drops to a quarter in these units, and only if quality stays accepted. The sentence dies without the eval pair. AI optimization discusses cost at a primer level; the ledger here is the control.
Knowledge Check
1. What problem does routing solve?
It attaches each tutor click to a task and a profile so latency and relative cost stay inside a budget, while a client cannot demand the most expensive profile. Unevaluated profiles do not receive traffic.
2. What alternatives exist, and when would you choose each?
One profile fits a product that has not measured a split and accepts the cost. Rule routing fits glossary versus section versus course, which you can see from the button and the length. A model-based router fits when a labeled sample shows the rules are wrong, and it should be cheaper than the model it saves. A job fits course_synthesis. A cache fits identical finished public answers.
3. Which data, identity, and trust boundaries matter?
The session owns the tenant and the allowance. The ACL still decides the excerpt. Profile choice is server-side. Provider model ids and credentials stay in config and the secret store. Logs store the decision, not the prompt. Eval evidence is a per-profile, per-task pair.
4. What can fail, and how should the system respond?
Bad input and missing evidence and an empty budget skip the gateway. Course scope on the player returns async_required. Timeout may try one next profile and debits both. Invalid output, abort, and a second failure stop. The lesson still renders.
5. How would you test quality, security, performance, and cost?
Tests lock cheap glossary selection, section routing, the course refusal, a single timeout fallback, the debit totals, and invalid-output behavior. Security review checks that profileId in the body cannot move the choice. Quality review checks the eval pair. Cost review checks debit-on-start and the absence of a third attempt.
Hands-on Assignment
Lab note. Relative units only. Do not add a live key or a real price table you have not read.
Problem. TechLearningPro should serve a short definition from draft-small, a section explanation from draft-standard, and refuse to run a course summary inside the player. A timeout may step up once. The browser cannot select draft-long.
Tasks.
Implement classify, select, ledger, and executeRouted with the tests in this lesson plus the three extra tests named above.
Draw the binding as a box outside the router. Write the config shape: profileId to providerModelId, loaded at startup, absent from the client.
Show the log line fields: tenantId, task, profileId, fallbackFrom, relativeCost, outcome, firstTokenMs. State that question is excluded.
Name the eval pairs required before draft-small may serve glossary. Point at lesson 18's accept_candidate.
Describe the 202 job response for course synthesis without implementing a queue. Include what the player must not do while waiting: it must not open an SSE stream to draft-long.
Mark every latency and cost figure in your write-up as illustrative or as measured. Do not mix them.
Deliverable. Diagram, source with no secrets, test output, the log-field list, and the binding note.
Challenge. Tenant B's allowance is 1 relative unit. Show that a glossary timeout on draft-small does not start draft-standard, and that tenant A's allowance is unchanged. Then state how a shared in-memory ledger on two servers would double-spend, and which atomic counter you would put in PostgreSQL instead.
Rubric. Conceptual accuracy and architecture 20%. Working implementation 25%. Security and privacy 20%. Tests, fallback, and ledger behavior 20%. Documentation of trade-offs 15%.
Common Mistakes
Honoring a client model name. Symptom: a script drives the bill to the largest profile. Cause: the JSON field was copied onto the gateway call. Fix: ignore it and test that ignore.
The largest profile as the default. Symptom: glossary latency matches long synthesis. Cause: no task class. Fix: the rules and the table.
A cheap profile with no eval. Symptom: the warm false completion from lesson 18, now cheaper. Cause: cost shipped before accept_candidate. Fix: the evidence set.
Unbounded fallback. Symptom: an outage walks every model and debits each. Cause: a retry loop. Fix: one timeout fallback.
Fallback on schema failure. Symptom: invalid JSON is "fixed" by a larger model that also rambles. Cause: timeout policy reused for invalid_output. Fix: stop and validate.
Course synthesis on the player stream. Symptom: the edge cuts the socket and the job is half done. Cause: draft-long won a sort it should not have entered. Fix: async_required.
Debiting only successes. Symptom: finance sees a timeout storm the product dashboard calls free. Cause: the ledger sat after ok. Fix: debit when the attempt starts.
A shared cache without tenant and profile. Symptom: another tenant sees a definition, or a cheap profile serves a draft the standard profile produced. Cause: the key was the question string alone. Fix: tenant, version, prompt version, profile, question hash.
Hard-coding yesterday's model id in the router. Symptom: a provider rename breaks every call site, or a review thinks the lesson endorsed a vendor. Cause: binding leaked inward. Fix: config at the gateway edge.
Classifying with a model call. Symptom: you pay and wait before you have chosen how to pay and wait. Cause: a router prompt. Fix: rules, until a labeled set proves they are wrong.
Two servers, two copies of the allowance. Symptom: the tenant spends twice the cap. Cause: memoryLedger in production. Fix: an atomic counter in the system of record.
Logging the question with the debit. Symptom: lesson questions in the billing export. Cause: one convenient structured log. Fix: the field list in the assignment.
Summary
Model choice is a server-side route from a task class to a profile, constrained by evaluation evidence, expected first-token time, and a tenant allowance in units you can replace with a real price later. The player handles glossary and section explanations. Course synthesis is a job. Timeout may try one next profile. The client does not pick the model. The lab proves the policy with a scripted gateway so a red test means the router changed, not that a vendor had a bad minute.
Next Lesson Preview
Responsible AI, Safety and Human-in-the-Loop Design takes the draft this router paid for and asks who is accountable when it is wrong, unsafe, or about to cause a side effect. You will design a human check for the decisions a profile must not make alone, and you will keep the quiz — not the cheapest model — in charge of completion.
This course's lesson 16 for first-token latency, lesson 18 for the evidence pair, and lesson 10 for 202 responses on long work.
Node.js for the process that must share a ledger across instances only through a real store.
Your provider's current pricing page and model list, read on the day you write the binding. Label any figure you copy with the date you read it. This lesson's 1, 4, and 15 are not those figures.
Ready to mark this lesson complete?Track your journey across the entire course.