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 58“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Cloud Deployment, Serverless and Managed Runtime Choices
TechLearningPro moved the API to a serverless function because the slide said scale-to-zero was cheaper.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 58 · Full-Stack Security, Testing and Deployment
Lesson Overview
TechLearningPro moved the API to a serverless function because the slide said scale-to-zero was cheaper. The lesson player is quiet at night, and the progress route is a short query. The tutor route is not. It streams tokens for several seconds. The platform cut the response at its maximum duration, the browser showed a half paragraph, and the function was billed for the work the learner never received. The same week, someone scheduled the golden-set live eval as a second function. The platform killed it at the job limit. Cold starts then added a pause to the first progress read of the morning, which had been fine on the container that stayed warm.
The image from the Docker lesson was not the mistake. The mistake was one runtime for every process. A serverless function runs a short invocation, scales toward zero, and stops at a hard timeout. A container service runs the image you already built, can hold a stream open, and costs money while it is warm. A managed data service runs PostgreSQL so you do not patch a database container on a laptop volume in production. A worker runs the eval batch off the request path. A CDN serves the player. None of these is "the cloud." The cloud is the decision to place each workload on the runtime whose limits match the work.
This lesson is that decision for the learning platform, written as a function and a manifest you can review. It does not open an account, create a key, or name a bill as if it were a quote. Vendor consoles change. The constraints do not: timeout, cold start, streaming, concurrency, secret injection, and what happens when the model is down.
/learn/ci-cd-automation is how a digest gets promoted. /learn/docker is how the image is built. This lesson chooses the place the digest is allowed to run. Module 6 starts with observability, because a runtime you cannot measure will hide the timeout that caused this incident.
Planning assumptions:
The player is static assets. The progress API is a short request. The tutor API streams and must survive longer than a default function timeout. The eval batch is a scheduled worker. Postgres is managed and not reachable from the public internet.
Illustrative limits used in the selector: functions may run at most 15 seconds in this design, container requests at most 30 seconds, workers at most 900 seconds. Those are policy numbers for the lab, not a vendor's current maximum. Read the platform page before you treat them as a quota.
Minimum warm API instances in production: 2, so one restart does not drop in-flight tutor streams. Scale-to-zero remains correct for the preview environment.
No account ids, access keys, or connection passwords appear in the manifest. The database is a private hostname the platform injects.
Learning Objectives
By the end of this lesson you will be able to:
Name the runtime classes this product uses: CDN, serverless function, container service, worker, and managed Postgres.
Match a workload to a runtime using timeout, streaming, startup, and state, not fashion.
Explain why the tutor stream and the eval batch were the wrong fit for a short function.
Keep scale-to-zero for preview environments and a warm minimum for the production API.
Place the provider credential in a runtime secret, injected into the API process, never into the static player.
Keep Postgres on a private network. The browser and the CDN do not open database connections.
Return the typed tutor fallback when the function or the container hits its timeout, without failing the lesson page.
Run the eval batch as a worker with an idempotency key so a retry does not double-spend the case budget.
Write a provider-neutral manifest that records the choice and the digest.
Refuse a design that puts the model call in the browser to "avoid the timeout."
State the cost shape of each runtime: per request, per warm hour, per token, per stored byte.
Hand Module 6 a list of signals: cold starts, stream truncations, worker kills, token spend, and error codes.
You can read TypeScript and YAML. You do not need a cloud login.
Detailed Core Concepts
What a runtime choice is
A runtime is the platform contract around your process: how it starts, how long it may run, how it receives a secret, how it reaches the database, and how you pay. "Deploy to the cloud" skips that contract. TechLearningPro already has a process. The remaining question is which contract each process signs.
Runtime
Fits
Breaks when
CDN / object storage
Hashed static player assets
You hide a provider key in the bundle
Serverless function
Short, stateless, spiky reads and writes
The work streams, exceeds the timeout, or needs a warm local cache of secrets
Container service
Long-lived API, streaming, a minimum warm count
You wanted scale-to-zero and will not pay for idle
Worker
Scheduled or queued batches
You needed a user to wait on the HTTP response
Managed Postgres
System of record, backups, private network
You treat it as a place to store prompts forever
Managed container platforms (the kind that run your image without you operating a cluster) are still the container row. A cluster you operate yourself is a later specialty. This product does not need one to ship the tutor.
Timeout, cold start, and streaming
A function invocation has a ceiling. When the ceiling hits, the platform stops the process. A tutor stream that is allowed 8 seconds of model time plus overhead can live inside a 30-second container request. It does not fit a 15-second function policy if the model is slow, because you would rather return timeout from your own code than be killed mid-byte. Your code can set the typed fallback. The platform kill looks like a broken connection.
Cold start is the time to boot a new instance. Progress reads are cacheable and short, so a cold start is a pause. Tutor streams are worse: the learner is watching. Production keeps two API instances warm. Preview environments scale to zero so a weekend branch does not bill a warm container. That split is the point of having two environments rather than one "serverless" switch.
The eval batch is not a request
A golden-set run over a live provider is a batch. It has a case cap, a spend cap, and a runtime measured in minutes. Putting it on the API's request path couples a release check to a learner click, or couples it to a function that will be killed. The worker pulls the same digest's eval package, reads the provider credential from the secret store, writes a report, and exits. If the platform kills the worker, the run resumes from the last completed case id. It does not start the spend over from case zero.
Identity of what you deployed
The manifest records a digest, the same way CI recorded a digest. "The API service" is not a version. sha256: plus 64 hex characters is a version. Rollback is deploying the previous digest, not asking the platform to undo a mutable tag. Serverless functions have the same duty: publish an immutable version id and point an alias at it only after the eval gate has passed.
Data and trust
Path
Crosses
Browser to CDN
Public assets only
Browser to API
Session cookie, no provider key
API to Postgres
Private network, credential from the secret store
API to model provider
Server egress, credential from the secret store, authorized excerpt only
Worker to provider
Same credential class, no learner session, synthetic or public cases only
Function timeout
Your process should already have returned a typed error
The static player and the API do not share an origin's secrets. A build-time public variable that contains a key will be on the CDN. The boot check from the Docker lesson still rejects tlp_live_ inside the API. The CDN has no business reading that variable at all.
Architecture and Request Flow
flowchart TB
subgraph edge [Edge]
Browser[Browser]
CDN[CDN player assets]
end
subgraph run [Application runtimes]
API[Container API warm min 2]
Worker[Eval worker]
end
subgraph data [Managed data]
DB[(Private Postgres)]
Secrets[Secret store]
end
subgraph model [Provider]
LLM[Model API]
end
Browser --> CDN
Browser -->|session, short timeout| API
API --> DB
API --> Secrets
API -->|stream with deadline| LLM
Worker --> Secrets
Worker -->|capped batch| LLM
Worker --> DB
text
Learner opens a lesson
-> CDN serves the player
-> player calls the API with the session
-> progress read on Postgres (short)
-> tutor stream on the container
-> deadline exceeded: typed timeout, lesson stays
-> provider down: typed unavailable, lesson stays
Eval schedule
-> worker loads digest's cases
-> stops at case cap or spend cap
-> writes a report row
-> retry continues after the last case id
Failure point to name in review: a private database with a public API is fine. A public database with a trusted container is not. Network placement is part of the runtime choice.
Step-by-step Implementation
Package: packages/runtime/. Manifest: deploy/prod/services.yaml. No cloud SDK. The selector is pure so a test can run it without credentials.
reason:"short stateless read or write, scale to zero",
};
default:{
const neverKind:never= workload.kind;
thrownewError(`unknown workload ${neverKind}`);
}
}
}
The progress API may be serverless. The tutor stream may not. Sharing one container service for both is a reasonable later simplification. The selector keeps them separate so the timeout policy stays visible. Collapsing them is a comment in the manifest, not a silent default.
The worker stores nextCaseIndex after a case is recorded, using runId as the idempotency key for that case. A kill at case 7 resumes at 7 only if case 7 did not commit. If it committed, the cursor is already 8. The function does not know the provider. It knows the budget.
Step 4: Manifest
deploy/prod/services.yaml
yaml
# Provider-neutral placement. Digests come from CI.
# Secret values are not in this file. Names are references.
# Injected at start. The value is not written here.
secretRefs:
-name: TUTOR_PROVIDER_KEY
store: platform-secret-store
evalWorker:
runtime: worker
timeoutSeconds:900
schedule:"15 6 * * 1-5"
public:false
maxCases:20
secretRefs:
-name: TUTOR_PROVIDER_KEY
store: platform-secret-store
database:
runtime: managed-postgres
public:false
backups:true
The digest in the lab file is 64 hex characters so it matches the CI check's shape. It is not a real image. Replace it with the verify job's output. secretRefs name the store entry. They are safe to commit because they are not the secret.
Preview overrides tutorApi.minInstances to 0 in deploy/preview/services.yaml, and sets tutor mode to fixture so preview does not need the provider key at all. Production is the only place the secret reference is required.
There is no cloud resource to delete. If you later apply the manifest with a vendor CLI, the cleanup is that CLI's delete command for the preview environment the same day. The lab itself creates nothing.
Security
Authentication stays on the API. The CDN does not know learners. The player bundle is public course chrome.
Authorization is unchanged by the runtime. A serverless function that forgets the tenant filter is the same bug as a container that forgets it, and it scales faster.
Least privilege. The tutor API identity can read TUTOR_PROVIDER_KEY and connect to Postgres as the application role. The worker can read the same key and write eval reports. It cannot alter lesson_progress. The CDN identity can read the asset bucket and nothing else.
Input validation. The selector is exhaustive on kind. The worker stops at caps before it calls a provider. Request bodies still go through the API validation from earlier lessons.
Secrets. References in YAML, values in the store, injection at process start. Build logs for the static web job must not print environment variables. Preview uses fixture mode so it does not need the key.
Tenant isolation. The worker's cases are the public golden set. A production incident replay that needs a real excerpt belongs in an access-controlled store, not in the worker image.
Network.database.public is false. The API reaches it on the platform private network. Opening Postgres for a migration laptop is how the database becomes a public runtime.
Prompt injection remains an application problem. A longer timeout does not make model text a completion fact. The worker does not apply prompt changes to production. It writes a report a human reads, which is the CI lesson's rule.
Error Handling
Event
Learner or operator sees
System does
Tutor deadline inside the container
Lesson content, tutor timeout
One user retry at most. No platform retry of a stream
Platform kill because the function ceiling was too low
A truncated body, which is a design bug
Move the route to the container. Do not raise the ceiling until the selector agrees
Provider 429 or 5xx
Tutor unavailable
Alert on rate. Do not fail the progress route
Worker killed mid-batch
No learner impact
Resume from cursor. Do not reset spentUnits
Spend cap
Report status spend_cap
Stop. A human raises the cap in policy, not by looping
Cold start on preview
A slower first request
Accepted. Production min instances stay 2
Deploy of the wrong digest
The manifest diff shows it
Rollback is the previous digest
Do not let the platform retry a non-idempotent tutor invocation. A retry can double-bill tokens and produce a different draft. Progress writes retry with the idempotency key you already use for completion. Those policies differ because the side effects differ.
Testing
packages/runtime/src/select.test.ts
typescript
import assert from"node:assert/strict";
import test from"node:test";
import{ selectRuntime }from"./select.js";
test("places the tutor stream on a warm container in production",()=>{
const choice =selectRuntime({
kind:"tutor_stream",
streams:true,
expectedRuntimeMs:8_000,
preview:false,
});
assert.equal(choice.runtime,"container");
assert.equal(choice.minInstances,2);
assert.ok(choice.timeoutMs >8_000);
});
test("scales the tutor to zero only in preview",()=>{
const choice =selectRuntime({
kind:"tutor_stream",
streams:true,
expectedRuntimeMs:8_000,
preview:true,
});
assert.equal(choice.minInstances,0);
assert.equal(choice.runtime,"container");
});
test("keeps a short progress call on serverless",()=>{
const choice =selectRuntime({
kind:"progress_api",
streams:false,
expectedRuntimeMs:400,
preview:false,
});
assert.equal(choice.runtime,"serverless");
assert.equal(choice.minInstances,0);
});
test("never gives the database a public ingress",()=>{
const choice =selectRuntime({
kind:"database",
streams:false,
expectedRuntimeMs:0,
preview:false,
});
assert.equal(choice.runtime,"managed_postgres");
assert.equal(choice.publicIngress,false);
});
packages/runtime/src/batch.test.ts
typescript
import assert from"node:assert/strict";
import test from"node:test";
import{ nextBatchStep }from"./batch.js";
const policy ={ maxCases:20, maxUnits:50};
test("resumes at the cursor instead of case zero",()=>{
Add a test that eval_batch selects worker with publicIngress false, and a test that a progress workload over 15 seconds selects container. Those two lock the incident so a refactor cannot put the batch back on a function.
Performance and Cost
Each runtime sends a different bill. Choosing serverless for the tutor to save idle cost moved the cost into truncated requests and retries, which is more expensive and worse for learners.
CDN: you pay for transfer and requests. Cache hashed assets. Do not cache personalized tutor drafts on the CDN. A shared cache key of lesson id alone leaks across learners.
Serverless progress API: you pay per invocation and per cold start. Short queries fit. A connection storm to Postgres does not. Use the platform's pooled connection or a small pooler, and cap concurrency.
Container API: you pay for warm instances. Two small instances are the production floor. Autoscale on CPU and in-flight streams, with a ceiling so a traffic spike cannot multiply the token bill through unlimited tutor concurrency.
Worker: you pay for the minutes it runs and for tokens. The caps are the cost control. A retry from case zero is the bug that doubles them.
Postgres: you pay for storage, IOPS, and backups. Tutor text does not belong in the hot progress table. If you store drafts, set a retention limit.
Egress to the model provider is a separate line. Streaming does not make tokens free. The output cap from the architecture lesson still applies inside the container timeout.
Illustrative ratio, not a quote: idle container cost is hours times instance size. Function cost is invocations times duration. Token cost tracks tutor opens and worker cases. Put the three on one review page before you call the serverless move a savings.
Knowledge Check
1. What problem does the runtime choice solve?
It keeps each TechLearningPro workload inside a platform contract it can finish: static files on a CDN, short progress calls on a function, tutor streams on a warm container, eval batches on a worker, and facts in private managed Postgres.
2. What alternatives exist, and when would you choose each?
One container for progress and tutor fits when you want a single service and will pay for warmth. Split them when the progress route should scale to zero and the tutor should not. A function for the tutor fits only if the vendor timeout, streaming support, and cold start meet the product deadline, which this lab's 15-second policy does not. A self-operated cluster fits a platform team with a reason. It is not required to ship this API.
3. Which data, identity, and trust boundaries matter?
The browser receives assets and API responses, never the provider key. The API and the worker receive the key from the secret store at runtime. Postgres has no public ingress. The worker cannot write completion. Preview runs the fixture and does not mount the production secret.
4. What can fail, and how should the system respond?
A tutor deadline returns timeout and the lesson stays. A provider failure returns unavailable and does not fail progress. A worker kill resumes from the cursor and keeps the spend already recorded. A bad digest is rolled back by deploying the previous digest. A public database flag is a release blocker.
5. How would you test quality, security, performance, and cost?
Unit tests cover placement, preview scale-to-zero, private Postgres, and batch resume. Security review checks secret references versus values, and the worker's database role. Performance review checks the timeout against the stream budget and the warm minimum. Cost review checks instance floor, case cap, and spend cap before any live provider is attached.
Hands-on Assignment
Lab note. Do not create a cloud account for this assignment. The manifest uses a placeholder digest and secret names.
Problem. Place TechLearningPro's five workloads and show the worker will not restart a batch at case zero.
Tasks.
Draw the diagram with a public edge and a private database.
Implement selectRuntime and nextBatchStep with the tests in this lesson, plus the two extra tests named above.
Add deploy/prod/services.yaml and a preview override that sets tutor minInstances to 0 and fixture mode.
Write six controls: digest pinned, database private, secret reference only, worker role cannot write progress, preview has no provider key, tutor timeout above the stream budget.
State the learner-visible behavior for tutor timeout, provider down, and a cold preview instance.
List the five meters Module 6 should graph first.
Deliverable. Diagram, source with no secrets, test output, the control table, and a trade-off note on one combined container versus split function-and-container.
Challenge. A launch week multiplies tutor traffic by ten, and the provider enforces a per-minute token cap. Explain what you change in minInstances, the API concurrency ceiling, and the user-visible fallback. The database stays on the private network. A queue for the tutor is allowed only if the player can show "still writing" without holding a function open past its deadline.
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
Putting the stream on a short function. Symptom: truncated tutor text and a generic platform error. Cause: one runtime chosen for the whole API. Fix: container with a deadline your code handles.
Running the eval batch inside a request. Symptom: the job dies at the platform limit and learners time out if it shares the API. Cause: the schedule was implemented as another route. Fix: worker plus cursor.
Scale-to-zero on the production tutor. Symptom: morning cold starts and dropped streams. Cause: the preview setting was copied to production. Fix: minInstances: 2 in prod only.
Baking the provider key into the web build. Symptom: the key is on the CDN. Cause: a public env prefix. Fix: server secret store. Rotate the key. Rebuild assets without it.
Public Postgres. Symptom: scans and a data incident. Cause: a laptop needed a migration path. Fix: private network and a one-off task identity, then close the path.
Retrying streams automatically. Symptom: double token spend and two different drafts. Cause: the platform retry policy matched the progress route. Fix: no automatic retry on the tutor. Idempotency keys on progress writes.
Restarting a killed batch at case zero. Symptom: the spend cap is hit twice. Cause: the cursor was not durable. Fix: commit the case result and the next index together.
Deploying a moving tag. Symptom: production is not the digest CI evaluated. Cause: the manifest said latest. Fix: the sha256 digest from the pipeline.
Caching personalized tutor output on the CDN. Symptom: learner B sees learner A's explanation. Cause: the cache key was the lesson URL. Fix: the CDN caches assets only. Personalized drafts stay on the API.
Raising every timeout to the vendor maximum. Symptom: a stuck call holds concurrency and money. Cause: timeouts used as hope. Fix: set the deadline from the product budget, and return a typed fallback when it fires.
Summary
Cloud deployment is a placement decision. TechLearningPro's player sits on a CDN, short progress calls may sit on a function, the tutor stream sits on a container with a warm production floor, the eval batch sits on a worker that can resume, and PostgreSQL sits on a private managed service. The image and the digest come from the previous two lessons. The provider key is a secret reference, injected only where the server runs. Preview does not get that key. Module 6 measures whether those choices hold.
Next Lesson Preview
Observability for Full-Stack and LLM Applications opens Module 6. You will trace a learner click across the CDN, the API, Postgres, and the model call, and you will see cold starts, truncated streams, token spend, and worker cursors as signals instead of as surprises in a bill.
Further Reading
/learn/docker for the image the container runtime pulls.
Your cloud vendor's current pages for function timeout, container services, and managed Postgres. The ceilings in selectRuntime are lab policy. The vendor page is the quota.
Ready to mark this lesson complete?Track your journey across the entire course.