Design Local Delivery

How to design a one-hour grocery delivery service: finding warehouses by travel time, serving stock quickly, and reserving orders without overselling.

Case study24 minLesson 3 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A local delivery service lets customers order groceries and household items and receive them within an hour. The company runs hundreds of small warehouses, called centres, and a driver brings each order from a centre near the customer. A customer opens the app, sees only the products that a nearby centre can deliver in time, and pays for a basket.

Three things make the design hard. "Near" has to mean travel time rather than distance. The product pages must show stock from several centres without overloading the database that takes orders. And an order for many items must reserve every item exactly once, even when two customers want the last carton at the same moment. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a service that delivers groceries within an hour from local warehouses.

You

Customers see what is available near them and place an order, and the company owns both the warehouses and the stock. Should an order ship from a single warehouse?

Interviewer

Yes, if possible. Splitting an order costs us a second driver.

You

How many warehouses, products and customers are there?

Interviewer

There are 500 centres. Each stocks about 5,000 of our 20,000 products. We have 5 million daily users and 1 million orders a day.

You

Then I will treat three things as the priorities. We never confirm an order we cannot fill, we only show products that can really arrive within the hour, and browsing stays fast. The product pages may lag the real stock by a second or two, but the order itself must be exact. I will leave out driver dispatch, picking and restocking.

Functional requirements. For a given delivery address, the app shows the products that can be delivered within the hour. The customer can order a basket of items. If an item has just sold out, the service rejects the order or offers a change to it.

Non-functional requirements. Catalogue pages respond in under 200 ms. The availability shown is at most a few seconds out of date. The system never oversells, meaning every confirmed order has its stock reserved. A failure in one region does not stop the others.

Out of scope. Driver dispatch (see Design Ride Sharing), picking, restocking and pricing are not part of this design.

Estimate the scale

Assume each daily user views 20 catalogue pages, which is 5 million × 20 = 100 million pages a day. Dividing by 86,400 seconds gives about 1,200 a second, and evenings are about 4 times busier, so the peak is about 4,600. Orders are far fewer: 1 million a day is about 12 a second and about 46 at peak.

The stock table has 500 centres × 5,000 products = 2.5 million rows of about 100 bytes, which is 250 MB and fits in the memory of an ordinary server.

Estimate: Stock lookups at peak

Each catalogue page shows 50 products, and each customer can be served by 2 centres. How many stock lookups (one per centre and product) happen each second at peak?

You know
  • 4,600 catalogue pages a second at peak
  • 50 products per page
  • 2 reachable centres per customer

Show the working
  1. 50 × 2 = 100 lookups per page
  2. 4,600 × 100 = 460,000 lookups a second

Estimate 460 thousand/s (anything from 150 thousand/s to 1.5 million/s is a good answer)

This is about 10,000 times the 46 orders a second, so page reads and orders need different data stores.

Your turn: Define the API

Write the catalogue and order endpoints. Decide whether the app or the server chooses the centre, and what an order returns when an item has just sold out.

Compare with a model answer

The app sends the customer's address and the server chooses the centre. A sold-out item returns a 409 response that lists the missing items and their alternatives, so the customer can fix the basket with one tap.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
GET /catalog?lat=40.73&lng=-73.99&category=dairy&cursor=...
  200 { "eta_min": 27,
        "items": [ { "id": "p_17", "name": "Oat milk 1 L", "price": 349,
                     "available": true }, ... ] }
  200 { "items": [], "reason": "outside delivery area" }
 
POST /orders                     Idempotency-Key: 6f1c...
  body: { "lat": 40.73, "lng": -73.99,
          "items": [ { "id": "p_17", "qty": 1 }, ... ], "payment": "pm_..." }
  201 { "order_id": "o_5521", "centre": "C1", "eta_min": 27 }
  409 Conflict { "unavailable": [ { "id": "p_17", "elsewhere": { "eta_min": 39 } } ] }
  402 Payment Required   card declined; nothing is reserved
 
GET /orders/{id}

The decision worth arguing is that the server chooses the centre. If the app sent a centre id, the customer could order from a centre that has since closed or that is now 45 minutes away because of traffic. With the address, the server applies current travel times and centre status. The order request also carries an idempotency key, so that a retry after a timeout does not create a second order.

Your turn: Model the data

Sketch the tables for centres, stock and orders. Decide how to partition stock so that an order with 15 items is a single local transaction.

Compare with a model answer

Stock rows are keyed by centre and product and hold an on-hand count and a reserved count, in a relational database partitioned by region. An order ships from one centre in one region, so all of its rows are on one partition.

Model the data

Records
centres
  centre_id PK, region_id, lat, lng, status    -- open | paused | closed
 
cell_centres                         -- precomputed, key-value
  cell        CHAR(6)                -- geohash of a ~0.75 km² area
  time_bucket SMALLINT               -- morning | midday | evening rush | night
  centres     JSON                   -- [["C1", 12], ["C2", 24]]: minutes away
  PRIMARY KEY (cell, time_bucket)
 
inventory                            -- partitioned by region_id
  region_id, centre_id, product_id
  on_hand     INT                    -- physically on the shelves
  reserved    INT                    -- promised to confirmed orders
  PRIMARY KEY (centre_id, product_id)
  CHECK (reserved <= on_hand)
 
orders                               -- same regional partition as inventory
  order_id PK, idempotency_key UNIQUE, region_id, customer_id, centre_id,
  status,     -- reserved | paid | picking | out | delivered | cancelled
  items JSON, total_cents, created_at

The stock available to sell is on_hand - reserved. An order increases reserved at checkout, and on_hand only drops when a picker scans the item off the shelf, so that on_hand always matches what is physically there.

An order changes several rows that must succeed or fail together, so inventory belongs in a relational database with transactions. It is partitioned by region, meaning a metro area with a few dozen centres. Because an order ships from one centre, it touches one partition, and the order row commits with its reservations. Partitioning by product would make every order a distributed transaction. Product names, photos and prices change rarely and are served through a cache and a CDN.

Your turn: High-level design

Sketch the read path for a catalogue page and the write path for an order. Say where each one gets its stock from.

Compare with a model answer

An availability service answers pages from an in-memory copy of stock that is fed by a change stream. An order service runs the reservation as a transaction on the region's partition. Both use a precomputed table that maps cells to centres.

High-level design

Page reads need 460,000 stock lookups a second, and they are served from a copy. Orders need only 46 writes a second, and they go to the source of truth, so neither workload slows down the other.

Pages read an in-memory copy of stock, while orders reserve stock in one transaction on the region's partition. A change stream keeps the copy a second or two behind.Customer app to API gateway (HTTPS); API gateway to Availability service (GET /catalog); API gateway to Order service (POST /orders); Availability service to Cell to centres (my cell); Order service to Cell to centres; Order service to Inventory DB by region (reserve); Order service to Payment processor (authorize); Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service (stock deltas), asynchronous.Customer appAPI gatewayAvailabilityserviceOrder servicePaymentprocessorCell to centresInventory DB byregionStock changesHTTPSGET /catalogPOST /ordersmy cellreserveauthorizestock deltas

request and replyasynchronous message

Pages read an in-memory copy of stock, while orders reserve stock in one transaction on the region's partition. A change stream keeps the copy a second or two behind.
Browsing, ordering, a race for the last item, and a lagging copyUse the arrows or ← → keys
  1. Browsing, ordering, a race for the last item, and a lagging copy, step 1Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceOrder servicePaymentprocessorCell to centresC1 12, C2 24Inventory DB byregionStock changes
    centres
    C1, C2

    1Ana opens the dairy aisle. Her address becomes a 6-character geohash cell, and the lookup says that centre C1 is 12 minutes away and centre C2 is 24 minutes away.

  2. Browsing, ordering, a race for the last item, and a lagging copy, step 2Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityservice100 lookupsOrder servicePaymentprocessorCell to centresInventory DB byregionStock changes
    oat milk at C1
    1
    oat milk at C2
    9

    2The service checks 50 products at both centres in memory, which is 100 lookups. Oat milk has 1 unit at C1 and 9 at C2, so it is shown as available in 12 + 15 = 27 minutes.

  3. Browsing, ordering, a race for the last item, and a lagging copy, step 3Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceOrder serviceC1, 15 itemsPaymentprocessorCell to centresInventory DB byregionStock changes
    oat milk at C1
    1

    3Ana checks out 15 items. The order service picks C1, the closest centre with all 15 in the copy, and opens one transaction.

  4. Browsing, ordering, a race for the last item, and a lagging copy, step 4Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceOrder servicePaymentprocessorCell to centresInventory DB byregion15 of 15Stock changes
    oat milk at C1
    0
    rows reserved
    15 of 15

    4Each item is reserved only if on_hand - reserved covers it. All 15 rows change, so it commits, and the last oat milk at C1 is Ana's.

  5. Browsing, ordering, a race for the last item, and a lagging copy, step 5Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceOrder servicePaymentprocessorCell to centresInventory DB byregionrollbackStock changes
    oat milk at C1
    0
    Ben
    409, C2 offered

    5Ben ordered oat milk from C1 at the same moment. His update waited for Ana's row lock, found no stock left, and rolled back. He gets a 409 offering C2, which is 24 + 15 = 39 minutes away, and nothing of his basket was reserved.

  6. Browsing, ordering, a race for the last item, and a lagging copy, step 6Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceOrder servicePaymentprocessorauthorizedCell to centresInventory DB byregionStock changes
    order o_5521
    paid

    6Ana's card is authorized and the order goes to the pickers. A declined card would release her 15 reservations in one transaction.

  7. Browsing, ordering, a race for the last item, and a lagging copy, step 7Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceC1 oat milk 0Order servicePaymentprocessorCell to centresInventory DB byregionStock changes
    copy of C1 oat milk
    0

    7The commit reaches the change stream, and every availability server applies it within a second or two, so pages now show oat milk at C1 as sold out.

  8. Browsing, ordering, a race for the last item, and a lagging copy, step 8Customer app to API gateway; API gateway to Availability service; API gateway to Order service; Availability service to Cell to centres; Order service to Cell to centres; Order service to Inventory DB by region; Order service to Payment processor; Inventory DB by region to Stock changes, asynchronous; Stock changes to Availability service, asynchronous.Customer appAPI gatewayAvailabilityserviceOrder servicePaymentprocessorCell to centresInventory DB byregionStock changes30 s behind
    oversold
    0

    8If the stream falls 30 seconds behind, pages keep showing sold-out items. Orders stay correct because the transaction checks the real stock, but customers see more 409 responses.

1 / 8

Deep dives

Mapping a customer to centres by travel time

The promise is a delivery within the hour, so a centre is near a customer when the travel time is short, not the distance. A centre 3 km away across a river can be 30 minutes by road, while one 6 km away on a highway can be 10. Picking and handover take about 15 minutes, so a driving limit of 30 minutes fits the hour. There are three ways to find the qualifying centres.

A straight-line radius keeps the centres within some distance of the customer. It needs no road data, but it offers centres that are far by road and hides centres that are close by road.

A routing engine call per request computes the real driving time for this address, including live traffic. At 4,600 pages a second and about 3 candidate centres per page, that is about 14,000 routes a second, which is too much for browsing but fine at checkout to refine the promised time.

A precomputed cell table divides the map into cells, and an offline job computes the driving time from each centre to every cell within reach, for a few time-of-day buckets. A page then needs one key lookup. The times are not live, and the table has to be rebuilt when a centre opens or a road changes.

The table is small. A geohash cell covers about 0.75 km² (see Design Proximity Search), so even 100,000 cells at about 100 bytes each come to 10 MB per time bucket. A centre that is paused because its pickers are overloaded, or closed, is skipped when a cell's centres are read, so live conditions need no rebuild.

Reading availability across centres quickly

For each of the 50 products on a page, the service needs the best result among the customer's 2 or 3 centres. The source of truth is the inventory database, but 460,000 lookups a second should not land on the database that takes orders. There are three places to read from.

The inventory database is always exact, but even with read replicas it becomes the busiest part of the system, for pages that do not need exact answers.

A shared cache fed by the change stream keeps one hash per centre in an in-memory store, and a page does one batched read per centre. It suits stock that is too large to copy onto every server.

An in-process copy fed by the change stream keeps the whole stock table in the memory of each availability server. A server loads a snapshot at start-up, notes its position in the change stream, and applies every later change, like a database replica. The data is 250 MB, so this fits, and a page's 100 lookups cost microseconds.

Where catalogue pages read stock from
OptionGood atBad atPick it when
Inventory databaseThe answer is always exact.460,000 lookups a second would land on the same partitions that take orders.Use it for a small operation with a few centres.
Shared cache fed by the change streamIt holds one hash per centre, so a page needs one batched read per centre.Every page pays a network call per centre, and a cache cluster has to be run.Use it when the stock data is too large to copy onto every server.
In-process copy fed by the change stream Usual defaultThe 250 MB fits on each server, so lookups cost microseconds and do not depend on another service.Each server must load a snapshot and apply every change, and servers can differ by a moment.Use it when the whole data set is small, as it is here. It is the choice for this design.

Ordering without overselling

A basket of 15 items must reserve all 15 items or none. Otherwise a customer pays for a bag with items missing, or a half-finished order locks 14 items away from others.

The naive approach reads the available count, checks it in the application, and writes the new count. Two orders can both read a count of 1 before either writes, so the item is sold twice. Locking each row first with SELECT ... FOR UPDATE fixes that, but it takes a round trip per item while the locks are held. The better approach is a single conditional update of the whole basket, which changes a row only when enough stock remains and then checks how many rows changed. The check and the change are one atomic step, and the locks last for one statement.

Reserve a basket at one centre, all or nothing
BEGIN;
UPDATE inventory AS i
   SET reserved = i.reserved + b.qty
  FROM (VALUES ('p_17', 1), ('p_42', 2), ...) AS b(product_id, qty)  -- 15 rows
 WHERE i.centre_id = 'C1' AND i.product_id = b.product_id
   AND i.on_hand - i.reserved >= b.qty;
-- rows changed = 15: INSERT the order, COMMIT.
-- fewer than 15:    ROLLBACK, and report which products fell short (409).
COMMIT;

The conditional update is safe because every row it changes stays locked until the transaction ends. A second order for the same product waits for that lock. At the read committed isolation level in databases such as PostgreSQL, it then re-evaluates its WHERE clause against the new values, finds too little stock, and skips the row, so its count comes up short and it rolls back. At stricter isolation levels the database raises a serialization error instead, and the service handles it the same way (see transactions and isolation). Two baskets that lock the same products in different orders can deadlock. The database aborts one of them, and the service retries it once. The CHECK constraint on reserved is a last defence against bugs.

The rest of the flow follows ticket booking: reserve, authorize the card, then confirm. An unpaid reservation expires after a few minutes, when a sweeper moves the order from reserved to cancelled only if it is still reserved and releases the stock in the same transaction.

Bottlenecks and failures

What breaks first at 10 times the load

At 10 times the load there are 46,000 page views and 460 orders a second at peak. Availability servers scale by adding servers that each hold a full copy, and orders are only about 1 a second per centre. The first strain is a hot product during a promotion, because many orders queue on one row's lock. The fixes are to cap the quantity per order and, if needed, to split the stock into several rows.

When an availability server fails

Pages routed to that server fail until the load balancer removes it, and the other servers absorb the traffic.

When the change stream fails or lags

The availability copies stop updating, so pages show stock as it was when the stream stopped. Orders remain correct because the reservation checks the real stock, but customers get more 409 responses. Lag should raise an alert.

When a region's inventory primary fails

Orders for that region fail until a replica is promoted, and other regions are not affected because their partitions are separate. A synchronous replica means no committed reservation is lost, and the idempotency key keeps a customer's retry from creating a second order.

When the payment processor is unavailable

Orders can reserve stock but cannot be authorized. The service releases the reservations after a short timeout and asks customers to retry.

What a strong answer sounds like

LevelWhat the answer does
JuniorThe answer uses straight-line distance, reads the main database for every page, and subtracts the items of an order one at a time.
Mid-levelThe answer uses travel time, caches availability, and reserves the whole basket in one transaction with a conditional update.
SeniorThe answer precomputes travel time per map cell, copies the stock into the read servers' memory from a change stream, partitions by region so that orders are local transactions, and keeps the copy that is shown separate from the truth that is sold.
Why partition by regionStrong answer
Interviewer

How would you shard the inventory database?

You

By region. An order ships from one centre in one region, so every basket is a local transaction. If I sharded by product, a 15-item basket could touch up to 15 shards and every order would need a distributed commit.

Interviewer

What does that cost you?

You

Regions are uneven, so a large metro area needs a bigger partition than a small one. A query across the whole country, such as the total stock of one product, has to ask every region, so I would serve those from a separate analytics copy.

Follow-up questions

What happens when no single centre has the whole basket?

The 409 response offers choices: order from a farther centre at a later time, drop the missing items, or split the order into two deliveries for a fee. A split is two transactions on two centres, and if the second fails the first is released.

How do you show a delivery time on the page?

The time is the travel time from the cell table for the chosen centre plus that centre's current picking time, which each centre publishes every few seconds. A routing call at checkout can refine it before the customer is promised the time.

Could you reserve stock when an item goes into the cart?

That would avoid surprises at checkout, but abandoned carts would hide stock from customers who are ready to pay. It is better to reserve at checkout and let the cart warn when the availability copy shows an item has run out.

Why not use a distributed lock per product instead of a database transaction?

A lock service is another system that can fail, and it cannot undo earlier items when a later one is short. The database already locks the rows it changes and rolls the whole basket back atomically.

Self-review: local delivery0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure