System Architecture
YeboCars's technical architecture is built for scalability, performance, and real-time interactions.
High-Level Architecture
mermaid
graph TB
subgraph "Client Layer"
WEB[Web App<br/>React 18 + Vite]
MOBILE[Mobile App<br/>React Native]
end
subgraph "CDN & Static Assets"
CDN[Cloudflare CDN]
MEDIA[Media Storage<br/>Cloudflare R2]
end
subgraph "API Layer"
API[Express.js API<br/>Node.js]
WS[Socket.io<br/>WebSocket Server]
end
subgraph "AI Services"
GEMINI[Google Gemini AI<br/>Listing Generation<br/>NL Search<br/>Recommendations]
end
subgraph "External Services"
VIN[VIN Decoder API]
SMS[SMS Gateway<br/>OTP Verification]
end
subgraph "Data Layer"
MONGO[(MongoDB<br/>Vector Search)]
REDIS[(Redis<br/>Session & Cache)]
end
WEB --> CDN
MOBILE --> CDN
WEB --> API
MOBILE --> API
WEB --> WS
MOBILE --> WS
API --> MONGO
API --> REDIS
API --> GEMINI
API --> VIN
API --> SMS
API --> MEDIA
WS --> REDIS
style WEB fill:#61dafb
style MOBILE fill:#61dafb
style API fill:#68a063
style WS fill:#010101
style MONGO fill:#4db33d
style REDIS fill:#dc382d
style GEMINI fill:#4285f4
style CDN fill:#f38020
style MEDIA fill:#f38020Technology Stack
Frontend
- React 18 - UI framework with Hooks
- Vite - Fast build tool and dev server
- TailwindCSS - Utility-first CSS framework
- React Router - Client-side routing
- Zustand - State management
- Socket.io Client - Real-time messaging
- React Query - Server state management
Backend
- Node.js - JavaScript runtime
- Express.js - Web framework
- TypeScript - Type-safe JavaScript
- Socket.io - WebSocket server
- JWT - Authentication tokens
- Bcrypt - Password hashing
Database
- MongoDB - Document database
- Mongoose - ODM for MongoDB
- MongoDB Atlas Search - Full-text and vector search
- Redis - Cache and session store
AI & ML
- Google Gemini AI - Generative AI
- Listing description generation
- Natural language search
- Price recommendations
- Personalized suggestions
Infrastructure
- Cloudflare Pages - Frontend hosting
- Cloudflare R2 - Object storage for images/videos
- Cloudflare CDN - Global content delivery
- Cloudflare Workers - Edge computing
- MongoDB Atlas - Managed database hosting
Application Flow
User Registration Flow
mermaid
sequenceDiagram
actor User
participant App
participant API
participant SMS
participant DB
User->>App: Enter phone & details
App->>API: POST /auth/signup
API->>DB: Check if user exists
DB-->>API: User does not exist
API->>SMS: Send OTP
SMS-->>User: SMS with OTP
API->>DB: Create pending user
API-->>App: Registration initiated
User->>App: Enter OTP
App->>API: POST /auth/verify-signup
API->>DB: Verify OTP
DB-->>API: OTP valid
API->>DB: Mark user as verified
API-->>App: JWT tokens
App->>User: Login successfulCar Listing Creation Flow
mermaid
sequenceDiagram
actor Dealer
participant App
participant API
participant AI
participant Storage
participant DB
Dealer->>App: Fill car details
App->>API: POST /cars
API->>DB: Save car listing
alt AI Description Enabled
Dealer->>App: Request AI description
App->>API: POST /ai/generate-description
API->>AI: Generate description
AI-->>API: AI-generated text
API-->>App: Description
App->>Dealer: Show description
end
Dealer->>App: Upload images
App->>Storage: Upload to R2
Storage-->>App: Image URLs
App->>API: PUT /cars/:id (update images)
API->>DB: Update car with images
API-->>App: Car created
App->>Dealer: Success messageCar Search Flow
mermaid
sequenceDiagram
actor Buyer
participant App
participant API
participant MongoDB
participant AI
Buyer->>App: Enter search query
alt Standard Search
App->>API: GET /cars?filters
API->>MongoDB: Query with filters
MongoDB-->>API: Matching cars
else Natural Language Search
App->>API: POST /ai/search-natural-language
API->>AI: Parse query
AI-->>API: Structured filters
API->>MongoDB: Vector search
MongoDB-->>API: Relevant cars
end
API-->>App: Search results
App->>Buyer: Display carsReal-Time Messaging Flow
mermaid
sequenceDiagram
actor Customer
actor Dealer
participant App1 as Customer App
participant App2 as Dealer App
participant WS as Socket.io Server
participant DB
Customer->>App1: Send message
App1->>WS: Emit 'send_message'
WS->>DB: Save message
WS->>App2: Emit 'new_message'
App2->>Dealer: Show notification
Dealer->>App2: Read message
App2->>WS: Emit 'mark_read'
WS->>DB: Update read status
WS->>App1: Emit 'message_read'
App1->>Customer: Show read receiptDatabase Schema
Core Collections
mermaid
erDiagram
User ||--o{ Car : creates
User ||--o{ Favorite : has
User ||--o{ Inquiry : sends
User ||--o| Dealer : becomes
Dealer ||--o{ Car : lists
Dealer ||--o{ DealerReview : receives
Car ||--o{ CarView : has
Car ||--o{ CarLike : has
Car ||--o{ CarComment : has
Car ||--o{ CarShare : has
Car ||--|| CarAnalytics : has
Car }o--|| CarMake : belongs_to
CarMake ||--o{ CarModel : has
User ||--o{ Message : sends
User ||--o{ Message : receives
Car ||--o{ Inquiry : about
Car ||--o{ TestDrive : schedules
User ||--|| Country : from
Car ||--|| Country : in
Dealer ||--|| Country : operates_in
User {
string phone PK
string email
string password
string name
string avatar
string role
ObjectId dealerId FK
ObjectId countryId FK
boolean isPhoneVerified
date lastLogin
}
Dealer {
string name
string email
string phone
string location
string businessLicense
string type
boolean isApproved
number rating
number totalSales
map businessHours
string website
string description
ObjectId countryId FK
}
Car {
string make
string model
number year
number price
number mileage
string fuelType
string transmission
string bodyType
string color
string description
array images
array videos
array features
ObjectId sellerId FK
string sellerType
string condition
string status
ObjectId countryId FK
}
CarMake {
string name
string logo
number popularity
}
CarModel {
ObjectId makeId FK
string name
array bodyTypes
array fuelTypes
number avgPrice
}
CarView {
ObjectId carId FK
ObjectId userId FK
string ipAddress
date viewedAt
}
CarLike {
ObjectId carId FK
ObjectId userId FK
date likedAt
}
CarComment {
ObjectId carId FK
ObjectId userId FK
string text
number rating
ObjectId parentId FK
date createdAt
}
Favorite {
ObjectId userId FK
ObjectId carId FK
date addedAt
}
Inquiry {
ObjectId customerId FK
ObjectId dealerId FK
ObjectId carId FK
string message
string contactMethod
string status
date createdAt
}
Message {
ObjectId senderId FK
ObjectId receiverId FK
string text
boolean isRead
date sentAt
date readAt
}
TestDrive {
ObjectId carId FK
ObjectId customerId FK
string preferredDate
string preferredTime
string message
string status
}
DealerReview {
ObjectId dealerId FK
ObjectId userId FK
number rating
string comment
date createdAt
}Indexes
User Collection
javascript
{ phone: 1 } // unique
{ role: 1 }
{ dealerId: 1 }
{ countryId: 1 }
{ isPhoneVerified: 1 }
{ createdAt: -1 }Car Collection
javascript
{ make: 1, model: 1 }
{ price: 1, year: -1 }
{ status: 1, createdAt: -1 }
{ sellerId: 1, status: 1 }
{ countryId: 1, status: 1 }
{ countryId: 1, price: 1 }
// Full-text search
{ description: "text", make: "text", model: "text" }Dealer Collection
javascript
{ email: 1 } // unique
{ type: 1 }
{ isApproved: 1 }
{ location: 1 }
{ rating: -1 }
{ countryId: 1 }API Architecture
Layered Architecture
mermaid
graph TB
subgraph "Presentation Layer"
ROUTES[Routes<br/>Express Router]
end
subgraph "Middleware Layer"
AUTH[Authentication]
VALID[Validation]
RATE[Rate Limiting]
COUNTRY[Country Context]
end
subgraph "Business Logic Layer"
CTRL[Controllers]
SERV[Services]
end
subgraph "Data Access Layer"
MODELS[Mongoose Models]
REPO[Repositories]
end
subgraph "External Layer"
AI[AI Service]
VIN_SRV[VIN Service]
SMS_SRV[SMS Service]
end
ROUTES --> AUTH
AUTH --> VALID
VALID --> RATE
RATE --> COUNTRY
COUNTRY --> CTRL
CTRL --> SERV
SERV --> MODELS
SERV --> REPO
SERV --> AI
SERV --> VIN_SRV
SERV --> SMS_SRV
MODELS --> REPORequest/Response Flow
mermaid
sequenceDiagram
participant Client
participant Route
participant Middleware
participant Controller
participant Service
participant Model
participant DB
Client->>Route: HTTP Request
Route->>Middleware: authenticate()
Middleware->>Middleware: Verify JWT
Middleware->>Route: User context
Route->>Middleware: validateBody()
Middleware->>Middleware: Schema validation
Middleware->>Route: Validated data
Route->>Controller: Handler function
Controller->>Service: Business logic
Service->>Model: Query data
Model->>DB: MongoDB query
DB-->>Model: Result
Model-->>Service: Data
Service-->>Controller: Processed data
Controller-->>Route: Response
Route-->>Client: JSON responseSecurity Architecture
Authentication Flow
mermaid
graph LR
A[User Login] --> B[Verify Credentials]
B --> C[Generate JWT]
C --> D[Access Token<br/>24h lifetime]
C --> E[Refresh Token<br/>30d lifetime]
D --> F[API Requests]
F --> G{Token Valid?}
G -->|Yes| H[Grant Access]
G -->|No| I[Refresh Token]
I --> J{Refresh Valid?}
J -->|Yes| K[New Access Token]
J -->|No| L[Re-authenticate]
K --> FSecurity Layers
mermaid
graph TB
subgraph "Edge Security"
WAF[Cloudflare WAF]
DDOS[DDoS Protection]
SSL[SSL/TLS Encryption]
end
subgraph "Application Security"
JWT[JWT Authentication]
BCRYPT[Bcrypt Password Hashing]
RATE_LIM[Rate Limiting]
INPUT[Input Validation]
CORS[CORS Policy]
end
subgraph "Data Security"
ENCRYPT[Encryption at Rest]
BACKUP[Automated Backups]
ACCESS[Access Control]
end
WAF --> JWT
DDOS --> JWT
SSL --> JWT
JWT --> ENCRYPT
BCRYPT --> ENCRYPT
RATE_LIM --> ENCRYPT
INPUT --> ENCRYPT
CORS --> ENCRYPTAI Integration Architecture
Google Gemini AI Integration
mermaid
graph TB
subgraph "Application"
API[API Endpoint]
AI_SRV[AI Service Layer]
CACHE[Response Cache]
end
subgraph "Google Cloud"
GEMINI[Gemini API]
end
subgraph "Use Cases"
GEN[Listing Generation]
ENH[Description Enhancement]
NLS[Natural Language Search]
REC[Recommendations]
PRICE[Pricing Insights]
end
API --> AI_SRV
AI_SRV --> CACHE
AI_SRV --> GEMINI
GEMINI --> GEN
GEMINI --> ENH
GEMINI --> NLS
GEMINI --> REC
GEMINI --> PRICE
style GEMINI fill:#4285f4Vector Search Architecture
mermaid
graph LR
A[User Query] --> B[AI Service]
B --> C[Generate Embeddings]
C --> D[MongoDB Vector Search]
D --> E[Similar Cars]
E --> F[Rank Results]
F --> G[Return to User]
H[Car Listing] --> I[Generate Description Embeddings]
I --> J[Store in MongoDB]Real-Time Features
Socket.io Architecture
mermaid
graph TB
subgraph "Clients"
C1[Customer App]
C2[Dealer App]
C3[Admin Panel]
end
subgraph "Socket.io Server"
WS[WebSocket Server]
ROOMS[Room Management]
EVENTS[Event Handlers]
end
subgraph "Backend"
REDIS[(Redis<br/>Pub/Sub)]
API[REST API]
end
C1 <--> WS
C2 <--> WS
C3 <--> WS
WS <--> ROOMS
WS <--> EVENTS
WS <--> REDIS
API <--> REDIS
style WS fill:#010101
style REDIS fill:#dc382dEvent Types
| Event | Direction | Description |
|---|---|---|
new_message | Server → Client | New message received |
message_read | Server → Client | Message marked as read |
car_viewed | Server → Dealer | Car listing viewed |
new_inquiry | Server → Dealer | New inquiry received |
typing | Client → Server | User is typing |
online | Server → Client | User came online |
offline | Server → Client | User went offline |
Media Processing Pipeline
mermaid
graph LR
A[User Upload] --> B[API Endpoint]
B --> C{File Validation}
C -->|Valid| D[Upload to R2]
C -->|Invalid| E[Reject]
D --> F[Generate Thumbnail]
F --> G[Optimize Image]
G --> H[CDN Distribution]
H --> I[Store URL in DB]
I --> J[Return to Client]Media Storage Structure
yebocars-media/
├── cars/
│ ├── {carId}/
│ │ ├── original/
│ │ │ ├── image1.jpg
│ │ │ └── image2.jpg
│ │ ├── thumbnails/
│ │ │ ├── image1_thumb.jpg
│ │ │ └── image2_thumb.jpg
│ │ └── videos/
│ │ └── video1.mp4
├── dealers/
│ └── {dealerId}/
│ ├── logo.png
│ └── banner.jpg
└── users/
└── {userId}/
└── avatar.jpgScalability Strategy
Horizontal Scaling
mermaid
graph TB
subgraph "Load Balancer"
LB[Cloudflare Load Balancer]
end
subgraph "API Servers"
API1[API Server 1]
API2[API Server 2]
API3[API Server 3]
end
subgraph "Database Cluster"
PRIMARY[(MongoDB Primary)]
SECONDARY1[(MongoDB Secondary 1)]
SECONDARY2[(MongoDB Secondary 2)]
end
subgraph "Cache Layer"
REDIS_M[(Redis Master)]
REDIS_S[(Redis Slave)]
end
LB --> API1
LB --> API2
LB --> API3
API1 --> PRIMARY
API2 --> PRIMARY
API3 --> PRIMARY
PRIMARY --> SECONDARY1
PRIMARY --> SECONDARY2
API1 --> REDIS_M
API2 --> REDIS_M
API3 --> REDIS_M
REDIS_M --> REDIS_SCaching Strategy
Cache Layers:
- CDN Cache - Static assets (images, CSS, JS)
- Application Cache - API responses, search results
- Database Cache - Query results, aggregations
Cache TTL:
- Car listings: 5 minutes
- Dealer profiles: 15 minutes
- Make/Model data: 24 hours
- Static data: 7 days
Monitoring & Observability
Metrics Collection
mermaid
graph LR
A[Application] --> B[Metrics Collection]
B --> C[Cloudflare Analytics]
B --> D[MongoDB Atlas Monitoring]
B --> E[Custom Metrics]
C --> F[Dashboard]
D --> F
E --> F
F --> G[Alerts]
G --> H[Team Notification]Key Metrics
Performance Metrics:
- API response time (P50, P95, P99)
- Database query time
- Cache hit rate
- WebSocket latency
Business Metrics:
- Car listings created
- User registrations
- Dealer applications
- Inquiry conversions
- Search queries
System Metrics:
- CPU usage
- Memory usage
- Network I/O
- Disk usage
- Error rates
Deployment Architecture
CI/CD Pipeline
mermaid
graph LR
A[Git Push] --> B[GitHub Actions]
B --> C[Build & Test]
C --> D{Tests Pass?}
D -->|Yes| E[Build Docker Image]
D -->|No| F[Notify Developer]
E --> G[Push to Registry]
G --> H{Branch?}
H -->|main| I[Deploy to Production]
H -->|develop| J[Deploy to Staging]
I --> K[Health Check]
J --> L[Health Check]
K --> M{Healthy?}
L --> M
M -->|Yes| N[Complete]
M -->|No| O[Rollback]Environment Configuration
| Environment | Domain | Database | Features |
|---|---|---|---|
| Development | dev-api.yebocars.app | Development DB | All features enabled |
| Staging | staging-api.yebocars.app | Staging DB | Production-like |
| Production | api.yebocars.app | Production DB | Optimized & monitored |
Performance Optimization
Database Optimization
- Compound indexes for common queries
- Index hints for complex queries
- Query result caching
- Connection pooling
- Read replicas for read-heavy operations
API Optimization
- Response compression (gzip)
- Pagination for large datasets
- Field filtering (sparse fieldsets)
- Rate limiting per endpoint
- Request coalescing
Frontend Optimization
- Code splitting
- Lazy loading
- Image optimization
- Service worker caching
- CDN delivery
Disaster Recovery
Backup Strategy
MongoDB Backups:
- Continuous backup (point-in-time recovery)
- Daily snapshots retained for 30 days
- Weekly snapshots retained for 1 year
Media Backups:
- Cloudflare R2 with versioning
- Cross-region replication
- 30-day recovery window
Configuration Backups:
- Environment variables in secure vault
- Infrastructure as Code (IaC)
- Documented manual procedures
Recovery Procedures
Recovery Time Objectives (RTO):
- API: 15 minutes
- Database: 30 minutes
- Media: 1 hour
Recovery Point Objectives (RPO):
- Database: 5 minutes
- Media: 1 hour
Future Architecture Considerations
Planned Improvements
Microservices Migration
- Split monolith into services
- Separate AI service
- Dedicated media processing service
GraphQL API
- Flexible data fetching
- Reduced over-fetching
- Better mobile performance
Enhanced AI
- Image-based car search
- VIN extraction from photos
- Automated condition assessment
Multi-Region Deployment
- Deploy to African regions
- Reduce latency
- Data sovereignty compliance
Advanced Analytics
- Real-time dashboards
- Predictive analytics
- Market trend analysis