Skip to main content
MockAttempt App Icon

Install MockAttempt App

Launch full-screen from your iPhone / iPad Home Screen

  1. Step 1: Tap the Safari Share icon โ†‘ at the bottom of your screen.
  2. Step 2: Scroll down and tap โ€œAdd to Home Screenโ€, then tap Add.
Node.js, TypeScript & Express Backend Engineering ๐Ÿ›ก๏ธ Get Placement or 100% Fees Refund* ≥90% AI Mock Gate ๐Ÿ“… Weekend-Only Batch (Satโ€“Sun โ€ข 2h/Day) ๐Ÿ‘จโ€๐Ÿ’ป 100% Working IT Professional Trainers Code: NBCP
Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program Official Course Logo

Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program 24 Weeks (6 Months) โ€ข Beginner to Job-Ready Live Weekend Cohort • 24 Modules (543 Topics) • JavaScript ES6+ & Strict TypeScript 5, Node.js 22 LTS (V8, libuv & Event Loop), Buffers, Streams & Async File Processing, Express.js Layered REST Architecture, OpenAPI 3.1, Swagger UI & Zod Validation • 100% Placement Guarantee*

100% Backend-Focused 6-Month Career Program: Master JavaScript ES6+, TypeScript 5, Node.js (V8/libuv/Streams), Express.js REST APIs, MongoDB + Mongoose, PostgreSQL + Prisma, JWT/OAuth2/RBAC, Redis, BullMQ, RabbitMQ/Kafka, Socket.IO, Jest/Supertest, Docker, Nginx & CI/CD across 24 modules and 6 mandatory projects.

โ˜…โ˜…โ˜…โ˜…โ˜… 4.95/5 Verified Cohort Rating โ€ข โœ“ Attend 1st Weekend Class Free โ€ข โœ“ Dual QR/Barcode Credentials (MAA + MAA-INT)
24 Modules
543 Live Topics
1086 Hands-On Labs
543 Mock Tests
543 AI Interviews
24 + 1 Module + Client
JavaScript ES6+ & Async Logo JavaScript ES6+ & Async Strict TypeScript 5 Logo Strict TypeScript 5 Node.js 22 (V8 & libuv) Logo Node.js 22 (V8 & libuv) Express.js & OpenAPI 3.1 Logo Express.js & OpenAPI 3.1 MongoDB 7 & Mongoose 8 Logo MongoDB 7 & Mongoose 8 PostgreSQL 16 & SQL Logo PostgreSQL 16 & SQL Prisma ORM 5 & ACID Logo Prisma ORM 5 & ACID JWT, OAuth2, RBAC & OWASP Logo JWT, OAuth2, RBAC & OWASP +8 More Tools โ†“
Already Enrolled in NBCP Candidates Already Enrolled in Node.js Backend Career Program (NBCP)
Weekend-Only Cohort (Satโ€“Sun โ€ข 2h/Day)

Vikramjit Gill

โœ“ Enrolled

๐Ÿ“ Dubai, UAE โ€ข Support Eng โ†’ Node.js, TypeScript & Redis

Node.js Backend Career Program Logo Enrolled: Node.js Backend Career Program (NBCP)

๐Ÿ“… Weekend Satโ€“Sun (3โ€“5 PM IST โ€ข UAE Afternoon)

ID: MAA-NBCP-313 Enrolled โ€ข 2d ago

Siddharth Rao

โœ“ Enrolled

๐Ÿ“ Hyderabad, India โ€ข Frontend Dev โ†’ Express, Prisma & BullMQ

Node.js Backend Career Program Logo Enrolled: Node.js Backend Career Program (NBCP)

๐Ÿ“… Weekend Satโ€“Sun (10 AMโ€“12 PM IST)

ID: MAA-NBCP-314 Enrolled โ€ข 5d ago

Ritika Malhotra

โœ“ Enrolled

๐Ÿ“ New Delhi, India โ€ข B.Tech CSE โ†’ Distributed Node Microservices

Node.js Backend Career Program Logo Enrolled: Node.js Backend Career Program (NBCP)

๐Ÿ“… Weekend Satโ€“Sun (6โ€“8 PM IST)

ID: MAA-NBCP-315 Enrolled โ€ข This Week
Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program Logo NBCP โ€ข Satโ€“Sun Live
Free 1st Demo
All-Inclusive Fee (Incl. 18% GST โ€ข 0% Salary Cut)
$160 USD All-Incl.

Net: $136 + 18% GST ($24 ) โ€ข ~$1 /Hr

โšก 3 ร— $53 (0% Installments)

Pay $160 One-Time or in 3 Easy 0% Installments of $53 (All-Inclusive โ€” 0% Interest, No Salary Cut)

Attend 1st Weekend Class Free & Get Roadmap:

โœ“ Live English Classes (24 Weeks (6 Months) โ€ข Beginner to Job-Ready) โ€ข โœ“ Instant Syllabus PDF

๐Ÿ›ก๏ธ Get Placement โ€” Or 100% Fees Refund* โ€ข Weekend-Only Live Batch

100+ Job Openings in 6 Months With Working IT Professional Trainers โ€” Or 100% Tuition Refund*

Full Legal Terms โ†’
STEP 01 โ€ข WEEKEND LIVE + REPOS

Weekend Live Classes & 24 Real Repos

Attend Satโ€“Sun (2h/day) live sessions with Working IT Professionals (โ‰ฅ85% attendance) and ship 100% original GitHub repositories.

STEP 02 โ€ข โ‰ฅ90% MASTERY GATE

Score โ‰ฅ90% in Mocks & AI Vivas (Unlimited Retries)

Clear โ‰ฅ90% in every Topic Mock Test & Spoken MockAttempt AI Interview with unlimited free re-attempts whenever below 90%.

STEP 03 โ€ข PLACEMENT OR 100% REFUND*

100+ Openings & Online AI Assessment Coaching

Get 100+ curated IT openings in 6 months + trainer coaching for employer Online AI Assessments (OA) โ€” or 100% net tuition refund*.

๐Ÿ” Transparent Distinction: Unconditional Career Support vs. Conditional 6-Month 100% Net Tuition Refund* ($136 )

1. Placement & Career Support (Every Graduate): All graduates receive ATS resume engineering, GitHub portfolio verification, mock technical/HR interviews, and ongoing access to curated hiring drives. 2. 6-Month 100% Net Tuition Fee Refund* Covenant: Activated when you complete (a) ≥85% live weekend attendance, (b) 100% original GitHub module repos & Live Client Project, (c) ≥90% in all 543 Topic Mocks & 543 Spoken AI Interviews (unlimited free retries included), and (d) apply to ≥95% of our 100+ curated IT openings & attend 100% of scheduled interviews within 180 days of graduation. Read our full Placement Guarantee Policy & Fee Refund Policy.

Structured Month-by-Month Progression

6-Month Learning Roadmap (24 Weekly Modules)

Every month concludes with measurable coding competency, a portfolio repository deliverable, and continuous DSA progression.

โš™๏ธ Recommended Baseline Stack: Node.js 22 LTS, JavaScript ES2024+, TypeScript 5.x (`strict: true`), Express.js, `Zod`, OpenAPI 3.1 / Swagger, MongoDB 7 + Mongoose 8, PostgreSQL 16 + Prisma 5, `argon2`, `jose` / `jsonwebtoken`, `helmet`, `ioredis` (Redis 7), `bullmq`, `amqplib` (RabbitMQ 3), `socket.io` 4, `minio` / S3-compatible presigned storage, `vitest` / `jest` + `supertest`, `pino`, Docker Compose v2, Nginx, PM2, and GitHub Actions.
Month 1 Weeks 1โ€“4 (Modules 1โ€“4)

Month 1: JavaScript, TypeScript and Backend Foundations

Master modern JavaScript ES6+, asynchronous execution internals (closures, prototypes, event loop, microtasks, Promises, async/await), strict TypeScript 5, Git/GitHub PR workflows, Linux CLI, and HTTP/TCP networking fundamentals.

Outcome: Write clean, strictly typed, asynchronous JavaScript & TypeScript backend code, navigate Linux servers confidently, and inspect raw HTTP wire traffic.

Deliverable: Project 1: TypeScript-Based Command-Line Employee Management System.

DSA Focus: Arrays, Strings, Hash Maps/Sets, Two Pointers & Big-O Complexity in TypeScript (22 Problems).

Month 2 Weeks 5โ€“8 (Modules 5โ€“8)

Month 2: Node.js Runtime and Express.js Backend Development

Deep-dive into V8, libuv, Node.js event-loop phases, core modules (fs, crypto, Buffer, Streams & backpressure, worker_threads, cluster), Express.js middleware/routing, OpenAPI/Swagger, and 3-layer Controller-Service-Repository REST architecture.

Outcome: Architect, validate, document, and log modular Express.js + TypeScript REST APIs handling large streams and graceful shutdowns without blocking the event loop.

Deliverable: Project 2: Production-Style Employee Management REST API (Express, TypeScript, Swagger & Postman).

DSA Focus: Sliding Window, Binary Search, Sorting, Recursion & Async Concurrency Machine-Coding (24 Problems).

Month 3 Weeks 9โ€“12 (Modules 9โ€“12)

Month 3: Database Engineering and ORM / ODM

Master polyglot persistence across MongoDB + Mongoose ODM (BSON modeling, ESR compound indexes, aggregation pipelines, replica-set sessions) AND PostgreSQL 16 + Complete SQL + Prisma ORM (3NF, joins, window functions, EXPLAIN ANALYZE, ACID interactive transactions, migrations).

Outcome: Design, index, query, migrate, and benchmark both NoSQL document stores and ACID relational databases in TypeScript.

Deliverable: Project 3: Multi-Database Inventory Management Backend (MongoDB + Mongoose & PostgreSQL + Prisma).

DSA Focus: Linked Lists, Monotonic Stacks/Queues & Database/Pagination Machine-Coding (22 Problems).

Month 4 Weeks 13โ€“16 (Modules 13โ€“16)

Month 4: API Security, Validation, Advanced Features and Testing

Implement Argon2/bcrypt, rotated/revocable JWT access & refresh tokens, sessions/cookies, OAuth 2.0/OIDC, RBAC & resource permissions, OWASP API Top 10 defenses, Zod/Joi validation, Multer + S3-compatible MinIO presigned uploads, signed webhooks, cron jobs, and Jest/Vitest + Supertest QA.

Outcome: Ship hardened, OWASP-compliant Node.js services verified by >= 80% automated unit and Supertest integration test suites.

Deliverable: Project 4: Secure Authentication and Authorization Service.

DSA Focus: Trees, Heaps/Priority Queues, REST & Auth/RBAC Machine-Coding (22 Problems).

Month 5 Weeks 17โ€“20 (Modules 17โ€“20)

Month 5: Redis, Queues, Messaging, WebSockets and Microservices

Scale backend throughput using Redis 7 caching/rate-limiting/locks, BullMQ delayed & repeatable worker queues, RabbitMQ exchanges/DLQs, Apache Kafka partitions/consumer groups, authenticated Socket.IO + Redis adapter real-time servers, and resilient Saga/Circuit-Breaker microservices.

Outcome: Engineer low-latency cached APIs, idempotent background workers, real-time WebSocket hubs, and event-driven multi-service architectures.

Deliverable: Project 5: 7-Service E-Commerce Microservices Backend.

DSA Focus: Graphs (BFS, DFS, Topological Sort, Dijkstra), Caching, Rate-Limiting & Queue Machine-Coding (23 Problems).

Month 6 Weeks 21โ€“24 (Modules 21โ€“24)

Month 6: Performance, Docker, Linux/Nginx CI/CD, System Design & Capstone

Profile V8 CPU/heap snapshots & event-loop lag, containerize multi-service backends with multi-stage Docker & Docker Compose, configure Linux servers, PM2, Nginx SSL reverse proxies, and GitHub Actions CI/CD, master Backend System Design interviews, and deliver the Final Enterprise Capstone.

Outcome: Deploy, monitor, load-test, and defend a complete production-ready Enterprise E-Commerce Backend in technical interviews.

Deliverable: Final Capstone (Project 6): Enterprise E-Commerce and Order Management Backend.

DSA Focus: Dynamic Programming & Backend System Design Machine-Coding (22 Problems โ€” Completing 135 Total Problems).

โšก Continuous 6-Month Coding Track โ€ข Separate Problem Tracking

135 Curated JS/TS DSA & Backend Machine-Coding Problems Across 18 Core Areas

Practised continuously from Month 1 to Month 6 (Easy โ†’ Medium โ†’ Selected Hard) with constraints, sample I/O, Big-O analysis, and TypeScript 5 & Node.js reference solutions and test cases inside the Student Coding Lab.

Arrays & Strings

12 Problems โ€ข M1

Hash Maps

10 Problems โ€ข M1

Searching & Sorting

10 Problems โ€ข M1

Two Pointers

10 Problems โ€ข M1

Sliding Window

10 Problems โ€ข M2

Recursion

9 Problems โ€ข M2

Linked Lists

8 Problems โ€ข M3

Stacks & Queues

9 Problems โ€ข M2

Trees

9 Problems โ€ข M4

Graphs

9 Problems โ€ข M4

Dynamic Programming

9 Problems โ€ข M3

Asynchronous JavaScript

5 Problems โ€ข M2

REST API Implementation

5 Problems โ€ข M2

Authentication

5 Problems โ€ข M4

Database Queries

4 Problems โ€ข M3

Caching

4 Problems โ€ข M5

Queue Processing

4 Problems โ€ข M5

Backend System Design

3 Problems โ€ข M6

Structured Weekly Delivery

Recommended Weekly Training & Practice Plan

Trainer-led concepts 8 hrs/week
Live coding 5 hrs/week
Guided practicals 4 hrs/week
Assignments & independent practice 4 hrs/week
DSA & interview preparation 2 hrs/week
Assessments & doubt clearing 2 hrs/week
Academic Passing Threshold: Minimum 70% in theoretical assessments, 70% in coding/practical assessments, 70% in project evaluations, 100% mandatory assignment submission, and live code defense.

โœ“ Included in This 6-Month Program

  • โœ“Complete JavaScript ES6+, Asynchronous Internals & Strict TypeScript 5 Backend Engineering
  • โœ“Node.js 22 Runtime Architecture (`V8`, `libuv`, Event Loop, `Buffers`, `Streams` & `worker_threads`)
  • โœ“Express.js Layered REST APIs (`Controller -> Service -> Repository`), `Zod`, RFC 9457 Errors & OpenAPI/Swagger
  • โœ“Polyglot Databases: `MongoDB 7 + Mongoose 8` AND `PostgreSQL 16 + Advanced SQL + Prisma ORM 5`
  • โœ“ACID Transactions, Row/Optimistic Locking, Query Tuning (`EXPLAIN ANALYZE`) & Zero-Downtime Migrations
  • โœ“Security: `Argon2id`, Rotated JWT Refresh Families, `OAuth 2.0 PKCE`, `RBAC`, `Helmet`, Rate Limiting & OWASP API Top 10
  • โœ“`Redis 7` Caching, `BullMQ` Background Jobs, `RabbitMQ` & `Kafka` Fundamentals, Outbox & Microservices Sagas
  • โœ“`WebSocket` & Multi-Node `Socket.IO` Real-Time Services + S3-Compatible `MinIO` Presigned File Uploads
  • โœ“Automated `Jest`, `Vitest` & `Supertest` Integration Suites + `autocannon` Load Testing
  • โœ“Vendor-Neutral Production Deployment: `Linux`, 3-Stage `Dockerfiles`, `Docker Compose`, `Nginx`, `PM2`, `HTTPS` & `GitHub Actions CI/CD`
  • โœ“135 Curated Problems (105 JS/TS DSA + 30 Backend Machine-Coding) + 10 System Design Rounds + 6 Mandatory Portfolio Projects

โœ• Not Part of Core 6-Month Syllabus

Published transparently so students compare scope honestly before enrolling:

  • โ€”Frontend UI frameworks (`React`, `Angular`, `Vue`, DOM styling or CSS design โ€” 100% of hours focus purely on Backend Engineering; see our Frontend Career Program for UI)
  • โ€”Cloud-vendor-specific certification tracks (proprietary cloud provider certifications are intentionally excluded; deployment uses portable vendor-neutral Linux, Docker Compose, Nginx, PM2, MinIO & GitHub Actions)
  • โ€”Dedicated enterprise Kubernetes cluster administration (`CKA`) or service-mesh infrastructure
  • โ€”Native mobile application development (`Android Kotlin`, `iOS Swift`, `React Native` or `Flutter`)
  • โ€”Deep learning / foundation model training specialization
๐Ÿ“ Test Yourself Live โ€ข NBCP OA Question Topic: Introduction to JavaScript and Server-Side Execution Environments โ†’

In production JavaScript Core, what is the primary backend engineering purpose of 'Introduction to JavaScript and Server-Side Execution Environments'?

โœ“ Correct Answer: A

'Introduction to JavaScript and Server-Side Execution Environments' is used in production JavaScript Core specifically for: Running high-concurrency JSON APIs, CLI tools, and background workers directly on Linux servers with Node.js.

2 Free Timed 50-MCQ Exams / Topic / Day Practice 543 NBCP Mocks โ†’
๐ŸŽ™๏ธ MockAttempt-AI v2.5 Viva 2 Free / Topic / Day

Rehearse Spoken NBCP Technical Interviews Aloud

Practice L1/L2 engineering questions across all 543 NBCP topics. Our AI Interviewer speaks questions aloud and scores your spoken answer across Technical Depth, Clarity, Edge Cases & Confidence.

100% Studentโ€“Trainer Syllabus & Next-Topic Sequence Transparency

Detailed Module & Topic-Wise Syllabus Inspector โ€” Zero-to-Expert Subtopics

Every module and topic lists its exact technical subtopics, hands-on code labs, Mock Tests, MockAttempt AI interviews, and explicit What Topic Is Next โ†’ progression so enrolled students and trainers always stay synchronized from Day 1 to Expert mastery.

Download Syllabus PDF
๐Ÿ’Ž Why This Curriculum Justifies Every Rupee โ€ข Zero-to-Expert Guarantee

Job-Guaranteed* Zero-to-Expert Career Engineering Track (24 Modules โ€ข 543 Live Topics โ€ข 4344+ Subtopics)

Engineered to take a learner from Day-1 scratch to Senior/Production-ready expertise across 600 guided hours (~โ‚น25/hr), 24 real GitHub repositories, โ‰ฅ90% Mock + AI Viva gates, and 100+ curated IT job openings in 6 months (or 100% net tuition refund*).

4,344+ Technical Subtopics ~$1 / Guided Hour ~$1 / Live Topic
Modules 1โ€“4 85 Topics โ€ข 680 Subtopics

Month 1 โ€“ Month 1: JavaScript, TypeScript and Backend Foundations (Weeks 1โ€“4 (Modules 1โ€“4))

Modules 5โ€“8 92 Topics โ€ข 736 Subtopics

Month 2 โ€“ Month 2: Node.js Runtime and Express.js Backend Development (Weeks 5โ€“8 (Modules 5โ€“8))

Modules 9โ€“12 90 Topics โ€ข 720 Subtopics

Month 3 โ€“ Month 3: Database Engineering and ORM / ODM (Weeks 9โ€“12 (Modules 9โ€“12))

Modules 13โ€“16 95 Topics โ€ข 760 Subtopics

Month 4 โ€“ Month 4: API Security, Validation, Advanced Features and Testing (Weeks 13โ€“16 (Modules 13โ€“16))

Modules 17โ€“20 99 Topics โ€ข 792 Subtopics

Month 5 โ€“ Month 5: Redis, Queues, Messaging, WebSockets and Microservices (Weeks 17โ€“20 (Modules 17โ€“20))

Modules 21โ€“24 82 Topics โ€ข 656 Subtopics

Month 6 โ€“ Month 6: Performance, Docker, Linux/Nginx CI/CD, System Design & Capstone (Weeks 21โ€“24 (Modules 21โ€“24))

Module Learning & Hands-On Objectives

โœ“ Write clean, predictable ES6+ JavaScript running on Node.js without implicit coercion bugs or global scope leaks.
โœ“ Manipulate arrays, strings, and nested objects fluently using immutable functional patterns (`map`, `filter`, `reduce`).
โœ“ Apply lexical scoping, arrow vs regular functions, and custom `Error` handling across modular CLI programs.
โœ“ Complete all 4 Week 1 practical builds: Calculator, Student Records Processor, Employee Data Manager, and CLI Utility.
Guide โ†’

ECMAScript specification vs host environments (Node.js server runtime vs browser), V8 JIT compilation, and running scripts via `node --watch`

Subtopics Covered (8):
  • ECMAScript specification vs host environments (Node.js server runtime vs browser)
  • V8 JIT compilation
  • Running scripts via `node --watch`
โ†’ What Topic Is Next: Next Topic 1.2: Variables: var, let and const
Guide โ†’

Function-scoped hoisted `var` pitfalls vs block-scoped `let` and `const`, the Temporal Dead Zone (`TDZ`), and `const` binding vs object mutability

Subtopics Covered (8):
  • Function-scoped hoisted `var` pitfalls vs block-scoped `let`
  • `const`
  • The Temporal Dead Zone (`TDZ`)
โ†’ What Topic Is Next: Next Topic 1.3: Primitive Data Types and Reference Data Types
Guide โ†’

7 primitives (`string`, `number`, `bigint`, `boolean`, `undefined`, `symbol`, `null`) stored by value vs Heap reference objects (`Object`, `Array`, `Function`, `Map`...

Subtopics Covered (8):
  • 7 primitives (`string`
  • `number`
  • `bigint`
โ†’ What Topic Is Next: Next Topic 1.4: Type Conversion and Type Coercion
Guide โ†’

Explicit parsing (`Number()`, `Number.parseInt(s, 10)`, `String()`, `Boolean()`) vs implicit `==` / `+` coercion traps, `Number.isNaN()` vs global `isNaN()`, and tru...

Subtopics Covered (8):
  • Explicit parsing (`Number()`
  • `Number.parseInt(s
  • 10)`
โ†’ What Topic Is Next: Next Topic 1.5: Operators and Expressions
Guide โ†’

Strict equality (`===`, `!==`), arithmetic/exponentiation (`**`), logical short-circuiting (`&&`, `||`, `!`), nullish assignment (`??=`), and ternary expressions

Subtopics Covered (8):
  • Strict equality (`===`
  • `!==`)
  • Arithmetic/exponentiation (`**`)
โ†’ What Topic Is Next: Next Topic 1.6: Conditional Statements and Guard Clauses
Guide โ†’

`if / else if / else`, early-return guard clauses flattening nested arrow-antipatterns, and exhaustive `switch` blocks with block scoping

Subtopics Covered (8):
  • `if / else if / else`
  • Early-return guard clauses flattening nested arrow-antipatterns
  • Exhaustive `switch` blocks with block scoping
โ†’ What Topic Is Next: Next Topic 1.7: Loops: for, while, do-while, for...of and for...in
Guide โ†’

Indexed `for`, condition-driven `while`/`do-while`, iterable `for...of` (`Array`, `Map`, `Set`, `String`), why `for...in` walks inherited prototype keys, and `break`...

Subtopics Covered (8):
  • Indexed `for`
  • Condition-driven `while`/`do-while`
  • Iterable `for...of` (`Array`
โ†’ What Topic Is Next: Next Topic 1.8: Strings and String Methods
Guide โ†’

Immutable UTF-16 strings, `slice`, `trim`, `toLowerCase`, `includes`, `startsWith`, `split`/`join`, `replaceAll`, `padStart`, and normalizing user emails/slugs

Subtopics Covered (8):
  • Immutable UTF-16 strings
  • `slice`
  • `trim`
โ†’ What Topic Is Next: Next Topic 1.9: Arrays and Functional Array Methods
Guide โ†’

Mutating (`push`, `pop`, `splice`, `sort`) vs non-mutating ES2023+ (`toSorted`, `map`, `filter`, `reduce`, `find`, `findIndex`, `some`, `every`, `flatMap`), and nume...

Subtopics Covered (8):
  • Mutating (`push`
  • `pop`
  • `splice`
โ†’ What Topic Is Next: Next Topic 1.10: Objects and Object Manipulation
Guide โ†’

Object literals, computed keys `[key]`, dynamic property lookup (`Object.hasOwn(obj, key)`), `Object.keys`, `Object.values`, `Object.entries`, `Object.fromEntries`,...

Subtopics Covered (8):
  • Object literals
  • Computed keys `[key]`
  • Dynamic property lookup (`Object.hasOwn(obj
โ†’ What Topic Is Next: Next Topic 1.11: Functions, Parameters and Return Values
Guide โ†’

First-class functions, arity, default parameter expressions (evaluated per call!), rest parameters `(...items)`, pure functions vs side effects, and returning struct...

Subtopics Covered (8):
  • First-class functions
  • Arity
  • Default parameter expressions (evaluated per call!)
โ†’ What Topic Is Next: Next Topic 1.12: Function Declarations, Expressions and Arrow Functions
Guide โ†’

Hoisted declarations vs `const fn = function() {}` expressions vs concise `=>` arrow functions (lexical `this`, no `arguments`, cannot be `new`-constructed, `() => (...

Subtopics Covered (8):
  • Hoisted declarations vs `const fn = function() {}` expressions vs concise `=>` arrow functions (lexical `this`
  • No `arguments`
  • Cannot be `new`-constructed
โ†’ What Topic Is Next: Next Topic 1.13: Scope and Hoisting
Guide โ†’

Global, module, function, and `{}` block scopes, scope-chain resolution, function declaration hoisting vs `let`/`const` Temporal Dead Zone (`ReferenceError`), and ES...

Subtopics Covered (8):
  • Global
  • Module
  • Function
โ†’ What Topic Is Next: Next Topic 1.14: Error Handling Using try, catch, finally
Guide โ†’

Synchronous exception unwinding, custom `class DomainError extends Error` with `cause` chaining (`new Error("msg", { cause: err })`), `finally` resource cleanup, and...

Subtopics Covered (8):
  • Synchronous exception unwinding
  • Custom `class DomainError extends Error` with `cause` chaining (`new Error("msg"
  • { cause: err })`)
โ†’ What Topic Is Next: Next Topic 1.15: Debugging and Developer Tools for Backend JS
Guide โ†’

Structured `console.table`/`console.time`, `node --inspect-brk`, VS Code `launch.json` breakpoints, conditional breakpoints, call-stack inspection, and building the...

Subtopics Covered (8):
  • Structured `console.table`/`console.time`
  • `node --inspect-brk`
  • VS Code `launch.json` breakpoints
โ†’ What Topic Is Next: Module 1 Capstone (Week 1 Lab Build: JavaScript ES6+ Payroll, Ledger & Text Analytics CLI Suite) โ†’ Next Topic 2.1: Execution Context and the Call Stack

Build a zero-dependency Node.js ES6+ command-line utility pack implementing immutable payroll tax slabs, array/object grouping pipelines, string/CSV log normalizers, and structured custom Error classes.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Trace execution contexts, closures, `this` binding (`call`/`apply`/`bind`), and the prototype chain accurately in interviews and code reviews.
โœ“ Design clean OOP domain models using ES2022+ `class`, `#private` fields, inheritance, and composition.
โœ“ Orchestrate concurrent and sequential I/O using Promises, `async/await`, and `Promise.all` / `allSettled` / `race` / `any`.
โœ“ Predict exact event-loop execution order across synchronous frames, microtasks, and macrotasks while avoiding unhandled rejections and memory leaks.
Guide โ†’

Global & Function Execution Contexts (Creation Phase vs Execution Phase), Variable Environment, Lexical Environment, LIFO Call Stack frames, and `RangeError: Maximum...

Subtopics Covered (8):
  • Global & Function Execution Contexts (Creation Phase vs Execution Phase)
  • Variable Environment
  • Lexical Environment
โ†’ What Topic Is Next: Next Topic 2.2: Lexical Scope and Closures
Guide โ†’

How inner functions retain live references to outer lexical environments even after the outer function returns โ€” powering factory functions, memoization, rate counte...

Subtopics Covered (8):
  • How inner functions retain live references to outer lexical environments even after the outer function returns โ€” powering factory functions
  • Memoization
  • Rate counters
โ†’ What Topic Is Next: Next Topic 2.3: The this Keyword and Binding Rules
Guide โ†’

4 `this` binding rules in priority order: (1) `new` binding, (2) explicit `call`/`apply`/`bind`, (3) implicit method `obj.fn()`, (4) default (`undefined` in strict m...

Subtopics Covered (8):
  • 4 `this` binding rules in priority order: (1) `new` binding
  • (2) explicit `call`/`apply`/`bind`
  • (3) implicit method `obj.fn()`
โ†’ What Topic Is Next: Next Topic 2.4: call(), apply() and bind()
Guide โ†’

Invoking functions immediately with explicit `this` (`fn.call(ctx, a, b)` vs `fn.apply(ctx, argsArray)`) vs creating a permanently bound function (`fn.bind(ctx)`)

Subtopics Covered (8):
  • Invoking functions immediately with explicit `this` (`fn.call(ctx
  • B)` vs `fn.apply(ctx
  • ArgsArray)`) vs creating a permanently bound function (`fn.bind(ctx)`)
โ†’ What Topic Is Next: Next Topic 2.5: Prototypes and Prototypal Inheritance
Guide โ†’

`Object.getPrototypeOf()`, `Fn.prototype` vs instance `[[Prototype]]`, property lookup delegation along the prototype chain, `Object.create(null)` dictionary maps, a...

Subtopics Covered (8):
  • `Object.getPrototypeOf()`
  • `Fn.prototype` vs instance `[[Prototype]]`
  • Property lookup delegation along the prototype chain
โ†’ What Topic Is Next: Next Topic 2.6: Constructor Functions and ES6 Classes
Guide โ†’

How `new` works in 4 steps (create object -> link `[[Prototype]]` -> bind `this` -> return object) and modern `class` syntax (`constructor`, instance methods, `stati...

Subtopics Covered (8):
  • How `new` works in 4 steps (create object -> link `[[Prototype]]` -> bind `this` -> return object)
  • Modern `class` syntax (`constructor`
  • Instance methods
โ†’ What Topic Is Next: Next Topic 2.7: Object-Oriented Programming in JavaScript
Guide โ†’

Modelling cohesive backend entities, value objects, services, and repositories with clear responsibilities rather than anemic global helper bags

Subtopics Covered (8):
  • Modelling cohesive backend entities
  • Value objects
  • Services
โ†’ What Topic Is Next: Next Topic 2.8: Inheritance and Polymorphism
Guide โ†’

`extends`, `super()`, method overriding, polymorphic dispatch across notification/payment strategies (`EmailNotifier`, `SmsNotifier`, `WebhookNotifier`), and favorin...

Subtopics Covered (8):
  • `extends`
  • `super()`
  • Method overriding
โ†’ What Topic Is Next: Next Topic 2.9: Encapsulation (#private Fields) and Abstraction
Guide โ†’

True runtime-enforced ECMAScript `#private` fields & `#private` methods (inaccessible even via `Object.keys` or `JSON.stringify`!) and exposing narrow public APIs

Subtopics Covered (8):
  • True runtime-enforced ECMAScript `#private` fields & `#private` methods (inaccessible even via `Object.keys` or `JSON.stringify`!)
  • Exposing narrow public APIs
  • Production Backend Pitfall & Guardrail (Encapsulation (#private Fields) and Abstraction)
โ†’ What Topic Is Next: Next Topic 2.10: Object and Array Destructuring
Guide โ†’

Nested destructuring, property aliasing (`{ user_id: userId }`), default values (`= 20` triggered ONLY on `undefined`, NOT `null`!), and function parameter destructu...

Subtopics Covered (8):
  • Nested destructuring
  • Property aliasing (`{ user_id: userId }`)
  • Default values (`= 20` triggered ONLY on `undefined`
โ†’ What Topic Is Next: Next Topic 2.11: Spread and Rest Operators (Shallow vs Deep Clone)
Guide โ†’

Immutable shallow updates (`{ ...user, role: "admin" }`), rest omission (`const { passwordHash, ...safeUser } = dbUser`!), and why spread is SHALLOW vs native `struc...

Subtopics Covered (8):
  • Immutable shallow updates (`{ ...user
  • Role: "admin" }`)
  • Rest omission (`const { passwordHash
โ†’ What Topic Is Next: Next Topic 2.12: Template Literals and Tagged Templates
Guide โ†’

Multi-line strings, `${expr}` interpolation, and how **Tagged Template Literals** (`sql\`SELECT * FROM users WHERE id = \${id}\``) power SQL-injection-safe parameter...

Subtopics Covered (8):
  • Multi-line strings
  • `${expr}` interpolation
  • How **Tagged Template Literals** (`sql\`SELECT * FROM users WHERE id = \${id}\``) power SQL-injection-safe parameterized queries in Prisma & Postgres!
โ†’ What Topic Is Next: Next Topic 2.13: Optional Chaining (?.) and Nullish Coalescing (??)
Guide โ†’

Safe deep access `req.user?.organization?.plan ?? "free"`, optional method `onComplete?.()`, and optional bracket `items?.[0]`

Subtopics Covered (8):
  • Safe deep access `req.user?.organization?.plan ?? "free"`
  • Optional method `onComplete?.()`
  • Optional bracket `items?.[0]`
โ†’ What Topic Is Next: Next Topic 2.14: Modules: CommonJS vs ES Modules Preview
Guide โ†’

Synchronous dynamic `require()` (`module.exports`) vs static asynchronous ESM (`import` / `export`), file extensions in Node ESM, and interoperability (`import pkg f...

Subtopics Covered (8):
  • Synchronous dynamic `require()` (`module.exports`) vs static asynchronous ESM (`import` / `export`)
  • File extensions in Node ESM
  • Interoperability (`import pkg from "cjs-pkg"`)
โ†’ What Topic Is Next: Next Topic 2.15: Callbacks and Error-First Callback Patterns
Guide โ†’

Legacy Node `(err, result) => {}` convention, Pyramid of Doom / Callback Hell, double-invocation hazards, and wrapping legacy callback APIs cleanly with `node:util`...

Subtopics Covered (8):
  • Legacy Node `(err
  • Result) => {}` convention
  • Pyramid of Doom / Callback Hell
โ†’ What Topic Is Next: Next Topic 2.16: Promises and Promise Chaining
Guide โ†’

Promise states (`pending` -> settled `fulfilled` or `rejected` โ€” immutable once settled!), `.then()`, `.catch()`, `.finally()`, and returning Promises inside `.then(...

Subtopics Covered (8):
  • Promise states (`pending` -> settled `fulfilled` or `rejected` โ€” immutable once settled!)
  • `.then()`
  • `.catch()`
โ†’ What Topic Is Next: Next Topic 2.17: async and await Execution Mechanics
Guide โ†’

How `async` always wraps return values in a Promise, how `await` suspends ONLY that async function (freeing the Node.js event loop for other requests!), and avoiding...

Subtopics Covered (8):
  • How `async` always wraps return values in a Promise
  • How `await` suspends ONLY that async function (freeing the Node.js event loop for other requests!)
  • Avoiding accidental sequential `await` bottlenecks!
โ†’ What Topic Is Next: Next Topic 2.18: Promise Combinators: all, allSettled, race and any
Guide โ†’

Exact failure semantics: `Promise.all` (fail-fast on 1st reject), `Promise.allSettled` (waits for all -> `{ status, value | reason }`), `Promise.race` (1st settled w...

Subtopics Covered (8):
  • Exact failure semantics: `Promise.all` (fail-fast on 1st reject)
  • `Promise.allSettled` (waits for all -> `{ status
  • Value | reason }`)
โ†’ What Topic Is Next: Next Topic 2.19: Event Loop and Task Queues
Guide โ†’

How single-threaded JS achieves high I/O concurrency: Call Stack empties -> drain ALL Microtasks -> pick next Macrotask -> drain Microtasks -> repeat

Subtopics Covered (8):
  • How single-threaded JS achieves high I/O concurrency: Call Stack empties -> drain ALL Microtasks -> pick next Macrotask -> drain Microtasks -> repeat
  • Production Backend Pitfall & Guardrail (Event Loop and Task Queues)
  • Hands-On TypeScript / Node.js Implementation (Event Loop and Task Queues)
โ†’ What Topic Is Next: Next Topic 2.20: Microtasks vs Macrotasks Ordering
Guide โ†’

Priority order in Node.js: Synchronous Stack -> `process.nextTick` -> Promise Microtasks (`.then`, `await` continuations, `queueMicrotask`) -> Macrotasks (`setTimeou...

Subtopics Covered (8):
  • Priority order in Node.js: Synchronous Stack -> `process.nextTick` -> Promise Microtasks (`.then`
  • `await` continuations
  • `queueMicrotask`) -> Macrotasks (`setTimeout`
โ†’ What Topic Is Next: Next Topic 2.21: Error Propagation in Asynchronous Code
Guide โ†’

`try / catch` around `await`, why `return fn()` vs `return await fn()` differs inside `try / catch` blocks (`return fn()` skips local `catch`!), and handling `unhand...

Subtopics Covered (8):
  • `try / catch` around `await`
  • Why `return fn()` vs `return await fn()` differs inside `try / catch` blocks (`return fn()` skips local `catch`!)
  • Handling `unhandledRejection`
โ†’ What Topic Is Next: Next Topic 2.22: Memory Management and Garbage Collection Fundamentals
Guide โ†’

V8 Young Generation (`Scavenge` Nursery) vs Old Generation (`Mark-Sweep-Compact`), root reachability, and the 4 classic Node.js memory leaks (unbounded in-memory cac...

Subtopics Covered (8):
  • V8 Young Generation (`Scavenge` Nursery) vs Old Generation (`Mark-Sweep-Compact`)
  • Root reachability
  • The 4 classic Node.js memory leaks (unbounded in-memory caches/arrays
โ†’ What Topic Is Next: Module 2 Capstone (Week 2 Lab Build: Async Concurrency Limiter, Retry Runner & Event Loop Tracer) โ†’ Next Topic 3.1: TypeScript Introduction, Installation and Build/Run Workflow

Implement a pure JavaScript `pLimit(concurrency)` task pool, exponential-backoff + full-jitter `withRetry(fn)` wrapper, `AbortSignal.timeout()` cancellable HTTP client, and deterministic microtask/macrotask trace suite.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Configure strict `tsconfig.json` (`strict: true`, `noUncheckedIndexedAccess: true`) catching `undefined`/null bugs at compile time.
โœ“ Model expressive backend domain states using Discriminated Unions, Type Guards, Interfaces, and Generics.
โœ“ Leverage built-in Utility Types (`Partial`, `Pick`, `Omit`, `Record`, `Readonly`) and `keyof`/`typeof` without duplicating DTO interfaces.
โœ“ Structure clean, fast-compiling multi-folder TypeScript Node.js backend projects.
Guide โ†’

Static structural type system + full type erasure at runtime, installing `typescript` + `@types/node`, running via `tsx` in dev vs `tsc` -> `node dist/server.js` in...

Subtopics Covered (8):
  • Static structural type system + full type erasure at runtime
  • Installing `typescript` + `@types/node`
  • Running via `tsx` in dev vs `tsc` -> `node dist/server.js` in production
โ†’ What Topic Is Next: Next Topic 3.2: Type Annotations and Type Inference
Guide โ†’

When TypeScript infers local constants/variables cleanly vs why explicit parameter and public function/method return types prevent accidental contract drift

Subtopics Covered (8):
  • When TypeScript infers local constants/variables cleanly vs why explicit parameter
  • Public function/method return types prevent accidental contract drift
  • Production Backend Pitfall & Guardrail (Type Annotations and Type Inference)
โ†’ What Topic Is Next: Next Topic 3.3: Primitive and Special Types: unknown, never, void and any
Guide โ†’

Why `unknown` is the type-safe top type (forces narrowing before property access!) vs unsafe `any` (disables type checking!), `never` for exhaustive checks, and `voi...

Subtopics Covered (8):
  • Why `unknown` is the type-safe top type (forces narrowing before property access!) vs unsafe `any` (disables type checking!)
  • `never` for exhaustive checks
  • `void`
โ†’ What Topic Is Next: Next Topic 3.4: Typed Arrays, Readonly Arrays, Tuples and Enums vs Const Unions
Guide โ†’

`string[]`, `readonly string[]` (prevents accidental `.push()`/`.sort()` mutation!), fixed-position tuples `[number, string]`, and why `as const` string literal unio...

Subtopics Covered (8):
  • `string[]`
  • `readonly string[]` (prevents accidental `.push()`/`.sort()` mutation!)
  • Fixed-position tuples `[number
โ†’ What Topic Is Next: Next Topic 3.5: Function Types, Call Signatures and Overloads
Guide โ†’

Function type aliases `(req: AuthReq) => Promise<ResponseDto>`, callback typing, and function overload signatures when return type depends on input mode

Subtopics Covered (8):
  • Function type aliases `(req: AuthReq) => Promise<ResponseDto>`
  • Callback typing
  • Function overload signatures when return type depends on input mode
โ†’ What Topic Is Next: Next Topic 3.6: Optional and Default Parameters in TypeScript
Guide โ†’

`limit?: number` (`number | undefined`) vs `limit = 20` (`number`), ordering required params before optional params, and `PaginationOptions = { page?: number; limit?...

Subtopics Covered (8):
  • `limit?: number` (`number | undefined`) vs `limit = 20` (`number`)
  • Ordering required params before optional params
  • `PaginationOptions = { page?: number
โ†’ What Topic Is Next: Next Topic 3.7: Union and Intersection Types + Discriminated Unions
Guide โ†’

Tagged **Discriminated Unions** (`type Result<T, E = string> = { ok: true; data: T } | { ok: false; error: E }`) where checking `if (!res.ok)` automatically narrows...

Subtopics Covered (8):
  • Tagged **Discriminated Unions** (`type Result<T
  • E = string> = { ok: true
  • Data: T } | { ok: false
โ†’ What Topic Is Next: Next Topic 3.8: Type Aliases vs Interfaces
Guide โ†’

Structural compatibility, `interface` `extends` & declaration merging (needed for augmenting `Express.Request.user`!) vs `type` aliases supporting Unions, Tuples, an...

Subtopics Covered (8):
  • Structural compatibility
  • `interface` `extends` & declaration merging (needed for augmenting `Express.Request.user`!) vs `type` aliases supporting Unions
  • Tuples
โ†’ What Topic Is Next: Next Topic 3.9: Type Narrowing and Custom Type Guards
Guide โ†’

Control-flow narrowing (`typeof`, `instanceof`, `"code" in err`, `Array.isArray`), user-defined type predicates (`function isAppError(e: unknown): e is AppError`), a...

Subtopics Covered (8):
  • Control-flow narrowing (`typeof`
  • `instanceof`
  • `"code" in err`
โ†’ What Topic Is Next: Next Topic 3.10: Literal Types and Template Literal Types
Guide โ†’

Exact literal types (`HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"`), template literal types (``EventKey = `${Domain}.${Action}` ``), and `satisfies` ope...

Subtopics Covered (8):
  • Exact literal types (`HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"`)
  • Template literal types (``EventKey = `${Domain}.${Action}` ``)
  • `satisfies` operator
โ†’ What Topic Is Next: Next Topic 3.11: Generics and Generic Constraints
Guide โ†’

Type parameters `<T>`, `<K, V>`, constraining `<T extends { readonly id: string }>`, and default generic parameters `<T = unknown>`

Subtopics Covered (8):
  • Type parameters `<T>`
  • `<K
  • V>`
โ†’ What Topic Is Next: Next Topic 3.12: Generic Functions, Interfaces and Classes
Guide โ†’

Designing `interface Repository<T, CreateInput, UpdateInput>` implemented identically by `InMemoryRepo` (unit tests), `PrismaRepo` (PostgreSQL), and `MongooseRepo` (...

Subtopics Covered (8):
  • Designing `interface Repository<T
  • CreateInput
  • UpdateInput>` implemented identically by `InMemoryRepo` (unit tests)
โ†’ What Topic Is Next: Next Topic 3.13: Classes and Access Modifiers in TypeScript
Guide โ†’

Constructor parameter properties (`constructor(private readonly repo: UserRepo) {}`), `public` / `private` / `protected` / `readonly`, and `override` (`noImplicitOve...

Subtopics Covered (8):
  • Constructor parameter properties (`constructor(private readonly repo: UserRepo) {}`)
  • `public` / `private` / `protected` / `readonly`
  • `override` (`noImplicitOverride`)
โ†’ What Topic Is Next: Next Topic 3.14: Inheritance and Abstract Classes
Guide โ†’

`abstract class BaseRepository<T>` sharing common pagination/logging helpers while enforcing `protected abstract mapRow(row: unknown): T` on concrete subclasses

Subtopics Covered (8):
  • `abstract class BaseRepository<T>` sharing common pagination/logging helpers while enforcing `protected abstract mapRow(row: unknown): T` on concrete subclasses
  • Production Backend Pitfall & Guardrail (Inheritance and Abstract Classes)
  • Hands-On TypeScript / Node.js Implementation (Inheritance and Abstract Classes)
โ†’ What Topic Is Next: Next Topic 3.15: Interfaces with Classes (Dependency Inversion)
Guide โ†’

`class RedisCacheService implements CachePort`, programming Services against `CachePort` / `MailPort` interfaces so infrastructure adapters remain pluggable

Subtopics Covered (8):
  • `class RedisCacheService implements CachePort`
  • Programming Services against `CachePort` / `MailPort` interfaces so infrastructure adapters remain pluggable
  • Production Backend Pitfall & Guardrail (Interfaces with Classes (Dependency Inversion))
โ†’ What Topic Is Next: Next Topic 3.16: Utility Types: Partial, Pick, Omit, Record, Required, Readonly
Guide โ†’

Deriving `PublicUser = Omit<UserEntity, "passwordHash">`, `UpdateEmployeeDto = Partial<Pick<Employee, "department" | "salary">>`, and `RoleMap = Record<Role, readonl...

Subtopics Covered (8):
  • Deriving `PublicUser = Omit<UserEntity
  • "passwordHash">`
  • `UpdateEmployeeDto = Partial<Pick<Employee
โ†’ What Topic Is Next: Next Topic 3.17: keyof, typeof and infer Fundamentals
Guide โ†’

Type-safe property selectors `<T, K extends keyof T>(obj: T, key: K): T[K]`, deriving types from runtime constants via `typeof`, and unwrapping Promise/function retu...

Subtopics Covered (8):
  • Type-safe property selectors `<T
  • K extends keyof T>(obj: T
  • Key: K): T[K]`
โ†’ What Topic Is Next: Next Topic 3.18: Modules, import type and Avoiding Circular Dependencies
Guide โ†’

`verbatimModuleSyntax` / `import type { User } from "./types.js"`, `.js` specifier resolution in `NodeNext`, and why barrel `index.ts` files cause circular-import `u...

Subtopics Covered (8):
  • `verbatimModuleSyntax` / `import type { User } from "./types.js"`
  • `.js` specifier resolution in `NodeNext`
  • Why barrel `index.ts` files cause circular-import `undefined` bugs in large backends
โ†’ What Topic Is Next: Next Topic 3.19: tsconfig.json Configuration for Modern Node.js
Guide โ†’

Recommended Node 22 LTS backend `tsconfig.json`: `"target": "ES2022"`, `"module": "NodeNext"`, `"moduleResolution": "NodeNext"`, `"rootDir": "src"`, `"outDir": "dist...

Subtopics Covered (8):
  • Recommended Node 22 LTS backend `tsconfig.json`: `"target": "ES2022"`
  • `"module": "NodeNext"`
  • `"moduleResolution": "NodeNext"`
โ†’ What Topic Is Next: Next Topic 3.20: Strict Type Checking Flags
Guide โ†’

`strict: true` (`strictNullChecks`, `noImplicitAny`, `strictBindCallApply`, `useUnknownInCatchVariables`) PLUS `noUncheckedIndexedAccess: true` (`arr[0]` is `T | und...

Subtopics Covered (8):
  • `strict: true` (`strictNullChecks`
  • `noImplicitAny`
  • `strictBindCallApply`
โ†’ What Topic Is Next: Next Topic 3.21: Type-Safe API Models (Request, Response & Error Contracts)
Guide โ†’

Typing Express `Request<Params, ResBody, ReqBody, ReqQuery>`, generic `ApiSuccess<T>` & `ApiErrorResponse` envelopes, and separating DB Models from Wire DTOs

Subtopics Covered (8):
  • Typing Express `Request<Params
  • ResBody
  • ReqBody
โ†’ What Topic Is Next: Next Topic 3.22: Production TypeScript Backend Project Structure
Guide โ†’

Organizing `src/{config, modules/{employees, departments}, shared/{errors, logger, middleware}, app.ts, server.ts}` + `tests/` for clarity and zero cross-layer coupl...

Subtopics Covered (8):
  • Organizing `src/{config
  • Modules/{employees
  • Departments}
โ†’ What Topic Is Next: Module 3 Capstone (Week 3 Lab Build: Strict TypeScript 5 Generic Repository & Result<T, E> Library) โ†’ Next Topic 4.1: Git Repository Creation and Identity Configuration

Create a strict TypeScript 5 (`strict: true`, `noUncheckedIndexedAccess: true`, zero `any`) library providing discriminated `Result<T, E>`, generic `InMemoryRepository<T extends { id: string }>`, custom type predicates, and mapped DTO utility types.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Collaborate cleanly using Git branches, rebasing, stashing, conflict resolution, and GitHub Pull Request reviews.
โœ“ Navigate Linux filesystems, permissions (`chmod`/`chown`), processes/signals, environment variables, SSH, and log pipelines confidently.
โœ“ Explain DNS, TCP/UDP, TLS/HTTPS, raw HTTP request/response headers, status codes, cookies/sessions, REST constraints, and CORS preflights.
โœ“ Deliver **Month 1 Project (Project 1): TypeScript-Based Command-Line Employee Management System**.
Guide โ†’

Distributed VCS snapshots, `git config --global user.name/email`, `init.defaultBranch main`, and `core.autocrlf` cross-OS line-ending hygiene

Subtopics Covered (8):
  • Distributed VCS snapshots
  • `git config --global user.name/email`
  • `init.defaultBranch main`
โ†’ What Topic Is Next: Next Topic 4.2: Core Git Workflow: init, status, add, commit, log and diff
Guide โ†’

Working Tree -> Staging Index -> Local Repo lifecycle, `git add -p` hunk staging, `git diff --staged`, `git log --oneline --graph`, and atomic Conventional Commits (...

Subtopics Covered (8):
  • Working Tree -> Staging Index -> Local Repo lifecycle
  • `git add -p` hunk staging
  • `git diff --staged`
โ†’ What Topic Is Next: Next Topic 4.3: Branching, Merging and Rebasing
Guide โ†’

Short-lived feature branches (`feat/employee-search`), fast-forward vs 3-way merge commits, interactive `git rebase main` linear history, and **NEVER rebasing shared...

Subtopics Covered (8):
  • Short-lived feature branches (`feat/employee-search`)
  • Fast-forward vs 3-way merge commits
  • Interactive `git rebase main` linear history
โ†’ What Topic Is Next: Next Topic 4.4: Undoing Safely: stash, reset and revert
Guide โ†’

`git stash push -u` / `pop`, `git restore`, `git reset --soft/--mixed` (local unpushed commits) vs `git revert <sha>` (safe compensating commit on shared branches!)

Subtopics Covered (8):
  • `git stash push -u` / `pop`
  • `git restore`
  • `git reset --soft/--mixed` (local unpushed commits) vs `git revert <sha>` (safe compensating commit on shared branches!)
โ†’ What Topic Is Next: Next Topic 4.5: Remote Collaboration: clone, fetch, pull and push
Guide โ†’

Origin remotes, why `git fetch` + inspect is safer than blind `git pull`, `git push -u origin <branch>`, and `--force-with-lease` safety

Subtopics Covered (8):
  • Origin remotes
  • Why `git fetch` + inspect is safer than blind `git pull`
  • `git push -u origin <branch>`
โ†’ What Topic Is Next: Next Topic 4.6: GitHub Pull Requests and Engineering Code Reviews
Guide โ†’

Structuring PR descriptions (Problem, Solution, Test Proof), line-by-line review comments, branch protection rules, and CI status checks (`tsc` + `jest`)

Subtopics Covered (8):
  • Structuring PR descriptions (Problem
  • Solution
  • Test Proof)
โ†’ What Topic Is Next: Next Topic 4.7: Merge Conflict Resolution
Guide โ†’

Reading `<<<<<<< HEAD`, `=======`, `>>>>>>> branch` conflict markers, resolving semantic TypeScript/package-lock conflicts, and verifying tests pass before completin...

Subtopics Covered (8):
  • Reading `<<<<<<< HEAD`
  • `=======`
  • `>>>>>>> branch` conflict markers
โ†’ What Topic Is Next: Next Topic 4.8: .gitignore Hygiene and Branching Strategies
Guide โ†’

Node/TS `.gitignore` (`node_modules/`, `dist/`, `coverage/`, `.env`, `.env.*`, `!.env.example`, `*.log`), Trunk-Based Development vs GitHub Flow

Subtopics Covered (8):
  • Node/TS `.gitignore` (`node_modules/`
  • `dist/`
  • `coverage/`
โ†’ What Topic Is Next: Next Topic 4.9: Linux Filesystem Hierarchy and Navigation
Guide โ†’

FHS layout (`/etc` config, `/var/log` logs, `/opt` & `/srv` apps, `/tmp`, `/proc`), `pwd`, `ls -lah`, `cd`, relative vs absolute paths

Subtopics Covered (8):
  • FHS layout (`/etc` config
  • `/var/log` logs
  • `/opt` & `/srv` apps
โ†’ What Topic Is Next: Next Topic 4.10: Linux File and Directory Operations
Guide โ†’

`mkdir -p`, `cp -r`, `mv`, `rm`, `touch`, `ln -s` symlinks, `find`, `tar -czf` / `-xzf`, `du -sh` & `df -h` disk-full diagnostics!

Subtopics Covered (8):
  • `mkdir -p`
  • `cp -r`
  • `mv`
โ†’ What Topic Is Next: Next Topic 4.11: Linux Permissions and Ownership (chmod & chown)
Guide โ†’

User/Group/Other bits (`r=4, w=2, x=1`), `chmod 600 ~/.ssh/id_ed25519`, `chmod 640 .env`, `chown -R nodeuser:nodegroup /srv/api`, and principle of least privilege (n...

Subtopics Covered (8):
  • User/Group/Other bits (`r=4
  • W=2
  • X=1`)
โ†’ What Topic Is Next: Next Topic 4.12: Linux Process Management and Signals
Guide โ†’

`ps aux`, `htop`/`top`, `ss -tulpn` / `lsof -i :3000` (finding what occupies port `3000`!), `SIGTERM` (`15`, graceful shutdown!) vs `SIGKILL` (`9`, immediate forced...

Subtopics Covered (8):
  • `ps aux`
  • `htop`/`top`
  • `ss -tulpn` / `lsof -i :3000` (finding what occupies port `3000`!)
โ†’ What Topic Is Next: Next Topic 4.13: Linux Environment Variables and Shell Configuration
Guide โ†’

`export KEY=VAL`, child-process inheritance, `env`/`printenv`, systemd `EnvironmentFile=/etc/api/.env`, and exit-status chaining (`&&`, `set -euo pipefail`)

Subtopics Covered (8):
  • `export KEY=VAL`
  • Child-process inheritance
  • `env`/`printenv`
โ†’ What Topic Is Next: Next Topic 4.14: SSH Fundamentals and Key-Based Remote Access
Guide โ†’

`ssh-keygen -t ed25519`, `~/.ssh/authorized_keys`, `~/.ssh/config` host aliases, `scp`/`rsync` file transfer, and disabling root password login in `/etc/ssh/sshd_con...

Subtopics Covered (8):
  • `ssh-keygen -t ed25519`
  • `~/.ssh/authorized_keys`
  • `~/.ssh/config` host aliases
โ†’ What Topic Is Next: Next Topic 4.15: Logs, Piping and Linux Production Troubleshooting
Guide โ†’

`journalctl -u api -f`, `tail -f`, `grep -E`, `jq` JSON log filtering (`cat app.log | jq "select(.level >= 50)"`), and standard `stdin`/`stdout`/`stderr` (`2>&1`) re...

Subtopics Covered (8):
  • `journalctl -u api -f`
  • `tail -f`
  • `grep -E`
โ†’ What Topic Is Next: Next Topic 4.16: Client-Server Request-Response Architecture
Guide โ†’

Stateless HTTP clients (browsers, mobile apps, webhook callers, microservices) -> Reverse Proxy (Nginx) -> Node.js Application -> Data/Cache Stores

Subtopics Covered (8):
  • Stateless HTTP clients (browsers
  • Mobile apps
  • Webhook callers
โ†’ What Topic Is Next: Next Topic 4.17: DNS and Domain Resolution
Guide โ†’

Recursive resolver -> Root -> TLD -> Authoritative nameserver, `A`, `AAAA`, `CNAME`, `TXT` (SPF/DKIM) records, TTL caching, and inspecting resolution with `dig` / `n...

Subtopics Covered (8):
  • Recursive resolver -> Root -> TLD -> Authoritative nameserver
  • `A`
  • `AAAA`
โ†’ What Topic Is Next: Next Topic 4.18: IP Addresses, Loopback, Subnets and Ports
Guide โ†’

IPv4 vs IPv6, `127.0.0.1` (loopback ONLY!) vs `0.0.0.0` (all interfaces โ€” required inside Docker containers!), ephemeral ports vs server ports (`80`, `443`, `3000`,...

Subtopics Covered (8):
  • IPv4 vs IPv6
  • `127.0.0.1` (loopback ONLY!) vs `0.0.0.0` (all interfaces โ€” required inside Docker containers!)
  • Ephemeral ports vs server ports (`80`
โ†’ What Topic Is Next: Next Topic 4.19: TCP vs UDP Fundamentals
Guide โ†’

TCP 3-Way Handshake (`SYN -> SYN-ACK -> ACK`), ordered reliable byte streams, flow/congestion control, `Keep-Alive` connection reuse vs connectionless low-overhead U...

Subtopics Covered (8):
  • TCP 3-Way Handshake (`SYN -> SYN-ACK -> ACK`)
  • Ordered reliable byte streams
  • Flow/congestion control
โ†’ What Topic Is Next: Next Topic 4.20: HTTP/1.1, HTTP/2 and HTTPS (TLS Termination)
Guide โ†’

Plaintext HTTP vs TLS 1.3 encrypted HTTPS (confidentiality, integrity & X.509 server authentication), HTTP/2 multiplexing, and terminating TLS at Nginx (`443 -> http...

Subtopics Covered (8):
  • Plaintext HTTP vs TLS 1.3 encrypted HTTPS (confidentiality
  • Integrity & X.509 server authentication)
  • HTTP/2 multiplexing
โ†’ What Topic Is Next: Next Topic 4.21: HTTP Request and Response Wire Structure
Guide โ†’

Start-line (`POST /api/v1/users HTTP/1.1`), Headers (`Host`, `Content-Type`, `Accept`, `Authorization`, `Content-Length`), blank CRLF separator, and Body stream

Subtopics Covered (8):
  • Start-line (`POST /api/v1/users HTTP/1.1`)
  • Headers (`Host`
  • `Content-Type`
โ†’ What Topic Is Next: Next Topic 4.22: HTTP Methods, Headers and Status Codes
Guide โ†’

Semantics & idempotency of `GET`, `HEAD`, `OPTIONS`, `POST`, `PUT`, `PATCH`, `DELETE`, caching/auth/security headers, and exact status codes (`200`, `201 Created + L...

Subtopics Covered (8):
  • Semantics & idempotency of `GET`
  • `HEAD`
  • `OPTIONS`
โ†’ What Topic Is Next: Next Topic 4.23: Cookies and Server-Side Sessions
Guide โ†’

`Set-Cookie` attributes (`HttpOnly` blocks JS XSS theft!, `Secure` HTTPS-only, `SameSite=Lax|Strict` CSRF defense, `Path`, `Max-Age`) and Redis-backed server session...

Subtopics Covered (8):
  • `Set-Cookie` attributes (`HttpOnly` blocks JS XSS theft!
  • `Secure` HTTPS-only
  • `SameSite=Lax|Strict` CSRF defense
โ†’ What Topic Is Next: Next Topic 4.24: JSON Serialization, Dates, BigInt and Payload Pitfalls
Guide โ†’

`JSON.stringify` / `JSON.parse` rules (`undefined`/functions/Symbols omitted, `Date` -> ISO-8601 string, `BigInt` throws `TypeError` without custom serializer!, circ...

Subtopics Covered (8):
  • `JSON.stringify` / `JSON.parse` rules (`undefined`/functions/Symbols omitted
  • `Date` -> ISO-8601 string
  • `BigInt` throws `TypeError` without custom serializer!
โ†’ What Topic Is Next: Next Topic 4.25: REST Architectural Principles
Guide โ†’

Statelessness, Uniform Interface, Resource identification via URIs, Manipulation through representations, Cacheability (`ETag` / `Cache-Control`), and Layered System

Subtopics Covered (8):
  • Statelessness
  • Uniform Interface
  • Resource identification via URIs
โ†’ What Topic Is Next: Next Topic 4.26: CORS (Cross-Origin Resource Sharing) Fundamentals
Guide โ†’

Browser Same-Origin Policy (`scheme + host + port`), Simple vs Preflight `OPTIONS` requests, `Access-Control-Allow-Origin` (explicit allowlist!), `Access-Control-All...

Subtopics Covered (8):
  • Browser Same-Origin Policy (`scheme + host + port`)
  • Simple vs Preflight `OPTIONS` requests
  • `Access-Control-Allow-Origin` (explicit allowlist!)
โ†’ What Topic Is Next: Module 4 Capstone (Project 1: TypeScript-Based Command-Line Employee Management System) โ†’ Next Topic 5.1: Introduction to Node.js and Backend Engineering Strengths

Before touching web frameworks or external databases, a strong backend engineer must master clean TypeScript domain modeling, OOP encapsulation, immutable data transformations, input validation, and crash-safe file I/O. Build a production-quality **TypeScript-Based Command-Line Employee Management System (`emp-cli`)** capable of managing employees, departments, compensation bands, attendance/leave summaries, multi-criteria search/sorting, and atomic JSON/CSV persistence from a Linux/Windows terminal.

โ€ข Strict TypeScript 5 modular CLI codebase (`src/domain`, `src/repositories`, `src/services`, `src/cli`)
โ€ข Atomic JSON persistence engine + CSV importer/exporter + NDJSON mutation audit trail
โ€ข 30+ automated unit/integration tests (`>= 85%` coverage) + comprehensive `README.md` command reference

Module Learning & Hands-On Objectives

โœ“ Explain V8, C++ bindings, `libuv`, OS async I/O (`epoll`/`kqueue`/`IOCP`), and the `libuv` worker threadpool clearly in senior backend interviews.
โœ“ Trace all 6 phases of the Node.js event loop and contrast `setImmediate` vs `setTimeout(..., 0)` inside I/O callbacks.
โœ“ Manage `process`, `Buffer`, environment variables, CLI flags, exit codes, and Node inspector profiling cleanly.
โœ“ Identify and prevent event-loop blocking anti-patterns before they degrade API tail latency.
Guide โ†’

Why event-driven non-blocking Node.js excels at I/O-intensive REST APIs, API gateways, real-time WebSockets, and streaming services (and when CPU-heavy tasks need `w...

Subtopics Covered (8):
  • Why event-driven non-blocking Node.js excels at I/O-intensive REST APIs
  • API gateways
  • Real-time WebSockets
โ†’ What Topic Is Next: Next Topic 5.2: Installing Node.js LTS, Version Managers and Lockfile Discipline
Guide โ†’

Active LTS releases (Node 22 LTS), `.nvmrc` / `"engines": { "node": ">=22.0.0" }`, semantic versioning (`^` vs `~`), and deterministic `npm ci` using `package-lock.j...

Subtopics Covered (8):
  • Active LTS releases (Node 22 LTS)
  • `.nvmrc` / `"engines": { "node": ">=22.0.0" }`
  • Semantic versioning (`^` vs `~`)
โ†’ What Topic Is Next: Next Topic 5.3: Node.js Layered Runtime Architecture
Guide โ†’

4-layer stack: Your TypeScript/JS App -> Node.js Standard Library (`node:fs`, `node:http`) -> C++ Node Bindings -> `V8` + `libuv` + `llhttp` + `OpenSSL` + `c-ares` +...

Subtopics Covered (8):
  • 4-layer stack: Your TypeScript/JS App -> Node.js Standard Library (`node:fs`
  • `node:http`) -> C++ Node Bindings -> `V8` + `libuv` + `llhttp` + `OpenSSL` + `c-ares` + `zlib`
  • Production Backend Pitfall & Guardrail (Node.js Layered Runtime Architecture)
โ†’ What Topic Is Next: Next Topic 5.4: V8 JavaScript Engine Internals
Guide โ†’

Parsing AST -> `Ignition` bytecode interpreter -> profiling hot functions -> `Sparkplug`/`Maglev`/`TurboFan` optimizing JIT machine code + Hidden Classes (Shapes) &...

Subtopics Covered (8):
  • Parsing AST -> `Ignition` bytecode interpreter -> profiling hot functions -> `Sparkplug`/`Maglev`/`TurboFan` optimizing JIT machine code + Hidden Classes (Shapes) & Inline Caches
  • Production Backend Pitfall & Guardrail (V8 JavaScript Engine Internals)
  • Hands-On TypeScript / Node.js Implementation (V8 JavaScript Engine Internals)
โ†’ What Topic Is Next: Next Topic 5.5: libuv and Asynchronous I/O Delegation
Guide โ†’

How `libuv` routes TCP/HTTP sockets directly to non-blocking OS kernel multiplexers (`epoll` on Linux, `kqueue` on macOS, `IOCP` on Windows) while delegating blockin...

Subtopics Covered (8):
  • How `libuv` routes TCP/HTTP sockets directly to non-blocking OS kernel multiplexers (`epoll` on Linux
  • `kqueue` on macOS
  • `IOCP` on Windows) while delegating blocking file/crypto/DNS calls to its C threadpool
โ†’ What Topic Is Next: Next Topic 5.6: Single-Threaded JS Execution Model and Event-Loop Safety
Guide โ†’

Why shared-memory mutex races disappear in single-threaded JS, YET logical async interleaving races (`read balance -> await -> write balance`) AND main-thread RegEx...

Subtopics Covered (8):
  • Why shared-memory mutex races disappear in single-threaded JS
  • YET logical async interleaving races (`read balance -> await -> write balance`)
  • Main-thread RegEx `ReDoS` blocking remain critical!
โ†’ What Topic Is Next: Next Topic 5.7: Event-Driven Architecture in Node.js
Guide โ†’

Observer pattern across Node servers, sockets, streams, and domain buses (`server.on("request")`, `stream.on("data")`, `process.on("SIGTERM")`)

Subtopics Covered (8):
  • Observer pattern across Node servers
  • Sockets
  • Streams
โ†’ What Topic Is Next: Next Topic 5.8: Non-Blocking vs Blocking I/O in Practice
Guide โ†’

`fs.readFileSync` / `crypto.pbkdf2Sync` / `execSync` (acceptable ONLY once before `server.listen()` at cold boot, NEVER inside request handlers!) vs non-blocking `fs...

Subtopics Covered (8):
  • `fs.readFileSync` / `crypto.pbkdf2Sync` / `execSync` (acceptable ONLY once before `server.listen()` at cold boot
  • NEVER inside request handlers!) vs non-blocking `fs/promises`
  • Production Backend Pitfall & Guardrail (Non-Blocking vs Blocking I/O in Practice)
โ†’ What Topic Is Next: Next Topic 5.9: Node.js Event Loop Phases in Detail
Guide โ†’

All 6 libuv phases in order: (1) `timers` (`setTimeout`/`setInterval`), (2) `pending callbacks`, (3) `idle, prepare`, (4) `poll` (retrieve new I/O events), (5) `chec...

Subtopics Covered (8):
  • All 6 libuv phases in order: (1) `timers` (`setTimeout`/`setInterval`)
  • (2) `pending callbacks`
  • (3) `idle
โ†’ What Topic Is Next: Next Topic 5.10: Call Stack, Callback Queue and Microtask Queue
Guide โ†’

Between EVERY event-loop phase transition/callback, Node drains `process.nextTick` queue followed by Promise Microtask queue before moving on

Subtopics Covered (8):
  • Between EVERY event-loop phase transition/callback
  • Node drains `process.nextTick` queue followed by Promise Microtask queue before moving on
  • Production Backend Pitfall & Guardrail (Call Stack, Callback Queue and Microtask Queue)
โ†’ What Topic Is Next: Next Topic 5.11: Timers, Intervals and Cancellation (AbortSignal & unref)
Guide โ†’

`setTimeout`, `setInterval`, `clearInterval`, `timers/promises` (`await setTimeout(100, undefined, { signal })`), and `timer.unref()` so background cache-sweep inter...

Subtopics Covered (8):
  • `setTimeout`
  • `setInterval`
  • `clearInterval`
โ†’ What Topic Is Next: Next Topic 5.12: Node.js Process Lifecycle, Signals and Uncaught Errors
Guide โ†’

`beforeExit` vs `exit` (sync only!), `SIGTERM` / `SIGINT` graceful handlers, `uncaughtException` & `unhandledRejection` (log fatal error, flush telemetry, and exit n...

Subtopics Covered (8):
  • `beforeExit` vs `exit` (sync only!)
  • `SIGTERM` / `SIGINT` graceful handlers
  • `uncaughtException` & `unhandledRejection` (log fatal error
โ†’ What Topic Is Next: Next Topic 5.13: Global Objects and Built-In Web-Standard Globals
Guide โ†’

Node 22 built-in standards: global `fetch`, `Headers`, `Request`, `Response`, `AbortController`, `structuredClone`, `crypto.randomUUID()`, `URL`, `TextEncoder`/`Text...

Subtopics Covered (8):
  • Node 22 built-in standards: global `fetch`
  • `Headers`
  • `Request`
โ†’ What Topic Is Next: Next Topic 5.14: process, Buffer and Global Hygiene
Guide โ†’

`process.cwd()`, `process.hrtime.bigint()` nanosecond timers, `process.memoryUsage()`, `Buffer.from(str, "utf8")` / base64url encoding, and never attaching request s...

Subtopics Covered (8):
  • `process.cwd()`
  • `process.hrtime.bigint()` nanosecond timers
  • `process.memoryUsage()`
โ†’ What Topic Is Next: Next Topic 5.15: Environment Variables and Native --env-file
Guide โ†’

Node 20.6+/22 native `node --env-file=.env dist/server.js`, why all `process.env.*` values are `string | undefined` (`process.env.DEBUG = "false"` is TRUTHY as a str...

Subtopics Covered (8):
  • Node 20.6+/22 native `node --env-file=.env dist/server.js`
  • Why all `process.env.*` values are `string | undefined` (`process.env.DEBUG = "false"` is TRUTHY as a string!)
  • Typed startup parsing
โ†’ What Topic Is Next: Next Topic 5.16: Command-Line Arguments (process.argv & util.parseArgs)
Guide โ†’

Native `node:util` `parseArgs({ options, allowPositionals })` building zero-dependency typed administrative/migration CLI scripts

Subtopics Covered (8):
  • Native `node:util` `parseArgs({ options
  • AllowPositionals })` building zero-dependency typed administrative/migration CLI scripts
  • Production Backend Pitfall & Guardrail (Command-Line Arguments (process.argv & util.parseArgs))
โ†’ What Topic Is Next: Next Topic 5.17: Node.js Debugging and Diagnostic Reports
Guide โ†’

`node --inspect`, VS Code Attach/Launch configs, `node --trace-warnings`, and `process.report.writeReport()` diagnostic JSON dumps on fatal crashes

Subtopics Covered (8):
  • `node --inspect`
  • VS Code Attach/Launch configs
  • `node --trace-warnings`
โ†’ What Topic Is Next: Next Topic 5.18: Node.js Performance Fundamentals (Event-Loop Lag Monitoring)
Guide โ†’

`node:perf_hooks` `monitorEventLoopDelay({ resolution: 20 })` tracking `p50`/`p99` event-loop lag in milliseconds and keeping JSON payloads & sync work bounded

Subtopics Covered (8):
  • `node:perf_hooks` `monitorEventLoopDelay({ resolution: 20 })` tracking `p50`/`p99` event-loop lag in milliseconds
  • Keeping JSON payloads & sync work bounded
  • Production Backend Pitfall & Guardrail (Node.js Performance Fundamentals (Event-Loop Lag Monitoring))
โ†’ What Topic Is Next: Module 5 Capstone (Week 5 Lab Build: Raw Node.js HTTP Router, EventEmitter Bus & Crypto Hash CLI) โ†’ Next Topic 6.1: CommonJS Module System Internals

Without Express, build a raw `node:http` JSON API router supporting URL path params, graceful `SIGTERM` connection draining, typed `EventEmitter` audit hooks, and non-blocking `node:crypto` `scrypt`/SHA-256 hashing.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Use `node:` prefixed core modules (`fs/promises`, `path`, `crypto`, `events`, `http`, `url`) idiomatically and securely.
โœ“ Process multi-gigabyte files and transforms in constant `O(1)` memory using Streams, `pipeline()`, and proper backpressure handling.
โœ“ Scale CPU-bound and multi-core workloads using `worker_threads`, `child_process.execFile`/`spawn`, `cluster`, and `UV_THREADPOOL_SIZE`.
โœ“ Implement zero-dropped-request graceful process shutdown draining HTTP keep-alive sockets and database pools.
Guide โ†’

How Node wraps CJS files `(function(exports, require, module, __filename, __dirname) { ... })`, synchronous load semantics, and `exports` vs `module.exports` reassig...

Subtopics Covered (8):
  • How Node wraps CJS files `(function(exports
  • Require
  • Module
โ†’ What Topic Is Next: Next Topic 6.2: ES Module System in Node.js
Guide โ†’

`"type": "module"` in `package.json`, `.mjs`/`.cjs` explicit extensions, asynchronous 3-phase loading (`Construction -> Instantiation -> Evaluation`), and Top-Level...

Subtopics Covered (8):
  • `"type": "module"` in `package.json`
  • `.mjs`/`.cjs` explicit extensions
  • Asynchronous 3-phase loading (`Construction -> Instantiation -> Evaluation`)
โ†’ What Topic Is Next: Next Topic 6.3: Module Exports, Imports and Subpath Exports
Guide โ†’

Named exports (preferred for refactoring & explicit contracts) vs default exports, and `package.json` `"exports"` encapsulating internal private files

Subtopics Covered (8):
  • Named exports (preferred for refactoring & explicit contracts) vs default exports
  • `package.json` `"exports"` encapsulating internal private files
  • Production Backend Pitfall & Guardrail (Module Exports, Imports and Subpath Exports)
โ†’ What Topic Is Next: Next Topic 6.4: Module Resolution and Singleton Caching
Guide โ†’

How Node caches evaluated modules by resolved real file path (case-sensitivity trap: `./User.js` vs `./user.js` on macOS/Windows loads TWICE, then crashes on Linux!!...

Subtopics Covered (8):
  • How Node caches evaluated modules by resolved real file path (case-sensitivity trap: `./User.js` vs `./user.js` on macOS/Windows loads TWICE
  • Then crashes on Linux!!)
  • Production Backend Pitfall & Guardrail (Module Resolution and Singleton Caching)
โ†’ What Topic Is Next: Next Topic 6.5: File System Module (node:fs/promises)
Guide โ†’

`readFile`, `writeFile`, atomic temp-write + `rename`, `mkdir({ recursive: true })`, `stat`, `opendir` async directory streaming, and `FileHandle` cleanup

Subtopics Covered (8):
  • `readFile`
  • `writeFile`
  • Atomic temp-write + `rename`
โ†’ What Topic Is Next: Next Topic 6.6: Path Module and Directory Traversal Defense (node:path)
Guide โ†’

`path.join`, `path.resolve`, `path.basename`, `path.extname`, `path.sep` (`\` vs `/`), and verifying `resolved.startsWith(allowedRoot + path.sep)`!

Subtopics Covered (8):
  • `path.join`
  • `path.resolve`
  • `path.basename`
โ†’ What Topic Is Next: Next Topic 6.7: OS Module Diagnostics (node:os)
Guide โ†’

`os.availableParallelism()` (cgroup/container-aware CPU count in Node 19.4+ โ€” better than `os.cpus().length` inside Docker!), `os.freemem()`, `os.totalmem()`, `os.lo...

Subtopics Covered (8):
  • `os.availableParallelism()` (cgroup/container-aware CPU count in Node 19.4+ โ€” better than `os.cpus().length` inside Docker!)
  • `os.freemem()`
  • `os.totalmem()`
โ†’ What Topic Is Next: Next Topic 6.8: Raw HTTP and HTTPS Modules (node:http / node:https)
Guide โ†’

Building a framework-free `http.createServer((req, res) => ...)` understanding `IncomingMessage` (Readable stream!) and `ServerResponse` (Writable stream!) + `header...

Subtopics Covered (8):
  • Building a framework-free `http.createServer((req
  • Res) => ...)` understanding `IncomingMessage` (Readable stream!)
  • `ServerResponse` (Writable stream!) + `headersTimeout` / `requestTimeout` Slowloris protection!
โ†’ What Topic Is Next: Next Topic 6.9: Events and Typed EventEmitter (node:events)
Guide โ†’

`on`, `once`, `off`, `emit` (synchronous listener invocation!), special `"error"` event (crashes process if unhandled!), and `events.once(emitter, "ready")` Promise...

Subtopics Covered (8):
  • `on`
  • `once`
  • `off`
โ†’ What Topic Is Next: Next Topic 6.10: Crypto Module (node:crypto)
Guide โ†’

`randomBytes`, `randomUUID`, `createHash("sha256")`, `createHmac("sha256", secret)`, `scrypt` password KDF, AES-256-GCM authenticated encryption, and **`timingSafeEq...

Subtopics Covered (8):
  • `randomBytes`
  • `randomUUID`
  • `createHash("sha256")`
โ†’ What Topic Is Next: Next Topic 6.11: WHATWG URL Module (node:url)
Guide โ†’

`new URL(input, base)`, safe hostname/protocol validation (`url.protocol === "https:"`), automatic encoding, and avoiding legacy deprecated `url.parse()`

Subtopics Covered (8):
  • `new URL(input
  • Base)`
  • Safe hostname/protocol validation (`url.protocol === "https:"`)
โ†’ What Topic Is Next: Next Topic 6.12: Query Strings and URLSearchParams
Guide โ†’

Building and parsing query parameters via standard `URLSearchParams` (`append` repeated keys, `getAll`, automatic UTF-8 percent-encoding)

Subtopics Covered (8):
  • Building
  • Parsing query parameters via standard `URLSearchParams` (`append` repeated keys
  • `getAll`
โ†’ What Topic Is Next: Next Topic 6.13: Buffer and Binary Data
Guide โ†’

Fixed-size raw byte allocations outside V8 JS string heap (`Uint8Array` subclass), `Buffer.from`, `Buffer.alloc` (zero-filled safe!) vs `Buffer.allocUnsafe` (uniniti...

Subtopics Covered (8):
  • Fixed-size raw byte allocations outside V8 JS string heap (`Uint8Array` subclass)
  • `Buffer.from`
  • `Buffer.alloc` (zero-filled safe!) vs `Buffer.allocUnsafe` (uninitialized memory leak hazard!)
โ†’ What Topic Is Next: Next Topic 6.14: Streams Architecture Overview
Guide โ†’

Processing unbounded data chunk-by-chunk (`default highWaterMark = 64 KB` for `fs` streams, `16 KB` general; `16` objects in `objectMode`) instead of buffering entir...

Subtopics Covered (8):
  • Processing unbounded data chunk-by-chunk (`default highWaterMark = 64 KB` for `fs` streams
  • `16 KB` general
  • `16` objects in `objectMode`) instead of buffering entire files in RAM
โ†’ What Topic Is Next: Next Topic 6.15: Readable Streams and Async Iteration
Guide โ†’

Flowing vs Paused modes, `Readable.from(asyncGenerator)`, and modern `for await (const chunk of readable)` clean async iteration

Subtopics Covered (8):
  • Flowing vs Paused modes
  • `Readable.from(asyncGenerator)`
  • Modern `for await (const chunk of readable)` clean async iteration
โ†’ What Topic Is Next: Next Topic 6.16: Writable Streams
Guide โ†’

`writable.write(chunk)` boolean return (`false` means internal buffer reached `highWaterMark` โ€” wait for `"drain"`!), `writable.end()`, and `"finish"` vs `"close"`

Subtopics Covered (8):
  • `writable.write(chunk)` boolean return (`false` means internal buffer reached `highWaterMark` โ€” wait for `"drain"`!)
  • `writable.end()`
  • `"finish"` vs `"close"`
โ†’ What Topic Is Next: Next Topic 6.17: Duplex and Transform Streams
Guide โ†’

`Duplex` (independent read/write sides, e.g. TCP `net.Socket`) vs `Transform` (output computed from input, e.g. `zlib.createGzip()`, `crypto.createCipheriv`, custom...

Subtopics Covered (8):
  • `Duplex` (independent read/write sides
  • E.g. TCP `net.Socket`) vs `Transform` (output computed from input
  • E.g. `zlib.createGzip()`
โ†’ What Topic Is Next: Next Topic 6.18: Piping and stream/promises pipeline()
Guide โ†’

Why legacy `a.pipe(b).pipe(c)` LEAKS file descriptors when `b` or `c` errors/disconnects vs **`await pipeline(a, b, c)`** (`node:stream/promises`) which destroys ALL...

Subtopics Covered (8):
  • Why legacy `a.pipe(b).pipe(c)` LEAKS file descriptors when `b` or `c` errors/disconnects vs **`await pipeline(a
  • C)`** (`node:stream/promises`) which destroys ALL streams cleanly on any error or client disconnect!
  • Production Backend Pitfall & Guardrail (Piping and stream/promises pipeline())
โ†’ What Topic Is Next: Next Topic 6.19: Backpressure Mechanics in Depth
Guide โ†’

How `pipeline()` automatically pauses a fast `500 MB/s` disk/DB `Readable` whenever a slow `2 MB/s` mobile 4G HTTP `Writable` fills its `highWaterMark`, resuming on...

Subtopics Covered (8):
  • How `pipeline()` automatically pauses a fast `500 MB/s` disk/DB `Readable` whenever a slow `2 MB/s` mobile 4G HTTP `Writable` fills its `highWaterMark`
  • Resuming on `"drain"`
  • Production Backend Pitfall & Guardrail (Backpressure Mechanics in Depth)
โ†’ What Topic Is Next: Next Topic 6.20: File Streaming and Multi-GB Large-File Processing
Guide โ†’

Combining `createReadStream`, `readline.createInterface({ crlfDelay: Infinity })`, streaming SHA-256 checksums, and `createGzip` for large CSV/log ingestion

Subtopics Covered (8):
  • Combining `createReadStream`
  • `readline.createInterface({ crlfDelay: Infinity })`
  • Streaming SHA-256 checksums
โ†’ What Topic Is Next: Next Topic 6.21: Child Processes (execFile & spawn vs Unsafe exec)
Guide โ†’

`execFile` (no shell spawned โ€” immune to `; rm -rf` shell metacharacter injection!) & streaming `spawn` vs why `exec(cmdString)` with user input is a critical RCE vu...

Subtopics Covered (8):
  • `execFile` (no shell spawned โ€” immune to `
  • Rm -rf` shell metacharacter injection!) & streaming `spawn` vs why `exec(cmdString)` with user input is a critical RCE vulnerability!
  • Production Backend Pitfall & Guardrail (Child Processes (execFile & spawn vs Unsafe exec))
โ†’ What Topic Is Next: Next Topic 6.22: Worker Threads for CPU-Intensive Tasks (node:worker_threads)
Guide โ†’

Isolated V8 isolates sharing one OS process (`Worker`, `parentPort`, `workerData`, transferable `ArrayBuffer`s), bounded worker pools (`piscina`), keeping main HTTP...

Subtopics Covered (8):
  • Isolated V8 isolates sharing one OS process (`Worker`
  • `parentPort`
  • `workerData`
โ†’ What Topic Is Next: Next Topic 6.23: Cluster Module for Multi-Core Scaling (node:cluster)
Guide โ†’

Primary process forking `os.availableParallelism()` worker processes sharing port `:3000` via OS round-robin accept, auto-respawning crashed workers with backoff, vs...

Subtopics Covered (8):
  • Primary process forking `os.availableParallelism()` worker processes sharing port `:3000` via OS round-robin accept
  • Auto-respawning crashed workers with backoff
  • Vs container horizontal replicas
โ†’ What Topic Is Next: Next Topic 6.24: Thread Pools and Concurrency Tuning (UV_THREADPOOL_SIZE)
Guide โ†’

Tuning `UV_THREADPOOL_SIZE` (default `4`, max `1024`, MUST be set in env BEFORE first threadpool call!) when heavy `crypto.scrypt` / `bcrypt` / `zlib` / `fs` workloa...

Subtopics Covered (8):
  • Tuning `UV_THREADPOOL_SIZE` (default `4`
  • Max `1024`
  • MUST be set in env BEFORE first threadpool call!) when heavy `crypto.scrypt` / `bcrypt` / `zlib` / `fs` workloads queue up
โ†’ What Topic Is Next: Next Topic 6.25: Graceful Process Shutdown
Guide โ†’

Complete zero-downtime shutdown sequence on `SIGTERM`: (1) Flip `/readyz` to `503` -> (2) `server.close()` (stop new connections, finish in-flight HTTP requests) ->...

Subtopics Covered (8):
  • Complete zero-downtime shutdown sequence on `SIGTERM`: (1) Flip `/readyz` to `503` -> (2) `server.close()` (stop new connections
  • Finish in-flight HTTP requests) -> (3) Close BullMQ workers -> (4) Disconnect Prisma/Mongoose/Redis -> (5) `process.exit(0)` (with hard `15s` force-exit timer!)
  • Production Backend Pitfall & Guardrail (Graceful Process Shutdown)
โ†’ What Topic Is Next: Module 6 Capstone (Week 6 Lab Build: Backpressure-Safe 1M-Row CSV Stream Transformer & NDJSON Logger) โ†’ Next Topic 7.1: Introduction to Express.js and Minimalist Request Pipeline

Build a constant-RAM (`< 60 MB` RSS) `stream.pipeline()` processor transforming multi-hundred-MB CSV files into validated gzip-compressed `.ndjson.gz` shards with dead-letter row quarantine and `AsyncLocalStorage` request correlation IDs.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Separate `createApp()` (`app.ts`) from `server.listen()` (`server.ts`) so Supertest tests run in-memory without port conflicts.
โœ“ Compose application, router, third-party, custom, and 4-argument error-handling middleware in exact execution order.
โœ“ Forward rejected async route Promises reliably into centralized RFC-style JSON error envelopes.
โœ“ Implement `/api/v1` versioning, pagination, filtering, sorting, search, and interactive Swagger/OpenAPI 3.1 docs.
Guide โ†’

How Express wraps `node:http` with routing tables, `req`/`res` prototype helpers, and a linear middleware stack

Subtopics Covered (8):
  • How Express wraps `node:http` with routing tables
  • `req`/`res` prototype helpers
  • A linear middleware stack
โ†’ What Topic Is Next: Next Topic 7.2: Express Installation, TypeScript Types and Express 5 Readiness
Guide โ†’

Installing `express` + `@types/express`, strict `tsconfig.json`, and how Express 5 automatically forwards rejected `async` route Promises to error middleware (vs `as...

Subtopics Covered (8):
  • Installing `express` + `@types/express`
  • Strict `tsconfig.json`
  • How Express 5 automatically forwards rejected `async` route Promises to error middleware (vs `asyncHandler` wrapper in Express 4!)
โ†’ What Topic Is Next: Next Topic 7.3: Creating an HTTP Server Cleanly (app.ts vs server.ts)
Guide โ†’

Wiring `const server = http.createServer(app)` with explicit `keepAliveTimeout` (`65s` > Nginx/ALB `60s` idle timeout to prevent `502` race conditions!) and `headers...

Subtopics Covered (8):
  • Wiring `const server = http.createServer(app)` with explicit `keepAliveTimeout` (`65s` > Nginx/ALB `60s` idle timeout to prevent `502` race conditions!)
  • `headersTimeout`
  • Production Backend Pitfall & Guardrail (Creating an HTTP Server Cleanly (app.ts vs server.ts))
โ†’ What Topic Is Next: Next Topic 7.4: Scalable Express Application Folder Structure
Guide โ†’

Feature-first modular layout: `src/modules/employees/{employee.routes.ts, employee.controller.ts, employee.service.ts, employee.repository.ts, employee.schema.ts}`

Subtopics Covered (8):
  • Feature-first modular layout: `src/modules/employees/{employee.routes.ts
  • Employee.controller.ts
  • Employee.service.ts
โ†’ What Topic Is Next: Next Topic 7.5: Routing and Route Parameters (req.params)
Guide โ†’

Route methods (`get`, `post`, `put`, `patch`, `delete`), `:id` parameters, route registration order (specific `/employees/stats` MUST come BEFORE `/employees/:id`!),...

Subtopics Covered (8):
  • Route methods (`get`
  • `post`
  • `put`
โ†’ What Topic Is Next: Next Topic 7.6: Query Parameters and Safe Coercion (req.query)
Guide โ†’

Why every `req.query.*` arrives as `string | string[] | ParsedQs | undefined` (`?role=a&role=b` becomes an ARRAY `["a", "b"]` โ€” HTTP Parameter Pollution `HPP`!)

Subtopics Covered (8):
  • Why every `req.query.*` arrives as `string | string[] | ParsedQs | undefined` (`?role=a&role=b` becomes an ARRAY `["a"
  • "b"]` โ€” HTTP Parameter Pollution `HPP`!)
  • Production Backend Pitfall & Guardrail (Query Parameters and Safe Coercion (req.query))
โ†’ What Topic Is Next: Next Topic 7.7: Express Request and Response Objects
Guide โ†’

`req.headers`, `req.get("Idempotency-Key")`, `req.ip`, `res.status(201).location(...).json(...)`, `res.set()`, `res.sendStatus(204)`, and `res.headersSent` guard

Subtopics Covered (8):
  • `req.headers`
  • `req.get("Idempotency-Key")`
  • `req.ip`
โ†’ What Topic Is Next: Next Topic 7.8: Request Body Parsing and Payload Size Limits
Guide โ†’

`express.json({ limit: "100kb", strict: true })`, `express.urlencoded({ extended: false, limit: "100kb" })`, and handling malformed JSON `SyntaxError` (`400 Bad Requ...

Subtopics Covered (8):
  • `express.json({ limit: "100kb"
  • Strict: true })`
  • `express.urlencoded({ extended: false
โ†’ What Topic Is Next: Next Topic 7.9: Middleware Architecture and Execution Order
Guide โ†’

Exact production middleware order: (1) `requestId` + `pino-http` logger -> (2) `helmet` + `cors` -> (3) Rate limiter -> (4) Body parsers -> (5) `/api/v1` Routers ->...

Subtopics Covered (8):
  • Exact production middleware order: (1) `requestId` + `pino-http` logger -> (2) `helmet` + `cors` -> (3) Rate limiter -> (4) Body parsers -> (5) `/api/v1` Routers -> (6) `404` catch-all -> (7) 4-arg Global Error Handler!
  • Production Backend Pitfall & Guardrail (Middleware Architecture and Execution Order)
  • Hands-On TypeScript / Node.js Implementation (Middleware Architecture and Execution Order)
โ†’ What Topic Is Next: Next Topic 7.10: Application-Level Middleware (app.use)
Guide โ†’

Cross-cutting concerns (`X-Request-Id` correlation header propagation/generation, response-time header, maintenance gate)

Subtopics Covered (8):
  • Cross-cutting concerns (`X-Request-Id` correlation header propagation/generation
  • Response-time header
  • Maintenance gate)
โ†’ What Topic Is Next: Next Topic 7.11: Router-Level Middleware (express.Router)
Guide โ†’

Modular sub-routers, `Router({ mergeParams: true })` for nested `/departments/:deptId/employees`, and scoping `authenticate` + `authorize("ADMIN")` to protected rout...

Subtopics Covered (8):
  • Modular sub-routers
  • `Router({ mergeParams: true })` for nested `/departments/:deptId/employees`
  • Scoping `authenticate` + `authorize("ADMIN")` to protected router trees
โ†’ What Topic Is Next: Next Topic 7.12: Built-In Express Middleware
Guide โ†’

`express.json()`, `express.urlencoded()`, `express.raw({ type: "application/json" })` (essential for Stripe/Razorpay webhook HMAC verification!), and why pure backen...

Subtopics Covered (8):
  • `express.json()`
  • `express.urlencoded()`
  • `express.raw({ type: "application/json" })` (essential for Stripe/Razorpay webhook HMAC verification!)
โ†’ What Topic Is Next: Next Topic 7.13: Essential Third-Party Middleware
Guide โ†’

`helmet` (security headers), `cors` (explicit allowlist), `compression` (gzip/brotli above threshold), `express-rate-limit`, `cookie-parser`, and `pino-http`

Subtopics Covered (8):
  • `helmet` (security headers)
  • `cors` (explicit allowlist)
  • `compression` (gzip/brotli above threshold)
โ†’ What Topic Is Next: Next Topic 7.14: Authoring Custom Middleware
Guide โ†’

Parameterized middleware factories (`validateBody(schema)`, `requirePermission("employees:write")`, `cacheResponse(ttlSeconds)`)

Subtopics Covered (8):
  • Parameterized middleware factories (`validateBody(schema)`
  • `requirePermission("employees:write")`
  • `cacheResponse(ttlSeconds)`)
โ†’ What Topic Is Next: Next Topic 7.15: Route Handlers and Transport Layer Discipline
Guide โ†’

What belongs in an Express handler (parse/extract HTTP -> call Service -> map HTTP status & DTO) vs what NEVER belongs in a handler (SQL/Prisma queries, password has...

Subtopics Covered (8):
  • What belongs in an Express handler (parse/extract HTTP -> call Service -> map HTTP status & DTO) vs what NEVER belongs in a handler (SQL/Prisma queries
  • Password hashing
  • Business math!)
โ†’ What Topic Is Next: Next Topic 7.16: Typed Controllers in TypeScript
Guide โ†’

Class controllers vs factory object controllers (`createEmployeeController(service)`) avoiding `this` binding pitfalls completely!

Subtopics Covered (8):
  • Class controllers vs factory object controllers (`createEmployeeController(service)`) avoiding `this` binding pitfalls completely!
  • Production Backend Pitfall & Guardrail (Typed Controllers in TypeScript)
  • Hands-On TypeScript / Node.js Implementation (Typed Controllers in TypeScript)
โ†’ What Topic Is Next: Next Topic 7.17: Error-Handling Middleware (4-Argument Signature)
Guide โ†’

Why Express identifies error middleware STRICTLY by `fn.length === 4` (`(err, req, res, next)` โ€” removing unused `_next` parameter turns it into a normal 3-arg middl...

Subtopics Covered (8):
  • Why Express identifies error middleware STRICTLY by `fn.length === 4` (`(err
  • Req
  • Res
โ†’ What Topic Is Next: Next Topic 7.18: Centralized Exception Hierarchy
Guide โ†’

`AppError(message, statusCode, errorCode, isOperational, details)` distinguishing expected client errors (`400`, `401`, `403`, `404`, `409`, `422`) from unexpected p...

Subtopics Covered (8):
  • `AppError(message
  • StatusCode
  • ErrorCode
โ†’ What Topic Is Next: Next Topic 7.19: Asynchronous Error Handling End-to-End
Guide โ†’

Ensuring every async middleware, route handler, event callback, and stream pipeline forwards errors to `next(err)` without hanging sockets or crashing the worker

Subtopics Covered (8):
  • Ensuring every async middleware
  • Route handler
  • Event callback
โ†’ What Topic Is Next: Next Topic 7.20: HTTP Status Codes in Express APIs
Guide โ†’

Consistent mapping: `POST` create -> `201`, `GET`/`PATCH` -> `200`, `DELETE` -> `204`, async job accepted -> `202`, validation -> `422`/`400`, duplicate unique key -...

Subtopics Covered (8):
  • Consistent mapping: `POST` create -> `201`
  • `GET`/`PATCH` -> `200`
  • `DELETE` -> `204`
โ†’ What Topic Is Next: Next Topic 7.21: Standardized JSON Response Envelopes
Guide โ†’

Consistent `{ success: true, data, meta? }` and RFC 9457 Problem Details `{ type, title, status, detail, instance, requestId, errors? }` across every service

Subtopics Covered (8):
  • Consistent `{ success: true
  • Data
  • Meta? }`
โ†’ What Topic Is Next: Next Topic 7.22: Request Validation Architecture
Guide โ†’

Validating `params`, `query`, and `body` BEFORE controllers run, stripping unknown fields (preventing mass assignment!), and returning field-level `errors: [{ field,...

Subtopics Covered (8):
  • Validating `params`
  • `query`
  • `body` BEFORE controllers run
โ†’ What Topic Is Next: Next Topic 7.23: API Versioning in Express
Guide โ†’

Mounting `app.use("/api/v1", v1Router)` vs `Accept-Version` header routing, maintaining `v1` response adapters while introducing breaking schema changes in `/api/v2`

Subtopics Covered (8):
  • Mounting `app.use("/api/v1"
  • V1Router)` vs `Accept-Version` header routing
  • Maintaining `v1` response adapters while introducing breaking schema changes in `/api/v2`
โ†’ What Topic Is Next: Next Topic 7.24: API Pagination Implementation
Guide โ†’

Implementing bounded `?page=1&limit=20` (`maxLimit = 100`) returning `{ items, page, limit, total, totalPages, hasNextPage }` AND cursor `?cursor=...&limit=20`

Subtopics Covered (8):
  • Implementing bounded `?page=1&limit=20` (`maxLimit = 100`) returning `{ items
  • Page
  • Limit
โ†’ What Topic Is Next: Next Topic 7.25: Filtering, Sorting and Search Endpoints
Guide โ†’

Whitelisting allowed filter fields (`department`, `status`, `minSalary`, `maxSalary`), whitelisting `sortBy` columns (`createdAt`, `salary`, `name`) + `sortOrder` (`...

Subtopics Covered (8):
  • Whitelisting allowed filter fields (`department`
  • `status`
  • `minSalary`
โ†’ What Topic Is Next: Next Topic 7.26: API Documentation Using Swagger and OpenAPI 3.1
Guide โ†’

Authoring OpenAPI 3.1 specs (`paths`, `components.schemas`, `securitySchemes: bearerAuth`), serving interactive `/api/docs` via `swagger-ui-express`, and keeping doc...

Subtopics Covered (8):
  • Authoring OpenAPI 3.1 specs (`paths`
  • `components.schemas`
  • `securitySchemes: bearerAuth`)
โ†’ What Topic Is Next: Module 7 Capstone (Week 7 Lab Build: Layered Express.js + TypeScript + Zod Task & Ticket API) โ†’ Next Topic 8.1: REST Principles and Resource Modelling

Build a `Controller -> Service -> Repository` Express.js + TypeScript REST API featuring `Zod` `body`/`query`/`params` validation middleware, centralized RFC 9457 Problem Details error handling, cursor pagination, and `/api/v1` versioning.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Design clean, idempotent, evolvable REST resource contracts passing senior API design reviews.
โœ“ Architect decoupled `Controller -> Service -> Repository` TypeScript backends using clean constructor Dependency Injection.
โœ“ Enforce fail-fast startup environment validation, structured `Pino` JSON logging with `AsyncLocalStorage` correlation IDs, and automated Postman collections.
โœ“ Build and defend **Month 2 Project (Project 2): Production-Style Employee Management REST API**.
Guide โ†’

Turning imperative business actions (`"promote employee"`, `"deactivate account"`, `"issue refund"`) into clean noun sub-resources (`POST /employees/{id}/promotions`...

Subtopics Covered (8):
  • Turning imperative business actions (`"promote employee"`
  • `"deactivate account"`
  • `"issue refund"`) into clean noun sub-resources (`POST /employees/{id}/promotions`
โ†’ What Topic Is Next: Next Topic 8.2: REST vs RPC (gRPC / tRPC) Trade-Offs
Guide โ†’

When public/partner/CRUD HTTP resource APIs favor REST + OpenAPI vs when ultra-low-latency internal service-to-service binary calls favor `gRPC` + Protobuf

Subtopics Covered (8):
  • When public/partner/CRUD HTTP resource APIs favor REST + OpenAPI vs when ultra-low-latency internal service-to-service binary calls favor `gRPC` + Protobuf
  • Production Backend Pitfall & Guardrail (REST vs RPC (gRPC / tRPC) Trade-Offs)
  • Hands-On TypeScript / Node.js Implementation (REST vs RPC (gRPC / tRPC) Trade-Offs)
โ†’ What Topic Is Next: Next Topic 8.3: Resource Naming Conventions
Guide โ†’

Lowercase kebab-case plural nouns (`/api/v1/purchase-orders`, never `/getPurchaseOrders` or `/Purchase_Order`), consistent `:id` path variables, and query params for...

Subtopics Covered (8):
  • Lowercase kebab-case plural nouns (`/api/v1/purchase-orders`
  • Never `/getPurchaseOrders` or `/Purchase_Order`)
  • Consistent `:id` path variables
โ†’ What Topic Is Next: Next Topic 8.4: HTTP Methods and Idempotency Keys
Guide โ†’

Natural idempotency of `GET`, `PUT`, `DELETE` vs non-idempotent `POST` โ€” and making `POST /orders` or `POST /payments` retry-safe via `Idempotency-Key` header + payl...

Subtopics Covered (8):
  • Natural idempotency of `GET`
  • `PUT`
  • `DELETE` vs non-idempotent `POST` โ€”
โ†’ What Topic Is Next: Next Topic 8.5: Status Codes and Actionable Error Contracts
Guide โ†’

Machine-parsable `error.code` (`EMAIL_ALREADY_EXISTS`, `DEPARTMENT_HAS_ACTIVE_EMPLOYEES`), human `message`, `requestId`, and field-level `details`

Subtopics Covered (8):
  • Machine-parsable `error.code` (`EMAIL_ALREADY_EXISTS`
  • `DEPARTMENT_HAS_ACTIVE_EMPLOYEES`)
  • Human `message`
โ†’ What Topic Is Next: Next Topic 8.6: Request and Response DTO Contracts
Guide โ†’

Strict separation between `EmployeeCreateRequest`, `EmployeeDbRecord`, and `EmployeeResponse` (never exposing internal auto-increment PKs, soft-delete flags, or audi...

Subtopics Covered (8):
  • Strict separation between `EmployeeCreateRequest`
  • `EmployeeDbRecord`
  • `EmployeeResponse` (never exposing internal auto-increment PKs
โ†’ What Topic Is Next: Next Topic 8.7: API Versioning Strategies in Production
Guide โ†’

URI prefix (`/api/v1`) vs Header (`Api-Version: 2026-01-01`), shared domain services serving both `v1Controller` and `v2Controller` via thin DTO transformers

Subtopics Covered (8):
  • URI prefix (`/api/v1`) vs Header (`Api-Version: 2026-01-01`)
  • Shared domain services serving both `v1Controller`
  • `v2Controller` via thin DTO transformers
โ†’ What Topic Is Next: Next Topic 8.8: Pagination Strategies: Offset vs Keyset Cursor
Guide โ†’

Why `OFFSET 100000 LIMIT 20` scans & discards `100,000` rows (`O(offset)` latency + skipped/duplicate rows on concurrent inserts!) vs **Keyset Cursor Pagination** (`...

Subtopics Covered (8):
  • Why `OFFSET 100000 LIMIT 20` scans & discards `100
  • 000` rows (`O(offset)` latency + skipped/duplicate rows on concurrent inserts!) vs **Keyset Cursor Pagination** (`WHERE (created_at
  • Id) < (:cursorTs
โ†’ What Topic Is Next: Next Topic 8.9: Filtering and Sorting Contract Design
Guide โ†’

Consistent filter query grammar (`status=ACTIVE`, `minSalary=50000`, `joinedAfter=2025-01-01`) and multi-column sort (`sort=-createdAt,lastName`) backed strictly by...

Subtopics Covered (8):
  • Consistent filter query grammar (`status=ACTIVE`
  • `minSalary=50000`
  • `joinedAfter=2025-01-01`)
โ†’ What Topic Is Next: Next Topic 8.10: Search API Design
Guide โ†’

Prefix/trigram/full-text search vs exact ID/email lookup, minimum query length (`>= 2` chars), highlighting/ranking, and debounced rate limits

Subtopics Covered (8):
  • Prefix/trigram/full-text search vs exact ID/email lookup
  • Minimum query length (`>= 2` chars)
  • Highlighting/ranking
โ†’ What Topic Is Next: Next Topic 8.11: Nested Resources and Depth Limits
Guide โ†’

Keep nesting `<= 2` levels: `POST /departments/:deptId/employees` & `GET /departments/:deptId/employees` are clear, whereas individual lookups use flat `GET /employe...

Subtopics Covered (8):
  • Keep nesting `<= 2` levels: `POST /departments/:deptId/employees` & `GET /departments/:deptId/employees` are clear
  • Whereas individual lookups use flat `GET /employees/:empId`!
  • Production Backend Pitfall & Guardrail (Nested Resources and Depth Limits)
โ†’ What Topic Is Next: Next Topic 8.12: Bulk Operations Design
Guide โ†’

Bounded batch sizes (`max 100 items` per call!), all-or-nothing transactional batch (`POST /employees/bulk`) vs partial-success `{ succeeded: [...], failed: [{ index...

Subtopics Covered (8):
  • Bounded batch sizes (`max 100 items` per call!)
  • All-or-nothing transactional batch (`POST /employees/bulk`) vs partial-success `{ succeeded: [...]
  • Failed: [{ index
โ†’ What Topic Is Next: Next Topic 8.13: Rate-Limiting Concepts and Standard Headers
Guide โ†’

Fixed Window vs Sliding Window vs Token Bucket, keying by `userId` (authenticated) vs `req.ip` (public/login), and returning `429 Too Many Requests` + `Retry-After`

Subtopics Covered (8):
  • Fixed Window vs Sliding Window vs Token Bucket
  • Keying by `userId` (authenticated) vs `req.ip` (public/login)
  • Returning `429 Too Many Requests` + `Retry-After`
โ†’ What Topic Is Next: Next Topic 8.14: API Documentation Standards
Guide โ†’

Documenting authentication schemes, pagination parameters, realistic request/response examples, idempotency headers, and every possible `4xx`/`5xx` error code in Ope...

Subtopics Covered (8):
  • Documenting authentication schemes
  • Pagination parameters
  • Realistic request/response examples
โ†’ What Topic Is Next: Next Topic 8.15: Postman Collections, Environments and Automated Assertions
Guide โ†’

Exporting version-controlled `postman/collection.json` + `local.environment.json`, chaining `pm.environment.set("employeeId", res.json().data.id)`, and writing `pm.t...

Subtopics Covered (8):
  • Exporting version-controlled `postman/collection.json` + `local.environment.json`
  • Chaining `pm.environment.set("employeeId"
  • Res.json().data.id)`
โ†’ What Topic Is Next: Next Topic 8.16: Controller-Service-Repository Pattern
Guide โ†’

`Controller` (HTTP status, headers, DTO mapping) -> `Service` (use-case orchestration, domain rules, transactions) -> `Repository` (data queries & persistence mappin...

Subtopics Covered (8):
  • `Controller` (HTTP status
  • Headers
  • DTO mapping) -> `Service` (use-case orchestration
โ†’ What Topic Is Next: Next Topic 8.17: Separation of Concerns
Guide โ†’

Isolating pure domain calculations, external infrastructure adapters (Mail, Storage, Cache), and HTTP transport concerns

Subtopics Covered (8):
  • Isolating pure domain calculations
  • External infrastructure adapters (Mail
  • Storage
โ†’ What Topic Is Next: Next Topic 8.18: Modular Backend Architecture (Bounded Modules)
Guide โ†’

Structuring medium-to-large backends as **Modular Monoliths** first: independent domain modules (`employees`, `departments`, `auth`) communicating through public ser...

Subtopics Covered (8):
  • Structuring medium-to-large backends as **Modular Monoliths** first: independent domain modules (`employees`
  • `departments`
  • `auth`) communicating through public service interfaces rather than reaching into each otherโ€™s private repositories!
โ†’ What Topic Is Next: Next Topic 8.19: Dependency Injection Fundamentals in TypeScript
Guide โ†’

Explicit **Composition Root** (`src/container.ts`) wiring `const repo = new ...; const svc = new EmployeeService(repo, deptSvc, logger); const ctrl = makeController(...

Subtopics Covered (8):
  • Explicit **Composition Root** (`src/container.ts`) wiring `const repo = new ...
  • Const svc = new EmployeeService(repo
  • DeptSvc
โ†’ What Topic Is Next: Next Topic 8.20: Configuration Management (12-Factor Fail-Fast Config)
Guide โ†’

Validating ALL environment variables at process boot into one frozen `AppConfig` object โ€” crashing immediately in `< 10ms` with clear field errors if `PORT`, `DATABA...

Subtopics Covered (8):
  • Validating ALL environment variables at process boot into one frozen `AppConfig` object โ€” crashing immediately in `< 10ms` with clear field errors if `PORT`
  • `DATABASE_URL`
  • Or `JWT_SECRET` is invalid!
โ†’ What Topic Is Next: Next Topic 8.21: Environment-Specific Settings
Guide โ†’

Clean behavior differences across `development` (pretty logs, Swagger UI enabled), `test` (ephemeral DB, silent/error logs, mocked mail), and `production` (JSON Pino...

Subtopics Covered (8):
  • Clean behavior differences across `development` (pretty logs
  • Swagger UI enabled)
  • `test` (ephemeral DB
โ†’ What Topic Is Next: Next Topic 8.22: Structured Logging (Pino & AsyncLocalStorage Correlation)
Guide โ†’

Why `console.log` blocks stdout synchronously on large payloads vs ultra-fast asynchronous **`pino`** JSON logging + `AsyncLocalStorage` injecting `requestId` & `use...

Subtopics Covered (8):
  • Why `console.log` blocks stdout synchronously on large payloads vs ultra-fast asynchronous **`pino`** JSON logging + `AsyncLocalStorage` injecting `requestId` & `userId` into every child log automatically!
  • Production Backend Pitfall & Guardrail (Structured Logging (Pino & AsyncLocalStorage Correlation))
  • Hands-On TypeScript / Node.js Implementation (Structured Logging (Pino & AsyncLocalStorage Correlation))
โ†’ What Topic Is Next: Next Topic 8.23: API Design Reviews and Production Readiness Checklist
Guide โ†’

12-point API review rubric: Naming, Idempotency, Pagination bounds, Whitelisted sort/filter, AuthN/AuthZ, Rate limits, Validation, Error envelope, OpenAPI, Logs, Tim...

Subtopics Covered (8):
  • 12-point API review rubric: Naming
  • Idempotency
  • Pagination bounds
โ†’ What Topic Is Next: Module 8 Capstone (Project 2: Production-Style Employee Management REST API) โ†’ Next Topic 9.1: Database Fundamentals: Storage Engines, Durability and Workload Fit

Transform Month 1โ€™s domain into a full-fledged, production-structured HTTP service! Build a **Production-Style Employee Management REST API** using **Node.js 22, Express.js, and TypeScript 5** following strict `Controller -> Service -> Repository` layered architecture with Employee CRUD, Department & Designation management, multi-field search/filtering/pagination, `Zod` request validation, centralized RFC 9457 error handling, `/api/v1` versioning, OpenAPI 3.1 / Swagger UI documentation, Postman collection, and `Pino` correlation-ID structured logging.

โ€ข Layered Express.js + TypeScript 5 REST API (`Controllers`, `Services`, `Repositories`, `Zod Schemas`, `Error Middleware`)
โ€ข Interactive OpenAPI 3.1 / Swagger UI (`/api/docs`) + Postman Collection & Environment JSON
โ€ข Pino Correlation-ID Logger + 35+ `Supertest` integration tests + Architecture `README.md`

Module Learning & Hands-On Objectives

โœ“ Choose objectively between MongoDB document modeling (polymorphic product attributes, high-velocity catalogs/events) and PostgreSQL relational tables.
โœ“ Model `1:1`, `1:Few` (embedded), `1:Many` / `1:Squillions` (referenced โ€” avoiding unbounded `16 MB` document growth!), and `M:N` relationships cleanly.
โœ“ Design `ESR` (`Equality -> Sort -> Range`), Unique, Partial, TTL, and Text indexes verified with `.explain("executionStats")`.
โœ“ Author high-performance Aggregation Pipelines (`$match`, `$group`, `$project`, `$sort`, `$lookup`, `$unwind`) and replica-set transactions.
Guide โ†’

OLTP vs OLAP, write-ahead journaling, read/write amplification, working-set RAM sizing, and access-pattern analysis

Subtopics Covered (8):
  • OLTP vs OLAP
  • Write-ahead journaling
  • Read/write amplification
โ†’ What Topic Is Next: Next Topic 9.2: SQL vs NoSQL Architectural Trade-Offs
Guide โ†’

Relational ACID tables (schema-on-write, arbitrary ad-hoc joins, foreign keys) vs Document/Key-Value/Wide-Column stores (schema flexibility, single-document locality...

Subtopics Covered (8):
  • Relational ACID tables (schema-on-write
  • Arbitrary ad-hoc joins
  • Foreign keys) vs Document/Key-Value/Wide-Column stores (schema flexibility
โ†’ What Topic Is Next: Next Topic 9.3: MongoDB WiredTiger Architecture
Guide โ†’

WiredTiger cache (~50% of available RAM), document-level concurrency control, snappy/zstd block compression, `oplog` replication, and journaling

Subtopics Covered (8):
  • WiredTiger cache (~50% of available RAM)
  • Document-level concurrency control
  • Snappy/zstd block compression
โ†’ What Topic Is Next: Next Topic 9.4: Databases, Collections and 16 MB BSON Documents
Guide โ†’

Dynamic vs JSON-Schema validated collections (`validator: { $jsonSchema: ... }`), `_id` immutability, and the hard `16 MB` BSON document ceiling

Subtopics Covered (8):
  • Dynamic vs JSON-Schema validated collections (`validator: { $jsonSchema: ... }`)
  • `_id` immutability
  • The hard `16 MB` BSON document ceiling
โ†’ What Topic Is Next: Next Topic 9.5: BSON Data Types in Depth
Guide โ†’

12-byte `ObjectId` (`4B timestamp + 5B random + 3B counter` โ€” naturally roughly time-ordered!), `Int32`/`Int64`, `Decimal128` (exact decimal math!), `ISODate` (`new...

Subtopics Covered (8):
  • 12-byte `ObjectId` (`4B timestamp + 5B random + 3B counter` โ€” naturally roughly time-ordered!)
  • `Int32`/`Int64`
  • `Decimal128` (exact decimal math!)
โ†’ What Topic Is Next: Next Topic 9.6: MongoDB Local & Docker Installation + mongosh
Guide โ†’

Running `mongo:7` in Docker with a single-node replica set (`--replSet rs0`, required locally to test multi-document transactions & Change Streams!) and `mongosh`

Subtopics Covered (8):
  • Running `mongo:7` in Docker with a single-node replica set (`--replSet rs0`
  • Required locally to test multi-document transactions & Change Streams!)
  • `mongosh`
โ†’ What Topic Is Next: Next Topic 9.7: MongoDB Atlas Fundamentals
Guide โ†’

Replica-set `M0/M10+` clusters, `mongodb+srv://` DNS seedlist connection strings, SCRAM auth, IP/VPC peering allowlists, and automated snapshots

Subtopics Covered (8):
  • Replica-set `M0/M10+` clusters
  • `mongodb+srv://` DNS seedlist connection strings
  • SCRAM auth
โ†’ What Topic Is Next: Next Topic 9.8: MongoDB Compass Visual Explain & Schema Profiling
Guide โ†’

Inspecting document schema distributions, index usage hit counts, and visual Explain Plans (`Keys Examined` vs `Docs Examined` ratio!)

Subtopics Covered (8):
  • Inspecting document schema distributions
  • Index usage hit counts
  • Visual Explain Plans (`Keys Examined` vs `Docs Examined` ratio!)
โ†’ What Topic Is Next: Next Topic 9.9: CRUD Operations and Atomic Update Operators
Guide โ†’

`insertOne`, `insertMany({ ordered: false })`, `find`, `updateOne` (`$set`, `$unset`, `$inc`, `$push`, `$addToSet`, `$pull`), `findOneAndUpdate(..., { returnDocument...

Subtopics Covered (8):
  • `insertOne`
  • `insertMany({ ordered: false })`
  • `find`
โ†’ What Topic Is Next: Next Topic 9.10: Query Operators ($in, $gt/$lte, $elemMatch, $exists)
Guide โ†’

Comparison (`$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`), logical (`$and`, `$or`), and why array-of-objects queries MUST use **`$elemMatch`** so conditions mat...

Subtopics Covered (8):
  • Comparison (`$eq`
  • `$ne`
  • `$gt`
โ†’ What Topic Is Next: Next Topic 9.11: Projection and Sorting
Guide โ†’

Inclusion `{ title: 1, pricePaise: 1 }` vs exclusion `{ internalCost: 0 }`, **Covered Queries** (`totalDocsExamined === 0` when all projected fields live in the inde...

Subtopics Covered (8):
  • Inclusion `{ title: 1
  • PricePaise: 1 }` vs exclusion `{ internalCost: 0 }`
  • **Covered Queries** (`totalDocsExamined === 0` when all projected fields live in the index!)
โ†’ What Topic Is Next: Next Topic 9.12: Cursor Pagination in MongoDB
Guide โ†’

Why `.skip(50000).limit(20)` walks 50,020 index entries vs keyset `{ _id: { $lt: lastObjectId } }` or compound `{ $or: [{ createdAt: { $lt: ts } }, { createdAt: ts,...

Subtopics Covered (8):
  • Why `.skip(50000).limit(20)` walks 50
  • 020 index entries vs keyset `{ _id: { $lt: lastObjectId } }` or compound `{ $or: [{ createdAt: { $lt: ts } }
  • { createdAt: ts
โ†’ What Topic Is Next: Next Topic 9.13: Embedded Documents Pattern
Guide โ†’

Embedding tightly owned, bounded `1:1` and `1:Few` data (`order.shippingAddress`, `product.dimensions`, `product.variants` `<= 50`) read & updated together atomicall...

Subtopics Covered (8):
  • Embedding tightly owned
  • Bounded `1:1`
  • `1:Few` data (`order.shippingAddress`
โ†’ What Topic Is Next: Next Topic 9.14: References, Relationships and Extended Reference Pattern
Guide โ†’

Referencing `categoryId` / `brandId` when cardinality is unbounded (`1:Many` / `1:Squillions`, e.g., `reviews` referencing `productId`!) + caching `{ id, name, slug...

Subtopics Covered (8):
  • Referencing `categoryId` / `brandId` when cardinality is unbounded (`1:Many` / `1:Squillions`
  • E.g.
  • `reviews` referencing `productId`!) + caching `{ id
โ†’ What Topic Is Next: Next Topic 9.15: One-to-One and One-to-Many Modelling
Guide โ†’

Choosing `1:1` embedded (`user.preferences`) vs split collection (large rarely-read `product_raw_audit`), and `1:Few` vs `1:Many` vs `1:Millions`

Subtopics Covered (8):
  • Choosing `1:1` embedded (`user.preferences`) vs split collection (large rarely-read `product_raw_audit`)
  • `1:Few` vs `1:Many` vs `1:Millions`
  • Production Backend Pitfall & Guardrail (One-to-One and One-to-Many Modelling)
โ†’ What Topic Is Next: Next Topic 9.16: Many-to-Many Modelling in MongoDB
Guide โ†’

Bounded two-way array of IDs (`product.tagIds[]` `<= 20`) with multikey index vs dedicated association collection (`warehouse_stock` with metadata `aisle`, `bin`, `u...

Subtopics Covered (8):
  • Bounded two-way array of IDs (`product.tagIds[]` `<= 20`) with multikey index vs dedicated association collection (`warehouse_stock` with metadata `aisle`
  • `bin`
  • `updatedAt`)
โ†’ What Topic Is Next: Next Topic 9.17: Schema Design Principles (Workload-Driven Design)
Guide โ†’

6 core MongoDB patterns: Embedded, Extended Reference, Subset (keep latest 5 reviews inline + rest in `reviews`!), Computed (`ratingAvg`), Bucket (IoT/metrics), and...

Subtopics Covered (8):
  • 6 core MongoDB patterns: Embedded
  • Extended Reference
  • Subset (keep latest 5 reviews inline + rest in `reviews`!)
โ†’ What Topic Is Next: Next Topic 9.18: Indexes and Compound Indexes (The ESR Rule)
Guide โ†’

B-Tree indexes in MongoDB and the golden **ESR Rule** for compound index field order: **1. Equality** (`status: "ACTIVE", categoryId: X`) -> **2. Sort** (`pricePaise...

Subtopics Covered (8):
  • B-Tree indexes in MongoDB
  • The golden **ESR Rule** for compound index field order: **1. Equality** (`status: "ACTIVE"
  • CategoryId: X`) -> **2. Sort** (`pricePaise: 1`) -> **3. Range** (`ratingAvg: { $gte: 4 }`)!
โ†’ What Topic Is Next: Next Topic 9.19: Unique, Partial, TTL and Text Indexes
Guide โ†’

`{ unique: true }` (`E11000` duplicate guard), `{ partialFilterExpression: { deletedAt: null } }` (unique active email even with soft deletes!), `{ expireAfterSecond...

Subtopics Covered (8):
  • `{ unique: true }` (`E11000` duplicate guard)
  • `{ partialFilterExpression: { deletedAt: null } }` (unique active email even with soft deletes!)
  • `{ expireAfterSeconds: 0 }` TTL cleanup
โ†’ What Topic Is Next: Next Topic 9.20: MongoDB Aggregation Pipeline Architecture
Guide โ†’

Streaming stage-by-stage transformation pipeline, pushing `$match` & `$sort` to Stage 1 so B-Tree indexes execute BEFORE heavy `$group`/`$lookup` stages, and `allowD...

Subtopics Covered (8):
  • Streaming stage-by-stage transformation pipeline
  • Pushing `$match` & `$sort` to Stage 1 so B-Tree indexes execute BEFORE heavy `$group`/`$lookup` stages
  • `allowDiskUse`
โ†’ What Topic Is Next: Next Topic 9.21: Core Stages: $match, $group, $project and $sort
Guide โ†’

Filtering (`$match`), grouping accumulators (`$sum`, `$avg`, `$min`, `$max`, `$count`, `$push`), reshaping/computed fields (`$project` / `$addFields`), and top-N `$s...

Subtopics Covered (8):
  • Filtering (`$match`)
  • Grouping accumulators (`$sum`
  • `$avg`
โ†’ What Topic Is Next: Next Topic 9.22: Relational & Multi-Facet Stages: $lookup, $unwind and $facet
Guide โ†’

Correlated/sub-pipeline `$lookup` (always ensure the foreign field is indexed!), `$unwind` (`preserveNullAndEmptyArrays: true`), and `$facet` returning `{ items, tot...

Subtopics Covered (8):
  • Correlated/sub-pipeline `$lookup` (always ensure the foreign field is indexed!)
  • `$unwind` (`preserveNullAndEmptyArrays: true`)
  • `$facet` returning `{ items
โ†’ What Topic Is Next: Next Topic 9.23: MongoDB Transactions, Security and Backups
Guide โ†’

Multi-document ACID sessions (`session.withTransaction` with automatic transient-transaction retry, `< 60s` max duration), SCRAM least-privilege DB users, TLS, and `...

Subtopics Covered (8):
  • Multi-document ACID sessions (`session.withTransaction` with automatic transient-transaction retry
  • `< 60s` max duration)
  • SCRAM least-privilege DB users
โ†’ What Topic Is Next: Module 9 Capstone (Week 9 Lab Build: MongoDB + Mongoose Catalog, Aggregation & ESR Index Benchmark) โ†’ Next Topic 10.1: Introduction to Mongoose ODM vs Native MongoDB Driver

Design a MongoDB 7 + Mongoose 8 product & review backend featuring embedded vs referenced modeling, multi-stage `$match -> $group -> $facet` analytics pipelines, `.lean()` read paths, and `explain("executionStats")` ESR compound index verification.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Define strict, TypeScript-typed Mongoose schemas (`strict: "throw"`, `autoIndex: false` in prod, `sanitizeFilter: true`).
โœ“ Avoid classic Mongoose production traps: missing `runValidators: true` on updates, `updateOne` bypassing `pre("save")`, slow hydrated reads without `.lean()`, and N+1 `.populate()` loops.
โœ“ Manage connection pools, graceful disconnects, multi-document `startSession()` transactions, and `11000` duplicate-key translation.
โœ“ Encapsulate Mongoose models cleanly behind typed `ProductRepository` interfaces.
Guide โ†’

What Mongoose adds (schema enforcement, TypeScript inference, middleware hooks, population, query builders) vs raw `mongodb` driver overhead, and when `.lean()` give...

Subtopics Covered (8):
  • What Mongoose adds (schema enforcement
  • TypeScript inference
  • Middleware hooks
โ†’ What Topic Is Next: Next Topic 10.2: Connecting Node.js to MongoDB Resiliently
Guide โ†’

`mongoose.connect(uri, { maxPoolSize: 20, serverSelectionTimeoutMS: 5000, socketTimeoutMS: 45000, autoIndex: !isProd })`, connection events (`connected`, `error`, `d...

Subtopics Covered (8):
  • `mongoose.connect(uri
  • { maxPoolSize: 20
  • ServerSelectionTimeoutMS: 5000
โ†’ What Topic Is Next: Next Topic 10.3: Mongoose Schema Definition and Strict Mode
Guide โ†’

`new Schema<IProduct>({ ... }, { strict: "throw", timestamps: true, versionKey: "__v" })` rejecting undeclared fields instead of silently dropping or saving typos

Subtopics Covered (8):
  • `new Schema<IProduct>({ ... }
  • { strict: "throw"
  • Timestamps: true
โ†’ What Topic Is Next: Next Topic 10.4: Models and Hydrated Documents
Guide โ†’

`model<IProduct>("Product", ProductSchema)`, model collection pluralization (`collection: "products"` explicit!), `.isModified()`, `.toObject()`, and `toJSON` transf...

Subtopics Covered (8):
  • `model<IProduct>("Product"
  • ProductSchema)`
  • Model collection pluralization (`collection: "products"` explicit!)
โ†’ What Topic Is Next: Next Topic 10.5: SchemaTypes and Built-In Validation
Guide โ†’

`String` (`trim`, `lowercase`, `minLength`, `maxLength`, `enum`, `match`), `Number` (`min`, `max`), `Boolean`, `Date`, `Schema.Types.ObjectId`, `Schema.Types.Decimal...

Subtopics Covered (8):
  • `String` (`trim`
  • `lowercase`
  • `minLength`
โ†’ What Topic Is Next: Next Topic 10.6: Required, Conditional and Custom Validators
Guide โ†’

Custom `validate: { validator: (v) => ..., message: ... }` functions, SKU format checks, and why uniqueness (`unique: true`) is a MongoDB **INDEX**, NOT a Mongoose v...

Subtopics Covered (8):
  • Custom `validate: { validator: (v) => ...
  • Message: ... }` functions
  • SKU format checks
โ†’ What Topic Is Next: Next Topic 10.7: Default Values, Immutable Fields and Timestamps
Guide โ†’

Function defaults (`default: () => randomUUID()` vs static value trap!), `immutable: true` (`tenantId`, `createdBy`, `sku`), and `timestamps: { createdAt: true, upda...

Subtopics Covered (8):
  • Function defaults (`default: () => randomUUID()` vs static value trap!)
  • `immutable: true` (`tenantId`
  • `createdBy`
โ†’ What Topic Is Next: Next Topic 10.8: Instance Methods, Static Methods and Query Helpers
Guide โ†’

Adding domain methods on `schema.methods` (`function` keyword โ€” NEVER arrow `() =>` which loses `this`!), `schema.statics`, and chainable `schema.query.active()`

Subtopics Covered (8):
  • Adding domain methods on `schema.methods` (`function` keyword โ€” NEVER arrow `() =>` which loses `this`!)
  • `schema.statics`
  • Chainable `schema.query.active()`
โ†’ What Topic Is Next: Next Topic 10.9: Mongoose Middleware and Hooks Architecture
Guide โ†’

4 distinct middleware types: **Document** (`validate`, `save`, `deleteOne`), **Query** (`find`, `findOneAndUpdate`, `updateOne`), **Aggregate**, and **Model** (`inse...

Subtopics Covered (8):
  • 4 distinct middleware types: **Document** (`validate`
  • `save`
  • `deleteOne`)
โ†’ What Topic Is Next: Next Topic 10.10: Pre and Post Hooks (and the updateOne Trap)
Guide โ†’

Why `Model.findOneAndUpdate()` and `Model.updateOne()` trigger **Query** middleware (where `this` is the `Query`, NOT the document!) and NEVER run `pre("save")` docu...

Subtopics Covered (8):
  • Why `Model.findOneAndUpdate()`
  • `Model.updateOne()` trigger **Query** middleware (where `this` is the `Query`
  • NOT the document!)
โ†’ What Topic Is Next: Next Topic 10.11: CRUD Using Mongoose Safely
Guide โ†’

`Model.create`, `findById`, `find`, `findOneAndUpdate(filter, update, { new: true, runValidators: true })`, `deleteOne`, and `mongoose.set("runValidators", true)` gl...

Subtopics Covered (8):
  • `Model.create`
  • `findById`
  • `find`
โ†’ What Topic Is Next: Next Topic 10.12: Query Operators and NoSQL Operator Injection Defense
Guide โ†’

Enabling `mongoose.set("sanitizeFilter", true)` + validating inputs as primitive `string`s in Zod so `{ "email": { "$gt": "" } }` attacker JSON cannot bypass login f...

Subtopics Covered (8):
  • Enabling `mongoose.set("sanitizeFilter"
  • True)` + validating inputs as primitive `string`s in Zod so `{ "email": { "$gt": "" } }` attacker JSON cannot bypass login filters!
  • Production Backend Pitfall & Guardrail (Query Operators and NoSQL Operator Injection Defense)
โ†’ What Topic Is Next: Next Topic 10.13: Population, References and Preventing N+1 Queries
Guide โ†’

`.populate({ path: "categoryId", select: "name slug" })` (executes 1 batched `$in` query across the page, NOT N queries โ€” UNLESS you call `await doc.populate()` insi...

Subtopics Covered (8):
  • `.populate({ path: "categoryId"
  • Select: "name slug" })` (executes 1 batched `$in` query across the page
  • NOT N queries โ€” UNLESS you call `await doc.populate()` inside a `for` loop!)
โ†’ What Topic Is Next: Next Topic 10.14: Virtual Properties
Guide โ†’

Computed non-persisted properties (`priceInRupees`), virtual populate, and why `.lean()` omits virtuals by default (compute DTO fields in your clean TypeScript DTO m...

Subtopics Covered (8):
  • Computed non-persisted properties (`priceInRupees`)
  • Virtual populate
  • Why `.lean()` omits virtuals by default (compute DTO fields in your clean TypeScript DTO mapper instead!)
โ†’ What Topic Is Next: Next Topic 10.15: Aggregation Using Mongoose
Guide โ†’

`ProductModel.aggregate<CategoryStat>([...])` noting Mongoose does NOT auto-cast string `"65f..."` to `Types.ObjectId` inside `.aggregate({ $match })` (cast `new Typ...

Subtopics Covered (8):
  • `ProductModel.aggregate<CategoryStat>([...])` noting Mongoose does NOT auto-cast string `"65f..."` to `Types.ObjectId` inside `.aggregate({ $match })` (cast `new Types.ObjectId(id)` explicitly!)
  • Production Backend Pitfall & Guardrail (Aggregation Using Mongoose)
  • Hands-On TypeScript / Node.js Implementation (Aggregation Using Mongoose)
โ†’ What Topic Is Next: Next Topic 10.16: Transactions and ClientSessions in Mongoose
Guide โ†’

`const session = await mongoose.startSession(); try { await session.withTransaction(async () => { ... }); } finally { await session.endSession(); }`

Subtopics Covered (8):
  • `const session = await mongoose.startSession()
  • Try { await session.withTransaction(async () => { ... })
  • } finally { await session.endSession()
โ†’ What Topic Is Next: Next Topic 10.17: Index Configuration and Production Migration Safety
Guide โ†’

Declaring compound/unique/TTL indexes on schemas, setting `autoIndex: false` in `NODE_ENV=production` (prevents startup index builds locking/slowing boot!), and sync...

Subtopics Covered (8):
  • Declaring compound/unique/TTL indexes on schemas
  • Setting `autoIndex: false` in `NODE_ENV=production` (prevents startup index builds locking/slowing boot!)
  • Syncing explicitly via `Model.syncIndexes()` / deploy scripts
โ†’ What Topic Is Next: Next Topic 10.18: Query Optimization (.lean, .select, Cursor Streaming, Explain)
Guide โ†’

Combining `.find(filter).select("sku title pricePaise").sort(...).limit(20).lean()` + `.cursor()` async iteration for batch jobs + `.explain("executionStats")` asser...

Subtopics Covered (8):
  • Combining `.find(filter).select("sku title pricePaise").sort(...).limit(20).lean()` + `.cursor()` async iteration for batch jobs + `.explain("executionStats")` assertions
  • Production Backend Pitfall & Guardrail (Query Optimization (.lean, .select, Cursor Streaming, Explain))
  • Hands-On TypeScript / Node.js Implementation (Query Optimization (.lean, .select, Cursor Streaming, Explain))
โ†’ What Topic Is Next: Next Topic 10.19: Connection Pooling Sizing and Monitoring
Guide โ†’

Sizing `maxPoolSize` (`10โ€“25` per Node process: `totalConnections = replicas * maxPoolSize < Atlas/Mongo limit!`), `minPoolSize`, and monitoring pool checkout wait t...

Subtopics Covered (8):
  • Sizing `maxPoolSize` (`10โ€“25` per Node process: `totalConnections = replicas * maxPoolSize < Atlas/Mongo limit!`)
  • `minPoolSize`
  • Monitoring pool checkout wait times
โ†’ What Topic Is Next: Next Topic 10.20: Mongoose Error Handling Translation
Guide โ†’

Mapping `MongoServerError` (`code === 11000` -> `409 Conflict` extracting duplicate key name!), `Error.CastError` (invalid `24-hex` ObjectId -> `400 Bad Request`), `...

Subtopics Covered (8):
  • Mapping `MongoServerError` (`code === 11000` -> `409 Conflict` extracting duplicate key name!)
  • `Error.CastError` (invalid `24-hex` ObjectId -> `400 Bad Request`)
  • `Error.ValidationError` -> `422`
โ†’ What Topic Is Next: Next Topic 10.21: Repository Pattern with Mongoose
Guide โ†’

Implementing `class MongooseProductRepository implements ProductRepository` returning clean domain POJOs (`ProductEntity`) so `ProductService` has zero `import mongo...

Subtopics Covered (8):
  • Implementing `class MongooseProductRepository implements ProductRepository` returning clean domain POJOs (`ProductEntity`) so `ProductService` has zero `import mongoose` coupling!
  • Production Backend Pitfall & Guardrail (Repository Pattern with Mongoose)
  • Hands-On TypeScript / Node.js Implementation (Repository Pattern with Mongoose)
โ†’ What Topic Is Next: Next Topic 10.22: TypeScript Integration with Mongoose
Guide โ†’

Explicit `interface ProductDoc` + `Schema<ProductDoc>` + `HydratedDocument<ProductDoc>`, `InferSchemaType<typeof ProductSchema>`, and strict `Types.ObjectId` vs `str...

Subtopics Covered (8):
  • Explicit `interface ProductDoc` + `Schema<ProductDoc>` + `HydratedDocument<ProductDoc>`
  • `InferSchemaType<typeof ProductSchema>`
  • Strict `Types.ObjectId` vs `string` boundary mapping
โ†’ What Topic Is Next: Module 10 Capstone (Week 10 Lab Build: Normalized 3NF PostgreSQL Financial Ledger & Window-Function Analytics) โ†’ Next Topic 11.1: Relational Database Concepts

Author a 3NF PostgreSQL 16 schema (`accounts`, `journal_entries`, `ledger_postings`) using `NUMERIC(14,2)`, `CHECK` constraints, `NOT EXISTS` anti-joins, recursive CTE category trees, `DENSE_RANK()`/`LAG()` window queries, and `EXPLAIN (ANALYZE, BUFFERS)` tuning.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Design normalized (`3NF`/`BCNF`) PostgreSQL schemas using exact types (`NUMERIC`, `UUID`, `TIMESTAMPTZ`, `JSONB`) and integrity constraints.
โœ“ Write complex analytical & transactional SQL using `JOIN`s, `EXISTS`, Recursive CTEs, Window Functions (`ROW_NUMBER`, `DENSE_RANK`, `LAG`), and `ON CONFLICT` upserts.
โœ“ Prevent Lost Updates, Dirty/Phantom Reads, and Deadlocks using ACID isolation levels and deterministic lock ordering (`SELECT ... FOR UPDATE`).
โœ“ Diagnose slow SQL using `EXPLAIN (ANALYZE, BUFFERS)` and tune composite/partial/covering indexes.
Guide โ†’

Relations (tables), tuples (rows), attributes (columns), domains, set-based declarative SQL vs imperative loops, and Coddโ€™s relational integrity principles

Subtopics Covered (8):
  • Relations (tables)
  • Tuples (rows)
  • Attributes (columns)
โ†’ What Topic Is Next: Next Topic 11.2: PostgreSQL Architecture (MVCC, Shared Buffers & WAL)
Guide โ†’

Client backend processes, `shared_buffers` page cache, Multi-Version Concurrency Control (**MVCC**: readers never block writers, writers never block readers!), `VACU...

Subtopics Covered (8):
  • Client backend processes
  • `shared_buffers` page cache
  • Multi-Version Concurrency Control (**MVCC**: readers never block writers
โ†’ What Topic Is Next: Next Topic 11.3: Database, Schema and Table Creation (DDL)
Guide โ†’

`CREATE SCHEMA`, `CREATE TABLE`, `GENERATED ALWAYS AS IDENTITY` (modern SQL standard over legacy `SERIAL`!), snake_case identifiers, and idempotent migrations

Subtopics Covered (8):
  • `CREATE SCHEMA`
  • `CREATE TABLE`
  • `GENERATED ALWAYS AS IDENTITY` (modern SQL standard over legacy `SERIAL`!)
โ†’ What Topic Is Next: Next Topic 11.4: PostgreSQL Data Types Selection
Guide โ†’

`BIGINT` / `UUID` (`gen_random_uuid()`), `NUMERIC(14, 2)` (exact decimal currency โ€” NEVER `REAL`/`DOUBLE PRECISION`!), `TEXT` vs `VARCHAR(n)`, `BOOLEAN`, **`TIMESTAM...

Subtopics Covered (8):
  • `BIGINT` / `UUID` (`gen_random_uuid()`)
  • `NUMERIC(14
  • 2)` (exact decimal currency โ€” NEVER `REAL`/`DOUBLE PRECISION`!)
โ†’ What Topic Is Next: Next Topic 11.5: Primary Keys and Foreign Keys
Guide โ†’

Surrogate keys (`BIGINT` / `UUIDv7`/`v4`) vs natural keys, composite primary keys, `REFERENCES ... ON DELETE RESTRICT | CASCADE | SET NULL`, and **ALWAYS indexing Fo...

Subtopics Covered (8):
  • Surrogate keys (`BIGINT` / `UUIDv7`/`v4`) vs natural keys
  • Composite primary keys
  • `REFERENCES ... ON DELETE RESTRICT | CASCADE | SET NULL`
โ†’ What Topic Is Next: Next Topic 11.6: Constraints (NOT NULL, UNIQUE, CHECK)
Guide โ†’

Enforcing domain invariants inside the database engine (`CHECK (qty_on_hand >= 0)`, `CHECK (reserved_qty <= qty_on_hand)`, `UNIQUE (warehouse_id, product_sku)`) so e...

Subtopics Covered (8):
  • Enforcing domain invariants inside the database engine (`CHECK (qty_on_hand >= 0)`
  • `CHECK (reserved_qty <= qty_on_hand)`
  • `UNIQUE (warehouse_id
โ†’ What Topic Is Next: Next Topic 11.7: INSERT, SELECT, UPDATE, DELETE and Upserts
Guide โ†’

Multi-row `INSERT ... VALUES ... RETURNING *`, atomic upsert `INSERT ... ON CONFLICT (warehouse_id, sku) DO UPDATE SET qty_on_hand = inventory_stock.qty_on_hand + EX...

Subtopics Covered (8):
  • Multi-row `INSERT ... VALUES ... RETURNING *`
  • Atomic upsert `INSERT ... ON CONFLICT (warehouse_id
  • Sku) DO UPDATE SET qty_on_hand = inventory_stock.qty_on_hand + EXCLUDED.qty_on_hand RETURNING *`
โ†’ What Topic Is Next: Next Topic 11.8: WHERE, ORDER BY and GROUP BY
Guide โ†’

Sargable predicates (`created_at >= $1 AND created_at < $2` uses index vs `EXTRACT(YEAR FROM created_at) = 2026` breaks index!), `IS NULL` / `IS NOT NULL` (never `=...

Subtopics Covered (8):
  • Sargable predicates (`created_at >= $1
  • Created_at < $2` uses index vs `EXTRACT(YEAR FROM created_at) = 2026` breaks index!)
  • `IS NULL` / `IS NOT NULL` (never `= NULL`!)
โ†’ What Topic Is Next: Next Topic 11.9: HAVING and Aggregate Functions
Guide โ†’

`COUNT(*)`, `COUNT(DISTINCT user_id)`, `COALESCE(SUM(amount), 0)`, `AVG`, `MIN`, `MAX`, `WHERE` (filters rows before grouping) vs `HAVING` (filters aggregated groups...

Subtopics Covered (8):
  • `COUNT(*)`
  • `COUNT(DISTINCT user_id)`
  • `COALESCE(SUM(amount)
โ†’ What Topic Is Next: Next Topic 11.10: INNER, LEFT, RIGHT and FULL OUTER Joins
Guide โ†’

Hash Join vs Nested Loop vs Merge Join, `INNER JOIN` vs `LEFT JOIN` (preserving zero-order customers!), and why putting a right-table filter in `WHERE` instead of `O...

Subtopics Covered (8):
  • Hash Join vs Nested Loop vs Merge Join
  • `INNER JOIN` vs `LEFT JOIN` (preserving zero-order customers!)
  • Why putting a right-table filter in `WHERE` instead of `ON` silently turns a `LEFT JOIN` into an `INNER JOIN`!
โ†’ What Topic Is Next: Next Topic 11.11: Self Joins
Guide โ†’

Joining a table onto itself with mandatory table aliases (`e.manager_id = m.id` employee-manager org trees, finding duplicate/overlapping shifts)

Subtopics Covered (8):
  • Joining a table onto itself with mandatory table aliases (`e.manager_id = m.id` employee-manager org trees
  • Finding duplicate/overlapping shifts)
  • Production Backend Pitfall & Guardrail (Self Joins)
โ†’ What Topic Is Next: Next Topic 11.12: Subqueries, Correlated Subqueries and EXISTS vs NOT IN
Guide โ†’

Scalar subqueries, derived tables, `EXISTS` (short-circuits on 1st match!), and the **deadly `NOT IN` NULL trap** (`WHERE id NOT IN (SELECT parent_id FROM t)` return...

Subtopics Covered (8):
  • Scalar subqueries
  • Derived tables
  • `EXISTS` (short-circuits on 1st match!)
โ†’ What Topic Is Next: Next Topic 11.13: Common Table Expressions (WITH & WITH RECURSIVE)
Guide โ†’

Readable multi-step `WITH` CTE pipelines, data-modifying CTEs (`WITH moved AS (DELETE ... RETURNING *) INSERT INTO archive ...`), and `WITH RECURSIVE` arbitrary-dept...

Subtopics Covered (8):
  • Readable multi-step `WITH` CTE pipelines
  • Data-modifying CTEs (`WITH moved AS (DELETE ... RETURNING *) INSERT INTO archive ...`)
  • `WITH RECURSIVE` arbitrary-depth category/org trees
โ†’ What Topic Is Next: Next Topic 11.14: Window Functions (OVER, PARTITION BY, ROW_NUMBER, DENSE_RANK, LAG)
Guide โ†’

Ranking (`ROW_NUMBER`, `RANK`, `DENSE_RANK` for Top-N per category!), offset (`LAG`, `LEAD` for MoM growth), and framing (`SUM(amount) OVER (PARTITION BY account_id...

Subtopics Covered (8):
  • Ranking (`ROW_NUMBER`
  • `RANK`
  • `DENSE_RANK` for Top-N per category!)
โ†’ What Topic Is Next: Next Topic 11.15: Views and Materialized Views
Guide โ†’

Virtual `CREATE VIEW` (query simplification / column security) vs persisted `CREATE MATERIALIZED VIEW` + unique index enabling zero-lock `REFRESH MATERIALIZED VIEW C...

Subtopics Covered (8):
  • Virtual `CREATE VIEW` (query simplification / column security) vs persisted `CREATE MATERIALIZED VIEW` + unique index enabling zero-lock `REFRESH MATERIALIZED VIEW CONCURRENTLY`!
  • Production Backend Pitfall & Guardrail (Views and Materialized Views)
  • Hands-On TypeScript / Node.js Implementation (Views and Materialized Views)
โ†’ What Topic Is Next: Next Topic 11.16: Indexes and Composite Indexes
Guide โ†’

B-Tree leftmost-prefix rule (`(tenant_id, status, created_at DESC)` serves `(tenant_id)` and `(tenant_id, status)`, NOT `(status)` alone!), Partial indexes (`WHERE s...

Subtopics Covered (8):
  • B-Tree leftmost-prefix rule (`(tenant_id
  • Status
  • Created_at DESC)` serves `(tenant_id)`
โ†’ What Topic Is Next: Next Topic 11.17: Transactions and ACID Properties
Guide โ†’

**Atomicity** (all or nothing), **Consistency** (constraints satisfied), **Isolation** (concurrent tx safety), **Durability** (committed WAL survives power loss), `B...

Subtopics Covered (8):
  • **Atomicity** (all or nothing)
  • **Consistency** (constraints satisfied)
  • **Isolation** (concurrent tx safety)
โ†’ What Topic Is Next: Next Topic 11.18: Transaction Isolation Levels
Guide โ†’

Read phenomena (Dirty Read, Non-Repeatable Read, Phantom Read, Serialization Anomaly) and PostgreSQLโ€™s `READ COMMITTED` (default!), `REPEATABLE READ` (snapshot isola...

Subtopics Covered (8):
  • Read phenomena (Dirty Read
  • Non-Repeatable Read
  • Phantom Read
โ†’ What Topic Is Next: Next Topic 11.19: Row-Level Locks (FOR UPDATE / SKIP LOCKED) and Deadlocks
Guide โ†’

Pessimistic row locking `SELECT ... FOR UPDATE`, job-claiming `FOR UPDATE SKIP LOCKED`, and preventing **Deadlocks (`40P01`)** by ALWAYS locking multiple rows in det...

Subtopics Covered (8):
  • Pessimistic row locking `SELECT ... FOR UPDATE`
  • Job-claiming `FOR UPDATE SKIP LOCKED`
  • Preventing **Deadlocks (`40P01`)** by ALWAYS locking multiple rows in deterministic sorted ID order (`ORDER BY product_id ASC FOR UPDATE`)!
โ†’ What Topic Is Next: Next Topic 11.20: Database Normalization (1NF, 2NF, 3NF, BCNF)
Guide โ†’

Eliminating repeating comma-separated columns (`1NF`), partial key dependencies (`2NF`), and transitive non-key dependencies (`3NF`), plus when controlled snapshot d...

Subtopics Covered (8):
  • Eliminating repeating comma-separated columns (`1NF`)
  • Partial key dependencies (`2NF`)
  • Transitive non-key dependencies (`3NF`)
โ†’ What Topic Is Next: Next Topic 11.21: Relationships and ER Diagrams
Guide โ†’

Drawing Crowโ€™s Foot Entity-Relationship Diagrams (`1:1`, `1:N`, `M:N` associative join tables with composite PK/unique + extra attributes), optionality (`0..1` vs `1...

Subtopics Covered (8):
  • Drawing Crowโ€™s Foot Entity-Relationship Diagrams (`1:1`
  • `1:N`
  • `M:N` associative join tables with composite PK/unique + extra attributes)
โ†’ What Topic Is Next: Next Topic 11.22: EXPLAIN (ANALYZE, BUFFERS) and Query Optimization
Guide โ†’

Reading execution trees bottom-up (`Actual Time`, `Rows Removed by Filter`, `Buffers: shared hit` RAM vs `read` disk, `Seq Scan` vs `Index Scan` vs `Index Only Scan`...

Subtopics Covered (8):
  • Reading execution trees bottom-up (`Actual Time`
  • `Rows Removed by Filter`
  • `Buffers: shared hit` RAM vs `read` disk
โ†’ What Topic Is Next: Next Topic 11.23: Backup and Restore Fundamentals (pg_dump & pg_restore)
Guide โ†’

Logical backups with custom compressed format `pg_dump -Fc -d app_db -f backup.dump`, `pg_restore --clean --if-exists`, WAL archiving concepts, and regular restore v...

Subtopics Covered (8):
  • Logical backups with custom compressed format `pg_dump -Fc -d app_db -f backup.dump`
  • `pg_restore --clean --if-exists`
  • WAL archiving concepts
โ†’ What Topic Is Next: Module 11 Capstone (Week 11 Lab Build: Prisma Interactive ACID Wallet Transfer & Optimistic Locking Service) โ†’ Next Topic 12.1: Introduction to Prisma ORM Architecture

Implement a deadlock-free PostgreSQL + Prisma 5 wallet & seat-booking service using sorted `SELECT ... FOR UPDATE` row locking inside `prisma.$transaction`, optimistic `version` compare-and-swap, `P2002`/`P2025` error mapping, and idempotency keys.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Model normalized PostgreSQL schemas in `schema.prisma` with exact `@db.*` native types, relations, and composite indexes.
โœ“ Execute type-safe CRUD, cursor pagination, `select`/`include` projection, and bounded interactive `$transaction` workflows.
โœ“ Manage schema migrations safely (`migrate dev` locally vs `migrate deploy` in CI/production) and size connection pools.
โœ“ Deliver **Month 3 Project (Project 3): Multi-Database Inventory Management Backend** integrating MongoDB (Mongoose) + PostgreSQL (Prisma).
Guide โ†’

Declarative `schema.prisma` -> `prisma generate` -> 100% compile-time type-safe `PrismaClient` query builder + Prisma Migrate DDL engine

Subtopics Covered (8):
  • Declarative `schema.prisma` -> `prisma generate` -> 100% compile-time type-safe `PrismaClient` query builder + Prisma Migrate DDL engine
  • Production Backend Pitfall & Guardrail (Introduction to Prisma ORM Architecture)
  • Hands-On TypeScript / Node.js Implementation (Introduction to Prisma ORM Architecture)
โ†’ What Topic Is Next: Next Topic 12.2: Prisma Installation and Multi-Environment Configuration
Guide โ†’

Installing `prisma` (devDependency) + `@prisma/client` (dependency), configuring `DATABASE_URL` via `.env`, and separating direct DB URL vs pooled URL when needed

Subtopics Covered (8):
  • Installing `prisma` (devDependency) + `@prisma/client` (dependency)
  • Configuring `DATABASE_URL` via `.env`
  • Separating direct DB URL vs pooled URL when needed
โ†’ What Topic Is Next: Next Topic 12.3: Prisma Schema Anatomy and Database Naming (@map & @@map)
Guide โ†’

Idiomatic camelCase TypeScript fields (`qtyOnHand`, `createdAt`) mapped cleanly onto PostgreSQL `snake_case` columns/tables via `@map("qty_on_hand")` and `@@map("inv...

Subtopics Covered (8):
  • Idiomatic camelCase TypeScript fields (`qtyOnHand`
  • `createdAt`) mapped cleanly onto PostgreSQL `snake_case` columns/tables via `@map("qty_on_hand")`
  • `@@map("inventory_stock")`!
โ†’ What Topic Is Next: Next Topic 12.4: Models, Scalar Fields, Enums and Defaults
Guide โ†’

`@id @default(uuid())` vs `@default(autoincrement())`, `@updatedAt`, native Postgres `enum` mapping, optional `?` (`NULL`), and `@@unique([warehouseId, sku])` + `@@i...

Subtopics Covered (8):
  • `@id @default(uuid())` vs `@default(autoincrement())`
  • `@updatedAt`
  • Native Postgres `enum` mapping
โ†’ What Topic Is Next: Next Topic 12.5: Native PostgreSQL Data Types (@db.*) and Decimal Precision
Guide โ†’

`Decimal @db.Decimal(12, 2)` (`Prisma.Decimal` exact decimal math โ€” never JS `float`!), `@db.Timestamptz(6)`, `@db.Uuid`, `@db.VarChar(64)`, and `Json` (`JSONB`)

Subtopics Covered (8):
  • `Decimal @db.Decimal(12
  • 2)` (`Prisma.Decimal` exact decimal math โ€” never JS `float`!)
  • `@db.Timestamptz(6)`
โ†’ What Topic Is Next: Next Topic 12.6: Modelling Relationships in Prisma (@relation)
Guide โ†’

Relation fields vs foreign-key scalar fields, explicit `onDelete: Restrict | Cascade | SetNull`, and disambiguating multiple relations between the same two models (`...

Subtopics Covered (8):
  • Relation fields vs foreign-key scalar fields
  • Explicit `onDelete: Restrict | Cascade | SetNull`
  • Disambiguating multiple relations between the same two models (`@relation("SourceWarehouse")` vs `@relation("TargetWarehouse")`)
โ†’ What Topic Is Next: Next Topic 12.7: One-to-One, One-to-Many and Explicit Many-to-Many Relations
Guide โ†’

`1:1` (`@unique` FK), `1:N`, and why **Explicit Join Models** (`OrderItem` with `qty`, `unitPricePaise`, `createdAt`) beat implicit Prisma M:N tables whenever relati...

Subtopics Covered (8):
  • `1:1` (`@unique` FK)
  • `1:N`
  • Why **Explicit Join Models** (`OrderItem` with `qty`
โ†’ What Topic Is Next: Next Topic 12.8: Singleton PrismaClient Lifecycle Management
Guide โ†’

Creating ONE shared `PrismaClient` per Node process (caching on `globalThis` during `tsx watch` dev hot-reloads so dev mode doesnโ€™t leak 50 DB pools!) and calling `$...

Subtopics Covered (8):
  • Creating ONE shared `PrismaClient` per Node process (caching on `globalThis` during `tsx watch` dev hot-reloads so dev mode doesnโ€™t leak 50 DB pools!)
  • Calling `$disconnect()` during graceful shutdown
  • Production Backend Pitfall & Guardrail (Singleton PrismaClient Lifecycle Management)
โ†’ What Topic Is Next: Next Topic 12.9: Type-Safe CRUD Operations with Prisma Client
Guide โ†’

`create`, `createManyAndReturn`, `findUnique` / `findFirst`, `findMany`, `update`, `updateMany` (conditional atomic guard `where: { id, qtyOnHand: { gte: n } }, data...

Subtopics Covered (8):
  • `create`
  • `createManyAndReturn`
  • `findUnique` / `findFirst`
โ†’ What Topic Is Next: Next Topic 12.10: Composable Filtering and Multi-Column Sorting
Guide โ†’

Building typed `const where: Prisma.InventoryStockWhereInput = { ... }` dynamically (`contains`, `mode: "insensitive"`, `in`, `gte`/`lte`, `AND`/`OR`) and determinis...

Subtopics Covered (8):
  • Building typed `const where: Prisma.InventoryStockWhereInput = { ... }` dynamically (`contains`
  • `mode: "insensitive"`
  • `in`
โ†’ What Topic Is Next: Next Topic 12.11: Offset vs Native Cursor Pagination in Prisma
Guide โ†’

`skip` + `take` vs high-scale `cursor: { id: lastId }, skip: 1, take: limit + 1` keyset pagination in Prisma

Subtopics Covered (8):
  • `skip` + `take` vs high-scale `cursor: { id: lastId }
  • Skip: 1
  • Take: limit + 1` keyset pagination in Prisma
โ†’ What Topic Is Next: Next Topic 12.12: Nested Queries, select vs include and Preventing N+1
Guide โ†’

Projecting strictly required columns with `select: { id: true, email: true }`, eager-loading relations via `include` (`relationLoadStrategy: "join"`), and Prismaโ€™s a...

Subtopics Covered (8):
  • Projecting strictly required columns with `select: { id: true
  • Email: true }`
  • Eager-loading relations via `include` (`relationLoadStrategy: "join"`)
โ†’ What Topic Is Next: Next Topic 12.13: Sequential Batch Transactions ($transaction([...]))
Guide โ†’

`await prisma.$transaction([op1, op2], { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead })` when operations donโ€™t depend on intermediate JS branchin...

Subtopics Covered (8):
  • `await prisma.$transaction([op1
  • Op2]
  • { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead })` when operations donโ€™t depend on intermediate JS branching
โ†’ What Topic Is Next: Next Topic 12.14: Interactive Transactions ($transaction(async (tx) => ...))
Guide โ†’

`await prisma.$transaction(async (tx) => { ... }, { maxWait: 3000, timeout: 5000, isolationLevel: ... })`, ALWAYS calling **`tx.*`** (NEVER outer `prisma.*`!) inside...

Subtopics Covered (8):
  • `await prisma.$transaction(async (tx) => { ... }
  • { maxWait: 3000
  • Timeout: 5000
โ†’ What Topic Is Next: Next Topic 12.15: Database Migrations (migrate dev vs migrate deploy)
Guide โ†’

Generating reviewable SQL files in `prisma/migrations/` via `npx prisma migrate dev --name ...`, reviewing destructive `DROP` warnings BEFORE committing, and running...

Subtopics Covered (8):
  • Generating reviewable SQL files in `prisma/migrations/` via `npx prisma migrate dev --name ...`
  • Reviewing destructive `DROP` warnings BEFORE committing
  • Running non-interactive **`npx prisma migrate deploy`** in CI/production (NEVER `migrate dev` or `db push` in prod!)!
โ†’ What Topic Is Next: Next Topic 12.16: Idempotent Database Seeding (prisma/seed.ts)
Guide โ†’

Writing re-runnable `upsert`-based seed scripts (`npx prisma db seed`) populating reference roles, warehouses, and sample SKUs without throwing duplicate errors on s...

Subtopics Covered (8):
  • Writing re-runnable `upsert`-based seed scripts (`npx prisma db seed`) populating reference roles
  • Warehouses
  • Sample SKUs without throwing duplicate errors on second run
โ†’ What Topic Is Next: Next Topic 12.17: Connection Management and Pool Sizing
Guide โ†’

Configuring `?connection_limit=10&pool_timeout=10&connect_timeout=5` in `DATABASE_URL`, matching `(num_containers * connection_limit) < postgres max_connections`, an...

Subtopics Covered (8):
  • Configuring `?connection_limit=10&pool_timeout=10&connect_timeout=5` in `DATABASE_URL`
  • Matching `(num_containers * connection_limit) < postgres max_connections`
  • `PgBouncer` transaction-mode (`?pgbouncer=true`)
โ†’ What Topic Is Next: Next Topic 12.18: Query Optimization, $queryRaw Safe Tagged Templates & Logging
Guide โ†’

Enabling slow-query event logging (`prisma.$on("query", e => { if (e.duration > 100) ... })`), using **`prisma.$queryRaw\`SELECT ... WHERE id = \${id} FOR UPDATE\``*...

Subtopics Covered (8):
  • Enabling slow-query event logging (`prisma.$on("query"
  • E => { if (e.duration > 100) ... })`)
  • Using **`prisma.$queryRaw\`SELECT ... WHERE id = \${id} FOR UPDATE\``** (safe parameterized `$1`!)
โ†’ What Topic Is Next: Next Topic 12.19: Repository and Service Patterns with Prisma
Guide โ†’

Passing optional `tx?: Prisma.TransactionClient` (defaulting to `this.prisma`) into repository methods so Services can compose multiple repositories inside ONE ACID...

Subtopics Covered (8):
  • Passing optional `tx?: Prisma.TransactionClient` (defaulting to `this.prisma`) into repository methods so Services can compose multiple repositories inside ONE ACID transaction cleanly!
  • Production Backend Pitfall & Guardrail (Repository and Service Patterns with Prisma)
  • Hands-On TypeScript / Node.js Implementation (Repository and Service Patterns with Prisma)
โ†’ What Topic Is Next: Next Topic 12.20: Advanced TypeScript Integration with Prisma
Guide โ†’

Using `Prisma.InventoryStockGetPayload<{ include: { warehouse: true } }>`, `Prisma.PrismaClientKnownRequestError` (`err.code === "P2002"` unique, `"P2025"` not found...

Subtopics Covered (8):
  • Using `Prisma.InventoryStockGetPayload<{ include: { warehouse: true } }>`
  • `Prisma.PrismaClientKnownRequestError` (`err.code === "P2002"` unique
  • `"P2025"` not found
โ†’ What Topic Is Next: Next Topic 12.21: Database Integration Testing Strategies
Guide โ†’

Testing Repositories & APIs against real ephemeral Docker PostgreSQL + MongoDB instances (never mocking SQL queries that pass in mocks and fail on real DB constraint...

Subtopics Covered (8):
  • Testing Repositories & APIs against real ephemeral Docker PostgreSQL + MongoDB instances (never mocking SQL queries that pass in mocks
  • Fail on real DB constraints!)
  • Fast `TRUNCATE ... RESTART IDENTITY CASCADE` between suites
โ†’ What Topic Is Next: Next Topic 12.22: Comparing Prisma, Mongoose and Direct SQL (Polyglot Synthesis)
Guide โ†’

When to use **Prisma** (type-safe relational CRUD/migrations), **Direct Parameterized SQL / `$queryRaw`** (complex CTEs, Window Functions, `FOR UPDATE SKIP LOCKED`,...

Subtopics Covered (8):
  • When to use **Prisma** (type-safe relational CRUD/migrations)
  • **Direct Parameterized SQL / `$queryRaw`** (complex CTEs
  • Window Functions
โ†’ What Topic Is Next: Module 12 Capstone (Project 3: Multi-Database Inventory Management Backend) โ†’ Next Topic 13.1: Authentication vs Authorization

Real-world commerce and supply-chain backends frequently combine **polyglot persistence**: document databases excel at flexible, deeply varied product specifications (`laptops` have RAM/CPU, `apparel` has fabric/size/color), while relational databases are non-negotiable for warehouse stock counts, purchase orders, and ACID inventory ledger movements. Build a **Multi-Database Inventory Management Backend** integrating **MongoDB 7 + Mongoose 8** (flexible Product Catalog & Variant Specs) with **PostgreSQL 16 + Prisma 5** (Warehouses, Stock Levels, Reservations, Purchase Orders & Immutable ACID Stock Ledger).

โ€ข Polyglot Express + TypeScript Backend (`MongoDB + Mongoose` Catalog + `PostgreSQL + Prisma` ACID Inventory & Ledger)
โ€ข Versioned Prisma Migrations + Deterministic Seed Script + Cross-DB Batch Hydration Service
โ€ข 50-Way Concurrency Race Test Suite + `EXPLAIN ANALYZE` / ESR Index Optimization Report + OpenAPI 3.1 Docs

Module Learning & Hands-On Objectives

โœ“ Hash passwords safely using `Argon2id` / `bcrypt` and implement enumeration-safe login, email verification, and one-time password resets.
โœ“ Implement short-lived JWT Access Tokens (`15m`) + rotated `HttpOnly` Refresh Tokens (`7d`) with reuse-detection family revocation.
โœ“ Contrast stateless JWTs against Redis-backed stateful sessions and integrate OAuth 2.0 (`PKCE`) / Google OIDC login.
โœ“ Enforce Role-Based (`RBAC`), Permission-Based, and Resource-Ownership (`BOLA`) authorization cleanly via Express middleware.
Guide โ†’

`Authentication (AuthN)` = verifying identity (`"Who are you?"` -> `401 Unauthorized` when missing/invalid) vs `Authorization (AuthZ)` = verifying permissions (`"Wha...

Subtopics Covered (8):
  • `Authentication (AuthN)` = verifying identity (`"Who are you?"` -> `401 Unauthorized` when missing/invalid) vs `Authorization (AuthZ)` = verifying permissions (`"What are you allowed to do?"` -> `403 Forbidden`)
  • Production Backend Pitfall & Guardrail (Authentication vs Authorization)
  • Hands-On TypeScript / Node.js Implementation (Authentication vs Authorization)
โ†’ What Topic Is Next: Next Topic 13.2: User Registration and Enumeration-Safe Login
Guide โ†’

Canonicalizing email (`trim().toLowerCase()`), constant-message `"Invalid email or password"` responses, and performing a dummy hash compare when user is not found t...

Subtopics Covered (8):
  • Canonicalizing email (`trim().toLowerCase()`)
  • Constant-message `"Invalid email or password"` responses
  • Performing a dummy hash compare when user is not found to prevent timing-based email enumeration!
โ†’ What Topic Is Next: Next Topic 13.3: Password Hashing Fundamentals
Guide โ†’

Why fast cryptographic hashes (`SHA-256` runs billions/sec on GPUs!) are catastrophic for passwords vs slow, salted, adaptive key-derivation functions (`Argon2id`, `...

Subtopics Covered (8):
  • Why fast cryptographic hashes (`SHA-256` runs billions/sec on GPUs!) are catastrophic for passwords vs slow
  • Salted
  • Adaptive key-derivation functions (`Argon2id`
โ†’ What Topic Is Next: Next Topic 13.4: bcrypt and Argon2id in Node.js
Guide โ†’

OWASP #1 recommended **`argon2` (`argon2id`, `memoryCost: 65536`)** vs `bcrypt` (`cost = 12`), async threadpool execution (NEVER `hashSync`/`compareSync`!), and `bcr...

Subtopics Covered (8):
  • OWASP #1 recommended **`argon2` (`argon2id`
  • `memoryCost: 65536`)** vs `bcrypt` (`cost = 12`)
  • Async threadpool execution (NEVER `hashSync`/`compareSync`!)
โ†’ What Topic Is Next: Next Topic 13.5: Password Reset Workflows
Guide โ†’

Generating `32-byte` CSPRNG token (`crypto.randomBytes(32).toString("hex")`), emailing raw token in link, storing ONLY `SHA-256(token)` + `expiresAt` (`15m`) + `used...

Subtopics Covered (8):
  • Generating `32-byte` CSPRNG token (`crypto.randomBytes(32).toString("hex")`)
  • Emailing raw token in link
  • Storing ONLY `SHA-256(token)` + `expiresAt` (`15m`) + `usedAt` in DB
โ†’ What Topic Is Next: Next Topic 13.6: Email Verification Workflows
Guide โ†’

Issuing hashed verification tokens on signup, rate-limiting resend requests (`1 / 60s`), marking `emailVerifiedAt = NOW()`, and gating sensitive actions on verified...

Subtopics Covered (8):
  • Issuing hashed verification tokens on signup
  • Rate-limiting resend requests (`1 / 60s`)
  • Marking `emailVerifiedAt = NOW()`
โ†’ What Topic Is Next: Next Topic 13.7: JWT Fundamentals
Guide โ†’

Compact URL-safe `base64url(header).base64url(payload).base64url(signature)` tokens โ€” **SIGNED (tamper-evident), NOT ENCRYPTED** (anyone can base64-decode payload!)

Subtopics Covered (8):
  • Compact URL-safe `base64url(header).base64url(payload).base64url(signature)` tokens โ€” **SIGNED (tamper-evident)
  • NOT ENCRYPTED** (anyone can base64-decode payload!)
  • Production Backend Pitfall & Guardrail (JWT Fundamentals)
โ†’ What Topic Is Next: Next Topic 13.8: JWT Structure and Strict Signature Verification
Guide โ†’

Symmetric `HS256` (`>= 256-bit` high-entropy secret) vs asymmetric `RS256`/`EdDSA` (Auth Service signs with private key; Microservices verify with public key!), and...

Subtopics Covered (8):
  • Symmetric `HS256` (`>= 256-bit` high-entropy secret) vs asymmetric `RS256`/`EdDSA` (Auth Service signs with private key
  • Microservices verify with public key!)
  • Pinning `algorithms: ["HS256"]` + `issuer` + `audience`!
โ†’ What Topic Is Next: Next Topic 13.9: Access Tokens and Refresh Tokens Architecture
Guide โ†’

Pairing short-lived stateless `Access Token` (`10โ€“15 min` in `Authorization: Bearer`) with long-lived revocable `Refresh Token` (`7โ€“30 days` in `HttpOnly` cookie, `S...

Subtopics Covered (8):
  • Pairing short-lived stateless `Access Token` (`10โ€“15 min` in `Authorization: Bearer`) with long-lived revocable `Refresh Token` (`7โ€“30 days` in `HttpOnly` cookie
  • `SHA-256` hash persisted in DB/Redis)
  • Production Backend Pitfall & Guardrail (Access Tokens and Refresh Tokens Architecture)
โ†’ What Topic Is Next: Next Topic 13.10: Token Expiration, Rotation and Theft Reuse Detection
Guide โ†’

On `POST /auth/refresh`: verify presented refresh token -> if already marked `replacedByTokenId != null`, **THEFT DETECTED: revoke ALL tokens in `familyId` immediate...

Subtopics Covered (8):
  • On `POST /auth/refresh`: verify presented refresh token -> if already marked `replacedByTokenId != null`
  • **THEFT DETECTED: revoke ALL tokens in `familyId` immediately!** -> else mark used & issue fresh pair!
  • Production Backend Pitfall & Guardrail (Token Expiration, Rotation and Theft Reuse Detection)
โ†’ What Topic Is Next: Next Topic 13.11: Immediate Token Revocation Strategies
Guide โ†’

Combining short `15m` access TTL with a lightweight Redis denylist `SET revoked:jti:<jti> 1 EX <remaining_ttl>` (checked in `< 0.5ms`) for critical immediate logouts...

Subtopics Covered (8):
  • Combining short `15m` access TTL with a lightweight Redis denylist `SET revoked:jti:<jti> 1 EX <remaining_ttl>` (checked in `< 0.5ms`) for critical immediate logouts/bans + `tokenVersion` bump on password change!
  • Production Backend Pitfall & Guardrail (Immediate Token Revocation Strategies)
  • Hands-On TypeScript / Node.js Implementation (Immediate Token Revocation Strategies)
โ†’ What Topic Is Next: Next Topic 13.12: Session-Based Authentication with Redis
Guide โ†’

Opaque CSPRNG `sessionId` cookie mapped to Redis JSON (`sess:<sid>`), sliding TTL renewal, session fixation prevention (**regenerate session ID on login!**), and ins...

Subtopics Covered (8):
  • Opaque CSPRNG `sessionId` cookie mapped to Redis JSON (`sess:<sid>`)
  • Sliding TTL renewal
  • Session fixation prevention (**regenerate session ID on login!**)
โ†’ What Topic Is Next: Next Topic 13.13: Cookie-Based Authentication Mechanics
Guide โ†’

Automatic browser `Cookie` attachment vs explicit `Authorization` header, scoping refresh cookies strictly to `Path=/api/v1/auth` so every `/api/v1/products` call do...

Subtopics Covered (8):
  • Automatic browser `Cookie` attachment vs explicit `Authorization` header
  • Scoping refresh cookies strictly to `Path=/api/v1/auth` so every `/api/v1/products` call doesnโ€™t even transmit the refresh cookie over the wire!
  • Production Backend Pitfall & Guardrail (Cookie-Based Authentication Mechanics)
โ†’ What Topic Is Next: Next Topic 13.14: Secure Cookie Configuration (__Host- Prefix & Flags)
Guide โ†’

`HttpOnly: true`, `Secure: true`, `SameSite: "lax" | "strict"`, and the **`__Host-`** cookie name prefix (`__Host-rt` forces browser enforcement of `Secure`, `Path=/...

Subtopics Covered (8):
  • `HttpOnly: true`
  • `Secure: true`
  • `SameSite: "lax" | "strict"`
โ†’ What Topic Is Next: Next Topic 13.15: OAuth 2.0 Fundamentals (Authorization Code + PKCE)
Guide โ†’

Roles (`Resource Owner`, `Client`, `Authorization Server`, `Resource Server`), why Implicit Flow is dead, **Authorization Code + PKCE (`code_verifier` / `code_challe...

Subtopics Covered (8):
  • Roles (`Resource Owner`
  • `Client`
  • `Authorization Server`
โ†’ What Topic Is Next: Next Topic 13.16: OpenID Connect (OIDC) Overview
Guide โ†’

Why OAuth 2.0 alone is an *authorization* protocol vs **OIDC** (`openid email profile` scopes) adding standardized identity `id_token` JWTs verified against provider...

Subtopics Covered (8):
  • Why OAuth 2.0 alone is an *authorization* protocol vs **OIDC** (`openid email profile` scopes) adding standardized identity `id_token` JWTs verified against provider `/.well-known/openid-configuration` `JWKS` keys!
  • Production Backend Pitfall & Guardrail (OpenID Connect (OIDC) Overview)
  • Hands-On TypeScript / Node.js Implementation (OpenID Connect (OIDC) Overview)
โ†’ What Topic Is Next: Next Topic 13.17: Google Login Backend Integration Fundamentals
Guide โ†’

Redirecting to Google Auth URL (`state`, `code_challenge`) -> exchanging `code` server-to-server -> verifying `id_token` via `google-auth-library` / `jose` JWKS -> u...

Subtopics Covered (8):
  • Redirecting to Google Auth URL (`state`
  • `code_challenge`) -> exchanging `code` server-to-server -> verifying `id_token` via `google-auth-library` / `jose` JWKS -> upserting `oauth_accounts(provider
  • ProviderAccountId)` -> issuing your own app session/JWT!
โ†’ What Topic Is Next: Next Topic 13.18: Role-Based Access Control (RBAC)
Guide โ†’

Modelling `CUSTOMER`, `SELLER`, `SUPPORT`, `ADMIN` roles and enforcing role gates on Express routers (`requireRoles("ADMIN", "SUPPORT")`)

Subtopics Covered (8):
  • Modelling `CUSTOMER`
  • `SELLER`
  • `SUPPORT`
โ†’ What Topic Is Next: Next Topic 13.19: Permission-Based (Fine-Grained) Authorization
Guide โ†’

Decoupling code from role renames: Roles map to **Permissions** (`orders:read`, `orders:refund`, `products:publish`), and routes check `requirePermissions("orders:re...

Subtopics Covered (8):
  • Decoupling code from role renames: Roles map to **Permissions** (`orders:read`
  • `orders:refund`
  • `products:publish`)
โ†’ What Topic Is Next: Next Topic 13.20: Resource-Level Ownership Authorization (Preventing BOLA / IDOR)
Guide โ†’

**OWASP API1 #1 Vulnerability (`Broken Object Level Authorization`)**: verifying `order.userId === req.user.sub || req.user.role === "ADMIN"` inside the query/policy...

Subtopics Covered (8):
  • **OWASP API1 #1 Vulnerability (`Broken Object Level Authorization`)**: verifying `order.userId === req.user.sub || req.user.role === "ADMIN"` inside the query/policy on EVERY `:id` endpoint!
  • Production Backend Pitfall & Guardrail (Resource-Level Ownership Authorization (Preventing BOLA / IDOR))
  • Hands-On TypeScript / Node.js Implementation (Resource-Level Ownership Authorization (Preventing BOLA / IDOR))
โ†’ What Topic Is Next: Next Topic 13.21: Multi-Role and Multi-Tenant Application Design
Guide โ†’

Users holding multiple roles or workspace memberships (`organization_members(orgId, userId, role)`), scoping active `X-Organization-Id` verified against DB/cache mem...

Subtopics Covered (8):
  • Users holding multiple roles or workspace memberships (`organization_members(orgId
  • UserId
  • Role)`)
โ†’ What Topic Is Next: Next Topic 13.22: Protected Routes and Composable Auth Middleware Pipeline
Guide โ†’

Chaining `authenticate -> requireVerifiedEmail -> requirePermissions("products:write")` cleanly with 100% TypeScript narrowing

Subtopics Covered (8):
  • Chaining `authenticate -> requireVerifiedEmail -> requirePermissions("products:write")` cleanly with 100% TypeScript narrowing
  • Production Backend Pitfall & Guardrail (Protected Routes and Composable Auth Middleware Pipeline)
  • Hands-On TypeScript / Node.js Implementation (Protected Routes and Composable Auth Middleware Pipeline)
โ†’ What Topic Is Next: Module 13 Capstone (Week 13 Lab Build: Argon2id + Rotated Refresh-Token Family & RBAC/BOLA Guard Engine) โ†’ Next Topic 14.1: OWASP API Security Top 10 Overview

Build a standalone Express + TypeScript authentication core implementing `Argon2id` password hashing, `15m` JWT access tokens, `HttpOnly` rotated refresh-token families with SHA-256 DB storage & reuse revocation, and BOLA-proof ownership middleware.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Mitigate all OWASP API Security Top 10 risks with concrete Express, TypeScript, Prisma, Mongoose, and Redis controls.
โœ“ Configure `helmet`, strict `cors`, tiered rate limiting, brute-force lockouts, magic-byte upload checks, and payload caps.
โœ“ Eliminate SQL injection, NoSQL operator injection, Prototype Pollution, `ReDoS`, and secret/PII leakage in logs and errors.
โœ“ Maintain append-only security audit trails and dependency vulnerability scanning in CI.
Guide โ†’

API1 BOLA, API2 Broken Auth, API3 Broken Object Property Level Auth (Mass Assignment & Excessive Data Exposure!), API4 Unrestricted Resource Consumption, API5 Broken...

Subtopics Covered (8):
  • API1 BOLA
  • API2 Broken Auth
  • API3 Broken Object Property Level Auth (Mass Assignment & Excessive Data Exposure!)
โ†’ What Topic Is Next: Next Topic 14.2: Input Validation and Sanitization
Guide โ†’

Allowlist validation (strict types, lengths, regexes, enums via Zod) OVER blocklist string stripping, plus Unicode normalization and prototype-pollution key blocking...

Subtopics Covered (8):
  • Allowlist validation (strict types
  • Lengths
  • Regexes
โ†’ What Topic Is Next: Next Topic 14.3: SQL Injection Prevention
Guide โ†’

Why parameterized placeholders (`$1, $2` in `pg`, Prisma ORM methods, and `prisma.$queryRaw\`...\`` tagged templates) separate SQL AST compilation from data values โ€”...

Subtopics Covered (8):
  • Why parameterized placeholders (`$1
  • $2` in `pg`
  • Prisma ORM methods
โ†’ What Topic Is Next: Next Topic 14.4: NoSQL Injection Prevention
Guide โ†’

Blocking JSON operator objects (`{ "$ne": null }`, `{ "$gt": "" }`, `$where` JS execution!) via Zod `z.string()` validation + `mongoose.set("sanitizeFilter", true)`

Subtopics Covered (8):
  • Blocking JSON operator objects (`{ "$ne": null }`
  • `{ "$gt": "" }`
  • `$where` JS execution!) via Zod `z.string()` validation + `mongoose.set("sanitizeFilter"
โ†’ What Topic Is Next: Next Topic 14.5: Cross-Site Scripting (XSS) Fundamentals for Backend Engineers
Guide โ†’

Enforcing `Content-Type: application/json; charset=utf-8` + `X-Content-Type-Options: nosniff` on APIs, escaping HTML in server-generated emails/PDFs, and `HttpOnly`...

Subtopics Covered (8):
  • Enforcing `Content-Type: application/json
  • Charset=utf-8` + `X-Content-Type-Options: nosniff` on APIs
  • Escaping HTML in server-generated emails/PDFs
โ†’ What Topic Is Next: Next Topic 14.6: Cross-Site Request Forgery (CSRF) Defense
Guide โ†’

When CSRF applies (cookie-authenticated state-changing endpoints; NOT pure `Authorization: Bearer` header APIs!), defending cookie endpoints via `SameSite=Lax|Strict...

Subtopics Covered (8):
  • When CSRF applies (cookie-authenticated state-changing endpoints
  • NOT pure `Authorization: Bearer` header APIs!)
  • Defending cookie endpoints via `SameSite=Lax|Strict` + `Origin`/`Referer` verification + Double-Submit / Synchronizer CSRF tokens
โ†’ What Topic Is Next: Next Topic 14.7: Production CORS Configuration
Guide โ†’

Dynamic `origin(reqOrigin, cb)` checking an explicit `Set<string>` allowlist, `credentials: true`, explicit `methods` & `allowedHeaders`, `maxAge: 86400` caching `OP...

Subtopics Covered (8):
  • Dynamic `origin(reqOrigin
  • Cb)` checking an explicit `Set<string>` allowlist
  • `credentials: true`
โ†’ What Topic Is Next: Next Topic 14.8: Helmet Security Headers
Guide โ†’

`Strict-Transport-Security` (`HSTS`), `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, and `Content-Security-Policy: defau...

Subtopics Covered (8):
  • `Strict-Transport-Security` (`HSTS`)
  • `X-Content-Type-Options: nosniff`
  • `X-Frame-Options: DENY`
โ†’ What Topic Is Next: Next Topic 14.9: Rate Limiting Architecture
Guide โ†’

Multi-layer rate limits: Nginx edge IP burst limit + Express Redis-backed per-user/per-IP sliding windows (`express-rate-limit` + `rate-limit-redis`)

Subtopics Covered (8):
  • Multi-layer rate limits: Nginx edge IP burst limit + Express Redis-backed per-user/per-IP sliding windows (`express-rate-limit` + `rate-limit-redis`)
  • Production Backend Pitfall & Guardrail (Rate Limiting Architecture)
  • Hands-On TypeScript / Node.js Implementation (Rate Limiting Architecture)
โ†’ What Topic Is Next: Next Topic 14.10: Brute-Force and Credential-Stuffing Protection
Guide โ†’

Dual-key tracking on `/login`: (1) per-IP limit (`30 / 15m` protecting corporate NATs) AND (2) per-`email` failure counter (`5 failed -> 15m cooldown` blocking distr...

Subtopics Covered (8):
  • Dual-key tracking on `/login`: (1) per-IP limit (`30 / 15m` protecting corporate NATs)
  • (2) per-`email` failure counter (`5 failed -> 15m cooldown` blocking distributed botnets rotating 10
  • 000 IPs!)
โ†’ What Topic Is Next: Next Topic 14.11: Password Security and Policy Standards
Guide โ†’

NIST SP 800-63B modern rules: length (`>= 8โ€“12` chars up to `128`), allowing spaces/passphrases, screening common breached passwords (`password123`, `qwerty12345`),...

Subtopics Covered (8):
  • NIST SP 800-63B modern rules: length (`>= 8โ€“12` chars up to `128`)
  • Allowing spaces/passphrases
  • Screening common breached passwords (`password123`
โ†’ What Topic Is Next: Next Topic 14.12: Secure Token Storage (Hashing Server-Side Secrets)
Guide โ†’

Hashing refresh tokens, API keys (`sk_live_...`), OTPs, and reset tokens with `SHA-256` BEFORE storing in PostgreSQL/MongoDB โ€” just like GitHub/Stripe show an API ke...

Subtopics Covered (8):
  • Hashing refresh tokens
  • API keys (`sk_live_...`)
  • OTPs
โ†’ What Topic Is Next: Next Topic 14.13: Secrets Management and Rotation
Guide โ†’

Supporting **Key Ring Arrays** (`JWT_SECRETS = [currentKey, previousKey]`: sign with `keys[0]`, verify trying `keys[0]` then `keys[1]`) so signing keys rotate with Z...

Subtopics Covered (8):
  • Supporting **Key Ring Arrays** (`JWT_SECRETS = [currentKey
  • PreviousKey]`: sign with `keys[0]`
  • Verify trying `keys[0]` then `keys[1]`) so signing keys rotate with ZERO user logouts!
โ†’ What Topic Is Next: Next Topic 14.14: Hardened Environment Configuration
Guide โ†’

Enforcing minimum secret entropy (`JWT_SECRET.length >= 32`), forbidding dev defaults (`"changeme"`, `"secret"`) when `NODE_ENV === "production"`, and freezing confi...

Subtopics Covered (8):
  • Enforcing minimum secret entropy (`JWT_SECRET.length >= 32`)
  • Forbidding dev defaults (`"changeme"`
  • `"secret"`) when `NODE_ENV === "production"`
โ†’ What Topic Is Next: Next Topic 14.15: File Upload Security Architecture
Guide โ†’

Renaming every uploaded file to a random `UUID` (`never` using original `file.originalname` on disk!), storing outside webroot in private buckets, `Content-Dispositi...

Subtopics Covered (8):
  • Renaming every uploaded file to a random `UUID` (`never` using original `file.originalname` on disk!)
  • Storing outside webroot in private buckets
  • `Content-Disposition: attachment`
โ†’ What Topic Is Next: Next Topic 14.16: Magic-Byte MIME Type Validation
Guide โ†’

Inspecting actual leading binary file signatures (`%PDF-` = `25 50 44 46`, PNG = `89 50 4E 47`, JPEG = `FF D8 FF`) rather than trusting spoofable `Content-Type` mult...

Subtopics Covered (8):
  • Inspecting actual leading binary file signatures (`%PDF-` = `25 50 44 46`
  • PNG = `89 50 4E 47`
  • JPEG = `FF D8 FF`) rather than trusting spoofable `Content-Type` multipart headers!
โ†’ What Topic Is Next: Next Topic 14.17: Request Size, Parameter and Depth Limits
Guide โ†’

Bounding `express.json({ limit: "100kb" })`, URL query parameter count (`parameterLimit: 50`), Multer `{ limits: { fileSize: 5 * 1024 * 1024, files: 3 } }`, and JSON...

Subtopics Covered (8):
  • Bounding `express.json({ limit: "100kb" })`
  • URL query parameter count (`parameterLimit: 50`)
  • Multer `{ limits: { fileSize: 5 * 1024 * 1024
โ†’ What Topic Is Next: Next Topic 14.18: API Abuse, Enumeration and SSRF Prevention
Guide โ†’

Using UUIDv4/v7 external IDs instead of sequential `/invoices/1, 2, 3`, protecting coupon/checkout business flows (`API6`), and blocking private IP ranges (`127.0.0....

Subtopics Covered (8):
  • Using UUIDv4/v7 external IDs instead of sequential `/invoices/1
  • Protecting coupon/checkout business flows (`API6`)
  • Blocking private IP ranges (`127.0.0.0/8`
โ†’ What Topic Is Next: Next Topic 14.19: Dependency Vulnerability Scanning
Guide โ†’

Running `npm audit --omit=dev --audit-level=high` in CI, pinning lockfiles, disabling untrusted install scripts (`--ignore-scripts` consideration), and preferring na...

Subtopics Covered (8):
  • Running `npm audit --omit=dev --audit-level=high` in CI
  • Pinning lockfiles
  • Disabling untrusted install scripts (`--ignore-scripts` consideration)
โ†’ What Topic Is Next: Next Topic 14.20: Secure Logging and Redaction
Guide โ†’

Configuring Pino `redact: { paths: [...], censor: "[REDACTED]" }` for `authorization`, `cookie`, `set-cookie`, `*.password`, `*.token`, `*.cvv`, and stripping `\r\n`...

Subtopics Covered (8):
  • Configuring Pino `redact: { paths: [...]
  • Censor: "[REDACTED]" }` for `authorization`
  • `cookie`
โ†’ What Topic Is Next: Next Topic 14.21: PII Handling and Field-Level Encryption
Guide โ†’

Classifying PII (`PAN`, `taxId`, `bankAccountNumber`), encrypting high-sensitivity fields at rest with `node:crypto` `aes-256-gcm` (unique `12-byte` IV + `16-byte` a...

Subtopics Covered (8):
  • Classifying PII (`PAN`
  • `taxId`
  • `bankAccountNumber`)
โ†’ What Topic Is Next: Next Topic 14.22: Immutable Security Audit Trails
Guide โ†’

Recording `security_audit_logs` (`actorUserId`, `action`, `targetType`, `targetId`, `ipAddress`, `userAgent`, `metadata`, `createdAt`) on logins, role changes, passw...

Subtopics Covered (8):
  • Recording `security_audit_logs` (`actorUserId`
  • `action`
  • `targetType`
โ†’ What Topic Is Next: Next Topic 14.23: Secure Error Responses in Production
Guide โ†’

Logging full `{ err, stack, sql, requestId }` internally to Pino while returning ONLY `{ code: "INTERNAL_ERROR", message: "Unexpected error", requestId }` to externa...

Subtopics Covered (8):
  • Logging full `{ err
  • Stack
  • Sql
โ†’ What Topic Is Next: Next Topic 14.24: Least-Privilege Access Across Stack Layers
Guide โ†’

Running Node as UID `1000` (`node` user, never `root`), connecting the app with a non-superuser PostgreSQL role (`SELECT, INSERT, UPDATE, DELETE` โ€” no `DROP DATABASE...

Subtopics Covered (8):
  • Running Node as UID `1000` (`node` user
  • Never `root`)
  • Connecting the app with a non-superuser PostgreSQL role (`SELECT
โ†’ What Topic Is Next: Module 14 Capstone (Week 14 Lab Build: OWASP API Top 10 Hardening Pack (Helmet, Zod, SSRF & Redis Rate Limiter)) โ†’ Next Topic 15.1: Advanced Validation Using Zod and Joi

Harden an Express API against NoSQL/SQL injection, mass assignment, prototype pollution, ReDoS, and private-IP SSRF while adding `Helmet`, strict origin allowlist `CORS`, and atomic Redis Lua Token-Bucket / Sliding-Window rate limiters.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Validate and infer TypeScript types from a single source of truth using `Zod` (and maintain `Joi` schemas) across requests AND outbound responses.
โœ“ Handle multipart uploads with `Multer` and offload large files via vendor-neutral S3-compatible (`MinIO`) Presigned URLs.
โœ“ Implement transactional email templates, cluster-safe cron schedules, streaming CSV/Excel imports & exports, and server-side PDF invoices.
โœ“ Build both inbound and outbound Webhooks with HMAC-SHA256 + timestamp replay verification, retries, and idempotency.
Guide โ†’

`Zod` (`z.object`, `.strict()`/`.strip()`, `.refine()`, `.transform()`, `z.infer<typeof Schema>` zero-duplication TS types!) alongside `Joi` awareness for existing e...

Subtopics Covered (8):
  • `Zod` (`z.object`
  • `.strict()`/`.strip()`
  • `.refine()`
โ†’ What Topic Is Next: Next Topic 15.2: Request Schema Validation Middleware (params, query, body)
Guide โ†’

`z.coerce.number().int().min(1).max(100).default(20)` for query strings, `z.string().uuid()` for params, formatting `ZodError.issues` into clean `422` field error ar...

Subtopics Covered (8):
  • `z.coerce.number().int().min(1).max(100).default(20)` for query strings
  • `z.string().uuid()` for params
  • Formatting `ZodError.issues` into clean `422` field error arrays
โ†’ What Topic Is Next: Next Topic 15.3: Outbound Response Validation
Guide โ†’

Running `PublicUserDtoSchema.parse(data)` before `res.json()` (or in tests/staging) as a hard data-leakage firewall guaranteeing `passwordHash` or `secret` can NEVER...

Subtopics Covered (8):
  • Running `PublicUserDtoSchema.parse(data)` before `res.json()` (or in tests/staging) as a hard data-leakage firewall guaranteeing `passwordHash` or `secret` can NEVER leave the server!
  • Production Backend Pitfall & Guardrail (Outbound Response Validation)
  • Hands-On TypeScript / Node.js Implementation (Outbound Response Validation)
โ†’ What Topic Is Next: Next Topic 15.4: Centralized API Error Mapping (Zod, Prisma, Mongoose, Multer, JWT)
Guide โ†’

Unified error normalizer converting `ZodError` (`422`), `Prisma P2002` (`409`), `Mongoose 11000` (`409`), `MulterError LIMIT_FILE_SIZE` (`413`), and `TokenExpiredErr...

Subtopics Covered (8):
  • Unified error normalizer converting `ZodError` (`422`)
  • `Prisma P2002` (`409`)
  • `Mongoose 11000` (`409`)
โ†’ What Topic Is Next: Next Topic 15.5: API Versioning Lifecycle & Deprecation Headers
Guide โ†’

Router-level `/api/v1` vs `/api/v2`, RFC 8594 `Sunset` & `Deprecation: true` headers, and tracking per-version traffic metrics before retiring old versions

Subtopics Covered (8):
  • Router-level `/api/v1` vs `/api/v2`
  • RFC 8594 `Sunset` & `Deprecation: true` headers
  • Tracking per-version traffic metrics before retiring old versions
โ†’ What Topic Is Next: Next Topic 15.6: Offset Pagination vs Opaque Cursor Pagination
Guide โ†’

Implementing tamper-checked base64url cursors `{ sortValue, id }` supporting forward (`after`) pagination without `OFFSET` degradation on `10M`-row tables

Subtopics Covered (8):
  • Implementing tamper-checked base64url cursors `{ sortValue
  • Id }` supporting forward (`after`) pagination without `OFFSET` degradation on `10M`-row tables
  • Production Backend Pitfall & Guardrail (Offset Pagination vs Opaque Cursor Pagination)
โ†’ What Topic Is Next: Next Topic 15.7: Advanced Filtering and Multi-Field Sorting
Guide โ†’

Supporting range operators (`price[gte]=1000&price[lte]=5000`), multi-select (`status=PAID,SHIPPED`), and safe multi-sort (`sort=-createdAt,pricePaise`)

Subtopics Covered (8):
  • Supporting range operators (`price[gte]=1000&price[lte]=5000`)
  • Multi-select (`status=PAID
  • SHIPPED`)
โ†’ What Topic Is Next: Next Topic 15.8: Bulk Insert and Bulk Update Patterns
Guide โ†’

`prisma.product.createMany({ data, skipDuplicates })`, chunking `5,000` rows into batches of `500` so single SQL packets stay fast, and parameterized `UNNEST` bulk u...

Subtopics Covered (8):
  • `prisma.product.createMany({ data
  • SkipDuplicates })`
  • Chunking `5
โ†’ What Topic Is Next: Next Topic 15.9: File Upload with Multer
Guide โ†’

Configuring `multer` (`diskStorage` to `/tmp` with `UUID` filename vs `memoryStorage` ONLY for small `< 2 MB` avatars), `fileFilter`, strict `limits`, and cleaning u...

Subtopics Covered (8):
  • Configuring `multer` (`diskStorage` to `/tmp` with `UUID` filename vs `memoryStorage` ONLY for small `< 2 MB` avatars)
  • `fileFilter`
  • Strict `limits`
โ†’ What Topic Is Next: Next Topic 15.10: Self-Hosted / S3-Compatible Object Storage Fundamentals (MinIO)
Guide โ†’

Why stateless Node containers NEVER store permanent uploads on local container disk (wiped on redeploy & invisible to sibling replicas!) -> storing objects in privat...

Subtopics Covered (8):
  • Why stateless Node containers NEVER store permanent uploads on local container disk (wiped on redeploy & invisible to sibling replicas!) -> storing objects in private S3-compatible buckets (`MinIO` in Docker / any S3-compatible provider) keyed by `{tenant}/{year}/{uuid}.ext`
  • Production Backend Pitfall & Guardrail (Self-Hosted / S3-Compatible Object Storage Fundamentals (MinIO))
  • Hands-On TypeScript / Node.js Implementation (Self-Hosted / S3-Compatible Object Storage Fundamentals (MinIO))
โ†’ What Topic Is Next: Next Topic 15.11: Presigned URL Concepts (Direct Upload & Time-Limited Download)
Guide โ†’

Client requests `POST /uploads/presign` (Node checks Auth + quota + MIME/size conditions -> signs a `5-minute` `PUT` URL) -> Client uploads `50 MB` directly to Objec...

Subtopics Covered (8):
  • Client requests `POST /uploads/presign` (Node checks Auth + quota + MIME/size conditions -> signs a `5-minute` `PUT` URL) -> Client uploads `50 MB` directly to Object Storage (zero Node RAM/bandwidth!) -> `GET` uses `5-minute` RBAC-checked presigned download URL!
  • Production Backend Pitfall & Guardrail (Presigned URL Concepts (Direct Upload & Time-Limited Download))
  • Hands-On TypeScript / Node.js Implementation (Presigned URL Concepts (Direct Upload & Time-Limited Download))
โ†’ What Topic Is Next: Next Topic 15.12: Email Services and Transactional Templates
Guide โ†’

Designing clean HTML + plain-text fallback email templates (Welcome, Verify Email, Password Reset, Order Receipt) with HTML-escaped variables and `List-Unsubscribe`...

Subtopics Covered (8):
  • Designing clean HTML + plain-text fallback email templates (Welcome
  • Verify Email
  • Password Reset
โ†’ What Topic Is Next: Next Topic 15.13: SMTP Integration with Nodemailer
Guide โ†’

Configuring `nodemailer.createTransport({ pool: true, maxConnections: 5, connectionTimeout: 5000 })`, testing locally against `Mailpit` / `MailHog` SMTP container (z...

Subtopics Covered (8):
  • Configuring `nodemailer.createTransport({ pool: true
  • MaxConnections: 5
  • ConnectionTimeout: 5000 })`
โ†’ What Topic Is Next: Next Topic 15.14: End-to-End Password Reset Email Workflows
Guide โ†’

Combining rate limit -> hashed token DB write -> queued reset email -> token verification -> Argon2 password update -> session revocation -> confirmation security al...

Subtopics Covered (8):
  • Combining rate limit -> hashed token DB write -> queued reset email -> token verification -> Argon2 password update -> session revocation -> confirmation security alert email!
  • Production Backend Pitfall & Guardrail (End-to-End Password Reset Email Workflows)
  • Hands-On TypeScript / Node.js Implementation (End-to-End Password Reset Email Workflows)
โ†’ What Topic Is Next: Next Topic 15.15: Scheduled Tasks Architecture
Guide โ†’

Use cases: expiring unpaid `15-minute` inventory reservations, nightly ledger reconciliations, purging expired tokens, and refreshing materialized views

Subtopics Covered (8):
  • Use cases: expiring unpaid `15-minute` inventory reservations
  • Nightly ledger reconciliations
  • Purging expired tokens
โ†’ What Topic Is Next: Next Topic 15.16: Cron Jobs and Multi-Instance Distributed Lock Safety
Guide โ†’

Cron 5-field expressions (`*/5 * * * *`), explicit `timezone: "UTC"`, and why `node-cron` inside 4 API containers fires **4 TIMES** unless moved to BullMQ Repeatable...

Subtopics Covered (8):
  • Cron 5-field expressions (`*/5 * * * *`)
  • Explicit `timezone: "UTC"`
  • Why `node-cron` inside 4 API containers fires **4 TIMES** unless moved to BullMQ Repeatable Jobs or guarded by a Redis `SET NX PX` lock!
โ†’ What Topic Is Next: Next Topic 15.17: Background Task Architecture Preview
Guide โ†’

Returning `202 Accepted` + `{ jobId, statusUrl: "/api/v1/jobs/..." }` for operations taking `> 500ms` (bulk imports, PDF generation, webhook fan-out)

Subtopics Covered (8):
  • Returning `202 Accepted` + `{ jobId
  • StatusUrl: "/api/v1/jobs/..." }` for operations taking `> 500ms` (bulk imports
  • PDF generation
โ†’ What Topic Is Next: Next Topic 15.18: Streaming CSV Import and Export (CSV Injection Defense!)
Guide โ†’

Streaming CSV rows via `csv-parse` / `fast-csv` + `pipeline()` in `O(1)` memory, AND defending against **CSV Formula Injection** (prefixing leading `=`, `+`, `-`, `@...

Subtopics Covered (8):
  • Streaming CSV rows via `csv-parse` / `fast-csv` + `pipeline()` in `O(1)` memory
  • Defending against **CSV Formula Injection** (prefixing leading `=`
  • `+`
โ†’ What Topic Is Next: Next Topic 15.19: Excel (.xlsx) Streaming Processing Fundamentals
Guide โ†’

Using `exceljs` streaming `WorkbookWriter` / `WorkbookReader` instead of loading entire multi-sheet workbooks into DOM memory

Subtopics Covered (8):
  • Using `exceljs` streaming `WorkbookWriter` / `WorkbookReader` instead of loading entire multi-sheet workbooks into DOM memory
  • Production Backend Pitfall & Guardrail (Excel (.xlsx) Streaming Processing Fundamentals)
  • Hands-On TypeScript / Node.js Implementation (Excel (.xlsx) Streaming Processing Fundamentals)
โ†’ What Topic Is Next: Next Topic 15.20: PDF Generation Fundamentals (pdfkit)
Guide โ†’

Generating lightweight vector GST tax invoices & receipts server-side using streaming `pdfkit` (`doc.pipe(writeStream)`) rather than spawning a `400 MB` headless Chr...

Subtopics Covered (8):
  • Generating lightweight vector GST tax invoices & receipts server-side using streaming `pdfkit` (`doc.pipe(writeStream)`) rather than spawning a `400 MB` headless Chromium browser!
  • Production Backend Pitfall & Guardrail (PDF Generation Fundamentals (pdfkit))
  • Hands-On TypeScript / Node.js Implementation (PDF Generation Fundamentals (pdfkit))
โ†’ What Topic Is Next: Next Topic 15.21: Webhook Creation (Outbound & Inbound Architecture)
Guide โ†’

Inbound webhooks (receiving payment events from Razorpay/Stripe) vs Outbound webhooks (notifying merchant URLs of `order.shipped` with `X-Webhook-Id`, `X-Webhook-Tim...

Subtopics Covered (8):
  • Inbound webhooks (receiving payment events from Razorpay/Stripe) vs Outbound webhooks (notifying merchant URLs of `order.shipped` with `X-Webhook-Id`
  • `X-Webhook-Timestamp`
  • `X-Webhook-Signature`)
โ†’ What Topic Is Next: Next Topic 15.22: Webhook Signature Validation + Replay-Window Defense
Guide โ†’

Signing `${timestamp}.${rawBody}` with HMAC-SHA256, verifying `Math.abs(nowSec - timestamp) <= 300` (`5-minute` replay window!), and comparing digests with `crypto.t...

Subtopics Covered (8):
  • Signing `${timestamp}.${rawBody}` with HMAC-SHA256
  • Verifying `Math.abs(nowSec - timestamp) <= 300` (`5-minute` replay window!)
  • Comparing digests with `crypto.timingSafeEqual`!
โ†’ What Topic Is Next: Next Topic 15.23: Webhook Retries and Consumer Idempotency
Guide โ†’

Why payment gateways deliver webhooks **At-Least-Once** (same `payment.captured` event can arrive 3 times!), guaranteeing exactly-once business effect via `UNIQUE (p...

Subtopics Covered (8):
  • Why payment gateways deliver webhooks **At-Least-Once** (same `payment.captured` event can arrive 3 times!)
  • Guaranteeing exactly-once business effect via `UNIQUE (provider
  • Provider_event_id)` inside the same DB transaction as order status update!
โ†’ What Topic Is Next: Next Topic 15.24: API Documentation and Contract Governance
Guide โ†’

Generating OpenAPI 3.1 JSON directly from `Zod` schemas (`zod-to-openapi`), exporting client SDK types, and running CI diffs catching accidental breaking contract ch...

Subtopics Covered (8):
  • Generating OpenAPI 3.1 JSON directly from `Zod` schemas (`zod-to-openapi`)
  • Exporting client SDK types
  • Running CI diffs catching accidental breaking contract changes
โ†’ What Topic Is Next: Module 15 Capstone (Week 15 Lab Build: MinIO Presigned Upload Service + Supertest & Testcontainers Suite) โ†’ Next Topic 16.1: Software Testing Fundamentals & the Backend Testing Trophy

Build a secure file upload & invoice attachment service verifying magic-byte file signatures (`file-type`) and S3-compatible `MinIO` presigned `PUT`/`GET` URLs โ€” backed by an `>= 85%` `Vitest`/`Jest` + `Supertest` integration suite.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Write fast unit tests (`Vitest`/`Jest`) for domain logic and comprehensive `Supertest` HTTP + real-DB integration tests for APIs.
โœ“ Test authentication edge cases, refresh-token rotation/theft detection, RBAC, negative BOLA attempts, and concurrent race conditions.
โœ“ Enforce `ESLint` (`no-floating-promises`), `Prettier`, `tsc --noEmit`, and `>= 80%` branch coverage gates automatically.
โœ“ Deliver **Month 4 Project (Project 4): Secure Authentication and Authorization Service**.
Guide โ†’

Static Type/Lint checks (`tsc` + `ESLint`) -> Fast Pure Unit Tests -> High-Confidence API + Real-DB Integration Tests (`Supertest`) -> Focused Critical-Path E2E Flow...

Subtopics Covered (8):
  • Static Type/Lint checks (`tsc` + `ESLint`) -> Fast Pure Unit Tests -> High-Confidence API + Real-DB Integration Tests (`Supertest`) -> Focused Critical-Path E2E Flows
  • Production Backend Pitfall & Guardrail (Software Testing Fundamentals & the Backend Testing Trophy)
  • Hands-On TypeScript / Node.js Implementation (Software Testing Fundamentals & the Backend Testing Trophy)
โ†’ What Topic Is Next: Next Topic 16.2: Unit Testing Pure Domain Logic and Services
Guide โ†’

Arrange-Act-Assert (`AAA`) structure, testing pure pricing/coupon/token calculators and Services injected with lightweight `InMemoryRepository` fakes in `< 5ms` per...

Subtopics Covered (8):
  • Arrange-Act-Assert (`AAA`) structure
  • Testing pure pricing/coupon/token calculators
  • Services injected with lightweight `InMemoryRepository` fakes in `< 5ms` per test
โ†’ What Topic Is Next: Next Topic 16.3: Integration Testing Repositories and Persistence
Guide โ†’

Verifying actual Prisma/PostgreSQL and Mongoose/MongoDB queries, unique/check constraints, cascade rules, and transactions against isolated test databases

Subtopics Covered (8):
  • Verifying actual Prisma/PostgreSQL
  • Mongoose/MongoDB queries
  • Unique/check constraints
โ†’ What Topic Is Next: Next Topic 16.4: HTTP API Testing Principles
Guide โ†’

Asserting HTTP status code, `Content-Type`, security/rate/location headers, response JSON schema, AND post-request database/audit state!

Subtopics Covered (8):
  • Asserting HTTP status code
  • `Content-Type`
  • Security/rate/location headers
โ†’ What Topic Is Next: Next Topic 16.5: End-to-End Backend Flow Testing
Guide โ†’

Multi-step stateful user journeys (`Register -> Capture OTP from FakeMailer -> Verify Email -> Login -> Access Protected Route -> Rotate Refresh Cookie -> Logout ->...

Subtopics Covered (8):
  • Multi-step stateful user journeys (`Register -> Capture OTP from FakeMailer -> Verify Email -> Login -> Access Protected Route -> Rotate Refresh Cookie -> Logout -> Verify Old Refresh Rejected`)
  • Production Backend Pitfall & Guardrail (End-to-End Backend Flow Testing)
  • Hands-On TypeScript / Node.js Implementation (End-to-End Backend Flow Testing)
โ†’ What Topic Is Next: Next Topic 16.6: Test-Driven Development (TDD) Fundamentals
Guide โ†’

`Red` (write failing test specifying exact behavior) -> `Green` (write minimal clean code to pass) -> `Refactor` (clean up with green safety net)

Subtopics Covered (8):
  • `Red` (write failing test specifying exact behavior) -> `Green` (write minimal clean code to pass) -> `Refactor` (clean up with green safety net)
  • Production Backend Pitfall & Guardrail (Test-Driven Development (TDD) Fundamentals)
  • Hands-On TypeScript / Node.js Implementation (Test-Driven Development (TDD) Fundamentals)
โ†’ What Topic Is Next: Next Topic 16.7: Jest and Vitest Configuration for TypeScript + ESM
Guide โ†’

Configuring `vitest.config.ts` / `jest.config.ts` (`ts-jest` / native ESM), separating fast `test:unit` from DB-backed `test:integration` (`maxWorkers: 1` or per-wor...

Subtopics Covered (8):
  • Configuring `vitest.config.ts` / `jest.config.ts` (`ts-jest` / native ESM)
  • Separating fast `test:unit` from DB-backed `test:integration` (`maxWorkers: 1` or per-worker DB schema!)
  • Environment setup
โ†’ What Topic Is Next: Next Topic 16.8: Node.js Testing Best Practices & Handle Cleanup
Guide โ†’

Closing Prisma (`$disconnect`), Mongoose (`disconnect`), and Redis (`quit`) in `afterAll`, using `--detectOpenHandles`, and avoiding port collisions (`supertest` bin...

Subtopics Covered (8):
  • Closing Prisma (`$disconnect`)
  • Mongoose (`disconnect`)
  • Redis (`quit`) in `afterAll`
โ†’ What Topic Is Next: Next Topic 16.9: Supertest Express HTTP Testing in Depth
Guide โ†’

`request(app).post("/api/v1/auth/login").set("Authorization", ...).send(...)` AND `request.agent(app)` for automatic `Set-Cookie` / `Cookie` jar persistence across r...

Subtopics Covered (8):
  • `request(app).post("/api/v1/auth/login").set("Authorization"
  • ...).send(...)`
  • `request.agent(app)` for automatic `Set-Cookie` / `Cookie` jar persistence across refresh/CSRF calls!
โ†’ What Topic Is Next: Next Topic 16.10: Assertions and Expressive Matchers
Guide โ†’

`toEqual`, `toMatchObject`, `expect.any(String)`, `expect.stringMatching()`, `.rejects.toThrow(ConflictError)`, and asserting absence of sensitive keys (`expect(res....

Subtopics Covered (8):
  • `toEqual`
  • `toMatchObject`
  • `expect.any(String)`
โ†’ What Topic Is Next: Next Topic 16.11: Test Lifecycle Hooks (beforeAll, beforeEach, afterEach, afterAll)
Guide โ†’

Connecting DB pools once in `beforeAll`, resetting table rows + `vi.restoreAllMocks()` in `beforeEach`/`afterEach`, and disconnecting pools in `afterAll`

Subtopics Covered (8):
  • Connecting DB pools once in `beforeAll`
  • Resetting table rows + `vi.restoreAllMocks()` in `beforeEach`/`afterEach`
  • Disconnecting pools in `afterAll`
โ†’ What Topic Is Next: Next Topic 16.12: Test Factories and Data Builders
Guide โ†’

Creating composable `buildUserOverrides({ role = "USER", isVerified = true } = {})` factories generating unique emails/SKUs (`crypto.randomUUID()`) per call

Subtopics Covered (8):
  • Creating composable `buildUserOverrides({ role = "USER"
  • IsVerified = true } = {})` factories generating unique emails/SKUs (`crypto.randomUUID()`) per call
  • Production Backend Pitfall & Guardrail (Test Factories and Data Builders)
โ†’ What Topic Is Next: Next Topic 16.13: Mocking, Stubbing and Fake Timers
Guide โ†’

Using `vi.useFakeTimers()` / `jest.useFakeTimers()` + `advanceTimersByTime(16 * 60 * 1000)` to test `15-minute` token expiry and `15-minute` rate-limit resets in `1...

Subtopics Covered (8):
  • Using `vi.useFakeTimers()` / `jest.useFakeTimers()` + `advanceTimersByTime(16 * 60 * 1000)` to test `15-minute` token expiry
  • `15-minute` rate-limit resets in `1 millisecond` (never `await sleep(60000)` in tests!)!
  • Production Backend Pitfall & Guardrail (Mocking, Stubbing and Fake Timers)
โ†’ What Topic Is Next: Next Topic 16.14: Dependency Mocking Boundaries (What to Mock vs Keep Real)
Guide โ†’

Golden rule: **Mock external third-party network boundaries** (SMTP, OAuth token endpoint, Payment Gateway HTTP); **DO NOT mock your own database, Zod schemas, or Ex...

Subtopics Covered (8):
  • Golden rule: **Mock external third-party network boundaries** (SMTP
  • OAuth token endpoint
  • Payment Gateway HTTP)
โ†’ What Topic Is Next: Next Topic 16.15: Database Testing & Fast Table Cleanup
Guide โ†’

Querying `pg_tables` (`schemaname = 'public'` excluding `_prisma_migrations`) to execute a single `TRUNCATE TABLE ... RESTART IDENTITY CASCADE` in `< 8ms` between in...

Subtopics Covered (8):
  • Querying `pg_tables` (`schemaname = 'public'` excluding `_prisma_migrations`) to execute a single `TRUNCATE TABLE ... RESTART IDENTITY CASCADE` in `< 8ms` between integration tests!
  • Production Backend Pitfall & Guardrail (Database Testing & Fast Table Cleanup)
  • Hands-On TypeScript / Node.js Implementation (Database Testing & Fast Table Cleanup)
โ†’ What Topic Is Next: Next Topic 16.16: Authentication Testing Matrix
Guide โ†’

Systematic tests: valid signup/login, duplicate email (`409`), wrong password (`401`), unverified login policy, expired JWT (`401`), wrong-secret JWT (`401`), `alg:...

Subtopics Covered (8):
  • Systematic tests: valid signup/login
  • Duplicate email (`409`)
  • Wrong password (`401`)
โ†’ What Topic Is Next: Next Topic 16.17: Authorization and BOLA Security Testing
Guide โ†’

Matrix testing `(Anonymous, Customer A, Customer B, Support, Admin)` ร— `(Read Own, Read Other, Mutate Other, Admin Route)` verifying `401`/`403`/`404` on every unaut...

Subtopics Covered (8):
  • Matrix testing `(Anonymous
  • Customer A
  • Customer B
โ†’ What Topic Is Next: Next Topic 16.18: Negative, Boundary and Concurrency Race Testing
Guide โ†’

Firing `await Promise.all(Array.from({ length: 10 }, () => request(app).post("/coupons/redeem")))` on a `maxUses = 1` coupon or `qty = 1` item โ€” proving **1 succeeds...

Subtopics Covered (8):
  • Firing `await Promise.all(Array.from({ length: 10 }
  • () => request(app).post("/coupons/redeem")))` on a `maxUses = 1` coupon or `qty = 1` item โ€” proving **1 succeeds (`200`)
  • 9 fail (`409`)**!
โ†’ What Topic Is Next: Next Topic 16.19: API Contract Testing Fundamentals
Guide โ†’

Validating every `Supertest` response JSON against your published OpenAPI 3.1 response schema so undocumented status codes or missing required fields fail tests auto...

Subtopics Covered (8):
  • Validating every `Supertest` response JSON against your published OpenAPI 3.1 response schema so undocumented status codes or missing required fields fail tests automatically
  • Production Backend Pitfall & Guardrail (API Contract Testing Fundamentals)
  • Hands-On TypeScript / Node.js Implementation (API Contract Testing Fundamentals)
โ†’ What Topic Is Next: Next Topic 16.20: Test Coverage Gates and Branch Coverage
Guide โ†’

Measuring Statements, Branches (`if/else`, `??`, `?:`), Functions, and Lines (`coverageThreshold: { global: { branches: 80, lines: 80 } }`) โ€” focusing on critical au...

Subtopics Covered (8):
  • Measuring Statements
  • Branches (`if/else`
  • `??`
โ†’ What Topic Is Next: Next Topic 16.21: ESLint Static Analysis for Async TypeScript
Guide โ†’

ESLint v9 flat config (`eslint.config.mjs`) + `typescript-eslint` type-aware rules: **`@typescript-eslint/no-floating-promises`** (catches forgotten `await`!), `no-m...

Subtopics Covered (8):
  • ESLint v9 flat config (`eslint.config.mjs`) + `typescript-eslint` type-aware rules: **`@typescript-eslint/no-floating-promises`** (catches forgotten `await`!)
  • `no-misused-promises` (Express async callback trap!)
  • `no-explicit-any`!
โ†’ What Topic Is Next: Next Topic 16.22: Prettier Code Formatting
Guide โ†’

`.prettierrc` + `eslint-config-prettier` + `prettier --check .` in CI eliminating bikeshedding formatting debates in Pull Requests

Subtopics Covered (8):
  • `.prettierrc` + `eslint-config-prettier` + `prettier --check .` in CI eliminating bikeshedding formatting debates in Pull Requests
  • Production Backend Pitfall & Guardrail (Prettier Code Formatting)
  • Hands-On TypeScript / Node.js Implementation (Prettier Code Formatting)
โ†’ What Topic Is Next: Next Topic 16.23: TypeScript Strict Compiler Checks in CI
Guide โ†’

Running `tsc --noEmit` in CI (because fast test runners like `vitest`/`swc`/`esbuild` transpile TS WITHOUT typechecking!)

Subtopics Covered (8):
  • Running `tsc --noEmit` in CI (because fast test runners like `vitest`/`swc`/`esbuild` transpile TS WITHOUT typechecking!)
  • Production Backend Pitfall & Guardrail (TypeScript Strict Compiler Checks in CI)
  • Hands-On TypeScript / Node.js Implementation (TypeScript Strict Compiler Checks in CI)
โ†’ What Topic Is Next: Next Topic 16.24: Backend Code Review Standards
Guide โ†’

Reviewing PRs systematically for: BOLA ownership, SQL/NoSQL parameterization, transaction boundaries, N+1 queries, missing timeouts/idempotency, unredacted logs, and...

Subtopics Covered (8):
  • Reviewing PRs systematically for: BOLA ownership
  • SQL/NoSQL parameterization
  • Transaction boundaries
โ†’ What Topic Is Next: Next Topic 16.25: Continuous Test Execution & Project 4 Delivery
Guide โ†’

Automating `lint + typecheck + unit + integration (with Postgres/Redis service containers)` on every push and completing **Project 4: Secure Authentication and Autho...

Subtopics Covered (8):
  • Automating `lint + typecheck + unit + integration (with Postgres/Redis service containers)` on every push
  • Completing **Project 4: Secure Authentication
  • Authorization Service**
โ†’ What Topic Is Next: Module 16 Capstone (Project 4: Secure Authentication and Authorization Service) โ†’ Next Topic 17.1: Redis Architecture and Docker Setup

Broken authentication, token theft, missing BOLA checks, and brute-force credential stuffing account for the majority of severe backend breaches. Build a standalone, reusable **Secure Authentication and Authorization Service** in **Node.js, Express.js, TypeScript 5, PostgreSQL (Prisma), and Redis** implementing registration, email verification, password reset, `Argon2id` hashing, short-lived JWT access tokens + rotated `HttpOnly` refresh-token families with reuse detection, RBAC + granular permissions, OAuth 2.0 (`PKCE` + `state`) login, Redis Lua rate limiting, and immutable security audit logs โ€” backed by `>= 80%` `Jest`/`Vitest` + `Supertest` coverage.

โ€ข Standalone TypeScript + Express + PostgreSQL + Redis AuthN/AuthZ Service
โ€ข Rotated Refresh-Token Family Reuse Detector + OAuth2 PKCE + RBAC/Permission/API-Key Middleware
โ€ข Redis Lua Rate Limiter + Immutable Audit Trail + `>= 80%` Coverage `Supertest` Security Suite

Module Learning & Hands-On Objectives

โœ“ Choose optimal Redis data structures (`String`, `Hash`, `List`, `Set`, `Sorted Set`) and namespace keys with explicit TTLs.
โœ“ Implement Cache-Aside, deterministic write invalidation, TTL jitter, and Single-Flight / Mutex cache-stampede protection.
โœ“ Build atomic Lua-backed Sliding-Window rate limiters and safe owner-token Distributed Locks in `ioredis`.
โœ“ Configure `RDB`/`AOF` persistence & `maxmemory-policy` and prove `5โ€“10x` latency/RPS improvements with `autocannon`.
Guide โ†’

Why single-threaded in-memory Redis executes `100,000+ ops/sec` at sub-millisecond latency (zero context-switching/lock overhead + multiplexed `epoll` I/O), `redis:7...

Subtopics Covered (8):
  • Why single-threaded in-memory Redis executes `100
  • 000+ ops/sec` at sub-millisecond latency (zero context-switching/lock overhead + multiplexed `epoll` I/O)
  • `redis:7-alpine`
โ†’ What Topic Is Next: Next Topic 17.2: Redis Data Types Overview
Guide โ†’

Choosing the right native structure (`String`, `Hash`, `List`, `Set`, `Sorted Set / ZSET`, `Stream`) instead of serializing giant JSON strings for tiny field updates

Subtopics Covered (8):
  • Choosing the right native structure (`String`
  • `Hash`
  • `List`
โ†’ What Topic Is Next: Next Topic 17.3: Strings, Hashes, Lists and Sets
Guide โ†’

`SET key val EX 300 NX` (atomic set-if-not-exists + expiry!), `INCR`/`DECR`, `HSET`/`HMGET`, `LPUSH`/`RPOP`, and `SADD`/`SISMEMBER`/`SCARD` unique counters

Subtopics Covered (8):
  • `SET key val EX 300 NX` (atomic set-if-not-exists + expiry!)
  • `INCR`/`DECR`
  • `HSET`/`HMGET`
โ†’ What Topic Is Next: Next Topic 17.4: Sorted Sets (ZSET) for Leaderboards & Sliding Windows
Guide โ†’

`ZADD key score member`, `ZINCRBY`, `ZREVRANGE` top-K rankings in `O(log N + K)`, `ZREMRANGEBYSCORE` pruning expired timestamps, and `ZCARD`

Subtopics Covered (8):
  • `ZADD key score member`
  • `ZINCRBY`
  • `ZREVRANGE` top-K rankings in `O(log N + K)`
โ†’ What Topic Is Next: Next Topic 17.5: Redis Commands, Expiration, SCAN and Pipelining
Guide โ†’

`EXPIRE`/`PEXPIRE`, `TTL`/`PTTL`, cursor-based `SCAN 0 MATCH prefix:* COUNT 100`, `UNLINK` (async non-blocking memory free vs blocking `DEL` on huge keys!), and `red...

Subtopics Covered (8):
  • `EXPIRE`/`PEXPIRE`
  • `TTL`/`PTTL`
  • Cursor-based `SCAN 0 MATCH prefix:* COUNT 100`
โ†’ What Topic Is Next: Next Topic 17.6: Key Naming Conventions and Memory Modelling
Guide โ†’

Colon-delimited hierarchical keys `{service}:{version}:{entity}:{id}` (`catalog:v1:product:SKU-101` โ€” bump `v1 -> v2` on DTO schema changes to avoid deserialization...

Subtopics Covered (8):
  • Colon-delimited hierarchical keys `{service}:{version}:{entity}:{id}` (`catalog:v1:product:SKU-101` โ€” bump `v1 -> v2` on DTO schema changes to avoid deserialization crashes during rolling deploys!)
  • Production Backend Pitfall & Guardrail (Key Naming Conventions and Memory Modelling)
  • Hands-On TypeScript / Node.js Implementation (Key Naming Conventions and Memory Modelling)
โ†’ What Topic Is Next: Next Topic 17.7: Node.js Redis Integration (ioredis & Lua Atomicity)
Guide โ†’

`new Redis(url, { maxRetriesPerRequest: 3, enableReadyCheck: true, lazyConnect: true })`, error event handling, and `redis.eval(luaScript, numKeys, ...keys, ...args)...

Subtopics Covered (8):
  • `new Redis(url
  • { maxRetriesPerRequest: 3
  • EnableReadyCheck: true
โ†’ What Topic Is Next: Next Topic 17.8: Caching Fundamentals (When to Cache & Hit-Ratio Math)
Guide โ†’

Effective latency `L_eff = hit_rate * L_cache + (1 - hit_rate) * L_db` (`95%` hit @ `0.5ms` + `5%` miss @ `40ms` = `2.47ms` avg!), read-heavy high-fanout candidates...

Subtopics Covered (8):
  • Effective latency `L_eff = hit_rate * L_cache + (1 - hit_rate) * L_db` (`95%` hit @ `0.5ms` + `5%` miss @ `40ms` = `2.47ms` avg!)
  • Read-heavy high-fanout candidates vs write-heavy/strictly-real-time non-candidates
  • Production Backend Pitfall & Guardrail (Caching Fundamentals (When to Cache & Hit-Ratio Math))
โ†’ What Topic Is Next: Next Topic 17.9: Cache-Aside (Lazy Loading) Pattern
Guide โ†’

Read path: `1) Check Redis -> Hit? Return parsed -> 2) Miss? Query DB -> 3) Populate Redis w/ TTL -> Return` + caching negative `"__NULL__"` sentinels (`short 30s TT...

Subtopics Covered (8):
  • Read path: `1) Check Redis -> Hit? Return parsed -> 2) Miss? Query DB -> 3) Populate Redis w/ TTL -> Return` + caching negative `"__NULL__"` sentinels (`short 30s TTL`) to block **Cache Penetration** attacks on non-existent IDs!
  • Production Backend Pitfall & Guardrail (Cache-Aside (Lazy Loading) Pattern)
  • Hands-On TypeScript / Node.js Implementation (Cache-Aside (Lazy Loading) Pattern)
โ†’ What Topic Is Next: Next Topic 17.10: Read-Through, Write-Through and Write-Behind Concepts
Guide โ†’

Comparing **Cache-Aside** (only requested items cached), **Write-Through** (write updates DB + Cache synchronously), and **Write-Behind** (write hits Redis fast -> a...

Subtopics Covered (8):
  • Comparing **Cache-Aside** (only requested items cached)
  • **Write-Through** (write updates DB + Cache synchronously)
  • **Write-Behind** (write hits Redis fast -> async batch flushes to DB
โ†’ What Topic Is Next: Next Topic 17.11: Deterministic Cache Invalidation
Guide โ†’

Why **deleting (`UNLINK`/`DEL`)** the cache key AFTER the DB transaction commits beats overwriting the cache value (avoids out-of-order concurrent write overwrite ra...

Subtopics Covered (8):
  • Why **deleting (`UNLINK`/`DEL`)** the cache key AFTER the DB transaction commits beats overwriting the cache value (avoids out-of-order concurrent write overwrite races!)
  • Production Backend Pitfall & Guardrail (Deterministic Cache Invalidation)
  • Hands-On TypeScript / Node.js Implementation (Deterministic Cache Invalidation)
โ†’ What Topic Is Next: Next Topic 17.12: TTL Strategies and Expiry Jitter (Preventing Cache Avalanche)
Guide โ†’

Why warming 10,000 product keys at boot with exact `EX 3600` causes all 10,000 keys to expire at the EXACT same second 1 hour later (`Cache Avalanche`!) -> adding ra...

Subtopics Covered (8):
  • Why warming 10
  • 000 product keys at boot with exact `EX 3600` causes all 10
  • 000 keys to expire at the EXACT same second 1 hour later (`Cache Avalanche`!) -> adding random jitter `baseTtl + randomInt(0
โ†’ What Topic Is Next: Next Topic 17.13: Database Query Caching
Guide โ†’

Hashing normalized query filter objects (`sha256(canonicalJson)`) into versioned cache keys (`catalog:v1:list:ver_${version}:${filterHash}`) bumped atomically via `I...

Subtopics Covered (8):
  • Hashing normalized query filter objects (`sha256(canonicalJson)`) into versioned cache keys (`catalog:v1:list:ver_${version}:${filterHash}`) bumped atomically via `INCR catalog:v1:version` on catalog writes!
  • Production Backend Pitfall & Guardrail (Database Query Caching)
  • Hands-On TypeScript / Node.js Implementation (Database Query Caching)
โ†’ What Topic Is Next: Next Topic 17.14: Session and Auth Metadata Storage in Redis
Guide โ†’

Storing `sess:${sid}`, user permission sets (`auth:v1:perms:${userId}` `TTL 5m`), OTP counters, and `revoked:jti:${jti}` with automatic sub-millisecond expiry

Subtopics Covered (8):
  • Storing `sess:${sid}`
  • User permission sets (`auth:v1:perms:${userId}` `TTL 5m`)
  • OTP counters
โ†’ What Topic Is Next: Next Topic 17.15: API Response Caching Middleware
Guide โ†’

Caching serialized JSON + `ETag` (`If-None-Match` -> `304 Not Modified` saving bandwidth!) strictly on `GET` public/tenant-scoped endpoints (`NEVER` cache personaliz...

Subtopics Covered (8):
  • Caching serialized JSON + `ETag` (`If-None-Match` -> `304 Not Modified` saving bandwidth!) strictly on `GET` public/tenant-scoped endpoints (`NEVER` cache personalized responses under a shared public key!)
  • Production Backend Pitfall & Guardrail (API Response Caching Middleware)
  • Hands-On TypeScript / Node.js Implementation (API Response Caching Middleware)
โ†’ What Topic Is Next: Next Topic 17.16: Redis-Based Sliding-Window & Token-Bucket Rate Limiting
Guide โ†’

Atomic Lua Sliding-Window Log (`ZREMRANGEBYSCORE` old hits -> `ZCARD` check `< limit` -> `ZADD now reqUuid` -> `PEXPIRE`) preventing the `2x` boundary burst flaw of...

Subtopics Covered (8):
  • Atomic Lua Sliding-Window Log (`ZREMRANGEBYSCORE` old hits -> `ZCARD` check `< limit` -> `ZADD now reqUuid` -> `PEXPIRE`) preventing the `2x` boundary burst flaw of naive Fixed-Window counters!
  • Production Backend Pitfall & Guardrail (Redis-Based Sliding-Window & Token-Bucket Rate Limiting)
  • Hands-On TypeScript / Node.js Implementation (Redis-Based Sliding-Window & Token-Bucket Rate Limiting)
โ†’ What Topic Is Next: Next Topic 17.17: Distributed Locks Fundamentals
Guide โ†’

Acquiring `SET lock:${resource} ${ownerUuid} PX ${ttlMs} NX` AND releasing ONLY via atomic Lua `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del"...

Subtopics Covered (8):
  • Acquiring `SET lock:${resource} ${ownerUuid} PX ${ttlMs} NX`
  • Releasing ONLY via atomic Lua `if redis.call("get"
  • KEYS[1]) == ARGV[1] then return redis.call("del"
โ†’ What Topic Is Next: Next Topic 17.18: Cache Consistency Patterns
Guide โ†’

Understanding why distributed Cache + DB is eventually consistent unless serialized, handling stale reads safely, and NEVER treating ephemeral cache as the authorita...

Subtopics Covered (8):
  • Understanding why distributed Cache + DB is eventually consistent unless serialized
  • Handling stale reads safely
  • NEVER treating ephemeral cache as the authoritative balance before charging money!
โ†’ What Topic Is Next: Next Topic 17.19: Cache Stampede (Thundering Herd) Prevention
Guide โ†’

When a hot homepage key expires under `5,000 RPS`, `500` requests simultaneously miss Redis and slam PostgreSQL! Defenses: (1) **In-Process Single-Flight Promise Map...

Subtopics Covered (8):
  • When a hot homepage key expires under `5
  • 000 RPS`
  • `500` requests simultaneously miss Redis
โ†’ What Topic Is Next: Next Topic 17.20: Redis Persistence (RDB vs AOF) and Eviction Policies
Guide โ†’

`RDB` point-in-time fork snapshots vs `AOF` (`appendfsync everysec`) durability, and why **Cache Redis** uses `maxmemory-policy allkeys-lru` whereas **BullMQ Queue R...

Subtopics Covered (8):
  • `RDB` point-in-time fork snapshots vs `AOF` (`appendfsync everysec`) durability
  • Why **Cache Redis** uses `maxmemory-policy allkeys-lru` whereas **BullMQ Queue Redis** MUST use **`noeviction`** (evicting job keys silently drops background jobs!!)!
  • Production Backend Pitfall & Guardrail (Redis Persistence (RDB vs AOF) and Eviction Policies)
โ†’ What Topic Is Next: Next Topic 17.21: Performance Benchmarking Before & After Redis
Guide โ†’

Running reproducible load benchmarks with `autocannon -c 100 -d 15` measuring `Req/Sec`, `p50`, `p95`, `p99` latency, and PostgreSQL CPU drop

Subtopics Covered (8):
  • Running reproducible load benchmarks with `autocannon -c 100 -d 15` measuring `Req/Sec`
  • `p50`
  • `p95`
โ†’ What Topic Is Next: Module 17 Capstone (Week 17 Lab Build: Redis 7 Cache-Aside, Single-Flight Stampede Shield & Redlock Service) โ†’ Next Topic 18.1: Synchronous vs Asynchronous Processing

Implement a typed `ioredis` caching layer featuring Cache-Aside with jittered TTLs, in-process `Map<string, Promise<T>>` Single-Flight stampede coalescing, tag/version invalidation, ZSET leaderboards, and Lua compare-and-delete distributed locks.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Design idempotent, retry-safe background worker pipelines with exponential backoff and Dead-Letter Queues (`DLQ`).
โœ“ Build production `BullMQ` Producers, Workers, Delayed Jobs, Repeatable Schedules, and concurrency/rate-limited processors.
โœ“ Publish and consume persistent `RabbitMQ` messages across `direct`, `fanout`, `topic`, and `headers` exchanges with manual `ack` and `DLX`/`DLQ` routing.
โœ“ Explain `Apache Kafka` brokers, partitioned ordering keys, replication, consumer groups, and offset replayability.
Guide โ†’

Keeping user-facing HTTP critical path minimal (`validate + write order = 25ms`) while pushing non-blocking side effects (invoice PDF, email, analytics, webhook deli...

Subtopics Covered (8):
  • Keeping user-facing HTTP critical path minimal (`validate + write order = 25ms`) while pushing non-blocking side effects (invoice PDF
  • Email
  • Analytics
โ†’ What Topic Is Next: Next Topic 18.2: Background Job Architecture
Guide โ†’

Producer (API container enqueues compact JSON `{ orderId }` โ€” NEVER `10 MB` blobs!) -> Durable Broker -> Independent Worker Processes -> Result/Audit Store

Subtopics Covered (8):
  • Producer (API container enqueues compact JSON `{ orderId }` โ€” NEVER `10 MB` blobs!) -> Durable Broker -> Independent Worker Processes -> Result/Audit Store
  • Production Backend Pitfall & Guardrail (Background Job Architecture)
  • Hands-On TypeScript / Node.js Implementation (Background Job Architecture)
โ†’ What Topic Is Next: Next Topic 18.3: Job Queues and Isolated Worker Pools
Guide โ†’

Separating fast high-priority queues (`otp-emails` SLA `< 3s`) from slow bulk queues (`monthly-csv-exports`) so 10,000 CSV exports NEVER delay login OTPs (`Head-of-L...

Subtopics Covered (8):
  • Separating fast high-priority queues (`otp-emails` SLA `< 3s`) from slow bulk queues (`monthly-csv-exports`) so 10
  • 000 CSV exports NEVER delay login OTPs (`Head-of-Line Blocking` prevention!)
  • Production Backend Pitfall & Guardrail (Job Queues and Isolated Worker Pools)
โ†’ What Topic Is Next: Next Topic 18.4: Scheduled and Recurring Jobs
Guide โ†’

Cron-driven recurring maintenance vs per-entity delayed timers (`check unpaid order #901 in 15m`)

Subtopics Covered (8):
  • Cron-driven recurring maintenance vs per-entity delayed timers (`check unpaid order #901 in 15m`)
  • Production Backend Pitfall & Guardrail (Scheduled and Recurring Jobs)
  • Hands-On TypeScript / Node.js Implementation (Scheduled and Recurring Jobs)
โ†’ What Topic Is Next: Next Topic 18.5: Job Retries and Exponential Backoff
Guide โ†’

`attempts: 5`, `backoff: { type: "exponential", delay: 2000 }` (`2s -> 4s -> 8s -> 16s -> 32s`) vs failing immediately (`UnrecoverableError`) on permanent `400` inva...

Subtopics Covered (8):
  • `attempts: 5`
  • `backoff: { type: "exponential"
  • Delay: 2000 }` (`2s -> 4s -> 8s -> 16s -> 32s`) vs failing immediately (`UnrecoverableError`) on permanent `400` invalid-email errors!
โ†’ What Topic Is Next: Next Topic 18.6: Failed Jobs and Dead-Letter Handling (DLQ)
Guide โ†’

Routing poison-pill messages that exhaust all `attempts` into a retained Dead-Letter Queue (`DLQ`) with error stack, attempt count, and admin replay tooling

Subtopics Covered (8):
  • Routing poison-pill messages that exhaust all `attempts` into a retained Dead-Letter Queue (`DLQ`) with error stack
  • Attempt count
  • Admin replay tooling
โ†’ What Topic Is Next: Next Topic 18.7: Idempotent Job Processing
Guide โ†’

Why EVERY queue guarantees **At-Least-Once** delivery (worker crash right after sending email / charging card but right BEFORE `ack` replays the job!) -> enforcing d...

Subtopics Covered (8):
  • Why EVERY queue guarantees **At-Least-Once** delivery (worker crash right after sending email / charging card but right BEFORE `ack` replays the job!) -> enforcing deterministic `jobId` + DB idempotency state!
  • Production Backend Pitfall & Guardrail (Idempotent Job Processing)
  • Hands-On TypeScript / Node.js Implementation (Idempotent Job Processing)
โ†’ What Topic Is Next: Next Topic 18.8: Job Queue Monitoring and Operational Health
Guide โ†’

Tracking `waiting`, `active`, `delayed`, `failed` counts, oldest-waiting job age (`queue lag`), and stalled-job recovery rates

Subtopics Covered (8):
  • Tracking `waiting`
  • `active`
  • `delayed`
โ†’ What Topic Is Next: Next Topic 18.9: BullMQ Installation and Architecture
Guide โ†’

Modern TypeScript-native `bullmq` (`Redis Streams` + atomic Lua scripts replacing legacy `bull`), separate `ioredis` connections for `Queue` vs blocking `Worker` (`m...

Subtopics Covered (8):
  • Modern TypeScript-native `bullmq` (`Redis Streams` + atomic Lua scripts replacing legacy `bull`)
  • Separate `ioredis` connections for `Queue` vs blocking `Worker` (`maxRetriesPerRequest: null` required on Worker connection!)
  • Production Backend Pitfall & Guardrail (BullMQ Installation and Architecture)
โ†’ What Topic Is Next: Next Topic 18.10: BullMQ Queues and Workers
Guide โ†’

Typed `new Queue<OrderEmailPayload, EmailResult, "send-receipt">(name, opts)` and `new Worker(name, async (job) => { ... }, { connection, concurrency: 10 })` + `awai...

Subtopics Covered (8):
  • Typed `new Queue<OrderEmailPayload
  • EmailResult
  • "send-receipt">(name
โ†’ What Topic Is Next: Next Topic 18.11: BullMQ Producers and Deduplicated Job IDs
Guide โ†’

`queue.add("send-receipt", payload, { jobId: \`receipt-\${orderId}\` })` โ€” passing a deterministic `jobId` prevents duplicate waiting jobs for the same order automat...

Subtopics Covered (8):
  • `queue.add("send-receipt"
  • Payload
  • { jobId: \`receipt-\${orderId}\` })` โ€” passing a deterministic `jobId` prevents duplicate waiting jobs for the same order automatically!
โ†’ What Topic Is Next: Next Topic 18.12: BullMQ Job Options and Memory Hygiene
Guide โ†’

`attempts`, `backoff`, `priority` (`1` = highest!), and **`removeOnComplete: { age: 3600, count: 1000 }` + `removeOnFail: { age: 86400 * 7, count: 5000 }`** (prevent...

Subtopics Covered (8):
  • `attempts`
  • `backoff`
  • `priority` (`1` = highest!)
โ†’ What Topic Is Next: Next Topic 18.13: Delayed Jobs in BullMQ
Guide โ†’

`queue.add("expire-unpaid-order", { orderId }, { delay: 15 * 60 * 1000, jobId: \`expire-\${orderId}\` })` promoted automatically from ZSET to waiting stream when due

Subtopics Covered (8):
  • `queue.add("expire-unpaid-order"
  • { orderId }
  • { delay: 15 * 60 * 1000
โ†’ What Topic Is Next: Next Topic 18.14: Repeatable / Job Schedulers in BullMQ
Guide โ†’

`queue.upsertJobScheduler("nightly-reconcile", { pattern: "0 2 * * *", tz: "Asia/Kolkata" }, { name: "reconcile" })` running cluster-safely ONCE per cron tick across...

Subtopics Covered (8):
  • `queue.upsertJobScheduler("nightly-reconcile"
  • { pattern: "0 2 * * *"
  • Tz: "Asia/Kolkata" }
โ†’ What Topic Is Next: Next Topic 18.15: Worker Concurrency and Outbound Rate Limiters
Guide โ†’

`concurrency: 15` (parallel async I/O jobs per worker) + `limiter: { max: 14, duration: 1000 }` (pacing outbound calls to respect third-party SMTP/SMS `14 emails/sec...

Subtopics Covered (8):
  • `concurrency: 15` (parallel async I/O jobs per worker) + `limiter: { max: 14
  • Duration: 1000 }` (pacing outbound calls to respect third-party SMTP/SMS `14 emails/sec` provider limits!)
  • Production Backend Pitfall & Guardrail (Worker Concurrency and Outbound Rate Limiters)
โ†’ What Topic Is Next: Next Topic 18.16: BullMQ Job Events and Progress Reporting
Guide โ†’

`await job.updateProgress(45)`, worker `.on("completed")` / `.on("failed")` / `.on("error")` (ALWAYS attach `.on("error")` on `Worker` & `Queue`!), and cross-process...

Subtopics Covered (8):
  • `await job.updateProgress(45)`
  • Worker `.on("completed")` / `.on("failed")` / `.on("error")` (ALWAYS attach `.on("error")` on `Worker` & `Queue`!)
  • Cross-process `QueueEvents`
โ†’ What Topic Is Next: Next Topic 18.17: Failed Job Management & Bull Board
Guide โ†’

Mounting `@bull-board/express` behind strict `ADMIN` RBAC, inspecting stacktraces (`job.failedReason`, `job.stacktrace`), `job.retry()`, and `UnrecoverableError`

Subtopics Covered (8):
  • Mounting `@bull-board/express` behind strict `ADMIN` RBAC
  • Inspecting stacktraces (`job.failedReason`
  • `job.stacktrace`)
โ†’ What Topic Is Next: Next Topic 18.18: RabbitMQ AMQP 0-9-1 Messaging Architecture
Guide โ†’

TCP Connection (`1` per process!) -> Multiplexed lightweight `Channel`s -> `Exchange` (receives from Producer) -> `Bindings` -> `Queue` (buffers messages) -> `Consum...

Subtopics Covered (8):
  • TCP Connection (`1` per process!) -> Multiplexed lightweight `Channel`s -> `Exchange` (receives from Producer) -> `Bindings` -> `Queue` (buffers messages) -> `Consumer` (`amqplib`)
  • Production Backend Pitfall & Guardrail (RabbitMQ AMQP 0-9-1 Messaging Architecture)
  • Hands-On TypeScript / Node.js Implementation (RabbitMQ AMQP 0-9-1 Messaging Architecture)
โ†’ What Topic Is Next: Next Topic 18.19: Exchanges and Queues (`durable: true`)
Guide โ†’

Why Producers NEVER publish directly to a Queue in AMQP โ€” Producers publish to an **Exchange**, and Exchanges route copies to bound Queues (`assertExchange(..., { du...

Subtopics Covered (8):
  • Why Producers NEVER publish directly to a Queue in AMQP โ€” Producers publish to an **Exchange**
  • Exchanges route copies to bound Queues (`assertExchange(...
  • { durable: true })`
โ†’ What Topic Is Next: Next Topic 18.20: Direct, Fanout, Topic and Headers Exchanges
Guide โ†’

`direct` (exact routingKey match), `fanout` (broadcast copy to ALL bound queues, e.g., `user.deleted`!), `topic` (`*` single word, `#` zero-or-more words, e.g., `ord...

Subtopics Covered (8):
  • `direct` (exact routingKey match)
  • `fanout` (broadcast copy to ALL bound queues
  • E.g.
โ†’ What Topic Is Next: Next Topic 18.21: Routing Keys and Topic Wildcards
Guide โ†’

Designing dot-delimited routing taxonomies `<domain>.<entity>.<event>.<region>` (`commerce.order.created.in`), matching `commerce.order.*.*` vs `commerce.#`

Subtopics Covered (8):
  • Designing dot-delimited routing taxonomies `<domain>.<entity>.<event>.<region>` (`commerce.order.created.in`)
  • Matching `commerce.order.*.*` vs `commerce.#`
  • Production Backend Pitfall & Guardrail (Routing Keys and Topic Wildcards)
โ†’ What Topic Is Next: Next Topic 18.22: Producers, Publisher Confirms and Consumer Prefetch
Guide โ†’

Using `createConfirmChannel()` (waits for broker disk persistence ack!) + checking `channel.publish()` boolean backpressure + setting **`channel.prefetch(10)`** on C...

Subtopics Covered (8):
  • Using `createConfirmChannel()` (waits for broker disk persistence ack!) + checking `channel.publish()` boolean backpressure + setting **`channel.prefetch(10)`** on Consumers!
  • Production Backend Pitfall & Guardrail (Producers, Publisher Confirms and Consumer Prefetch)
  • Hands-On TypeScript / Node.js Implementation (Producers, Publisher Confirms and Consumer Prefetch)
โ†’ What Topic Is Next: Next Topic 18.23: Manual Acknowledgments (ack / nack)
Guide โ†’

Setting `{ noAck: false }`, calling `channel.ack(msg)` ONLY AFTER DB commit succeeds, and calling `channel.nack(msg, false, false)` (route to DLQ, NOT infinite immed...

Subtopics Covered (8):
  • Setting `{ noAck: false }`
  • Calling `channel.ack(msg)` ONLY AFTER DB commit succeeds
  • Calling `channel.nack(msg
โ†’ What Topic Is Next: Next Topic 18.24: RabbitMQ Retry Strategies (TTL Delay Queues)
Guide โ†’

Implementing non-blocking delayed retries in RabbitMQ using Wait Queues (`x-message-ttl: 5000`, `x-dead-letter-exchange: main.ex`) tracking retry count in `msg.prope...

Subtopics Covered (8):
  • Implementing non-blocking delayed retries in RabbitMQ using Wait Queues (`x-message-ttl: 5000`
  • `x-dead-letter-exchange: main.ex`) tracking retry count in `msg.properties.headers["x-retry-count"]`
  • Production Backend Pitfall & Guardrail (RabbitMQ Retry Strategies (TTL Delay Queues))
โ†’ What Topic Is Next: Next Topic 18.25: Dead-Letter Exchanges (DLX) and Dead-Letter Queues (DLQ)
Guide โ†’

Configuring `arguments: { "x-dead-letter-exchange": "orders.dlx", "x-dead-letter-routing-key": "orders.failed" }` on primary queues so rejected/expired messages land...

Subtopics Covered (8):
  • Configuring `arguments: { "x-dead-letter-exchange": "orders.dlx"
  • "x-dead-letter-routing-key": "orders.failed" }` on primary queues so rejected/expired messages land safely in `orders.dlq`
  • Production Backend Pitfall & Guardrail (Dead-Letter Exchanges (DLX) and Dead-Letter Queues (DLQ))
โ†’ What Topic Is Next: Next Topic 18.26: Apache Kafka Architecture (Distributed Commit Log)
Guide โ†’

Why Kafka is an **immutable append-only event log** (consumers pull & advance offsets; reading a message does NOT delete it!) vs RabbitMQ queue deletion on `ack`, KR...

Subtopics Covered (8):
  • Why Kafka is an **immutable append-only event log** (consumers pull & advance offsets
  • Reading a message does NOT delete it!) vs RabbitMQ queue deletion on `ack`
  • KRaft metadata mode (no ZooKeeper!)
โ†’ What Topic Is Next: Next Topic 18.27: Kafka Brokers and Topics
Guide โ†’

Multi-broker clusters, Topic retention (`retention.ms = 7 days` or `compact` log compaction keeping latest value per key), and sequential disk I/O + OS pagecache zer...

Subtopics Covered (8):
  • Multi-broker clusters
  • Topic retention (`retention.ms = 7 days` or `compact` log compaction keeping latest value per key)
  • Sequential disk I/O + OS pagecache zero-copy speed
โ†’ What Topic Is Next: Next Topic 18.28: Partitions, Ordering Keys and Replication
Guide โ†’

Why **ordering in Kafka is guaranteed ONLY WITHIN a single Partition** -> hashing **`key: orderId`** (`murmur2(key) % numPartitions`) ensures `OrderCreated -> OrderP...

Subtopics Covered (8):
  • Why **ordering in Kafka is guaranteed ONLY WITHIN a single Partition** -> hashing **`key: orderId`** (`murmur2(key) % numPartitions`) ensures `OrderCreated -> OrderPaid -> OrderShipped` for `order_42` ALWAYS land in the SAME partition in exact order!!
  • Production Backend Pitfall & Guardrail (Partitions, Ordering Keys and Replication)
  • Hands-On TypeScript / Node.js Implementation (Partitions, Ordering Keys and Replication)
โ†’ What Topic Is Next: Next Topic 18.29: Kafka Producers (acks, Idempotence & Batching)
Guide โ†’

`acks: -1` (`all` in-sync replicas `ISR` confirm!), `idempotent: true` producer sequence numbers preventing duplicate appends on network retry, and `linger.ms` / `sn...

Subtopics Covered (8):
  • `acks: -1` (`all` in-sync replicas `ISR` confirm!)
  • `idempotent: true` producer sequence numbers preventing duplicate appends on network retry
  • `linger.ms` / `snappy` batching
โ†’ What Topic Is Next: Next Topic 18.30: Consumer Groups and Parallelism Ceiling
Guide โ†’

Within ONE `groupId` (`inventory-svc-group`), each Partition is assigned to AT MOST ONE consumer instance (`12 partitions` + `4 consumers` = `3 partitions each`; `12...

Subtopics Covered (8):
  • Within ONE `groupId` (`inventory-svc-group`)
  • Each Partition is assigned to AT MOST ONE consumer instance (`12 partitions` + `4 consumers` = `3 partitions each`
  • `12 partitions` + `15 consumers` = **`3 consumers sit 100% IDLE`**!)
โ†’ What Topic Is Next: Next Topic 18.31: Consumer Offsets, Commits and Event-Driven Concepts
Guide โ†’

`__consumer_offsets` topic, committing `offset + 1` ONLY AFTER processing + idempotent DB write succeeds (`autoCommit: false`), consumer lag monitoring (`latestOffse...

Subtopics Covered (8):
  • `__consumer_offsets` topic
  • Committing `offset + 1` ONLY AFTER processing + idempotent DB write succeeds (`autoCommit: false`)
  • Consumer lag monitoring (`latestOffset - committedOffset`)
โ†’ What Topic Is Next: Module 18 Capstone (Week 18 Lab Build: BullMQ Retry/DLQ Worker + RabbitMQ Topic Exchange & Kafka Partition Lab) โ†’ Next Topic 19.1: Real-Time Application Architecture

Build a fault-tolerant background processing pipeline combining `BullMQ` (exponential backoff, deterministic `jobId` deduplication, DLQ inspection, PDF invoice generation) with a `RabbitMQ` topic exchange + DLX consumer and `Kafka` partition key ordering demo.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Contrast Short Polling, Long Polling, SSE, and full-duplex WebSockets across latency, directionality, and server overhead.
โœ“ Build strictly typed `Socket.IO` servers in TypeScript supporting rooms, namespaces, private/group messaging, and presence.
โœ“ Enforce JWT handshake authentication, per-room ownership authorization (`BOLA`), and Zod payload validation on WebSocket events.
โœ“ Scale `Socket.IO` across multiple Node/Docker instances seamlessly using `@socket.io/redis-adapter`.
Guide โ†’

Bidirectional low-latency use cases (chat, collaborative cursors, live bidding) vs unidirectional server-push (`SSE` for live order/ticker feeds), stateful TCP socke...

Subtopics Covered (8):
  • Bidirectional low-latency use cases (chat
  • Collaborative cursors
  • Live bidding) vs unidirectional server-push (`SSE` for live order/ticker feeds)
โ†’ What Topic Is Next: Next Topic 19.2: Short Polling, Long Polling and SSE vs WebSockets
Guide โ†’

Short Polling (high wasted overhead), HTTP Long Polling (held request), Server-Sent Events (`text/event-stream`, HTTP/2 friendly one-way server->client), and WebSock...

Subtopics Covered (8):
  • Short Polling (high wasted overhead)
  • HTTP Long Polling (held request)
  • Server-Sent Events (`text/event-stream`
โ†’ What Topic Is Next: Next Topic 19.3: WebSocket Protocol (RFC 6455 Handshake & Framing)
Guide โ†’

`GET / HTTP/1.1` + `Upgrade: websocket` + `Sec-WebSocket-Key` -> `101 Switching Protocols` + `Sec-WebSocket-Accept`, lightweight binary/text frames, opcode `0x9` Pin...

Subtopics Covered (8):
  • `GET / HTTP/1.1` + `Upgrade: websocket` + `Sec-WebSocket-Key` -> `101 Switching Protocols` + `Sec-WebSocket-Accept`
  • Lightweight binary/text frames
  • Opcode `0x9` Ping / `0xA` Pong
โ†’ What Topic Is Next: Next Topic 19.4: Managing Stateful WebSocket Connections & Heartbeats
Guide โ†’

Detecting half-open "zombie" TCP connections (mobile tunnel drop without FIN packet!) via `pingInterval` (`25s`) & `pingTimeout` (`20s`), and bounding `maxHttpBuffer...

Subtopics Covered (8):
  • Detecting half-open "zombie" TCP connections (mobile tunnel drop without FIN packet!) via `pingInterval` (`25s`) & `pingTimeout` (`20s`)
  • Bounding `maxHttpBufferSize` (`e.g. 64 KB`
  • Default `1 MB`!)
โ†’ What Topic Is Next: Next Topic 19.5: Socket.IO Architecture vs Raw ws
Guide โ†’

What `Socket.IO` adds on top of WebSockets: automatic reconnection with backoff, packet buffering, acknowledgments (`emitWithAck`), Rooms, Namespaces, HTTP long-poll...

Subtopics Covered (8):
  • What `Socket.IO` adds on top of WebSockets: automatic reconnection with backoff
  • Packet buffering
  • Acknowledgments (`emitWithAck`)
โ†’ What Topic Is Next: Next Topic 19.6: Typed Server-Side Socket.IO Integration in TypeScript
Guide โ†’

Attaching `new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>(httpServer, { cors })` onto the SAME `http.Server` as Express!

Subtopics Covered (8):
  • Attaching `new Server<ClientToServerEvents
  • ServerToClientEvents
  • InterServerEvents
โ†’ What Topic Is Next: Next Topic 19.7: Connection and Disconnection Lifecycle Events
Guide โ†’

`io.on("connection", socket => ...)`, `socket.on("disconnecting")` (`socket.rooms` is STILL populated here!) vs `socket.on("disconnect", reason => ...)` (`socket.roo...

Subtopics Covered (8):
  • `io.on("connection"
  • Socket => ...)`
  • `socket.on("disconnecting")` (`socket.rooms` is STILL populated here!) vs `socket.on("disconnect"
โ†’ What Topic Is Next: Next Topic 19.8: Targeted Emits, Broadcasting and Acknowledgments
Guide โ†’

`socket.emit` (sender only), `socket.broadcast.emit` (everyone EXCEPT sender), `io.to(room).emit` (all in room), and callback/Promise acknowledgments (`socket.timeou...

Subtopics Covered (8):
  • `socket.emit` (sender only)
  • `socket.broadcast.emit` (everyone EXCEPT sender)
  • `io.to(room).emit` (all in room)
โ†’ What Topic Is Next: Next Topic 19.9: Rooms and Namespaces
Guide โ†’

Auto-joining every authenticated socket into `socket.join(\`user:\${socket.data.userId}\`)` (supports 3 open browser tabs + mobile app effortlessly!), resource rooms...

Subtopics Covered (8):
  • Auto-joining every authenticated socket into `socket.join(\`user:\${socket.data.userId}\`)` (supports 3 open browser tabs + mobile app effortlessly!)
  • Resource rooms `order:${orderId}`
  • Isolated `/admin` Namespaces (`io.of("/admin")`)
โ†’ What Topic Is Next: Next Topic 19.10: Private 1-to-1 Messaging Architecture
Guide โ†’

Persist-First flow: `1) Validate Zod -> 2) Authorize conversation membership -> 3) Persist message in PostgreSQL/MongoDB with clientIdempKey -> 4) Emit to user:${rec...

Subtopics Covered (8):
  • Persist-First flow: `1) Validate Zod -> 2) Authorize conversation membership -> 3) Persist message in PostgreSQL/MongoDB with clientIdempKey -> 4) Emit to user:${recipientId} & user:${senderId} -> 5) Ack messageId`
  • Production Backend Pitfall & Guardrail (Private 1-to-1 Messaging Architecture)
  • Hands-On TypeScript / Node.js Implementation (Private 1-to-1 Messaging Architecture)
โ†’ What Topic Is Next: Next Topic 19.11: Group / Channel Messaging
Guide โ†’

Channel membership rooms (`channel:${channelId}`), typing indicators (`volatile.emit` โ€” droppable if congested!), read-cursor watermarks (`lastReadMessageId`), and b...

Subtopics Covered (8):
  • Channel membership rooms (`channel:${channelId}`)
  • Typing indicators (`volatile.emit` โ€” droppable if congested!)
  • Read-cursor watermarks (`lastReadMessageId`)
โ†’ What Topic Is Next: Next Topic 19.12: Online and Offline Presence Tracking
Guide โ†’

Multi-device accurate presence in Redis: `SADD presence:user:${uid} ${socket.id}` on connect + `SREM` on disconnect (`user is offline ONLY when SCARD === 0`!) + hear...

Subtopics Covered (8):
  • Multi-device accurate presence in Redis: `SADD presence:user:${uid} ${socket.id}` on connect + `SREM` on disconnect (`user is offline ONLY when SCARD === 0`!) + heartbeat TTL fallback for crashed nodes!
  • Production Backend Pitfall & Guardrail (Online and Offline Presence Tracking)
  • Hands-On TypeScript / Node.js Implementation (Online and Offline Presence Tracking)
โ†’ What Topic Is Next: Next Topic 19.13: Authentication for WebSockets (io.use Middleware)
Guide โ†’

Verifying `socket.handshake.auth.token` (or `HttpOnly` cookie on handshake โ€” NEVER `?token=jwt` in URL query string which leaks into Nginx/proxy access logs!!) insid...

Subtopics Covered (8):
  • Verifying `socket.handshake.auth.token` (or `HttpOnly` cookie on handshake โ€” NEVER `?token=jwt` in URL query string which leaks into Nginx/proxy access logs!!) inside `io.use(async (socket
  • Next) => ...)` + periodic token-expiry re-check!
  • Production Backend Pitfall & Guardrail (Authentication for WebSockets (io.use Middleware))
โ†’ What Topic Is Next: Next Topic 19.14: Authorization for Rooms (Preventing Real-Time BOLA)
Guide โ†’

Validating DB ownership inside `socket.on("order:subscribe", async ({ orderId }, ack) => { const ok = await orderSvc.canView(socket.data.userId, orderId); if (!ok) r...

Subtopics Covered (8):
  • Validating DB ownership inside `socket.on("order:subscribe"
  • Async ({ orderId }
  • Ack) => { const ok = await orderSvc.canView(socket.data.userId
โ†’ What Topic Is Next: Next Topic 19.15: Reconnection Strategies and Missed-Event Recovery
Guide โ†’

Randomized reconnection jitter (`reconnectionDelay`, `randomizationFactor: 0.5` preventing `10,000` clients reconnecting at the exact same millisecond after a deploy...

Subtopics Covered (8):
  • Randomized reconnection jitter (`reconnectionDelay`
  • `randomizationFactor: 0.5` preventing `10
  • 000` clients reconnecting at the exact same millisecond after a deploy!)
โ†’ What Topic Is Next: Next Topic 19.16: WebSocket Error Handling, Zod Validation & Event Rate Limiting
Guide โ†’

Wrapping every `socket.on(...)` listener in a safe `withSocketGuard(schema, rateLimiter, handler)` because an unhandled `async` rejection inside `socket.on()` crashe...

Subtopics Covered (8):
  • Wrapping every `socket.on(...)` listener in a safe `withSocketGuard(schema
  • RateLimiter
  • Handler)` because an unhandled `async` rejection inside `socket.on()` crashes Node (Express `errorMiddleware` does NOT cover Socket.IO events!)!
โ†’ What Topic Is Next: Next Topic 19.17: Horizontal Scaling Challenge for Stateful WebSockets
Guide โ†’

Why scaling to `N` Node containers breaks in-memory `io.to("user:42").emit(...)` + why Socket.IO HTTP long-polling fallback requires sticky sessions (or `transports:...

Subtopics Covered (8):
  • Why scaling to `N` Node containers breaks in-memory `io.to("user:42").emit(...)` + why Socket.IO HTTP long-polling fallback requires sticky sessions (or `transports: ["websocket"]` direct upgrade!)
  • Production Backend Pitfall & Guardrail (Horizontal Scaling Challenge for Stateful WebSockets)
  • Hands-On TypeScript / Node.js Implementation (Horizontal Scaling Challenge for Stateful WebSockets)
โ†’ What Topic Is Next: Next Topic 19.18: Redis Adapter Fundamentals (@socket.io/redis-adapter)
Guide โ†’

Creating dedicated `pubClient` and `subClient = pubClient.duplicate()`, attaching `io.adapter(createAdapter(pubClient, subClient))` so `io.to("user:42").emit(...)` f...

Subtopics Covered (8):
  • Creating dedicated `pubClient`
  • `subClient = pubClient.duplicate()`
  • Attaching `io.adapter(createAdapter(pubClient
โ†’ What Topic Is Next: Next Topic 19.19: Real-Time Notification Service Architecture
Guide โ†’

End-to-end flow: Domain Service emits `OrderShipped` -> BullMQ/RabbitMQ Consumer persists `notifications` DB row (`isRead: false`) -> publishes via Redis Emitter to...

Subtopics Covered (8):
  • End-to-end flow: Domain Service emits `OrderShipped` -> BullMQ/RabbitMQ Consumer persists `notifications` DB row (`isRead: false`) -> publishes via Redis Emitter to `user:${userId}` room -> unread badge updates in `< 20ms`!
  • Production Backend Pitfall & Guardrail (Real-Time Notification Service Architecture)
  • Hands-On TypeScript / Node.js Implementation (Real-Time Notification Service Architecture)
โ†’ What Topic Is Next: Next Topic 19.20: Event-Driven Real-Time Design Patterns
Guide โ†’

Out-of-order frame protection (`version` / sequence numbers on state updates so v2 doesnโ€™t overwrite v3!), backpressure coalescing, and graceful socket drain on depl...

Subtopics Covered (8):
  • Out-of-order frame protection (`version` / sequence numbers on state updates so v2 doesnโ€™t overwrite v3!)
  • Backpressure coalescing
  • Graceful socket drain on deploy
โ†’ What Topic Is Next: Module 19 Capstone (Week 19 Lab Build: Multi-Node Authenticated Socket.IO Real-Time Notification & Room Server) โ†’ Next Topic 20.1: Monolithic vs Microservices Architecture

Build a JWT-authenticated `Socket.IO` server using `@socket.io/redis-adapter` across 2 Node instances, auto-joining `user:${userId}` multi-tab rooms, enforcing server-side BOLA room-subscription checks, Redis presence heartbeats, and acknowledgments.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Define clean DDD Bounded Contexts and choose pragmatically between a Modular Monolith and Microservices.
โœ“ Enforce Database-per-Service isolation and coordinate cross-service workflows using the **Saga Pattern** (compensating transactions) + **Transactional Outbox**.
โœ“ Protect synchronous inter-service calls with strict timeouts, jittered retries, Circuit Breakers, Bulkheads, and scoped service JWTs.
โœ“ Deliver **Month 5 Project (Project 5): 7-Service E-Commerce Microservices Backend**.
Guide โ†’

Comparing Deployment simplicity, ACID single-DB joins, and `0ms` in-process calls (Monolith) vs Independent team/service scaling, fault isolation, and polyglot datab...

Subtopics Covered (8):
  • Comparing Deployment simplicity
  • ACID single-DB joins
  • `0ms` in-process calls (Monolith) vs Independent team/service scaling
โ†’ What Topic Is Next: Next Topic 20.2: Modular Monolith Architecture
Guide โ†’

Starting new products as a strictly modularized single deployable (`modules/users`, `modules/catalog`, `modules/orders` with zero cross-schema SQL joins!) and extrac...

Subtopics Covered (8):
  • Starting new products as a strictly modularized single deployable (`modules/users`
  • `modules/catalog`
  • `modules/orders` with zero cross-schema SQL joins!)
โ†’ What Topic Is Next: Next Topic 20.3: Microservice Principles (Single Responsibility & Loose Coupling)
Guide โ†’

Independent deployability, backward-compatible API/event contracts, autonomous data ownership, and resilience when peer services are down

Subtopics Covered (8):
  • Independent deployability
  • Backward-compatible API/event contracts
  • Autonomous data ownership
โ†’ What Topic Is Next: Next Topic 20.4: Defining Clean Service Boundaries
Guide โ†’

Splitting by **Business Capability** (`User`, `Product Catalog`, `Inventory`, `Cart`, `Order`, `Payment`, `Notification`), NOT by technical layer (`DatabaseService`,...

Subtopics Covered (8):
  • Splitting by **Business Capability** (`User`
  • `Product Catalog`
  • `Inventory`
โ†’ What Topic Is Next: Next Topic 20.5: Domain-Driven Design (DDD) Bounded Contexts Fundamentals
Guide โ†’

Why `"Product"` means `{ title, description, images, specs }` inside **Catalog Context** (`MongoDB`), `{ sku, warehouseId, qtyOnHand, reservedQty }` inside **Invento...

Subtopics Covered (8):
  • Why `"Product"` means `{ title
  • Description
  • Images
โ†’ What Topic Is Next: Next Topic 20.6: Service-to-Service Communication Overview
Guide โ†’

Choosing **Synchronous Request/Response** (`REST` / `gRPC` for immediate read queries) vs **Asynchronous Event-Driven** (`RabbitMQ` / `Kafka` for state changes & mul...

Subtopics Covered (8):
  • Choosing **Synchronous Request/Response** (`REST` / `gRPC` for immediate read queries) vs **Asynchronous Event-Driven** (`RabbitMQ` / `Kafka` for state changes & multi-step workflows)
  • Production Backend Pitfall & Guardrail (Service-to-Service Communication Overview)
  • Hands-On TypeScript / Node.js Implementation (Service-to-Service Communication Overview)
โ†’ What Topic Is Next: Next Topic 20.7: REST-Based Inter-Service Communication
Guide โ†’

Internal HTTP clients using pooled `fetch` / `undici` keep-alive connections, mandatory `AbortSignal.timeout(3000)`, propagating `X-Correlation-Id`, and strict Zod r...

Subtopics Covered (8):
  • Internal HTTP clients using pooled `fetch` / `undici` keep-alive connections
  • Mandatory `AbortSignal.timeout(3000)`
  • Propagating `X-Correlation-Id`
โ†’ What Topic Is Next: Next Topic 20.8: gRPC and Protocol Buffers Fundamentals
Guide โ†’

Contract-first `.proto` IDL schemas, strongly typed generated TypeScript stubs, compact binary Protobuf serialization (`3โ€“7x` smaller than JSON), and multiplexed HTT...

Subtopics Covered (8):
  • Contract-first `.proto` IDL schemas
  • Strongly typed generated TypeScript stubs
  • Compact binary Protobuf serialization (`3โ€“7x` smaller than JSON)
โ†’ What Topic Is Next: Next Topic 20.9: API Gateway Architecture
Guide โ†’

Single external entrypoint (`gateway` / `Nginx` + Gateway service) handling TLS, CORS, Edge Rate Limiting, JWT verification (forwarding verified `X-User-Id`/`X-User-...

Subtopics Covered (8):
  • Single external entrypoint (`gateway` / `Nginx` + Gateway service) handling TLS
  • CORS
  • Edge Rate Limiting
โ†’ What Topic Is Next: Next Topic 20.10: Service Discovery
Guide โ†’

Client-side vs Server-side discovery; how Docker Compose internal DNS (`http://inventory-svc:3003`) and container orchestrator Services resolve healthy container IPs...

Subtopics Covered (8):
  • Client-side vs Server-side discovery
  • How Docker Compose internal DNS (`http://inventory-svc:3003`)
  • Container orchestrator Services resolve healthy container IPs automatically without hardcoded IPs!
โ†’ What Topic Is Next: Next Topic 20.11: Centralized and Validated Service Configuration
Guide โ†’

Shared typed config validation pattern per service (`PORT`, `SERVICE_NAME`, `LOG_LEVEL`, own `DATABASE_URL`, `BROKER_URL`, `INTERNAL_JWT_PUBLIC_KEY`)

Subtopics Covered (8):
  • Shared typed config validation pattern per service (`PORT`
  • `SERVICE_NAME`
  • `LOG_LEVEL`
โ†’ What Topic Is Next: Next Topic 20.12: Database-per-Service Principle
Guide โ†’

`user-svc` owns `users_db` (Postgres), `product-svc` owns `catalog_db` (MongoDB), `cart-svc` owns `cart_redis` (Redis), `inventory-svc` owns `inventory_db` (Postgres...

Subtopics Covered (8):
  • `user-svc` owns `users_db` (Postgres)
  • `product-svc` owns `catalog_db` (MongoDB)
  • `cart-svc` owns `cart_redis` (Redis)
โ†’ What Topic Is Next: Next Topic 20.13: Event-Driven Microservice Architecture
Guide โ†’

Publishing immutable past-tense **Domain Events** (`OrderCreated`, `StockReserved`, `StockInsufficient`, `PaymentSucceeded`, `PaymentFailed`) carrying `{ eventId, ev...

Subtopics Covered (8):
  • Publishing immutable past-tense **Domain Events** (`OrderCreated`
  • `StockReserved`
  • `StockInsufficient`
โ†’ What Topic Is Next: Next Topic 20.14: Message Brokers in Microservices (RabbitMQ vs Kafka)
Guide โ†’

When RabbitMQ topic exchanges shine (task routing, flexible bindings, per-message TTL/DLQ) vs when Kafka shines (high-throughput ordered event streaming, multi-day r...

Subtopics Covered (8):
  • When RabbitMQ topic exchanges shine (task routing
  • Flexible bindings
  • Per-message TTL/DLQ) vs when Kafka shines (high-throughput ordered event streaming
โ†’ What Topic Is Next: Next Topic 20.15: Synchronous vs Asynchronous Communication Matrix
Guide โ†’

Queries needing immediate read response (`GET /cart`) -> Sync HTTP/gRPC + Cache; Cross-service multi-step state mutations (`Checkout Saga`) -> Async Events / Command...

Subtopics Covered (8):
  • Queries needing immediate read response (`GET /cart`) -> Sync HTTP/gRPC + Cache
  • Cross-service multi-step state mutations (`Checkout Saga`) -> Async Events / Commands!
  • Production Backend Pitfall & Guardrail (Synchronous vs Asynchronous Communication Matrix)
โ†’ What Topic Is Next: Next Topic 20.16: Why Distributed 2PC Transactions Fail & the Dual-Write Trap
Guide โ†’

Why cross-service `XA / 2PC` locks kill availability, AND why naive `await db.saveOrder(); await broker.publish("OrderCreated");` loses events if the process crashes...

Subtopics Covered (8):
  • Why cross-service `XA / 2PC` locks kill availability
  • Why naive `await db.saveOrder()
  • Await broker.publish("OrderCreated")
โ†’ What Topic Is Next: Next Topic 20.17: Saga Pattern Fundamentals (Choreography, Orchestration & Compensations)
Guide โ†’

Forward steps + **Compensating Transactions** on failure: `1) Create Order (PENDING) -> 2) Reserve Stock -> 3) Charge Payment -> [IF PAYMENT FAILS] -> Compensate: Re...

Subtopics Covered (8):
  • Forward steps + **Compensating Transactions** on failure: `1) Create Order (PENDING) -> 2) Reserve Stock -> 3) Charge Payment -> [IF PAYMENT FAILS] -> Compensate: Release Stock -> Mark Order PAYMENT_FAILED`!
  • Production Backend Pitfall & Guardrail (Saga Pattern Fundamentals (Choreography, Orchestration & Compensations))
  • Hands-On TypeScript / Node.js Implementation (Saga Pattern Fundamentals (Choreography, Orchestration & Compensations))
โ†’ What Topic Is Next: Next Topic 20.18: Eventual Consistency in Practice
Guide โ†’

Read-your-own-writes UX, maintaining local read projections (`order-svc` listens to `ProductUpdated` or snapshots SKU summary), and handling out-of-order event arriv...

Subtopics Covered (8):
  • Read-your-own-writes UX
  • Maintaining local read projections (`order-svc` listens to `ProductUpdated` or snapshots SKU summary)
  • Handling out-of-order event arrival
โ†’ What Topic Is Next: Next Topic 20.19: End-to-End Idempotency in Distributed Systems
Guide โ†’

Recording `processed_events(event_id PRIMARY KEY, processed_at)` INSIDE the same local DB transaction as the consumerโ€™s state update (`Inventory` stock deduction)!

Subtopics Covered (8):
  • Recording `processed_events(event_id PRIMARY KEY
  • Processed_at)` INSIDE the same local DB transaction as the consumerโ€™s state update (`Inventory` stock deduction)!
  • Production Backend Pitfall & Guardrail (End-to-End Idempotency in Distributed Systems)
โ†’ What Topic Is Next: Next Topic 20.20: Retries and Exponential Backoff with Full Jitter
Guide โ†’

Why synchronized fixed-interval retries (`100` callers all retrying at exact `+2.000s`, `+4.000s`) hammer a recovering service back down vs **Full Jitter** `random(0...

Subtopics Covered (8):
  • Why synchronized fixed-interval retries (`100` callers all retrying at exact `+2.000s`
  • `+4.000s`) hammer a recovering service back down vs **Full Jitter** `random(0
  • Min(cap
โ†’ What Topic Is Next: Next Topic 20.21: Circuit Breakers (CLOSED -> OPEN -> HALF_OPEN)
Guide โ†’

Tracking rolling failure rate: when downstream `payment-svc` hits `>= 5` consecutive timeouts/5xx, trip **OPEN** (fail fast in `0.1ms` for `15s` cooldown without tyi...

Subtopics Covered (8):
  • Tracking rolling failure rate: when downstream `payment-svc` hits `>= 5` consecutive timeouts/5xx
  • Trip **OPEN** (fail fast in `0.1ms` for `15s` cooldown without tying up sockets!) -> test 1 probe in **HALF_OPEN** -> **CLOSED** on success!
  • Production Backend Pitfall & Guardrail (Circuit Breakers (CLOSED -> OPEN -> HALF_OPEN))
โ†’ What Topic Is Next: Next Topic 20.22: Timeouts and Bulkhead Isolation
Guide โ†’

Propagating deadline budgets (`AbortSignal.timeout`) AND **Bulkheads** (separate connection/concurrency pools per downstream dependency so a slow `ReportingService`...

Subtopics Covered (8):
  • Propagating deadline budgets (`AbortSignal.timeout`)
  • **Bulkheads** (separate connection/concurrency pools per downstream dependency so a slow `ReportingService` cannot starve `InventoryService` HTTP sockets!)
  • Production Backend Pitfall & Guardrail (Timeouts and Bulkhead Isolation)
โ†’ What Topic Is Next: Next Topic 20.23: Distributed Tracing Fundamentals (OpenTelemetry)
Guide โ†’

W3C `traceparent` header (`00-<traceId>-<spanId>-01`) propagating one `traceId` across HTTP calls AND RabbitMQ/Kafka message headers (`OpenTelemetry` Node SDK -> `Ja...

Subtopics Covered (8):
  • W3C `traceparent` header (`00-<traceId>-<spanId>-01`) propagating one `traceId` across HTTP calls
  • RabbitMQ/Kafka message headers (`OpenTelemetry` Node SDK -> `Jaeger`)
  • Production Backend Pitfall & Guardrail (Distributed Tracing Fundamentals (OpenTelemetry))
โ†’ What Topic Is Next: Next Topic 20.24: Correlation IDs Across Async Flows
Guide โ†’

Generating `correlationId` at API Gateway entry, storing in `AsyncLocalStorage`, forwarding in every outbound HTTP call, Outbox row, Queue job, and Socket.IO emit!

Subtopics Covered (8):
  • Generating `correlationId` at API Gateway entry
  • Storing in `AsyncLocalStorage`
  • Forwarding in every outbound HTTP call
โ†’ What Topic Is Next: Next Topic 20.25: Centralized Structured Logging
Guide โ†’

Standardizing Pino JSON log schema (`timestamp`, `level`, `service`, `env`, `correlationId`, `userId`, `durationMs`, `msg`) written to `stdout` (`12-Factor` log rout...

Subtopics Covered (8):
  • Standardizing Pino JSON log schema (`timestamp`
  • `level`
  • `service`
โ†’ What Topic Is Next: Next Topic 20.26: Microservice Security (Zero-Trust Internal Network)
Guide โ†’

Why `"itโ€™s on the internal Docker network"` is NOT sufficient auth: validating caller identity, scoping `aud: "inventory-svc"`, network segmentation (DBs unreachable...

Subtopics Covered (8):
  • Why `"itโ€™s on the internal Docker network"` is NOT sufficient auth: validating caller identity
  • Scoping `aud: "inventory-svc"`
  • Network segmentation (DBs unreachable from unrelated services)
โ†’ What Topic Is Next: Next Topic 20.27: Service-to-Service Authentication (Asymmetric JWT / HMAC & Project 5)
Guide โ†’

Signing short-lived internal tokens (`iss: "order-svc"`, `aud: "inventory-svc"`, `exp: +60s`) verified offline via `RS256`/`Ed25519` public keys (`JWKS`) โ€” and deliv...

Subtopics Covered (8):
  • Signing short-lived internal tokens (`iss: "order-svc"`
  • `aud: "inventory-svc"`
  • `exp: +60s`) verified offline via `RS256`/`Ed25519` public keys (`JWKS`) โ€”
โ†’ What Topic Is Next: Module 20 Capstone (Project 5: E-Commerce Microservices Backend) โ†’ Next Topic 21.1: Node.js CPU Profiling and Flamegraphs

When engineering orgs and domain throughput outgrow a single deployment unit, backend engineers must decompose bounded contexts cleanly without accidentally building a fragile "distributed monolith" plagued by shared DB tables, synchronous cascading timeouts, or lost domain events. Build an **E-Commerce Microservices Backend** comprising **7 independent Node.js + TypeScript services** (`User`, `Product`, `Inventory`, `Cart`, `Order`, `Payment Simulation`, and `Notification`) communicating through an API Gateway, asymmetric JWT verification, **Transactional Outbox + RabbitMQ/Kafka events**, **Saga distributed compensation**, **Redis caching**, and **BullMQ background workers**.

โ€ข 7-Service TypeScript Monorepo (`User`, `Product`, `Inventory`, `Cart`, `Order`, `Payment Simulation`, `Notification`) + Gateway
โ€ข Transactional Outbox Publisher + Idempotent RabbitMQ/Kafka Saga Consumers + Circuit Breakers
โ€ข Docker Compose Orchestration + Happy-Path & Compensation Saga E2E Test Suite + Architecture Docs

Module Learning & Hands-On Objectives

โœ“ Capture and read V8 `--cpu-prof` flamegraphs and `--heapsnapshot` retainer trees to pinpoint CPU bottlenecks and memory leaks.
โœ“ Right-size V8 `--max-old-space-size`, `libuv` threadpools, HTTP `undici` keep-alive pools, and PostgreSQL/MongoDB connection pools.
โœ“ Stress-test APIs with `autocannon` / `k6`, enforce backpressure/load-shedding, and separate `/healthz` (liveness) from `/readyz` (readiness).
โœ“ Design stateless horizontally scalable Node.js architectures with zero-downtime rolling reloads.
Guide โ†’

`node --cpu-prof dist/server.js` (or `inspector` `Profiler.start`), reading wide flat plateaus on Flamegraphs (wide bar = CPU time spent IN that function!), and `cli...

Subtopics Covered (8):
  • `node --cpu-prof dist/server.js` (or `inspector` `Profiler.start`)
  • Reading wide flat plateaus on Flamegraphs (wide bar = CPU time spent IN that function!)
  • `clinic flame`
โ†’ What Topic Is Next: Next Topic 21.2: Measuring and Alerting on Event-Loop Delay
Guide โ†’

`monitorEventLoopDelay` `p50`/`p95`/`p99` (`healthy < 20ms`, `degraded > 100ms`), why high event-loop lag delays `setTimeout` timeouts, health checks, and WebSocket...

Subtopics Covered (8):
  • `monitorEventLoopDelay` `p50`/`p95`/`p99` (`healthy < 20ms`
  • `degraded > 100ms`)
  • Why high event-loop lag delays `setTimeout` timeouts
โ†’ What Topic Is Next: Next Topic 21.3: CPU-Bound vs I/O-Bound Workloads
Guide โ†’

Classifying JSON serialization of 50k rows, image/PDF rendering, regex, compression, and crypto (`CPU-bound`) vs SQL/Mongo/Redis/HTTP queries (`I/O-bound`)

Subtopics Covered (8):
  • Classifying JSON serialization of 50k rows
  • Image/PDF rendering
  • Regex
โ†’ What Topic Is Next: Next Topic 21.4: Eliminating Hidden Blocking Operations (ReDoS & Sync Calls)
Guide โ†’

Auditing vulnerable nested-quantifier regexes (`/^(a+)+$/` -> `O(2^n)` CPU freeze on `"aaaaaaaaaaaaaaaaaaaaaaaaX"`!), replacing with linear regexes/`re2`/bounded str...

Subtopics Covered (8):
  • Auditing vulnerable nested-quantifier regexes (`/^(a+)+$/` -> `O(2^n)` CPU freeze on `"aaaaaaaaaaaaaaaaaaaaaaaaX"`!)
  • Replacing with linear regexes/`re2`/bounded string lengths (`<= 256` chars before regex!)
  • Production Backend Pitfall & Guardrail (Eliminating Hidden Blocking Operations (ReDoS & Sync Calls))
โ†’ What Topic Is Next: Next Topic 21.5: Memory Leaks and V8 Heap Snapshots
Guide โ†’

Taking TWO heap snapshots (`v8.writeHeapSnapshot()` at `t=1m` after warmup and `t=10m` after 10,000 requests) -> diffing `Delta > 0` allocated objects & inspecting t...

Subtopics Covered (8):
  • Taking TWO heap snapshots (`v8.writeHeapSnapshot()` at `t=1m` after warmup
  • `t=10m` after 10
  • 000 requests) -> diffing `Delta > 0` allocated objects & inspecting the **Retainers** path back to GC roots!
โ†’ What Topic Is Next: Next Topic 21.6: Garbage Collection Fundamentals & Container Memory Tuning
Guide โ†’

Scavenge (fast `< 2ms` nursery copy) vs Major Mark-Sweep-Compact, setting `NODE_OPTIONS="--max-old-space-size=384"` inside a `512Mi` Docker container (leaving headro...

Subtopics Covered (8):
  • Scavenge (fast `< 2ms` nursery copy) vs Major Mark-Sweep-Compact
  • Setting `NODE_OPTIONS="--max-old-space-size=384"` inside a `512Mi` Docker container (leaving headroom for RSS buffers
  • C++ OpenSSL/Prisma & stack so Linux `OOMKiller` doesnโ€™t `SIGKILL 137` the container!)
โ†’ What Topic Is Next: Next Topic 21.7: Worker Threads Pool Sizing
Guide โ†’

Sizing fixed worker-thread pools (`Math.max(1, os.availableParallelism() - 1)`) with bounded input queues (`maxQueue`) rejecting with `503` on overload

Subtopics Covered (8):
  • Sizing fixed worker-thread pools (`Math.max(1
  • Os.availableParallelism() - 1)`) with bounded input queues (`maxQueue`) rejecting with `503` on overload
  • Production Backend Pitfall & Guardrail (Worker Threads Pool Sizing)
โ†’ What Topic Is Next: Next Topic 21.8: Child Processes for Isolated Heavy External Tools
Guide โ†’

Streaming `stdin`/`stdout` to external CLI tools (`pg_dump`, image/document tools) with hard `timeout`, `killSignal`, and concurrency semaphore caps

Subtopics Covered (8):
  • Streaming `stdin`/`stdout` to external CLI tools (`pg_dump`
  • Image/document tools) with hard `timeout`
  • `killSignal`
โ†’ What Topic Is Next: Next Topic 21.9: Cluster Module vs Container Replicas
Guide โ†’

When `node:cluster` / `PM2 -i max` wins (single Linux VPS) vs when `1` single-process Node container ร— `N` Docker/orchestrator replicas wins (clean per-process cgrou...

Subtopics Covered (8):
  • When `node:cluster` / `PM2 -i max` wins (single Linux VPS) vs when `1` single-process Node container ร— `N` Docker/orchestrator replicas wins (clean per-process cgroup limits
  • Independent restarts
  • Simpler metrics)
โ†’ What Topic Is Next: Next Topic 21.10: Process Management and Crash Auto-Healing
Guide โ†’

Restart backoff delays (`exp_backoff_restart_delay`), max memory restart thresholds (`max_memory_restart: "450M"` safety net while fixing leaks), and crash-loop aler...

Subtopics Covered (8):
  • Restart backoff delays (`exp_backoff_restart_delay`)
  • Max memory restart thresholds (`max_memory_restart: "450M"` safety net while fixing leaks)
  • Crash-loop alerts
โ†’ What Topic Is Next: Next Topic 21.11: Connection Pooling Across DB, Redis and Outbound HTTP
Guide โ†’

End-to-end pool math: PostgreSQL (`connection_limit`), MongoDB (`maxPoolSize`), Redis (`ioredis`), AND Nodeโ€™s built-in `undici` global `fetch` connection poolkeep-al...

Subtopics Covered (8):
  • End-to-end pool math: PostgreSQL (`connection_limit`)
  • MongoDB (`maxPoolSize`)
  • Redis (`ioredis`)
โ†’ What Topic Is Next: Next Topic 21.12: Database Query Optimization at Scale
Guide โ†’

Eliminating `SELECT *`, batching `IN (...)` lookups, pushing aggregations into SQL/Mongo, read-replica routing for heavy analytics reports, and `statement_timeout =...

Subtopics Covered (8):
  • Eliminating `SELECT *`
  • Batching `IN (...)` lookups
  • Pushing aggregations into SQL/Mongo
โ†’ What Topic Is Next: Next Topic 21.13: Index Optimization & Write-Amplification Balance
Guide โ†’

Inspecting `pg_stat_user_indexes` (`idx_scan = 0` unused indexes slow down every `INSERT`/`UPDATE` and waste RAM!), covering `INCLUDE` indexes enabling `Index Only S...

Subtopics Covered (8):
  • Inspecting `pg_stat_user_indexes` (`idx_scan = 0` unused indexes slow down every `INSERT`/`UPDATE`
  • Waste RAM!)
  • Covering `INCLUDE` indexes enabling `Index Only Scan` (`Heap Fetches: 0`)
โ†’ What Topic Is Next: Next Topic 21.14: API Response Optimization (Compression, ETag & Projection)
Guide โ†’

Selective `brotli`/`gzip` above `1 KB` (preferring compression at **Nginx** reverse proxy so Nodeโ€™s main thread/threadpool saves `zlib` CPU!), `ETag` `304`, and spar...

Subtopics Covered (8):
  • Selective `brotli`/`gzip` above `1 KB` (preferring compression at **Nginx** reverse proxy so Nodeโ€™s main thread/threadpool saves `zlib` CPU!)
  • `ETag` `304`
  • Sparse DTOs
โ†’ What Topic Is Next: Next Topic 21.15: Pagination at Scale (Deep Offset Elimination)
Guide โ†’

Enforcing max offset caps (`page <= 100` for classic numbered pages) + switching feeds, audit logs, and exports to `O(log N)` keyset cursors (`WHERE (created_at, id)...

Subtopics Covered (8):
  • Enforcing max offset caps (`page <= 100` for classic numbered pages) + switching feeds
  • Audit logs
  • Exports to `O(log N)` keyset cursors (`WHERE (created_at
โ†’ What Topic Is Next: Next Topic 21.16: Multi-Tier Caching Strategies (L1 Memory + L2 Redis)
Guide โ†’

Tiny bounded in-process `L1 LRU` (`max: 500` items, `TTL: 5s` for ultra-hot static config/categories -> `0.002ms` zero network!) backed by `L2 Redis` (`TTL: 5m` -> `...

Subtopics Covered (8):
  • Tiny bounded in-process `L1 LRU` (`max: 500` items
  • `TTL: 5s` for ultra-hot static config/categories -> `0.002ms` zero network!) backed by `L2 Redis` (`TTL: 5m` -> `0.4ms`) + Redis Pub/Sub L1 invalidation
  • Production Backend Pitfall & Guardrail (Multi-Tier Caching Strategies (L1 Memory + L2 Redis))
โ†’ What Topic Is Next: Next Topic 21.17: Load Testing Fundamentals (autocannon & k6)
Guide โ†’

Warm-up phase -> Ramp-up (`10 -> 50 -> 200 -> 500` VUs) -> Sustained plateau -> Spike test; tracking `p95`, `p99`, error rate `< 0.1%`, and finding saturation bottle...

Subtopics Covered (8):
  • Warm-up phase -> Ramp-up (`10 -> 50 -> 200 -> 500` VUs) -> Sustained plateau -> Spike test
  • Tracking `p95`
  • `p99`
โ†’ What Topic Is Next: Next Topic 21.18: Concurrency Handling and Load Shedding
Guide โ†’

Bounding max in-flight requests per worker, shedding excess load early with fast `503 Retry-After: 2` instead of accepting 10,000 requests that all time out after 30...

Subtopics Covered (8):
  • Bounding max in-flight requests per worker
  • Shedding excess load early with fast `503 Retry-After: 2` instead of accepting 10
  • 000 requests that all time out after 30s (`Littleโ€™s Law: L = ฮป * W`)!
โ†’ What Topic Is Next: Next Topic 21.19: Horizontal vs Vertical Scaling
Guide โ†’

Vertical (`2 vCPU -> 8 vCPU`, simplest up to hardware ceiling, single point of failure) vs Horizontal (`N` stateless API containers across `2+` hosts behind Load Bal...

Subtopics Covered (8):
  • Vertical (`2 vCPU -> 8 vCPU`
  • Simplest up to hardware ceiling
  • Single point of failure) vs Horizontal (`N` stateless API containers across `2+` hosts behind Load Balancer โ€” requires zero local state: sessions/locks/sockets in Redis
โ†’ What Topic Is Next: Next Topic 21.20: Graceful Shutdown Under Active Load
Guide โ†’

Handling keep-alive idle connections vs active in-flight requests (`server.closeIdleConnections()` in Node 18.2+!), failing `/readyz` for `3โ€“5s` FIRST so Nginx stops...

Subtopics Covered (8):
  • Handling keep-alive idle connections vs active in-flight requests (`server.closeIdleConnections()` in Node 18.2+!)
  • Failing `/readyz` for `3โ€“5s` FIRST so Nginx stops sending new requests BEFORE `server.close()`!
  • Production Backend Pitfall & Guardrail (Graceful Shutdown Under Active Load)
โ†’ What Topic Is Next: Next Topic 21.21: Health Checks (/healthz Liveness vs /readyz Readiness)
Guide โ†’

CRITICAL distinction: **`GET /healthz` (Liveness)** checks ONLY that the Node event loop responds (`200 OK`, NEVER queries Postgres/Redis!) vs **`GET /readyz` (Readi...

Subtopics Covered (8):
  • CRITICAL distinction: **`GET /healthz` (Liveness)** checks ONLY that the Node event loop responds (`200 OK`
  • NEVER queries Postgres/Redis!) vs **`GET /readyz` (Readiness)** pings Postgres + Mongo + Redis (`503` stops traffic routing WITHOUT restarting containers when DB blips!)!
  • Production Backend Pitfall & Guardrail (Health Checks (/healthz Liveness vs /readyz Readiness))
โ†’ What Topic Is Next: Next Topic 21.22: High Availability Fundamentals
Guide โ†’

Eliminating Single Points of Failure (`SPOF`): redundant Load Balancers, `>= 2` API instances, PostgreSQL Primary + Streaming Standby Replica, MongoDB 3-node Replica...

Subtopics Covered (8):
  • Eliminating Single Points of Failure (`SPOF`): redundant Load Balancers
  • `>= 2` API instances
  • PostgreSQL Primary + Streaming Standby Replica
โ†’ What Topic Is Next: Module 21 Capstone (Week 21 Lab Build: Autocannon Load Benchmark, Clinic.js Flamegraph & Worker-Thread Offloader) โ†’ Next Topic 22.1: Linux Server Filesystems and Production Directory Layout

Profile an intentionally slow/leaky Node API with `autocannon`, `--inspect` heap snapshots, and `perf_hooks.monitorEventLoopDelay()`, eliminate `O(N)` event-loop stalls via `worker_threads` + `Piscina`, tune PostgreSQL pools, and cut `p99` latency by `>= 70%`.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Administer and harden Linux backend servers (`users`, `chmod`, `systemd`, `ufw` firewall, SSH keys, `journalctl` logs).
โœ“ Author optimized multi-stage non-root `Dockerfile`s and health-checked `Docker Compose` stacks (`Node.js`, `PostgreSQL`, `MongoDB`, `Redis`, `MinIO`, `Nginx`).
โœ“ Configure `Nginx` reverse proxying, `PM2` zero-downtime reloads, Domain/DNS records, and automated Letโ€™s Encrypt TLS/HTTPS.
โœ“ Automate `GitHub Actions` CI/CD pipelines, secrets management, Prometheus/health monitoring, automated backups, and production incident recovery.
Guide โ†’

Structuring `/srv/backend` or `/opt/app`, `/etc/nginx/sites-available`, `/var/log/nginx`, swap sizing, and checking inode (`df -i`) as well as block (`df -h`) exhaus...

Subtopics Covered (8):
  • Structuring `/srv/backend` or `/opt/app`
  • `/etc/nginx/sites-available`
  • `/var/log/nginx`
โ†’ What Topic Is Next: Next Topic 22.2: Linux Users, Groups and Least-Privilege Permissions
Guide โ†’

Creating dedicated unprivileged system user `useradd --system --create-home --shell /usr/sbin/nologin nodeapp`, disabling root SSH login, and scoping `sudo` strictly...

Subtopics Covered (8):
  • Creating dedicated unprivileged system user `useradd --system --create-home --shell /usr/sbin/nologin nodeapp`
  • Disabling root SSH login
  • Scoping `sudo` strictly where needed
โ†’ What Topic Is Next: Next Topic 22.3: Linux Process Management and systemd Service Units
Guide โ†’

Writing `/etc/systemd/system/backend-api.service` (`Restart=on-failure`, `RestartSec=5`, `User=nodeapp`, `EnvironmentFile=/etc/backend/api.env`, `LimitNOFILE=65535`)...

Subtopics Covered (8):
  • Writing `/etc/systemd/system/backend-api.service` (`Restart=on-failure`
  • `RestartSec=5`
  • `User=nodeapp`
โ†’ What Topic Is Next: Next Topic 22.4: Linux Networking Commands and Firewall Hardening (ufw)
Guide โ†’

`ss -tulpn`, `ip addr`, `curl -I http://127.0.0.1:3000/healthz`, `nc -zv`, and `ufw default deny incoming` allowing ONLY `22/tcp` (SSH), `80/tcp` (HTTP), and `443/tc...

Subtopics Covered (8):
  • `ss -tulpn`
  • `ip addr`
  • `curl -I http://127.0.0.1:3000/healthz`
โ†’ What Topic Is Next: Next Topic 22.5: SSH Hardening and Secure Remote Administration
Guide โ†’

Ed25519 SSH keys, `PasswordAuthentication no`, `PermitRootLogin no`, SSH bastion/port forwarding (`ssh -L 5433:127.0.0.1:5432 deploy@server` to inspect prod DB safel...

Subtopics Covered (8):
  • Ed25519 SSH keys
  • `PasswordAuthentication no`
  • `PermitRootLogin no`
โ†’ What Topic Is Next: Next Topic 22.6: Production Server Environment Variable Management
Guide โ†’

Storing `/etc/backend/api.env` (`chmod 0600`, `chown root:nodeapp` or `nodeapp:nodeapp`) outside the Git working directory so `git clean` or redeploys never touch or...

Subtopics Covered (8):
  • Storing `/etc/backend/api.env` (`chmod 0600`
  • `chown root:nodeapp` or `nodeapp:nodeapp`) outside the Git working directory so `git clean` or redeploys never touch or expose secrets
  • Production Backend Pitfall & Guardrail (Production Server Environment Variable Management)
โ†’ What Topic Is Next: Next Topic 22.7: Server Logs, logrotate and Diagnostics
Guide โ†’

`journalctl -u backend-api --since "10 min ago"`, configuring `/etc/logrotate.d/` (`daily`, `rotate 14`, `compress`, `delaycompress`), and diagnosing high load (`top...

Subtopics Covered (8):
  • `journalctl -u backend-api --since "10 min ago"`
  • Configuring `/etc/logrotate.d/` (`daily`
  • `rotate 14`
โ†’ What Topic Is Next: Next Topic 22.8: Linux Server Tuning (File Descriptors & TCP Backlog)
Guide โ†’

Raising `ulimit -n` (`nofile = 65535`, default `1024` crashes Node with `EMFILE: too many open files` at ~900 concurrent WebSockets!), `somaxconn`, and NTP time sync...

Subtopics Covered (8):
  • Raising `ulimit -n` (`nofile = 65535`
  • Default `1024` crashes Node with `EMFILE: too many open files` at ~900 concurrent WebSockets!)
  • `somaxconn`
โ†’ What Topic Is Next: Next Topic 22.9: Containerization Concepts vs Virtual Machines
Guide โ†’

Linux kernel `namespaces` (isolated PID, net, mount, user views) + `cgroups` (CPU/RAM caps) sharing the host kernel (`~20ms` boot, near-zero overhead) vs hypervisor...

Subtopics Covered (8):
  • Linux kernel `namespaces` (isolated PID
  • Net
  • Mount
โ†’ What Topic Is Next: Next Topic 22.10: Docker Engine Architecture
Guide โ†’

Docker CLI -> `dockerd` Daemon -> `containerd` -> `runc` OCI runtime, layered copy-on-write UnionFS image layers, and OCI registries (`GHCR` / Docker Hub)

Subtopics Covered (8):
  • Docker CLI -> `dockerd` Daemon -> `containerd` -> `runc` OCI runtime
  • Layered copy-on-write UnionFS image layers
  • OCI registries (`GHCR` / Docker Hub)
โ†’ What Topic Is Next: Next Topic 22.11: Docker Images and Containers Lifecycle
Guide โ†’

Immutable tagged Images (`ghcr.io/org/api:git-sha`, NEVER deploy mutable `:latest` tags in production!) vs ephemeral Containers (`docker run --rm`, `docker ps`, `doc...

Subtopics Covered (8):
  • Immutable tagged Images (`ghcr.io/org/api:git-sha`
  • NEVER deploy mutable `:latest` tags in production!) vs ephemeral Containers (`docker run --rm`
  • `docker ps`
โ†’ What Topic Is Next: Next Topic 22.12: Authoring Production Dockerfiles and .dockerignore
Guide โ†’

`FROM node:22-bookworm-slim` (avoid `alpine` `musl` libc surprises with `prisma`/`argon2`/`sharp` native binaries unless tested โ€” `bookworm-slim` uses standard `glib...

Subtopics Covered (8):
  • `FROM node:22-bookworm-slim` (avoid `alpine` `musl` libc surprises with `prisma`/`argon2`/`sharp` native binaries unless tested โ€” `bookworm-slim` uses standard `glibc`!)
  • `.dockerignore` (`node_modules`
  • `.git`
โ†’ What Topic Is Next: Next Topic 22.13: Building and Running Hardened Containers
Guide โ†’

Running as built-in non-root `USER node` (UID `1000`), `--read-only` root filesystem (`--tmpfs /tmp`), `--cap-drop=ALL`, and resource limits (`mem_limit: 512m`, `cpu...

Subtopics Covered (8):
  • Running as built-in non-root `USER node` (UID `1000`)
  • `--read-only` root filesystem (`--tmpfs /tmp`)
  • `--cap-drop=ALL`
โ†’ What Topic Is Next: Next Topic 22.14: Docker Volumes and Persistent Database Storage
Guide โ†’

Named volumes (`pg_data:/var/lib/postgresql/data`, `mongo_data:/data/db`, `redis_data:/data`, `minio_data:/data`) vs bind mounts (dev only!), and NEVER running `dock...

Subtopics Covered (8):
  • Named volumes (`pg_data:/var/lib/postgresql/data`
  • `mongo_data:/data/db`
  • `redis_data:/data`
โ†’ What Topic Is Next: Next Topic 22.15: Container Networking and Internal DNS Isolation
Guide โ†’

Custom isolated Docker networks: `edge_net` (`nginx <-> api`) vs `backend_net` (`api + worker <-> postgres + mongo + redis + minio` with `internal: true` so DB conta...

Subtopics Covered (8):
  • Custom isolated Docker networks: `edge_net` (`nginx <-> api`) vs `backend_net` (`api + worker <-> postgres + mongo + redis + minio` with `internal: true` so DB containers have ZERO external exposure!)
  • Production Backend Pitfall & Guardrail (Container Networking and Internal DNS Isolation)
  • Hands-On TypeScript / Node.js Implementation (Container Networking and Internal DNS Isolation)
โ†’ What Topic Is Next: Next Topic 22.16: Docker Compose Orchestration
Guide โ†’

Modern `compose.yaml` (`healthcheck`, `depends_on: { postgres: { condition: service_healthy } }`, `restart: unless-stopped`, `logging: { driver: "json-file", options...

Subtopics Covered (8):
  • Modern `compose.yaml` (`healthcheck`
  • `depends_on: { postgres: { condition: service_healthy } }`
  • `restart: unless-stopped`
โ†’ What Topic Is Next: Next Topic 22.17: Multi-Container Backend Stack (Node + Postgres + Mongo + Redis + MinIO)
Guide โ†’

Assembling the complete polyglot backend stack (`nginx`, `migrate`, `api`, `worker`, `postgres:16`, `mongo:7`, `redis:7`, `minio`) booting cleanly from cold start in...

Subtopics Covered (8):
  • Assembling the complete polyglot backend stack (`nginx`
  • `migrate`
  • `api`
โ†’ What Topic Is Next: Next Topic 22.18: Docker Image Optimization and Multi-Stage Builds
Guide โ†’

3-stage `Dockerfile`: Stage 1 `deps` (`npm ci`) -> Stage 2 `builder` (`npx prisma generate && npm run build` + `npm prune --omit=dev`) -> Stage 3 `runtime` (copies O...

Subtopics Covered (8):
  • 3-stage `Dockerfile`: Stage 1 `deps` (`npm ci`) -> Stage 2 `builder` (`npx prisma generate && npm run build` + `npm prune --omit=dev`) -> Stage 3 `runtime` (copies ONLY production `node_modules`
  • Generated Prisma client & `dist/` โ€” zero TypeScript compiler
  • Zero `src/`
โ†’ What Topic Is Next: Next Topic 22.19: Nginx Reverse Proxy Configuration
Guide โ†’

`upstream backend_api { server 127.0.0.1:3001; server 127.0.0.1:3002; keepalive 32; }`, `X-Real-IP` / `X-Forwarded-For` / `X-Forwarded-Proto`, `client_max_body_size...

Subtopics Covered (8):
  • `upstream backend_api { server 127.0.0.1:3001
  • Server 127.0.0.1:3002
  • Keepalive 32
โ†’ What Topic Is Next: Next Topic 22.20: PM2 Process Manager for Bare-Metal Linux Deployments
Guide โ†’

`ecosystem.config.cjs` (`instances: "max"`, `exec_mode: "cluster"`, `wait_ready: true`, `listen_timeout: 8000`, `kill_timeout: 15000`), zero-downtime `pm2 reload`, `...

Subtopics Covered (8):
  • `ecosystem.config.cjs` (`instances: "max"`
  • `exec_mode: "cluster"`
  • `wait_ready: true`
โ†’ What Topic Is Next: Next Topic 22.21: Domain and DNS Configuration
Guide โ†’

Configuring `A` (IPv4) & `AAAA` (IPv6) records for `api.yourdomain.com`, `CAA` records restricting certificate issuance to Letโ€™s Encrypt, and lowering DNS `TTL` (`30...

Subtopics Covered (8):
  • Configuring `A` (IPv4) & `AAAA` (IPv6) records for `api.yourdomain.com`
  • `CAA` records restricting certificate issuance to Letโ€™s Encrypt
  • Lowering DNS `TTL` (`300s`) 24 hours before IP migrations
โ†’ What Topic Is Next: Next Topic 22.22: SSL Certificates and HTTPS (Letโ€™s Encrypt & Certbot)
Guide โ†’

Automating free trusted TLS 1.2/1.3 certificates via `certbot --nginx -d api.example.com`, HTTP `80 -> 301 HTTPS 443` redirect, `HSTS`, OCSP stapling, and verifying...

Subtopics Covered (8):
  • Automating free trusted TLS 1.2/1.3 certificates via `certbot --nginx -d api.example.com`
  • HTTP `80 -> 301 HTTPS 443` redirect
  • `HSTS`
โ†’ What Topic Is Next: Next Topic 22.23: GitHub Actions CI/CD Workflows
Guide โ†’

Authoring `.github/workflows/ci-cd.yml` with `npm ci` caching, `postgres:16` + `mongo:7` + `redis:7` GitHub Actions `services:` containers, running `lint -> typechec...

Subtopics Covered (8):
  • Authoring `.github/workflows/ci-cd.yml` with `npm ci` caching
  • `postgres:16` + `mongo:7` + `redis:7` GitHub Actions `services:` containers
  • Running `lint -> typecheck -> prisma migrate deploy -> test -> docker build`!
โ†’ What Topic Is Next: Next Topic 22.24: Automated Deployment Workflows & Safe Rollouts
Guide โ†’

Push to `main` -> CI passes -> Build & push GHCR image (`:git-sha`) -> Deploy over SSH (`docker compose pull && docker compose run --rm migrate && docker compose up...

Subtopics Covered (8):
  • Push to `main` -> CI passes -> Build & push GHCR image (`:git-sha`) -> Deploy over SSH (`docker compose pull && docker compose run --rm migrate && docker compose up -d --remove-orphans`) -> Post-deploy `/readyz` smoke check -> Auto-rollback to previous SHA if `/readyz` fails!
  • Production Backend Pitfall & Guardrail (Automated Deployment Workflows & Safe Rollouts)
  • Hands-On TypeScript / Node.js Implementation (Automated Deployment Workflows & Safe Rollouts)
โ†’ What Topic Is Next: Next Topic 22.25: Production Observability & Server Health Monitoring
Guide โ†’

Exposing Prometheus `/metrics` (`prom-client`: HTTP request duration histograms by route/status, event-loop lag, active handles, heap bytes, DB pool queue), Grafana...

Subtopics Covered (8):
  • Exposing Prometheus `/metrics` (`prom-client`: HTTP request duration histograms by route/status
  • Event-loop lag
  • Active handles
โ†’ What Topic Is Next: Next Topic 22.26: Backup, Disaster Recovery and Production Troubleshooting
Guide โ†’

Automated encrypted off-host `pg_dump` + `mongodump` schedules with retention pruning, monthly restore drills, and the 6-step Incident Runbook (`Check /readyz -> Che...

Subtopics Covered (8):
  • Automated encrypted off-host `pg_dump` + `mongodump` schedules with retention pruning
  • Monthly restore drills
  • The 6-step Incident Runbook (`Check /readyz -> Check recent deploy diff -> Check Pino 5xx logs -> Check DB pg_stat_activity locks -> Check disk/RAM/OOM -> Rollback first
โ†’ What Topic Is Next: Module 22 Capstone (Week 22 Lab Build: 3-Stage Non-Root Docker Compose + Nginx + PM2 + GitHub Actions CI/CD Stack) โ†’ Next Topic 23.1: Interview Mastery: Closures, Prototypes, Promises & Event Loop

Containerize and deploy a polyglot Node.js + PostgreSQL + MongoDB + Redis + MinIO + Nginx stack using a `~165 MB` 3-stage non-root `Dockerfile`, dual-network `compose.yaml` with `service_healthy` checks, `PM2` cluster config, Prometheus `/metrics`, and `.github/workflows/ci-cd.yml`.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Answer rapid-fire JS/TS, V8/libuv/Streams, MongoDB/PostgreSQL/Prisma, and Auth/OWASP oral interview questions with production depth.
โœ“ Lead 45-minute Backend System Design rounds covering capacity math, schema design, caching, queues, sharding, and failure modes across all 10 classic systems.
โœ“ Complete timed 60โ€“75 minute Node.js + TypeScript Backend Machine-Coding challenges cleanly under interview pressure.
โœ“ Clear structured mock technical interviews ahead of Week 24 Capstone Defense.
Guide โ†’

Lexical closures & memory retainers, `this` & prototype delegation, Promise combinators (`all` vs `allSettled` vs `any`), `return await` inside `try/catch`, and exac...

Subtopics Covered (8):
  • Lexical closures & memory retainers
  • `this` & prototype delegation
  • Promise combinators (`all` vs `allSettled` vs `any`)
โ†’ What Topic Is Next: Next Topic 23.2: Interview Mastery: TypeScript Interfaces, Generics & Strict Narrowing
Guide โ†’

`unknown` vs `any` vs `never`, discriminated unions, custom type predicates (`x is T`), `keyof`/`typeof`/`infer`, utility types (`Pick`, `Omit`, `Partial`, `Record`)...

Subtopics Covered (8):
  • `unknown` vs `any` vs `never`
  • Discriminated unions
  • Custom type predicates (`x is T`)
โ†’ What Topic Is Next: Next Topic 23.3: Interview Mastery: Node.js V8, libuv, Streams, Workers & Memory
Guide โ†’

V8 JIT & GC generations, `libuv` epoll vs 4-thread pool (`UV_THREADPOOL_SIZE`), `Buffer` & Stream backpressure (`pipeline()`), `worker_threads` vs `cluster`, and dia...

Subtopics Covered (8):
  • V8 JIT & GC generations
  • `libuv` epoll vs 4-thread pool (`UV_THREADPOOL_SIZE`)
  • `Buffer` & Stream backpressure (`pipeline()`)
โ†’ What Topic Is Next: Next Topic 23.4: Interview Mastery: Express Middleware, Routing & Controller Architecture
Guide โ†’

Middleware execution stack, 4-arg `(err, req, res, next)` error handler mechanics, `asyncHandler` / Express 5 Promise forwarding, `keepAliveTimeout` > proxy idle tim...

Subtopics Covered (8):
  • Middleware execution stack
  • 4-arg `(err
  • Req
โ†’ What Topic Is Next: Next Topic 23.5: Interview Mastery: MongoDB Aggregation, PostgreSQL SQL, Indexes & ACID
Guide โ†’

MongoDB `$match`/`$group`/`$lookup` + `ESR` compound indexes + `.lean()`, PostgreSQL Joins, `NOT EXISTS`, Window Functions (`DENSE_RANK`, `LAG`), `EXPLAIN ANALYZE`,...

Subtopics Covered (8):
  • MongoDB `$match`/`$group`/`$lookup` + `ESR` compound indexes + `.lean()`
  • PostgreSQL Joins
  • `NOT EXISTS`
โ†’ What Topic Is Next: Next Topic 23.6: Interview Mastery: JWT Rotation, OAuth2, RBAC & OWASP API Security
Guide โ†’

Argon2id vs bcrypt, `15m` Access + `7d` rotated `HttpOnly` Refresh family reuse detection, OAuth2 PKCE + OIDC `email_verified`, RBAC + BOLA query scoping, Rate Limit...

Subtopics Covered (8):
  • Argon2id vs bcrypt
  • `15m` Access + `7d` rotated `HttpOnly` Refresh family reuse detection
  • OAuth2 PKCE + OIDC `email_verified`
โ†’ What Topic Is Next: Next Topic 23.7: System Design #1: High-Scale URL Shortener (10k Reads/sec)
Guide โ†’

Capacity math (`100:1` read:write), Base62 (`[0-9a-zA-Z]`, `7` chars = `62^7 = 3.5 trillion` URLs!) over Snowflake/Range-Allocated IDs (zero collision!), `302` (anal...

Subtopics Covered (8):
  • Capacity math (`100:1` read:write)
  • Base62 (`[0-9a-zA-Z]`
  • `7` chars = `62^7 = 3.5 trillion` URLs!) over Snowflake/Range-Allocated IDs (zero collision!)
โ†’ What Topic Is Next: Next Topic 23.8: System Design #2: Centralized Authentication & SSO Service
Guide โ†’

Multi-app OIDC/OAuth2 issuer, `Ed25519`/`RS256` key rotation via cached `/.well-known/jwks.json`, Redis rate-limit + `jti` revocation broadcast, refresh-token family...

Subtopics Covered (8):
  • Multi-app OIDC/OAuth2 issuer
  • `Ed25519`/`RS256` key rotation via cached `/.well-known/jwks.json`
  • Redis rate-limit + `jti` revocation broadcast
โ†’ What Topic Is Next: Next Topic 23.9: System Design #3: Flash-Sale E-Commerce & Order Management System
Guide โ†’

Handling `50,000` users clicking Buy on `500` iPhones at `12:00:00`: CDN/Redis catalog cache -> Lua atomic stock pre-decrement gate (blocks 49,500 oversells in `0.2m...

Subtopics Covered (8):
  • Handling `50
  • 000` users clicking Buy on `500` iPhones at `12:00:00`: CDN/Redis catalog cache -> Lua atomic stock pre-decrement gate (blocks 49
  • 500 oversells in `0.2ms` before Postgres!) -> Order Queue -> Saga Payment + `15m` unpaid expiry release!
โ†’ What Topic Is Next: Next Topic 23.10: System Design #4: Multi-Channel Notification Service (Email, SMS, Push, In-App)
Guide โ†’

Unified `POST /notify` API + Idempotency Key -> User Preference/Opt-Out filter -> Channel-isolated Priority Queues (`otp-sms` vs `promo-email`) -> Provider Adapters...

Subtopics Covered (8):
  • Unified `POST /notify` API + Idempotency Key -> User Preference/Opt-Out filter -> Channel-isolated Priority Queues (`otp-sms` vs `promo-email`) -> Provider Adapters with Circuit Breaker failover (`Vendor A -> Vendor B`) + Delivery status webhook tracker
  • Production Backend Pitfall & Guardrail (System Design #4: Multi-Channel Notification Service (Email, SMS, Push, In-App))
  • Hands-On TypeScript / Node.js Implementation (System Design #4: Multi-Channel Notification Service (Email, SMS, Push, In-App))
โ†’ What Topic Is Next: Next Topic 23.11: System Design #5: Real-Time Chat Backend (1-on-1 & Group)
Guide โ†’

Stateful WebSocket Gateway fleet + Redis Presence/Routing Registry (`userId -> gatewayNodeId`) + Message Service + Partitioned/Time-Sorted Message Store (`(conversat...

Subtopics Covered (8):
  • Stateful WebSocket Gateway fleet + Redis Presence/Routing Registry (`userId -> gatewayNodeId`) + Message Service + Partitioned/Time-Sorted Message Store (`(conversation_id
  • Message_id DESC)`) + Offline Push Notification fallback
  • Production Backend Pitfall & Guardrail (System Design #5: Real-Time Chat Backend (1-on-1 & Group))
โ†’ What Topic Is Next: Next Topic 23.12: System Design #6: Object File Storage & Media Processing Pipeline
Guide โ†’

Metadata DB (`files` table: `id`, `ownerId`, `sha256`, `status`, `size`) separated from Blob Storage (`MinIO` / Object Store): Presigned Multipart Chunked Upload (re...

Subtopics Covered (8):
  • Metadata DB (`files` table: `id`
  • `ownerId`
  • `sha256`
โ†’ What Topic Is Next: Next Topic 23.13: System Design #7: Distributed Job Scheduling System
Guide โ†’

Durable `scheduled_jobs` table (`next_run_at` indexed) -> Partitioned Scheduler Pollers using `SELECT ... WHERE next_run_at <= NOW() AND status = 'READY' FOR UPDATE...

Subtopics Covered (8):
  • Durable `scheduled_jobs` table (`next_run_at` indexed) -> Partitioned Scheduler Pollers using `SELECT ... WHERE next_run_at <= NOW()
  • Status = 'READY' FOR UPDATE SKIP LOCKED LIMIT 100` -> Worker Queue -> Heartbeat lease renewal + Dead-worker recovery!
  • Production Backend Pitfall & Guardrail (System Design #7: Distributed Job Scheduling System)
โ†’ What Topic Is Next: Next Topic 23.14: System Design #8: Distributed Rate Limiter & API Gateway
Guide โ†’

API Gateway placement, Token Bucket vs Sliding-Window Counter (`curr_min * 1 + prev_min * overlap_ratio` โ€” `O(1)` memory using just 2 integers!), Redis Lua atomicity...

Subtopics Covered (8):
  • API Gateway placement
  • Token Bucket vs Sliding-Window Counter (`curr_min * 1 + prev_min * overlap_ratio` โ€” `O(1)` memory using just 2 integers!)
  • Redis Lua atomicity
โ†’ What Topic Is Next: Next Topic 23.15: System Design #9: Centralized Log Ingestion & Distributed Caching
Guide โ†’

Non-blocking stdout JSON -> Shipper agent -> Kafka buffer (absorbs `10x` incident log storms!) -> Bulk indexer -> Hot (`7d` searchable) vs Cold (`90d` compressed arc...

Subtopics Covered (8):
  • Non-blocking stdout JSON -> Shipper agent -> Kafka buffer (absorbs `10x` incident log storms!) -> Bulk indexer -> Hot (`7d` searchable) vs Cold (`90d` compressed archive) tiers
  • PLUS Distributed Cache consistent hashing ring (`virtual nodes`) minimizing key remapping (`1/N`) when cache nodes join/leave!
  • Production Backend Pitfall & Guardrail (System Design #9: Centralized Log Ingestion & Distributed Caching)
โ†’ What Topic Is Next: Next Topic 23.16: Machine Coding #1โ€“#3: Auth API, Employee CRUD & Dynamic RBAC Engine
Guide โ†’

Timed 60-min builds: (1) User Registration/Login + Rotated Refresh JWT API, (2) Validated Employee CRUD + Paginated Search/Filter/Sort API, and (3) Role + Granular P...

Subtopics Covered (8):
  • Timed 60-min builds: (1) User Registration/Login + Rotated Refresh JWT API
  • (2) Validated Employee CRUD + Paginated Search/Filter/Sort API
  • (3) Role + Granular Permission + Resource-Ownership Middleware Engine with Supertest suites
โ†’ What Topic Is Next: Next Topic 23.17: Machine Coding #4โ€“#6: Paginated Search, Safe File Upload & Email Notification Worker
Guide โ†’

Timed 60-min builds: (4) Keyset Cursor + Faceted Search API, (5) Multer + Magic-Byte + Checksum File Upload & Presigned URL Service, and (6) BullMQ Templated Email N...

Subtopics Covered (8):
  • Timed 60-min builds: (4) Keyset Cursor + Faceted Search API
  • (5) Multer + Magic-Byte + Checksum File Upload & Presigned URL Service
  • (6) BullMQ Templated Email Notification Service with Exponential Backoff & Idempotency
โ†’ What Topic Is Next: Next Topic 23.18: Machine Coding #7โ€“#10: Redis Cache Layer, Job Processor, Signed Webhook & Order Workflow
Guide โ†’

Timed 75-min builds: (7) Cache-Aside + Single-Flight Stampede Guard + Invalidation Layer, (8) Priority Retry + DLQ Background Job Processor, (9) HMAC-SHA256 + Timest...

Subtopics Covered (8):
  • Timed 75-min builds: (7) Cache-Aside + Single-Flight Stampede Guard + Invalidation Layer
  • (8) Priority Retry + DLQ Background Job Processor
  • (9) HMAC-SHA256 + Timestamp + Idempotent Webhook Processor
โ†’ What Topic Is Next: Module 23 Capstone (Week 23 Lab Build: 10 System Design Whiteboards + Timed Backend Machine-Coding Portfolio) โ†’ Next Topic 24.1: Capstone Blueprint & Modular Bounded-Context Setup

Deliver architecture specs & capacity calculations for all 10 Backend System Design problems (URL Shortener, Auth/SSO, Flash-Sale Order Engine, Notification Hub, Chat, Object Storage, Job Scheduler, Rate Limiter, Log/Cache Ring) plus runnable timed Machine-Coding builds.

โ€ข Clean, strictly-typed Node.js / TypeScript backend source code on GitHub
โ€ข Automated unit/integration test suite verifying happy, boundary, and error paths
โ€ข Technical README documenting architecture, schema/index choices, and sample cURL/Postman usage

Module Learning & Hands-On Objectives

โœ“ Deliver all 24 functional requirements of the **Enterprise E-Commerce and Order Management Backend** cleanly in strict TypeScript.
โœ“ Integrate PostgreSQL (`Prisma` ACID orders/inventory/coupons), MongoDB (`Mongoose` catalog), Redis (caching & rate limits), BullMQ (jobs), RabbitMQ/Kafka (events), MinIO (files), and Socket.IO (real-time order updates).
โœ“ Ship complete OpenAPI/Swagger docs, Postman collection, `Jest + Supertest` suite, ER & Architecture diagrams, and multi-container `Docker Compose + Nginx` deployment.
โœ“ Pass Mock Technical Interview #3 and defend your Final Capstone live in a rigorous technical viva.
Guide โ†’

Structuring `src/modules/{auth, users, catalog, inventory, cart, coupons, orders, payments, notifications, uploads}` with strict TypeScript config, Composition Root...

Subtopics Covered (8):
  • Structuring `src/modules/{auth
  • Users
  • Catalog
โ†’ What Topic Is Next: Next Topic 24.2: Capstone Auth, Rotated Refresh Tokens & Granular RBAC
Guide โ†’

Implementing registration, email verification, password reset, `Argon2id`, `15m` Access + `7d` rotated `HttpOnly` Refresh family reuse detection, OAuth2 fundamentals...

Subtopics Covered (8):
  • Implementing registration
  • Email verification
  • Password reset
โ†’ What Topic Is Next: Next Topic 24.3: Capstone Polyglot Data Layer (MongoDB Catalog + PostgreSQL Ledger)
Guide โ†’

Modelling polymorphic Product & Category specs/attributes in **MongoDB (`Mongoose`)** with `ESR` + text indexes, alongside **PostgreSQL (`Prisma`)** Users, Inventory...

Subtopics Covered (8):
  • Modelling polymorphic Product & Category specs/attributes in **MongoDB (`Mongoose`)** with `ESR` + text indexes
  • Alongside **PostgreSQL (`Prisma`)** Users
  • Inventory Stock
โ†’ What Topic Is Next: Next Topic 24.4: Capstone Product Search, Faceted Filters, Pagination & Redis Caching
Guide โ†’

Building `GET /api/v1/products` with keyword search, category/price/rating/in-stock filters, whitelisted sorting, cursor/offset pagination, and Redis Cache-Aside + S...

Subtopics Covered (8):
  • Building `GET /api/v1/products` with keyword search
  • Category/price/rating/in-stock filters
  • Whitelisted sorting
โ†’ What Topic Is Next: Next Topic 24.5: Capstone Shopping Cart & Coupon/Discount Engine
Guide โ†’

Redis Hash / DB-synced Shopping Cart APIs (`add`, `updateQty`, `remove`, `clear`, live stock/price re-validation) + Coupon Engine (`PERCENTAGE` w/ `maxDiscountPaise`...

Subtopics Covered (8):
  • Redis Hash / DB-synced Shopping Cart APIs (`add`
  • `updateQty`
  • `remove`
โ†’ What Topic Is Next: Next Topic 24.6: Capstone Race-Free Inventory Reservation & Order Creation
Guide โ†’

Sorted-SKU `SELECT ... FOR UPDATE` / conditional atomic `qtyOnHand >= qty` stock reservation, snapshotting `title` + `unitPricePaise` on `OrderItem`, `Idempotency-Ke...

Subtopics Covered (8):
  • Sorted-SKU `SELECT ... FOR UPDATE` / conditional atomic `qtyOnHand >= qty` stock reservation
  • Snapshotting `title` + `unitPricePaise` on `OrderItem`
  • `Idempotency-Key` protection on `POST /api/v1/orders`
โ†’ What Topic Is Next: Next Topic 24.7: Capstone Sandbox Payment Integration & Signed Webhook Processing
Guide โ†’

Creating sandbox payment intents (`orderId`, `amountPaise`, `currency: "INR"`), verifying inbound `payment.captured` / `payment.failed` webhooks via `express.raw` +...

Subtopics Covered (8):
  • Creating sandbox payment intents (`orderId`
  • `amountPaise`
  • `currency: "INR"`)
โ†’ What Topic Is Next: Next Topic 24.8: Capstone Order Status State Machine & Refund Handling
Guide โ†’

Enforcing strict legal state transitions (`PENDING_PAYMENT -> PAID -> CONFIRMED -> PACKED -> SHIPPED -> DELIVERED`, `CANCELLED`, `REFUNDED`) with audit history times...

Subtopics Covered (8):
  • Enforcing strict legal state transitions (`PENDING_PAYMENT -> PAID -> CONFIRMED -> PACKED -> SHIPPED -> DELIVERED`
  • `CANCELLED`
  • `REFUNDED`) with audit history timestamps
โ†’ What Topic Is Next: Next Topic 24.9: Capstone File Uploads & S3-Compatible Object Storage (MinIO)
Guide โ†’

Multer + magic-byte validation (`PNG`/`JPEG`/`WEBP` product images; `PDF` GST invoices) stored in private Dockerized `MinIO` buckets with presigned upload/download U...

Subtopics Covered (8):
  • Multer + magic-byte validation (`PNG`/`JPEG`/`WEBP` product images
  • `PDF` GST invoices) stored in private Dockerized `MinIO` buckets with presigned upload/download URLs
  • Production Backend Pitfall & Guardrail (Capstone File Uploads & S3-Compatible Object Storage (MinIO))
โ†’ What Topic Is Next: Next Topic 24.10: Capstone BullMQ Background Jobs & RabbitMQ/Kafka Domain Events
Guide โ†’

Publishing `OrderPaid`, `OrderShipped`, `OrderCancelled` domain events via Outbox -> RabbitMQ/Kafka + BullMQ workers generating PDF invoices, sending transactional e...

Subtopics Covered (8):
  • Publishing `OrderPaid`
  • `OrderShipped`
  • `OrderCancelled` domain events via Outbox -> RabbitMQ/Kafka + BullMQ workers generating PDF invoices
โ†’ What Topic Is Next: Next Topic 24.11: Capstone Real-Time Socket.IO Order & Admin Notifications
Guide โ†’

JWT-authenticated Socket.IO (`@socket.io/redis-adapter`) pushing live `order:status_changed` events to `user:${buyerId}` and `inventory:low_stock` alerts to `/admin`...

Subtopics Covered (8):
  • JWT-authenticated Socket.IO (`@socket.io/redis-adapter`) pushing live `order:status_changed` events to `user:${buyerId}`
  • `inventory:low_stock` alerts to `/admin` namespace!
  • Production Backend Pitfall & Guardrail (Capstone Real-Time Socket.IO Order & Admin Notifications)
โ†’ What Topic Is Next: Next Topic 24.12: Capstone Rate Limiting, Centralized Errors & Structured Observability
Guide โ†’

Tiered Redis rate limiters (`/auth`, `/orders`, `/webhooks`, `/products`), `helmet`, strict `cors`, RFC-style error envelopes, Pino redacted JSON logs with `correlat...

Subtopics Covered (8):
  • Tiered Redis rate limiters (`/auth`
  • `/orders`
  • `/webhooks`
โ†’ What Topic Is Next: Next Topic 24.13: Capstone Swagger / OpenAPI 3.1 & Automated Postman Collection
Guide โ†’

Serving complete `/api/docs` OpenAPI 3.1 specification + exporting `postman/ecommerce-capstone.collection.json` covering Auth -> Catalog -> Cart -> Coupon -> Order -...

Subtopics Covered (8):
  • Serving complete `/api/docs` OpenAPI 3.1 specification + exporting `postman/ecommerce-capstone.collection.json` covering Auth -> Catalog -> Cart -> Coupon -> Order -> Webhook -> Admin Ship flows
  • Production Backend Pitfall & Guardrail (Capstone Swagger / OpenAPI 3.1 & Automated Postman Collection)
  • Hands-On TypeScript / Node.js Implementation (Capstone Swagger / OpenAPI 3.1 & Automated Postman Collection)
โ†’ What Topic Is Next: Next Topic 24.14: Capstone Automated Test Suite (Jest / Vitest & Supertest)
Guide โ†’

Unit tests (pricing, coupons, state machine, HMAC) + Real-DB Supertest integration suites (Auth rotation, Catalog search, Concurrent Stock Race, Idempotent Payment W...

Subtopics Covered (8):
  • Unit tests (pricing
  • Coupons
  • State machine
โ†’ What Topic Is Next: Next Topic 24.15: Capstone Multi-Container Docker Compose & Nginx Deployment
Guide โ†’

Multi-stage non-root `Dockerfile`, `compose.yaml` (`nginx`, `migrate`, `api`, `worker`, `postgres`, `mongo`, `redis`, `minio`, `rabbitmq`) with healthchecks, `.env.e...

Subtopics Covered (8):
  • Multi-stage non-root `Dockerfile`
  • `compose.yaml` (`nginx`
  • `migrate`
โ†’ What Topic Is Next: Next Topic 24.16: GitHub Portfolio Polish, Mock Interviews & Final Capstone Viva
Guide โ†’

Polishing all 6 mandatory GitHub repositories (architecture diagrams, ER diagrams, benchmark tables, setup guides), completing 105 JS/TS DSA + 30 Backend Machine-Cod...

Subtopics Covered (8):
  • Polishing all 6 mandatory GitHub repositories (architecture diagrams
  • ER diagrams
  • Benchmark tables
โ†’ What Topic Is Next: Module 24 Capstone โ†’ End-of-Course Live Client Project: Enterprise E-Commerce and Order Management Backend

Architect, implement, secure, load-test, document, and containerize a complete, production-ready **Enterprise E-Commerce and Order Management Backend** in **TypeScript 5, Node.js 22, and Express.js**. This flagship 6-month capstone unifies polyglot persistence (**PostgreSQL 16 + Prisma** for users, RBAC, addresses, coupons, inventory reservations, orders, payments, refunds & audit logs + **MongoDB 7 + Mongoose** for hierarchical categories, brands, polymorphic product catalogs, variants & customer reviews), **Redis 7** (Cache-Aside, single-flight stampede protection, guest/user carts & Lua rate limiting), **BullMQ** (PDF/JSON invoices, transactional emails & unpaid-order expiry), **RabbitMQ / Kafka** domain event streaming with Transactional Outbox, **Socket.IO** real-time order-status notifications, **S3-compatible MinIO** presigned media storage, **Jest/Vitest + Supertest** suites, **OpenAPI 3.1 / Swagger**, and **3-Stage Non-Root Docker Compose + Nginx** vendor-neutral Linux deployment.

โ€ข 1. Complete Strict TypeScript 5 + Node.js + Express.js Production Source Code Repository
โ€ข 2. System Architecture, Saga Checkout Flow & Network Topology Diagrams
โ€ข 3. PostgreSQL ER Diagram (`Prisma` Migrations) + MongoDB Document Schema & ESR Index Spec
โ€ข 4. Interactive OpenAPI 3.1 / Swagger Documentation (`/api/docs`)
โ€ข 5. Exported Postman Collection & Environment Suite (Customer, Ops & Admin Flows)
โ€ข 6. Automated `Jest`/`Vitest` + `Supertest` Test Suite & Concurrency Race Proof (`>= 80%` Core Coverage)
โ€ข 7. `autocannon` Performance & `EXPLAIN ANALYZE` Index Optimization Benchmark Report
โ€ข 8. 3-Stage Non-Root `Dockerfile`, Health-Checked `compose.yaml` (`Postgres + Mongo + Redis + RabbitMQ + MinIO + Nginx`) & `.github/workflows/ci-cd.yml`
โ€ข 9. Security Hardening Checklist (OWASP API Top 10, Token Rotation, Webhook HMAC & Audit Logs)
โ€ข 10. Recorded Demo Walkthrough + Live 45-Minute Technical Viva & Incident-Debugging Defense
๐ŸŽ“ Like the 24-Module (543-Topic) Syllabus? Experience It Live First!

Attend Your 1st Weekend Live Class Free With Active Working IT Professionals

Verify your email OTP in 15 seconds to receive the live Zoom/Meet demo link, complete 24-module PDF, and personalized roadmap for Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program.

๐Ÿ“„ Download Syllabus PDF
Hands-On Industry Stack โ€ข 16 Core Technologies

Technologies, Frameworks & Tools You Will Master

โœ“ Taught Live by Working IT Professionals
JavaScript ES6+ & Async Logo

JavaScript ES6+ & Async

Web Language
Strict TypeScript 5 Logo

Strict TypeScript 5

Typed Language
Node.js 22 (V8 & libuv) Logo

Node.js 22 (V8 & libuv)

Backend Runtime
Express.js & OpenAPI 3.1 Logo

Express.js & OpenAPI 3.1

HTTP API Layer
MongoDB 7 & Mongoose 8 Logo

MongoDB 7 & Mongoose 8

NoSQL Document DB
PostgreSQL 16 & SQL Logo

PostgreSQL 16 & SQL

Enterprise RDBMS
Prisma ORM 5 & ACID Logo

Prisma ORM 5 & ACID

Type-Safe ORM
JWT, OAuth2, RBAC & OWASP Logo

JWT, OAuth2, RBAC & OWASP

App & Cloud Security
Redis 7 & BullMQ Queues Logo

Redis 7 & BullMQ Queues

In-Memory Cache
RabbitMQ, Kafka & Sagas Logo

RabbitMQ, Kafka & Sagas

Event Streaming
Jest, Vitest & Supertest Logo

Jest, Vitest & Supertest

Test Automation
Linux, Nginx & PM2 Logo

Linux, Nginx & PM2

OS & Scripting
3-Stage Docker Compose Logo

3-Stage Docker Compose

Containers
GitHub Actions CI/CD Logo

GitHub Actions CI/CD

CI/CD Pipelines
LeetCode Problem Solving Logo

LeetCode Problem Solving

Trainer Coding Prep
HackerRank Coding Prep Logo

HackerRank Coding Prep

Trainer Coding Prep
Course Overview โ€ข Freshers & Working Pros

What You Will Learn & Why It Matters on Real Jobs

๐Ÿ‘จโ€๐Ÿ’ป 100% Working IT Pro Trainers
What Is This Course?

Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program teaches you how modern tech companies design, build, test, and deploy reliable Node.js, TypeScript & Express Backend Engineering software using JavaScript ES6+ & Strict TypeScript 5, Node.js 22 LTS (V8, libuv & Event Loop), Buffers, Streams & Async File Processing, Express.js Layered REST Architecture, OpenAPI 3.1, Swagger UI & Zod Validation โ€” explained in clear everyday language before writing real production code.

Who Should Join?

Suitable for both complete beginners (guided step-by-step from Day 1 setup and core logic) and technical students/working professionals aiming for production architecture mastery.

Key Engineering Capabilities You Will Build:

  • โ€ข JavaScript, TypeScript 5 & Node.js Runtime Mastery: Write zero-`any` TypeScript 5 backend code with deep fluency in V8 memory, `libuv` event-loop phases, backpressure-safe Streams, and `AsyncLocalStorage`.

    Purpose: Directly required by Node.js, TypeScript & Express Backend Engineering engineering teams to ship reliable client systems.

  • โ€ข Production Express.js REST APIs: Architect versioned `/api/v1` `Controller -> Service -> Repository` APIs with `Zod` schemas, RFC 9457 Problem Details error handling, cursor pagination, Pino correlation logs, and OpenAPI 3.1 / Swagger docs.

    Purpose: Directly required by Node.js, TypeScript & Express Backend Engineering engineering teams to ship reliable client systems.

  • โ€ข Polyglot Databases (MongoDB + PostgreSQL): Design Mongoose document schemas with aggregation pipelines & ESR indexes alongside 3NF PostgreSQL + Prisma schemas with Window Functions, `EXPLAIN ANALYZE`, and deadlock-free `SELECT ... FOR UPDATE` ACID transactions.

    Purpose: Directly required by Node.js, TypeScript & Express Backend Engineering engineering teams to ship reliable client systems.

  • โ€ข Enterprise Auth & OWASP API Security: Implement `Argon2id`, short-lived JWT access + rotated SHA-256 refresh-token family reuse detection, OAuth 2.0 PKCE, RBAC/BOLA guards, Redis Lua rate limiters, magic-byte file checks, and signed webhooks.

    Purpose: Directly required by Node.js, TypeScript & Express Backend Engineering engineering teams to ship reliable client systems.

  • โ€ข Redis, Queues, Real-Time & Microservices: Scale backends with Redis Cache-Aside + Single-Flight stampede shields, `BullMQ` retry/DLQ workers, `RabbitMQ`/Kafka Transactional Outbox & Saga compensation, and multi-node `Socket.IO` rooms.

    Purpose: Directly required by Node.js, TypeScript & Express Backend Engineering engineering teams to ship reliable client systems.

  • โ€ข Performance, Vendor-Neutral DevOps & System Design: Profile `p95`/`p99` latency with `autocannon`, offload CPU work to `worker_threads`, deploy hardened 3-stage non-root Docker Compose + Nginx + PM2 + GitHub Actions stacks on Linux, and lead 45-minute Backend System Design interviews.

    Purpose: Directly required by Node.js, TypeScript & Express Backend Engineering engineering teams to ship reliable client systems.

Student Learning Outcomes (By End of Course):

Recommended Baseline Stack: Node.js 22 LTS, JavaScript ES2024+, TypeScript 5.x (`strict: true`), Express.js, `Zod`, OpenAPI 3.1 / Swagger, MongoDB 7 + Mongoose 8, PostgreSQL 16 + Prisma 5, `argon2`, `jose` / `jsonwebtoken`, `helmet`, `ioredis` (Redis 7), `bullmq`, `amqplib` (RabbitMQ 3), `socket.io` 4, `minio` / S3-compatible presigned storage, `vitest` / `jest` + `supertest`, `pino`, Docker Compose v2, Nginx, PM2, and GitHub Actions.
  1. 1. JavaScript, TypeScript 5 & Node.js Runtime Mastery: Write zero-`any` TypeScript 5 backend code with deep fluency in V8 memory, `libuv` event-loop phases, backpressure-safe Streams, and `AsyncLocalStorage`.
  2. 2. Production Express.js REST APIs: Architect versioned `/api/v1` `Controller -> Service -> Repository` APIs with `Zod` schemas, RFC 9457 Problem Details error handling, cursor pagination, Pino correlation logs, and OpenAPI 3.1 / Swagger docs.
  3. 3. Polyglot Databases (MongoDB + PostgreSQL): Design Mongoose document schemas with aggregation pipelines & ESR indexes alongside 3NF PostgreSQL + Prisma schemas with Window Functions, `EXPLAIN ANALYZE`, and deadlock-free `SELECT ... FOR UPDATE` ACID transactions.
  4. 4. Enterprise Auth & OWASP API Security: Implement `Argon2id`, short-lived JWT access + rotated SHA-256 refresh-token family reuse detection, OAuth 2.0 PKCE, RBAC/BOLA guards, Redis Lua rate limiters, magic-byte file checks, and signed webhooks.
  5. 5. Redis, Queues, Real-Time & Microservices: Scale backends with Redis Cache-Aside + Single-Flight stampede shields, `BullMQ` retry/DLQ workers, `RabbitMQ`/Kafka Transactional Outbox & Saga compensation, and multi-node `Socket.IO` rooms.
  6. 6. Performance, Vendor-Neutral DevOps & System Design: Profile `p95`/`p99` latency with `autocannon`, offload CPU work to `worker_threads`, deploy hardened 3-stage non-root Docker Compose + Nginx + PM2 + GitHub Actions stacks on Linux, and lead 45-minute Backend System Design interviews.

Weekend-Only Live Batches

Taught live by active Working IT Professionals between 7:00 AM and 8:00 PM IST (choose any slot based on trainer availability).

Batch Available (Sat โ€“ Sun Only): 2 Hours / Day โ€ข 7:00 AM to 8:00 PM IST (choose any slot based on trainer availability)

Mon โ€“ Fri Guided Practice: Real GitHub repository builds, LeetCode/HackerRank coding & โ‰ฅ90% Mock/AI Interview gates.

BATCH-NBCP-2026 ONGOING

Node.js Backend Developer (TypeScript, Express, PostgreSQL, MongoDB, Redis, BullMQ & Microservices) โ€” 6-Month Live Career Cohort

Satโ€“Sun Live + Weekday Guided Node.js/TypeScript Labs & DSA โ€ข 08:00 PM โ€“ 10:30 PM IST (25 Hrs/Week โ€ข 600 Hrs Total)

Starts: 21 Nov 2026

Eligibility

Prerequisites

  • โ€ข No prior backend framework or TypeScript experience required โ€” Month 1 builds JavaScript ES6+, asynchronous execution, strict TypeScript 5, OOP, Git, Linux CLI, and HTTP fundamentals from scratch.
  • โ€ข Consistent 25 hours/week commitment (~600 total hours across 24 weeks) completing all 6 mandatory backend projects, 105 JS/TS DSA problems, and 30 Backend Machine-Coding exercises.
  • โ€ข Ideal for B.Tech / BCA / MCA / B.Sc IT students, non-CS beginners, career switchers, and working developers upgrading to 2026 production standards.
Live Client Production Deployment & Verified Internship Showcase ๐Ÿš€ Live Client Production Project + Internship Letter
End-of-Course Production Deployment

Enterprise E-Commerce and Order Management Backend

Role: Node.js Backend Developer Project Intern

After completing all 24 progressive hands-on module projects during live classes, students join our mentor-led Client Production Sprint to build, test, and deploy "Enterprise E-Commerce and Order Management Backend" to live cloud production โ€” earning an Official Verified Internship Letter detailing their exact technical contributions.

Domain: Live Enterprise Node.js, TypeScript & Express Backend Engineering Production Engagement โ€ข Infra: TypeScript, Node.js, Express.js, PostgreSQL + Prisma, MongoDB + Mongoose, JWT/OAuth/RBAC, Sandbox Payments & Signed Webhooks, Redis, BullMQ, RabbitMQ/Kafka, Socket.IO, Jest/Supertest, Docker Compose & Nginx

Certified on Your Official Internship Confirmation Letter:

  • โœ“ Architected and implemented 'Enterprise E-Commerce and Order Management Backend' using JavaScript ES6+ & Strict TypeScript 5, Node.js 22 LTS (V8, libuv & Event Loop), Buffers, Streams & Async File Processing, Express.js Layered REST Architecture, OpenAPI 3.1, Swagger UI & Zod Validation under Senior Working IT Professional code review.
  • โœ“ Engineered production authentication/RBAC, schema migrations, input validation, caching/security hardening, and clean modular layers.
  • โœ“ Completed automated unit/integration test suites, Docker/IaC packaging, and Git pull-request review sprints.
  • โœ“ Deployed and defended the complete production build with observability, runbooks, and 1-on-1 architecture viva sign-off.
ID: MAA-2026-XXXX QR + BARCODE

1. Graduation Certificate

Certifies NBCP module mastery, Mock/AI Viva scores & GitHub repos.

ID: MAA-INT-XXXX VERIFY 24ร—7 โ†’

2. Client Internship Letter

Employer BGV-verifiable proof of live production deployment contributions.

Complete End-to-End Job Curriculum • Annual CTC Scope & Optional High-ROI Certifications

Career Scope, Salary Packages & Optional Certifications for Better Position & Higher CTC

Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program already covers 100% of the end-to-end engineering stack required for IT placement โ€” no “next course” is needed. Below are the 100% optional, curriculum-matched industry certifications genuinely worth taking if you want a better position and higher CTC package, backed by MockAttempt’s 100% Exam-Success Mentorship where our Working IT Professional trainers ensure you succeed in every exam.

Direct Job Roles After This Course
๐Ÿ’ผ Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program Developer ๐Ÿ’ผ Associate Node.js, TypeScript & Express Backend Engineering Engineer ๐Ÿ’ผ Software Development Engineer (SDE-1)
Top Hiring Industries & Domains
๐Ÿข Global SaaS & Product Companies ๐Ÿข FinTech & Digital Banking ๐Ÿข Cloud & AI Platforms ๐Ÿข Global Capability Centers (GCCs) ๐Ÿข Enterprise Engineering Consulting
Fresher / Entry-Level (0โ€“1 Yr) โ‚น4.5 โ€“ โ‚น8.5 LPA โ€ข $55Kโ€“$85K Global

Hands-on module projects, topic-wise MCQ mocks, AI interviews & live client internship proof.

Mid-Level Product Engineer (1โ€“3 Yrs) โ‚น9.5 โ€“ โ‚น19.0 LPA โ€ข $85Kโ€“$130K Global

Production architecture, performance tuning & automated testing mastery.

Senior / Multi-Stack Specialist (3โ€“6+ Yrs) โ‚น20.0 โ€“ โ‚น38.0+ LPA โ€ข $130Kโ€“$185K+ Global

Accelerated when paired with the optional curriculum-matched global vendor certifications below.

100% Optional Position & CTC Upgrade • Complete Stack Already Covered in This Program

Worthwhile Curriculum-Matched Certifications for Better Position & Higher Package (100% Exam-Success Support)

Selected strictly from Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program modules โ€” zero filler badges, only globally respected exams that unlock higher SDE/Architect shortlists and stronger CTC offers.

๐Ÿ›ก๏ธ 100% Optional • Guaranteed Exam-Success Mentorship
Meta / OpenJS Ecosystem Logo
Meta / OpenJS Ecosystem EXAM: FE-PRO
Optional #1

Professional React, TypeScript & Modern Frontend Specialist

๐Ÿ’ฐ โ‚น9.0 โ€“ โ‚น22.0 LPA โ€ข $80Kโ€“$130K Global ๐ŸŽฏ Frontend, React & Enterprise Angular Engineer

Already Taught in Your Curriculum: Semantic HTML5/WCAG, CSS Grid/Tailwind, TypeScript 5, React Hooks/Redux & Angular Signals

โœ“ M3: Module 3: TypeScript Complete Fundamentals

Why Worth Taking: Validates accessible, type-safe, tested UI engineering for global SaaS and enterprise frontend teams.

โœ… How We Ensure Exam Success: Machine-coding UI challenges, Vitest/Playwright test reviews & 1-on-1 Senior Frontend Architect prep.

OpenJS / Linux Foundation Logo
OpenJS / Linux Foundation EXAM: JSNAD
Optional #2

OpenJS Node.js Application Developer

๐Ÿ’ฐ โ‚น12.0 LPA โ€“ โ‚น27.0 LPA (Hands-On Coding Exam) ๐ŸŽฏ Senior Node.js & Backend TypeScript Engineer

Already Taught in Your Curriculum: Node.js Event Loop, Async Control Flow, Streams, Buffers & Automated Testing

โœ“ M2: Module 2: Advanced JavaScript and Asynchronous... โœ“ M5: Module 5: Node.js Fundamentals and Runtime Arc...

Why Worth Taking: Live-coding Linux Foundation credential prized by high-paying SaaS unicorns and global product startups.

โœ… How We Ensure Exam Success: Timed Node.js coding drills, exam-environment rehearsals & 1-on-1 Senior Node.js Architect mentorship.

OpenJS / Linux Foundation Logo
OpenJS / Linux Foundation EXAM: JSNSD
Optional #3

OpenJS Node.js Services Developer

๐Ÿ’ฐ โ‚น14.0 LPA โ€“ โ‚น30.0 LPA (API & Security Exam) ๐ŸŽฏ Principal REST API, Security & Microservices Engineer

Already Taught in Your Curriculum: Express REST APIs, Input Validation, OWASP Security, Rate Limiting & HTTP Architecture

โœ“ M5: Module 5: Node.js Fundamentals and Runtime Arc... โœ“ M8: Module 8: REST API Design and Professional Bac...

Why Worth Taking: Validates production HTTP service architecture, authentication hardening, and input/attack mitigation in Node.js.

โœ… How We Ensure Exam Success: Hands-on Express security drills, mock service scenarios & 1-on-1 Backend Architect code review.

100% Optional Choice • We Stand Behind Your Success in Every Recommended Certification Exam (FE-PRO, JSNAD, JSNSD)

Your Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program cohort already prepares you completely for placement. If you opt in for certification mentorship to target higher MNC/GCC positions and top-band packages, our Working IT Pro trainers guide you with hands-on blueprint labs, timed mock simulators, and 1-on-1 revision until you clear every exam.

Curriculum Governance & E-E-A-T Faculty Review

Architected & Audited by Ravi Shankar Mishra (Founder & Lead Architect, MockAttempt Academy) & Active Production Engineers

Every module, GitHub lab, 50-MCQ assessment, and 4-axis Spoken AI Viva in Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program is reviewed quarterly against live enterprise hiring bars and taught in clear English on weekends by active Working IT Professionals.

Program Questions

Frequently Asked Questions โ€” Node.js Backend Developer โ€“ 6-Month Industry-Ready Career Program

The complete 6-month (24-week โ€ข 600-hour) Node.js Backend Developer โ€“ Industry-Ready Career Program is โ‚น15,000 All-Inclusive (Incl. 18% GST โ€” zero hidden fees and 0% ISA salary share), payable upfront or in 3 equal 0% interest installments of โ‚น5,000 each.

This is a dedicated backend-only engineering career program. Instead of splitting weeks across React, Angular, or CSS UI work, 100% of your 600 hours go deep into JavaScript ES6+, strict TypeScript, Node.js V8/libuv internals, Express.js REST APIs, MongoDB + Mongoose, PostgreSQL + Prisma, JWT/OAuth2/RBAC security, Redis, BullMQ, RabbitMQ/Kafka, Socket.IO, Microservices, Jest/Supertest, Linux, Docker Compose, Nginx, PM2, and GitHub Actions CI/CD.

Yes. Month 3 teaches both MongoDB + Mongoose ODM (aggregation pipelines, indexes, sessions) AND PostgreSQL 16 + Complete SQL + Prisma ORM (joins, window functions, ACID isolation, EXPLAIN plans, interactive transactions, and migrations), and you combine both in the Multi-Database Inventory Backend and Enterprise E-Commerce Capstone.

You build 6 progressive production-style backends: (1) TypeScript Employee Management CLI, (2) Production-Style Employee Management REST API, (3) Multi-Database Inventory Management Backend (MongoDB + PostgreSQL), (4) Secure Authentication & Authorization Service, (5) 7-Service E-Commerce Microservices Backend, and (6) Final Capstone: Enterprise E-Commerce & Order Management Backend.

The 6-month Coding Lab includes 135 curated TypeScript/JavaScript problems: 105 Data Structures & Algorithms problems (meeting the 100โ€“150 DSA requirement) plus 30 practical Backend Machine-Coding exercises covering async concurrency, REST pagination/idempotency, JWT/RBAC, caching, rate limiting, queues, and system design.

Deployment stays 100% vendor-neutral and focused on portable production backend operations without proprietary cloud lock-in: Linux server administration, SSH hardening, ufw firewall, PM2 cluster reloads, Nginx reverse proxy, Letโ€™s Encrypt SSL/HTTPS, multi-stage Dockerfiles, multi-container Docker Compose (Node.js + PostgreSQL + MongoDB + Redis + MinIO), Prometheus health monitoring, automated backups, and GitHub Actions CI/CD.

25 hours/week across 24 weeks (~600 hours): 8h trainer-led concepts, 5h live coding, 4h guided practicals, 4h assignments, 2h DSA/interview prep, and 2h assessments/doubt clearing, with a 70% passing threshold across quizzes, coding, modules, projects, and the final capstone.

Yes. Month 1 starts from JavaScript fundamentals, variables, functions, closures, promises/async-await, complete TypeScript, Git, Linux CLI, and HTTP networking before entering Node.js runtime internals and Express.js.

โšก Free 1st Live Demo โ€ข All-Inclusive Fees (Incl. 18% GST)

Book Free Live Demo or Reserve Batch Seat

+ Add Background, Location or Questions (Optional)