JK
Proyectos
JK
>CARGANDO // CARGANDO
INICIALIZANDO VISTA
Creado y diseñado porJK
JK
>CARGANDO // PROJECT DETAILS
PARSING ARCHITECTURE, DIAGRAMS & API ENDPOINTS
Volver a proyectos
Ver en GitHub
Backend de Microservicios
Completadonestjspostgrestypescriptjesteslintdockergithubactionspostmanswagger

Backend de Microservicios

Arquitectura de microservicios con NestJS, PostgreSQL y Docker que soporta servicios de productos y pedidos a través de un API Gateway centralizado.

Problema y solución

Demuestra una arquitectura empresarial desacoplada entre el enrutamiento (API Gateway), la lógica de dominio (servicios independientes) y la persistencia de datos (PostgreSQL), permitiendo despliegues y escalado independientes.

Características

  • Arquitectura de microservicios con servicios independientes de Producto y Pedido
  • API Gateway para enrutamiento centralizado y seguridad
  • Base de datos PostgreSQL con orquestación Docker
  • Monorepo gestionado con TurboRepo
  • Pipeline CI/CD con GitHub Actions y despliegues automáticos a Docker Hub
  • Pruebas unitarias completas con Jest

Stack tecnológico

TecnologíaVersiónPropósitoPor qué se eligió
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

Arquitectura

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

Estructura del proyecto

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

Endpoints de API

API Gateway (puerto 3000)

MétodoRutaPropósito
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 (puerto 3001)

MétodoRutaPropósito
POST/productsCreate product
GET/productsList all products
GET/products/:idGet product by ID
PATCH/products/:idUpdate product
DELETE/products/:idDelete product

Orders Service (puerto 3002)

MétodoRutaPropósito
POST/ordersCreate order
GET/ordersList all orders
GET/orders/:idGet order by ID

Diseño de base de datos

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

ColumnaTipoNotas
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

ColumnaTipoNotas
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.

Decisiones de diseño clave

Shared PostgreSQL Database

Decisión: Both services connect to the same PostgreSQL instance and database (procura_db)

Motivo: Simplifies development and deployment — one database to manage

Beneficios: Simpler infrastructure, lower resource usage, easier local development

Compensaciones: Violates database-per-service principle, creates hidden coupling, makes independent scaling harder

JSONB for Order Products

Decisión: Order entity stores product data as JSONB rather than foreign key references

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

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

Compensaciones: No referential integrity, data duplication, no automatic product validation on order creation

API Key Authentication

Decisión: Simple static API key in x-api-key header, compared against environment variable

Motivo: Simplest possible authentication for demonstration purposes

Beneficios: Minimal implementation, no token management, no state

Compensaciones: No user identity, no fine-grained permissions, key is static and shared

HTTP-based Inter-service Communication

Decisión: API Gateway communicates with downstream services via synchronous HTTP (Axios)

Motivo: Simplest approach for synchronous request-response pattern

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

Compensaciones: Synchronous coupling, no retry/circuit breaker, no async processing

Multi-stage Docker Builds

Decisión: Each service uses a 3-stage Dockerfile (deps → builder → runner)

Motivo: Minimizes final image size and attack surface

Beneficios: Production images contain only runtime dependencies and compiled code

Compensaciones: Build time for each stage, no layer caching optimization for src changes

TypeORM synchronize: true

Decisión: Both services use synchronize: true in TypeORM config

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

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

Compensaciones: Dangerous in production — can cause data loss on schema changes

Pruebas

Jest ^30.0.0 with ts-jest ^29.2.5•34 pruebas unitarias

Qué se prueba

  • 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)

Cobertura faltante

  • 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)

Desafíos clave

  • Coordinar múltiples servicios garantizando aislamiento de fallos
  • Configuración de pipelines CI/CD para compilación de múltiples imágenes Docker
  • Gestión limpia de variables de entorno dentro de contenedores

Aprendizajes clave

  • Patrones de API Gateway para puntos de entrada unificados y proxy de peticiones
  • Redes de contenedores y orquestación multi-servicio con Docker Compose
  • Flujos automatizados de imágenes Docker mediante GitHub Actions