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

    Scaling, Resilience and Production Readiness

    Northwind's cohort opens on a Monday.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

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

    Lesson Overview

    Northwind's cohort opens on a Monday. Instructors open the lesson player, editors ask the workspace copilot for a draft, and a support lead starts the reminder workflow from Lesson 47. The model provider returns 429s for eleven minutes. A production-ready TechLearningPro keeps the player readable, returns model_unavailable on draft routes, sheds new AI admissions when in-flight work hits the cap, and leaves an already-approved mail ticket on its original idempotency key. A build that "works on one laptop" instead retries the provider inside the HTTP request, pins sessions to one Node process, and marks the pod Ready before the migration that adds tenant_id has finished.

    This lesson is the gate those capstones must pass. Scaling is how the stateless API, the Postgres pool, and the worker fleet grow. Resilience is how a timeout, an open circuit, and a dead-letter queue stay bounded. Production readiness is a versioned checklist, readiness-v1, evaluated by evaluateProductionReadiness before a deploy is called ready. The function does not call a cloud API. It reads a ServiceProfile the repo owns and fails closed when a control is missing.

    Planning assumptions:

    • The API process stores no session, no job, and no circuit history that another replica must see. Circuit state is per process and is allowed to flap independently.
    • Player reads and AI writes have separate SLOs. A provider outage burns the AI error budget. It does not page the player as a site outage.
    • Illustrative numbers: request deadline 30 seconds, provider deadline 12 seconds, AI in-flight cap 32 per process, circuit opens after 5 failures, queue depth page at 500, player availability target 0.999, AI draft p95 target 8 seconds. Finance and SRE replace the numbers. The shape of the checks stays.
    • Secrets stay in the platform secret store. Profiles and traces contain names and counts.
    • Lessons 59 through 62 already defined traces, cost budgets, queues, and tenant-keyed caches. This lesson composes them into one ship gate.

    The four capstones that follow cite this checklist. A project that cannot explain its shed behavior, its degrade path, and its probe is not done.

    Learning Objectives

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

    1. Separate horizontal scale of a stateless API from resilience of a dependency you do not control.
    2. Give the lesson player and the model path different SLOs and different page routes.
    3. Implement admission control that sheds AI work at a fixed in-flight cap.
    4. Bound provider calls with a deadline shorter than the request deadline.
    5. Open a circuit after repeated failures and allow a single half-open probe.
    6. Retry only idempotent reads, with a budget, and leave write keys stable.
    7. Degrade to model_unavailable while Postgres reads continue.
    8. Gate Ready on migrations, pool headroom, and a draining flag.
    9. Cap queue depth and require a dead-letter path for AI jobs.
    10. Evaluate readiness-v1 in CI so a missing control fails the build.
    11. Keep traces free of prompts, document bodies, and secret handles.
    12. Size connection pools so replica count times pool size stays under Postgres max_connections.
    13. Name the load you shed first when the provider is hot.
    14. Write the on-call line that says an open circuit is a successful degrade.
    15. Apply the same gate to the SaaS workspace, the RAG assistant, and the ops agent.

    Prerequisites

    You can run Node's test runner. You do not need a cloud account or a provider key to evaluate a profile.

    What is Scaling, Resilience and Production Readiness?

    Scaling is adding capacity on purpose: more stateless API replicas, a larger worker fleet when queue delay grows, and a database pool that still fits the server. Resilience is the behavior when capacity or a dependency is not there: shed, timeout, open the circuit, degrade, and keep the idempotency key. Production readiness is the written, testable claim that both are true for this service before traffic arrives.

    The purpose is to stop "the demo succeeded" from becoming the launch plan. A single Node process can hide a memory session, an unbounded Promise.all of provider calls, and a Ready probe that always returns 200. The checklist makes those properties visible in git.

    The industry pattern is old. Load balancers, circuit breakers, and error budgets (Google SRE, Microsoft Azure well-architected guidance, AWS multi-AZ writeups) predate LLMs. What changed is the failure domain. A model provider is slower, rate-limited, and non-deterministic. TechLearningPro treats that provider as a dependency with its own SLO, the way a bank treats a card network and a hospital treats an external lab interface. The product database remains the system of record.

    TermMeaning in this lesson
    ReplicaOne stateless API process behind the load balancer
    Admissionadmit allows or sheds a new AI call
    DeadlineAbortSignal time after which the call is failure
    CircuitClosed, open, or half-open around the provider
    DegradePlayer reads succeed; AI routes return model_unavailable
    ReadyProcess may receive traffic
    LiveProcess should be restarted if this fails
    Error budgetAllowed unavailability before a release freeze
    ProfileServiceProfile checked by readiness-v1
    ShedHTTP 429 shed with no provider call

    Why Do We Need It?

    text
    One process, in-memory session, retry-until-success
    |
    v
    Provider 429 holds every request; pool exhausts; Ready stays green
    |
    v
    Player, drafts, and reminders fail together
    |
    v
    Stateless replicas, admission, deadlines, open circuit, separate SLOs
    |
    v
    Reads continue, AI sheds, deploys wait for migrations

    Benefits:

    • A second replica does not fork the session or the job.
    • The provider's bad hour does not become an unbounded retry storm.
    • CI can reject a service that forgot idempotency or a dead-letter queue.
    • On-call has one report: which readiness-v1 checks are red.
    • Capstone projects inherit the same gate instead of inventing a new one in the README.

    Real World Example

    During the Monday launch, Northwind traffic doubles. The platform adds API replicas. Each replica uses a pool of 10 Postgres connections. The runbook caps replicas so replicas * 10 stays below the server's max_connections, leaving room for workers and migrations. AI admission on each process stops at 32 in-flight provider calls. The 33rd draft receives shed and does not occupy a pool slot waiting on the provider.

    When the provider error rate crosses five failures, the circuit opens for 30 seconds. Draft routes return model_unavailable immediately. The lesson player still loads from Postgres. A half-open probe sends one request. Success closes the circuit. Failure opens it again from that timestamp.

    Netflix-style playback and Amazon-style product pages taught the same split: the browse path survives when a recommendation dependency is sick. Google and Microsoft document circuit breaking on their API gateways for the same reason. A card issuer sheds authorizations before it stalls the ledger. TechLearningPro's version is concrete: shed AI, serve the lesson, keep the reminder ticket's key.

    A deploy that has not applied the tenant_id migration fails migrations_applied. The pod stays out of rotation. Traffic remains on the previous revision.

    Internal Working

    1. The load balancer sends the request to any Ready replica. Stickiness is not required.
    2. Liveness returns 200 when the event loop can answer. It does not check the provider.
    3. Readiness returns 503 unless migrations are applied, the pool has headroom, and the process is not draining.
    4. Player and note reads take a tenant-scoped query with requestTimeoutMs as the deadline. They do not call the model.
    5. An AI route calls admit. shed returns 429 and records ai_shed_total. The provider is not called.
    6. Admitted work calls the provider with providerTimeoutMs and the caller's AbortSignal. The provider deadline is shorter than the request deadline.
    7. An idempotent read may retry inside retry.budgetMs with jitter. A write uses the original idempotency key and does not loop inside the request.
    8. Failures update the circuit. At errorThreshold the state becomes open and openedAtMs is set. Calls during open fail as circuit_open with no network I/O.
    9. After openMs, one probe is allowed (half_open). A second concurrent call still sees open until the probe settles.
    10. Provider failure on a user-facing draft becomes model_unavailable. The stored note body is unchanged. A queue worker uses the same circuit and parks the job or dead-letters it. It does not tight-loop.
    11. Queue depth above maxDepth fails readiness for the worker service and pages. The API keeps serving reads.
    12. evaluateProductionReadiness runs in CI and as a boot assertion. ready: false fails the pipeline. The report lists every check id.

    Architecture

    flowchart TB
      subgraph edge [Edge]
        LB[Load balancer]
      end
      subgraph api [Stateless API replicas]
        Live[Liveness]
        Ready[Readiness]
        Admit[AI admission]
        Player[Lesson reads]
        Draft[Draft routes]
      end
      subgraph data [System of record]
        PG[(Postgres)]
        Queue[AI job queue]
        DLQ[Dead letter]
      end
      subgraph dep [Dependency]
        Circuit[Circuit breaker]
        Model[Model provider]
      end
      LB --> Live
      LB --> Ready
      LB --> Player
      LB --> Draft
      Player --> PG
      Draft --> Admit
      Admit -->|shed| Client[Client 429]
      Admit -->|ok| Circuit
      Circuit -->|closed or probe| Model
      Circuit -->|open| Degrade[model_unavailable]
      Draft --> Queue
      Queue --> DLQ
      Queue --> Circuit
    text
    Request
    |
    +--> live probe --> process up?
    +--> ready probe --> migrations, pool, not draining
    |
    +--> player read --> tenant query --> Postgres
    |
    +--> AI route
    |
    +--> admit == shed --> 429, stop
    +--> circuit open --> model_unavailable, stop
    +--> provider deadline --> model_unavailable
    +--> success --> persist draft, trace counts

    Request flow never holds a Postgres connection for the full provider timeout. The handler checks the circuit and the cap first. Response flow for a shed or an open circuit is a small JSON reason. The provider body is not forwarded.

    sequenceDiagram
      participant Client
      participant API as API replica
      participant PG as Postgres
      participant CB as Circuit
      participant Model as Provider
    
      Client->>API: GET lesson
      API->>PG: tenant-scoped read
      PG-->>Client: 200 lesson
      Client->>API: POST draft
      API->>API: admit at cap
      API-->>Client: 429 shed
      Note over API,CB: later, circuit open after failures
      Client->>API: POST draft
      API->>CB: state open
      API-->>Client: model_unavailable
      API->>PG: note body unchanged

    Deep Dive

    Stateless replicas

    A replica may keep a per-process circuit, an in-flight counter, and a parsed config. It may not keep the logged-in user, the draft, or the job. Those live in Postgres, the queue, or the signed session cookie from Lesson 48. Horizontal scale is then "add a pod." A memory session would make the second replica a different product.

    Drain happens before exit. The process fails readiness, finishes admitted calls up to the request deadline, and then exits. The load balancer uses readiness, so new work lands elsewhere while old work completes.

    Two SLOs

    playerAvailability targets 0.999 over 30 days. aiDraftP95Ms targets 8000. Burning the AI budget freezes AI releases and prompt changes. It does not freeze a CSS fix on the player. Combining them into one "site is red" alert trains on-call to restart the API during a provider incident, which makes the circuit useless.

    The error budget for the player is about 43 minutes per 30 days at 0.999. Spend it on deploys and real faults. Do not spend it on purpose by coupling Ready to the provider.

    Admission and the pool

    maxInFlight is per process. The shed response is cheaper than a queued provider call. Postgres pools stay small because each replica holds poolSize connections even when idle. The checklist item pool_headroom requires replicas * poolSize < maxConnections * 0.7. The 0.7 leaves workers, admin sessions, and migrations. Raising the pool to "fix latency" without lowering replicas is how Monday becomes too many connections.

    Shed order when the node is hot: AI drafts first, then background ingest triggers, then player writes. Player reads are last. Health probes are never shed.

    Deadlines, retries, idempotency

    The request deadline covers the handler. The provider deadline is inside it, so the handler can still write model_unavailable and release the connection. Retries of a provider read use jitter and stop at retry.budgetMs. Three immediate retries without jitter are a self-inflicted 429 storm.

    Writes do not retry with a new key. Lesson 47's idem_${runId} remains the key if the reminder worker sees execution_unknown. Scaling out workers increases the chance of a duplicate delivery. Idempotency is the control that makes that safe.

    Circuit

    closed counts consecutive failures. At errorThreshold the circuit opens and records openedAtMs. While open, allowCall returns false. After openMs, the first caller gets probe: true and the state becomes half_open. Other callers wait. The probe's success closes. The probe's failure reopens and refreshes openedAtMs. A process restart closes the circuit because state is local. That is acceptable: a new replica is a fresh probe. A shared circuit in Redis is optional later and is not required to pass readiness-v1.

    Queues

    Interactive drafts may run in the request until the provider deadline. Ingestion, embedding, and eval jobs go to the queue from Lesson 61. maxDepth fails the worker's readiness when the backlog is the incident. The dead-letter queue holds jobs that exhausted attempts. Operators replay from the DLQ with the same idempotency key. They do not point the poison message back at the live consumer in a loop.

    The production readiness checklist

    readiness-v1 is the contract. Each row is a check id, a pass rule, and the incident it prevents.

    Check idPass ruleIncident prevented
    stateless_apiProfile says replicas store no session or jobSplit brain after scale-out
    live_probeLiveness path answers without the providerRestart loop during a vendor outage
    ready_probeReadiness path can return 503Traffic on a half-migrated schema
    migrations_appliedBoot waits for the required schema versionQueries against a missing tenant_id
    timeouts_boundedRequest ≤ 30s and provider ≤ 12s, provider shorter than requestHung handlers, pool exhaustion
    admission_capmaxInFlight is a positive finite numberUnbounded provider concurrency
    retry_budgetAttempts ≥ 1 and budget ≤ provider timeoutRetry storms
    circuit_breakerThreshold and open window are setCalling a dead provider on every hit
    idempotent_writesWrite routes declare an idempotency keyDuplicate mail or double refunds
    tenant_predicateEvery data access is tenant-scopedCross-tenant cache or query under load
    graceful_degradeProvider failure has a non-500 AI reason and reads still workSite down because the model is down
    slo_splitPlayer availability and AI latency are separate numbersPaging the player for a 429
    queue_boundsMax depth is set and a DLQ exists for workersInfinite backlog, poison jobs
    pool_headroomreplicas * poolSize under 70% of maxConnectionstoo many connections
    secrets_externalProfile forbids secrets in the repo and the client bundleKey in git
    trace_redactionTraces store ids and counts, not prompts or document bodiesPII in the log vendor
    drain_on_exitRollout fails readiness before SIGTERM work endsDropped requests on every deploy
    cost_ceilingA per-tenant token or call ceiling existsOne tenant spends the month's budget

    A new capstone adds rows only by extending the evaluator and the tests. A README checklist that CI does not run is not readiness-v1.

    What this lesson will not do

    It will not autoscale on CPU alone. Queue delay and shed rate are the AI signals. It will not mark Ready when the provider is healthy and Postgres is not. It will not put the provider key in the profile. It will not retry a refund inside the request. It will not share a cache key across tenants to "improve hit rate" during a spike. Lesson 62's tenant prefix remains mandatory when you add replicas.

    Code Examples

    Place the gate in packages/platform/src/readiness/. CI imports evaluateProductionReadiness. The API imports admit, allowCall, and noteProviderResult.

    Simple example: admission

    packages/platform/src/readiness/admit.ts

    typescript
    export interface Admission {
    decision: "ok" | "shed";
    inFlight: number;
    maxInFlight: number;
    }
    /**
    * Shed when this process is already at the cap.
    * The caller must not start provider I/O after "shed".
    */
    export function admit(inFlight: number, maxInFlight: number): Admission {
    if (!Number.isFinite(maxInFlight) || maxInFlight < 1) {
    return { decision: "shed", inFlight, maxInFlight };
    }
    if (inFlight >= maxInFlight) {
    return { decision: "shed", inFlight, maxInFlight };
    }
    return { decision: "ok", inFlight, maxInFlight };
    }

    A missing or non-finite cap sheds. That is the fail-closed direction. The route increments the counter only after ok, and decrements it in finally.

    Intermediate example: circuit

    packages/platform/src/readiness/circuit.ts

    typescript
    export type CircuitState = "closed" | "open" | "half_open";
    export interface Circuit {
    state: CircuitState;
    failures: number;
    openedAtMs?: number;
    probeInFlight: boolean;
    }
    export function initialCircuit(): Circuit {
    return { state: "closed", failures: 0, probeInFlight: false };
    }
    export interface AllowDecision {
    allow: boolean;
    circuit: Circuit;
    reason: "closed" | "probe" | "open";
    }
    /**
    * One probe after the open window. Concurrent callers stay shed
    * until that probe records a result.
    */
    export function allowCall(circuit: Circuit, nowMs: number, openMs: number): AllowDecision {
    if (circuit.state === "open") {
    const elapsed = circuit.openedAtMs === undefined ? 0 : nowMs - circuit.openedAtMs;
    if (elapsed >= openMs && !circuit.probeInFlight) {
    return {
    allow: true,
    reason: "probe",
    circuit: { ...circuit, state: "half_open", probeInFlight: true },
    };
    }
    return { allow: false, reason: "open", circuit };
    }
    return { allow: true, reason: "closed", circuit };
    }
    export function noteProviderResult(
    circuit: Circuit,
    nowMs: number,
    succeeded: boolean,
    errorThreshold: number,
    ): Circuit {
    if (succeeded) {
    return { state: "closed", failures: 0, probeInFlight: false };
    }
    const failures = circuit.failures + 1;
    if (failures >= errorThreshold || circuit.state === "half_open") {
    return { state: "open", failures, openedAtMs: nowMs, probeInFlight: false };
    }
    return { state: "closed", failures, probeInFlight: false };
    }

    allowCall returns the next circuit so the caller stores it before awaiting the provider. Forgetting to store the half-open probe lets a second request through.

    Enterprise example: the readiness gate

    packages/platform/src/readiness/profile.ts

    typescript
    export const READINESS_VERSION = "readiness-v1" as const;
    export interface ServiceProfile {
    name: string;
    stateless: boolean;
    livenessPath: string;
    readinessPath: string;
    migrationsApplied: boolean;
    drainingSupported: boolean;
    requestTimeoutMs: number;
    providerTimeoutMs: number;
    maxInFlight: number;
    retry: { maxAttempts: number; budgetMs: number };
    circuit: { errorThreshold: number; openMs: number };
    idempotentWrites: boolean;
    tenantPredicate: boolean;
    gracefulDegrade: boolean;
    slo: { playerAvailability: number; aiDraftP95Ms: number };
    queue: { enabled: boolean; maxDepth: number; deadLetter: boolean };
    pool: { replicas: number; poolSize: number; maxConnections: number };
    secretsExternal: boolean;
    traceRedaction: boolean;
    costCeiling: boolean;
    }
    export interface ReadinessCheck {
    id: string;
    passed: boolean;
    detail: string;
    }
    export interface ReadinessReport {
    version: typeof READINESS_VERSION;
    service: string;
    ready: boolean;
    checks: ReadinessCheck[];
    }
    export const TECHLEARNINGPRO_API: ServiceProfile = {
    name: "techlearningpro-api",
    stateless: true,
    livenessPath: "/live",
    readinessPath: "/ready",
    migrationsApplied: true,
    drainingSupported: true,
    requestTimeoutMs: 30_000,
    providerTimeoutMs: 12_000,
    maxInFlight: 32,
    retry: { maxAttempts: 2, budgetMs: 400 },
    circuit: { errorThreshold: 5, openMs: 30_000 },
    idempotentWrites: true,
    tenantPredicate: true,
    gracefulDegrade: true,
    slo: { playerAvailability: 0.999, aiDraftP95Ms: 8_000 },
    queue: { enabled: true, maxDepth: 500, deadLetter: true },
    pool: { replicas: 4, poolSize: 10, maxConnections: 100 },
    secretsExternal: true,
    traceRedaction: true,
    costCeiling: true,
    };

    TECHLEARNINGPRO_API is the reference profile. Capstones copy it and change name. They do not weaken tenantPredicate or secretsExternal.

    packages/platform/src/readiness/evaluate.ts

    typescript
    import { READINESS_VERSION, type ReadinessCheck, type ReadinessReport, type ServiceProfile } from "./profile.js";
    const LIMITS = {
    maxRequestTimeoutMs: 30_000,
    maxProviderTimeoutMs: 12_000,
    minPlayerAvailability: 0.995,
    maxAiDraftP95Ms: 8_000,
    maxQueueDepth: 500,
    poolFraction: 0.7,
    } as const;
    function check(id: string, passed: boolean, detail: string): ReadinessCheck {
    return { id, passed, detail };
    }
    /**
    * Fail closed. One red check means ready === false.
    * The function does not read the network or the secret store.
    */
    export function evaluateProductionReadiness(profile: ServiceProfile): ReadinessReport {
    const poolUsed = profile.pool.replicas * profile.pool.poolSize;
    const poolCap = profile.pool.maxConnections * LIMITS.poolFraction;
    const checks: ReadinessCheck[] = [
    check("stateless_api", profile.stateless, "Replicas must not own session or job state"),
    check("live_probe", profile.livenessPath.startsWith("/"), "Liveness path is required"),
    check("ready_probe", profile.readinessPath.startsWith("/"), "Readiness path is required"),
    check("migrations_applied", profile.migrationsApplied, "Schema version must be applied before Ready"),
    check("drain_on_exit", profile.drainingSupported, "Rollouts fail readiness before exit"),
    check(
    "timeouts_bounded",
    profile.providerTimeoutMs > 0 &&
    profile.providerTimeoutMs <= LIMITS.maxProviderTimeoutMs &&
    profile.requestTimeoutMs <= LIMITS.maxRequestTimeoutMs &&
    profile.providerTimeoutMs < profile.requestTimeoutMs,
    "Provider deadline sits inside the request deadline",
    ),
    check("admission_cap", Number.isFinite(profile.maxInFlight) && profile.maxInFlight >= 1, "AI admission cap is finite"),
    check(
    "retry_budget",
    profile.retry.maxAttempts >= 1 && profile.retry.budgetMs > 0 && profile.retry.budgetMs <= profile.providerTimeoutMs,
    "Retries stay inside the provider deadline",
    ),
    check(
    "circuit_breaker",
    profile.circuit.errorThreshold >= 1 && profile.circuit.openMs >= 1_000,
    "Circuit opens and stays open for a window",
    ),
    check("idempotent_writes", profile.idempotentWrites, "Writes declare an idempotency key"),
    check("tenant_predicate", profile.tenantPredicate, "Queries and cache keys include the tenant"),
    check("graceful_degrade", profile.gracefulDegrade, "Provider failure degrades AI and keeps reads"),
    check(
    "slo_split",
    profile.slo.playerAvailability >= LIMITS.minPlayerAvailability &&
    profile.slo.aiDraftP95Ms > 0 &&
    profile.slo.aiDraftP95Ms <= LIMITS.maxAiDraftP95Ms,
    "Player availability and AI latency are separate",
    ),
    check(
    "queue_bounds",
    profile.queue.enabled && profile.queue.deadLetter && profile.queue.maxDepth > 0 && profile.queue.maxDepth <= LIMITS.maxQueueDepth,
    "Workers have a depth cap and a dead-letter queue",
    ),
    check("pool_headroom", poolUsed > 0 && poolUsed < poolCap, "Replica pools fit under max_connections"),
    check("secrets_external", profile.secretsExternal, "Secrets stay in the platform store"),
    check("trace_redaction", profile.traceRedaction, "Traces keep ids and counts"),
    check("cost_ceiling", profile.costCeiling, "A per-tenant cost ceiling exists"),
    ];
    return {
    version: READINESS_VERSION,
    service: profile.name,
    ready: checks.every((item) => item.passed),
    checks,
    };
    }

    packages/platform/src/readiness/degrade.ts

    typescript
    export type AiFailureReason = "shed" | "circuit_open" | "model_unavailable" | "deadline";
    export interface AiResult<T> {
    ok: boolean;
    reason?: AiFailureReason;
    value?: T;
    }
    /**
    * Map dependency outcomes to a client reason.
    * The note body is not part of this result. Callers leave it unchanged.
    */
    export function degradeAi<T>(input: {
    admission: "ok" | "shed";
    circuitAllowed: boolean;
    provider: { ok: true; value: T } | { ok: false; kind: "timeout" | "http" | "unavailable" };
    }): AiResult<T> {
    if (input.admission === "shed") return { ok: false, reason: "shed" };
    if (!input.circuitAllowed) return { ok: false, reason: "circuit_open" };
    if (!input.provider.ok) {
    return { ok: false, reason: input.provider.kind === "timeout" ? "deadline" : "model_unavailable" };
    }
    return { ok: true, value: input.provider.value };
    }

    packages/platform/src/readiness/evaluate.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { admit } from "./admit.js";
    import { allowCall, initialCircuit, noteProviderResult } from "./circuit.js";
    import { degradeAi } from "./degrade.js";
    import { evaluateProductionReadiness } from "./evaluate.js";
    import { TECHLEARNINGPRO_API } from "./profile.js";
    test("reference profile is ready", () => {
    const report = evaluateProductionReadiness(TECHLEARNINGPRO_API);
    assert.equal(report.ready, true);
    assert.equal(report.checks.length, 18);
    });
    test("provider timeout longer than the request fails closed", () => {
    const report = evaluateProductionReadiness({
    ...TECHLEARNINGPRO_API,
    providerTimeoutMs: 60_000,
    });
    assert.equal(report.ready, false);
    assert.equal(report.checks.find((item) => item.id === "timeouts_bounded")?.passed, false);
    });
    test("shed at the cap does not look like a provider success", () => {
    const admission = admit(32, 32);
    assert.equal(admission.decision, "shed");
    const result = degradeAi({
    admission: "shed",
    circuitAllowed: true,
    provider: { ok: true, value: "unused" },
    });
    assert.equal(result.reason, "shed");
    assert.equal(result.value, undefined);
    });
    test("the fifth failure opens and the window blocks the next call", () => {
    let circuit = initialCircuit();
    for (let i = 0; i < 5; i += 1) {
    circuit = noteProviderResult(circuit, 1_000, false, 5);
    }
    assert.equal(circuit.state, "open");
    const blocked = allowCall(circuit, 1_000, 30_000);
    assert.equal(blocked.allow, false);
    const probe = allowCall(circuit, 31_000, 30_000);
    assert.equal(probe.reason, "probe");
    });

    The shed test passes a successful provider payload on purpose. degradeAi must ignore it when admission already shed. That is the bug where a route calls the model and then decides it was over cap.

    Architecture Diagram

    text
    CI
    |
    v
    ServiceProfile in git
    |
    v
    evaluateProductionReadiness
    |
    +--> ready: false --> pipeline red, no traffic
    +--> ready: true --> deploy
    |
    v
    replicas + /live + /ready
    |
    v
    player path AI path
    tenant SQL admit --> circuit --> provider
    Postgres degrade reason, body unchanged

    Component interaction on deploy:

    text
    Migration job applies schema
    |
    v
    New replica boots, migrations_applied is true
    |
    v
    /ready returns 200, balancer adds the replica
    |
    v
    Old replica /ready returns 503 while draining
    |
    v
    Old replica exits after in-flight deadlines

    Real-Time Enterprise Example

    In production the platform runs four API replicas with the reference profile. Northwind's Monday traffic hits all four. Lesson reads use the tenant predicate and return from Postgres. Draft traffic above 32 in-flight on a replica returns shed. When the provider fails five times on a replica, that replica's circuit opens and draft calls return circuit_open without waiting 12 seconds. The player SLO stays green. The AI dashboard shows shed rate and open circuits. On-call does not restart the fleet to "clear" the provider.

    A worker fleet consumes embedding jobs. Depth above 500 pages the worker, and readiness for that service goes red so autoscaling has a signal other than CPU. Poison jobs land in the dead-letter queue. Replay uses the same job id.

    Challenge: the provider is down, the queue is deep, and a deploy is in progress. Reads stay on healthy replicas. AI sheds or degrades. The new replica stays unready until migrations finish. The draining replica accepts no new AI work. You do not raise maxInFlight to 10_000 in the incident channel. You do not point Ready at the provider health endpoint. You do not drop tenant_id from the hot query to "make the index faster."

    Performance Optimization

    The fast path for a shed or an open circuit does no provider I/O and holds no pool connection. That is the latency win during an incident. Player reads stay on indexes that lead with tenant_id. A cache from Lesson 62 may serve a lesson only when the key includes the tenant. A stampede on a cold key is another admission problem: single-flight per tenant and key, then shed, rather than 32 replicas recomputing the same embedding.

    Retries are the expensive kind of "reliability." Two attempts inside 400 ms are enough for a blip. A user-visible draft should fail the deadline and let the person retry, or move to the queue if the product promised background completion. Do not hold the browser request open for a 2-minute embedding job.

    Pool size of 10 is a starting point for this profile because four replicas use 40 connections. Measure lock time and pool wait. If pool wait dominates, the next step is a shorter transaction, not a pool of 100. CPU on the API should stay modest because token generation happens at the provider. Scaling the API on CPU will not speed up a slow model. Scale workers on queue delay. Scale the API when shed rate climbs while CPU is idle, which means the cap or the event loop is the bottleneck.

    Keep JSON traces small: tenant id, route, reason, duration, in-flight count. Large prompt logs become both a cost and a privacy incident.

    Security

    • Authentication. Scale-out does not change who issues the session. Every replica validates the same cookie or token. A replica-local allow list is a bypass.
    • Authorization. Shed responses and model_unavailable still run after the authz check. An unauthenticated client does not learn whether the circuit is open for a private note. Return the same 401 you would return when the provider is healthy.
    • Tenant. tenant_predicate is a readiness check because load tests are when a missing WHERE becomes an incident. Cache keys include the tenant.
    • Idempotency. Duplicate worker delivery must not double-charge or double-send. The key is part of the write contract.
    • Secrets. secrets_external means the profile, the image, and the client bundle do not contain provider keys. Runtime reads them from the secret store into memory.
    • Traces. Redaction is a ship gate. Incident debug does not justify logging the handbook or the draft instruction by default.
    • OWASP. Unrestricted resource consumption is the AI failure mode. Admission, deadlines, queue caps, and cost ceilings are the controls. Broken access control is the tenant check you are tempted to drop under load.
    • Degrade honesty. A fallback must not call a second provider that the tenant did not allow. Lesson 23's allow-list still applies when the primary circuit is open.

    Common Mistakes

    1. Ready depends on the model provider. Symptom: a vendor 429 restarts every pod. Cause: the probe called the model. Fix: liveness is the process; readiness is schema, pool, and drain.
    2. Retries with a fresh idempotency key. Symptom: duplicate reminders after a worker crash. Cause: the catch block minted a new key. Fix: reuse the key and let the downstream dedupe.
    3. Unbounded Promise.all on the provider. Symptom: one request fans out into hundreds of calls. Cause: no maxInFlight. Fix: admit, and queue the rest.
    4. Pool size copied per replica without math. Symptom: too many connections after autoscaling. Cause: pool_headroom was not in CI. Fix: fail the profile when replicas * poolSize crosses the fraction.
    5. One SLO for the whole site. Symptom: the player pages during a model outage. Cause: AI 503s count as availability loss. Fix: split the SLOs and the burn alerts.
    6. Circuit state only inside the handler, not stored. Symptom: every call still hits the provider. Cause: allowCall's returned circuit was discarded. Fix: save the half-open probe flag before awaiting.
    7. Tight retry on 429. Symptom: the provider extends the ban. Cause: no jitter and no budget. Fix: retry.budgetMs and a shed when the circuit opens.
    8. Holding a database connection during the provider call. Symptom: pool wait while the model thinks. Cause: the transaction wrapped the HTTP client. Fix: read, commit, call, write a short second transaction.
    9. Shared cache key under load. Symptom: Contoso sees Northwind's lesson. Cause: the hot key omitted tenant_id. Fix: the tenant predicate applies to caches too.
    10. Raising the cap in the incident. Symptom: a longer outage and a bigger bill. Cause: shed was treated as a bug. Fix: shed is the control. Add replicas only if the event loop is saturated.
    11. DLQ disabled for "simplicity." Symptom: one poison embedding blocks the partition. Cause: the consumer retried forever. Fix: queue.deadLetter is mandatory when the queue is enabled.
    12. Logging the prompt to debug latency. Symptom: handbook text in the log vendor. Cause: trace redaction was a comment. Fix: trace_redaction fails CI, and the logger drops those fields.

    Best Practices

    1. Keep API replicas stateless.
    2. Put sessions in the cookie and the store, not in the process.
    3. Split player and AI SLOs.
    4. Page AI burn separately from player burn.
    5. Fail readiness until migrations match the code.
    6. Drain by failing readiness before exit.
    7. Keep liveness independent of the provider.
    8. Set a finite maxInFlight per process.
    9. Shed AI before you shed player reads.
    10. Put the provider deadline inside the request deadline.
    11. Retry idempotent reads inside a budget with jitter.
    12. Keep write idempotency keys stable across delivery.
    13. Open the circuit on a threshold and probe once.
    14. Store the circuit the function returns.
    15. Map provider failure to model_unavailable and leave stored bodies unchanged.
    16. Bound queues and require a dead-letter path.
    17. Size pools with replica count in the formula.
    18. Include the tenant in queries and cache keys.
    19. Keep secrets in the platform store.
    20. Redact prompts and document bodies in traces.
    21. Enforce a per-tenant cost ceiling.
    22. Run evaluateProductionReadiness in CI.
    23. Treat a red check as a failed deploy.
    24. Add checklist rows in code and tests, not only in a wiki.
    25. Do not switch to an unapproved provider when the circuit is open.

    Interview Questions & Answers

    Beginner

    1. What is the difference between liveness and readiness?
      Liveness answers "should the platform restart this process?" Readiness answers "should this process receive traffic?" A model outage must not fail liveness. A missing migration must fail readiness.

    2. Why shed instead of queueing every draft in the request handler?
      The request has a deadline and a database pool. A queue inside the handler still occupies the process. Admission returns 429 quickly. Work that can wait goes to the real queue from Lesson 61.

    3. Why are there two SLOs?
      Learners can read lessons when the model is down. If one SLO covers both, on-call treats a provider incident as a full outage and may restart healthy replicas.

    Intermediate

    1. How do you scale the API without duplicating sessions?
      Keep the process stateless. Validate a signed session on every replica. Store drafts and jobs in Postgres and the queue. Then the load balancer can use any Ready replica.

    2. What happens on the 33rd in-flight AI call when the cap is 32?
      admit returns shed. degradeAi returns reason shed even if a provider result is sitting in a variable. The route must not have called the provider.

    3. How does a circuit avoid a thundering herd when it closes?
      After openMs, one caller receives probe. probeInFlight blocks the rest until noteProviderResult closes or reopens the circuit.

    Senior

    1. How do you test this without a cloud account?
      Unit-test admit, allowCall, and evaluateProductionReadiness with the reference profile and with one field broken at a time. Assert ready === false and the check id. An integration test can boot the process with a fake provider that sleeps, and assert the handler returns before the sleep ends because the circuit is open.

    2. Where do idempotency and scale meet?
      More workers means more duplicate deliveries. The write key is stable, so the second delivery returns the original effect. A retry that changes the key turns scale-out into double sends.

    Architect

    1. How do you roll this out?
      Land the evaluator in CI first, with the reference profile matching today's true settings. If today's pool math is red, fix the pool before adding stricter gates. Then wire /live and /ready. Then turn on admission for the draft route. Watch ai_shed_total and player availability separately.

    2. What should the capstones change, and what should they leave alone?
      They may set a different name, queue depth, and in-flight cap. They leave tenantPredicate, secretsExternal, traceRedaction, idempotentWrites, and gracefulDegrade true. A project that needs a long job uses the queue. It does not raise the request timeout to five minutes.

    3. How do you handle a regional provider outage without dropping isolation?
      Open the circuit, serve reads, and refuse AI with a clear reason. A second region is useful for the API and Postgres if you already run them there. A second model vendor is allowed only when that vendor is on the tenant's provider allow-list. The tenant predicate stays on every path you fail over to.

    4. What failure do you refuse to "fix" by relaxing the checklist?
      You refuse to mark Ready on provider health, to share cache keys across tenants, to retry writes with a new idempotency key, and to disable the dead-letter queue so the consumer "keeps up." Those are the incidents the checklist names.

    Knowledge Check

    1. What problem does this capability solve?

    It makes scale-out and dependency failure explicit, so a provider 429 cannot take down the lesson player, and a deploy cannot receive traffic on an unfinished migration.

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

    A single process is enough for a local demo. A queue is the right place for embedding and eval. A request-path draft is acceptable inside the provider deadline with admission. A multi-region active-active database is a later step when the player SLO requires it. The checklist still applies in one region.

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

    The session is validated on every replica. Queries and caches carry the tenant. The provider sees only the payload for that request. Traces do not become a second copy of the handbook. Secrets stay out of the profile.

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

    Provider errors open the circuit and degrade AI. Pool exhaustion is prevented by headroom math and short transactions. Deep queues page the worker and dead-letter poison jobs. A failed migration keeps the new replica unready.

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

    Unit tests cover the reference profile, a broken timeout, shed-at-cap, and the fifth failure. A security test asserts cache keys include the tenant. A performance test asserts an open circuit returns without waiting for the provider deadline. A cost test asserts shed and circuit_open do not increment provider spend.

    Practical Exercise

    Implement packages/platform/src/readiness/ and run the tests. Add a case where replicas is 20 and poolSize is 10 with maxConnections of 100, and assert check pool_headroom fails. Write the on-call sentence you would put above the AI dashboard: what shed and circuit_open mean, and why the player can stay green.

    Deliverable and Rubric

    Submit the checklist table, the readiness package, the test output, the SLO split, and a short note on what you shed first.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • evaluateProductionReadiness is the ship gate.
    • The reference profile passes.
    • A single broken control fails ready.
    • Liveness ignores the provider.
    • Readiness includes migrations, pool headroom, and drain.
    • Admission sheds at a finite cap.
    • The circuit probes once.
    • Writes keep their idempotency keys.
    • Player and AI SLOs are separate.
    • Queues have a depth cap and a dead-letter path.
    • Traces and profiles contain no secrets and no document bodies.
    • Tenant predicates survive the hot path.

    Key Takeaways

    1. Scaling out works when the API is stateless.
    2. Resilience is shed, deadline, circuit, and degrade.
    3. Production readiness is readiness-v1 in CI.
    4. Liveness is the process. Readiness is "send traffic."
    5. The provider deadline sits inside the request deadline.
    6. The in-flight cap fails closed when it is missing.
    7. An open circuit is a successful protection.
    8. Half-open allows one probe.
    9. Idempotency keys survive retries and extra workers.
    10. Player availability and AI latency are different budgets.
    11. Pool math includes replica count.
    12. Queues need a max depth and a dead-letter path.
    13. Tenant predicates apply to SQL and to cache keys.
    14. Secrets stay in the secret store.
    15. Capstones may tune numbers and may not drop isolation, redaction, or degrade.

    Summary

    Lesson 63 closes the operations sequence of Module 6's opening and opens the capstone sequence. Observability, cost, queues, and caches are now a single gate the platform can fail in CI. TechLearningPro can add replicas for Monday's cohort, keep the lesson player up when the model provider is not, and refuse a deploy that would serve traffic on the wrong schema. The next three projects are product builds. Each one inherits this checklist instead of treating production as a paragraph at the end of the README.

    Next Lesson Preview

    Project 1: AI-Powered SaaS Workspace is the first capstone. You will build a multi-tenant workspace where editors request AI drafts and viewers cannot, where a cross-tenant note id does not leak, and where accept is idempotent. The readiness profile from this lesson is an exit gate for that project, not a sequel you might skip.

    Further Reading

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