System Design: Designing a Food Delivery App
A food delivery platform (like Uber Eats, DoorDash, or Grab) is more than just an e-commerce site. It is a Three-Sided Marketplace that must coordinate between Customers, Restaurants, and Couriers (Drivers) in real-time, all while managing a complex logistical window (the food is only hot for 30 minutes).
1. Core Requirements
- Order Management: Taking orders and managing the lifecycle (Created -> Accepted -> Prepared -> Picked Up -> Delivered).
- Inventory/Menu: Restaurants updating their menus and stock in real-time.
- Courier Dispatching: Efficiently matching an order with the best courier.
- Tracking: Customers seeing the courier's location in real-time.
2. The Order State Machine
The state of an order is the source of truth for all three parties. We use a State Machine to ensure valid transitions:
PLACED->ACCEPTED_BY_RESTAURANT->PREPARING->READY_FOR_PICKUP->OUT_FOR_DELIVERY->DELIVERED.- Consistency: Use a relational database (PostgreSQL) for order state to ensure ACID compliance during transitions.
3. Courier Dispatching (The Core Challenge)
Matching an order with a courier is an optimization problem.
- The Process:
- An order is
READY_FOR_PICKUP. - The system identifies available couriers within a 3-5km radius using Geohashing (like in our Yelp/Uber articles).
- The Dispatch Service ranks couriers based on distance, vehicle type, and historical performance.
- It sends a "Gig Request" to the top-ranked courier. If they reject, it moves to the next.
- An order is
4. Real-time Location Tracking
- Ingestion: Couriers send GPS pings every 5 seconds via WebSockets or gRPC.
- Processing: Apache Kafka buffers these pings.
- Storage: Only the "Latest Location" is stored in Redis for fast access by the tracking UI. Historical paths are stored in Cassandra.
5. Handling Flash Sales and Peak Hours (Lunch/Dinner)
Traffic spikes during meal times are massive.
- Adaptive Throttling: If a restaurant is overwhelmed, the system automatically increases their "Estimated Prep Time" or hides them from the search results to prevent a bad user experience.
- Batching: To improve efficiency, the system may assign two orders from the same restaurant to a single courier if the destinations are close.
6. Menu Management and Search
- Search: Use Elasticsearch to handle fuzzy search ("Burgir" -> "Burger") and filtering by category/rating.
- Cache: Restaurant menus are cached in Redis with a short TTL, as they don't change every second but need to be retrieved millions of times.
Summary
The engineering of food delivery is a logistical dance. By treating the order as a strict state machine and using geospatial indexing for courier dispatching, you can build a system that scales to millions of orders across thousands of cities.
