---
name: Enterprise Microservices
overview: Thiết lập cấu trúc thư mục enterprise-grade monorepo cho hệ thống microservices, bắt đầu với Auth Service, hỗ trợ Web + Mobile, và full infrastructure stack (Traefik, Observability, CI/CD).
todos:
  - id: root-structure
    content: Create root folder structure and workspace configuration
    status: completed
  - id: shared-packages
    content: Setup shared packages (logger, types, config, http-client, auth-sdk, tracing)
    status: completed
  - id: auth-service
    content: Create Auth Service with modules, database, and API endpoints
    status: completed
  - id: service-template
    content: Create service template for future microservices
    status: completed
  - id: infrastructure
    content: Setup Traefik, databases, and observability stack
    status: completed
  - id: web-app
    content: Create Next.js web application with API integration
    status: completed
  - id: mobile-app
    content: Create React Native mobile application
    status: completed
  - id: docker-configs
    content: Create Docker and docker-compose configurations for all services
    status: completed
  - id: cicd-workflows
    content: Setup GitHub Actions workflows for CI/CD
    status: completed
  - id: deployments
    content: Create deployment configs for local, staging, and production
    status: completed
  - id: automation-scripts
    content: Create helper scripts for development and deployment
    status: completed
  - id: documentation
    content: Write comprehensive documentation and guides
    status: completed
---

# Plan: Cấu trúc Microservices Enterprise-Grade

## Tổng quan kiến trúc

Dự án sẽ được tổ chức theo mô hình **monorepo** với các nguyên tắc:

- Tách biệt rõ ràng: Apps - Services - Packages - Infra - Deployments
- Mỗi service deploy độc lập với CI/CD riêng
- Shared packages để tái sử dụng code
- Infrastructure as Code với Traefik + Docker + Observability
- Hỗ trợ cả Docker Compose (dev) và Kubernetes (prod)
```mermaid
graph TB
    subgraph apps [Apps Layer]
        web[Web App<br/>NextJS]
        mobile[Mobile App<br/>React Native]
    end
    
    subgraph gateway [API Gateway]
        traefik[Traefik<br/>Routing & Load Balancing]
    end
    
    subgraph services [Services Layer]
        auth[Auth Service<br/>Node.js]
        future[Future Services<br/>Ready to add]
    end
    
    subgraph packages [Shared Packages]
        logger[Logger]
        types[Types]
        config[Config]
    end
    
    subgraph infra [Infrastructure]
        obs[Observability<br/>Prometheus/Grafana/Loki]
        db[Databases<br/>PostgreSQL/Redis]
    end
    
    web --> traefik
    mobile --> traefik
    traefik --> auth
    traefik --> future
    auth --> packages
    auth --> db
    future --> packages
    obs --> auth
    obs --> future
```


## Cấu trúc thư mục chi tiết

### 1. Root Level Structure

Tạo cấu trúc thư mục gốc với các folder chính:

```
/Users/velikho/Desktop/WORKING/Base/
├── apps/                 # Frontend applications
├── services/             # Backend microservices  
├── packages/             # Shared libraries & utilities
├── infra/                # Infrastructure as Code
├── deployments/          # Environment-specific configs
├── .github/              # CI/CD workflows
├── scripts/              # Automation scripts
├── docs/                 # Documentation
├── .gitignore           
├── .dockerignore
├── README.md
└── package.json          # Root workspace config
```

### 2. Apps - Frontend Layer

**[apps/web](apps/web)** - Next.js Web Application:

```
apps/web/
├── public/
├── src/
│   ├── app/              # App router (Next.js 14+)
│   ├── components/
│   │   ├── ui/           # Base UI components
│   │   ├── features/     # Feature-specific components
│   │   └── layouts/      # Layout components
│   ├── hooks/            # Custom React hooks
│   ├── services/         # API client services
│   │   ├── api/
│   │   │   ├── auth.api.ts
│   │   │   └── client.ts
│   │   └── config.ts
│   ├── stores/           # State management (Zustand)
│   ├── styles/           # Global styles
│   ├── types/            # TypeScript types
│   └── utils/            # Helper functions
├── .env.example
├── .env.local
├── Dockerfile
├── docker-compose.dev.yml
├── next.config.js
├── package.json
├── tsconfig.json
└── README.md
```

**[apps/mobile](apps/mobile)** - React Native Application:

```
apps/mobile/
├── src/
│   ├── screens/          # Screen components
│   ├── components/       # Reusable components
│   ├── navigation/       # React Navigation
│   ├── services/         # API clients
│   ├── stores/           # State management
│   ├── hooks/
│   ├── utils/
│   └── types/
├── ios/
├── android/
├── .env.example
├── Dockerfile            # For CI builds
├── package.json
└── README.md
```

### 3. Services - Backend Microservices

**[services/auth-service](services/auth-service)** - Authentication Service (Node.js + TypeScript):

```
services/auth-service/
├── src/
│   ├── modules/          # Feature modules
│   │   ├── auth/
│   │   │   ├── auth.controller.ts
│   │   │   ├── auth.service.ts
│   │   │   ├── auth.dto.ts
│   │   │   └── auth.module.ts
│   │   ├── user/
│   │   │   ├── user.controller.ts
│   │   │   ├── user.service.ts
│   │   │   ├── user.dto.ts
│   │   │   └── user.module.ts
│   │   └── health/
│   ├── config/           # Service configuration
│   │   ├── database.config.ts
│   │   ├── jwt.config.ts
│   │   └── app.config.ts
│   ├── middlewares/      # Express middlewares
│   │   ├── auth.middleware.ts
│   │   ├── error.middleware.ts
│   │   └── logger.middleware.ts
│   ├── routes/           # API routes
│   ├── jobs/             # Background jobs
│   ├── utils/
│   └── main.ts           # Entry point
├── prisma/               # Database schema & migrations
│   ├── schema.prisma
│   ├── migrations/
│   └── seed.ts
├── tests/
│   ├── unit/
│   └── integration/
├── .env.example
├── Dockerfile
├── docker-compose.yml
├── package.json
├── tsconfig.json
└── README.md
```

**[services/_template](services/_template)** - Template cho services tương lai:

- Sẵn sàng để copy và tạo services mới
- Chứa boilerplate code chuẩn

### 4. Packages - Shared Libraries

**[packages/logger](packages/logger)** - Centralized logging:

```typescript
// packages/logger/src/index.ts
import winston from 'winston'
export const logger = winston.createLogger({...})
```

**[packages/types](packages/types)** - Shared TypeScript types:

```typescript
// packages/types/src/user.types.ts
export interface User { id: string; email: string; }
```

**[packages/config](packages/config)** - Shared configs:

```
packages/config/
├── eslint-config/        # ESLint rules
├── tsconfig/             # TypeScript configs
└── prettier-config/      # Prettier rules
```

**[packages/http-client](packages/http-client)** - API client wrapper:

```typescript
// packages/http-client/src/index.ts
import axios from 'axios'
export const createHttpClient = (baseURL: string) => {...}
```

**[packages/auth-sdk](packages/auth-sdk)** - Auth utilities:

```typescript
// packages/auth-sdk/src/index.ts
export const verifyToken = (token: string) => {...}
```

**[packages/tracing](packages/tracing)** - OpenTelemetry setup:

```typescript
// packages/tracing/src/index.ts
export const initTracing = (serviceName: string) => {...}
```

Cấu trúc packages:

```
packages/
├── logger/
├── types/
├── config/
├── http-client/
├── auth-sdk/
├── tracing/
└── ui/                   # Design system (optional)
```

### 5. Infrastructure - Traefik + Observability

**[infra/traefik](infra/traefik)** - Traefik configuration:

