engineering docs

Microservices & Micro-Frontend Architecture Blueprint

Document Version: 1.0 Date: August 4, 2026 Status: Architecture Design & Migration Strategy Author: System Analysis


Table of Contents

  1. Executive Summary
  2. Current Architecture Analysis
  3. Target Microservices Architecture
  4. Component Inventory & Mapping
  5. Migration Strategy (5 Phases)
  6. Docker & Infrastructure Setup
  7. Deployment Topology
  8. Risks & Mitigation

Executive Summary

Current State: Monorepo with Shared Packages

  • Structure: Turborepo-based monorepo with multiple products
  • Tech Stack: Next.js, React, React Native, Prisma, MongoDB
  • Package Manager: Bun v1.2.19
  • Build Tool: Turborepo
  • Deployment: Unified build process

Target State: Microservices + Micro-Frontend

  • Architecture: Domain-driven microservices with independent deployments
  • Frontend: Micro-frontend modules per domain
  • Backend: Separate containerized services per business domain
  • Communication: REST/gRPC APIs between services
  • Orchestration: Docker Compose (dev) + Kubernetes (prod ready)
  • Data: Separate databases per service (Database per Service pattern)

Key Benefits

✅ Independent scaling per domain ✅ Technology flexibility per service ✅ Faster deployment cycles ✅ Team ownership per domain ✅ Better fault isolation ✅ Easier testing & debugging


Current Architecture Analysis

📦 Projects Structure

apps/
├── main/              → Main portal (Next.js)
├── app/               → Public application (Next.js)
│   ├── landing        → Landing page
│   ├── store          → E-commerce frontend
│   └── warehouse      → Inventory management
├── app/mobile         → Mobile app (React Native/Expo)
├── api                → Backend API (Prisma + MongoDB)
└── docs               → Documentation (Next.js)
 
packages/
├── db                 → Prisma ORM & Database client
├── auth               → Authentication utilities
├── core               → Core business logic (validators, etc)
├── engines            → Business engines
├── permissions        → RBAC utilities
├── helpers            → Helper functions
├── hooks              → React hooks library
├── http-client        → Axios wrapper
├── i18n               → Internationalization
├── components/        → Reusable UI components (web)
├── icons/             → Icon library
├── ui/                → Design system
└── [mobile versions]

🎯 Business Domains Identified

  1. Authentication & Authorization

    • Account management
    • Token/Session handling
    • Role-based access control (RBAC)
    • 2FA, password reset, email verification
  2. Product Management

    • CRUD operations for products
    • Categories & inventory
    • Product analytics
    • Pricing management
  3. Order Management

    • Order creation & processing
    • Order history & tracking
    • Order status updates
  4. User & Organization Management

    • User profiles
    • Organization/workspace management
    • Team member management
    • Invite system
  5. Analytics & Reporting

    • Dashboard analytics
    • Business metrics
    • History & audit logs
    • REST statistics
  6. Settings & Configuration

    • System settings
    • FAQ management
    • Workspace configuration
    • Subscription management
  7. Media & File Management

    • Image uploads
    • File storage
    • Asset management

📊 Current Data Model

Key Entities:

  • User (auth, profile)
  • Account (OAuth, credentials)
  • VerificationToken, PasswordResetToken, TwoFactorToken
  • InvitationToken
  • Organization/Workspace
  • Product, Category, Inventory
  • Order, OrderItem
  • Analytics data
  • Settings

Relationships:

  • User ← → Account (1:N)
  • User ← → Organization (N:N via memberships)
  • Organization ← → Product (1:N)
  • Product ← → Order (N:N via OrderItem)

Target Microservices Architecture

🎯 Service Decomposition

Core Infrastructure Services (Foundation)

1. API Gateway Service
   ├── Port: 3000
   ├── Functions: Request routing, rate limiting, auth validation
   ├── Tech: Node.js + Express/Fastify
   └── Uses: JWT validation, service discovery

Domain Services (Business Logic)

2. Auth Service (Port: 3001)
   ├── Domain: User authentication & authorization
   ├── Tables: Account, VerificationToken, PasswordResetToken, TwoFactorToken, TwoFactorConfirmation
   ├── APIs:
   │   POST   /auth/register
   │   POST   /auth/login
   │   POST   /auth/refresh-token
   │   GET    /auth/verify/:token
   │   POST   /auth/2fa
   │   DELETE /auth/logout
   ├── Dependencies: None (independent)
   └── Database: MongoDB (auth_db)
 
3. User Service (Port: 3002)
   ├── Domain: User profiles & preferences
   ├── Tables: User, UserProfile, UserSettings
   ├── APIs:
   │   GET    /users/:id
   │   PUT    /users/:id
   │   GET    /users/:id/profile
   │   PUT    /users/:id/profile
   │   DELETE /users/:id
   ├── Dependencies: Auth Service (token validation)
   └── Database: MongoDB (users_db)
 
4. Organization Service (Port: 3003)
   ├── Domain: Workspace/org management
   ├── Tables: Organization, OrganizationMember, InvitationToken
   ├── APIs:
   │   POST   /orgs
   │   GET    /orgs/:id
   │   PUT    /orgs/:id
   │   POST   /orgs/:id/members
   │   GET    /orgs/:id/members
   │   DELETE /orgs/:id/members/:memberId
   │   POST   /orgs/:id/invites
   ├── Dependencies: Auth Service, User Service
   └── Database: MongoDB (orgs_db)
 
5. Product Service (Port: 3004)
   ├── Domain: Product catalog & inventory
   ├── Tables: Product, Category, ProductImage, Inventory, ProductVariant
   ├── APIs:
   │   GET    /products
   │   POST   /products
   │   GET    /products/:id
   │   PUT    /products/:id
   │   DELETE /products/:id
   │   GET    /products/:id/inventory
   │   POST   /categories
   │   GET    /categories
   ├── Dependencies: Auth Service, Organization Service
   └── Database: MongoDB (products_db)
 
6. Order Service (Port: 3005)
   ├── Domain: Order processing
   ├── Tables: Order, OrderItem, OrderStatus, OrderHistory
   ├── APIs:
   │   POST   /orders
   │   GET    /orders/:id
   │   GET    /orders (user orders)
   │   PUT    /orders/:id/status
   │   GET    /orders/:id/history
   │   POST   /orders/:id/cancel
   ├── Dependencies: Auth Service, Product Service, User Service
   ├── Events: order-created, order-confirmed, order-shipped, order-delivered
   └── Database: MongoDB (orders_db)
 
7. Analytics Service (Port: 3006)
   ├── Domain: Analytics, metrics, reporting
   ├── Tables: Analytics, UserActivity, DashboardMetrics, AuditLog
   ├── APIs:
   │   GET    /analytics/dashboard
   │   GET    /analytics/products
   │   GET    /analytics/orders
   │   GET    /analytics/users
   │   POST   /analytics/events
   │   GET    /audit/logs
   ├── Dependencies: Event stream (Kafka/Redis)
   └── Database: MongoDB (analytics_db) + Time-series database (optional: InfluxDB)
 
8. Settings Service (Port: 3007)
   ├── Domain: Configuration & settings
   ├── Tables: Setting, FAQ, Subscription, FeatureFlag
   ├── APIs:
   │   GET    /settings/:org_id
   │   PUT    /settings/:org_id
   │   GET    /faq
   │   POST   /faq (admin)
   │   PUT    /faq/:id (admin)
   │   DELETE /faq/:id (admin)
   ├── Dependencies: Auth Service, Organization Service
   └── Database: MongoDB (settings_db)
 
9. Notification Service (Port: 3008)
   ├── Domain: Email, SMS, push notifications
   ├── APIs:
   │   POST   /notifications/email
   │   POST   /notifications/sms
   │   POST   /notifications/push
   │   GET    /notifications/:user_id
   ├── Dependencies: Event stream
   └── External: SendGrid, Twilio, Firebase Cloud Messaging

Supporting Services

10. Event Service (Message Broker)
    ├── Technology: Redis (dev) / RabbitMQ or Kafka (prod)
    ├── Port: 6379 (Redis) or 5672 (RabbitMQ)
    ├── Purpose: Async communication, event streaming
 
11. Cache Service
    ├── Technology: Redis
    ├── Port: 6380
    ├── Purpose: Session caching, rate limiting
 
12. Search Service (Optional)
    ├── Technology: Elasticsearch/MeiliSearch
    ├── Port: 9200
    ├── Purpose: Full-text search for products

🎨 Micro-Frontend Architecture

Frontend Module Structure

micro-frontends/
├── shell (Port: 3100)
│   ├── Layout & routing orchestration
│   ├── Header, Navigation, Footer
│   ├── Module loader & error boundary
│   └── Global state (theme, language)

├── auth-module (Port: 3101)
│   ├── Login, Register, 2FA
│   ├── Password reset
│   ├── OAuth integration
│   └── Shared with: All modules (auth boundary)

├── user-module (Port: 3102)
│   ├── User profile
│   ├── Settings
│   ├── Preferences
│   └── APIs: User Service

├── organization-module (Port: 3103)
│   ├── Organization dashboard
│   ├── Member management
│   ├── Invite management
│   └── APIs: Organization Service

├── product-module (Port: 3104)
│   ├── Product catalog
│   ├── Search & filter
│   ├── Product detail
│   ├── Category browser
│   └── APIs: Product Service

├── order-module (Port: 3105)
│   ├── Order creation
│   ├── Order history
│   ├── Order tracking
│   ├── Cart management
│   └── APIs: Order Service

├── analytics-module (Port: 3106)
│   ├── Dashboard & charts
│   ├── Reports
│   ├── Metrics display
│   └── APIs: Analytics Service

└── admin-module (Port: 3107)
    ├── Admin dashboard
    ├── FAQ management
    ├── Settings management
    ├── Subscription management
    └── APIs: Settings Service + others

📡 Communication Patterns

Synchronous (REST/gRPC):

  • API Gateway → Services
  • Services → Authentication validation
  • Frontend → Service APIs

Asynchronous (Event-Driven):

  • Order Service → Analytics Service (order-created event)
  • Product Service → Analytics Service (product-viewed event)
  • User Service → Notification Service (user-registered event)
  • Any Service → Notification Service (action events)

Data Sharing:

  • Service-to-Service: API calls with circuit breaker pattern
  • Caching: Redis for frequently accessed data
  • Search: Elasticsearch for product catalog

Component Inventory & Mapping

📦 Packages to Microservices Mapping

Current PackageTarget Microservice(s)TypeAction
@repo/dbAll servicesSharedMigrate to service-specific schemas
@repo/authAuth ServiceCoreBecomes Auth Service core
@repo/core (validators)All servicesSharedReplicate validators to each service
@repo/permissionsAuth Service + API GatewayCoreCentralize in Auth Service
@repo/http-clientAll servicesSharedKeep as NPM package, use by all
@repo/helpersAll servicesUtilityReplicate or maintain as package
@repo/hooksAll MFE modulesUIMove to respective micro-frontend
@repo/i18nShell module + AllUIKeep as shared, reference by all
@repo/components/Product/UI modulesUIMove to specific MFE modules
@repo/ui-<*>Shell moduleUIBecomes design system in shell
@repo/icons-<*>Shell moduleUIBecomes icon library in shell

🗄️ Database Schema Distribution

Current: Single MongoDB database (all tables mixed)

Target: Polyglot persistence (Database per Service)

auth_db (MongoDB)
├── Account
├── VerificationToken
├── PasswordResetToken
├── TwoFactorToken
├── TwoFactorConfirmation
 
users_db (MongoDB)
├── User (subset: id, email, name, role)
├── UserProfile
├── UserSettings
 
orgs_db (MongoDB)
├── Organization
├── OrganizationMember
├── InvitationToken
 
products_db (MongoDB)
├── Product
├── Category
├── ProductImage
├── Inventory
├── ProductVariant
 
orders_db (MongoDB)
├── Order
├── OrderItem
├── OrderStatus
├── OrderHistory
 
analytics_db (MongoDB) + Optional InfluxDB
├── Analytics
├── UserActivity
├── DashboardMetrics
├── AuditLog
 
settings_db (MongoDB)
├── Setting
├── FAQ
├── Subscription
├── FeatureFlag

🔌 API Endpoints Mapping

Before: Single API (/api/...)

After: Distributed APIs

API Gateway (Port 3000)
├── /api/auth        → Auth Service (3001)
├── /api/users       → User Service (3002)
├── /api/orgs        → Organization Service (3003)
├── /api/products    → Product Service (3004)
├── /api/orders      → Order Service (3005)
├── /api/analytics   → Analytics Service (3006)
├── /api/settings    → Settings Service (3007)
└── /api/notify      → Notification Service (3008)

Migration Strategy (5 Phases)

✅ Phase 1: Foundation & Infrastructure Setup

Duration: 2-3 weeks Difficulty: LOW Parallel Activity: Can start while building services

Objectives:

  • Set up Docker & Compose infrastructure
  • Create API Gateway service skeleton
  • Set up local development environment
  • Configure CI/CD pipeline basics

Tasks:

  1. Docker Infrastructure

    ✓ Create Dockerfile templates for Node.js services
    ✓ Create Docker Compose file for local development
    ✓ Set up .dockerignore files
    ✓ Configure volume mounts for hot reload
    ✓ Set up networking between containers
  2. API Gateway Service

    ✓ Create Express/Fastify server
    ✓ Implement routing to backend services
    ✓ Add request logging & monitoring
    ✓ Set up CORS & security headers
    ✓ Implement rate limiting
    ✓ Add circuit breaker pattern
  3. Development Environment

    ✓ Docker Compose with all services
    ✓ Environment variables management
    ✓ Local database setup scripts
    ✓ Service discovery configuration
    ✓ Logging aggregation setup (optional)
  4. CI/CD Basics

    ✓ GitHub Actions workflow template
    ✓ Docker image building & pushing
    ✓ Environment-based deployment

Deliverables:

  • docker-compose.yml with basic services
  • API Gateway running & routing to stub services
  • Development guide with Docker commands

✅ Phase 2: Extract Micro-Frontend (Store)

Duration: 1-2 weeks Difficulty: LOW-MEDIUM Dependencies: Phase 1 complete

Why start here: Frontend extraction is lower risk than backend service extraction

Objectives:

  • Separate frontend shell and modules
  • Implement module federation
  • Set up micro-frontend orchestration
  • Maintain existing API communication

Tasks:

  1. Create Shell Application

    ✓ Extract layout from current main
    ✓ Create main shell (Port 3100)
    ✓ Implement module loader
    ✓ Setup dynamic import system
    ✓ Global state (zustand/context)
    ✓ Theme management
    ✓ Language switching
  2. Extract Micro-Frontend Modules

    ✓ Auth Module (3101) - Login, Register, 2FA
    ✓ Product Module (3104) - Catalog, Search, Detail
    ✓ Order Module (3105) - Cart, Order creation, History
    ✓ Analytics Module (3106) - Dashboard, Charts
  3. Implement Module Federation (Webpack/Module Federation)

    ✓ Configure webpack for module sharing
    ✓ Define shared dependencies (React, etc)
    ✓ Remote entry points for each module
    ✓ Fallback handling
  4. Error Handling & Boundaries

    ✓ Error boundaries in shell
    ✓ Graceful module load failures
    ✓ Timeout handling

Deliverables:

  • Shell application orchestrating modules
  • Each module as separate Next.js app
  • Module Federation configuration
  • Development guide for running all modules

⚙️ Phase 3: Extract Core Services (Auth, User)

Duration: 3-4 weeks Difficulty: MEDIUM Dependencies: Phase 1 complete, can run in parallel with Phase 2

Objectives:

  • Create Auth Service (database extraction)
  • Create User Service (database extraction)
  • Set up inter-service communication
  • Implement data replication/caching strategy

Tasks:

  1. Auth Service Extraction

    ✓ Create service skeleton (Port 3001)
    ✓ Extract auth tables to auth_db
    ✓ Implement JWT token generation
    ✓ Implement 2FA logic
    ✓ Implement password hashing (bcrypt)
    ✓ Create REST endpoints
    ✓ Create service-to-service auth middleware
    ✓ Add rate limiting for auth endpoints
    ✓ Implement token refresh mechanism
  2. User Service Extraction

    ✓ Create service skeleton (Port 3002)
    ✓ Extract user data to users_db
    ✓ Implement profile management
    ✓ Implement settings management
    ✓ Create REST endpoints
    ✓ Add token validation middleware (via Auth Service)
    ✓ Implement user deletion cascade logic
  3. Organization Service Creation

    ✓ Create service skeleton (Port 3003)
    ✓ Extract organization data to orgs_db
    ✓ Implement member management
    ✓ Implement invite system
    ✓ Create REST endpoints
    ✓ Integration with Auth & User Services
  4. Inter-Service Communication

    ✓ Implement service discovery (DNS or consul)
    ✓ Service-to-service HTTP calls with retry
    ✓ Circuit breaker implementation
    ✓ Implement caching layer (Redis)
  5. Data Migration

    ✓ Create migration scripts for auth data
    ✓ Create migration scripts for user data
    ✓ Create migration scripts for org data
    ✓ Validation & verification
    ✓ Rollback procedures

Deliverables:

  • Auth Service running independently
  • User Service running independently
  • Organization Service running independently
  • Migration scripts and documentation
  • Service integration tests

⚙️ Phase 4: Extract Business Services (Product, Order)

Duration: 4-5 weeks Difficulty: MEDIUM-HIGH Dependencies: Phase 3 complete

Objectives:

  • Create Product Service
  • Create Order Service
  • Create Analytics Service
  • Implement event-driven communication

Tasks:

  1. Product Service Extraction

    ✓ Create service skeleton (Port 3004)
    ✓ Extract product tables to products_db
    ✓ Implement CRUD operations
    ✓ Implement inventory management
    ✓ Implement category management
    ✓ Create search/filter logic
    ✓ Create REST endpoints
    ✓ Integration with Auth Service
    ✓ Add caching for catalog
  2. Order Service Extraction

    ✓ Create service skeleton (Port 3005)
    ✓ Extract order tables to orders_db
    ✓ Implement order creation logic
    ✓ Implement order status workflow
    ✓ Implement order history tracking
    ✓ Create REST endpoints
    ✓ Integration with Auth, User, Product Services
    ✓ Implement saga pattern for order processing
    ✓ Add order status notifications
  3. Analytics Service Creation

    ✓ Create service skeleton (Port 3006)
    ✓ Set up analytics_db (MongoDB)
    ✓ Implement event listener (Kafka/Redis Streams)
    ✓ Implement dashboard metrics aggregation
    ✓ Implement audit logging
    ✓ Create REST endpoints for reporting
    ✓ Add time-series capabilities
  4. Event Bus Setup

    ✓ Set up message broker (Redis or Kafka)
    ✓ Implement event producers in services
    ✓ Implement event consumers for analytics
    ✓ Implement event schema validation
    ✓ Add dead letter queue handling
    ✓ Implement event replay capability
  5. Data Migration

    ✓ Create migration scripts for products
    ✓ Create migration scripts for orders
    ✓ Create migration scripts for analytics
    ✓ Parallel running with old system
    ✓ Validation & reconciliation
    ✓ Rollback procedures

Deliverables:

  • Product Service running independently
  • Order Service running independently
  • Analytics Service running independently
  • Event bus infrastructure
  • Migration scripts
  • Service integration tests

⚙️ Phase 5: Extract Remaining Services & Optimize

Duration: 2-3 weeks Difficulty: LOW-MEDIUM Dependencies: Phase 4 complete

Objectives:

  • Create Settings Service
  • Create Notification Service
  • Decommission old monolithic API
  • Performance optimization
  • Production readiness

