Skip to content

Repository files navigation

High-Throughput Driver Allocation Engine

A production-grade, low-latency driver matching engine built with NestJS, raw PostgreSQL, and Redis. The system leverages Redis Geospatial indices for area searches and an atomic Lua script to handle high-concurrency race conditions gracefully, preventing double-booking errors.

Excalidraw Diagram Link: https://excalidraw.com/#json=CSY5382Epag3ZHO-O5hjJ,rHBc-L0yvDEy6sdX_ImNmg


🔒 Upfront Security Note (Production vs. Take-Home Design)

⚠️ Architectural Shortcut: In a real-world production environment, passing the driverId explicitly inside the request body of the acceptance payload is an ID-spoofing security risk. In a production-hardened system, an authentication guard (AuthGuard) intercepts the request, verifies the bearer JWT, and securely infers the driver's identity on the backend using the validated session claims (req.user.id).

For the scope of this standalone take-home assignment, the driverId is passed directly in the payload to allow for frictionless, out-of-the-box testing via curl and the automated concurrency validation scripts.


🚀 Quick Start & Setup Instructions

Prerequisites

Make sure you have Docker Desktop installed and running on your system.

1. Environment Configuration

Create a .env file in the root directory of the project and paste the following configuration:

PORT=3000

# PostgreSQL Credentials
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=password
DB_NAME=driver_allocation

# Redis Credentials
REDIS_HOST=localhost
REDIS_PORT=6379

2. Boot the Infrastructure (Docker)

Before running the application, make sure any local native instances of Redis or Postgres are turned off so Docker can claim the standard ports. Then run:

# Spin up PostgreSQL 18 and Redis 8 containers in the background
docker compose down -v
docker compose up -d

Verify that both containers are active and healthy:

docker ps

3. Driver Setup & Geospatial Initialization

Before requesting a ride, you must populate the Redis Geospatial plane with active, available driver coordinates. Without seeding this telemetry data, the engine's background matching loop will query an empty set and naturally time out.

Run the following commands in your terminal to register an available driver nearby:

# Seed the driver's coordinates near the rider's test coordinates
docker exec -it driver_allocation_cache redis-cli GEOADD drivers:locations 77.594562 12.971598 "driver_metro_01"

# Initialize the driver's state plane to AVAILABLE
docker exec -it driver_allocation_cache redis-cli SET driver:status:driver_metro_01 "AVAILABLE"

4. Run the NestJS Server

Install dependencies and kickstart the development environment:

# Clean previous builds
rm -rf dist

# Install Node modules
npm install

# Run the live development server
npm run start:dev

On boot, the application will automatically connect to the Docker containers and inject the raw SQL database schemas cleanly.


🕹️ Key Endpoint API Specification & cURL Examples

You can test the core allocation and state lifecycle endpoints using the curl blocks below in a separate terminal panel.

1. Request a Ride

Kicks off the asynchronous, expanding background batch search loop over a geospatial area (5km → 10km → 15km).

curl -X POST http://localhost:3000/api/v1/rides/request \
  -H "Content-Type: application/json" \
  -d '{
    "riderId": "rider_shreyak_99",
    "pickupLat": 12.971598,
    "pickupLng": 77.594562
  }'

Expected Response (201 Created):

{
  "rideId": "YOUR_GENERATED_RIDE_UUID",
  "status": "SEARCHING",
  "message": "Ride request accepted. System is actively searching for nearby drivers."
}

2. Accept a Match (The High-Concurrency Target)

Simulates a driver claiming the active matching offer. The underlying engine executes an atomic Redis Lua evaluation to instantly block parallel execution attempts from competing drivers.

Replace :rideId in the URL with the UUID returned from the step above.

curl -X POST http://localhost:3000/api/v1/rides/:rideId/accept \
  -H "Content-Type: application/json" \
  -d '{
    "driverId": "driver_metro_01"
  }'

Expected Success Response (201 Created):

{
  "success": true,
  "status": "ASSIGNED",
  "assignedDriverId": "driver_metro_01",
  "message": "Congratulations! You successfully secured the match."
}

3. Complete a Trip (Release Driver)

Terminates the trip tracking loop and flags the driver's status as available inside Redis so they can accept new allocations.

curl -X POST http://localhost:3000/api/v1/rides/:rideId/complete

Expected Response (201 Created):

{
  "success": true,
  "message": "Ride successfully completed. Driver driver_metro_01 is now available for new bookings."
}

🧪 Validating Concurrency (Race Conditions)

To view the engine under load, run your automated validation script:

node test-concurrency.js

The console will display exactly 1 Driver success (201) and 4 Driver deflections (400 Bad Request), validating that the concurrency gate works flawlessly.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages