Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 55

Building a DoorDash-like Delivery Service

This lesson is built with resources from youtube.com, dev.to and 1 more site.

Hello! Welcome to our lesson on designing a food delivery service.

In our previous lesson, we designed a news feed system, focusing on Meta's approach to large-scale content delivery. We explored fan-out strategies, ML-powered ranking, and the real-time infrastructure required to serve billions.

Today, we pivot from content personalization to the complex world of real-time logistics. Our goal is to design a food delivery service, with a focus on DoorDash. This problem combines elements of the ride-sharing system we designed (geospatial logistics) with the dynamics of a three-sided marketplace connecting customers, restaurants, and drivers (or "Dashers"). We will cover order management, logistics, and real-time tracking, with a special emphasis on the sophisticated optimization required at a Staff+ level.

1. Understanding the Marketplace: Requirements and High-Level Design

A food delivery platform like DoorDash is a classic three-sided marketplace. Any design must balance the needs of these three distinct user groups:

  • Customers: Want a wide selection, fast delivery, and low prices.
  • Restaurants: Want to increase order volume, manage kitchen capacity, and maintain food quality.
  • Drivers (Dashers): Want to maximize their earnings by completing deliveries efficiently with minimal downtime.

Let's begin by scoping the problem and outlining the core functionalities.

System Design of Doordash: Geo-Hashing and WebSockets for Location Based Services

This clip from a mock interview with Gaurav Sen frames the problem by discussing core functionalities and initial capacity estimates. This is a great starting point for any system design interview.

Watch from 01:34 to 06:46. Pay attention to how the candidate clarifies the scope, focusing on the delivery and logistics aspects while setting aside payments and restaurant onboarding for now. This is a crucial interview skill.

Based on this, let's establish a clear set of requirements.

Functional Requirements:

  • Customer: Search for restaurants, view menus, place an order, make a payment, and track the delivery in real-time.
  • Restaurant: Manage their menu and hours, receive and confirm incoming orders, and notify the system when an order is ready for pickup.
  • Driver: Set their availability (online/offline), receive delivery offers, accept/reject offers, and update their status (e.g., at the restaurant, order picked up, at the customer).

Non-Functional Requirements:

  • High Availability: The service must be operational, especially during peak meal times.
  • Low Latency: Search, order placement, and tracking updates should feel instantaneous.
  • Reliability: Order and payment information must not be lost.
  • Scalability: The system must handle millions of users, restaurants, and drivers across many geographical regions.

With these requirements, we can sketch a high-level microservices architecture.

High-Level Design of a Food Delivery System
This diagram illustrates a common microservices architecture for a food delivery platform. It shows the clear separation of concerns into services like User, Restaurant, Order, and Payment, all orchestrated through an API Gateway. Note the use of a messaging queue for asynchronous operations, which will be critical.

This architecture separates the core domains. A user interacts with the User Service, views data from the Restaurant Service, and creates transactions in the Order Service. The magic, however, happens in the logistics layer, which we will now explore.


2. The Core Logistics Problem: Finding and Matching Drivers

At the heart of a food delivery system is the dispatch problem: how do you efficiently match an incoming order with the best available driver? A naive approach might be to query the location of every single online driver, but this is computationally infeasible.

The key is to rapidly narrow the search space to only those drivers in the immediate vicinity of the restaurant. This is a classic use case for geospatial indexing.

Geospatial Indexing with Geohashing

To find nearby drivers, we need a way to index their locations for fast querying. While you could use database-native geospatial indexes (e.g., PostGIS) or quadtrees, a very common and effective technique in distributed systems is geohashing.

Geohashing converts 2D geographic coordinates (latitude, longitude) into a short alphanumeric string. A key property is that the longer the shared prefix between two geohashes, the closer they are geographically. This allows us to turn a 2D proximity search into a 1D range query on strings, which is something standard databases and indexes are highly optimized for.

System Design of Doordash: Geo-Hashing and WebSockets for Location Based Services

The Gaurav Sen mock interview provides one of the clearest explanations of geohashing available. It covers the core concept, its recursive nature, and how to handle the critical 'edge case' problem.

Watch from 10:45 to 19:56. Focus on understanding: How geohashing recursively subdivides the world into a grid. Why this structure allows for efficient range queries using a standard B-tree or sorted set. The solution to the edge problem: querying the central cell plus its eight neighbors to guarantee you find all points within a given radius.

Driver Location Tracking Architecture

Now that we understand geohashing, how do we apply it? We need a system to track driver locations in near real-time.

  1. High-Frequency Updates: Drivers' apps send their (lat, lon) coordinates to a Location Update Service every few seconds. This is a high-throughput write stream.
  2. Asynchronous Processing: To handle this load without overwhelming our services, we use a message queue like Kafka as a buffer. The location service simply ingests updates and publishes them to a Kafka topic.
  3. Indexing: A consumer service reads from the Kafka topic, converts each (lat, lon) to a geohash, and updates the driver's location in a data store optimized for fast geo-queries. Redis is an excellent choice here, as its GEOADD, GEORADIUS, and GEOHASH commands provide a built-in, in-memory implementation of this logic.
  4. Stale Data: We must handle drivers who go offline without explicitly telling us (e.g., phone dies). A Time-To-Live (TTL) on each driver's location entry in Redis is crucial. If an update isn't received within a certain window (e.g., 30 seconds), the entry expires and the driver is considered offline.

When a new order needs a driver, the Dispatch Service can now query Redis: "Give me all available drivers within a 5km radius of the restaurant's geohash." This is incredibly fast and efficient.


3. Staff+ Deep Dive: The Dispatch Optimization Engine

Finding the nearest available driver is a solid Senior-level answer. However, for a Staff-level role, you must demonstrate a deeper understanding of the business objectives. Is the nearest driver truly the best driver?

  • What if the food won't be ready for 15 minutes? Sending the nearest driver now just makes them wait, which is inefficient and frustrating.
  • What if the nearest driver has a low order completion rate?
  • What if two small orders from the same restaurant could be delivered by a single driver (batching)?

This transforms the problem from a simple proximity search into a complex optimization problem. DoorDash's system for this, internally named DeepRed, provides a fantastic case study.

Using ML and Optimization to Solve DoorDash's Dispatch Problem

This official DoorDash Engineering blog post is a masterclass in Staff-level thinking. It describes how they combine Machine Learning and mathematical optimization to solve the dispatch problem far more intelligently than a simple nearest-neighbor approach.

Please read the sections 'Building DeepRed: our dispatch service' and 'An order’s journey through dispatch'. This is the core of the lesson. Focus on the two-stage process: ML Layer (Prediction): Identify the key variables they predict before making a decision (e.g., order ready time, travel times, acceptance likelihood). Optimization Layer (Decision): Understand that these predictions are inputs to a Mixed-Integer Programming (MIP) solver that makes the final recommendation, considering trade-offs between efficiency and quality. Note the key decisions it makes: which dasher, whether to batch, and whether to delay dispatch.

The key takeaway is that a state-of-the-art dispatch system doesn't just find a nearby driver. It builds a model of the world, predicts future states, and makes a globally (or locally) optimal decision.

The Dispatch Flow with Optimization:

  1. Candidate Generation: When an order is ready for dispatch, the system generates a set of potential offers (e.g., offer Order A to Driver 1; offer Order A and Order B to Driver 2 as a batch).
  2. ML Prediction: For each potential offer, ML models predict outcomes:
    • Prep Time: When will the food actually be ready?
    • Travel Time: How long will the driver take to get to the store and then to the customer?
    • Acceptance Probability: Will this specific driver likely accept this specific offer?
  3. Optimization: The predicted outcomes and their associated variances are fed into an optimization solver. The solver's objective function is to minimize costs (like driver time and customer wait time). It weighs all potential offers and makes the final decision, which might be:
    • Offer to Driver X now.
    • Offer a batch of orders to Driver Y.
    • Wait 3 minutes and re-evaluate, because a better driver will become free or the food needs more time.

This demonstrates a deep understanding of trade-offs and business impact, which is exactly what's expected at the Staff+ level.


4. End-to-End Order Management and Tracking

Let's trace an order through our sophisticated system, focusing on how services communicate. An event-driven architecture using Kafka is the perfect fit.

✅ System Design 6: Design Food Delivery Application like Zomato / Swiggy / Uber Eats | HLD | LLD

This video provides a detailed walk-through of the various services and their interactions, with a strong emphasis on using Kafka for asynchronous communication and an event-driven flow.

Watch from 43:40 to 52:53. This segment clearly explains the event-driven nature of the order service. Follow the sequence: An order placement triggers a payment, which then fires an event into a Kafka broker. Multiple consumer services react to this event: one updates the order database, another notifies the user, and a third notifies the restaurant. The restaurant's acceptance fires another event, which in turn triggers the driver dispatch process we just discussed.

The E2E Flow:

  1. A customer places an order via the Order Service.
  2. The Payment Service processes the payment. On success, the Order Service publishes an OrderPlaced event to a Kafka topic.
  3. Multiple consumers react:
    • Notification Service: Sends a confirmation to the customer.
    • Restaurant Service: Pushes the order to the restaurant's tablet.
  4. The restaurant accepts the order. The Restaurant Service publishes an OrderAcceptedByRestaurant event.
  5. The Dispatch Service (our DeepRed) consumes this event, runs its ML+optimization process, and selects the best driver offer. It publishes a DriverAssigned event.
  6. The Notification Service consumes this and notifies both the driver (with the offer) and the customer ("A driver is on the way!").
  7. The driver picks up the food and marks it in their app. This fires a FoodPickedUp event.

Real-time Tracking with WebSockets

Once the FoodPickedUp event is fired, the customer wants to see the driver moving on a map. While the driver's app is already sending location updates to Kafka for our internal logistics, this isn't suitable for pushing updates to millions of individual customers.

For this, we use WebSockets.

  • When the customer opens the tracking screen, their app establishes a persistent WebSocket connection with a WebSocket Gateway.
  • The driver's app continues sending location data. A service consumes these updates and forwards them to the WebSocket Gateway.
  • The gateway, knowing which customer is connected to which session, pushes the relevant coordinate updates to the correct customer's app in real-time.

Conclusion

Designing a food delivery service is a fantastic interview problem that touches on microservices, geospatial indexing, high-throughput data streams, and complex optimization. While a basic design can match drivers to orders, a Staff-level design showcases a deeper understanding of the business goals by incorporating an ML-driven optimization engine.

Key Takeaways:

  • Three-Sided Marketplace: The design must balance the competing needs of customers, restaurants, and drivers.
  • Geospatial Indexing: Geohashing is a powerful technique for solving the proximity search problem at scale, often implemented with in-memory stores like Redis.
  • Event-Driven Orchestration: Kafka is the ideal backbone for an asynchronous, event-driven architecture that decouples services and manages the complex lifecycle of an order.
  • Staff-Level Optimization: The core of a modern logistics platform is not just finding the nearest entity, but the optimal one. This involves a dispatch engine that uses ML to predict outcomes and optimization solvers to make decisions (e.g., batching, delayed dispatch).
  • Real-Time Client Updates: WebSockets are the standard solution for pushing low-latency, real-time updates (like a driver's location) to clients.

Preview of the Next Lesson:
We have now covered your requested company-specific designs for Google, Uber, Meta, and DoorDash. Next, we will tackle the design for Airbnb: a hotel/rental booking system. This will shift our focus to new challenges, including complex search criteria, managing inventory and availability, and preventing conflicts in a high-concurrency booking environment.