Tasks:

  1. Settings Service

    ✓ Create service skeleton (Port 3007)
    ✓ Extract settings tables
    ✓ Implement FAQ management
    ✓ Implement subscription management
    ✓ Implement feature flags
    ✓ Create REST endpoints
    ✓ Integration with other services
  2. Notification Service

    ✓ Create service skeleton (Port 3008)
    ✓ Implement email notifications (SendGrid)
    ✓ Implement SMS notifications (Twilio)
    ✓ Implement push notifications (FCM)
    ✓ Integrate with event bus
    ✓ Create notification templates
    ✓ Implement notification history/logging
  3. Remaining Micro-Frontend Modules

    ✓ User Module (3102) - Profile, Settings
    ✓ Organization Module (3103) - Org Dashboard, Member Mgmt
    ✓ Admin Module (3107) - Admin Dashboard, Settings
  4. Complete Admin Portal as MFE

    ✓ Extract main as admin-module
    ✓ Integrate with Settings Service
    ✓ Integrate with Analytics Service
    ✓ Implement admin-specific dashboards
  5. Optimization & Hardening

    ✓ Database indexing optimization
    ✓ Query optimization
    ✓ Caching strategy refinement
    ✓ API response time optimization
    ✓ Security hardening (HTTPS, encryption)
    ✓ Load testing
    ✓ Performance monitoring setup
  6. Decommission Old API

    ✓ Verify all services running correctly
    ✓ Verify all data migrated
    ✓ Monitor for errors in new system
    ✓ Gradual rollout (canary deployment)
    ✓ Old API deprecation warnings
    ✓ Complete cutover when stable

Deliverables:

  • All services running independently
  • All micro-frontend modules operational
  • Old monolithic API decommissioned
  • Complete monitoring & observability
  • Production deployment guide
  • Performance benchmarks

Docker & Infrastructure Setup

🐳 Docker Compose Configuration

File: docker-compose.yml

version: '3.8'
 
services:
  # API Gateway
  api-gateway:
    build:
      context: ./services/api-gateway
      dockerfile: Dockerfile
    ports:
      - '3000:3000'
    environment:
      NODE_ENV: development
      AUTH_SERVICE_URL: http://auth:3001
      USER_SERVICE_URL: http://user:3002
      ORG_SERVICE_URL: http://org:3003
      PRODUCT_SERVICE_URL: http://product:3004
      ORDER_SERVICE_URL: http://order:3005
      ANALYTICS_SERVICE_URL: http://analytics:3006
      SETTINGS_SERVICE_URL: http://settings:3007
      NOTIFY_SERVICE_URL: http://notify:3008
    depends_on:
      - redis
    networks:
      - aori-network
 
  # Auth Service
  auth:
    build:
      context: ./services/auth
      dockerfile: Dockerfile
    ports:
      - '3001:3001'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/auth_db
      JWT_SECRET: ${JWT_SECRET:-your-secret-key}
      REDIS_URL: redis://redis:6379
    depends_on:
      - mongodb
      - redis
    networks:
      - aori-network
    volumes:
      - ./services/auth/src:/app/src
 
  # User Service
  user:
    build:
      context: ./services/user
      dockerfile: Dockerfile
    ports:
      - '3002:3002'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/users_db
      AUTH_SERVICE_URL: http://auth:3001
      REDIS_URL: redis://redis:6379
    depends_on:
      - mongodb
      - redis
      - auth
    networks:
      - aori-network
    volumes:
      - ./services/user/src:/app/src
 
  # Organization Service
  org:
    build:
      context: ./services/org
      dockerfile: Dockerfile
    ports:
      - '3003:3003'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/orgs_db
      AUTH_SERVICE_URL: http://auth:3001
      USER_SERVICE_URL: http://user:3002
      REDIS_URL: redis://redis:6379
    depends_on:
      - mongodb
      - redis
      - auth
      - user
    networks:
      - aori-network
    volumes:
      - ./services/org/src:/app/src
 
  # Product Service
  product:
    build:
      context: ./services/product
      dockerfile: Dockerfile
    ports:
      - '3004:3004'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/products_db
      AUTH_SERVICE_URL: http://auth:3001
      ORG_SERVICE_URL: http://org:3003
      REDIS_URL: redis://redis:6379
      EVENT_BUS_URL: redis://redis:6379/1
    depends_on:
      - mongodb
      - redis
    networks:
      - aori-network
    volumes:
      - ./services/product/src:/app/src
 
  # Order Service
  order:
    build:
      context: ./services/order
      dockerfile: Dockerfile
    ports:
      - '3005:3005'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/orders_db
      AUTH_SERVICE_URL: http://auth:3001
      USER_SERVICE_URL: http://user:3002
      PRODUCT_SERVICE_URL: http://product:3004
      REDIS_URL: redis://redis:6379
      EVENT_BUS_URL: redis://redis:6379/1
    depends_on:
      - mongodb
      - redis
      - auth
      - user
      - product
    networks:
      - aori-network
    volumes:
      - ./services/order/src:/app/src
 
  # Analytics Service
  analytics:
    build:
      context: ./services/analytics
      dockerfile: Dockerfile
    ports:
      - '3006:3006'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/analytics_db
      AUTH_SERVICE_URL: http://auth:3001
      REDIS_URL: redis://redis:6379
      EVENT_BUS_URL: redis://redis:6379/1
    depends_on:
      - mongodb
      - redis
      - auth
    networks:
      - aori-network
    volumes:
      - ./services/analytics/src:/app/src
 
  # Settings Service
  settings:
    build:
      context: ./services/settings
      dockerfile: Dockerfile
    ports:
      - '3007:3007'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/settings_db
      AUTH_SERVICE_URL: http://auth:3001
      REDIS_URL: redis://redis:6379
    depends_on:
      - mongodb
      - redis
      - auth
    networks:
      - aori-network
    volumes:
      - ./services/settings/src:/app/src
 
  # Notification Service
  notify:
    build:
      context: ./services/notify
      dockerfile: Dockerfile
    ports:
      - '3008:3008'
    environment:
      NODE_ENV: development
      DATABASE_URL: mongodb://mongodb:27017/notify_db
      SENDGRID_API_KEY: ${SENDGRID_API_KEY}
      TWILIO_ACCOUNT_SID: ${TWILIO_ACCOUNT_SID}
      TWILIO_AUTH_TOKEN: ${TWILIO_AUTH_TOKEN}
      REDIS_URL: redis://redis:6379
      EVENT_BUS_URL: redis://redis:6379/1
    depends_on:
      - redis
    networks:
      - aori-network
    volumes:
      - ./services/notify/src:/app/src
 
  # Micro-Frontend: Shell
  shell:
    build:
      context: ./micro-frontends/shell
      dockerfile: Dockerfile
    ports:
      - '3100:3000'
    environment:
      NODE_ENV: development
      API_GATEWAY_URL: http://localhost:3000
    depends_on:
      - api-gateway
    networks:
      - aori-network
    volumes:
      - ./micro-frontends/shell/src:/app/src
 
  # Micro-Frontend: Auth Module
  auth-module:
    build:
      context: ./micro-frontends/auth
      dockerfile: Dockerfile
    ports:
      - '3101:3000'
    environment:
      NODE_ENV: development
      API_GATEWAY_URL: http://localhost:3000
    networks:
      - aori-network
    volumes:
      - ./micro-frontends/auth/src:/app/src
 
  # Micro-Frontend: Product Module
  product-module:
    build:
      context: ./micro-frontends/product
      dockerfile: Dockerfile
    ports:
      - '3104:3000'
    environment:
      NODE_ENV: development
      API_GATEWAY_URL: http://localhost:3000
    networks:
      - aori-network
    volumes:
      - ./micro-frontends/product/src:/app/src
 
  # Micro-Frontend: Order Module
  order-module:
    build:
      context: ./micro-frontends/order
      dockerfile: Dockerfile
    ports:
      - '3105:3000'
    environment:
      NODE_ENV: development
      API_GATEWAY_URL: http://localhost:3000
    networks:
      - aori-network
    volumes:
      - ./micro-frontends/order/src:/app/src
 
  # Databases
  mongodb:
    image: mongo:7
    ports:
      - '27017:27017'
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD:-password}
    volumes:
      - mongodb_data:/data/db
    networks:
      - aori-network
    healthcheck:
      test: ['CMD', 'mongosh', '--eval', "db.adminCommand('ping')"]
      interval: 10s
      timeout: 5s
      retries: 5
 
  # Cache & Event Bus
  redis:
    image: redis:7-alpine
    ports:
      - '6379:6379'
    volumes:
      - redis_data:/data
    networks:
      - aori-network
    healthcheck:
      test: ['CMD', 'redis-cli', 'ping']
      interval: 10s
      timeout: 5s
      retries: 5
 
