JK
프로젝트
JK
>로딩 중 // 로딩 중
뷰 초기화 중
제작 및 디자인:JK
JK
>로딩 중 // PROJECT DETAILS
PARSING ARCHITECTURE, DIAGRAMS & API ENDPOINTS
프로젝트 목록으로 돌아가기
GitHub에서 보기
마이크로서비스 백엔드
완료nestjspostgrestypescriptjesteslintdockergithubactionspostmanswagger

마이크로서비스 백엔드

NestJS, PostgreSQL, Docker를 활용하여 독립적인 상품/주문 서비스를 중앙 API Gateway로 관리하는 실전 마이크로서비스 아키텍처.

문제 및 해결책

라우팅(Gateway), 도메인 로직(각 서비스), 데이터베이스 간의 관심사를 분리하여 개별 배포 및 수평 확장이 가능한 구조를 제공합니다.

기능

  • 상품 및 주문 서비스가 분리된 마이크로서비스 구조
  • 중앙 집중 라우팅 및 보안을 담당하는 API Gateway
  • Docker Compose 기반 PostgreSQL 데이터베이스 연동
  • TurboRepo 기반 모노레포 구조
  • GitHub Actions를 통한 Docker Hub 자동 빌드 및 배포 CI/CD
  • Jest 단위 테스트 완벽 구축

기술 스택

기술버전목적선택 이유
TypeScript^5.7.3Primary language for all servicesType safety, NestJS ecosystem standard
NestJS^11.0.1Application frameworkModular architecture, dependency injection, TypeScript-first
TypeORM^0.3.27ORM for PostgreSQL accessActive Record/Repository pattern, NestJS integration
PostgreSQL15Primary databaseJSONB support, ACID compliance, reliability
Docker—Containerization for all servicesConsistent environments, reproducible deployments
Turborepo^2.5.8Monorepo task orchestrationFast parallel builds, caching, npm workspaces integration
GitHub Actions—CI/CD pipeline executionFree for public repos, tight Git integration
Jest^30.0.0Unit testing frameworkNestJS default, snapshot support
Swagger^11.2.0API documentationAuto-generates OpenAPI from decorators

아키텍처

Client

API Gateway

:3000

Products Service

:3001

Orders Service

:3002

PostgreSQL

:5432
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

Core System Components

  • API Gateway for routing requests to internal services
  • Products & Orders service as independent NestJS services
  • Docker Compose orchestration
  • PostgreSQL container

Infrastructure

  • GitHub Actions CI (lint, test, build)
  • Docker Hub CD image deployment
  • Environment variable management

프로젝트 구조

.github
workflows
apps
api-gateway
orders-service
products-service
libs
common
docker-compose.ymlOrchestrates all services and PostgreSQL database

API 엔드포인트

API Gateway (포트 3000)

메서드경로목적
GET/productsList all products
GET/products/:idGet product by ID
POST/productsCreate product
PATCH/products/:idUpdate product
DELETE/products/:idDelete product
GET/ordersList all orders
GET/orders/:idGet order by ID
POST/ordersCreate order

Products Service (포트 3001)

메서드경로목적
POST/productsCreate product
GET/productsList all products
GET/products/:idGet product by ID
PATCH/products/:idUpdate product
DELETE/products/:idDelete product

Orders Service (포트 3002)

메서드경로목적
POST/ordersCreate order
GET/ordersList all orders
GET/orders/:idGet order by ID

데이터베이스 설계

product

6 cols
idPK
SERIAL
code
VARCHAR
name
VARCHAR
description
VARCHAR
price
DECIMAL
image
VARCHAR

order

4 cols
idPK
SERIAL
customer
JSONB
products
JSONB
totalAmount
DECIMAL
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

product

컬럼유형비고
idPKSERIALAuto-generated primary key
codeVARCHARProduct SKU/code
nameVARCHARProduct display name
descriptionVARCHARProduct description
priceDECIMALProduct price
imageVARCHARImage URL

No explicit indexes beyond primary key. No unique constraints on code.

order

컬럼유형비고
idPKSERIALAuto-generated primary key
customerJSONBStores {name, phone}
productsJSONBArray of {id, name, rate, qty}
totalAmountDECIMALTotal order amount

Products stored as JSONB snapshot — intentional denormalization. No foreign keys to product table.

No foreign key relationships. Order.products is a JSONB snapshot — orders are self-contained records that do not reference the product table. Product price changes do not affect existing orders.

주요 설계 결정

Shared PostgreSQL Database

결정: Both services connect to the same PostgreSQL instance and database (procura_db)

이유: Simplifies development and deployment — one database to manage

이점: Simpler infrastructure, lower resource usage, easier local development

트레이드오프: Violates database-per-service principle, creates hidden coupling, makes independent scaling harder

JSONB for Order Products

결정: Order entity stores product data as JSONB rather than foreign key references

이유: Decouples order data from product lifecycle — orders are immutable snapshots

이점: Orders are self-contained, product changes don't affect historical orders

트레이드오프: No referential integrity, data duplication, no automatic product validation on order creation

API Key Authentication

결정: Simple static API key in x-api-key header, compared against environment variable

이유: Simplest possible authentication for demonstration purposes

이점: Minimal implementation, no token management, no state

트레이드오프: No user identity, no fine-grained permissions, key is static and shared

HTTP-based Inter-service Communication

결정: API Gateway communicates with downstream services via synchronous HTTP (Axios)

이유: Simplest approach for synchronous request-response pattern

이점: Easy to understand, debug, and test; standard HTTP tooling

트레이드오프: Synchronous coupling, no retry/circuit breaker, no async processing

Multi-stage Docker Builds

결정: Each service uses a 3-stage Dockerfile (deps → builder → runner)

이유: Minimizes final image size and attack surface

이점: Production images contain only runtime dependencies and compiled code

트레이드오프: Build time for each stage, no layer caching optimization for src changes

TypeORM synchronize: true

결정: Both services use synchronize: true in TypeORM config

이유: Auto-creates/updates database schema from entities during development

이점: No migration files needed, schema stays in sync with code

트레이드오프: Dangerous in production — can cause data loss on schema changes

테스트

Jest ^30.0.0 with ts-jest ^29.2.5•단위 테스트 34개

테스트 항목

  • API Gateway: root health check, all proxy operations (products + orders)
  • Products Service: controller methods (create, findAll, findOne, update, remove)
  • Products Service: service methods (create, findAll, findOne, update, remove)
  • Orders Service: controller methods (create, findAll, findOne, id conversion)
  • Orders Service: service methods (create, findAll, findOne)

부족한 커버리지

  • Integration tests with real database
  • API Gateway ↔ Service integration tests
  • Middleware tests for API key validation
  • Validation error scenario tests
  • Error path tests (404, 500 scenarios)

주요 과제

  • 다중 서비스 간 결함 격리 및 안정적인 통신 보장
  • 다중 컨테이너 빌드를 위한 효율적인 CI/CD 파이프라인 구성

주요 학습

  • 통합 진입점 구축을 위한 API Gateway 설계 패턴
  • Docker 네트워크를 활용한 서비스 간 격리 통신