Overview
Rodando Backend follows a modular monolithic architecture built on NestJS principles. The application is organized into independent, loosely-coupled modules that communicate through well-defined interfaces and domain events.High-Level Architecture
Core Modules
The application is organized into feature modules, each handling a specific domain:Application Modules (src/modules/)
Trip Module
Trip Module
Manages the complete trip lifecycle from request to completion.Key Components:Responsibilities:
TripController: REST endpoints for trip operationsTripService: Business logic for trip state transitionsTripRepository: Database operations- Trip entities:
Trip,TripAssignment,TripEvent
- Trip estimation and fare calculation
- Driver assignment workflow
- Status transitions with validation
- Event emission for real-time updates
src/modules/trip/controllers/trip.controller.ts:1src/modules/trip/services/trip.service.ts
Auth Module
Auth Module
Handles authentication, authorization, and session management.Key Components:
AuthController: Login, refresh, logout endpointsAuthService: JWT token generation and validation- Guards:
JwtAuthGuard,RolesGuard - Strategies: JWT access and refresh token strategies
- User sends credentials to
/api/auth/login - Service validates and generates access + refresh tokens
- Web clients receive tokens in HTTP-only cookies
- Mobile clients receive tokens in response body
- Access token used for API requests (expires in 15min)
- Refresh token used to get new access tokens (expires in 7 days)
WEB: Cookie-based sessions for web dashboardsMOBILE: Token-based sessions for mobile appsAPI_CLIENT: Token-based for third-party integrations
src/modules/auth/controllers/auth.controller.ts:1src/modules/auth/services/auth.service.ts
Drivers Availability Module
Drivers Availability Module
Tracks driver locations and online status in real-time.Key Components:
DriversAvailabilityService: Location updates and queriesDriverAvailabilityRepository: Geohash-based storage- Scheduled tasks for offline detection
- Driver locations encoded as geohash strings
- Enables efficient proximity queries
- Configurable precision for radius matching
- Drivers send periodic “ping” updates
- TTL-based expiry (default: 120 seconds)
- Sweep job marks inactive drivers as offline
- Find available drivers near pickup location
- Filter by vehicle type and service class
- Exclude drivers already in active trips
- Return ordered by distance
User Module
User Module
Manages user accounts, profiles, and roles.User Roles:
passenger: Can request tripsdriver: Can accept and complete tripsadmin: Full system access
User: Core user account dataUserProfile: Extended profile informationSession: Active user sessions
- User → DriverProfile (if role = driver)
- User → Vehicle (drivers can have multiple vehicles)
- User → Trips (as passenger or driver)
Vehicles Module
Vehicles Module
Manages vehicle information, types, and categories.Structure:
Vehicle: Individual vehicle instancesVehicleType: Economy, Premium, Luxury, etc.VehicleCategory: Sedan, SUV, Van, etc.VehicleServiceClass: Standard, Comfort, Business
- Vehicle registration for drivers
- Type-based fare calculation
- Service class filtering in trip matching
Transactions Module
Transactions Module
Handles financial transactions and payment processing.Transaction Types:
- Trip payments
- Driver earnings
- Refunds and adjustments
- Cash collections
- Transaction history and audit trail
- Balance calculations
- Payment method support
Settings Modules
Settings Modules
Configuration and business rules.Sub-modules:
- Price Policies: Per-mile, per-minute, surge pricing
- Zones: Service area boundaries and rules
- Cities: Geographic configuration
- Core Settings: System-wide configuration
Infrastructure Modules (src/infrastructure/)
Notifications
Mail Module: Email notifications via SMTPSMS Module: SMS alerts via third-party providersUsed for trip confirmations, driver alerts, etc.
Queue Module
Background job processingHandles async tasks like notifications, reports, and batch operations
Outbox Module
Transactional outbox patternEnsures reliable event publishing with database consistency
WebSocket Module
Socket.IO infrastructureManages connections, rooms, and message broadcasting
Real-time Module (src/realtime/)
The real-time module orchestrates WebSocket communications: Gateways (WebSocket endpoints):DriverAuthGateway: Driver authentication and connectionDriverAvailabilityGateway: Location updates and status changesPassengerGateway: Trip requests and updates for passengersAdminGateway: System monitoring and control
TripRealtimePublisher: Broadcasts trip state changesDriverAvailabilityRealtimePublisher: Notifies availability updatesAuthRealtimePublisher: Handles auth events
TripEventsListener: Listens to trip.* eventsDriverAvailabilityEventsListener: Reacts to driver status changesAssignmentExpiryListener: Handles timeout logic
TripAssigningOrchestrator: Manages driver matching and retry logicDriverAssignedAutoArrivingOrchestrator: Auto-transitions to arriving state
src/realtime/realtime.module.ts:1
Database Layer
TypeORM Configuration
The database layer uses TypeORM with PostgreSQL:src/database/database.module.ts
- Automatic database creation on startup
- Entity auto-discovery from modules
- Migration support (production)
- Synchronize mode (development only)
src/database/database.module.ts:1
Repository Pattern
Each entity has a dedicated repository:API Response Structure
All API responses follow a consistent format:src/common/dto/api-response.dto.ts
src/common/dto/api-response.dto.ts:1
Success Response:
Event-Driven Architecture
The application uses EventEmitter2 for loose coupling:Event Flow
src/app.module.ts:61:
Common Events
trip.created- New trip requestedtrip.assigning.started- Matching driverstrip.assignment.offered- Offer sent to drivertrip.assignment.accepted- Driver acceptedtrip.assignment.rejected- Driver rejectedtrip.assignment.expired- Offer timeouttrip.completed- Trip finisheddriver.status.changed- Online/offline statusdriver.location.updated- Location ping received
Design Patterns
1. Repository Pattern
- Abstracts database operations
- Enables testing with mock repositories
- Centralizes query logic
2. Service Layer Pattern
- Business logic separated from controllers
- Single responsibility per service
- Injected via dependency injection
3. DTO Pattern
- Data validation with class-validator
- Type safety for API contracts
- Auto-generated Swagger documentation
4. Guard Pattern
- Authentication and authorization checks
- Reusable across controllers
- Examples:
JwtAuthGuard,RolesGuard
5. Interceptor Pattern
- Cross-cutting concerns
- Response transformation
- Example:
ApiResponseInterceptorwraps all responses
6. State Machine Pattern
- Trip status transitions with validation
- Prevents invalid state changes
- Clear business rules
7. Observer Pattern (EventEmitter)
- Decoupled communication between modules
- Multiple listeners for same event
- Async processing
Technology Stack
- Backend Framework
- Database
- Real-time
- Authentication
- Validation
- Documentation
NestJS 11.x
- Modular architecture
- Dependency injection
- Decorator-based
- TypeScript-first
@nestjs/common: Core decorators and utilities@nestjs/core: Application context@nestjs/platform-express: HTTP server
Configuration Management
The application uses NestJS ConfigModule:- Type-safe configuration
- Validation on startup
- Environment-specific settings
- Centralized access via
ConfigService
Scalability Considerations
Horizontal Scaling
- Stateless API design
- Sticky sessions for WebSockets
- Redis adapter for Socket.IO clustering
- Database connection pooling
Database Optimization
- Indexed queries (geohash, user IDs, trip status)
- Pagination for list endpoints
- Eager loading to prevent N+1 queries
- Caching for frequently accessed data
Real-time Performance
- Room-based broadcasting (not global)
- Event filtering at gateway level
- Batch updates where possible
- WebSocket connection limits
Async Processing
- Event-driven for non-critical operations
- Queue for background jobs
- Scheduled tasks for cleanup
- Transactional outbox for reliability
Security Measures
Authentication
- JWT with short-lived access tokens (15 min)
- Long-lived refresh tokens (7 days)
- HTTP-only cookies for web clients
- Token revocation on logout
Authorization
- Role-based access control (RBAC)
- Route guards on protected endpoints
- User ID validation from JWT
- Resource ownership checks
Input Validation
- DTO validation with class-validator
- Whitelist mode (strip unknown properties)
- SQL injection prevention (parameterized queries)
- XSS protection (input sanitization)
Rate Limiting
- Throttling with @nestjs/throttler
- Configurable limits per endpoint
- IP-based tracking
- Protection against DDoS
Testing Strategy
Test files use the
.spec.ts extension and are colocated with source files- Services with mocked dependencies
- Repository logic
- Utility functions
- Run with:
npm run test
- Controller endpoints
- Database operations
- Authentication flows
- Run with:
npm run test:e2e
- Custom scripts in
scripts/directory - Manual connection testing
- Event flow verification
Next Steps
API Reference
Explore detailed endpoint documentation
Authentication Concept
Deep dive into JWT auth implementation
WebSocket Guide
Learn about real-time features
Trip Lifecycle
Understand trip state machine