volumes:
  mongodb_data:
  redis_data:
 
networks:
  aori-network:
    driver: bridge

📦 Service Dockerfile Template

File: services/<service>/Dockerfile

FROM node:20-alpine
 
WORKDIR /app
 
# Install dependencies
COPY package*.json bun.lock* ./
RUN npm install -g bun && bun install --frozen-lockfile
 
# Copy source code
COPY src ./src
COPY tsconfig.json ./
COPY .env* ./
 
# Build if needed (optional for development)
# RUN bun run build
 
# Expose port
EXPOSE 3001
 
# Start service
CMD ["bun", "run", "src/index.ts"]

📝 Environment Configuration

File: .env.docker

# API Gateway
API_GATEWAY_PORT=3000
 
# Services
AUTH_SERVICE_PORT=3001
USER_SERVICE_PORT=3002
ORG_SERVICE_PORT=3003
PRODUCT_SERVICE_PORT=3004
ORDER_SERVICE_PORT=3005
ANALYTICS_SERVICE_PORT=3006
SETTINGS_SERVICE_PORT=3007
NOTIFY_SERVICE_PORT=3008
 
# Database
DATABASE_URL=mongodb://root:password@mongodb:27017/
MONGODB_URI=mongodb://root:password@mongodb:27017/
 
# Cache & Events
REDIS_URL=redis://redis:6379
EVENT_BUS_URL=redis://redis:6379/1
 
# Security
JWT_SECRET=your-very-secure-secret-key-change-in-production
JWT_EXPIRE=7d
 
# Notifications
SENDGRID_API_KEY=your-sendgrid-key
TWILIO_ACCOUNT_SID=your-twilio-sid
TWILIO_AUTH_TOKEN=your-twilio-token
 
# Environment
NODE_ENV=development
LOG_LEVEL=debug

Deployment Topology

📊 Development Environment (Docker Compose)

┌─────────────────────────────────────────────────────────────┐
│                    Docker Network: aori-network             │
│                                                             │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  Localhost Port Mapping (Developer Machine)           │  │
│  │                                                       │  │
│  │  3000  → API Gateway (routing)                        │  │
│  │  3001  → Auth Service                                 │  │
│  │  3002  → User Service                                 │  │
│  │  3003  → Organization Service                         │  │
│  │  3004  → Product Service                              │  │
│  │  3005  → Order Service                                │  │
│  │  3006  → Analytics Service                            │  │
│  │  3007  → Settings Service                             │  │
│  │  3008  → Notification Service                         │  │
│  │                                                       │  │
│  │  3100  → Shell (MFE)                                  │  │
│  │  3101  → Auth Module (MFE)                            │  │
│  │  3102  → User Module (MFE)                            │  │
│  │  3104  → Product Module (MFE)                         │  │
│  │  3105  → Order Module (MFE)                           │  │
│  │  3106  → Analytics Module (MFE)                       │  │
│  │  3107  → Admin Module (MFE)                           │  │
│  │                                                       │  │
│  │  27017 → MongoDB                                      │  │
│  │  6379  → Redis                                        │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
┌───────────────────────────────────────────────────────────┐
│                  Kubernetes Cluster                       │
│                                                           │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  Ingress Controller (nginx-ingress)                 │  │
│  │  ├─ /api/*         → API Gateway Service            │  │
│  │  ├─ /shell/*       → Shell MFE                      │  │
│  │  └─ /auth/*        → Auth Module MFE                │  │
│  └─────────────────────────────────────────────────────┘  │
│                      ▼                                    │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  Service Mesh (Istio) - Optional                    │  │
│  │  ├─ Traffic management                              │  │
│  │  ├─ Security policies                               │  │
│  │  └─ Observability                                   │  │
│  └─────────────────────────────────────────────────────┘  │
│                      ▼                                    │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  Services (Deployments with auto-scaling)           │  │
│  │  ├─ auth-service (replicas: 2-5)                    │  │
│  │  ├─ user-service (replicas: 2-5)                    │  │
│  │  ├─ product-service (replicas: 2-5)                 │  │
│  │  ├─ order-service (replicas: 3-10)                  │  │
│  │  ├─ api-gateway (replicas: 2-5)                     │  │
│  │  └─ ...other services                               │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                           │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  StatefulSets & PersistentVolumes                   │  │
│  │  ├─ MongoDB (replicas: 3 - ReplicaSet)              │  │
│  │  ├─ Redis (cache & event bus)                       │  │
│  │  └─ Elasticsearch (optional search)                 │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                           │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  Monitoring & Observability                         │  │
│  │  ├─ Prometheus (metrics)                            │  │
│  │  ├─ Grafana (dashboards)                            │  │
│  │  ├─ ELK Stack (logging)                             │  │
│  │  └─ Jaeger (distributed tracing)                    │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                           │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  CI/CD Integration                                  │  │
│  │  ├─ GitHub Actions / GitLab CI                      │  │
│  │  ├─ Automated testing on each push                  │  │
│  │  ├─ Docker image building & registry                │  │
│  │  ├─ ArgoCD for GitOps deployment                    │  │
│  │  └─ Automated rollback on failure                   │  │
│  └─────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────┘

🔄 CI/CD Pipeline (GitHub Actions)

File: .github/workflows/ci-cd.yml

name: CI/CD Pipeline
 
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]
 
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: oven-sh/setup-bun@v1
 
      - name: Install dependencies
        run: bun install --frozen-lockfile
 
      - name: Lint
        run: bun run lint
 
      - name: Type check
        run: bun run type-check
 
      - name: Unit tests
        run: bun run test
 
      - name: Build services
        run: bun run build
 
  build-and-push:
    needs: test
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    strategy:
      matrix:
        service: [api-gateway, auth, user, org, product, order, analytics, settings, notify]
 
    steps:
      - uses: actions/checkout@v3
 
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2
 
      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
 
      - name: Build and push
        uses: docker/build-push-action@v4
        with:
          context: ./services/${{ matrix.service }}
          push: true
          tags: |
            ${{ secrets.DOCKER_REGISTRY }}/aori-${{ matrix.service }}:${{ github.sha }}
            ${{ secrets.DOCKER_REGISTRY }}/aori-${{ matrix.service }}:latest
 
  deploy:
    needs: build-and-push
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to Kubernetes
        run: |
          kubectl set image deployment/auth-service \
            auth-service=${{ secrets.DOCKER_REGISTRY }}/aori-auth:${{ github.sha }} \
            --record
          # Repeat for other services...

Risks & Mitigation

⚠️ Technical Risks

RiskImpactLikelihoodMitigation
Data consistency across servicesHIGHMEDIUMImplement event sourcing, saga pattern, distributed transactions
Network latency between servicesMEDIUMHIGHService mesh, caching, async processing
Cascading failuresCRITICALMEDIUMCircuit breakers, timeouts, fallbacks, bulkheads
Database transaction limitationsHIGHHIGHCompensating transactions, eventual consistency
Debugging distributed systemsHIGHHIGHDistributed tracing (Jaeger), centralized logging
Service discovery failuresHIGHMEDIUMUse Kubernetes DNS, health checks, load balancer

🛡️ Mitigation Strategies

1. Circuit Breaker Pattern

Service A → [Circuit Breaker] → Service B
 
States: CLOSED (normal) → OPEN (failing) → HALF_OPEN (testing recovery)

2. Eventual Consistency

  • Accept temporary inconsistency
  • Implement reconciliation jobs
  • Use event logs for audit trail

3. Distributed Tracing

  • Add trace IDs to all requests
  • Log trace ID in every service
  • Use Jaeger for visualization

4. Comprehensive Monitoring

  • Service health checks
  • Request/response times
  • Error rates per service
  • Resource utilization

5. Staged Rollout

  • Canary deployment (5% traffic)
  • Blue-green deployment
  • Feature flags for gradual rollout
  • Quick rollback procedures

📈 Migration Risks

PhaseRiskMitigation
Phase 1Infrastructure setup delaysStart early, use templates
Phase 2Module federation complexityProof of concept first
Phase 3Data migration errorsExtensive testing, parallel running, rollback plan
Phase 4Service integration issuesIntegration tests, end-to-end tests
Phase 5Monolithic API decommissionGradual rollout, deprecation warnings

Implementation Checklist

Phase 1: Foundation

  • Create infrastructure directory structure
  • Write Dockerfile templates
  • Create docker-compose.yml
  • Implement API Gateway service
  • Set up GitHub Actions CI/CD basics
  • Create environment configuration
  • Document setup instructions
  • Local development guide

Phase 2: Micro-Frontend

  • Create shell application
  • Implement module federation
  • Extract auth module
  • Extract product module
  • Extract order module
  • Extract analytics module
  • Module communication setup
  • Error handling & boundaries

Phase 3: Core Services

  • Auth Service implementation
  • User Service implementation
  • Organization Service implementation
  • Data migration scripts (auth, user, org)
  • Integration tests
  • Service-to-service communication
  • Caching layer setup

Phase 4: Business Services

  • Product Service implementation
  • Order Service implementation
  • Analytics Service implementation
  • Event bus setup
  • Data migration scripts (product, order)
  • Saga pattern implementation
  • Event-driven communication

Phase 5: Finalization

  • Settings Service implementation
  • Notification Service implementation
  • Remaining micro-frontend modules
  • Admin portal as micro-frontend
  • Performance optimization
  • Security hardening
  • Load testing
  • Monolithic API decommission

File Structure (Post-Migration)

aori-apps/
├── services/                          # Microservices
│   ├── api-gateway/
│   │   ├── src/
│   │   ├── Dockerfile
│   │   └── package.json
│   ├── auth/
│   ├── user/
│   ├── org/
│   ├── product/
│   ├── order/
│   ├── analytics/
│   ├── settings/
│   └── notify/

├── micro-frontends/                   # Micro-Frontend Apps
│   ├── shell/                         # Main orchestrator
│   ├── auth-module/
│   ├── user-module/
│   ├── org-module/
│   ├── product-module/
│   ├── order-module/
│   ├── analytics-module/
│   └── admin-module/

├── shared/                            # Shared packages
│   ├── http-client/                   # HTTP client library
│   ├── validators/                    # Shared validators
│   ├── constants/                     # Shared constants
│   ├── types/                         # Shared TypeScript types
│   └── utils/                         # Shared utilities

├── infrastructure/                    # Infrastructure as Code
│   ├── docker-compose.yml
│   ├── kubernetes/
│   │   ├── namespaces.yaml
│   │   ├── deployments/
│   │   ├── services/
│   │   ├── ingress.yaml
│   │   └── config-maps.yaml
│   ├── terraform/
│   └── github/

├── docs/                              # Documentation
│   ├── architecture/
│   ├── deployment/
│   ├── development/
│   └── api-reference/

├── tools/                             # Development tools
│   ├── scripts/
│   └── cli/

├── .github/workflows/                 # CI/CD
│   └── ci-cd.yml

├── docker-compose.yml
├── .env.example
├── package.json                       # Root workspace config
└── README.md

Success Metrics

After full migration, measure:

Performance:

  • API response time: < 200ms p99
  • Service startup time: < 30s
  • Deployment time: < 5m per service
  • Database query time: < 50ms p99

Reliability:

  • System uptime: > 99.9%
  • Error rate: < 0.1%
  • MTTR (Mean Time To Recovery): < 15m
  • Zero cascading failures in production

Development:

  • Local development setup time: < 10m
  • Build time per service: < 2m
  • Test execution time: < 5m
  • Deployment frequency: Daily

Scaling:

  • Horizontal scaling: Services scale independently
  • Resource utilization: 60-70%
  • Cost optimization: Pay per service, not total
  • Peak load handling: 5x traffic increase

Next Steps

  1. Review & Approve Blueprint

    • Stakeholder alignment on architecture
    • Technical team consensus
    • Business case validation
  2. Phase 1 Kickoff

    • Set up repository structure
    • Create templates and tools
    • Assign team members
    • Define success criteria
  3. Continuous Monitoring

    • Track migration progress
    • Adjust timeline if needed
    • Document learnings
    • Share updates with team
  4. Post-Migration

    • Gather feedback from teams
    • Optimize based on learnings
    • Plan ecosystem expansion
    • Plan Phase 5 (optional) for advanced features

References


Document prepared for internal team use. Last updated: August 4, 2026