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

    Backend Engineering with Node.js

    On the Tuesday of TechLearningPro's enrollment week, the lesson player stayed fast and the Monday completion board stayed quiet.

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

    AI-Powered Full Stack Development · Lesson 09 · Full-Stack Engineering Foundations

    Lesson Overview

    On the Tuesday of TechLearningPro's enrollment week, the lesson player stayed fast and the Monday completion board stayed quiet. The enrollment API did not. A route that had started as a convenience handler inside the Next.js app was now concatenating SQL, trusting a role string from the browser, and holding database connections open while it waited on a slow progress recount. When the recount stalled, the Node process kept accepting new requests until the pool was exhausted and every checkout returned 500. The UI team could not tell whether the failure was a render bug, a database lock, or a process that had stopped making progress. Leadership asked for a backend they could operate: a clear trust boundary, a timeout on every outbound call, and a query path that cannot be rewritten by user input.

    That boundary is this lesson. Backend engineering with Node.js is the practice of running an HTTP service on Node's event loop so that I/O-bound product work—reading enrollments, writing lesson progress, calling an identity provider—stays concurrent without giving each request its own operating-system thread. The service owns validation, authorization, parameterized SQL, structured logs, and shutdown. The browser and the Next.js UI remain clients of that service. Later AI features will call model providers from this same process model; those calls are slower and less predictable than a primary-key read, so the timeouts, cancellation, and pool limits you set here are the controls those features inherit.

    The running system is the TechLearningPro Learning Platform: learner enrollment, lesson progress, and the APIs that the player and the instructor console call. This lesson uses Fastify on Node.js with the pg driver and PostgreSQL. The same boundaries apply if your team standardizes on Express: a router, a schema validator, a pool, and handlers that never build SQL by string concatenation. Framework syntax is a detail. The trust boundary is the lesson.

    Planning assumptions, labeled so they are not mistaken for a capacity study:

    • Enrollment week multiplies writes; a quiet Wednesday does not. The API must shed load with explicit limits rather than unbounded queues inside one process.
    • Progress reads are interactive. A recount job may be slower and must not hold the request pool hostage.
    • Database credentials live in a local, uncommitted environment or a secret store. This lesson never prints a password, token, or connection string that contains a secret.
    • Illustrative pool sizes and timeouts are design examples. Measure them against your PostgreSQL max_connections and your process count before you copy them into production.

    Module 1 ends with the data model in lesson 11. Lesson 10 turns the handlers you write here into a versioned HTTP contract. Module 2 starts at Generative AI, LLMs and Transformer Fundamentals, where the same backend will call a model without letting that call rewrite authorization.

    Learning Objectives

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

    1. Explain why Node.js fits I/O-bound HTTP APIs and where the single JavaScript thread stops being enough.
    2. Trace a request from socket accept through routing, validation, authorization, a parameterized query, and the response.
    3. Separate the event loop, the libuv thread pool, worker threads, and multiple Node processes, and place each on a TechLearningPro workload.
    4. Choose Fastify or Express as a thin HTTP boundary and keep business rules out of framework plugins that every route accidentally inherits.
    5. Configure a PostgreSQL pool with timeouts, a bounded size, and credentials loaded from the environment.
    6. Write queries with bound parameters so enrollment and progress filters cannot become SQL injection.
    7. Enforce authorization on the server from a verified identity, including row filters that a client cannot widen.
    8. Add structured logs, request identifiers, and graceful shutdown so deploys do not cut off in-flight progress writes.
    9. Distinguish deterministic backend behavior from later probabilistic model calls, and reserve timeouts for both.
    10. Identify failure modes: pool exhaustion, event-loop blocking, missing await, and handlers that trust client-supplied roles.
    11. Sketch tests for the success path, an authorization failure, and a database timeout.
    12. Hand lesson 10 an API surface that can be described in OpenAPI without rewriting the security model.

    Prerequisites

    If your current "backend" is a Server Action that interpolates request fields into SQL, stay here until that path is gone.

    Detailed Core Concepts

    What the Node backend is for

    A backend exists so that product rules have one enforceable place. TechLearningPro's rule "a learner may read only their enrollment" cannot live only in a React condition. The browser is a hostile, or at least untrusted, environment: extensions, replayed requests, and curious learners will call the API directly. Node is the process that accepts those calls, checks identity, talks to PostgreSQL, and returns a small JSON document.

    Node.js combines the V8 JavaScript engine with libuv, which performs non-blocking network and filesystem operations and notifies JavaScript when they complete. Your handler starts a query and yields. Other requests run while PostgreSQL works. That is the reason Node became a default for HTTP APIs that spend their time waiting. It is a poor default for long CPU-bound loops on the same thread that must also accept connections. A progress percentile computed in a tight loop on the request thread will stall health checks. Move that work to a job, a SQL aggregate, or a worker thread, and keep the request thread scheduling I/O.

    Event loop, thread pool, and processes

    JavaScript in one Node process runs your code on a single call stack. The event loop schedules timers, I/O callbacks, and promise reactions. Blocking that stack blocks every request in the process. await pool.query(...) does not block the stack while PostgreSQL runs; the query is off-thread from JavaScript's point of view. JSON.parse on a multi-megabyte body, a synchronous bcrypt with an excessive cost on the request path, or a large for loop over every learner does block it.

    libuv maintains a small thread pool (the UV_THREADPOOL_SIZE environment variable, default 4) for certain operations such as some filesystem and DNS work. It is not a general-purpose worker farm for your business logic. Worker threads run JavaScript in parallel on additional threads and communicate by message. They help with CPU work that must stay in-process. Multiple processes—several containers, or Node's cluster module—are how you use more than one CPU for the HTTP tier. Each process has its own pool of database connections. If you run eight processes with a pool of 10, you open up to 80 server connections before background jobs are counted. Size the pool from the database's max_connections, not from a tutorial constant.

    Fastify, Express, and the shape of a handler

    Fastify is the framework used in this lesson's code. It gives you a router, JSON schema validation, encapsulation through plugins, and a logger. Express gives you middleware ordered by app.use and a large ecosystem. Either can host a safe API. Neither will invent authorization or stop you from concatenating SQL.

    A handler should do five things in order:

    1. Parse and validate input against a schema (path, query, headers, body).
    2. Resolve the caller from a verified session or token. Ignore role fields that arrived in the JSON body.
    3. Decide whether this caller may perform this action on this resource (authorization).
    4. Run parameterized SQL or call another service with a timeout.
    5. Map the outcome to a status code and a stable error body.

    Plugins may add a request id, authenticate a session, or attach a database client. They should not query "whatever the user asked for" on behalf of every route.

    Configuration without secrets in git

    Process environment is the contract. DATABASE_URL points at PostgreSQL. SESSION_SECRET or a public-key set verifies cookies or tokens. Names belong in documentation. Values belong in a developer .env that is gitignored, or in a secret manager in deployed environments. Log the presence of a variable during boot if you must; never log the value. A sample file may contain DATABASE_URL=postgres://app_rw@localhost:5432/techlearningpro_dev with no password, plus a comment that the password is supplied locally.

    Validate configuration at startup. A missing DATABASE_URL should crash the process before it listens. Discovering the miss on the first learner request turns a deploy bug into an incident.

    Deterministic core, probabilistic neighbors

    Enrollment status is deterministic: the same authorized read returns the stored row. A later model call that summarizes a lesson is probabilistic: temperature, provider outages, and token limits change the outcome. Keep those paths separate. The Node service may invoke a model through a narrow client with a timeout, an idempotency key, and a schema for the model's JSON. It must not let the model choose the SQL, the learner id, or the authorization decision. This lesson builds the deterministic core. Module 2 and the security lessons add the model client and the prompt-injection boundary.

    Timeouts, cancellation, and backpressure

    Every wait needs a deadline. PostgreSQL should enforce statement_timeout for the application role. The HTTP server should stop reading oversized bodies. Upstream HTTP calls should use AbortSignal.timeout. When the pool is busy, fail the request with 503 and a Retry-After hint rather than queueing without bound inside the process. Unbounded in-memory queues hide overload until memory or latency collapses.

    Idempotency matters for enrollment writes. A client retry after a timeout must not create two enrollments. A unique constraint on (learner_id, course_id) is the database's enforcement; the handler translates a unique violation into a stable response. Lesson 11 owns the constraint design. This lesson owns the handler that expects the constraint to exist.

    Architecture and Design Diagrams

    The first diagram places the Node API between the UI and PostgreSQL and shows the identity check before any query.

    flowchart TB
      subgraph clients [Untrusted clients]
        Browser[Browser lesson player]
        Next[Next.js UI]
      end
    
      subgraph edge [Edge]
        Proxy[TLS terminating proxy]
      end
    
      subgraph nodeproc [Node.js process]
        HTTP[Fastify router]
        Authn[Session verification]
        Authz[Authorization]
        Handler[Enrollment handler]
        Pool[pg Pool]
      end
    
      subgraph data [Data and identity]
        IdP[Identity provider]
        DB[(PostgreSQL)]
      end
    
      Browser --> Next
      Next --> Proxy
      Proxy --> HTTP
      HTTP --> Authn
      Authn --> IdP
      Authn --> Authz
      Authz --> Handler
      Handler --> Pool
      Pool --> DB

    The second diagram is the failure path that caused enrollment week to page the team: work that holds a connection while doing something slow.

    sequenceDiagram
      participant C as Client
      participant N as Node handler
      participant P as Pool
      participant Q as PostgreSQL
    
      C->>N: POST /api/enrollments
      N->>P: checkout connection
      P->>Q: INSERT enrollment
      Q-->>N: row
      N->>N: synchronous recount of all lessons
      Note over P,Q: Connection still checked out
      C->>N: more requests arrive
      N--xP: pool exhausted
      N-->>C: 500 after clients time out

    Request flow in text:

    text
    socket accept
    -> body limit and schema validation
    -> verify session (fail closed: 401)
    -> authorize action on this learner and course (fail closed: 403)
    -> parameterized SQL with statement timeout
    -> map rows to a DTO (no internal columns)
    -> access log with request id, status, duration
    -> release connection to the pool

    Trust boundaries: the browser and any header it can set are untrusted. The proxy may set a forwarded-for header; trust it only when trustProxy matches your real topology. PostgreSQL is trusted to enforce constraints, not to know which human clicked the button. The Node process is the policy enforcement point for application authorization.

    Technical Explanation

    From packet to handler

    Node's HTTP parser assembles headers and the body up to the configured limit. Fastify matches the route, runs schema validation, and invokes encapsulated hooks. A validation failure is 400 with a body that names the field and a stable code. It does not echo the entire payload back, and it does not include a stack trace.

    Authentication answers "who is calling?" A session cookie or bearer token is verified with a secret or public key that the server holds. The result is a caller object: learnerId, organizationId, and roles issued by your identity system. Authorization answers "may this caller do this?" For GET /api/enrollments/:id, the query filters by both the path id and caller.learnerId, unless the caller holds an instructor scope that the server checks against organization membership. A request that omits the filter and then checks row.learnerId in JavaScript after the fetch is already too late if the query returned another tenant's row into logs or a cache.

    Parameterized SQL

    The pg driver sends the SQL text and the parameter values separately. PostgreSQL binds $1, $2, and so on. The values are data even when they contain quotes, semicolons, or comment markers. This is the injection control for the query path.

    sql
    SELECT id, course_slug, status
    FROM enrollments
    WHERE id = $1
    AND learner_id = $2

    Building WHERE id = '${id}' lets a caller close the quote and append SQL. ORMs do not save you if one route drops to a raw string. Lesson 11 and /learn/postgresql go further on least-privilege roles; the driver habit starts here.

    Pool behavior

    pg.Pool creates connections up to max, checks one out per query (or per transaction if you use a client), and returns it on completion or failure. A leaked client—connect() without release() in a finally—shrinks the pool permanently until restart. Prefer pool.query for single statements. For a transaction, connect, BEGIN, work, COMMIT or ROLLBACK, and release in finally.

    Set connectionTimeoutMillis so a saturated database fails the checkout quickly. Set statement_timeout on the database role so a runaway query is cancelled server-side even if the Node caller has a bug. Idle connections should die before a load balancer or firewall silently drops them; idleTimeoutMillis plus PostgreSQL tcp_keepalives cover that class of "first query after lunch fails."

    Shutdown

    On SIGTERM, stop accepting new connections, finish in-flight requests up to a deadline, close the Fastify server, then pool.end(). Kubernetes and most process managers send SIGTERM before SIGKILL. A process that ignores SIGTERM loses progress writes during every deploy. Log the shutdown reason at info, not as an unhandled rejection.

    Observability you can debug from

    Each request gets an id, propagated as a response header and a log field. Logs are JSON: timestamp, level, request id, route template (not a raw URL full of secrets), status, duration, and caller id. Do not log enrollment notes, tokens, or SQL parameter values that may contain personal data. Metrics that matter on day one: request duration by route, pool waiting count, pool size, and error rate by status class. Traces can wait until Observability for Full-Stack and LLM Applications. The fields you emit now are what those traces will join.

    Practical Implementation or Design Walkthrough

    Files in this walkthrough:

    • src/server.ts — process entry, config check, shutdown
    • src/db.ts — pool
    • src/routes/enrollments.ts — one read route
    • test/enrollments.test.ts — authorization and injection-shaped input

    Install current versions when you implement. Names used here are fastify, pg, and Node's built-in test runner. Confirm APIs in the library docs at implementation time.

    Simple example: a process that fails closed on config

    ts
    // src/server.ts
    import Fastify from "fastify";
    import { pool } from "./db.js";
    function requiredEnv(name: string): string {
    const value = process.env[name];
    if (!value) {
    // Crash at boot. A listening process with a missing DSN fails on the first learner.
    throw new Error(`Missing required environment variable: ${name}`);
    }
    return value;
    }
    requiredEnv("DATABASE_URL");
    export const app = Fastify({
    logger: true,
    trustProxy: process.env.TRUST_PROXY === "true",
    bodyLimit: 64 * 1024,
    });
    app.get("/health", async () => ({ status: "ok" }));
    const shutdown = async (signal: string) => {
    app.log.info({ signal }, "shutting down");
    await app.close();
    await pool.end();
    };
    process.on("SIGTERM", () => {
    shutdown("SIGTERM").catch((err) => {
    app.log.error(err);
    process.exit(1);
    });
    });

    /health tells the process manager the event loop can respond. It does not prove PostgreSQL is reachable. A readiness route may run SELECT 1 with a short timeout; keep liveness cheap so a database blip does not restart every replica at once.

    Intermediate example: authorized read with bound parameters

    ts
    // src/db.ts
    import pg from "pg";
    const { Pool } = pg;
    export const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 10,
    connectionTimeoutMillis: 2_000,
    idleTimeoutMillis: 10_000,
    statement_timeout: 3_000,
    });
    ts
    // src/routes/enrollments.ts
    import type { FastifyInstance } from "fastify";
    import { pool } from "../db.js";
    type Caller = { learnerId: string; role: "learner" | "instructor" };
    // Production replaces this stub with verified session claims.
    // A header the browser can set is not an identity.
    export function callerFromRequest(headers: Record<string, unknown>): Caller | null {
    const id = headers["x-test-learner-id"];
    if (typeof id !== "string" || id.length === 0) return null;
    return { learnerId: id, role: "learner" };
    }
    export async function registerEnrollmentRoutes(app: FastifyInstance) {
    app.get<{ Params: { enrollmentId: string } }>(
    "/api/enrollments/:enrollmentId",
    async (request, reply) => {
    const caller = callerFromRequest(request.headers);
    if (!caller) {
    return reply.code(401).send({ code: "unauthenticated" });
    }
    const { rows } = await pool.query(
    `SELECT id, course_slug, status
    FROM enrollments
    WHERE id = $1
    AND learner_id = $2`,
    [request.params.enrollmentId, caller.learnerId],
    );
    if (rows.length === 0) {
    // Same 404 for missing and for not-yours avoids confirming another learner's id.
    return reply.code(404).send({ code: "not_found" });
    }
    return rows[0];
    },
    );
    }

    The test learner header exists so local tests can pass an identity without standing up an identity provider. A comment in the module says it is a stub. The production build reads the verified session and rejects that header. Shipping the stub behind a real hostname is a broken access-control bug (OWASP API1:2023, broken object level authorization).

    Enterprise example: transaction, unique violation, and a test for hostile input

    ts
    // src/routes/create-enrollment.ts
    import type pg from "pg";
    type CreateInput = { learnerId: string; courseSlug: string };
    export async function createEnrollment(client: pg.PoolClient, input: CreateInput) {
    try {
    const { rows } = await client.query(
    `INSERT INTO enrollments (learner_id, course_slug, status)
    VALUES ($1, $2, 'active')
    RETURNING id, course_slug, status`,
    [input.learnerId, input.courseSlug],
    );
    return { ok: true as const, enrollment: rows[0] };
    } catch (err) {
    // 23505 is unique_violation. The constraint is the idempotency backstop.
    if (typeof err === "object" && err && "code" in err && err.code === "23505") {
    return { ok: false as const, code: "already_enrolled" as const };
    }
    throw err;
    }
    }
    ts
    // test/enrollments.test.ts
    import assert from "node:assert/strict";
    import test from "node:test";
    test("hostile id is a parameter, not SQL", () => {
    const hostile = "00000000-0000-4000-8000-000000000000' OR '1'='1";
    const text = "SELECT id FROM enrollments WHERE id = $1 AND learner_id = $2";
    const values = [hostile, "learner-1"];
    assert.equal(text.includes(hostile), false);
    assert.equal(values[0], hostile);
    });

    That unit test does not prove the driver is safe; it locks the team habit that values stay in the array. An integration test against a disposable database should send the same string and assert that the result is either a 400 (uuid schema rejected it) or a 404 (no row), never a list of every enrollment.

    Schema validation belongs in front of the query. A UUID parameter that fails the schema never reaches PostgreSQL. Validation is not a substitute for parameters: a free-text search box is still data and still goes in $1 inside ILIKE or, better, a dedicated search API with a bound pattern.

    Run locally:

    bash
    # DATABASE_URL comes from an uncommitted env file. Do not echo it.
    npm run dev
    curl -sS -D - http://127.0.0.1:3001/health
    curl -sS -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3001/api/enrollments/1

    The unauthenticated call must return 401. Cleanup is pool.end() on shutdown; for tests, use a transaction you roll back or a database you drop. Do not point tests at a shared production instance.

    Enterprise Real-World Scenarios

    Scenario A: Enrollment week pool exhaustion

    TechLearningPro's recount ran inside the request after the insert, on the same checked-out client. Latency climbed, then every route failed.

    What good looks like. The request inserts one row and returns. Recounts run as a SQL aggregate on a read path or as a job with its own pool budget. Dashboards show pool waiting count. A 503 with retry guidance appears before the process becomes unresponsive.

    Scenario B: Client-supplied role

    A JSON body included "role": "instructor". The handler trusted it and returned organization-wide progress.

    What good looks like. Roles come from the verified session. The body schema strips unknown fields or rejects role. Integration tests send an escalated role and expect 403.

    Scenario C: String-built filter

    An export route appended request.query.status into SQL so instructors could filter. A crafted status returned extra rows and created a second statement.

    What good looks like. Status is an enum validated before the query. The value is bound as $3. Dynamic ORDER BY uses an allow-list of column names in code, never the raw query string.

    Scenario D: Deploy that killed writes

    A rolling restart sent SIGKILL after a short grace period. In-flight inserts disappeared and clients retried into duplicate-key errors the UI treated as outages.

    What good looks like. SIGTERM handling drains for a bounded time. The unique constraint plus a typed already_enrolled response makes the retry safe. The UI treats that code as success-shaped idempotency.

    Scenario E: AI helper sharing the request pool

    A prototype called a model provider while holding a database client "so the summary could be saved in the same transaction." Provider latency exhausted the pool.

    What good looks like. Model calls use their own timeout and do not hold a PostgreSQL client. Persistence of a model result is a short transaction after the call returns, with authorization re-checked. Prompt text is not written to info logs.

    Best Practices

    1. Validate environment at boot and refuse to listen when DATABASE_URL is missing.
    2. Keep secrets out of git, images, and logs. Commit variable names and a password-free sample only.
    3. Validate every path, query, and body field with a schema before business logic runs.
    4. Take identity from a verified session. Discard role and learner id supplied by the client.
    5. Authorize per action and per resource. Filter SQL with the caller's id for learner-scoped rows.
    6. Return 404 when a row is outside the caller's scope if revealing existence would leak data.
    7. Send SQL text and values separately through pg parameters on every query, including dynamic filters.
    8. Allow-list identifiers such as sort columns. Parameters cannot bind SQL identifiers.
    9. Bound the pool, the body size, and statement time. Fail with 503 when the pool cannot check out.
    10. Release transactional clients in finally. Prefer pool.query for single statements.
    11. Map unique violations to stable error codes so retries are idempotent.
    12. Log route templates, status, duration, and request id. Omit tokens, emails, and raw SQL parameters.
    13. Handle SIGTERM by draining HTTP and then ending the pool.
    14. Keep CPU-heavy work off the request thread. Use SQL, a job, or a worker with a clear limit.
    15. Separate liveness (/health) from readiness (database reachable).
    16. Pin Node to an LTS line and upgrade on a schedule. Confirm Fastify and pg versions against current security advisories.
    17. Set trustProxy only behind a proxy you control, or client IP and rate limits will trust a spoofed header.
    18. Time-bound every outbound call, including future model-provider calls.
    19. Test the unauthenticated path, the wrong-learner path, and a quote-laden parameter.
    20. Document which process owns which routes so Next.js server code does not grow a second, weaker data path.

    Common Mistakes and Anti-Patterns

    1. SQL string concatenation. Symptom: unexpected rows or syntax errors that include user text. Cause: urgency and a belief that TypeScript types sanitize strings. Fix: parameters always; add a test that the SQL text does not contain the user value.
    2. Trusting x-user-id or body roles in production. Symptom: horizontal access across learners. Cause: a test stub left enabled. Fix: one authentication plugin; delete the header path outside tests.
    3. Unbounded pool or pool larger than max_connections. Symptom: database refusing connections, cascading 500s. Cause: per-process max copied from a blog, multiplied by replica count. Fix: budget connections on paper before deploy.
    4. Holding a client during slow work. Symptom: pool wait spikes while CPU or a model call runs. Cause: transaction opened too early. Fix: transaction covers only the writes that must commit together.
    5. Blocking the event loop. Symptom: health checks time out while one request runs. Cause: synchronous crypto, huge JSON, or a loop. Fix: move the work; measure event-loop delay.
    6. Missing await. Symptom: empty responses, unhandled rejections, queries that race the response. Cause: a returned promise the handler ignored. Fix: lint rule no-floating-promises; handlers are async.
    7. Stack traces and SQL in JSON errors. Symptom: schema and table names in the browser. Cause: a global error handler that sends err. Fix: log the error server-side; send { code, message } from an allow-list.
    8. Logging the DATABASE_URL. Symptom: credentials in log storage. Cause: debug boot banner. Fix: log host and database name parsed from the URL, never the userinfo.
    9. SELECT * into the response. Symptom: internal columns and future sensitive fields leak. Cause: convenience. Fix: explicit column lists and a DTO type.
    10. Health check that runs a heavy query. Symptom: restarts during a slow migration. Cause: liveness tied to a hot table. Fix: liveness is in-process; readiness is a cheap SELECT 1.
    11. No shutdown hook. Symptom: duplicate key noise and lost responses on every deploy. Cause: process manager kills mid-request. Fix: drain on SIGTERM within the platform grace period.
    12. One shared god-service module. Symptom: every change risks auth. Cause: no plugin boundary. Fix: routes register explicitly; auth hooks are visible in the route file.

    Troubleshooting and Design Review

    All routes slow, one route pegs CPU. Capture a CPU profile. If the hot stack is JavaScript rather than waiting on pg, you are on the event loop. Move that work. If stacks sit inside the driver, look at pool waits and PostgreSQL activity.

    Intermittent 500s with timeout exceeded when trying to connect. The pool cannot check out. Inspect in-flight transactions, max, replica count, and any path that forgets release(). Compare to PostgreSQL max_connections and reserved superuser connections.

    A quote in a search box changes the rows returned. Treat it as injection until proven otherwise. Read the SQL text construction. Bind the value. Add the hostile-input test to CI.

    Users see another learner's course after "fixing" a 404. Someone removed the learner_id predicate to make a test pass. Restore the predicate and test two identities.

    Deploy returns 502 for about a minute. Graceful shutdown exceeds the platform's termination grace, or the new process fails the ready check because DATABASE_URL is absent. Check boot logs for the missing-variable error and the time between SIGTERM and process exit.

    Design review checklist

    • Does every query use bound parameters, including admin filters?
    • Is the caller taken from a verified session on every mutating and reading route?
    • Are pool size, statement timeout, and body limit written down?
    • Does SIGTERM drain and then pool.end()?
    • Can logs be shipped without secrets or lesson content?
    • Which routes will later call a model, and do they avoid holding a database client during that call?
    • Is the test stub for identity impossible to enable in production configuration?

    Knowledge Check

    1. What problem does a Node backend solve for TechLearningPro?

    It gives enrollment and progress a single policy enforcement point: schema validation, verified identity, authorization, parameterized SQL, timeouts, and operability. The UI stays a client. Without that point, each Server Action or route can invent a weaker copy of the rules, and enrollment week fails in ways the UI cannot diagnose.

    2. When would you choose Fastify, Express, or split processes?

    Choose Fastify or Express based on team familiarity and validation style; both can implement the same boundary. Choose more processes when you need more CPU for concurrent I/O waiters or isolation between a public API and a worker. Choose worker threads for CPU-heavy in-process work. Choose a separate worker service when the work is slow, retryable, and must not consume the request pool.

    3. Which identity and trust boundaries matter?

    The browser is untrusted. Headers it sets are untrusted unless a proxy you control strips and resets them. The verified session is the identity. PostgreSQL enforces constraints and row visibility only for predicates you send. Model providers, when added later, are untrusted writers of prose and must not choose row ids or roles.

    4. What fails when the pool is exhausted or a query blocks, and how should the service respond?

    New checkouts wait until connectionTimeoutMillis, then error. The handler should surface 503, log pool stats, and avoid retry storms. A blocked event loop fails health checks for every request in that process; the fix is to remove the blocking work, not to raise the pool. Shutdown must stop accepting, finish or cancel in-flight work, and close the pool.

    5. How do you test quality, security, and performance of this service?

    Assert 401 without a session, 404 or 403 for a second learner, and a bound parameter that contains SQL punctuation. Assert unique violations become already_enrolled. Measure pool wait and route latency under a local concurrency run. Confirm logs contain a request id and omit the connection string. Re-check timeouts with a query you deliberately delay in a disposable database.

    Interview Questions and Answers

    Q1. Why is Node.js a fit for TechLearningPro's enrollment API?

    The API waits on PostgreSQL and, later, on identity and model providers. Node schedules those waits without a thread per request, which matches I/O-bound HTTP. The fit depends on staying non-blocking. CPU-heavy summarization on the request thread cancels the advantage. Interviewers want that caveat in the same breath as the event loop.

    Q2. What does await pool.query actually wait for?

    It waits for a pool checkout, for PostgreSQL to run the statement, and for rows to arrive. JavaScript's call stack is free to run other requests during that wait, provided you did not block before or after the await with synchronous work. The connection is occupied from the database's point of view until the query finishes.

    Q3. How do you prevent SQL injection with pg?

    Pass a constant SQL string with $1 placeholders and a values array. The driver uses the extended query protocol so values are not parsed as SQL. Refuse string concatenation, template literals that interpolate input into the statement, and identifier injection via ORDER BY ${sort}. Identifiers need an allow-list.

    Q4. Where should authorization live if the UI already hides the button?

    On the server, in the handler, expressed as both a role check and a row predicate. The UI hide is a usability affordance. Direct calls bypass it. Returning another learner's row and then filtering in the client is a data leak even if the screen looks correct.

    Q5. How do you size a pg pool?

    Start from PostgreSQL max_connections, subtract admin and migration headroom, divide by the number of API processes and workers, and leave margin. A large pool on a small database increases context switching and waiting. Prove the number with pool-wait metrics. Do not copy max: 10 from this lesson into a twenty-replica deployment without doing that arithmetic.

    Q6. What is the difference between liveness and readiness?

    Liveness means the process should be restarted if it fails: the event loop can answer. Readiness means the process should receive traffic: it can reach its critical dependencies. Using a heavy query as liveness restarts healthy processes during a database stall and makes the stall worse.

    Q7. How do you make enrollment creation safe under retries?

    Put a unique constraint on the natural key (learner_id, course_slug). Insert with parameters. Map SQLSTATE 23505 to a stable already_enrolled code and return the existing row if the product wants a 200. The client may retry timeouts without creating duplicates. Application-level "check then insert" without the constraint races.

    Q8. What belongs in structured logs for an API request?

    Timestamp, level, request id, route template, method, status, duration, and a stable caller id. Omit authorization headers, cookies, passwords, connection strings, and free-text lesson notes. Log unexpected errors with a server-side stack that is not returned to the client.

    Q9. Why can a model call inside a database transaction take down the API?

    The checked-out connection sits idle in an open transaction while the provider responds, sometimes for tens of seconds, and row locks may be held. Other requests exhaust the pool. Call the model outside the transaction, bound it with a timeout, then open a short transaction to store an authorized result.

    Q10. Fastify plugin encapsulation: why does it matter?

    Hooks registered inside a plugin apply to routes encapsulated there. A parser or authentication hook registered at the root applies to every route, including health checks and future webhooks, unless you designed that on purpose. Encapsulation makes the blast radius of a hook visible.

    Q11. What is a graceful shutdown sequence?

    Handle SIGTERM. Stop accepting new HTTP connections. Allow in-flight handlers to finish until the platform grace period. Close the server, then end the pool so PostgreSQL sessions do not linger as idle in transaction. Exit non-zero if shutdown itself throws, so the platform does not treat a stuck process as healthy.

    Q12. How would you explain the event loop to a colleague who wants to add a sync PDF render on POST /progress?

    The render would freeze every concurrent request in that process, including health checks, because JavaScript does not interleave on one thread. Generate the PDF in a worker or a job, store the artifact, and return 202 with a status URL. The progress write itself stays a short parameterized update.

    Hands-On Exercises

    Lab note. Use a local or disposable PostgreSQL. Keep credentials in an uncommitted env file. Do not log DATABASE_URL. Do not point experiments at production.

    Exercise 1: Authorized enrollment read

    Problem. Implement GET /api/enrollments/:enrollmentId so a learner receives only their row, hostile ids cannot change the statement, and a missing DATABASE_URL prevents boot.

    Tasks.

    1. Create a gitignored env file with DATABASE_URL aimed at a local database. Add a password-free sample env to the repo.
    2. Boot Fastify only after the variable is present. Add /health.
    3. Add the parameterized select filtered by verified caller id. In tests, inject the caller; in the server path, read a session stub you can disable with NODE_ENV=production or an explicit ALLOW_TEST_IDENTITY=false default.
    4. Validate enrollmentId as a UUID. Reject invalid ids with 400.
    5. Write tests: 401 without caller, 404 for another learner's id, 200 for the owner, and a value containing quotes that must not appear inside the SQL string.
    6. Handle SIGTERM in the entry file and confirm a local kill closes the pool without an unhandled rejection.
    7. Cleanup: drop the local test schema and confirm no connection string landed in git (git status, log review).

    Deliverables. Source, tests, a one-page note of pool size versus a stated max_connections, and a shutdown log line.

    Challenge. Two tenants share the table. Add organization_id to the predicate and a test where the same learner id in another organization is invisible. Describe what you would change if an instructor may list every enrollment in their organization: a separate route, an explicit role check, and a query that still binds organization_id from the session.

    Lesson Summary

    Node.js is TechLearningPro's HTTP runtime for I/O-bound product APIs: one JavaScript thread schedules many waits, a pool talks to PostgreSQL, and the handler is the place identity becomes a row filter. Fastify or Express can host that handler. Safety comes from schema validation, verified callers, parameterized SQL, bounded pools, and a shutdown path that respects in-flight writes. Blocking work, client-supplied roles, and model calls inside open transactions are how a small API becomes an enrollment-week outage.

    This lesson sits after the UI foundations and before the contract and the schema. API Design with REST, OpenAPI and GraphQL Concepts turns these routes into a contract clients and tests can share. Relational Data Modeling with PostgreSQL designs the tables, keys, and privileges those parameters target. The runtime primer lives at /learn/nodejs. When the contract and the tables are in place, Generative AI, LLMs and Transformer Fundamentals adds model behavior beside this deterministic core without replacing it.

    Further Reading

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