Lab 15: Capstone — API Platform

Time: 45 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Overview

Combine every advanced Node.js skill into a production-ready API platform with hexagonal architecture, JWT auth, Redis caching, rate limiting, structured logging, health checks, and graceful shutdown.


Step 1: Project Structure (Hexagonal Architecture)

Hexagonal architecture (ports & adapters) isolates business logic from infrastructure, making it testable and technology-agnostic.

mkdir -p api-platform/src/{routes,services,repos,middleware}
cd api-platform
npm init -y
api-platform/
├── src/
│   ├── routes/        # HTTP entry points (adapters)
│   ├── services/      # Business logic (core)
│   ├── repos/         # Data access (adapters)
│   └── middleware/    # Cross-cutting concerns
├── app.js             # App factory
└── server.js          # Entry point (binds port)

💡 routes/ depend on services/. services/ depend on repos/. Nothing imports from routes/ upward — dependency flow is always inward.

📸 Verified Output:


Step 2: Express Router with JSDoc + Zod Validation

src/middleware/validate.js — reusable validation middleware:

src/routes/users.js — typed route with Zod schema:

Verify:

📸 Verified Output:


Step 3: Redis Caching Middleware (Cache-Aside Pattern)

src/middleware/cache.js — cache-aside with TTL and invalidation:

Usage in routes:

💡 Cache-aside: App checks cache first; on miss, loads from DB and populates cache. On write, invalidate affected keys immediately to prevent stale reads.


Step 4: JWT Authentication Middleware

src/middleware/auth.js — sign, verify, refresh:

Verify:

📸 Verified Output:


Step 5: Rate Limiting (Sliding Window)

src/middleware/rateLimiter.js:

Wire in app.js:

💡 Sliding window tracks request timestamps within a rolling time window, giving smoother rate control than fixed windows which can allow 2× burst at window boundaries.


Step 6: Structured Logging with Pino

src/middleware/logger.js:

Verify:

📸 Verified Output:


Step 7: Health Check Endpoint

src/routes/health.js:

Verify:

📸 Verified Output:


Step 8 (Capstone): Graceful Shutdown + Full Platform Assembly

server.js — Wiring Everything Together

docker-compose.yml

Dockerfile

Graceful Shutdown Verification

📸 Verified Output:


Summary

Component
Technology
Pattern

Architecture

Hexagonal

Ports & Adapters

Routing & Validation

Express + Zod

Schema-first validation

Caching

ioredis

Cache-aside, TTL, invalidation

Authentication

jsonwebtoken

Bearer tokens, refresh flow

Rate Limiting

express-rate-limit

Sliding window, 100 req/15min

Logging

pino

JSON structured, request correlation

Health Checks

Express

/health (liveness), /ready (readiness)

Shutdown

Node.js signals

SIGTERM drain → close dependencies

Containerization

Docker Compose

Multi-service with health checks

Last updated