Skip to content

A thread-safe, production-ready P2P parcel delivery system similar to Dunzo, built with Java. Features include FIFO order management, auto driver assignment, rating system, notification services, and comprehensive thread safety mechanisms.

Notifications You must be signed in to change notification settings

Kakashi54321/P2P-Delivery-System

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Peer-to-Peer Parcel Delivery System

A thread-safe, production-ready P2P delivery system similar to Dunzo, built for Flipkart's SDE-3 Machine Coding Round.

Table of Contents

Features

Core Features (P0)

  1. Onboarding: Add customers and drivers to the system
  2. Preconfigured Items: Fixed catalog of deliverable items
  3. Order Management: Create and cancel orders
  4. Driver Assignment: Auto-assign orders to available drivers using FIFO queue
  5. Order Lifecycle: Drivers can pickup and deliver orders
  6. Status Tracking: View order, driver, and system status
  7. Cancellation Rules: Orders cannot be cancelled after pickup
  8. Multiple Orders: Customers can place multiple orders simultaneously
  9. Thread Safety: Complete concurrency handling

Bonus Features

  1. Notification System: Email and SMS notifications (mock vendors)
  2. Rating System: Customers can rate drivers after delivery
  3. Driver Dashboard: Top drivers by deliveries, ratings, and combined score
  4. Auto-Cancel: Orders auto-cancel if not picked up within configurable timeout

Design Patterns

1. Facade Pattern

Class: DeliverySystem

Reasoning: Provides a simplified, unified interface to the complex subsystems (assignment, notification, rating, dashboard). This makes the system easy to use and hides internal complexity from clients.

Benefits:

  • Single entry point for all operations
  • Loose coupling between client code and subsystems
  • Easier to test and maintain

2. Strategy Pattern

Classes: DashboardService, RankingStrategy and implementations

Reasoning: Allows different ranking algorithms (by deliveries, ratings, combined score) to be selected at runtime without changing the dashboard service code.

Benefits:

  • Easy to add new ranking strategies
  • Follows Open/Closed Principle
  • Runtime flexibility

3. Composite Pattern

Class: CompositeNotificationService

Reasoning: Allows sending notifications through multiple channels (Email, SMS) simultaneously. Treats individual notification services and composite uniformly.

Benefits:

  • Easy to add new notification channels
  • Uniform interface for single and multiple notifications
  • Flexible notification routing

4. Producer-Consumer Pattern

Class: OrderAssignmentService with BlockingQueue

Reasoning: Pending orders (producers) are queued and consumed by available drivers. This decouples order creation from assignment and handles the scenario where demand exceeds driver availability.

Benefits:

  • Thread-safe order queuing
  • Natural FIFO ordering
  • Efficient resource utilization

5. Singleton-like Service Layer

Services: OrderAssignmentService, RatingService, DashboardService

Reasoning: Each service is instantiated once in DeliverySystem and manages its domain, ensuring centralized state management.

Benefits:

  • Single source of truth
  • Centralized business logic
  • Easier testing with dependency injection

Thread Safety

Concurrency Mechanisms Used

  1. ConcurrentHashMap: For all data stores (customers, drivers, items, orders)

    • Thread-safe without external synchronization
    • Better performance than synchronized HashMap
  2. AtomicReference: For mutable fields in Order and Driver

    • Lock-free atomic operations
    • Ensures visibility across threads
  3. ReentrantLock: In OrderAssignmentService

    • Ensures atomic assignment operations
    • Prevents race conditions during driver-order assignment
  4. ReentrantReadWriteLock: For driver list operations

    • Multiple readers can access simultaneously
    • Exclusive write access
    • Better performance for read-heavy operations
  5. Synchronized Methods: In Driver and Order classes

    • Ensures atomic state transitions
    • Prevents concurrent modification issues
  6. BlockingQueue: For pending orders

    • Thread-safe producer-consumer pattern
    • Built-in synchronization

Critical Sections Protected

  1. Order Assignment: Lock prevents race condition where multiple drivers try to take same order
  2. Driver Status Change: Synchronized to prevent inconsistent state
  3. Order State Transitions: Synchronized to ensure valid state machine progression
  4. Rating Calculation: Synchronized to prevent race conditions in average calculation

Architecture

com.flipkart.delivery
├── model/
│   ├── Customer.java (Immutable)
│   ├── Driver.java (Thread-safe)
│   ├── Item.java (Immutable)
│   ├── Order.java (Thread-safe)
│   ├── OrderStatus.java
│   └── DriverStatus.java
├── service/
│   ├── OrderAssignmentService.java (FIFO queue + thread safety)
│   ├── RatingService.java (Thread-safe rating management)
│   ├── DashboardService.java (Strategy pattern for ranking)
│   ├── OrderTimeoutService.java (Scheduled auto-cancellation)
│   └── notification/
│       ├── NotificationService.java (Interface)
│       ├── EmailNotificationService.java
│       ├── SmsNotificationService.java
│       └── CompositeNotificationService.java
├── exception/
│   ├── DeliveryException.java
│   ├── InvalidOperationException.java
│   └── ResourceNotFoundException.java
├── DeliverySystem.java (Facade)
└── Main.java (Demo/Driver)

Setup and Running

Prerequisites

  • Java 11 or higher
  • Maven 3.6+

Build the Project

mvn clean compile

Run Tests

mvn test

Run the Demo

mvn exec:java -Dexec.mainClass="com.flipkart.delivery.Main"

Or compile and run:

mvn clean package
java -cp target/p2p-delivery-system-1.0-SNAPSHOT.jar com.flipkart.delivery.Main

Testing

Unit Tests Coverage

  • OrderTest: Order lifecycle and state transitions
  • DriverTest: Driver state management and rating
  • DeliverySystemTest: Integration tests for all operations
  • OrderAssignmentServiceTest: Assignment logic and queue management
  • RatingServiceTest: Rating validation and duplicate prevention
  • DashboardServiceTest: Ranking strategies

Test Scenarios Covered

  1. ✅ Basic CRUD operations
  2. ✅ Auto-assignment with FIFO
  3. ✅ Order cancellation rules
  4. ✅ Driver availability management
  5. ✅ Concurrent order creation
  6. ✅ Rating system with validation
  7. ✅ Dashboard ranking strategies
  8. ✅ Edge cases and error handling

Running Specific Tests

# Run all tests
mvn test

# Run specific test class
mvn test -Dtest=DeliverySystemTest

# Run with coverage (if jacoco configured)
mvn clean test jacoco:report

Assumptions

Business Logic Assumptions

  1. Driver Availability: Drivers are available 24x7 and don't go offline
  2. Travel Time: Ignored as per requirements
  3. Item Catalog: Fixed list of 7 predefined items; new items cannot be added at runtime
  4. Same Item Orders: Multiple customers can order the same item simultaneously
  5. Order Priority: FIFO (First-In-First-Out) for pending orders
  6. Auto-Assignment: Orders are immediately assigned if drivers available, otherwise queued
  7. Timeout: Default 30 minutes (configurable), but 5 seconds used in demo for visibility

Technical Assumptions

  1. In-Memory Storage: All data stored in memory using concurrent data structures

    • Reasoning: Fast access, simple implementation, suitable for machine coding round
    • Trade-off: Data lost on restart, but avoids database complexity
  2. No Authentication: System assumes valid user IDs are provided

    • Reasoning: Focus on core business logic rather than auth complexity
  3. Notification Delivery: Mock services that only log (don't actually send)

    • Reasoning: Demonstrates design without external dependencies
  4. Single System Instance: No distributed systems or replication

    • Reasoning: Appropriate scope for machine coding round
  5. Order ID Generation: Uses UUID for uniqueness

    • Reasoning: Simple, thread-safe, no need for distributed ID generation
  6. Error Handling: Runtime exceptions for invalid operations

    • Reasoning: Fail-fast approach, clear error messages
  7. Synchronous Operations: All operations are synchronous

    • Reasoning: Simpler to reason about, easier testing

Simplifications

  1. No Payment System: Orders don't involve actual payment
  2. No Location/GPS: No real-world coordinates or routing
  3. No Order Modifications: Orders cannot be modified after creation
  4. No Partial Cancellations: Cancel entire order only
  5. No Driver Rejection: Drivers cannot reject assigned orders
  6. No Order History Archive: All orders remain in memory

API Usage Examples

Onboard Entities

DeliverySystem system = new DeliverySystem();

// Onboard customers
Customer customer = system.onboardCustomer("C001", "Alice Johnson");

// Onboard drivers  
Driver driver = system.onboardDriver("D001", "Bob Driver");

Order Operations

// Create order (auto-assigns to available driver or queues)
Order order = system.createOrder("C001", "ITEM001");

// Cancel order (only before pickup)
system.cancelOrder(order.getId());

// Driver pickup
system.pickupOrder("D001", order.getId());

// Complete delivery
system.completeOrder("D001", order.getId());

Status Checks

// Order status
String orderStatus = system.getOrderStatus(order.getId());

// Driver status
String driverStatus = system.getDriverStatus("D001");

// System overview
String systemStatus = system.getSystemStatus();

Bonus Features

// Rate driver after delivery
system.rateDriver(order.getId(), 4.5);

// Show driver dashboard
system.showDriverDashboard(5); // Top 5 drivers

// Get available items
List<Item> items = system.getAvailableItems();

Key Implementation Highlights

1. FIFO Order Assignment

Orders are added to a LinkedBlockingQueue when no driver is available. When a driver becomes free (after completing an order), the system automatically assigns the oldest pending order.

2. Thread-Safe State Transitions

All critical state changes (order status, driver status) use synchronized methods or atomic operations to ensure consistency in concurrent scenarios.

3. Auto-Cancellation

Uses ScheduledExecutorService to schedule cancellation tasks when orders are created. Tasks are cancelled if order is picked up before timeout.

4. Notification System

Composite pattern allows notifications to be sent via multiple channels. Easy to add new channels (Push, WhatsApp, etc.) by implementing NotificationService interface.

5. Flexible Ranking

Strategy pattern allows dynamic switching between ranking algorithms for driver dashboard without code modification.

Performance Considerations

  1. ConcurrentHashMap: O(1) average case for lookups
  2. BlockingQueue: O(1) for enqueue/dequeue operations
  3. Lock Contention: Minimized by using read-write locks where appropriate
  4. Memory: All data in-memory for fast access
  5. Scalability: Can handle thousands of concurrent orders with proper tuning

Potential Enhancements (Future)

  1. Persistent Storage: Add database layer with repositories
  2. Distributed System: Use message queues (Kafka) for order assignment
  3. Location-Based Assignment: Assign nearest driver instead of FIFO
  4. Priority Orders: Add order priority/express delivery
  5. Driver Zones: Assign drivers based on geographic zones
  6. Analytics Dashboard: Real-time metrics and reporting
  7. Admin Console: Manage system configuration and monitoring

Author: Flipkart SDE-3 Candidate
Date: October 2025
Time Complexity: Core operations are O(1) or O(log n)
Space Complexity: O(n) where n is total entities (orders + drivers + customers)

About

A thread-safe, production-ready P2P parcel delivery system similar to Dunzo, built with Java. Features include FIFO order management, auto driver assignment, rating system, notification services, and comprehensive thread safety mechanisms.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages