Skip to content

Pranjal360Agarwal/RideSphere

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

30 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

RideSphere - Ride Sharing Microservices Platform

A scalable, distributed ride-sharing application built with microservices architecture, real-time communication, and asynchronous message queuing.


πŸ“‹ Table of Contents

  1. Overview
  2. Features
  3. Architecture
  4. Tech Stack
  5. Project Structure
  6. Installation & Setup
  7. Running the Application
  8. API Endpoints
  9. Database Schema
  10. Communication Patterns
  11. Deployment
  12. Contributing

🎯 Overview

RideSphere is a modern ride-sharing platform that implements a microservices architecture with independent services for user management, captain (driver) management, and ride coordination. The system uses an API Gateway pattern for request routing, RabbitMQ for asynchronous communication, MongoDB for data persistence, and JWT for authentication.

The architecture enables:

  • Scalability: Each microservice can be scaled independently
  • Resilience: Failure of one service doesn't cascade to others
  • Decoupling: Services communicate through message queues
  • Real-time Updates: Long polling for ride notifications
  • Security: JWT-based authentication and password hashing with bcrypt

✨ Features

User Features

  • User registration and authentication
  • Secure password storage with bcrypt hashing
  • JWT-based session management
  • Profile management
  • Ride request creation

Captain (Driver) Features

  • Captain registration and authentication
  • Availability toggle (online/offline status)
  • Real-time ride notifications via long polling
  • Accept/reject ride requests
  • JWT-based session management

Ride Management

  • Ride request creation by users
  • Ride acceptance by available captains
  • Real-time notification system via RabbitMQ
  • Ride status tracking (requested β†’ accepted β†’ started β†’ completed)
  • Persistent ride history

System Features

  • API Gateway for unified routing
  • Asynchronous Communication via RabbitMQ
  • Token Blacklisting for secure logout
  • Request Logging with Morgan
  • Error Handling across all services
  • Database Connection Pooling

πŸ—οΈ Architecture

High-Level Architecture (HLD)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Client Applications                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
                           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚             API Gateway (Port 3000)                          β”‚
β”‚  - Request Routing & Forwarding                             β”‚
β”‚  - Request/Response Logging                                 β”‚
β”‚  - Header Management                                        β”‚
β””β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
   β”‚             β”‚             β”‚
   β–Ό             β–Ό             β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ User   β”‚  β”‚Captain β”‚   β”‚  Ride  β”‚
β”‚Service β”‚  β”‚Service β”‚   β”‚Service β”‚
β”‚(3001)  β”‚  β”‚(3002)  β”‚   β”‚ (3003) β”‚
β””β”€β”€β”€β”¬β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”¬β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”¬β”€β”€β”€β”€β”˜
    β”‚          β”‚            β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
               β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  Message Queue      β”‚
    β”‚   (RabbitMQ)        β”‚
    β”‚  - new-ride queue   β”‚
    β”‚  - event publishing β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
               β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  Database           β”‚
    β”‚  (MongoDB)          β”‚
    β”‚  - users            β”‚
    β”‚  - captains         β”‚
    β”‚  - rides            β”‚
    β”‚  - blacklist_tokens β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Service Responsibilities

Service Port Responsibility
User Service 3001 User authentication, registration, profile management
Captain Service 3002 Captain authentication, availability, ride notifications
Ride Service 3003 Ride creation, acceptance, status management
API Gateway 3000 Request routing, logging, unified entry point

πŸ› οΈ Tech Stack

Backend

  • Node.js - JavaScript runtime
  • Express.js - REST API framework
  • MongoDB - NoSQL database
  • Mongoose - MongoDB ODM
  • RabbitMQ - Message broker (asynchronous communication)
  • JWT - Authentication tokens
  • bcrypt - Password hashing
  • amqplib - RabbitMQ client library
  • express-http-proxy - API Gateway routing
  • Morgan - HTTP request logger
  • dotenv - Environment variable management

Infrastructure

  • Docker (optional for containerization)
  • MongoDB Atlas or local MongoDB instance

πŸ“ Project Structure

RideSphere/
β”œβ”€β”€ gateway/                      # API Gateway Service
β”‚   β”œβ”€β”€ app.js                   # Express app setup
β”‚   β”œβ”€β”€ package.json
β”‚   └── server.js
β”‚
β”œβ”€β”€ user/                        # User Microservice
β”‚   β”œβ”€β”€ app.js
β”‚   β”œβ”€β”€ server.js
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   └── db.js               # MongoDB connection
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   └── user.model.js        # User schema
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── user.controller.js   # User logic
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── user.routes.js       # User endpoints
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   └── auth.middleware.js   # Authentication
β”‚   β”œβ”€β”€ service/
β”‚   β”‚   └── rabbit.js            # RabbitMQ client
β”‚   └── package.json
β”‚
β”œβ”€β”€ captain/                     # Captain Microservice
β”‚   β”œβ”€β”€ app.js
β”‚   β”œβ”€β”€ server.js
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   └── db.js
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ captain.model.js     # Captain schema
β”‚   β”‚   └── blacklisttoken.model.js
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── captain.controller.js
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── captain.routes.js
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   └── authMiddleWare.js
β”‚   β”œβ”€β”€ service/
β”‚   β”‚   └── rabbit.js
β”‚   └── package.json
β”‚
β”œβ”€β”€ ride/                        # Ride Microservice
β”‚   β”œβ”€β”€ app.js
β”‚   β”œβ”€β”€ server.js
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   └── db.js
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   └── ride.model.js        # Ride schema
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── ride.controller.js
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── ride.routes.js
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   └── auth.middleware.js
β”‚   β”œβ”€β”€ service/
β”‚   β”‚   └── rabbit.js
β”‚   └── package.json
β”‚
β”œβ”€β”€ backend-check/              # Load testing & health checks
β”‚   β”œβ”€β”€ app.js
β”‚   β”œβ”€β”€ gateway.service.js
β”‚   β”œβ”€β”€ stress.service.js
β”‚   └── test/
β”‚       β”œβ”€β”€ package.json
β”‚       └── test.js
β”‚
β”œβ”€β”€ .env.example               # Environment variables template
└── README.md                  # This file

πŸš€ Installation & Setup

Prerequisites

  • Node.js (v14+)
  • npm or yarn
  • MongoDB (local or Atlas)
  • RabbitMQ server running

1. Clone the Repository

git clone https://github.com/Pranjal360Agarwal/RideSphere.git
cd RideSphere

2. Environment Configuration

Create a .env file in each service directory with the following variables:

# MongoDB Connection
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/ridesphere?retryWrites=true&w=majority

# JWT Secret
JWT_SECRET=your_jwt_secret_key_here

# RabbitMQ Configuration
RABBIT_URL=amqp://guest:guest@localhost:5672

# Service Ports (optional, if overriding defaults)
PORT=3001  # for user service
PORT=3002  # for captain service
PORT=3003  # for ride service

3. Install Dependencies

# Install gateway dependencies
cd gateway && npm install && cd ..

# Install user service dependencies
cd user && npm install && cd ..

# Install captain service dependencies
cd captain && npm install && cd ..

# Install ride service dependencies
cd ride && npm install && cd ..

4. MongoDB Setup

If using MongoDB Atlas:

  1. Create a cluster at MongoDB Atlas
  2. Create a database user and whitelist your IP
  3. Update MONGO_URI in .env files

If using local MongoDB:

# Start MongoDB service
mongod

5. RabbitMQ Setup

# Using Docker (recommended)
docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management

# Or install locally: https://www.rabbitmq.com/download.html

πŸ“± Running the Application

Option 1: Manual Startup (Development)

Terminal 1 - Start User Service:

cd user && npm start

Terminal 2 - Start Captain Service:

cd captain && npm start

Terminal 3 - Start Ride Service:

cd ride && npm start

Terminal 4 - Start API Gateway:

cd gateway && npm start

Option 2: Using PM2 (Production-like)

npm install -g pm2

# Start all services
pm2 start gateway/server.js --name "gateway" --env production
pm2 start user/server.js --name "user-service" --env production
pm2 start captain/server.js --name "captain-service" --env production
pm2 start ride/server.js --name "ride-service" --env production

# Monitor
pm2 monit

# View logs
pm2 logs

Option 3: Using Docker Compose (Recommended for Production)

Create docker-compose.yml:

version: "3.8"

services:
  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_DATABASE: ridesphere

  rabbitmq:
    image: rabbitmq:3-management
    ports:
      - "5672:5672"
      - "15672:15672"

  gateway:
    build: ./gateway
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production

  user-service:
    build: ./user
    ports:
      - "3001:3001"
    environment:
      - NODE_ENV=production
    depends_on:
      - mongodb
      - rabbitmq

  captain-service:
    build: ./captain
    ports:
      - "3002:3002"
    environment:
      - NODE_ENV=production
    depends_on:
      - mongodb
      - rabbitmq

  ride-service:
    build: ./ride
    ports:
      - "3003:3003"
    environment:
      - NODE_ENV=production
    depends_on:
      - mongodb
      - rabbitmq

Run with:

docker-compose up -d

πŸ”— API Endpoints

User Service (via Gateway: /user)

Method Endpoint Description Auth
POST /register User registration ❌
POST /login User login ❌
GET /profile Get user profile βœ…
POST /logout User logout βœ…

Captain Service (via Gateway: /captain)

Method Endpoint Description Auth
POST /register Captain registration ❌
POST /login Captain login ❌
GET /profile Get captain profile βœ…
POST /logout Captain logout βœ…
PUT /toggle-availability Toggle online/offline status βœ…
GET /wait-for-ride Long polling for new rides βœ…

Ride Service (via Gateway: /ride)

Method Endpoint Description Auth
POST /create-ride Create a new ride request βœ… (User)
PUT /accept-ride Accept a ride request βœ… (Captain)

πŸ’Ύ Database Schema

Users Collection

{
  _id: ObjectId,
  name: String,
  email: String (unique),
  password: String (hashed),
  createdAt: Date,
  updatedAt: Date
}

Captains Collection

{
  _id: ObjectId,
  name: String,
  email: String (unique),
  password: String (hashed),
  isAvailable: Boolean (default: false),
  createdAt: Date,
  updatedAt: Date
}

Rides Collection

{
  _id: ObjectId,
  user: ObjectId (reference to User),
  captain: ObjectId (reference to Captain),
  pickup: String,
  destination: String,
  status: String (enum: ["requested", "accepted", "started", "completed"]),
  createdAt: Date,
  updatedAt: Date
}

Blacklisted Tokens Collection

{
  _id: ObjectId,
  token: String,
  createdAt: Date
}

πŸ“¨ Communication Patterns

1. Synchronous Communication

  • REST APIs between gateway and services
  • Request-response pattern for immediate operations

2. Asynchronous Communication (RabbitMQ)

New Ride Queue (new-ride)

  • Publisher: Ride Service (when ride is created)
  • Subscribers: Captain Service (all connected captains receive notifications)
  • Purpose: Real-time notifications for available captains

Flow:

User creates ride β†’ Ride Service β†’ Publish to "new-ride" queue
                                 β†’ All captains receive notification

Captain Availability

  • Captains subscribe to ride notifications only when isAvailable = true
  • Long polling mechanism with 30-second timeout

πŸ” Security Features

Authentication & Authorization

  • JWT Tokens: 1-hour expiration for secure sessions
  • Token Blacklisting: Logout invalidates tokens in database
  • Password Hashing: bcrypt with 10 salt rounds
  • Middleware Protection: authMiddleware validates JWT on protected routes

Data Protection

  • Environment Variables: Sensitive data in .env files
  • Cookie-based Storage: Tokens stored as HTTP-only cookies
  • MongoDB Connection: SSL/TLS with MongoDB Atlas

API Security

  • CORS: Cross-origin handling via express
  • Input Validation: Express middleware for JSON/URL-encoded data
  • Error Handling: Generic error messages to prevent information disclosure

πŸ“Š Performance Optimization

Scalability Strategies

  1. Horizontal Scaling: Deploy multiple instances of each service
  2. Load Balancing: Use Nginx or cloud load balancers
  3. Database Indexing: Ensure indexes on email, user, captain fields
  4. Connection Pooling: MongoDB connection pooling via Mongoose
  5. Caching: Implement Redis for frequently accessed data (future enhancement)

Monitoring & Logging

  • Morgan: HTTP request logging
  • PM2: Process monitoring and auto-restart
  • RabbitMQ Management UI: Queue monitoring (http://localhost:15672)

πŸ› Troubleshooting

MongoDB Connection Issues

# Check MongoDB is running
mongod --version

# For Atlas, verify connection string and IP whitelist

RabbitMQ Connection Failures

# Check RabbitMQ service
sudo systemctl status rabbitmq-server

# Or with Docker
docker logs rabbitmq

JWT Token Errors

  • Ensure JWT_SECRET is set consistently across all services
  • Check token expiration (1 hour default)
  • Verify token is being sent in Authorization header

Service Not Starting

# Clear node_modules and reinstall
rm -rf node_modules
npm install

# Check for port conflicts
lsof -i :3000  # Check if port 3000 is in use

πŸ“ Example Workflows

Workflow 1: User Registration & Login

1. User POST /user/register with email & password
2. Password hashed with bcrypt
3. User document created in MongoDB
4. JWT token generated & stored in cookie
5. User can now create rides

Workflow 2: Captain Availability & Ride Notifications

1. Captain logs in (POST /captain/login)
2. Captain toggles availability (PUT /captain/toggle-availability)
3. Captain calls GET /captain/wait-for-ride (long polling)
4. Request held for 30 seconds waiting for ride notifications
5. When user creates ride:
   - Ride Service publishes to "new-ride" queue
   - Captain Service receives message
   - All waiting captains get notified with ride data

Workflow 3: Create & Accept Ride

1. User creates ride (POST /ride/create-ride)
   - Ride stored in MongoDB with status "requested"
   - Message published to "new-ride" queue
2. Available captains receive notification
3. Captain accepts ride (PUT /ride/accept-ride)
   - Ride status updated to "accepted"
   - Captain ID assigned to ride
4. Ride in progress

πŸš€ Deployment

AWS Deployment

  1. EC2 Instances: One per service + Gateway
  2. RDS: MongoDB Atlas alternative
  3. SQS/SNS: Alternative to RabbitMQ
  4. Load Balancer: ALB for API Gateway
  5. CloudWatch: Monitoring and logging

Heroku Deployment

# Create Heroku apps
heroku create ridesphere-gateway
heroku create ridesphere-user
heroku create ridesphere-captain
heroku create ridesphere-ride

# Add MongoDB Atlas add-on
heroku addons:create mongolab:sandbox --app ridesphere-user

# Deploy
git push heroku main

GCP/Google Cloud

  1. Cloud Run: Serverless deployment
  2. Cloud SQL: Managed MongoDB alternative
  3. Pub/Sub: Alternative to RabbitMQ
  4. Cloud Load Balancing: Request routing

πŸ“š API Usage Examples

cURL Examples

User Registration:

curl -X POST http://localhost:3000/user/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123"
  }'

User Login:

curl -X POST http://localhost:3000/user/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "password123"
  }'

Create Ride:

curl -X POST http://localhost:3000/ride/create-ride \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <JWT_TOKEN>" \
  -d '{
    "pickup": "123 Main St",
    "destination": "456 Oak Ave"
  }'

Accept Ride:

curl -X PUT http://localhost:3000/ride/accept-ride \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <JWT_TOKEN>" \
  -d '{
    "rideId": "ride_object_id"
  }'

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Coding Standards

  • Use consistent indentation (2 spaces)
  • Follow Node.js naming conventions
  • Add comments for complex logic
  • Test all endpoints before submitting PR

πŸ‘¨β€πŸ’» Author

Pranjal Agarwal


πŸ“ž Support

For issues, questions, or suggestions, please:

  1. Check existing GitHub Issues
  2. Create a new issue with detailed information
  3. Include error messages, environment details, and steps to reproduce

🎯 Future Enhancements

  • Real-time location tracking with WebSockets
  • Payment integration (Stripe/Razorpay)
  • Rating and review system
  • Ride sharing/pooling
  • Admin dashboard
  • Mobile app (React Native)
  • AI-based driver matching
  • Real-time notifications (Push notifications)
  • Analytics dashboard
  • Caching layer (Redis)

Contact

If you have any questions or feedback, please feel free to contact me at pranjal360agarwal@gmail.com. You can also connect with me on LinkedIn or Twitter. Thank you for visiting my project!

Made with ❀ by Pranjal Agarwal.

About

RideSphere is a scalable, event-driven ride-sharing backend system built using microservices architecture with Node.js, Express, MongoDB, RabbitMQ, and JWT authentication. The platform demonstrates real-world system design principles, asynchronous communication, API Gateway pattern, and fault-tolerant service orchestration.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors