Bird
Raised Fist0

Design a Food Delivery System - Restaurant Discovery, Order Tracking, Driver Assignment

HLDhardInterview freq: high
Choose your preparation mode4 modes available
🏗️
Design a Food Delivery System - Restaurant Discovery, Order Tracking, Driver Assignment
Design a scalable, low-latency food delivery platform supporting 2B DAU with real-time order tracking and driver assignment
hardLocation and Mapping SystemsFreq: high
Prerequisites:System Design FundamentalsCAP TheoremDistributed DatabasesReal-time Messaging SystemsGeospatial Indexing
⚙️
Functional Requirements
  • Restaurant discovery by location, cuisine, ratings, and availability
  • Real-time order placement and status tracking for customers
  • Driver assignment based on proximity, availability, and load balancing
  • Order lifecycle management including preparation, pickup, delivery, and completion
  • Real-time notifications and ETA updates to customers and drivers
  • Support for user reviews and ratings for restaurants and drivers
📊
Non-Functional Requirements
  • Support 2 billion daily active users (DAU)
  • End-to-end latency under 100ms P99 for restaurant search queries
  • Order status updates delivered with 99.99% availability and <1s delay
  • System must handle peak write QPS of ~1 million writes/sec for orders and updates
  • Data durability with 30 days retention for order history and 1 year for analytics
❓
Clarifying Questions to Ask
  • What is the expected peak concurrent user load and write/read ratio?
  • Are drivers managed by the platform or third-party contractors?
  • What is the geographic scope - global, country, or city-level?
  • What are the SLAs for order tracking updates and driver assignment latency?
  • Is offline support or eventual consistency acceptable for any components?
  • What are the data privacy and compliance requirements for user and driver data?
Out of Scope
✗ Payment processing and fraud detection
✗ In-depth menu management and dynamic pricing
✗ Third-party logistics integration beyond driver assignment
✗ Marketing and promotional campaign management
📌
Assumptions
  • 2 billion DAU
  • Each user generates 40 messages (searches, orders, updates) per day
  • Average message size is 100 bytes
  • Peak traffic is 3x average load during lunch/dinner hours
⚡
QPS Calculation
write qps2B × 40 / 86400 ≈ 925,926 writes/sec
peak write qps925,926 × 3 ≈ 2,777,778 writes/sec
read qpsAssuming 5 reads per write, read_qps = 925,926 × 40 × 5 / 86400 ≈ 4,629,630 reads/sec
💾
Storage Estimate
daily storage2B × 40 × 100 bytes = 8 TB/day
retention days30
total storage8 TB × 30 = 240 TB
with replication240 TB × 3 (replication factor) = 720 TB
🖥️
Server Estimate
api serversAssuming each server handles 5,000 QPS, need 2,778,000 / 5,000 ≈ 556 API servers
database nodesUsing Cassandra with 100K writes/sec per node, need 2,778,000 / 100,000 ≈ 28 nodes
🏗️
Architecture Diagram
Architecture Diagram
        +-------------+
        |  Mobile App |
        +------+------+
               | REST API (HTTPS)
        +------+------+
        |  API Gateway|
        +------+------+
               |
   +-----------+-----------+
   |                       |
 +------+             +---------+
 |Search|             |Order Svc|
 +------+             +---------+
   |                       |
   |                       |
 +------+             +---------+
 |GeoDB |             |Cassandra|
 +------+             +---------+
   |                       |
   |                       |
 +------+             +---------+
 |Kafka |<------------|Driver Svc|
 +------+             +---------+
   |                       |
   |                       |
 +------+             +---------+
 |Notif |             |Redis    |
 +------+             +---------+
🧩
Components
API Gateway
Entry point for all client requests, handles authentication, rate limiting, and routing
Why thisEnvoy proxy supports high throughput, TLS termination, and dynamic routing with low latency
Why notNginx lacks native service discovery and dynamic routing needed for microservices at 2B DAU
Search Service
Handles restaurant discovery queries using geospatial and attribute filters
Why thisElasticsearch supports geo-distance queries and full-text search with sub-100ms P99 latency
Why notRelational DBs like PostgreSQL with PostGIS cannot sustain 4.6M QPS with low latency
Order Service
Manages order lifecycle, writes order data, and publishes events for downstream processing
Why thisCassandra provides linear write scalability and high availability for 2.7M writes/sec with tunable consistency
Why notMongoDB's single primary write bottleneck and replica lag fail at this write scale
Driver Service
Assigns drivers to orders based on proximity, availability, and load balancing
Why thisKafka enables asynchronous event-driven driver assignment with partitioning by city and driver ID for scalability
Why notRabbitMQ lacks partitioning and throughput needed for millions of concurrent driver assignments
Notification Service
Sends real-time order status and ETA updates to customers and drivers
Why thisRedis Pub/Sub with Redis Streams supports sub-second delivery and message persistence for notifications
Why notFirebase Cloud Messaging is external and cannot guarantee 99.99% availability at this scale
GeoDB
Stores geospatial data of restaurants and drivers for fast proximity queries
Why thisCassandra with GeoMesa plugin supports distributed geospatial indexing and queries at scale
Why notElasticsearch alone cannot handle high write QPS for geospatial updates from drivers
🔄
Data Flow
1
Mobile App → API Gateway
User sends restaurant search or order placement request
API Gateway authenticates and routes request to appropriate service
2
API Gateway → Search Service
Search queries forwarded with location and filters
Search Service queries Elasticsearch for matching restaurants
3
API Gateway → Order Service
Order placement request stored in Cassandra
Order Service writes order and publishes event to Kafka
4
Kafka → Driver Service
Driver Service consumes order events and assigns drivers
Assignment based on driver location from GeoDB and availability
5
Driver Service → Notification Service
Send real-time order and ETA updates
Notification Service pushes updates via Redis Pub/Sub to clients
6
Driver Service → GeoDB
Update driver location and status
GeoDB maintains fresh geospatial data for proximity queries
7
Mobile App → Notification Service
Receive real-time order status and driver ETA
Clients get sub-second updates for tracking

Practice

(1/5)
1. A critical database cluster must failover automatically without data loss or downtime during a primary node crash. Which component is responsible for orchestrating this failover in a distributed SQL database system?
easy
A. Consensus protocol (e.g., Raft) managing leader election and log replication
B. Load balancer redirecting traffic based on health checks
C. Client-side retry logic to reconnect to a new primary node
D. Backup scheduler triggering periodic snapshots for recovery

Solution

  1. Step 1: Identify failover orchestration component

    The consensus protocol like Raft manages leader election and ensures log replication consistency, enabling automatic failover without data loss.
  2. Step 2: Eliminate other options

    Client-side retries (A) handle reconnection but don't orchestrate failover; load balancers (B) redirect traffic but don't manage state; backups (D) aid recovery but not live failover.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Consensus protocol controls leader election and failover [check]
Hint: Consensus protocols manage failover, not clients or load balancers
Common Mistakes:
2. If the PageRank computation component fails during an update cycle, what is the immediate impact on search result ranking and user experience?
medium
A. Search results become completely unavailable until PageRank recovers
B. Search results degrade to random ordering because PageRank scores are missing
C. The indexing pipeline halts, blocking new documents from being indexed
D. Search results continue serving the last successful PageRank snapshot without updates

Solution

  1. Step 1: Understand PageRank failure impact

    Without updated PageRank, the system cannot assign fresh relevance scores, causing degraded or random ordering.
  2. Step 2: Evaluate other impacts

    Search remains available (not A). Last snapshot is not used if update fails mid-cycle (not B). Indexing continues independently (not D).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    PageRank failure causes degraded ranking, not outage [check]
Hint: PageRank failure -> degraded ranking, not outage [check]
Common Mistakes:
3. For a distributed cache with frequent node additions and removals, which approach best balances load and minimizes key remapping?
medium
A. Use rendezvous hashing to assign keys to nodes
B. Use a modulo hash on node count with manual rebalancing
C. Use consistent hashing with virtual nodes to smooth load distribution
D. Use a centralized directory to track key-node mappings

Solution

  1. Step 1: Compare consistent hashing and rendezvous hashing

    Both minimize remapping, but consistent hashing with virtual nodes better smooths load across nodes, especially with frequent changes.
  2. Step 2: Evaluate centralized directory and modulo hashing

    Centralized directory adds latency and single point of failure; modulo hashing causes massive remapping and manual rebalancing overhead.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Virtual nodes in consistent hashing smooth load and minimize remapping [check]
Hint: Virtual nodes smooth load in consistent hashing [check]
Common Mistakes:
4. A team must decide between using a detailed blame-focused report or a blameless timeline with action items for their post-mortem. Which approach is best for fostering continuous improvement in a high-trust engineering culture?
medium
A. Use blameless timelines with actionable steps to encourage learning and improvement
B. Use blame-focused reports to enforce accountability and prevent future errors
C. Use only automated logs without human analysis to avoid bias
D. Skip post-mortems entirely to save time and avoid conflict

Solution

  1. Step 1: Evaluate cultural impact of blame vs blameless approaches

    Blame-focused reports create fear and reduce openness, harming continuous improvement.
  2. Step 2: Assess effectiveness of blameless timelines with action items

    They foster trust, encourage learning, and drive actionable improvements aligned with high-trust culture.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Blameless + action items -> continuous improvement [check]
Hint: Blameless + action items build trust and improve systems [check]
Common Mistakes:
5. You need to design a distributed configuration system that supports dynamic updates with strong consistency guarantees. Which approach is best suited for this scenario?
medium
A. Use Zookeeper to store configuration with watches for immediate update notifications
B. Use a distributed cache with eventual consistency and periodic refresh
C. Use a relational database with polling clients for configuration changes
D. Use a message queue to broadcast configuration changes asynchronously

Solution

  1. Step 1: Identify consistency and update requirements

    Strong consistency and immediate update notification are required.
  2. Step 2: Evaluate options

    Distributed cache with eventual consistency delays updates; relational DB polling adds latency; message queue is asynchronous without state storage.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Zookeeper watches -> immediate, consistent config updates [check]
Hint: Watches + strong consistency -> Zookeeper for config updates [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard