Skip to main content

Lesson 3 of 8

Production Architecture Patterns

A production TypeScript application follows a layered architecture - each layer has typed inputs and outputs, depends only on abstractions (interfaces), and is independently testable. Knowing the patterns (Repository, Service, Controller, DTO mapper) and how they fit together completes the mental model.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Layered Architecture - Full Stack Type Flow

Layered Architecture - Full Stack Type Flow
// ── Architecture diagram: type flow ─────────────────────────
//
// CLIENT REQUEST
//    │  (req.body: unknown)
//    ▼
// [Validation Layer]    → Zod.safeParse()       → CreateTaskDTO
//    │
//    ▼
// [Controller]          → calls Service         → receives Task
//    │  (maps to DTO)
//    ▼
// [Response DTO mapper] → toTaskResponseDTO()   → TaskResponseDTO
//    │
//    ▼
// CLIENT RESPONSE: TaskResponseDTO (no internal fields)
//
//         ↕ (inside Service)
// [Service]             → domain logic          → uses Task (domain)
//    │
//    ▼
// [Repository interface] → ITaskRepository
//    │
//    ▼
// [Repository impl]     → PgTaskRepository / InMemoryTaskRepository

// ── Key interfaces - the dependency seams ────────────────────
interface ITaskRepository {   // storage abstraction
  findById(id: number): Promise<Task | null>;
  findPaginated(q: TaskQuery): Promise<Paginated<Task>>;
  save(task: Task): Promise<Task>;
  delete(id: number): Promise<void>;
}

interface Notifier {          // notification abstraction
  notify(userId: number, message: string): Promise<void>;
}

interface Logger {            // logging abstraction
  info(msg: string, ctx?: object): void;
  error(msg: string, err?: Error): void;
}

// ── Dependency graph - wired in bootstrap ─────────────────────
// src/server/bootstrap.ts (composition root)

const db         = new PostgresDatabase(config.DATABASE_URL);
const redis      = new RedisCache(config.REDIS_URL);
const mailer     = new SmtpMailService(config.SMTP_HOST, config.SMTP_PORT);
const logger     = new PinoLogger({ env: config.NODE_ENV });
const eventBus   = new TypedEventBus<TaskManagerEvents>();

// Repositories
const taskRepo = new PgTaskRepository(db);
const userRepo = new PgUserRepository(db);

// Notifications
const notifier = new EmailNotifier(mailer, userRepo);

// Services
const taskService = new TaskService(taskRepo, notifier, logger);
const authService = new AuthService(userRepo, config.JWT_SECRET);

// Controllers
const taskController = new TaskController(taskService);
const authController = new AuthController(authService);

// Express app
export const app = createApp({
  taskController,
  authController,
  logger,
});

// ── Type safety checklist ─────────────────────────────────────
// ✅ Every API input validated by Zod at the controller boundary
// ✅ Services accept and return domain types (Task, User)
// ✅ Repositories accept interfaces, not concrete classes
// ✅ Response DTOs strip internal fields (mapper function)
// ✅ Dates converted to ISO strings in DTOs
// ✅ Environment validated at startup with process.exit on failure
// ✅ Error hierarchy: AppError subclasses → typed errorHandler
// ✅ Event bus typed with TaskManagerEvents map

Common Mistakes

  • No composition root - creating services inside controllers means they can't be swapped. All dependency wiring happens in one `bootstrap.ts` file. The rest of the app only depends on interfaces.
  • Leaking domain types into API responses - controllers must explicitly map Task → TaskResponseDTO. Never `res.json(task)` directly - this sends internal fields to the client.
  • Not separating configuration from wiring - `bootstrap.ts` should read from the validated `config` object. It should not call `process.env` directly. Config access is centralised and typed.

Tip

Tip

Practice Production Architecture Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Production Architecture Patterns

Practice Task

Note

Practice Task - (1) Write a working example of Production Architecture Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Production Architecture Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • A production TypeScript application follows a layered architecture - each layer has typed inputs and outputs, depends only on abstractions (interfaces), and is independently testable.
  • No composition root - creating services inside controllers means they can't be swapped. All dependency wiring happens in one `bootstrap.ts` file. The rest of the app only depends on interfaces.
  • Leaking domain types into API responses - controllers must explicitly map Task → TaskResponseDTO. Never `res.json(task)` directly - this sends internal fields to the client.
  • Not separating configuration from wiring - `bootstrap.ts` should read from the validated `config` object. It should not call `process.env` directly. Config access is centralised and typed.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done