System Architecture Overview¶
Complete technical documentation of MessWala's system design and architecture.
๐๏ธ System Architecture¶
MessWala is a three-tier architecture:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FRONTEND (React + Vite) โ
โ Deployed on Vercel (Static) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ API GATEWAY (CORS) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ BACKEND (Node.js + Express) โ
โ Deployed on Render (Server) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ DATABASE (MongoDB Atlas) โ
โ Cloud-hosted MongoDB Cluster โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฏ Component Overview¶
Frontend Layer¶
Technology: React 18 + Vite + Tailwind CSS
Responsibilities: - User interface rendering - Form handling and validation - State management (React Context) - Client-side authentication (JWT storage) - API communication
Key Components:
src/
โโ pages/ # Route pages
โโ components/ # Reusable UI components
โโ services/ # API integration
โโ context/ # Global state (Auth, Config)
โโ App.jsx # Root component
Build Optimization: - Code splitting by route - Lazy-loaded components - Vendor chunk separation - CSS-in-JS with Tailwind mini - Gzipped size: ~12KB entry point
Backend Layer¶
Technology: Node.js + Express.js
Responsibilities: - Request routing and handling - Business logic processing - Database operations - Authentication/Authorization - API response formatting
Structure:
backend/
โโ src/
โ โโ controllers/ # Request handlers
โ โโ models/ # Database schemas
โ โโ routes/ # Route definitions
โ โโ middleware/ # Auth, validation
โ โโ utils/ # Helper functions
โโ server.js # Entry point
Database Layer¶
Technology: MongoDB Atlas
Responsibilities: - Data persistence - Document storage - Indexing for performance - Backup and recovery
Collections:
messwaladb/
โโ users # User accounts
โโ expenses # Expense records
โโ meals # Menu items
โโ attendance # Attendance records
โโ feedback # Meal feedback
โโ messconfig # Mess configuration
๐๏ธ Database Schema¶
Users Collection¶
{
_id: ObjectId,
email: String (unique),
password: String (hashed),
fullName: String,
collegeId: String,
room: String,
phone: String,
role: String // "admin", "manager", "student"
status: String // "approved", "pending", "rejected"
googleId: String, // If Google OAuth
createdAt: Date,
updatedAt: Date
}
Expenses Collection¶
{
_id: ObjectId,
category: String,
amount: Number,
description: String,
date: Date,
recordedBy: ObjectId (ref: Users),
createdAt: Date,
updatedAt: Date
}
Meals Collection¶
{
_id: ObjectId,
date: Date,
mealType: String // "Breakfast", "Lunch", "Dinner"
dishes: [String],
notes: String,
createdBy: ObjectId (ref: Users),
createdAt: Date,
updatedAt: Date
}
Attendance Collection¶
{
_id: ObjectId,
userId: ObjectId (ref: Users),
date: Date,
mealType: String,
status: String // "present", "absent"
markedAt: Date,
createdAt: Date
}
Feedback Collection¶
{
_id: ObjectId,
userId: ObjectId (ref: Users),
date: Date,
mealType: String,
rating: Number (1-5),
comment: String,
createdAt: Date,
updatedAt: Date
}
MessConfig Collection โญ NEW¶
{
_id: ObjectId,
messName: String,
description: String,
email: String,
phone: String,
expenseCategories: [String],
mealTimes: [
{
name: String,
startTime: String, // "HH:MM"
endTime: String // "HH:MM"
}
],
createdBy: ObjectId (ref: Users),
createdAt: Date,
updatedAt: Date
}
๐ Data Flow¶
Login Flow¶
User Input (Email/Password)
โ
POST /auth/login
โ
Validate email exists
โ
Compare passwords (bcrypt)
โ
Generate JWT token
โ
Return token + user info
โ
Frontend stores in localStorage
โ
Use token in Authorization header
Expense Recording Flow¶
Manager Input (Expense form)
โ
POST /expenses with JWT token
โ
Verify user is Manager/Treasurer
โ
Validate expense data
โ
Insert into Expenses collection
โ
Return created expense
โ
Frontend updates list
โ
Student sees in Analytics โ Fair share recalculated
Attendance Marking Flow¶
Student marks attendance
โ
POST /attendance with JWT
โ
Verify user authenticated
โ
Check/insert into Attendance
โ
Calculate participation rate
โ
Trigger fair share recalculation
โ
Update Analytics cache (optional)
๐ Key Features¶
Configuration System (NEW in v2.0)¶
All system configuration stored in MessConfig:
// Frontend loads this on app start
const config = await fetch('/api/auth/admin/config');
// {
// messName: "Krishna Bhawan",
// expenseCategories: ["Vegetables", "Rice", ...],
// mealTimes: [...]
// }
// Used throughout frontend
<select>
{config.expenseCategories.map(cat => (
<option key={cat}>{cat}</option>
))}
</select>
Benefits: - No hardcoded values - Admin can update without redeployment - Scales to multiple messes (future) - Zero data on fresh deploy
Authentication & Authorization¶
JWT Verification Middleware:
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};
Role-Based Access Control:
const requireRole = (role) => {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
};
// Usage
router.post('/expenses', requireRole('manager'), createExpense);
Fair Share Calculation¶
Algorithm:
1. Get all expenses for the month
2. Get all active members (attended โฅ1 meal)
3. For each member:
- Count meals attended (all types combined)
- Share = (Total รท Active members) ร (Member meals รท Total meals)
4. Display per member
Analytics Aggregation¶
Real-time calculation:
// On analytics page request:
1. Fetch all expenses for period
2. Fetch all attendance for period
3. Fetch all feedback for period
4. Aggregate:
- Sum by category
- Average ratings
- Attendance percentages
5. Return summarized data
๐ Security Architecture¶
Authentication Layer¶
- โ JWT tokens (7-day expiry)
- โ Password hashing (bcrypt, 10 rounds)
- โ Google OAuth integration
- โ HTTP-only secure cookies
API Security¶
- โ CORS whitelist (only allowed origins)
- โ Rate limiting (MongoDB-backed)
- โ Input validation (all endpoints)
- โ Helmet.js (CSP, HSTS, etc.)
Data Security¶
- โ MongoDB encryption at rest
- โ HTTPS in transit
- โ No sensitive data in logs
- โ Environment variables (no hardcoded secrets)
Authorization¶
- โ Role-based access control (RBAC)
- โ Resource-level checks (user can only edit own data)
- โ Admin-only endpoints protected
- โ Activity logging (optional)
๐ Database Relationships¶
Users
โโ has many Expenses (recordedBy)
โโ has many Meals (createdBy)
โโ has many Attendance records
โโ has many Feedback
โโ has one MessConfig (createdBy - admin only)
Expenses
โโ belongs to User (recordedBy)
Meals
โโ belongs to User (createdBy)
โโ has many Attendance records (implicit)
Attendance
โโ belongs to User
โโ references Meals (implicit via date/mealType)
Feedback
โโ belongs to User
โโ references Meals (implicit via date/mealType)
MessConfig
โโ belongs to Admin User (createdBy)
๐ Deployment Architecture¶
Frontend (Vercel)¶
GitHub Repository
โ
Push to branch
โ
Vercel detects change
โ
Build: npm run build
โ
Deploy to CDN
โ
https://mess-walah.vercel.app (live)
Environment: - VITE_API_URL โ Backend URL - VITE_GOOGLE_CLIENT_ID โ Google OAuth config
Backend (Render)¶
GitHub Repository
โ
Push to branch
โ
Render detects change
โ
Build: npm install
โ
Start: node server.js
โ
https://messwala-6jvj.onrender.com (live)
Environment: - MONGO_URI โ Database connection - JWT_SECRET โ Token signing key - NODE_ENV โ Environment (production) - Other configs...
Database (MongoDB Atlas)¶
MongoDB Atlas Cluster
โ
Network whitelist: 0.0.0.0/0
โ
Database user with R/W access
โ
Connection string: mongodb+srv://...
โ
Hourly backups (Atlas)
๐ Scaling Considerations¶
Horizontal Scaling¶
Future improvements: - Microservices for analytics - Message queue for async tasks - Cache layer (Redis) for frequent queries - Load balancer for multiple backend instances
Vertical Scaling¶
Current capacity: - Render free tier: ~5000 requests/hour - MongoDB free tier: 512MB storage - Suitable for: Single mess (10-100 members)
Upgrade path: - Paid Render plan: 100,000+ requests/hour - MongoDB paid: Unlimited storage - Suitable for: Multi-mess platform (1000+ members)
๐ ๏ธ Development Workflow¶
Local Setup¶
# Backend
cd backend
npm install
npm run dev # Starts on port 5000
# Frontend
cd frontend
npm install
npm run dev # Starts on port 5173
# Database
# Use MongoDB Atlas (cloud) or local MongoDB
MONGO_URI=mongodb://localhost:27017/messwala
Code Deployment¶
Feature development on local
โ
Push to feature branch
โ
Create Pull Request
โ
Review & test
โ
Merge to main
โ
CI/CD deploys automatically
๐ Performance Metrics¶
Frontend¶
- First Load: <2 seconds
- Entry Point: 12 KB (gzipped)
- Interactive: <3 seconds (LCP)
Backend¶
- API Response: <100ms (average)
- Database Query: <50ms (average)
- p95 Response: <500ms
Database¶
- Query Performance: Indexed collections
- Backup: Daily snapshots
- Uptime: 99.5% SLA (MongoDB Atlas)
๐ Monitoring & Observability¶
Current: - Browser console logs - Server-side logging to stdout - Health endpoint: /api/health
Recommended future: - Sentry for error tracking - DataDog for metrics - ELK stack for log aggregation - NewRelic for APM
Last Updated: March 17, 2026
Version: 2.0