A production-ready microservices system built with NestJS, demonstrating event-driven architecture, distributed tracing, and inter-service communication patterns for managing building facilities and alarms.
Virtual Facility is a comprehensive microservices-based application that implements modern distributed system patterns including:
- Event-Driven Architecture using NATS and RabbitMQ message brokers
- Orchestration & Choreography patterns for service communication
- Distributed Tracing with correlation IDs across all services
- API Gateway with rate limiting, caching, and security features
- Transactional Outbox Pattern for reliable message publishing
- Inbox Pattern for idempotent message processing
- Health Checks and observability built-in
- Single entry point for all client requests
- HTTP REST API with Swagger documentation
- Rate limiting and request throttling
- Redis-based response caching
- Security features (CORS, Helmet)
- Request/response logging and tracing
- Routes requests to appropriate backend services
- Manages building data and operations
- PostgreSQL database for persistence
- REST API for CRUD operations on buildings
- Transactional Outbox pattern for reliable event publishing
- Publishes events to RabbitMQ
- Orchestrates complex business workflows
- PostgreSQL database with Inbox pattern
- Listens to RabbitMQ events
- Idempotent message processing
- Manages workflow state and execution
- Processes alarm events in real-time
- Orchestrates alarm classification and notifications
- Consumes events from NATS
- Implements orchestration pattern (coordinator)
- Communicates with classifier and notifications services
- Simulates alarm generation for testing
- Scheduled job to create random alarms
- Publishes alarm events to NATS
- Includes distributed tracing headers
- AI/ML alarm classification logic
- Request/response pattern via NATS
- Categorizes alarms: critical, non-critical, or invalid
- Stateless service for horizontal scaling
- Sends notifications about classified alarms
- Event-driven via RabbitMQ
- Handles multiple notification channels
- Asynchronous processing
- NATS: High-performance pub/sub for synchronous request/response patterns
- RabbitMQ: Reliable message queue for asynchronous event processing
- Redis: In-memory cache and distributed locking
- PostgreSQL:
virtual-facility-db- Building data storageworkflows-db- Workflow state and inbox messages
- Node.js 20+
- Docker & Docker Compose
- pnpm (package manager)
# Install dependencies
pnpm install# Start all services
docker-compose up
# Start with live reload (development mode)
docker-compose watch
# Start specific services
docker-compose up api-gateway virtual-facility
# View logs
docker-compose logs -f [service-name]
# Stop all services
docker-compose down# Development mode with watch
pnpm run start:dev
# Start specific microservice
pnpm run start:dev -- [service-name]
# Production mode
pnpm run start:prod
# Build all services
pnpm run buildAPI Gateway (http://localhost:3000)
POST /alarms- Create new alarm (fire-and-forget)POST /alarms/classify- Classify alarm synchronously (cached)
POST /buildings- Create new building (proxied to Virtual Facility)
Access interactive API documentation at: http://localhost:3000/api
GET /health- API Gateway health status
Each service can be configured via environment variables in docker-compose.yml:
PORT: 3000
NATS_URL: nats://nats:4222
RABBITMQ_URL: amqp://rabbitmq:5672
REDIS_URL: redis://redis:6379
CORS_ORIGIN: *
BROKER_TIMEOUT_MS: 3000
BROKER_RETRIES: 1
RATE_LIMIT_TTL: 60000
RATE_LIMIT: 300
IDEMPOTENCY_TTL_MS: 600000
CLASSIFY_CACHE_TTL: 5000POSTGRES_HOST: [service]-db
POSTGRES_PORT: 5432
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: [database-name]Centralized entry point providing:
- Request routing
- Rate limiting
- Authentication/Authorization
- Response caching
- Cross-cutting concerns
Orchestration (Alarms Service):
// Alarms Service coordinates the workflow
const classification = await natsClient.send('alarm.classify', data);
await rabbitmqClient.emit('notification.send', { alarm, classification });Choreography (Event-driven):
// Services react independently to events
@EventPattern('alarm.created')
async handleAlarm(@Payload() data) { ... }Ensures reliable event publishing with database transactions.
Guarantees idempotent message processing using message deduplication.
Correlation IDs propagated across all service calls:
const traceId = tracingService.generateTraceId();
headers.set('traceId', traceId);virtual-facility/
βββ apps/ # Microservices
β βββ api-gateway/ # HTTP Gateway
β βββ virtual-facility/ # Building management
β βββ workflows-service/ # Workflow orchestration
β βββ alarms-service/ # Alarm processing
β βββ alarms-generator/ # Test data generator
β βββ alarms-classifier-service/ # ML classification
β βββ notifications-service/ # Notification handling
βββ libs/ # Shared libraries
β βββ alarms/ # Alarm DTOs
β βββ buildings/ # Building DTOs
β βββ workflows/ # Workflow DTOs
β βββ tracing/ # Distributed tracing
βββ docker-compose.yml # Service orchestration
βββ Dockerfile # Multi-service build
βββ package.json # Dependencies & scripts
# Unit tests
pnpm run test
# E2E tests
pnpm run test:e2e
# Test coverage
pnpm run test:cov
# Watch mode
pnpm run test:watch# Lint code
pnpm run lint
# Format code
pnpm run format- RabbitMQ Management: http://localhost:15672 (guest/guest)
- Redis: Connect via redis-cli or GUI tools
All services use structured logging with trace IDs for correlation.
Built-in health endpoints using @nestjs/terminus for:
- Service health
- Database connectivity
- Message broker status
Metrics middleware tracks request duration and counts.
- Helmet: Security headers
- CORS: Configurable origins
- Rate Limiting: Request throttling per client
- Input Validation: Class-validator decorators
- Request Size Limits: 1MB body limit
# Build all services
pnpm run build
# Run production mode
pnpm run start:prod# Multi-stage build included in Dockerfile
docker build --build-arg APP_NAME=api-gateway -t virtual-facility-gateway .
docker run -p 3000:3000 virtual-facility-gatewayServices support horizontal scaling:
# Scale workflows service to 3 replicas
docker-compose up --scale workflows-service=3- Framework: NestJS 11.x
- Language: TypeScript 5.7
- Message Brokers: NATS 2.x, RabbitMQ 3.x
- Databases: PostgreSQL 13, Redis 7
- API Documentation: Swagger/OpenAPI
- Validation: class-validator, class-transformer
- HTTP Client: Axios
- ORM: TypeORM 0.3
- API Gateway β Virtual Facility (HTTP)
- API Gateway β Classifier (NATS)
- Alarms Generator β Alarms Service (NATS)
- Alarms Service β Notifications (RabbitMQ)
- Virtual Facility β Workflows (RabbitMQ)
UNLICENSED - Private project
This project demonstrates enterprise-grade microservices patterns suitable for:
- High-throughput event processing
- Complex workflow orchestration
- Distributed system reliability
- Scalable cloud-native applications