Design a Fresh Grocery Delivery System
0%
Editorial Solution
System requirements
Functional
Capacity estimation
Traffic
API design
Product Catalog
Database design
Core Schema
High-level design
Request flows
Product Browse and Search Flow
Detailed component design
Atomic Inventory Reservation
Tradeoffs
Monolith vs. Microservices
Failure scenarios
Payment Gateway Failure
Future improvements
Real-Time Delivery Tracking
Table of Contents
System requirements
Functional
Capacity estimation
Traffic
API design
Product Catalog
Database design
Core Schema
High-level design
Request flows
Product Browse and Search Flow
Detailed component design
Atomic Inventory Reservation
Tradeoffs
Monolith vs. Microservices
Failure scenarios
Payment Gateway Failure
Future improvements
Real-Time Delivery Tracking
A fresh grocery delivery system connects consumers with local stores and farmers to order and receive groceries at home. The twist compared to generic e-commerce is perishability: products expire, inventory changes by the hour, and delivery windows matter because nobody wants milk sitting on a porch in July. These constraints shape every architectural decision that follows.
Functional
Product catalog with real-time availability: Customers browse, search, and filter grocery items by category, name, and price. Each product shows current stock status. Unlike a bookstore where inventory changes slowly, a grocery catalog must reflect stock that shifts throughout the day as items sell out or new shipments arrive.
The numbers for a grocery delivery system are driven by one insight: browsing traffic dwarfs ordering traffic by 50:1 or more, but the ordering path is where consistency and atomicity matter. Designing for browsing volume on the read path and ordering correctness on the write path shapes the architecture.
Traffic
10,000 daily active users as a starting point for a regional grocery platform. Each user browses an average of 20 product pages per session, searches 5 times, and places 0.5 orders per day (ordering every other day on average).
The API surface covers four domains: products, cart, orders, and payments. Each endpoint is designed around a specific user action with clear request/response contracts.
Product Catalog
1GET /v1/products?category=produce&search=avocado&page=1&limit=20
2Response: 200 OK {
3products: [{ id, name, price, category, stock_status, image_url }],
4total: number,
5page: number
6}
7
8GET /v1/products/:product_id
9Response: 200 OK {
10id, name, price, description, category,
11stock_status: "in_stock" | "low_stock" | "out_of_stock",
12images: [url],
13nutrition_info: object
14}The data model centers on four entities: products, carts, orders, and payments. PostgreSQL is the primary store because grocery checkout requires ACID transactions: reserving inventory and creating an order must succeed or fail atomically.
Core Schema
1products
2id UUID Primary Key
3name VARCHAR Indexed for search
4price DECIMAL Cents to avoid float errors
5category VARCHAR Indexed for filtering
6stock_count INTEGER Current available quantity
7stock_status VARCHAR in_stock / low_stock / out_of_stock
8description TEXT
9image_urls JSONB
10created_at TIMESTAMP
11updated_at TIMESTAMP
12
13shopping_carts
14id UUID Primary Key
15customer_id UUID Foreign Key to users
16created_at TIMESTAMP
17updated_at TIMESTAMP
18
19cart_items
20id UUID Primary Key
21cart_id UUID Foreign Key to shopping_carts
22product_id UUID Foreign Key to products
23quantity INTEGER
24version INTEGER For optimistic locking
25
26orders
27id UUID Primary Key
28customer_id UUID Foreign Key to users
29idempotency_key VARCHAR Unique index
30status VARCHAR placed / confirmed / preparing /
31out_for_delivery / delivered / cancelled
32delivery_slot_id UUID Foreign Key to delivery_slots
33subtotal DECIMAL
34delivery_fee DECIMAL
35total DECIMAL
36created_at TIMESTAMP
37updated_at TIMESTAMP
38
39order_items
40id UUID Primary Key
41order_id UUID Foreign Key to orders
42product_id UUID Foreign Key to products
43quantity INTEGER
44unit_price DECIMAL Price at time of purchase
45
46payment_transactions
47id UUID Primary Key
48order_id UUID Foreign Key to orders
49amount DECIMAL
50status VARCHAR processing / completed / failed / refunded
51gateway_ref VARCHAR Stripe payment intent ID
52created_at TIMESTAMP
53updated_at TIMESTAMP
54
55delivery_slots
56id UUID Primary Key
57date DATE
58start_time TIME
59end_time TIME
60capacity INTEGER Max orders for this slot
61booked_count INTEGER Current bookingsThe architecture follows a standard web application pattern with one critical distinction: the checkout path is transactional and strongly consistent, while the browsing path is cached and eventually consistent. This split lets the system handle high read volume without sacrificing write correctness.
Mid: design a monolithic service with PostgreSQL and Redis that handles browsing, checkout, and delivery scheduling.
Senior: separate checkout into a transactional service with SELECT FOR UPDATE inventory locking, introduce an event-driven delivery slot manager, and add idempotency keys for payment retries.
Staff: design cold chain monitoring across multiple fulfillment centers, implement distributed inventory reservation with cross-zone transfers, and evaluate pessimistic locking under flash sale concurrency versus optimistic locking with retry storms.
Two flows define the system: the browse-and-search flow (high volume, cache-heavy) and the checkout flow (low volume, transaction-heavy). Understanding the exact steps in each reveals why the architecture separates them.
Product Browse and Search Flow
The core engineering challenge (the GATE of this problem) is atomically reserving inventory during checkout so that concurrent orders never oversell the same product. Every component in this section exists to support that guarantee while keeping the system responsive under normal browsing load.
The GATE insight: inventory reservation must be atomic with order creation. The naive approach (check stock, then decrement, then create order) has a race condition window between the check and the decrement where another transaction can slip through. SELECT FOR UPDATE within a PostgreSQL transaction eliminates this window by locking the inventory row during the check, making the check-and-decrement a single atomic operation.
Atomic Inventory Reservation
Every architectural decision in this system trades one desirable property for another. Understanding these trade-offs, and being able to articulate them in an interview, shows you made deliberate choices rather than following patterns blindly.
Monolith vs. Microservices
Monolith: A single deployable unit containing product catalog, cart management, order processing, and payment handling. Simpler to develop, test, and deploy. One database connection pool, one deployment pipeline, one log stream. The downside: scaling requires scaling everything. If checkout needs more capacity during a flash sale, you scale the entire application even though catalog browsing is fine.
The system's reliability comes from handling failures gracefully at each layer. Each failure scenario maps to a specific architectural decision made earlier.
Payment Gateway Failure
These improvements extend the system without changing the core architecture. Each builds on the existing PostgreSQL-based transactional model.
Real-Time Delivery Tracking
The current system updates order status at discrete milestones (placed, preparing, out for delivery, delivered). Real-time tracking would show the delivery driver's live location on a map with estimated arrival time. Implementation: the driver app sends GPS coordinates every 10 seconds to a lightweight WebSocket service. The service pushes location updates to the customer's app and recalculates ETA based on current position, route, and traffic data from a mapping API (Google Maps, Mapbox). This does not affect the order pipeline; it is a read-only overlay on the existing delivery flow.
Try this problem yourself
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Editorial Solution
System requirements
Functional
Capacity estimation
Traffic
API design
Product Catalog
Database design
Core Schema
High-level design
Request flows
Product Browse and Search Flow
Detailed component design
Atomic Inventory Reservation
Tradeoffs
Monolith vs. Microservices
Failure scenarios
Payment Gateway Failure
Future improvements
Real-Time Delivery Tracking
Table of Contents
System requirements
Functional
Capacity estimation
Traffic
API design
Product Catalog
Database design
Core Schema
High-level design
Request flows
Product Browse and Search Flow
Detailed component design
Atomic Inventory Reservation
Tradeoffs
Monolith vs. Microservices
Failure scenarios
Payment Gateway Failure
Future improvements
Real-Time Delivery Tracking