```
infra/traefik/
├── traefik.yml           # Static configuration
├── dynamic/              # Dynamic configuration
│   ├── routes.yml        # HTTP routing rules
│   ├── middlewares.yml   # Rate limiting, CORS, etc
│   └── services.yml      # Service definitions
├── certs/                # SSL certificates
└── README.md
```

Traefik routing example:

```yaml
http:
  routers:
    auth-router:
      rule: "Host(`api.goodgo.vn`) && PathPrefix(`/api/v1/auth`)"
      service: auth-service
      middlewares:
    - auth-ratelimit
    - cors
```

**[infra/docker](infra/docker)** - Docker configurations:

```
infra/docker/
├── docker-compose.dev.yml      # Development environment
├── docker-compose.prod.yml     # Production environment
├── networks.yml                # Docker networks
└── volumes.yml                 # Persistent volumes
```

**[infra/observability](infra/observability)** - Monitoring stack:

```
infra/observability/
├── prometheus/
│   ├── prometheus.yml
│   └── rules/
├── grafana/
│   ├── dashboards/
│   │   ├── service-overview.json
│   │   └── auth-service.json
│   └── datasources/
├── loki/
│   └── loki-config.yml
└── docker-compose.observability.yml
```

**[infra/databases](infra/databases)** - Database configs:

```
infra/databases/
├── postgres/
│   ├── init.sql
│   └── postgres.conf
├── redis/
│   └── redis.conf
└── docker-compose.databases.yml
```

**[infra/secrets](infra/secrets)** - Secrets management (not committed):

```
infra/secrets/
├── .gitignore            # Ignore all secrets
├── dev/
│   └── .env.example
└── prod/
    └── .env.example
```

### 6. Deployments - Environment Configs

**[deployments/local](deployments/local)** - Local development:

```
deployments/local/
├── docker-compose.yml    # Full stack for local dev
├── .env.local
└── README.md
```

**[deployments/staging](deployments/staging)** - Staging environment:

```
deployments/staging/
├── kubernetes/           # K8s manifests
│   ├── auth-service.yaml
│   ├── ingress.yaml
│   └── configmap.yaml
├── helm/                 # Helm charts (optional)
└── .env.staging
```

**[deployments/production](deployments/production)** - Production environment:

```
deployments/production/
├── kubernetes/
├── helm/
└── .env.production
```

### 7. CI/CD - GitHub Actions

**[.github/workflows](.github/workflows)** - CI/CD pipelines:

```
.github/
├── workflows/
│   ├── ci-web.yml              # Web app CI
│   ├── ci-mobile.yml           # Mobile app CI  
│   ├── ci-auth-service.yml     # Auth service CI
│   ├── docker-build.yml        # Docker build & push
│   ├── deploy-staging.yml      # Staging deployment
│   ├── deploy-production.yml   # Production deployment
│   └── pr-checks.yml           # PR validation
└── actions/                    # Reusable actions
    ├── setup-node/
    └── docker-build/
```

CI/CD flow:

```mermaid
graph LR
    PR[Pull Request] --> Lint[Lint & Format]
    Lint --> Test[Unit Tests]
    Test --> Build[Build]
    Build --> Docker[Docker Build]
    Docker --> Push[Push to Registry]
    Push --> Deploy[Deploy to Staging]
    Deploy --> E2E[E2E Tests]
```

Example workflow structure:

```yaml
# .github/workflows/ci-auth-service.yml
name: Auth Service CI
on:
  push:
    paths:
   - 'services/auth-service/**'
  pull_request:
    paths:
   - 'services/auth-service/**'
```

### 8. Scripts - Automation

**[scripts](scripts)** - Helper scripts:

```
scripts/
├── setup/
│   ├── init-project.sh       # Initial project setup
│   └── install-deps.sh       # Install all dependencies
├── dev/
│   ├── start-all.sh          # Start all services
│   ├── start-service.sh      # Start specific service
│   └── logs.sh               # View service logs
├── db/
│   ├── migrate.sh            # Run migrations
│   ├── seed.sh               # Seed databases
│   └── backup.sh             # Backup databases
├── build/
│   ├── build-all.sh          # Build all services
│   └── build-service.sh      # Build specific service
├── deploy/
│   ├── deploy-staging.sh
│   └── deploy-prod.sh
└── utils/
    ├── create-service.sh     # Generate new service from template
    └── cleanup.sh            # Cleanup temp files
```

### 9. Documentation

**[docs](docs)** - System documentation:

```
docs/
├── architecture/
│   ├── system-design.md
│   ├── service-communication.md
│   ├── data-flow.md
│   └── diagrams/
│       ├── system-architecture.png
│       └── auth-flow.png
├── api/
│   ├── openapi/
│   │   └── auth-service.yaml
│   └── postman/
├── guides/
│   ├── getting-started.md
│   ├── development.md
│   ├── deployment.md
│   └── troubleshooting.md
├── runbooks/
│   ├── incident-response.md
│   └── rollback-procedure.md
└── onboarding/
    └── new-developer-guide.md
```

### 10. Root Configuration Files

**Root level configs**:

- `.gitignore` - Git ignore rules
- `.dockerignore` - Docker ignore rules  
- `package.json` - Workspace configuration (npm/pnpm/yarn workspaces)
- `pnpm-workspace.yaml` - PNPM workspace config
- `turbo.json` - Turborepo configuration (optional)
- `README.md` - Project overview
- `CONTRIBUTING.md` - Contribution guidelines
- `LICENSE` - License file

## Nguyên tắc thiết kế chính

### Separation of Concerns

- **Apps**: Presentation layer (UI/UX)
- **Services**: Business logic (độc lập, scalable)
- **Packages**: Shared utilities (DRY principle)
- **Infra**: Infrastructure setup (IaC)
- **Deployments**: Environment configs (12-factor app)

### Service Independence

- Mỗi service có database riêng (Database per service pattern)
- Mỗi service có Dockerfile riêng
- Mỗi service có CI/CD pipeline riêng
- Services giao tiếp qua HTTP/gRPC hoặc message queue

### Shared Packages Strategy

```typescript
// Import từ shared packages
import { logger } from '@goodgo/logger'
import { User } from '@goodgo/types'
import { createHttpClient } from '@goodgo/http-client'
```

### Environment Management

- Không commit secrets vào Git
- Sử dụng `.env.example` làm template
- Production secrets qua CI/CD secrets hoặc vault

### CI/CD Strategy

- Path-based triggers (chỉ build service thay đổi)
- Parallel builds cho các services độc lập
- Automated testing trước khi merge
- Automated deployment sau khi merge

## Implementation Steps (High-level)

Khi bắt đầu thực hiện, các bước chính sẽ là:

1. **Setup Root Structure** - Tạo folders gốc và config files
2. **Setup Packages** - Tạo shared libraries trước
3. **Setup Auth Service** - Backend service đầu tiên
4. **Setup Infrastructure** - Traefik + Databases + Observability
5. **Setup Frontend** - Web app với Next.js
6. **Setup Mobile** - React Native app
7. **Setup CI/CD** - GitHub Actions workflows
8. **Setup Deployments** - Docker Compose + K8s configs
9. **Documentation** - README và guides
10. **Testing** - Verify toàn bộ hệ thống

## Tech Stack Summary

**Frontend:**

- Web: Next.js 14+ (App Router), TypeScript, Tailwind CSS
- Mobile: React Native, TypeScript
- State: Zustand
- HTTP: Axios (wrapped trong shared package)

**Backend:**

- Auth Service: Node.js + TypeScript + Express/NestJS
- Database: PostgreSQL (Prisma ORM)
- Cache: Redis
- Future services: Mixed (Node.js + Python support)

**Infrastructure:**

- Reverse Proxy: Traefik
- Containers: Docker + Docker Compose
- Orchestration: Kubernetes (production)
- Monitoring: Prometheus + Grafana + Loki
- Tracing: OpenTelemetry

**DevOps:**

- CI/CD: GitHub Actions
- Registry: Docker Hub / GitHub Container Registry
- Secrets: GitHub Secrets / HashiCorp Vault

## Expected File Structure Size

Sau khi hoàn thành, cấu trúc sẽ có:

- ~150-200 files
- ~50-70 configuration files
- ~20-30 Docker/compose files
- ~10-15 GitHub Actions workflows
- Full documentation suite

## Monorepo Tooling Strategy

### PNPM Workspaces (Khuyến nghị)

**pnpm-workspace.yaml**:

```yaml
packages:
 - 'apps/*'
 - 'services/*'
 - 'packages/*'
```

**Root package.json**:

```json
{
  "name": "@goodgo/monorepo",
  "private": true,
  "workspaces": [
    "apps/*",
    "services/*",
    "packages/*"
  ],
  "scripts": {
    "dev": "pnpm --parallel -r dev",
    "build": "pnpm -r build",
    "test": "pnpm -r test",
    "lint": "pnpm -r lint"
  },
  "devDependencies": {
    "typescript": "^5.3.0",
    "prettier": "^3.1.0",
    "eslint": "^8.56.0"
  }
}
```

### Turborepo (Optional - Để tăng tốc build)

**turbo.json**:

```json
{
  "$schema": "https://turbo.build/schema.json",
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**"]
    },
    "test": {
      "dependsOn": ["build"],
      "outputs": []
    },
    "lint": {
      "outputs": []
    },
    "dev": {
      "cache": false
    }
  }
}
```

## Security Best Practices

### 1. Authentication & Authorization

- JWT với refresh token rotation
- Rate limiting trên Traefik
- RBAC (Role-Based Access Control)
- API key management cho service-to-service

### 2. Network Security

```yaml
# Traefik middleware example
http:
  middlewares:
    secure-headers:
      headers:
        sslRedirect: true
        stsSeconds: 31536000
        contentTypeNosniff: true
        browserXssFilter: true
        frameDeny: true
    
    rate-limit:
      rateLimit:
        average: 100
        burst: 50
```

### 3. Secrets Management

- Không commit `.env` files
- Sử dụng GitHub Secrets cho CI/CD
- Kubernetes Secrets cho production
- HashiCorp Vault cho enterprise (optional)

### 4. Database Security

- Connection pooling
- Prepared statements (Prisma tự động)
- Encryption at rest
- Regular backups

## Performance Optimization

### 1. Caching Strategy

```typescript
// Redis caching layers
- API Response Cache (TTL: 5-60s)
- Session Cache (TTL: 24h)
- Database Query Cache (TTL: varies)
```

### 2. Database Optimization

- Proper indexing
- Connection pooling
- Read replicas (future)
- Query optimization với Prisma

### 3. API Gateway Optimization

- Request compression (gzip)
- Response caching
- Load balancing
- Circuit breaker pattern

## Monitoring & Alerting

### Metrics to Track

**Service Health**:

- Uptime
- Response time (p50, p95, p99)
- Error rate
- Request rate

**Infrastructure**:

- CPU usage
- Memory usage
- Disk I/O
- Network I/O

**Business Metrics**:

- Active users
- API usage
- Feature adoption

### Grafana Dashboards

1. **System Overview Dashboard**

                                                                                                                                                                                                                                                                                                                                                                                                - All services health
                                                                                                                                                                                                                                                                                                                                                                                                - Traffic overview
                                                                                                                                                                                                                                                                                                                                                                                                - Error rates
                                                                                                                                                                                                                                                                                                                                                                                                - Response times

2. **Auth Service Dashboard**

                                                                                                                                                                                                                                                                                                                                                                                                - Login attempts
                                                                                                                                                                                                                                                                                                                                                                                                - Token generation rate
                                                                                                                                                                                                                                                                                                                                                                                                - Failed authentications
                                                                                                                                                                                                                                                                                                                                                                                                - Active sessions

3. **Database Dashboard**

                                                                                                                                                                                                                                                                                                                                                                                                - Query performance
                                                                                                                                                                                                                                                                                                                                                                                                - Connection pool usage
                                                                                                                                                                                                                                                                                                                                                                                                - Slow queries
                                                                                                                                                                                                                                                                                                                                                                                                - Database size

### Alerting Rules

```yaml
# Prometheus alerting example
groups:
 - name: service_alerts
    rules:
   - alert: HighErrorRate
        expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.05
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "High error rate detected"
      
   - alert: ServiceDown
        expr: up == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Service is down"
```

## Testing Strategy

### 1. Unit Tests

- Coverage target: 80%+
- Jest cho Node.js services
- React Testing Library cho frontend

### 2. Integration Tests

- API endpoint testing
- Database integration tests
- Service-to-service communication

### 3. E2E Tests

- Playwright/Cypress cho web
- Detox cho mobile
- Critical user flows

### 4. Load Testing

- K6 hoặc Artillery
- Performance benchmarks
- Stress testing scenarios

## Database Design Principles

### Auth Service Schema Example

```prisma
// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id            String    @id @default(uuid())
  email         String    @unique
  passwordHash  String
  role          Role      @default(USER)
  isActive      Boolean   @default(true)
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
  
  sessions      Session[]
  refreshTokens RefreshToken[]
  
  @@index([email])
  @@map("users")
}

model Session {
  id        String   @id @default(uuid())
  userId    String
  token     String   @unique
  expiresAt DateTime
  createdAt DateTime @default(now())
  
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  
  @@index([userId])
  @@index([token])
  @@map("sessions")
}

model RefreshToken {
  id        String   @id @default(uuid())
  userId    String
  token     String   @unique
  expiresAt DateTime
  createdAt DateTime @default(now())
  
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  
  @@index([userId])
  @@index([token])
  @@map("refresh_tokens")
}

enum Role {
  USER
  ADMIN
  SUPER_ADMIN
}
```

## API Design Standards

### RESTful Endpoints Convention

```
Auth Service:
POST   /api/v1/auth/register      - Register new user
POST   /api/v1/auth/login         - Login user
POST   /api/v1/auth/logout        - Logout user
POST   /api/v1/auth/refresh       - Refresh access token
GET    /api/v1/auth/me            - Get current user
PUT    /api/v1/auth/password      - Change password
POST   /api/v1/auth/forgot        - Forgot password
POST   /api/v1/auth/reset         - Reset password

User Management:
GET    /api/v1/users              - List users (admin)
GET    /api/v1/users/:id          - Get user by ID
PUT    /api/v1/users/:id          - Update user
DELETE /api/v1/users/:id          - Delete user

Health Check:
GET    /health                    - Health check
GET    /health/ready              - Readiness probe
GET    /health/live               - Liveness probe
```

### Response Format Standard

```typescript
// Success Response
{
  "success": true,
  "data": { /* payload */ },
  "message": "Operation successful",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

// Error Response
{
  "success": false,
  "error": {
    "code": "AUTH_001",
    "message": "Invalid credentials",
    "details": {}
  },
  "timestamp": "2024-01-01T00:00:00.000Z"
}

// Pagination Response
{
  "success": true,
  "data": [ /* items */ ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 100,
    "totalPages": 5
  },
  "timestamp": "2024-01-01T00:00:00.000Z"
}
```

## Environment Variables Template

### Auth Service .env.example

```bash
# Server Configuration
NODE_ENV=development
PORT=5001
API_VERSION=v1

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/auth_db?schema=public

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRES_IN=15m
JWT_REFRESH_SECRET=your-super-secret-refresh-key
JWT_REFRESH_EXPIRES_IN=7d

# CORS
CORS_ORIGIN=http://localhost:3000,http://localhost:3001

# Logging
LOG_LEVEL=debug

# External Services
EMAIL_SERVICE_URL=http://notification-service:5003
EMAIL_FROM=noreply@goodgo.vn

# Monitoring
PROMETHEUS_PORT=9090
TRACING_ENABLED=true
JAEGER_ENDPOINT=http://jaeger:14268/api/traces
```

## Development Workflow

### 1. Branch Strategy (Git Flow)

```
main (production)
  └── develop (staging)
       ├── feature/auth-login
       ├── feature/user-profile
       ├── bugfix/token-refresh
       └── hotfix/security-patch
```

### 2. Commit Convention (Conventional Commits)

```bash
feat: add login endpoint
fix: resolve token expiration issue
docs: update API documentation
refactor: restructure auth module
test: add unit tests for auth service
chore: update dependencies
ci: add GitHub Actions workflow
perf: optimize database queries
```

### 3. PR Process

1. Create feature branch từ `develop`
2. Implement changes với tests
3. Run linter và tests locally
4. Push và create PR
5. CI/CD auto run checks
6. Code review
7. Merge vào `develop` (auto deploy staging)
8. QA testing trên staging
9. Merge vào `main` (manual deploy production)

### 4. Local Development Commands

```bash
# Install dependencies
pnpm install

# Start all services
pnpm dev

# Start specific service
pnpm --filter @goodgo/auth-service dev

# Run tests
pnpm test

# Run linter
pnpm lint

# Build all
pnpm build

# Database migrations
cd services/auth-service
pnpm prisma migrate dev

# Seed database
pnpm prisma db seed
```

## Docker Best Practices

### Multi-stage Build Example

```dockerfile
# services/auth-service/Dockerfile
FROM node:20-alpine AS base
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Dependencies stage
FROM base AS deps
COPY package.json pnpm-lock.yaml ./
RUN corepack enable pnpm && pnpm install --frozen-lockfile

# Builder stage
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm prisma generate
RUN pnpm build

# Production stage
FROM base AS runner
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 microservice
USER microservice

COPY --from=builder --chown=microservice:nodejs /app/dist ./dist
COPY --from=builder --chown=microservice:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=microservice:nodejs /app/package.json ./

EXPOSE 5001
CMD ["node", "dist/main.js"]
```

### Docker Compose for Local Development

```yaml
# deployments/local/docker-compose.yml
version: '3.8'

services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: devuser
      POSTGRES_PASSWORD: devpass
      POSTGRES_DB: auth_db
    ports:
   - "5432:5432"
    volumes:
   - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U devuser"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    ports:
   - "6379:6379"
    volumes:
   - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

  auth-service:
    build:
      context: ../../services/auth-service
      dockerfile: Dockerfile
    environment:
   - DATABASE_URL=postgresql://devuser:devpass@postgres:5432/auth_db
   - REDIS_HOST=redis
   - NODE_ENV=development
    ports:
   - "5001:5001"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    volumes:
   - ../../services/auth-service:/app
   - /app/node_modules

  traefik:
    image: traefik:v2.10
    command:
   - "--api.insecure=true"
   - "--providers.docker=true"
   - "--entrypoints.web.address=:80"
    ports:
   - "80:80"
   - "8080:8080"
    volumes:
   - /var/run/docker.sock:/var/run/docker.sock:ro
   - ../../infra/traefik:/etc/traefik

volumes:
  postgres_data:
  redis_data:
```

## Migration & Rollback Strategy

### Database Migration

```bash
# Create migration
pnpm prisma migrate dev --name add_user_table

# Apply migrations (production)
pnpm prisma migrate deploy

# Rollback (manual)
# Prisma không support auto rollback
# Cần tạo migration mới để reverse changes
```

### Service Rollback

```bash
# Kubernetes rollback
kubectl rollout undo deployment/auth-service

# Docker Compose rollback
docker-compose up -d --build auth-service:previous-tag

# GitHub Actions manual rollback
# Re-run previous successful deployment workflow
```

## Scalability Considerations

### Horizontal Scaling

```yaml
# Kubernetes HPA example
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: auth-service-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: auth-service
  minReplicas: 2
  maxReplicas: 10
  metrics:
 - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
 - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80
```

### Database Scaling

- Read replicas cho read-heavy workloads
- Connection pooling (PgBouncer)
- Caching layer (Redis)
- Sharding (future consideration)

### Caching Strategy

```typescript
// Redis caching wrapper
import { Redis } from 'ioredis';

export class CacheService {
  private redis: Redis;

  async get<T>(key: string): Promise<T | null> {
    const data = await this.redis.get(key);
    return data ? JSON.parse(data) : null;
  }

  async set(key: string, value: any, ttl: number = 3600): Promise<void> {
    await this.redis.setex(key, ttl, JSON.stringify(value));
  }

  async del(key: string): Promise<void> {
    await this.redis.del(key);
  }
}
```

## Cost Optimization

### Development Environment

- Use Docker Compose (free)
- Single VPS cho staging (~$10-20/month)
- Free tier databases (Neon, Supabase)

### Production Environment

- Kubernetes cluster (GKE/EKS) ~$50-100/month
- Managed databases ~$30-50/month
- CDN (Cloudflare) - Free tier
- Monitoring (Grafana Cloud) - Free tier
- Total estimate: $100-200/month initial

## Next Steps

Sau khi approve plan này, implementation sẽ bắt đầu với:

1. **Phase 1: Foundation (Week 1)**

                                                                                                                                                                                                                                                                                                                                                                                                - Tạo root structure và workspace config
                                                                                                                                                                                                                                                                                                                                                                                                - Setup shared packages với PNPM workspaces
                                                                                                                                                                                                                                                                                                                                                                                                - Configure ESLint, Prettier, TypeScript

2. **Phase 2: Core Service (Week 2-3)**

                                                                                                                                                                                                                                                                                                                                                                                                - Bootstrap Auth Service với full features
                                                                                                                                                                                                                                                                                                                                                                                                - Database setup với Prisma
                                                                                                                                                                                                                                                                                                                                                                                                - Unit & integration tests

3. **Phase 3: Infrastructure (Week 3-4)**

                                                                                                                                                                                                                                                                                                                                                                                                - Setup Traefik với routing rules
                                                                                                                                                                                                                                                                                                                                                                                                - Configure Prometheus, Grafana, Loki
                                                                                                                                                                                                                                                                                                                                                                                                - Docker Compose cho local dev

4. **Phase 4: Frontend (Week 4-5)**

                                                                                                                                                                                                                                                                                                                                                                                                - Create Next.js web app
                                                                                                                                                                                                                                                                                                                                                                                                - Create React Native mobile app
                                                                                                                                                                                                                                                                                                                                                                                                - API integration với auth service

5. **Phase 5: CI/CD (Week 5-6)**

                                                                                                                                                                                                                                                                                                                                                                                                - GitHub Actions workflows
                                                                                                                                                                                                                                                                                                                                                                                                - Docker build & push automation
                                                                                                                                                                                                                                                                                                                                                                                                - Deployment automation

6. **Phase 6: Documentation (Week 6)**

                                                                                                                                                                                                                                                                                                                                                                                                - API documentation (OpenAPI)
                                                                                                                                                                                                                                                                                                                                                                                                - Development guides
                                                                                                                                                                                                                                                                                                                                                                                                - Deployment runbooks

**Total Timeline**: 6-8 weeks cho MVP đầy đủ chức năng