System Architecture
AmbioSys follows a microservices architecture with clear separation of concerns. Each service is independently deployable, scalable, and maintainable.Core Services
Backend API
Container:
ambiotec-backendPort: 3000Technology: Express.js + Node.js 20Purpose: Main business logic and data managementWhatsApp Bot
Container:
gpt4-ambiotec-botPort: 4500Technology: Express.js + OpenAI + Socket.IOPurpose: AI-powered customer conversationsFrontend
Container: (Development only)Port: 5173Technology: React 18 + Vite + Material-UIPurpose: User interface and interaction
Redis
Container:
ambiotec-redisPort: 6379Technology: Redis 7 AlpinePurpose: Cache, sessions, job queuesBackend API Service
Service Structure
The backend API (Backend/web-ambiotec) is the core of AmbioSys, handling all business operations.
Key Features
Authentication & Authorization
Authentication & Authorization
Database Connection Management
Database Connection Management
Implementation:
src/config/db.js- PostgreSQL connection pooling with retry logic
- Configurable pool size (default 20 connections)
- SSL support for cloud databases (AWS RDS)
- Automatic reconnection with exponential backoff
- Graceful shutdown handling
API Routes & Middleware
API Routes & Middleware
Implementation:
src/app.jsAll routes are protected with authentication and API usage logging:Scheduled Jobs
Scheduled Jobs
Implementation:
src/jobs/cronJobs.js- Quotation follow-up reminders
- License expiration notifications
- SLA deadline monitoring
- Overdue service request alerts
node-cron for scheduling and BullMQ for reliable job execution.Key Dependencies
WhatsApp Bot Service
Service Structure
The WhatsApp bot (Backend/gpt4-ambiotec-bot) provides AI-powered customer support.
Real-Time Architecture
Message Processing
The webhook controller:
- Validates the request signature
- Extracts message content and sender
- Retrieves conversation context from Redis
- Queries customer data from PostgreSQL
Socket.IO Events
Internal Chat: chat:send-message
Internal Chat: chat:send-message
Emitted by: Frontend (internal team chat)Handled by: Bot service
External Chat: chat:send-message-chatweb
External Chat: chat:send-message-chatweb
Emitted by: Frontend (customer-facing web chat)Handled by: Bot service with GPT-4 processing
Frontend Application
Technology Stack
Context Architecture
The frontend uses React Context for state management:AuthContext
User authentication state, login/logout, token management
PermissionContext
Role-based UI rendering, feature flags, module access
NotificationsContext
Real-time notification management and display
ThemeModeContext
Dark/light theme toggle with Material-UI integration
Data Flow
Example: Creating a Service Request
Backend Validates & Processes
requireAuthmiddleware verifies JWTlogApiUsagemiddleware logs the request- Route handler validates input with
express-validator - Business logic in controller
Database Transaction
Stored procedure called:This:
- Inserts into
service_requeststable - Creates initial status entry
- Calculates SLA deadlines
- Triggers notification job
Database Architecture
Schema Structure
PostgreSQL database with thedb_ambiotec schema:
- Core Tables
- Service Management
- Sales & Finance
- Communication
users- System users with roles and permissionscustomers- Customer organizationscontacts- Customer contact personsdepartments- Geographic departmentsmunicipio- Municipalities within departmentsroles- User roles with descriptionsmodules- System modules for permissions
Stored Procedures
Business logic encapsulated in PostgreSQL functions:DB/Functions_StoredProcedures/:
SP_ServiceRequest.sqlSP_Quotations.sqlSP_Customers.sqlSP_Creditos.sqlSP_Payments.sql- And more…
Docker Orchestration
Network Architecture
ambio_net Docker network:
- Backend → Redis (via hostname
redis) - Bot → Redis (via hostname
redis) - Backend → PostgreSQL (external host)
- Bot → PostgreSQL (external host)
Volume Management
Backend Volume Mounts
Backend Volume Mounts
Redis Persistence
Redis Persistence
Security Considerations
Authentication & Sessions
Authentication & Sessions
- JWT tokens with configurable expiration
- Secure session storage in Redis
- Password hashing with
bcrypt(work factor 10) - HTTPS enforcement in production
Input Validation
Input Validation
express-validatorfor all API inputs- SQL injection prevention via parameterized queries
- XSS protection with DOMPurify on frontend
- File upload validation (MIME type, size limits)
API Security
API Security
- Rate limiting (TODO: implement with
express-rate-limit) - CORS configuration for allowed origins
- Request size limits (50MB for file uploads)
- API usage logging for audit trails
Sensitive Data Handling
Sensitive Data Handling
- Query parameters sanitized in logs:
Performance Optimizations
Database Connection Pooling
20 concurrent connections with automatic retry and backoff
Redis Caching
Session data, conversation context, and frequently accessed data
Job Queue Processing
Asynchronous email sending and notification processing with BullMQ
Frontend Code Splitting
React lazy loading for routes and heavy components
Monitoring & Logging
- Backend Logs
- Bot Logs
- Database Query Logs
Morgan HTTP request logging:Custom application logs:
Deployment Considerations
For production deployment:
-
Build production images:
-
Environment-specific configs:
- Use secrets management (AWS Secrets Manager, HashiCorp Vault)
- Enable SSL/TLS for database connections
- Set
NODE_ENV=production
-
Scaling:
- Deploy multiple backend instances behind a load balancer
- Use Redis Cluster for high availability
- Consider PostgreSQL read replicas for analytics
-
Monitoring:
- Integrate with APM tools (New Relic, Datadog)
- Set up health check endpoints
- Configure alerting for errors and performance
Next Steps
API Reference
Explore detailed endpoint documentation
Database Schema
Deep dive into table structures and relationships
Environment Variables
Fine-tune environment variables and settings
Docker Setup
Production deployment with Docker