AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 60

    LLM Cost, Latency and Performance Engineering

    The spans from Observability for Full-Stack and LLM Applications were finally safe to read.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 60 · Production AI Products, Capstones and Career Readiness

    Lesson Overview

    The spans from Observability for Full-Stack and LLM Applications were finally safe to read. They were also embarrassing. Northwind's glossary clicks, including Priya's "what is a primary key," ran on draft-long because the player query string profile=draft-long was honored again. ttftMs equaled durationMs on those spans: the container buffered the whole completion and flushed once, so the first byte arrived when the model was finished, inside the 30-second deadline from the deployment lesson. Two warm API instances each recorded a charge for the same browser retry. Finance still had one pooled token number for Northwind and Contoso together. The trace told the truth. Nothing in the request path acted on it.

    Model Selection, Routing, Latency and Cost Optimization already defined profiles, relative units, and a router that ignores a client-supplied model. This lesson is the production half: a latency budget the stream must meet, a flush rule so time to first token is real, an admission ceiling so a traffic spike cannot multiply the token bill, and a ledger that charges each organization once per request id. Units are relative. They are not a currency quote and not a vendor price card. Prices move. The shape of the control does not.

    A glossary task that fits draft-small stays on the player stream. A course synthesis that cannot meet the player budget becomes a job. The next lesson builds the queue. This lesson only decides that the HTTP request must not hold the container until a long generation finishes.

    Planning assumptions:

    • Profiles stay draft-small, draft-standard, and draft-long, with relative unit weights 1, 4, and 15. These match lesson 19. They are not dollars.
    • Illustrative player budget: first token within 1,000 ms, total stream within 8,000 ms. The container deadline remains 30 seconds so your code can return timeout before the platform kills the socket. Measure your own first-token times before you treat 1,000 ms as a contract.
    • Output tokens weigh three times input tokens in the lab formula, because many price cards charge more for output. Replace the weight when you read the current card. Keep the formula in one function.
    • Northwind's weekly allowance in the lab is 500 units. Contoso's is 500 units. They do not share a counter.
    • The same requestId is idempotent per organization. A second instance that sees it records a duplicate and does not add units.
    • The lab does not call a provider. A scripted result supplies token counts and timestamps.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Explain why a redacted token count is not yet a cost control.
    2. Compute relative units from a profile weight and input and output token counts.
    3. Charge those units to one organization's allowance, keyed by requestId.
    4. Treat a repeated requestId as a duplicate charge, including across two API instances that share the ledger.
    5. Keep Northwind's spend off Contoso's allowance.
    6. Refuse a client-supplied profile and select from the task class on the server.
    7. Classify a player task against a first-token budget and a total budget.
    8. Flush the first token when it arrives, so ttftMs is not a copy of total time.
    9. Admit a tutor call only while in-flight work is under a ceiling.
    10. Return busy when the ceiling is full, without starting a provider call.
    11. Send course synthesis off the player path when it cannot meet the stream budget.
    12. Charge a timeout for tokens already consumed, once, and skip an automatic retry.
    13. Read inputTokens, outputTokens, ttftMs, and profile from the lesson 59 span and nothing else.
    14. Show a weekly review that lists units by organization and profile without putting tenant id on a metric.

    Prerequisites

    Detailed Core Concepts

    Cost is units on a ledger, not a feeling about the largest model

    A token count becomes a cost when you multiply it by a weight you control and add it under an organization. The lab formula is:

    text
    weighted = inputTokens + outputTokens * 3
    units = ceil(weighted / 1000 * profileWeight)

    draft-small has weight 1, draft-standard weight 4, draft-long weight 15. A glossary answer of 400 input tokens and 80 output tokens on draft-small is a small integer. The same tokens on draft-long are fifteen times that integer. The incident was the weight, not the question. Relative units let two engineers review a change without pasting a vendor's price, which will be stale by the time the lesson is read. When you bind a provider, you replace the weights from that day's card and you keep unitsForCall as the only multiplication.

    The ledger is a list of charges plus an allowance per organizationId. A charge stores organization, requestId, profile, and units. It does not store the prompt. The span already refused the prompt. The ledger does not get a second chance to keep it.

    Idempotency is part of the bill

    Lesson 58 forbade the platform from retrying a tutor stream, because a retry double-spends and can draft a different paragraph. Learners still click again. Two warm instances can both see that click if the first response never reached the browser. The idempotency key is the browser's requestId, stored on the charge. The second recordCharge for the same organization and request id returns duplicate: true and does not add units. A different organization may use the same request-id string. Keys are not global. A Northwind id colliding with a Contoso id must not suppress Contoso's charge or add Contoso's units to Northwind.

    Timeouts still cost whatever tokens the provider metered before the deadline. Record that partial charge once under the same request id. Do not start a second provider call inside the request. The learner sees timeout or busy and decides whether to send a new request id.

    Latency is two clocks

    Time to first token is when the player can paint the first word. Total time is when the stream ends. Buffering the completion makes the first clock a copy of the second. The learner waits in silence, and the span's ttftMs lies. The flush rule is: when the first delta arrives, write it to the response. Do not wait for the model to finish. The helper firstByteDelayMs returns the first-token timestamp when you have one, and the completion timestamp when you do not. A review fails the handler when those numbers match on a stream that produced tokens. The status helper then compares both clocks to the player budget:

    ConditionStatusLearner-facing result
    First token and total inside budgetokStream the draft
    First token late, total inside budgetslow_ttftStream, and count a latency miss
    Total over the player budgetover_totalStop with typed timeout before the platform kill
    Task cannot fit any stream profilejob202 and a job id, built in the next lesson

    The container's 30-second ceiling is the backstop. The 8-second player budget is the product. Hitting the ceiling means your budget check did not run.

    Admission is how a spike stays inside the allowance

    Two warm instances with unlimited concurrent tutor calls will multiply tokens by the concurrency, not by the number of learners you planned for. admitTutor compares in-flight streams with a ceiling. Under the ceiling, the call proceeds. At the ceiling, the response is busy and the provider is not contacted. The ceiling is a process-local guard plus a shared counter if you run more than one instance. A local-only counter on two instances doubles the real concurrency. The lab function is pure: you pass the current in-flight count. The deployment wires that count to a shared store. The lesson 58 manifest's instance floor stays 2. The ceiling is the new knob. Raising minInstances without a ceiling makes a launch week more expensive, not safer.

    The client does not select the profile

    selectProfile maps a task class to a profile. glossary maps to draft-small. section maps to draft-standard. synthesis maps to a job, not to draft-long on the player. A requestedProfile argument is ignored. Lesson 19 called this out when a script spent an afternoon on the largest profile. The regression in this incident is why the ignore lives in a tested function and not in a code review comment.

    If the chosen profile's units do not fit the remaining allowance, the result is over_allowance and the provider is not called. Downgrading a section explanation to a smaller profile is allowed only when that profile is on the task's eligible list from the evaluation report. This lesson's table has one eligible profile per task so the test stays honest. Adding a fallback profile is a change to the table, reviewed with the eval report, not a silent catch.

    What you may read from the span

    The ledger reads organizationId, profile, inputTokens, outputTokens, ttftMs, status, and the request id you correlated on the span. It does not read an error string, even a redacted one. Weekly review groups charges by organization and profile in the application database, under the same tenant predicate as every other query. That report is not a metric labeled by tenant. Lesson 59's rule stands.

    Architecture and Request Flow

    flowchart TB
      subgraph edge [Edge]
        Browser[Browser]
      end
    
      subgraph api [Tutor container]
        Admit[admitTutor ceiling]
        Pick[selectProfile from task]
        Stream[Flush first token]
        Ledger[recordCharge by org and requestId]
      end
    
      subgraph data [Private data]
        Allow[(Allowance rows)]
      end
    
      subgraph model [Provider]
        LLM[Model API]
      end
    
      Browser -->|session, requestId, task| Admit
      Admit -->|busy| Browser
      Admit --> Pick
      Pick -->|job| Browser
      Pick -->|over allowance| Browser
      Pick --> Stream
      Stream --> LLM
      Stream --> Ledger
      Ledger --> Allow
    text
    Priya asks for a glossary explanation
    -> admitTutor: in-flight under ceiling, else busy and stop
    -> selectProfile("glossary") = draft-small
    requested profile draft-long is ignored
    -> remaining allowance covers unitsForCall estimate, else over_allowance
    -> provider streams
    -> first delta is flushed immediately
    -> deadline 8s: typed timeout, partial units charged once
    -> recordCharge(northwind, requestId, units)
    -> same requestId on the other instance: duplicate, no second add
    Course synthesis
    -> selectProfile returns job
    -> no provider call on this request
    Contoso
    -> a separate allowance row
    -> a Northwind charge cannot increment it

    Trust boundary: the allowance row is written by the API role for the session's organization only. The browser may send requestId and a task name. It may send a profile, and the server discards it. Estimated units before the call use a conservative token cap so a late bill cannot blow the allowance by surprise. The assignment records the estimate as a reservation and reconciles to actual tokens when the span closes.

    Failure point: a process-local ledger on two instances. Both charge, unless the charge commit is a unique key on (organization_id, request_id) in Postgres.

    Step-by-step Implementation

    Package: packages/budget/. Pure functions. Postgres is the unique key in production. Tests use an in-memory ledger.

    Step 1: Profiles, budgets, charges

    packages/budget/src/types.ts

    typescript
    export type ProfileId = "draft-small" | "draft-standard" | "draft-long";
    export type TaskClass = "glossary" | "section" | "synthesis";
    export interface ProfileCard {
    id: ProfileId;
    /** Relative weight. Not currency. */
    weight: number;
    expectedTtftMs: number;
    }
    export interface LatencyBudget {
    maxTtftMs: number;
    maxTotalMs: number;
    }
    export interface Charge {
    organizationId: string;
    requestId: string;
    profile: ProfileId;
    units: number;
    }
    export interface Ledger {
    charges: Charge[];
    /** Weekly cap per organization. Not a remaining balance. */
    allowanceUnits: Record<string, number>;
    }
    export type LatencyStatus = "ok" | "slow_ttft" | "over_total";
    export const PROFILES: readonly ProfileCard[] = [
    { id: "draft-small", weight: 1, expectedTtftMs: 400 },
    { id: "draft-standard", weight: 4, expectedTtftMs: 900 },
    { id: "draft-long", weight: 15, expectedTtftMs: 2000 },
    ];
    export const PLAYER_BUDGET: LatencyBudget = { maxTtftMs: 1_000, maxTotalMs: 8_000 };

    draft-long expects a first token at 2,000 ms, which is already outside PLAYER_BUDGET. The long profile is not a player-path choice in this lab.

    Step 2: Units, ledger, and duplicate charges

    packages/budget/src/ledger.ts

    typescript
    import type { Charge, Ledger, ProfileCard } from "./types.js";
    /** Output tokens weigh more. The multiplier is a lab stand-in for a price card. */
    export function unitsForCall(profile: ProfileCard, inputTokens: number, outputTokens: number): number {
    if (inputTokens < 0 || outputTokens < 0) {
    throw new Error("token counts must be >= 0");
    }
    const weighted = inputTokens + outputTokens * 3;
    return Math.ceil((weighted / 1000) * profile.weight);
    }
    export function spentUnits(ledger: Ledger, organizationId: string): number {
    return ledger.charges
    .filter((charge) => charge.organizationId === organizationId)
    .reduce((sum, charge) => sum + charge.units, 0);
    }
    export function recordCharge(
    ledger: Ledger,
    charge: Charge,
    ): { ok: true; spent: number; duplicate: boolean } | { ok: false; code: "unknown_tenant" | "over_allowance" } {
    const cap = ledger.allowanceUnits[charge.organizationId];
    if (cap === undefined) return { ok: false, code: "unknown_tenant" };
    const existing = ledger.charges.find(
    (row) => row.organizationId === charge.organizationId && row.requestId === charge.requestId,
    );
    if (existing) {
    return { ok: true, spent: spentUnits(ledger, charge.organizationId), duplicate: true };
    }
    const next = spentUnits(ledger, charge.organizationId) + charge.units;
    if (next > cap) return { ok: false, code: "over_allowance" };
    ledger.charges.push(charge);
    return { ok: true, spent: next, duplicate: false };
    }

    recordCharge mutates the in-memory ledger the way a transaction mutates a row. Tests pass a fresh ledger. Production wraps the same decision in a unique constraint so two instances cannot both pass the find and both insert. The function's job is the decision. The constraint is the backstop. Write both. The production key is (organization_id, request_id).

    Step 3: Profile selection, flush, and admission

    packages/budget/src/route.ts

    typescript
    import { PLAYER_BUDGET, PROFILES } from "./types.js";
    import type { LatencyBudget, LatencyStatus, ProfileId, TaskClass } from "./types.js";
    export type RouteDecision =
    | { path: "stream"; profile: ProfileId }
    | { path: "job"; reason: "over_player_budget" }
    | { path: "refuse"; code: "over_allowance" };
    const TASK_PROFILE: Record<TaskClass, ProfileId | "job"> = {
    glossary: "draft-small",
    section: "draft-standard",
    synthesis: "job",
    };
    /** requestedProfile stays in the signature so a test can prove the server ignores it. */
    export function selectProfile(task: TaskClass, requestedProfile: string | null): RouteDecision {
    const chosen = TASK_PROFILE[task];
    void requestedProfile;
    if (chosen === "job") return { path: "job", reason: "over_player_budget" };
    return { path: "stream", profile: chosen };
    }
    export function latencyStatus(ttftMs: number, totalMs: number, budget: LatencyBudget = PLAYER_BUDGET): LatencyStatus {
    if (totalMs > budget.maxTotalMs) return "over_total";
    if (ttftMs > budget.maxTtftMs) return "slow_ttft";
    return "ok";
    }
    /** A buffered completion reports total time as the first byte. Streaming reports the real first token. */
    export function firstByteDelayMs(firstTokenAtMs: number | null, completedAtMs: number): number {
    if (firstTokenAtMs === null) return completedAtMs;
    return firstTokenAtMs;
    }
    export function admitTutor(inFlight: number, ceiling: number): "admit" | "busy" {
    if (ceiling < 1) throw new Error("ceiling must be >= 1");
    return inFlight < ceiling ? "admit" : "busy";
    }
    export function profileCard(id: ProfileId): (typeof PROFILES)[number] {
    const card = PROFILES.find((profile) => profile.id === id);
    if (!card) throw new Error(`unknown profile ${id}`);
    return card;
    }

    Reservation before the call uses unitsForCall with the route's max input and max output. If that reservation exceeds the remaining allowance, return over_allowance and do not open the provider socket. When the span closes, reconcile to actual tokens under the same request id. Update the row if you reserved a higher number. Do not insert a second charge. The in-memory function records the actual charge once. The assignment adds a held flag so a crash between reserve and reconcile releases the hold.

    selectProfile does not return over_allowance. The handler compares unitsForCall with allowanceUnits - spentUnits after selection. Splitting the decisions keeps the profile table free of ledger state.

    Step 4: Run

    bash
    node --test packages/budget/src/ledger.test.ts packages/budget/src/route.test.ts

    No cloud bill is created. If a later environment points weights at a live price, that binding stays outside this package and outside git. The weights in PROFILES are the reviewed stand-ins.

    Security

    • Authentication. Charging runs after the session is valid. An anonymous request does not open a provider call and does not write a ledger row.
    • Authorization. The session organization is the only organizationId that the handler passes to recordCharge. A body field named organizationId is ignored, the same way a body tenant is ignored on every other route.
    • Least privilege. The API role inserts charges for its organization and reads its allowance. It cannot update Contoso's cap. Finance reads a report role that can aggregate and cannot call the model.
    • Input validation. Token counts must be zero or positive. A negative count would shrink spend. The task class is a closed union. Unknown tasks fail before selectProfile.
    • Secrets. The ledger stores ids, profile ids, and units. It does not store prompts, completions, or the provider key. The span allowlist from lesson 59 is the source.
    • Tenant isolation. Allowances are separate maps. A duplicate check includes organizationId. A Northwind retry must not mark a Contoso request id as already charged.
    • Abuse. admitTutor and the allowance limit a script that loops Explain. The ignored client profile limits a script that asks for draft-long. Rate limits from the API security lesson still apply. They do not replace the ceiling.

    A model that rambles can inflate output tokens. The output cap from the streaming lesson still applies inside this budget. Units are calculated on the tokens you actually accepted, after that cap.

    Error Handling

    EventLearner seesSystem does
    In-flight at the ceilingTutor busy, lesson staysNo provider call, no charge
    Allowance would be exceededTutor over_allowanceNo provider call
    Client sent profile=draft-long on a glossary taskA draft-small streamselectProfile ignores the argument
    First token late, total inside budgetThe streamslow_ttft on the review metric
    Total time past 8 secondsTyped timeoutOne partial charge for consumed tokens. No automatic second call
    Same requestId arrives againThe original outcomeduplicate: true, units unchanged
    Unknown organization on the ledgerNo tutorunknown_tenant. An allowance is not created implicitly
    Synthesis task202 with a job placeholderNo player-path provider call
    Provider 429 or 5xxTyped unavailableCharge only tokens the provider billed. Profiles are not looped

    over_allowance is a product state, not a 500. The lesson page renders the same calm fallback it uses for unavailable, with copy that a weekly limit was reached. The numeric cap stays on the finance report. It is not rendered to every learner.

    Testing

    packages/budget/src/ledger.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { recordCharge, unitsForCall } from "./ledger.js";
    import { profileCard } from "./route.js";
    import type { Ledger } from "./types.js";
    function emptyLedger(): Ledger {
    return {
    charges: [],
    allowanceUnits: { northwind: 500, contoso: 500 },
    };
    }
    test("weighs the long profile higher for the same tokens", () => {
    const small = unitsForCall(profileCard("draft-small"), 400, 80);
    const long = unitsForCall(profileCard("draft-long"), 400, 80);
    assert.equal(long, small * 15);
    });
    test("charges Northwind once for a repeated request id", () => {
    const ledger = emptyLedger();
    const charge = {
    organizationId: "northwind",
    requestId: "req_priya_1",
    profile: "draft-small" as const,
    units: 2,
    };
    const first = recordCharge(ledger, charge);
    const second = recordCharge(ledger, charge);
    assert.equal(first.ok && first.duplicate, false);
    assert.equal(second.ok && second.duplicate, true);
    assert.equal(ledger.charges.length, 1);
    });
    test("does not spend Contoso's allowance for a Northwind charge", () => {
    const ledger = emptyLedger();
    recordCharge(ledger, {
    organizationId: "northwind",
    requestId: "req_shared_string",
    profile: "draft-standard",
    units: 40,
    });
    const contoso = recordCharge(ledger, {
    organizationId: "contoso",
    requestId: "req_shared_string",
    profile: "draft-standard",
    units: 40,
    });
    assert.equal(contoso.ok && contoso.duplicate, false);
    assert.equal(contoso.ok && contoso.spent, 40);
    });
    test("stops at the allowance", () => {
    const ledger = emptyLedger();
    ledger.allowanceUnits.northwind = 10;
    const result = recordCharge(ledger, {
    organizationId: "northwind",
    requestId: "req_big",
    profile: "draft-long",
    units: 11,
    });
    assert.deepEqual(result, { ok: false, code: "over_allowance" });
    assert.equal(ledger.charges.length, 0);
    });

    packages/budget/src/route.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { admitTutor, firstByteDelayMs, latencyStatus, selectProfile } from "./route.js";
    test("ignores a client profile on glossary", () => {
    const decision = selectProfile("glossary", "draft-long");
    assert.deepEqual(decision, { path: "stream", profile: "draft-small" });
    });
    test("sends synthesis off the player path", () => {
    const decision = selectProfile("synthesis", null);
    assert.equal(decision.path, "job");
    });
    test("treats a buffered completion as a late first byte", () => {
    assert.equal(firstByteDelayMs(null, 8_000), 8_000);
    assert.equal(firstByteDelayMs(450, 8_000), 450);
    assert.equal(latencyStatus(450, 8_000), "ok");
    assert.equal(latencyStatus(450, 8_001), "over_total");
    assert.equal(latencyStatus(1_200, 2_000), "slow_ttft");
    });
    test("rejects work at the ceiling", () => {
    assert.equal(admitTutor(4, 4), "busy");
    assert.equal(admitTutor(3, 4), "admit");
    });

    Add a test that a negative token count throws, and a test that unknown_tenant does not insert a charge. Add a test that a timeout's second recordCharge with the same request id stays a duplicate after the partial units were stored.

    Performance and Cost

    The point of this package is the bill and the wait. A few more rules keep the controls from becoming the bottleneck.

    • Compute unitsForCall in process. A pricing API on the tutor path would make a pricing outage take down Explain.
    • The unique index on (organization_id, request_id) is the cross-instance lock. A read-then-insert without that index double-charges under concurrency even when the unit test passes.
    • Reservation uses the route max tokens. Over-reserving blocks legitimate calls. Under-reserving lets a long completion pass a check it will fail at reconcile time. Reconcile downward in place. If actual units exceed the reservation, the output cap is wrong. Fix the cap. Do not insert a second silent charge.
    • admitTutor is an integer compare. The expensive bug is a shared counter that forgets to decrement on timeout. Decrement in a finally so a thrown provider error cannot leak a slot until restart.
    • Flush the first token immediately, then coalesce later deltas on a short interval well under maxTtftMs. Coalescing the first token is the buffering bug.
    • Glossary traffic should dominate the call count and not the units. If the weekly report shows glossary on draft-long, the selector regressed. Review that pair. Do not wait for the invoice.
    • Worker eval spend from lesson 58 uses unitsForCall and a separate allowance, or the same bucket with a reserved floor for learners. A morning golden-set run must leave room for Priya's tutor. Write the split down.
    • Caching repeated glossary answers is the largest remaining unit cut. It is lesson 62. A cache designed inside this package, in a hurry, will cross tenants. Leave the key design to that lesson.

    Illustrative ratio, not a quote: moving glossary from weight 15 to weight 1 cuts that task's units by fifteen times before any cache. Flushing the first token does not cut units. It cuts the silence, and it keeps the call inside 8 seconds so you do not pay for a truncated completion the learner never reads.

    Knowledge Check

    1. What problem does this cost and latency work solve?

    It stops TechLearningPro from spending the long profile on a glossary click, from buffering the stream until the deadline, and from charging Northwind twice for one request id. Contoso's allowance stays Contoso's. Synthesis leaves the player path. The numbers come from the redacted span, not from a new transcript.

    2. What alternatives exist, and when would you choose each?

    A single shared company allowance fits an internal tool with one tenant. It does not fit Northwind and Contoso. A hard daily cap at the provider fits as a backstop and does not replace the per-organization ledger, because the provider cannot see your tenant boundary. Streaming the first token is the player default. Buffering fits a batch job that nobody is watching. A queue fits synthesis and any task whose expected first token misses PLAYER_BUDGET. A smaller profile fits when the eval report says quality still passes.

    3. Which data, identity, and trust boundaries matter?

    The session organization owns the charge. The body cannot choose an organization or a profile. The ledger stores units and ids. The provider key stays in the secret store. Allowances are per organization. The report query uses the same tenant predicate as the rest of the API. Metric labels stay free of tenant id.

    4. What can fail, and how should the system respond?

    A full ceiling returns busy and does not call the model. An allowance miss returns over_allowance and does not call the model. A late total returns timeout, charges consumed tokens once, and does not retry. A duplicate request id does not add units. An unknown organization does not create a cap. A provider error returns unavailable. A client profile string does not change the card.

    5. How would you test quality, security, performance, and cost?

    Unit tests cover weights, duplicate request ids, cross-tenant request-id strings, the allowance stop, the ignored client profile, the job path, both clocks, and the ceiling. Security review checks that the handler passes the session organization only. Performance review checks first-byte flush and finally decrement of the in-flight count. Cost review checks weekly units by profile and confirms glossary is not on draft-long. A unique index, or a concurrency test against Postgres, covers two instances.

    Hands-on Assignment

    Lab note. Do not call a provider and do not paste a price card into git. Weights stay 1, 4, and 15 until you change them in a reviewed binding outside this lesson's tests.

    Problem. Serve Priya's glossary click on draft-small, flush the first token, charge Northwind once, and leave Contoso's 500 units untouched.

    Tasks.

    1. Draw admission, selection, stream, and ledger, with the provider behind the ceiling.
    2. Implement unitsForCall, recordCharge, selectProfile, latencyStatus, firstByteDelayMs, and admitTutor with the tests above, plus the extra tests named in Testing.
    3. Document the production unique key (organization_id, request_id) next to recordCharge.
    4. Reserve the worst-case units for a glossary call and refuse when Northwind's remaining cap cannot hold them.
    5. Show the learner-visible result for busy, over_allowance, timeout, and job.
    6. Write the weekly review columns: organization, profile, calls, units. Confirm the review is a query, not a metric label.
    7. State which span fields you read. Confirm the prompt is not one of them.

    Deliverable. Diagram, source with no secrets, test output, the review columns, and a trade-off note on one shared allowance versus per-organization caps.

    Challenge. Launch week multiplies Northwind tutor traffic by ten, and the provider enforces a per-minute token cap. Explain the new ceiling, the busy copy, and whether you raise minInstances. Contoso's traffic is flat. Their allowance and their latency must stay independent of Northwind's queue. Synthesis stays on the job path. A second constraint: finance wants the prompt stored on the charge for audit. Refuse, and point at the span allowlist.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.

    Common Mistakes

    1. Honoring profile from the query string. Symptom: glossary units jump by 15 times. Cause: the client hint was convenient in a demo. Fix: selectProfile ignores it. Test with draft-long on a glossary task.
    2. Buffering the completion before the first write. Symptom: ttftMs equals total time, then the deadline truncates the answer. Cause: the handler awaited the full body. Fix: flush the first delta. Compare the two clocks in review.
    3. A process-local ledger on two instances. Symptom: one click, two charges. Cause: each instance's array could not see the other. Fix: a unique key on organization and request id.
    4. A global request-id map. Symptom: Contoso's call is treated as Northwind's duplicate, or Northwind is billed for both. Cause: the key omitted organizationId. Fix: both fields, covered by the shared-string test.
    5. Retrying a timeout automatically. Symptom: a second draft and a second set of units. Cause: the progress-route retry policy was copied onto the tutor. Fix: one charge, no second provider call. A new learner click is a new request id.
    6. Creating an allowance on first sight. Symptom: a typo'd organization spends without a cap. Cause: unknown_tenant inserted a row and then charged it. Fix: fail closed.
    7. Negative or client-supplied token counts. Symptom: spend shrinks. Cause: the count came from the browser. Fix: counts come from the server-side provider response. Reject negatives.
    8. Raising the container timeout instead of enforcing the budget. Symptom: silent waits and a larger bill. Cause: the platform ceiling was used as hope. Fix: return timeout at 8 seconds. Leave the platform ceiling as a backstop.
    9. Putting organization id on tutor.tokens. Symptom: a cardinality jump and a cross-tenant chart. Cause: the ledger was exported as a metric label. Fix: the report is a query with a tenant predicate.
    10. Letting the eval batch share the learner allowance with no floor. Symptom: a morning golden-set run blocks Priya's tutor. Cause: one counter, two workloads. Fix: separate caps, or a reserved learner floor.

    Summary

    Cost and latency controls turn lesson 59's counts into decisions. TechLearningPro charges relative units to one organization's allowance, once per request id, on the profile the server selected. Glossary stays on draft-small. The first token is flushed so time to first token is real. A ceiling returns busy before a spike multiplies the provider bill. Work that cannot meet the player budget leaves the request as a job. Northwind's spend cannot move Contoso's cap. The prompt stays out of the ledger. The job itself is the next lesson.

    Next Lesson Preview

    Background Jobs, Queues and Event-Driven AI Processing picks up the job decision. You will accept a cohort reminder, a synthesis, and an eval batch with 202, run them on a worker, and make a retry finish the side effect once. The player will not hold a stream open until forty model calls complete.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.